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 "@v12/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 Stream from "effect/Stream";
13import * as SubscriptionRef from "effect/SubscriptionRef";
14import { AsyncResult, Atom } from "effect/unstable/reactivity";
15
16import { EnvironmentRegistry } from "../connection/registry.ts";
17import { connectionProjectionPhase } from "../connection/model.ts";
18import { EnvironmentSupervisor } from "../connection/supervisor.ts";
19import { safeErrorLogAttributes } from "../errors/safeLog.ts";
20import { EnvironmentCacheStore } from "../platform/persistence.ts";
21import { subscribe } from "../rpc/client.ts";
22import { ShellSnapshotLoader } from "./shellSnapshotHttp.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<OrchestrationShellSnapshot>;
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<OrchestrationShellSnapshot>,
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 snapshotLoader = yield* ShellSnapshotLoader;
53 const environmentId = supervisor.target.environmentId;
54 const cachedSnapshot = yield* cache.loadShell(environmentId).pipe(
55 Effect.catch((error) =>
56 Effect.logWarning("Could not load cached environment shell.").pipe(
57 Effect.annotateLogs({
58 environmentId,
59 ...safeErrorLogAttributes(error),
60 }),
61 Effect.as(Option.none<OrchestrationShellSnapshot>()),
62 ),
63 ),
64 );
65 const state = yield* SubscriptionRef.make<EnvironmentShellState>({
66 snapshot: cachedSnapshot,
67 status: shellStatusForSnapshot(cachedSnapshot),
68 error: Option.none(),
69 });
70 const persistence = yield* Queue.sliding<OrchestrationShellSnapshot>(1);
71
72 const persist = Effect.fn("EnvironmentShellState.persist")(function* (
73 snapshot: OrchestrationShellSnapshot,
74 ) {
75 yield* cache.saveShell(environmentId, snapshot).pipe(
76 Effect.catch((error) =>
77 Effect.logWarning("Could not persist environment shell cache.").pipe(
78 Effect.annotateLogs({
79 environmentId,
80 ...safeErrorLogAttributes(error),
81 }),
82 ),
83 ),
84 );
85 });
86
87 yield* Stream.fromQueue(persistence).pipe(
88 Stream.debounce("500 millis"),
89 Stream.runForEach(persist),
90 Effect.forkScoped,
91 );
92
93 const setDisconnected = SubscriptionRef.update(state, (current) => ({
94 ...current,
95 status: shellStatusForSnapshot(current.snapshot),
96 }));
97 const setSynchronizing = SubscriptionRef.update(state, (current) => ({
98 ...current,
99 status: "synchronizing" as const,
100 error: Option.none(),
101 }));
102 const setReady = SubscriptionRef.update(state, (current) =>
103 current.status === "live"
104 ? current
105 : {
106 ...current,
107 status: "synchronizing" as const,
108 error: Option.none(),
109 },
110 );
111 const setStreamError = (error: unknown) =>
112 Effect.logWarning("Could not synchronize the environment shell.").pipe(
113 Effect.annotateLogs({
114 environmentId,
115 ...safeErrorLogAttributes(error),
116 }),
117 Effect.andThen(
118 SubscriptionRef.update(state, (current) => ({
119 ...current,
120 status: shellStatusForSnapshot(current.snapshot),
121 error: Option.some(SHELL_SYNCHRONIZATION_ERROR_MESSAGE),
122 })),
123 ),
124 );
125
126 const applyItem = Effect.fn("EnvironmentShellState.applyItem")(function* (
127 item: OrchestrationShellStreamItem,
128 ) {
129 const current = yield* SubscriptionRef.get(state);
130 const nextSnapshot =
131 item.kind === "snapshot"
132 ? item.snapshot
133 : Option.match(current.snapshot, {
134 onNone: () => null,
135 onSome: (snapshot) =>
136 item.sequence > snapshot.snapshotSequence
137 ? applyShellStreamEvent(snapshot, item)
138 : snapshot,
139 });
140 if (nextSnapshot === null) {
141 return;
142 }
143
144 yield* SubscriptionRef.set(state, {
145 snapshot: Option.some(nextSnapshot),
146 status: "live",
147 error: Option.none(),
148 });
149 yield* Queue.offer(persistence, nextSnapshot);
150 });
151
152 yield* Effect.forkScoped(
153 Effect.gen(function* () {
154 // Establish the base shell snapshot to resume from, minimizing bytes over
155 // the wire:
156 // - Warm cache: reuse the cached snapshot (zero network) and resume via
157 // `afterSequence` so we only receive shell events since the cached
158 // sequence.
159 // - Cold cache: load the full shell snapshot over HTTP (gzip-compressible,
160 // and off the socket), then resume via `afterSequence`.
161 // If no base can be established we fall back to the socket-embedded
162 // snapshot so the shell still synchronizes. Overlapping/replayed events are
163 // deduped by sequence in applyItem.
164 const base = Option.isSome(cachedSnapshot)
165 ? cachedSnapshot
166 : yield* Effect.gen(function* () {
167 const prepared = yield* SubscriptionRef.changes(supervisor.prepared).pipe(
168 Stream.filter(Option.isSome),
169 Stream.map((current) => current.value),
170 Stream.runHead,
171 );
172 return Option.isSome(prepared)
173 ? yield* snapshotLoader.load(prepared.value)
174 : Option.none<OrchestrationShellSnapshot>();
175 });
176
177 if (Option.isSome(base)) {
178 yield* applyItem({ kind: "snapshot", snapshot: base.value });
179 }
180
181 const subscribeInput = Option.match(base, {
182 onNone: () => ({}),
183 onSome: (snapshot) => ({ afterSequence: snapshot.snapshotSequence }),
184 });
185
186 yield* subscribe(ORCHESTRATION_WS_METHODS.subscribeShell, subscribeInput, {
187 onExpectedFailure: (cause) => setStreamError(Cause.squash(cause)),
188 }).pipe(Stream.runForEach(applyItem));
189 }),
190 );
191 yield* SubscriptionRef.changes(supervisor.state).pipe(
192 Stream.runForEach((connectionState) => {
193 switch (connectionProjectionPhase(connectionState)) {
194 case "synchronizing":
195 return setSynchronizing;
196 case "disconnected":
197 return setDisconnected;
198 case "ready":
199 return setReady;
200 }
201 }),
202 Effect.forkScoped,
203 );
204
205 return state;
206});
207
208export function shellStateChanges(environmentId: EnvironmentId) {
209 return followStreamInEnvironment(
210 environmentId,
211 Stream.unwrap(makeEnvironmentShellState().pipe(Effect.map(SubscriptionRef.changes))),
212 );
213}
214
215export interface EnvironmentShellSummary {
216 readonly hasSnapshot: boolean;
217 readonly hasSynchronizingShell: boolean;
218 readonly hasCachedShell: boolean;
219 readonly hasLiveShell: boolean;
220 readonly firstError: string | null;
221 readonly latestSnapshotUpdatedAt: string | null;
222}
223
224const EMPTY_ENVIRONMENT_SHELL_SUMMARY: EnvironmentShellSummary = Object.freeze({
225 hasSnapshot: false,
226 hasSynchronizingShell: false,
227 hasCachedShell: false,
228 hasLiveShell: false,
229 firstError: null,
230 latestSnapshotUpdatedAt: null,
231});
232
233const EMPTY_SERVER_CONFIGS: ReadonlyMap<EnvironmentId, ServerConfig> = new Map();
234
235function shellSummariesEqual(
236 left: EnvironmentShellSummary,
237 right: EnvironmentShellSummary,
238): boolean {
239 return (
240 left.hasSnapshot === right.hasSnapshot &&
241 left.hasSynchronizingShell === right.hasSynchronizingShell &&
242 left.hasCachedShell === right.hasCachedShell &&
243 left.hasLiveShell === right.hasLiveShell &&
244 left.firstError === right.firstError &&
245 left.latestSnapshotUpdatedAt === right.latestSnapshotUpdatedAt
246 );
247}
248
249function mapsEqual<K, V>(left: ReadonlyMap<K, V>, right: ReadonlyMap<K, V>): boolean {
250 if (left.size !== right.size) {
251 return false;
252 }
253 for (const [key, value] of left) {
254 if (right.get(key) !== value) {
255 return false;
256 }
257 }
258 return true;
259}
260
261export function createEnvironmentShellSummaryAtom(input: {
262 readonly catalogValueAtom: Atom.Atom<EnvironmentCatalogState>;
263 readonly shellStateValueAtom: (environmentId: EnvironmentId) => Atom.Atom<EnvironmentShellState>;
264}) {
265 let previousSummary = EMPTY_ENVIRONMENT_SHELL_SUMMARY;
266 return Atom.make((get) => {
267 let hasSnapshot = false;
268 let hasSynchronizingShell = false;
269 let hasCachedShell = false;
270 let hasLiveShell = false;
271 let firstError: string | null = null;
272 let latestSnapshotUpdatedAt: string | null = null;
273
274 for (const environmentId of get(input.catalogValueAtom).entries.keys()) {
275 const state = get(input.shellStateValueAtom(environmentId));
276 hasSynchronizingShell ||= state.status === "synchronizing";
277 hasCachedShell ||= state.status === "cached";
278 hasLiveShell ||= state.status === "live";
279 if (firstError === null) {
280 firstError = Option.getOrNull(state.error);
281 }
282 if (Option.isNone(state.snapshot)) {
283 continue;
284 }
285 hasSnapshot = true;
286 const updatedAt = state.snapshot.value.updatedAt;
287 if (latestSnapshotUpdatedAt === null || updatedAt > latestSnapshotUpdatedAt) {
288 latestSnapshotUpdatedAt = updatedAt;
289 }
290 }
291
292 const next: EnvironmentShellSummary = {
293 hasSnapshot,
294 hasSynchronizingShell,
295 hasCachedShell,
296 hasLiveShell,
297 firstError,
298 latestSnapshotUpdatedAt,
299 };
300 if (shellSummariesEqual(previousSummary, next)) {
301 return previousSummary;
302 }
303 previousSummary = next;
304 return previousSummary;
305 }).pipe(Atom.withLabel("environment-shell-summary"));
306}
307
308export function createEnvironmentServerConfigsAtom(input: {
309 readonly catalogValueAtom: Atom.Atom<EnvironmentCatalogState>;
310 readonly serverConfigValueAtom: (environmentId: EnvironmentId) => Atom.Atom<ServerConfig | null>;
311}) {
312 let previousServerConfigs = EMPTY_SERVER_CONFIGS;
313 return Atom.make((get) => {
314 const next = new Map<EnvironmentId, ServerConfig>();
315 for (const environmentId of get(input.catalogValueAtom).entries.keys()) {
316 const config = get(input.serverConfigValueAtom(environmentId));
317 if (config !== null) {
318 next.set(environmentId, config);
319 }
320 }
321 if (mapsEqual(previousServerConfigs, next)) {
322 return previousServerConfigs;
323 }
324 previousServerConfigs = next;
325 return previousServerConfigs;
326 }).pipe(Atom.withLabel("environment-server-configs"));
327}
328
329export function createEnvironmentShellAtoms<R, E>(
330 runtime: Atom.AtomRuntime<
331 EnvironmentRegistry | EnvironmentCacheStore | ShellSnapshotLoader | R,
332 E
333 >,
334) {
335 const stateAtom = Atom.family((environmentId: EnvironmentId) =>
336 runtime.atom(shellStateChanges(environmentId), {
337 initialValue: EMPTY_SHELL_STATE,
338 }),
339 );
340
341 const stateValueAtom = Atom.family((environmentId: EnvironmentId) =>
342 Atom.make((get) =>
343 Option.getOrElse(AsyncResult.value(get(stateAtom(environmentId))), () => EMPTY_SHELL_STATE),
344 ).pipe(Atom.withLabel(`environment-shell-state-value:${environmentId}`)),
345 );
346
347 return {
348 stateAtom,
349 stateValueAtom,
350 };
351}
352
353export * from "./models.ts";
354export * from "./shellCommands.ts";
355export * from "./shellReducer.ts";
356export * from "./shellSnapshotHttp.ts";
357export * from "./snapshots.ts";