Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

shell.ts

450 lines16.2 KB

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