Open History to see the last commit
1import {
2 ORCHESTRATION_WS_METHODS,
3 type EnvironmentId,
4 type OrchestrationShellSnapshot,
5 type OrchestrationShellStreamItem,
6 type ServerConfig,
7} from "@t3tools/contracts";
8import * as Cause from "effect/Cause";
9import * as Effect from "effect/Effect";
10import * as Option from "effect/Option";
11import * as Queue from "effect/Queue";
12import * as Ref from "effect/Ref";
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 * as ConnectionWakeups from "../connection/wakeups.ts";
21import { safeErrorLogAttributes } from "../errors/safeLog.ts";
22import { EnvironmentCacheStore } from "../platform/persistence.ts";
23import { subscribeDynamic } from "../rpc/client.ts";
24import type { RpcSession } from "../rpc/session.ts";
25import { ShellSnapshotLoader } from "./shellSnapshotHttp.ts";
26import { applyShellStreamEvent } from "./shellReducer.ts";
27import { type EnvironmentCatalogState, enabledEnvironmentIds } from "./connections.ts";
28import { followStreamInEnvironment } from "./runtime.ts";
29
30export type EnvironmentShellStatus = "empty" | "cached" | "synchronizing" | "live";
31
32export interface EnvironmentShellState {
33 readonly snapshot: Option.Option<OrchestrationShellSnapshot>;
34 readonly status: EnvironmentShellStatus;
35 readonly error: Option.Option<string>;
36}
37
38const EMPTY_SHELL_STATE: EnvironmentShellState = {
39 snapshot: Option.none(),
40 status: "empty",
41 error: Option.none(),
42};
43
44function shellStatusForSnapshot(
45 snapshot: Option.Option<OrchestrationShellSnapshot>,
46): EnvironmentShellStatus {
47 return Option.isSome(snapshot) ? "cached" : "empty";
48}
49
50const SHELL_SYNCHRONIZATION_ERROR_MESSAGE = "Could not synchronize environment data.";
51
52export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")(function* () {
53 const supervisor = yield* EnvironmentSupervisor;
54 const cache = yield* EnvironmentCacheStore;
55 const snapshotLoader = yield* ShellSnapshotLoader;
56 const wakeups = yield* Effect.serviceOption(ConnectionWakeups.ConnectionWakeups);
57 const environmentId = supervisor.target.environmentId;
58 const cachedSnapshot = yield* cache.loadShell(environmentId).pipe(
59 Effect.catch((error) =>
60 Effect.logWarning("Could not load cached environment shell.").pipe(
61 Effect.annotateLogs({
62 environmentId,
63 ...safeErrorLogAttributes(error),
64 }),
65 Effect.as(Option.none<OrchestrationShellSnapshot>()),
66 ),
67 ),
68 );
69 const state = yield* SubscriptionRef.make<EnvironmentShellState>({
70 snapshot: cachedSnapshot,
71 status: shellStatusForSnapshot(cachedSnapshot),
72 error: Option.none(),
73 });
74 const awaitingCompletion = yield* Ref.make(false);
75 const lastAuthoritativeSession = yield* Ref.make<RpcSession | null>(null);
76 const activeSubscriptionSession = yield* Ref.make<RpcSession | null>(null);
77 const persistence = yield* Queue.sliding<OrchestrationShellSnapshot>(1);
78
79 const persist = Effect.fn("EnvironmentShellState.persist")(function* (
80 snapshot: OrchestrationShellSnapshot,
81 ) {
82 yield* cache.saveShell(environmentId, snapshot).pipe(
83 Effect.catch((error) =>
84 Effect.logWarning("Could not persist environment shell cache.").pipe(
85 Effect.annotateLogs({
86 environmentId,
87 ...safeErrorLogAttributes(error),
88 }),
89 ),
90 ),
91 );
92 });
93
94 yield* Stream.fromQueue(persistence).pipe(
95 Stream.debounce("500 millis"),
96 Stream.runForEach(persist),
97 Effect.forkScoped,
98 );
99
100 const setDisconnected = Ref.set(awaitingCompletion, false).pipe(
101 Effect.andThen(
102 SubscriptionRef.update(state, (current) => ({
103 ...current,
104 status: shellStatusForSnapshot(current.snapshot),
105 })),
106 ),
107 );
108 const setSynchronizing = SubscriptionRef.update(state, (current) => ({
109 ...current,
110 status: "synchronizing" as const,
111 error: Option.none(),
112 }));
113 const setReady = SubscriptionRef.update(state, (current) =>
114 current.status === "live"
115 ? current
116 : {
117 ...current,
118 status: "synchronizing" as const,
119 error: Option.none(),
120 },
121 );
122 const setStreamError = (error: unknown) =>
123 Ref.set(awaitingCompletion, false).pipe(
124 Effect.andThen(Effect.logWarning("Could not synchronize the environment shell.")),
125 Effect.annotateLogs({
126 environmentId,
127 ...safeErrorLogAttributes(error),
128 }),
129 Effect.andThen(
130 SubscriptionRef.update(state, (current) => ({
131 ...current,
132 status: shellStatusForSnapshot(current.snapshot),
133 error: Option.some(SHELL_SYNCHRONIZATION_ERROR_MESSAGE),
134 })),
135 ),
136 );
137
138 // Apply each received batch with one state write. The RPC client's bounded
139 // buffer can split a server chunk, so a bulk action can still need several
140 // writes, but each write includes every event in that batch.
141 const applyItems = Effect.fn("EnvironmentShellState.applyItems")(function* (
142 items: ReadonlyArray<OrchestrationShellStreamItem>,
143 ) {
144 const initial = yield* SubscriptionRef.get(state);
145 let waiting = yield* Ref.get(awaitingCompletion);
146 let next = initial;
147 let receivedSnapshot = false;
148 for (const item of items) {
149 if (item.kind === "synchronized") {
150 waiting = false;
151 if (Option.isSome(next.snapshot)) {
152 next = { ...next, status: "live", error: Option.none() };
153 }
154 continue;
155 }
156 const nextSnapshot =
157 item.kind === "snapshot"
158 ? item.snapshot
159 : Option.match(next.snapshot, {
160 onNone: () => null,
161 onSome: (snapshot) =>
162 item.sequence > snapshot.snapshotSequence
163 ? applyShellStreamEvent(snapshot, item)
164 : snapshot,
165 });
166 if (nextSnapshot === null) continue;
167 receivedSnapshot ||= item.kind === "snapshot";
168 next = {
169 snapshot: Option.some(nextSnapshot),
170 status: waiting ? "synchronizing" : "live",
171 error: Option.none(),
172 };
173 }
174 yield* Ref.set(awaitingCompletion, waiting);
175 if (next === initial) return;
176 yield* SubscriptionRef.set(state, next);
177 if (receivedSnapshot) {
178 const session = yield* Ref.get(activeSubscriptionSession);
179 if (session !== null) {
180 yield* Ref.set(lastAuthoritativeSession, session);
181 }
182 }
183 if (next.snapshot !== initial.snapshot && Option.isSome(next.snapshot)) {
184 yield* Queue.offer(persistence, next.snapshot.value);
185 }
186 });
187
188 const foregroundResubscriptions = Option.match(wakeups, {
189 onNone: () => Stream.never,
190 onSome: (service) =>
191 service.changes.pipe(Stream.filter(ConnectionWakeups.shouldResubscribeAfterWakeup)),
192 });
193
194 yield* setSynchronizing;
195 yield* Effect.forkScoped(
196 subscribeDynamic(
197 ORCHESTRATION_WS_METHODS.subscribeShell,
198 Effect.fn("EnvironmentShellState.makeSubscribeInput")(function* (session) {
199 yield* Ref.set(activeSubscriptionSession, session);
200 const supportsCompletionMarker = yield* session.initialConfig.pipe(
201 Effect.map((config) => config.shellResumeCompletionMarker === true),
202 Effect.orElseSucceed(() => false),
203 );
204 yield* Ref.set(awaitingCompletion, supportsCompletionMarker);
205 yield* setSynchronizing;
206
207 // Foreground resubscriptions on the same live session can resume from
208 // the in-memory cursor. A new session reloads the authoritative HTTP
209 // snapshot so a valid cursor cannot preserve incomplete cached data.
210 const hasAuthoritativeSnapshot = (yield* Ref.get(lastAuthoritativeSession)) === session;
211 let canResume = hasAuthoritativeSnapshot;
212 let current = yield* SubscriptionRef.get(state);
213 if (!hasAuthoritativeSnapshot || Option.isNone(current.snapshot)) {
214 const prepared = yield* SubscriptionRef.get(supervisor.prepared).pipe(
215 Effect.flatMap(
216 Option.match({
217 onSome: Effect.succeed,
218 onNone: () =>
219 SubscriptionRef.changes(supervisor.prepared).pipe(
220 Stream.filter(Option.isSome),
221 Stream.map((value) => value.value),
222 Stream.runHead,
223 Effect.map(Option.getOrThrow),
224 ),
225 }),
226 ),
227 );
228 const httpSnapshot = yield* snapshotLoader.load(prepared);
229 if (Option.isSome(httpSnapshot)) {
230 yield* applyItems([{ kind: "snapshot", snapshot: httpSnapshot.value }]);
231 canResume = true;
232 current = yield* SubscriptionRef.get(state);
233 }
234 }
235
236 // If the authoritative refresh failed, omit the cached cursor so the
237 // socket fallback sends a complete snapshot for this new session.
238 if (!canResume || Option.isNone(current.snapshot)) {
239 return supportsCompletionMarker ? { requestCompletionMarker: true as const } : {};
240 }
241 if (!supportsCompletionMarker) {
242 // Without a completion marker there is no synchronized signal for a
243 // resumed subscription, so report live immediately, like threads.
244 yield* SubscriptionRef.update(state, (value) => ({
245 ...value,
246 status: "live" as const,
247 error: Option.none(),
248 }));
249 }
250 return {
251 afterSequence: current.snapshot.value.snapshotSequence,
252 ...(supportsCompletionMarker ? { requestCompletionMarker: true as const } : {}),
253 };
254 }),
255 {
256 onExpectedFailure: (cause) => setStreamError(Cause.squash(cause)),
257 retryExpectedFailureAfter: "250 millis",
258 resubscribe: foregroundResubscriptions,
259 },
260 ).pipe(Stream.runForEachArray(applyItems)),
261 );
262 yield* SubscriptionRef.changes(supervisor.state).pipe(
263 Stream.runForEach((connectionState) => {
264 switch (connectionProjectionPhase(connectionState)) {
265 case "synchronizing":
266 return setSynchronizing;
267 case "disconnected":
268 return setDisconnected;
269 case "ready":
270 return setReady;
271 }
272 }),
273 Effect.forkScoped,
274 );
275
276 return state;
277});
278
279function shellStateChanges(environmentId: EnvironmentId) {
280 return followStreamInEnvironment(
281 environmentId,
282 Stream.unwrap(makeEnvironmentShellState().pipe(Effect.map(SubscriptionRef.changes))),
283 );
284}
285
286export interface EnvironmentShellSummary {
287 readonly hasSnapshot: boolean;
288 readonly hasSynchronizingShell: boolean;
289 readonly hasCachedShell: boolean;
290 readonly hasLiveShell: boolean;
291 readonly firstError: string | null;
292 readonly latestSnapshotUpdatedAt: string | null;
293}
294
295const EMPTY_ENVIRONMENT_SHELL_SUMMARY: EnvironmentShellSummary = Object.freeze({
296 hasSnapshot: false,
297 hasSynchronizingShell: false,
298 hasCachedShell: false,
299 hasLiveShell: false,
300 firstError: null,
301 latestSnapshotUpdatedAt: null,
302});
303
304const EMPTY_SERVER_CONFIGS: ReadonlyMap<EnvironmentId, ServerConfig> = new Map();
305
306function shellSummariesEqual(
307 left: EnvironmentShellSummary,
308 right: EnvironmentShellSummary,
309): boolean {
310 return (
311 left.hasSnapshot === right.hasSnapshot &&
312 left.hasSynchronizingShell === right.hasSynchronizingShell &&
313 left.hasCachedShell === right.hasCachedShell &&
314 left.hasLiveShell === right.hasLiveShell &&
315 left.firstError === right.firstError &&
316 left.latestSnapshotUpdatedAt === right.latestSnapshotUpdatedAt
317 );
318}
319
320function mapsEqual<K, V>(left: ReadonlyMap<K, V>, right: ReadonlyMap<K, V>): boolean {
321 if (left.size !== right.size) {
322 return false;
323 }
324 for (const [key, value] of left) {
325 if (right.get(key) !== value) {
326 return false;
327 }
328 }
329 return true;
330}
331
332export function createEnvironmentShellSummaryAtom(input: {
333 readonly catalogValueAtom: Atom.Atom<EnvironmentCatalogState>;
334 readonly shellStateValueAtom: (environmentId: EnvironmentId) => Atom.Atom<EnvironmentShellState>;
335}) {
336 let previousSummary = EMPTY_ENVIRONMENT_SHELL_SUMMARY;
337 return Atom.make((get) => {
338 let hasSnapshot = false;
339 let hasSynchronizingShell = false;
340 let hasCachedShell = false;
341 let hasLiveShell = false;
342 let firstError: string | null = null;
343 let latestSnapshotUpdatedAt: string | null = null;
344
345 for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
346 const state = get(input.shellStateValueAtom(environmentId));
347 hasSynchronizingShell ||= state.status === "synchronizing";
348 hasCachedShell ||= state.status === "cached";
349 hasLiveShell ||= state.status === "live";
350 if (firstError === null) {
351 firstError = Option.getOrNull(state.error);
352 }
353 if (Option.isNone(state.snapshot)) {
354 continue;
355 }
356 hasSnapshot = true;
357 const updatedAt = state.snapshot.value.updatedAt;
358 if (latestSnapshotUpdatedAt === null || updatedAt > latestSnapshotUpdatedAt) {
359 latestSnapshotUpdatedAt = updatedAt;
360 }
361 }
362
363 const next: EnvironmentShellSummary = {
364 hasSnapshot,
365 hasSynchronizingShell,
366 hasCachedShell,
367 hasLiveShell,
368 firstError,
369 latestSnapshotUpdatedAt,
370 };
371 if (shellSummariesEqual(previousSummary, next)) {
372 return previousSummary;
373 }
374 previousSummary = next;
375 return previousSummary;
376 }).pipe(Atom.withLabel("environment-shell-summary"));
377}
378
379export function createEnvironmentServerConfigsAtom(input: {
380 readonly catalogValueAtom: Atom.Atom<EnvironmentCatalogState>;
381 readonly serverConfigValueAtom: (environmentId: EnvironmentId) => Atom.Atom<ServerConfig | null>;
382}) {
383 let previousServerConfigs = EMPTY_SERVER_CONFIGS;
384 return Atom.make((get) => {
385 const next = new Map<EnvironmentId, ServerConfig>();
386 for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
387 const config = get(input.serverConfigValueAtom(environmentId));
388 if (config !== null) {
389 next.set(environmentId, config);
390 }
391 }
392 if (mapsEqual(previousServerConfigs, next)) {
393 return previousServerConfigs;
394 }
395 previousServerConfigs = next;
396 return previousServerConfigs;
397 }).pipe(Atom.withLabel("environment-server-configs"));
398}
399
400export function createEnvironmentShellAtoms<R, E>(
401 runtime: Atom.AtomRuntime<
402 EnvironmentRegistry | EnvironmentCacheStore | ShellSnapshotLoader | R,
403 E
404 >,
405) {
406 const stateAtom = Atom.family((environmentId: EnvironmentId) =>
407 runtime.atom(shellStateChanges(environmentId), {
408 initialValue: EMPTY_SHELL_STATE,
409 }),
410 );
411
412 const stateValueAtom = Atom.family((environmentId: EnvironmentId) =>
413 Atom.make((get) =>
414 Option.getOrElse(AsyncResult.value(get(stateAtom(environmentId))), () => EMPTY_SHELL_STATE),
415 ).pipe(Atom.withLabel(`environment-shell-state-value:${environmentId}`)),
416 );
417
418 return {
419 stateAtom,
420 stateValueAtom,
421 };
422}
423
424export * from "./models.ts";
425export * from "./shellCommands.ts";
426export * from "./shellReducer.ts";
427export * from "./shellSnapshotHttp.ts";
428export * from "./snapshots.ts";