Open History to see the last commit
1import {
2 ORCHESTRATION_V2_WS_METHODS,
3 type EnvironmentId,
4 type OrchestrationV2ShellSnapshot,
5 type OrchestrationV2ShellStreamItem,
6 type ServerConfig,
7} from "@t3tools/contracts";
8import * as Cause from "effect/Cause";
9import * as DateTime from "effect/DateTime";
10import * as Effect from "effect/Effect";
11import * as Option from "effect/Option";
12import * as Queue from "effect/Queue";
13import * as Stream from "effect/Stream";
14import * as SubscriptionRef from "effect/SubscriptionRef";
15import { AsyncResult, Atom } from "effect/unstable/reactivity";
16
17import { EnvironmentRegistry } from "../connection/registry.ts";
18import { connectionProjectionPhase } from "../connection/model.ts";
19import { EnvironmentSupervisor } from "../connection/supervisor.ts";
20import { safeErrorLogAttributes } from "../errors/safeLog.ts";
21import { EnvironmentCacheStore } from "../platform/persistence.ts";
22import { subscribe } from "../rpc/client.ts";
23import { applyShellStreamEvent } from "./shellReducer.ts";
24import type { EnvironmentCatalogState } from "./connections.ts";
25import { followStreamInEnvironment } from "./runtime.ts";
26
27export type EnvironmentShellStatus = "empty" | "cached" | "synchronizing" | "live";
28
29export interface EnvironmentShellState {
30 readonly snapshot: Option.Option<OrchestrationV2ShellSnapshot>;
31 readonly status: EnvironmentShellStatus;
32 readonly error: Option.Option<string>;
33}
34
35const EMPTY_SHELL_STATE: EnvironmentShellState = {
36 snapshot: Option.none(),
37 status: "empty",
38 error: Option.none(),
39};
40
41function shellStatusForSnapshot(
42 snapshot: Option.Option<OrchestrationV2ShellSnapshot>,
43): EnvironmentShellStatus {
44 return Option.isSome(snapshot) ? "cached" : "empty";
45}
46
47const SHELL_SYNCHRONIZATION_ERROR_MESSAGE = "Could not synchronize environment data.";
48
49export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")(function* () {
50 const supervisor = yield* EnvironmentSupervisor;
51 const cache = yield* EnvironmentCacheStore;
52 const environmentId = supervisor.target.environmentId;
53 const cachedSnapshot = yield* cache.loadShell(environmentId).pipe(
54 Effect.catch((error) =>
55 Effect.logWarning("Could not load cached environment shell.").pipe(
56 Effect.annotateLogs({
57 environmentId,
58 ...safeErrorLogAttributes(error),
59 }),
60 Effect.as(Option.none<OrchestrationV2ShellSnapshot>()),
61 ),
62 ),
63 );
64 const state = yield* SubscriptionRef.make<EnvironmentShellState>({
65 snapshot: cachedSnapshot,
66 status: shellStatusForSnapshot(cachedSnapshot),
67 error: Option.none(),
68 });
69 const persistence = yield* Queue.sliding<OrchestrationV2ShellSnapshot>(1);
70
71 const persist = Effect.fn("EnvironmentShellState.persist")(function* (
72 snapshot: OrchestrationV2ShellSnapshot,
73 ) {
74 yield* cache.saveShell(environmentId, snapshot).pipe(
75 Effect.catch((error) =>
76 Effect.logWarning("Could not persist environment shell cache.").pipe(
77 Effect.annotateLogs({
78 environmentId,
79 ...safeErrorLogAttributes(error),
80 }),
81 ),
82 ),
83 );
84 });
85
86 yield* Stream.fromQueue(persistence).pipe(
87 Stream.debounce("500 millis"),
88 Stream.runForEach(persist),
89 Effect.forkScoped,
90 );
91
92 const setDisconnected = SubscriptionRef.update(state, (current) => ({
93 ...current,
94 status: shellStatusForSnapshot(current.snapshot),
95 }));
96 const setSynchronizing = SubscriptionRef.update(state, (current) => ({
97 ...current,
98 status: "synchronizing" as const,
99 error: Option.none(),
100 }));
101 const setReady = SubscriptionRef.update(state, (current) =>
102 current.status === "live"
103 ? current
104 : {
105 ...current,
106 status: "synchronizing" as const,
107 error: Option.none(),
108 },
109 );
110 const setStreamError = (error: unknown) =>
111 Effect.logWarning("Could not synchronize the environment shell.").pipe(
112 Effect.annotateLogs({
113 environmentId,
114 ...safeErrorLogAttributes(error),
115 }),
116 Effect.andThen(
117 SubscriptionRef.update(state, (current) => ({
118 ...current,
119 status: shellStatusForSnapshot(current.snapshot),
120 error: Option.some(SHELL_SYNCHRONIZATION_ERROR_MESSAGE),
121 })),
122 ),
123 );
124
125 const applyItem = Effect.fn("EnvironmentShellState.applyItem")(function* (
126 item: OrchestrationV2ShellStreamItem,
127 ) {
128 const current = yield* SubscriptionRef.get(state);
129 const nextSnapshot =
130 item.kind === "snapshot"
131 ? item.snapshot
132 : Option.match(current.snapshot, {
133 onNone: () => null,
134 onSome: (snapshot) =>
135 item.sequence > snapshot.snapshotSequence
136 ? applyShellStreamEvent(snapshot, item)
137 : snapshot,
138 });
139 if (nextSnapshot === null) {
140 return;
141 }
142
143 yield* SubscriptionRef.set(state, {
144 snapshot: Option.some(nextSnapshot),
145 status: "live",
146 error: Option.none(),
147 });
148 yield* Queue.offer(persistence, nextSnapshot);
149 });
150
151 yield* subscribe(
152 ORCHESTRATION_V2_WS_METHODS.subscribeShell,
153 {},
154 {
155 onExpectedFailure: (cause) => setStreamError(Cause.squash(cause)),
156 },
157 ).pipe(Stream.runForEach(applyItem), Effect.forkScoped);
158 yield* SubscriptionRef.changes(supervisor.state).pipe(
159 Stream.runForEach((connectionState) => {
160 switch (connectionProjectionPhase(connectionState)) {
161 case "synchronizing":
162 return setSynchronizing;
163 case "disconnected":
164 return setDisconnected;
165 case "ready":
166 return setReady;
167 }
168 }),
169 Effect.forkScoped,
170 );
171
172 return state;
173});
174
175export function shellStateChanges(environmentId: EnvironmentId) {
176 return followStreamInEnvironment(
177 environmentId,
178 Stream.unwrap(makeEnvironmentShellState().pipe(Effect.map(SubscriptionRef.changes))),
179 );
180}
181
182export interface EnvironmentShellSummary {
183 readonly hasSnapshot: boolean;
184 readonly hasSynchronizingShell: boolean;
185 readonly hasCachedShell: boolean;
186 readonly hasLiveShell: boolean;
187 readonly firstError: string | null;
188 readonly latestSnapshotUpdatedAt: string | null;
189}
190
191const EMPTY_ENVIRONMENT_SHELL_SUMMARY: EnvironmentShellSummary = Object.freeze({
192 hasSnapshot: false,
193 hasSynchronizingShell: false,
194 hasCachedShell: false,
195 hasLiveShell: false,
196 firstError: null,
197 latestSnapshotUpdatedAt: null,
198});
199
200const EMPTY_SERVER_CONFIGS: ReadonlyMap<EnvironmentId, ServerConfig> = new Map();
201
202function shellSummariesEqual(
203 left: EnvironmentShellSummary,
204 right: EnvironmentShellSummary,
205): boolean {
206 return (
207 left.hasSnapshot === right.hasSnapshot &&
208 left.hasSynchronizingShell === right.hasSynchronizingShell &&
209 left.hasCachedShell === right.hasCachedShell &&
210 left.hasLiveShell === right.hasLiveShell &&
211 left.firstError === right.firstError &&
212 left.latestSnapshotUpdatedAt === right.latestSnapshotUpdatedAt
213 );
214}
215
216function mapsEqual<K, V>(left: ReadonlyMap<K, V>, right: ReadonlyMap<K, V>): boolean {
217 if (left.size !== right.size) {
218 return false;
219 }
220 for (const [key, value] of left) {
221 if (right.get(key) !== value) {
222 return false;
223 }
224 }
225 return true;
226}
227
228export function createEnvironmentShellSummaryAtom(input: {
229 readonly catalogValueAtom: Atom.Atom<EnvironmentCatalogState>;
230 readonly shellStateValueAtom: (environmentId: EnvironmentId) => Atom.Atom<EnvironmentShellState>;
231}) {
232 let previousSummary = EMPTY_ENVIRONMENT_SHELL_SUMMARY;
233 return Atom.make((get) => {
234 let hasSnapshot = false;
235 let hasSynchronizingShell = false;
236 let hasCachedShell = false;
237 let hasLiveShell = false;
238 let firstError: string | null = null;
239 let latestSnapshotUpdatedAt: string | null = null;
240
241 for (const environmentId of get(input.catalogValueAtom).entries.keys()) {
242 const state = get(input.shellStateValueAtom(environmentId));
243 hasSynchronizingShell ||= state.status === "synchronizing";
244 hasCachedShell ||= state.status === "cached";
245 hasLiveShell ||= state.status === "live";
246 if (firstError === null) {
247 firstError = Option.getOrNull(state.error);
248 }
249 if (Option.isNone(state.snapshot)) {
250 continue;
251 }
252 hasSnapshot = true;
253 const snapshot = state.snapshot.value;
254 const updatedAt = snapshot.threads.concat(snapshot.archivedThreads).reduce<string | null>(
255 (latest, thread) => {
256 const value = DateTime.formatIso(thread.updatedAt);
257 return latest === null || value > latest ? value : latest;
258 },
259 snapshot.projects.reduce<string | null>((latest, project) => {
260 return latest === null || project.updatedAt > latest ? project.updatedAt : latest;
261 }, null),
262 );
263 if (
264 updatedAt !== null &&
265 (latestSnapshotUpdatedAt === null || updatedAt > latestSnapshotUpdatedAt)
266 ) {
267 latestSnapshotUpdatedAt = updatedAt;
268 }
269 }
270
271 const next: EnvironmentShellSummary = {
272 hasSnapshot,
273 hasSynchronizingShell,
274 hasCachedShell,
275 hasLiveShell,
276 firstError,
277 latestSnapshotUpdatedAt,
278 };
279 if (shellSummariesEqual(previousSummary, next)) {
280 return previousSummary;
281 }
282 previousSummary = next;
283 return previousSummary;
284 }).pipe(Atom.withLabel("environment-shell-summary"));
285}
286
287export function createEnvironmentServerConfigsAtom(input: {
288 readonly catalogValueAtom: Atom.Atom<EnvironmentCatalogState>;
289 readonly serverConfigValueAtom: (environmentId: EnvironmentId) => Atom.Atom<ServerConfig | null>;
290}) {
291 let previousServerConfigs = EMPTY_SERVER_CONFIGS;
292 return Atom.make((get) => {
293 const next = new Map<EnvironmentId, ServerConfig>();
294 for (const environmentId of get(input.catalogValueAtom).entries.keys()) {
295 const config = get(input.serverConfigValueAtom(environmentId));
296 if (config !== null) {
297 next.set(environmentId, config);
298 }
299 }
300 if (mapsEqual(previousServerConfigs, next)) {
301 return previousServerConfigs;
302 }
303 previousServerConfigs = next;
304 return previousServerConfigs;
305 }).pipe(Atom.withLabel("environment-server-configs"));
306}
307
308export function createEnvironmentShellAtoms<R, E>(
309 runtime: Atom.AtomRuntime<EnvironmentRegistry | EnvironmentCacheStore | R, E>,
310) {
311 const stateAtom = Atom.family((environmentId: EnvironmentId) =>
312 runtime.atom(shellStateChanges(environmentId), {
313 initialValue: EMPTY_SHELL_STATE,
314 }),
315 );
316
317 const stateValueAtom = Atom.family((environmentId: EnvironmentId) =>
318 Atom.make((get) =>
319 Option.getOrElse(AsyncResult.value(get(stateAtom(environmentId))), () => EMPTY_SHELL_STATE),
320 ).pipe(Atom.withLabel(`environment-shell-state-value:${environmentId}`)),
321 );
322
323 return {
324 stateAtom,
325 stateValueAtom,
326 };
327}
328
329export * from "./models.ts";
330export * from "./shellCommands.ts";
331export * from "./shellReducer.ts";
332export * from "./snapshots.ts";