Open History to see the last commit
1import {
2 ORCHESTRATION_V2_WS_METHODS,
3 type EnvironmentId,
4 type OrchestrationV2ShellSnapshot,
5 type OrchestrationV2ShellStreamItem,
6 type OrchestrationV2ThreadShell,
7 type ServerConfig,
8 type ThreadId,
9 type ThreadPullRequestLink,
10} from "@t3tools/contracts";
11import * as Cause from "effect/Cause";
12import * as Effect from "effect/Effect";
13import * as Fiber from "effect/Fiber";
14import * as Option from "effect/Option";
15import * as Queue from "effect/Queue";
16import * as Ref from "effect/Ref";
17import * as Semaphore from "effect/Semaphore";
18import * as Stream from "effect/Stream";
19import * as SubscriptionRef from "effect/SubscriptionRef";
20import { AsyncResult, Atom } from "effect/reactivity";
21
22import * as EnvironmentRegistry from "../connection/registry.ts";
23import { connectionProjectionPhase } from "../connection/model.ts";
24import * as EnvironmentSupervisor from "../connection/supervisor.ts";
25import * as ConnectionWakeups from "../connection/wakeups.ts";
26import { safeErrorLogAttributes } from "../errors/safeLog.ts";
27import * as Persistence from "../platform/persistence.ts";
28import { runCachePersistence } from "./cachePersistence.ts";
29import { subscribeDynamic } from "../rpc/client.ts";
30import type { RpcSession } from "../rpc/session.ts";
31import * as ShellSnapshotLoader from "./shellSnapshotHttp.ts";
32import type { DeferredShellSnapshot } from "./shellPullRequests.ts";
33import {
34 applyShellStreamEvent,
35 mergeShellSnapshotProjects,
36 reuseUnchangedThreadShells,
37 sameThreadPullRequests,
38} from "./shellReducer.ts";
39import { type EnvironmentCatalogState, enabledEnvironmentIds } from "./connections.ts";
40import { followStreamInEnvironment } from "./runtime.ts";
41
42export type EnvironmentShellStatus = "empty" | "cached" | "synchronizing" | "live";
43
44export interface EnvironmentShellState {
45 readonly snapshot: Option.Option<OrchestrationV2ShellSnapshot>;
46 readonly status: EnvironmentShellStatus;
47 readonly error: Option.Option<string>;
48}
49
50const EMPTY_SHELL_STATE: EnvironmentShellState = {
51 snapshot: Option.none(),
52 status: "empty",
53 error: Option.none(),
54};
55
56function shellStatusForSnapshot(
57 snapshot: Option.Option<OrchestrationV2ShellSnapshot>,
58): EnvironmentShellStatus {
59 return Option.isSome(snapshot) ? "cached" : "empty";
60}
61
62function withoutDeferredPullRequests(value: DeferredShellSnapshot): OrchestrationV2ShellSnapshot {
63 if (value.loadPullRequests === undefined) return value;
64 const { loadPullRequests: _deferred, ...snapshot } = value;
65 return snapshot;
66}
67
68const SHELL_SYNCHRONIZATION_ERROR_MESSAGE = "Could not synchronize environment data.";
69
70export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")(function* () {
71 const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
72 const cache = yield* Persistence.EnvironmentCacheStore;
73 const snapshotLoader = yield* ShellSnapshotLoader.ShellSnapshotLoader;
74 const wakeups = yield* Effect.serviceOption(ConnectionWakeups.ConnectionWakeups);
75 const environmentId = supervisor.target.environmentId;
76 const cached = yield* cache.loadShell(environmentId).pipe(
77 Effect.catch((error) =>
78 Effect.logWarning("Could not load cached environment shell.").pipe(
79 Effect.annotateLogs({
80 environmentId,
81 ...safeErrorLogAttributes(error),
82 }),
83 Effect.as(Option.none<DeferredShellSnapshot>()),
84 ),
85 ),
86 );
87 const cachedSnapshot = Option.map(cached, withoutDeferredPullRequests);
88 const state = yield* SubscriptionRef.make<EnvironmentShellState>({
89 snapshot: cachedSnapshot,
90 status: shellStatusForSnapshot(cachedSnapshot),
91 error: Option.none(),
92 });
93 const awaitingCompletion = yield* Ref.make(false);
94 const lastAuthoritativeSession = yield* Ref.make<RpcSession | null>(null);
95 const activeSubscriptionSession = yield* Ref.make<RpcSession | null>(null);
96 const latestLiveSnapshot = yield* Ref.make<Option.Option<OrchestrationV2ShellSnapshot>>(
97 Option.none(),
98 );
99 const persistence = yield* Queue.sliding<OrchestrationV2ShellSnapshot>(1);
100
101 const persistenceLock = yield* Semaphore.make(1);
102 let lastPersisted: OrchestrationV2ShellSnapshot | undefined;
103 // Rows still waiting for their deferred pull request links, which must not be saved:
104 // the cache would keep them without links until the next server refresh.
105 let pendingLinkRows: ReadonlySet<OrchestrationV2ThreadShell> = new Set();
106 const persistLatest = Effect.fn("EnvironmentShellState.persistLatest")(function* (
107 flush: boolean,
108 ) {
109 while (true) {
110 const latest = yield* Ref.get(latestLiveSnapshot);
111 if (Option.isNone(latest) || latest.value === lastPersisted) return;
112 if (latest.value.threads.some((thread) => pendingLinkRows.has(thread))) return;
113 const snapshot = latest.value;
114 const saved = yield* cache.saveShell(environmentId, snapshot).pipe(
115 Effect.as(true),
116 Effect.catch((error) =>
117 Effect.logWarning("Could not persist environment shell cache.").pipe(
118 Effect.annotateLogs({ environmentId, ...safeErrorLogAttributes(error) }),
119 Effect.as(false),
120 ),
121 ),
122 );
123 if (!saved) return;
124 lastPersisted = snapshot;
125 // Only lifecycle flushes chase updates that arrived during an in-flight save.
126 // The regular worker leaves those updates for the next write window.
127 if (!flush) return;
128 }
129 }, persistenceLock.withPermit);
130 const persist = () => persistLatest(false);
131 const flushLiveShellSnapshot = persistLatest(true);
132
133 // Register before scoped worker fibers so reverse finalizer order interrupts
134 // those fibers first and this flush sees a stable latestLiveSnapshot.
135 yield* Effect.addFinalizer(() => flushLiveShellSnapshot);
136
137 yield* runCachePersistence(persistence, persist).pipe(Effect.forkScoped);
138
139 const setDisconnected = Ref.set(awaitingCompletion, false).pipe(
140 Effect.andThen(
141 SubscriptionRef.update(state, (current) => ({
142 ...current,
143 status: shellStatusForSnapshot(current.snapshot),
144 })),
145 ),
146 Effect.andThen(flushLiveShellSnapshot.pipe(Effect.forkScoped)),
147 Effect.asVoid,
148 );
149 const setSynchronizing = SubscriptionRef.update(state, (current) => ({
150 ...current,
151 status: "synchronizing" as const,
152 error: Option.none(),
153 }));
154 const setReady = SubscriptionRef.update(state, (current) =>
155 current.status === "live"
156 ? current
157 : {
158 ...current,
159 status: "synchronizing" as const,
160 error: Option.none(),
161 },
162 );
163 const setStreamError = (error: unknown) =>
164 Ref.set(awaitingCompletion, false).pipe(
165 Effect.andThen(Effect.logWarning("Could not synchronize the environment shell.")),
166 Effect.annotateLogs({
167 environmentId,
168 ...safeErrorLogAttributes(error),
169 }),
170 Effect.andThen(
171 SubscriptionRef.update(state, (current) => ({
172 ...current,
173 status: shellStatusForSnapshot(current.snapshot),
174 error: Option.some(SHELL_SYNCHRONIZATION_ERROR_MESSAGE),
175 })),
176 ),
177 );
178
179 // Server items and deferred link fills both read the snapshot and write it back; one at a
180 // time, so neither can overwrite what the other wrote in between.
181 const snapshotWriteLock = yield* Semaphore.make(1);
182
183 // Apply each received batch with one state write. The RPC client's bounded
184 // buffer can split a server chunk, so a bulk action can still need several
185 // writes, but each write includes every event in that batch.
186 const applyItems = Effect.fn("EnvironmentShellState.applyItems")(function* (
187 items: ReadonlyArray<OrchestrationV2ShellStreamItem>,
188 // Ids of rows whose links will fill later; they are held out of saves before one queues.
189 pendingLinkIds?: ReadonlySet<ThreadId>,
190 ) {
191 const initial = yield* SubscriptionRef.get(state);
192 let waiting = yield* Ref.get(awaitingCompletion);
193 let next = initial;
194 let receivedSnapshot = false;
195 for (const item of items) {
196 if (item.kind === "synchronized") {
197 waiting = false;
198 if (Option.isSome(next.snapshot)) {
199 next = { ...next, status: "live", error: Option.none() };
200 }
201 continue;
202 }
203 const nextSnapshot =
204 item.kind === "snapshot"
205 ? mergeShellSnapshotProjects(
206 Option.getOrNull(next.snapshot),
207 item.snapshot,
208 item.resolvedRepositoryIdentityRoots === undefined
209 ? undefined
210 : {
211 resolvedRepositoryIdentityRoots: item.resolvedRepositoryIdentityRoots,
212 },
213 )
214 : Option.match(next.snapshot, {
215 onNone: () => null,
216 onSome: (snapshot) =>
217 item.sequence > snapshot.snapshotSequence
218 ? applyShellStreamEvent(snapshot, item)
219 : snapshot,
220 });
221 if (nextSnapshot === null) continue;
222 receivedSnapshot ||= item.kind === "snapshot";
223 next = {
224 snapshot: Option.some(nextSnapshot),
225 status: waiting ? "synchronizing" : "live",
226 error: Option.none(),
227 };
228 }
229 yield* Ref.set(awaitingCompletion, waiting);
230 if (next === initial) return;
231 if (pendingLinkIds !== undefined && Option.isSome(next.snapshot)) {
232 pendingLinkRows = new Set(
233 next.snapshot.value.threads.filter((thread) => pendingLinkIds.has(thread.id)),
234 );
235 }
236 if (Option.isSome(next.snapshot)) {
237 yield* Ref.set(latestLiveSnapshot, next.snapshot);
238 }
239 yield* SubscriptionRef.set(state, next);
240 if (receivedSnapshot) {
241 const session = yield* Ref.get(activeSubscriptionSession);
242 if (session !== null) {
243 yield* Ref.set(lastAuthoritativeSession, session);
244 }
245 }
246 if (next.snapshot !== initial.snapshot && Option.isSome(next.snapshot)) {
247 yield* Queue.offer(persistence, next.snapshot.value);
248 }
249 }, snapshotWriteLock.withPermit);
250
251 // Rows can arrive before their pull request links (see DeferredShellSnapshot), so the list
252 // paints first. The links then fill into the rows that still hold the object they arrived
253 // with; a row the server has replaced since carries its own links.
254 // Captured so fills started from the subscription callback still end with this state.
255 const stateScope = yield* Effect.scope;
256 // Each full snapshot supersedes the previous one's fill; links from an older snapshot must
257 // not land on rows a newer snapshot reused. A cancelled fill's rows stay pending until the
258 // next snapshot replaces the pending set.
259 let activeFill: Fiber.Fiber<void> | undefined;
260 const cancelActiveFill = Effect.suspend(() => {
261 const fill = activeFill;
262 activeFill = undefined;
263 return fill === undefined ? Effect.void : Fiber.interrupt(fill);
264 });
265 const fillDeferredPullRequests = Effect.fnUntraced(function* (
266 source: DeferredShellSnapshot,
267 applied: OrchestrationV2ShellSnapshot,
268 ) {
269 yield* cancelActiveFill;
270 if (source.loadPullRequests === undefined) return;
271 const arrivedRows = new Set(applied.threads);
272 const arrivedIds = new Set(source.threads.map((thread) => thread.id));
273 pendingLinkRows = new Set(applied.threads.filter((thread) => arrivedIds.has(thread.id)));
274 activeFill = yield* source.loadPullRequests.pipe(
275 Effect.flatMap((linksByThreadId) =>
276 writeFilledLinks(linksByThreadId, arrivedRows, arrivedIds),
277 ),
278 Effect.forkIn(stateScope),
279 );
280 });
281 const writeFilledLinks = Effect.fnUntraced(
282 function* (
283 linksByThreadId: ReadonlyMap<ThreadId, ReadonlyArray<ThreadPullRequestLink>>,
284 arrivedRows: ReadonlySet<OrchestrationV2ThreadShell>,
285 arrivedIds: ReadonlySet<ThreadId>,
286 ) {
287 const filled = yield* SubscriptionRef.modify(
288 state,
289 (current): [Option.Option<OrchestrationV2ShellSnapshot>, EnvironmentShellState] => {
290 if (Option.isNone(current.snapshot)) return [Option.none(), current];
291 const snapshot = current.snapshot.value;
292 let changed = false;
293 const threads = snapshot.threads.map((thread) => {
294 if (!arrivedRows.has(thread) || !arrivedIds.has(thread.id)) return thread;
295 const links = linksByThreadId.get(thread.id);
296 // A reused row may already hold these links from an earlier fill.
297 if (sameThreadPullRequests(thread.pullRequests, links)) return thread;
298 changed = true;
299 if (links === undefined) {
300 const { pullRequests: _previous, ...row } = thread;
301 return row;
302 }
303 return { ...thread, pullRequests: links };
304 });
305 if (!changed) return [Option.none(), current];
306 const next = { ...snapshot, threads };
307 return [Option.some(next), { ...current, snapshot: Option.some(next) }];
308 },
309 );
310 // Saves skipped while links were pending are queued again. Cached rows are never live:
311 // until a server snapshot arrives there is nothing new to save.
312 pendingLinkRows = new Set();
313 const live = yield* Ref.get(latestLiveSnapshot);
314 if (Option.isNone(live)) return;
315 const latest = Option.isSome(filled) ? filled : live;
316 yield* Ref.set(latestLiveSnapshot, latest);
317 yield* Queue.offer(persistence, latest.value);
318 },
319 (effect) => snapshotWriteLock.withPermit(effect),
320 );
321 if (Option.isSome(cached) && Option.isSome(cachedSnapshot)) {
322 yield* fillDeferredPullRequests(cached.value, cachedSnapshot.value);
323 }
324
325 const foregroundResubscriptions = Option.match(wakeups, {
326 onNone: () => Stream.never,
327 onSome: (service) =>
328 service.changes.pipe(Stream.filter(ConnectionWakeups.shouldResubscribeAfterWakeup)),
329 });
330
331 yield* setSynchronizing;
332 yield* Effect.forkScoped(
333 subscribeDynamic(
334 ORCHESTRATION_V2_WS_METHODS.subscribeShell,
335 Effect.fn("EnvironmentShellState.makeSubscribeInput")(function* (session) {
336 yield* Ref.set(activeSubscriptionSession, session);
337 const supportsCompletionMarker = yield* session.initialConfig.pipe(
338 Effect.map((config) => config.shellResumeCompletionMarker === true),
339 Effect.orElseSucceed(() => false),
340 );
341 yield* Ref.set(awaitingCompletion, supportsCompletionMarker);
342 yield* setSynchronizing;
343
344 // Foreground resubscriptions on the same live session can resume from
345 // the in-memory cursor. A new session reloads the authoritative HTTP
346 // snapshot so a valid cursor cannot preserve incomplete cached data.
347 const hasAuthoritativeSnapshot = (yield* Ref.get(lastAuthoritativeSession)) === session;
348 let canResume = hasAuthoritativeSnapshot;
349 let current = yield* SubscriptionRef.get(state);
350 if (!hasAuthoritativeSnapshot || Option.isNone(current.snapshot)) {
351 const prepared = yield* SubscriptionRef.get(supervisor.prepared).pipe(
352 Effect.flatMap(
353 Option.match({
354 onSome: Effect.succeed,
355 onNone: () =>
356 SubscriptionRef.changes(supervisor.prepared).pipe(
357 Stream.filter(Option.isSome),
358 Stream.map((value) => value.value),
359 Stream.runHead,
360 Effect.map(Option.getOrThrow),
361 ),
362 }),
363 ),
364 );
365 const httpSnapshot = yield* snapshotLoader.load(prepared);
366 if (Option.isSome(httpSnapshot)) {
367 yield* cancelActiveFill;
368 const previous = yield* SubscriptionRef.get(state);
369 const snapshot = reuseUnchangedThreadShells(
370 Option.getOrNull(previous.snapshot),
371 withoutDeferredPullRequests(httpSnapshot.value),
372 );
373 const pendingLinkIds = new Set(
374 httpSnapshot.value.loadPullRequests === undefined
375 ? []
376 : httpSnapshot.value.threads.map((thread) => thread.id),
377 );
378 yield* applyItems([{ kind: "snapshot", snapshot }], pendingLinkIds);
379 canResume = true;
380 current = yield* SubscriptionRef.get(state);
381 if (Option.isSome(current.snapshot)) {
382 yield* fillDeferredPullRequests(httpSnapshot.value, current.snapshot.value);
383 }
384 }
385 }
386
387 // If the authoritative refresh failed, omit the cached cursor so the
388 // socket fallback sends a complete snapshot for this new session.
389 if (!canResume || Option.isNone(current.snapshot)) {
390 return supportsCompletionMarker ? { requestCompletionMarker: true as const } : {};
391 }
392 if (!supportsCompletionMarker) {
393 // Without a completion marker there is no synchronized signal for a
394 // resumed subscription, so report live immediately, like threads.
395 yield* SubscriptionRef.update(state, (value) => ({
396 ...value,
397 status: "live" as const,
398 error: Option.none(),
399 }));
400 }
401 return {
402 afterSequence: current.snapshot.value.snapshotSequence,
403 ...(supportsCompletionMarker ? { requestCompletionMarker: true as const } : {}),
404 };
405 }),
406 {
407 onExpectedFailure: (cause) => setStreamError(Cause.squash(cause)),
408 retryExpectedFailureAfter: "250 millis",
409 resubscribe: foregroundResubscriptions,
410 },
411 ).pipe(Stream.runForEachArray((items) => applyItems(items))),
412 );
413 yield* SubscriptionRef.changes(supervisor.state).pipe(
414 Stream.runForEach((connectionState) => {
415 switch (connectionProjectionPhase(connectionState)) {
416 case "synchronizing":
417 return setSynchronizing;
418 case "disconnected":
419 return setDisconnected;
420 case "ready":
421 return setReady;
422 }
423 }),
424 Effect.forkScoped,
425 );
426
427 return state;
428});
429
430function shellStateChanges(environmentId: EnvironmentId) {
431 return followStreamInEnvironment(
432 environmentId,
433 Stream.unwrap(makeEnvironmentShellState().pipe(Effect.map(SubscriptionRef.changes))),
434 );
435}
436
437export interface EnvironmentShellSummary {
438 readonly hasSnapshot: boolean;
439 readonly hasSynchronizingShell: boolean;
440 readonly hasCachedShell: boolean;
441 readonly hasLiveShell: boolean;
442 readonly firstError: string | null;
443}
444
445const EMPTY_ENVIRONMENT_SHELL_SUMMARY: EnvironmentShellSummary = Object.freeze({
446 hasSnapshot: false,
447 hasSynchronizingShell: false,
448 hasCachedShell: false,
449 hasLiveShell: false,
450 firstError: null,
451});
452
453const EMPTY_SERVER_CONFIGS: ReadonlyMap<EnvironmentId, ServerConfig> = new Map();
454
455function shellSummariesEqual(
456 left: EnvironmentShellSummary,
457 right: EnvironmentShellSummary,
458): boolean {
459 return (
460 left.hasSnapshot === right.hasSnapshot &&
461 left.hasSynchronizingShell === right.hasSynchronizingShell &&
462 left.hasCachedShell === right.hasCachedShell &&
463 left.hasLiveShell === right.hasLiveShell &&
464 left.firstError === right.firstError
465 );
466}
467
468function mapsEqual<K, V>(left: ReadonlyMap<K, V>, right: ReadonlyMap<K, V>): boolean {
469 if (left.size !== right.size) {
470 return false;
471 }
472 for (const [key, value] of left) {
473 if (right.get(key) !== value) {
474 return false;
475 }
476 }
477 return true;
478}
479
480export function createEnvironmentShellSummaryAtom(input: {
481 readonly catalogValueAtom: Atom.Atom<EnvironmentCatalogState>;
482 readonly shellStateValueAtom: (environmentId: EnvironmentId) => Atom.Atom<EnvironmentShellState>;
483}) {
484 let previousSummary = EMPTY_ENVIRONMENT_SHELL_SUMMARY;
485 return Atom.make((get) => {
486 let hasSnapshot = false;
487 let hasSynchronizingShell = false;
488 let hasCachedShell = false;
489 let hasLiveShell = false;
490 let firstError: string | null = null;
491
492 for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
493 const state = get(input.shellStateValueAtom(environmentId));
494 hasSynchronizingShell ||= state.status === "synchronizing";
495 hasCachedShell ||= state.status === "cached";
496 hasLiveShell ||= state.status === "live";
497 if (firstError === null) {
498 firstError = Option.getOrNull(state.error);
499 }
500 if (Option.isNone(state.snapshot)) {
501 continue;
502 }
503 hasSnapshot = true;
504 }
505
506 const next: EnvironmentShellSummary = {
507 hasSnapshot,
508 hasSynchronizingShell,
509 hasCachedShell,
510 hasLiveShell,
511 firstError,
512 };
513 if (shellSummariesEqual(previousSummary, next)) {
514 return previousSummary;
515 }
516 previousSummary = next;
517 return previousSummary;
518 }).pipe(Atom.withLabel("environment-shell-summary"));
519}
520
521export function createEnvironmentServerConfigsAtom(input: {
522 readonly catalogValueAtom: Atom.Atom<EnvironmentCatalogState>;
523 readonly serverConfigValueAtom: (environmentId: EnvironmentId) => Atom.Atom<ServerConfig | null>;
524}) {
525 let previousServerConfigs = EMPTY_SERVER_CONFIGS;
526 return Atom.make((get) => {
527 const next = new Map<EnvironmentId, ServerConfig>();
528 for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
529 const config = get(input.serverConfigValueAtom(environmentId));
530 if (config !== null) {
531 next.set(environmentId, config);
532 }
533 }
534 if (mapsEqual(previousServerConfigs, next)) {
535 return previousServerConfigs;
536 }
537 previousServerConfigs = next;
538 return previousServerConfigs;
539 }).pipe(Atom.withLabel("environment-server-configs"));
540}
541
542export function createEnvironmentShellAtoms<R, E>(
543 runtime: Atom.AtomRuntime<
544 | EnvironmentRegistry.EnvironmentRegistry
545 | Persistence.EnvironmentCacheStore
546 | ShellSnapshotLoader.ShellSnapshotLoader
547 | R,
548 E
549 >,
550) {
551 const stateAtom = Atom.family((environmentId: EnvironmentId) =>
552 runtime.atom(shellStateChanges(environmentId), {
553 initialValue: EMPTY_SHELL_STATE,
554 }),
555 );
556
557 const stateValueAtom = Atom.family((environmentId: EnvironmentId) =>
558 Atom.make((get) =>
559 Option.getOrElse(AsyncResult.value(get(stateAtom(environmentId))), () => EMPTY_SHELL_STATE),
560 ).pipe(Atom.withLabel(`environment-shell-state-value:${environmentId}`)),
561 );
562
563 return {
564 stateAtom,
565 stateValueAtom,
566 };
567}
568
569export * from "./models.ts";
570export * from "./shellCommands.ts";
571export * from "./shellReducer.ts";
572export * from "./shellPullRequests.ts";
573export * as ShellSnapshotLoader from "./shellSnapshotHttp.ts";
574export * from "./snapshots.ts";