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 } 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 const applyItem = Effect.fn("EnvironmentShellState.applyItem")(function* (
139 item: OrchestrationShellStreamItem,
140 ) {
141 if (item.kind === "synchronized") {
142 yield* Ref.set(awaitingCompletion, false);
143 yield* SubscriptionRef.update(state, (current) =>
144 Option.isSome(current.snapshot)
145 ? { ...current, status: "live" as const, error: Option.none() }
146 : current,
147 );
148 return;
149 }
150
151 const current = yield* SubscriptionRef.get(state);
152 const nextSnapshot =
153 item.kind === "snapshot"
154 ? item.snapshot
155 : Option.match(current.snapshot, {
156 onNone: () => null,
157 onSome: (snapshot) =>
158 item.sequence > snapshot.snapshotSequence
159 ? applyShellStreamEvent(snapshot, item)
160 : snapshot,
161 });
162 if (nextSnapshot === null) {
163 return;
164 }
165
166 const waiting = yield* Ref.get(awaitingCompletion);
167 yield* SubscriptionRef.set(state, {
168 snapshot: Option.some(nextSnapshot),
169 status: waiting ? "synchronizing" : "live",
170 error: Option.none(),
171 });
172 if (item.kind === "snapshot") {
173 const session = yield* Ref.get(activeSubscriptionSession);
174 if (session !== null) {
175 yield* Ref.set(lastAuthoritativeSession, session);
176 }
177 }
178 yield* Queue.offer(persistence, nextSnapshot);
179 });
180
181 const foregroundResubscriptions = Option.match(wakeups, {
182 onNone: () => Stream.never,
183 onSome: (service) =>
184 service.changes.pipe(Stream.filter(ConnectionWakeups.shouldResubscribeAfterWakeup)),
185 });
186
187 yield* setSynchronizing;
188 yield* Effect.forkScoped(
189 subscribeDynamic(
190 ORCHESTRATION_WS_METHODS.subscribeShell,
191 Effect.fn("EnvironmentShellState.makeSubscribeInput")(function* (session) {
192 yield* Ref.set(activeSubscriptionSession, session);
193 const supportsCompletionMarker = yield* session.initialConfig.pipe(
194 Effect.map((config) => config.shellResumeCompletionMarker === true),
195 Effect.orElseSucceed(() => false),
196 );
197 yield* Ref.set(awaitingCompletion, supportsCompletionMarker);
198 yield* setSynchronizing;
199
200 // Foreground resubscriptions on the same live session can resume from
201 // the in-memory cursor. A new session reloads the authoritative HTTP
202 // snapshot so a valid cursor cannot preserve incomplete cached data.
203 const hasAuthoritativeSnapshot = (yield* Ref.get(lastAuthoritativeSession)) === session;
204 let canResume = hasAuthoritativeSnapshot;
205 let current = yield* SubscriptionRef.get(state);
206 if (!hasAuthoritativeSnapshot || Option.isNone(current.snapshot)) {
207 const prepared = yield* SubscriptionRef.get(supervisor.prepared).pipe(
208 Effect.flatMap(
209 Option.match({
210 onSome: Effect.succeed,
211 onNone: () =>
212 SubscriptionRef.changes(supervisor.prepared).pipe(
213 Stream.filter(Option.isSome),
214 Stream.map((value) => value.value),
215 Stream.runHead,
216 Effect.map(Option.getOrThrow),
217 ),
218 }),
219 ),
220 );
221 const httpSnapshot = yield* snapshotLoader.load(prepared);
222 if (Option.isSome(httpSnapshot)) {
223 yield* applyItem({ kind: "snapshot", snapshot: httpSnapshot.value });
224 canResume = true;
225 current = yield* SubscriptionRef.get(state);
226 }
227 }
228
229 // If the authoritative refresh failed, omit the cached cursor so the
230 // socket fallback sends a complete snapshot for this new session.
231 if (!canResume || Option.isNone(current.snapshot)) {
232 return supportsCompletionMarker ? { requestCompletionMarker: true as const } : {};
233 }
234 if (!supportsCompletionMarker) {
235 // Without a completion marker there is no synchronized signal for a
236 // resumed subscription, so report live immediately, like threads.
237 yield* SubscriptionRef.update(state, (value) => ({
238 ...value,
239 status: "live" as const,
240 error: Option.none(),
241 }));
242 }
243 return {
244 afterSequence: current.snapshot.value.snapshotSequence,
245 ...(supportsCompletionMarker ? { requestCompletionMarker: true as const } : {}),
246 };
247 }),
248 {
249 onExpectedFailure: (cause) => setStreamError(Cause.squash(cause)),
250 retryExpectedFailureAfter: "250 millis",
251 resubscribe: foregroundResubscriptions,
252 },
253 ).pipe(Stream.runForEach(applyItem)),
254 );
255 yield* SubscriptionRef.changes(supervisor.state).pipe(
256 Stream.runForEach((connectionState) => {
257 switch (connectionProjectionPhase(connectionState)) {
258 case "synchronizing":
259 return setSynchronizing;
260 case "disconnected":
261 return setDisconnected;
262 case "ready":
263 return setReady;
264 }
265 }),
266 Effect.forkScoped,
267 );
268
269 return state;
270});
271
272export function shellStateChanges(environmentId: EnvironmentId) {
273 return followStreamInEnvironment(
274 environmentId,
275 Stream.unwrap(makeEnvironmentShellState().pipe(Effect.map(SubscriptionRef.changes))),
276 );
277}
278
279export interface EnvironmentShellSummary {
280 readonly hasSnapshot: boolean;
281 readonly hasSynchronizingShell: boolean;
282 readonly hasCachedShell: boolean;
283 readonly hasLiveShell: boolean;
284 readonly firstError: string | null;
285 readonly latestSnapshotUpdatedAt: string | null;
286}
287
288const EMPTY_ENVIRONMENT_SHELL_SUMMARY: EnvironmentShellSummary = Object.freeze({
289 hasSnapshot: false,
290 hasSynchronizingShell: false,
291 hasCachedShell: false,
292 hasLiveShell: false,
293 firstError: null,
294 latestSnapshotUpdatedAt: null,
295});
296
297const EMPTY_SERVER_CONFIGS: ReadonlyMap<EnvironmentId, ServerConfig> = new Map();
298
299function shellSummariesEqual(
300 left: EnvironmentShellSummary,
301 right: EnvironmentShellSummary,
302): boolean {
303 return (
304 left.hasSnapshot === right.hasSnapshot &&
305 left.hasSynchronizingShell === right.hasSynchronizingShell &&
306 left.hasCachedShell === right.hasCachedShell &&
307 left.hasLiveShell === right.hasLiveShell &&
308 left.firstError === right.firstError &&
309 left.latestSnapshotUpdatedAt === right.latestSnapshotUpdatedAt
310 );
311}
312
313function mapsEqual<K, V>(left: ReadonlyMap<K, V>, right: ReadonlyMap<K, V>): boolean {
314 if (left.size !== right.size) {
315 return false;
316 }
317 for (const [key, value] of left) {
318 if (right.get(key) !== value) {
319 return false;
320 }
321 }
322 return true;
323}
324
325export function createEnvironmentShellSummaryAtom(input: {
326 readonly catalogValueAtom: Atom.Atom<EnvironmentCatalogState>;
327 readonly shellStateValueAtom: (environmentId: EnvironmentId) => Atom.Atom<EnvironmentShellState>;
328}) {
329 let previousSummary = EMPTY_ENVIRONMENT_SHELL_SUMMARY;
330 return Atom.make((get) => {
331 let hasSnapshot = false;
332 let hasSynchronizingShell = false;
333 let hasCachedShell = false;
334 let hasLiveShell = false;
335 let firstError: string | null = null;
336 let latestSnapshotUpdatedAt: string | null = null;
337
338 for (const environmentId of get(input.catalogValueAtom).entries.keys()) {
339 const state = get(input.shellStateValueAtom(environmentId));
340 hasSynchronizingShell ||= state.status === "synchronizing";
341 hasCachedShell ||= state.status === "cached";
342 hasLiveShell ||= state.status === "live";
343 if (firstError === null) {
344 firstError = Option.getOrNull(state.error);
345 }
346 if (Option.isNone(state.snapshot)) {
347 continue;
348 }
349 hasSnapshot = true;
350 const updatedAt = state.snapshot.value.updatedAt;
351 if (latestSnapshotUpdatedAt === null || updatedAt > latestSnapshotUpdatedAt) {
352 latestSnapshotUpdatedAt = updatedAt;
353 }
354 }
355
356 const next: EnvironmentShellSummary = {
357 hasSnapshot,
358 hasSynchronizingShell,
359 hasCachedShell,
360 hasLiveShell,
361 firstError,
362 latestSnapshotUpdatedAt,
363 };
364 if (shellSummariesEqual(previousSummary, next)) {
365 return previousSummary;
366 }
367 previousSummary = next;
368 return previousSummary;
369 }).pipe(Atom.withLabel("environment-shell-summary"));
370}
371
372export function createEnvironmentServerConfigsAtom(input: {
373 readonly catalogValueAtom: Atom.Atom<EnvironmentCatalogState>;
374 readonly serverConfigValueAtom: (environmentId: EnvironmentId) => Atom.Atom<ServerConfig | null>;
375}) {
376 let previousServerConfigs = EMPTY_SERVER_CONFIGS;
377 return Atom.make((get) => {
378 const next = new Map<EnvironmentId, ServerConfig>();
379 for (const environmentId of get(input.catalogValueAtom).entries.keys()) {
380 const config = get(input.serverConfigValueAtom(environmentId));
381 if (config !== null) {
382 next.set(environmentId, config);
383 }
384 }
385 if (mapsEqual(previousServerConfigs, next)) {
386 return previousServerConfigs;
387 }
388 previousServerConfigs = next;
389 return previousServerConfigs;
390 }).pipe(Atom.withLabel("environment-server-configs"));
391}
392
393export function createEnvironmentShellAtoms<R, E>(
394 runtime: Atom.AtomRuntime<
395 EnvironmentRegistry | EnvironmentCacheStore | ShellSnapshotLoader | R,
396 E
397 >,
398) {
399 const stateAtom = Atom.family((environmentId: EnvironmentId) =>
400 runtime.atom(shellStateChanges(environmentId), {
401 initialValue: EMPTY_SHELL_STATE,
402 }),
403 );
404
405 const stateValueAtom = Atom.family((environmentId: EnvironmentId) =>
406 Atom.make((get) =>
407 Option.getOrElse(AsyncResult.value(get(stateAtom(environmentId))), () => EMPTY_SHELL_STATE),
408 ).pipe(Atom.withLabel(`environment-shell-state-value:${environmentId}`)),
409 );
410
411 return {
412 stateAtom,
413 stateValueAtom,
414 };
415}
416
417export * from "./models.ts";
418export * from "./shellCommands.ts";
419export * from "./shellReducer.ts";
420export * from "./shellSnapshotHttp.ts";
421export * from "./snapshots.ts";