Open History to see the last commit
1import { mFallback, msg } from "gt-i18n";
2import type { MFunctionType } from "gt-i18n/types";
3import {
4 ORCHESTRATION_V2_WS_METHODS,
5 type EnvironmentId,
6 type ExecutionEnvironmentDescriptor,
7 type OrchestrationV2ShellSnapshot,
8 type OrchestrationV2ShellStreamItem,
9 type OrchestrationV2ThreadShell,
10 type ServerConfig,
11 type ThreadId,
12 type ThreadPullRequestLink,
13} from "@t3tools/contracts";
14import * as Cause from "effect/Cause";
15import * as Clock from "effect/Clock";
16import * as DateTime from "effect/DateTime";
17import * as Effect from "effect/Effect";
18import * as Exit from "effect/Exit";
19import * as Fiber from "effect/Fiber";
20import * as Option from "effect/Option";
21import * as Queue from "effect/Queue";
22import * as Ref from "effect/Ref";
23import * as Semaphore from "effect/Semaphore";
24import * as Stream from "effect/Stream";
25import * as SubscriptionRef from "effect/SubscriptionRef";
26import * as SynchronizedRef from "effect/SynchronizedRef";
27import { AsyncResult, Atom } from "effect/reactivity";
28
29import { observeServerTime } from "../clock.ts";
30import * as EnvironmentRegistry from "../connection/registry.ts";
31import { connectionProjectionPhase, type PreparedConnection } from "../connection/model.ts";
32import * as EnvironmentSupervisor from "../connection/supervisor.ts";
33import * as ConnectionWakeups from "../connection/wakeups.ts";
34import { safeErrorLogAttributes } from "../errors/safeLog.ts";
35import * as Persistence from "../platform/persistence.ts";
36import { runCachePersistence } from "./cachePersistence.ts";
37import { subscribeDynamicWithSession, subscriptionRetryDelay } from "../rpc/client.ts";
38import type { RpcSession } from "../rpc/session.ts";
39import * as ShellSnapshotLoader from "./shellSnapshotHttp.ts";
40import type { DeferredShellSnapshot } from "./shellPullRequests.ts";
41import {
42 applyShellStreamEvents,
43 type ShellStreamEvent,
44 mergeShellSnapshotProjects,
45 reuseUnchangedThreadShells,
46 sameThreadPullRequests,
47} from "./shellReducer.ts";
48import { type EnvironmentCatalogState, enabledEnvironmentIds } from "./connections.ts";
49import { followStreamInEnvironment } from "./runtime.ts";
50
51export type EnvironmentShellStatus = "empty" | "cached" | "synchronizing" | "live";
52
53export interface EnvironmentShellState {
54 readonly snapshot: Option.Option<OrchestrationV2ShellSnapshot>;
55 readonly status: EnvironmentShellStatus;
56 readonly error: Option.Option<string>;
57 /**
58 * Changes with each authoritative snapshot (not enrichment refreshes); 0 until the first one.
59 * Thread families read for an older generation may miss changes from before the latest snapshot,
60 * so they are read again.
61 */
62 readonly generation: number;
63 /** Sequences of the thread removals applied since the latest authoritative snapshot. */
64 readonly removedAt: ReadonlyMap<ThreadId, number>;
65}
66
67const EMPTY_REMOVALS: ReadonlyMap<ThreadId, number> = new Map();
68// Shared by every shell state, so a rebuilt one never reuses a generation another already used.
69let lastShellGeneration = 0;
70
71export const EMPTY_SHELL_STATE: EnvironmentShellState = {
72 snapshot: Option.none(),
73 status: "empty",
74 error: Option.none(),
75 generation: 0,
76 removedAt: EMPTY_REMOVALS,
77};
78
79function shellStatusForSnapshot(
80 snapshot: Option.Option<OrchestrationV2ShellSnapshot>,
81): EnvironmentShellStatus {
82 return Option.isSome(snapshot) ? "cached" : "empty";
83}
84
85function withoutDeferredPullRequests(value: DeferredShellSnapshot): OrchestrationV2ShellSnapshot {
86 if (value.loadPullRequests === undefined) return value;
87 const { loadPullRequests: _deferred, ...snapshot } = value;
88 return snapshot;
89}
90
91const SHELL_SYNCHRONIZATION_ERROR_MESSAGE = msg("Could not synchronize environment data.");
92
93/** @public The shell's sync error in the active language; other messages stay as they are. */
94export function shellErrorText(error: string, resolve: MFunctionType = mFallback): string {
95 return error === SHELL_SYNCHRONIZATION_ERROR_MESSAGE ? resolve(error) : error;
96}
97
98/**
99 * Replay does not refresh the older-settled cut, rows that left the newest window, or
100 * projections the server rebuilt, so drift grows with the age of the last server snapshot.
101 */
102const CACHE_RESUME_MAX_AGE_MILLIS = 12 * 60 * 60 * 1000;
103
104// How long a ready socket waits for the early HTTP answer before it resumes held rows itself.
105// The supervisor's quick probe allows a live host the same time. A proxy that drops `/api`
106// without an answer would otherwise hold each connect for the full HTTP timeout.
107const EARLY_LOAD_GRACE = "3 seconds";
108
109type ShellOriginIdentity = Omit<Persistence.ShellCacheOrigin, "snapshotAt">;
110
111interface ShellSubscription {
112 readonly session: RpcSession;
113 /** What a snapshot from this subscription descends from; null when the server did not say. */
114 readonly identity: ShellOriginIdentity | null;
115}
116
117function shellIdentity(
118 environment: Pick<ExecutionEnvironmentDescriptor, "serverVersion" | "databaseMigration">,
119 flags: { readonly shellThreadFamilies?: boolean; readonly shellOlderSettled?: boolean },
120): ShellOriginIdentity {
121 const omitIdleSubagents = flags.shellThreadFamilies === true;
122 return {
123 serverVersion: environment.serverVersion,
124 // Migrations rewrite projections without events, so a migrated server reloads.
125 databaseMigration: environment.databaseMigration ?? null,
126 omitIdleSubagents,
127 omitOlderSettled: flags.shellOlderSettled === true && omitIdleSubagents,
128 };
129}
130
131function sameConnection(left: PreparedConnection, right: PreparedConnection): boolean {
132 const keys = Object.keys({ ...left, ...right }) as Array<keyof PreparedConnection>;
133 return keys.every((key) => key === "httpAuthorization" || left[key] === right[key]);
134}
135
136/** Null for a server whose descriptor does not name its shell flags; only its config does. */
137function descriptorShellIdentity(
138 descriptor: ExecutionEnvironmentDescriptor | undefined,
139): ShellOriginIdentity | null {
140 if (descriptor?.capabilities.shellThreadFamilies === undefined) return null;
141 return shellIdentity(descriptor, descriptor.capabilities);
142}
143
144function sameShellIdentity(left: ShellOriginIdentity, right: ShellOriginIdentity): boolean {
145 return (
146 left.serverVersion === right.serverVersion &&
147 left.databaseMigration === right.databaseMigration &&
148 left.omitIdleSubagents === right.omitIdleSubagents &&
149 left.omitOlderSettled === right.omitOlderSettled
150 );
151}
152
153function canResumeFrom(
154 origin: Persistence.ShellCacheOrigin | undefined,
155 identity: ShellOriginIdentity | null,
156 now: number,
157): boolean {
158 if (origin === undefined || identity === null) return false;
159 const age = now - origin.snapshotAt;
160 return sameShellIdentity(origin, identity) && age >= 0 && age < CACHE_RESUME_MAX_AGE_MILLIS;
161}
162
163type HttpShellOutcome =
164 | { readonly kind: "snapshot"; readonly projectIdentities: string | undefined }
165 /** The server can replay from the rows the client holds. */
166 | { readonly kind: "resumable" }
167 | { readonly kind: "failed" };
168
169interface EarlyShellLoad {
170 readonly prepared: PreparedConnection;
171 readonly identity: ShellOriginIdentity;
172 readonly fiber: Fiber.Fiber<HttpShellOutcome>;
173 // One subscription uses a load; a later one on the same connection decides again.
174 readonly claimed: boolean;
175}
176
177interface LiveShell {
178 readonly snapshot: OrchestrationV2ShellSnapshot;
179 // Read together with the rows, so a save never pairs them with another snapshot's origin.
180 readonly origin: Persistence.ShellCacheOrigin | undefined;
181}
182
183export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")(function* () {
184 const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
185 const cache = yield* Persistence.EnvironmentCacheStore;
186 const snapshotLoader = yield* ShellSnapshotLoader.ShellSnapshotLoader;
187 const wakeups = yield* Effect.serviceOption(ConnectionWakeups.ConnectionWakeups);
188 const environmentId = supervisor.target.environmentId;
189 const cached = yield* cache.loadShell(environmentId).pipe(
190 Effect.catch((error) =>
191 Effect.logWarning("Could not load cached environment shell.").pipe(
192 Effect.annotateLogs({
193 environmentId,
194 ...safeErrorLogAttributes(error),
195 }),
196 Effect.as(Option.none<Persistence.CachedShellSnapshot>()),
197 ),
198 ),
199 );
200 const cachedOrigin = Option.isSome(cached) ? cached.value.origin : undefined;
201 const cachedSnapshot = Option.map(cached, ({ origin: _origin, ...rows }) =>
202 withoutDeferredPullRequests(rows),
203 );
204 const state = yield* SubscriptionRef.make<EnvironmentShellState>({
205 ...EMPTY_SHELL_STATE,
206 snapshot: cachedSnapshot,
207 status: shellStatusForSnapshot(cachedSnapshot),
208 });
209 const awaitingCompletion = yield* Ref.make(false);
210 const activeSubscription = yield* Ref.make<ShellSubscription | null>(null);
211 // The server snapshot the in-memory rows descend from, directly or through the cache.
212 // Only a server snapshot renews it; `snapshot-required` drops it.
213 const origin = yield* Ref.make(cachedOrigin);
214 const reloadRequests = yield* Queue.unbounded<void>();
215 let defectRetries = 0;
216 const latestLive = yield* Ref.make<Option.Option<LiveShell>>(Option.none());
217 const persistence = yield* Queue.sliding<OrchestrationV2ShellSnapshot>(1);
218
219 const persistenceLock = yield* Semaphore.make(1);
220 let lastPersisted: LiveShell | undefined;
221 // Rows still waiting for their deferred pull request links, which must not be saved:
222 // the cache would keep them without links until the next server refresh.
223 let pendingLinkRows: ReadonlySet<OrchestrationV2ThreadShell> = new Set();
224 const persistLatest = Effect.fn("EnvironmentShellState.persistLatest")(function* (
225 flush: boolean,
226 ) {
227 while (true) {
228 const latest = yield* Ref.get(latestLive);
229 if (Option.isNone(latest) || latest.value === lastPersisted) return;
230 const { snapshot, origin } = latest.value;
231 if (snapshot.threads.some((thread) => pendingLinkRows.has(thread))) return;
232 if (
233 lastPersisted !== undefined &&
234 origin === lastPersisted.origin &&
235 snapshot.snapshotSequence >= lastPersisted.snapshot.snapshotSequence &&
236 snapshot.schemaVersion === lastPersisted.snapshot.schemaVersion &&
237 snapshot.projects === lastPersisted.snapshot.projects &&
238 snapshot.threads === lastPersisted.snapshot.threads &&
239 snapshot.archivedThreads === lastPersisted.snapshot.archivedThreads
240 ) {
241 // Keep the live cursor without rewriting the rows. Remember it here too so a
242 // later authoritative reset to a lower sequence still reaches the cache.
243 lastPersisted = latest.value;
244 return;
245 }
246 const saved = yield* cache.saveShell(environmentId, snapshot, origin).pipe(
247 Effect.as(true),
248 Effect.catch((error) =>
249 Effect.logWarning("Could not persist environment shell cache.").pipe(
250 Effect.annotateLogs({ environmentId, ...safeErrorLogAttributes(error) }),
251 Effect.as(false),
252 ),
253 ),
254 );
255 if (!saved) return;
256 lastPersisted = latest.value;
257 if (!flush) return;
258 }
259 }, persistenceLock.withPermit);
260 const persist = () => persistLatest(false);
261 const flushLiveShellSnapshot = persistLatest(true);
262
263 // Register before scoped worker fibers so reverse finalizer order interrupts
264 // those fibers first and this flush sees a stable latestLiveSnapshot.
265 yield* Effect.addFinalizer(() => flushLiveShellSnapshot);
266
267 yield* runCachePersistence(persistence, persist).pipe(Effect.forkScoped);
268
269 const setDisconnected = Ref.set(awaitingCompletion, false).pipe(
270 Effect.andThen(
271 SubscriptionRef.update(state, (current) => ({
272 ...current,
273 status: shellStatusForSnapshot(current.snapshot),
274 })),
275 ),
276 Effect.andThen(flushLiveShellSnapshot.pipe(Effect.forkScoped)),
277 Effect.asVoid,
278 );
279 const setSynchronizing = SubscriptionRef.update(state, (current) => ({
280 ...current,
281 status: "synchronizing" as const,
282 error: Option.none(),
283 }));
284 const setReady = SubscriptionRef.update(state, (current) =>
285 current.status === "live"
286 ? current
287 : {
288 ...current,
289 status: "synchronizing" as const,
290 error: Option.none(),
291 },
292 );
293 const setStreamError = (error: unknown) =>
294 Ref.set(awaitingCompletion, false).pipe(
295 Effect.andThen(Effect.logWarning("Could not synchronize the environment shell.")),
296 Effect.annotateLogs({
297 environmentId,
298 ...safeErrorLogAttributes(error),
299 }),
300 Effect.andThen(
301 SubscriptionRef.update(state, (current) => ({
302 ...current,
303 status: shellStatusForSnapshot(current.snapshot),
304 error: Option.some(SHELL_SYNCHRONIZATION_ERROR_MESSAGE),
305 })),
306 ),
307 );
308
309 // Server items and deferred link fills both read the snapshot and write it back; one at a
310 // time, so neither can overwrite what the other wrote in between.
311 const snapshotWriteLock = yield* Semaphore.make(1);
312
313 const applyLocked = Effect.fnUntraced(function* (
314 items: ReadonlyArray<OrchestrationV2ShellStreamItem>,
315 /** What an authoritative snapshot among the items descends from. */
316 identity: ShellOriginIdentity | null,
317 /** Set for an HTTP snapshot: the rows that still wait for their pull request links. */
318 pendingLinkIds?: ReadonlySet<ThreadId>,
319 ) {
320 const initial = yield* SubscriptionRef.get(state);
321 // No socket has confirmed an HTTP snapshot, so it never makes the shell live.
322 const fromHttp = pendingLinkIds !== undefined;
323 const disconnected = initial.status === "empty" || initial.status === "cached";
324 let waiting = yield* Ref.get(awaitingCompletion);
325 let next = initial;
326 let receivedAuthoritativeSnapshot = false;
327 let snapshotRequired = false;
328 let deltas: Array<ShellStreamEvent> = [];
329 const receivedAtMs = yield* Clock.currentTimeMillis;
330 const flushDeltas = () => {
331 if (deltas.length > 0 && Option.isSome(next.snapshot)) {
332 let sequence = next.snapshot.value.snapshotSequence;
333 let removedAt: Map<ThreadId, number> | undefined;
334 for (const delta of deltas) {
335 if (delta.sequence <= sequence) continue;
336 switch (delta.kind) {
337 case "thread.removed":
338 removedAt ??= new Map(next.removedAt);
339 removedAt.set(delta.threadId, delta.sequence);
340 break;
341 case "thread.updated":
342 // Replayed catch-up deltas may predate a backward host clock correction.
343 if (!waiting) {
344 observeServerTime(
345 environmentId,
346 DateTime.toEpochMillis(delta.thread.updatedAt),
347 receivedAtMs,
348 );
349 }
350 break;
351 case "project.updated":
352 case "project.removed":
353 break;
354 default:
355 continue;
356 }
357 sequence = delta.sequence;
358 }
359 next = {
360 ...next,
361 removedAt: removedAt ?? next.removedAt,
362 snapshot: Option.some(applyShellStreamEvents(next.snapshot.value, deltas)),
363 status: waiting ? "synchronizing" : "live",
364 error: Option.none(),
365 };
366 }
367 deltas = [];
368 };
369 for (const item of items) {
370 if (item.kind === "snapshot-required") {
371 snapshotRequired = true;
372 continue;
373 }
374 if (item.kind !== "snapshot" && item.kind !== "synchronized") {
375 deltas.push(item);
376 continue;
377 }
378 // Snapshots can reset the cursor; completion markers change the sync status.
379 flushDeltas();
380 if (item.kind === "synchronized") {
381 waiting = false;
382 if (Option.isSome(next.snapshot)) {
383 next = {
384 ...next,
385 status: "live",
386 error: Option.none(),
387 // A cache resume that caught up is as current as a snapshot for generation readers.
388 generation: next.generation === 0 ? ++lastShellGeneration : next.generation,
389 };
390 }
391 continue;
392 }
393 const authoritative = item.resolvedRepositoryIdentityRoots === undefined;
394 const nextSnapshot = mergeShellSnapshotProjects(
395 Option.getOrNull(next.snapshot),
396 item.snapshot,
397 item.resolvedRepositoryIdentityRoots === undefined
398 ? undefined
399 : { resolvedRepositoryIdentityRoots: item.resolvedRepositoryIdentityRoots },
400 );
401 if (authoritative) receivedAuthoritativeSnapshot = true;
402 next = {
403 snapshot: Option.some(nextSnapshot),
404 status:
405 fromHttp && disconnected ? "cached" : waiting || fromHttp ? "synchronizing" : "live",
406 error: Option.none(),
407 generation: authoritative ? ++lastShellGeneration : next.generation,
408 removedAt: authoritative ? EMPTY_REMOVALS : next.removedAt,
409 };
410 }
411 flushDeltas();
412 yield* Ref.set(awaitingCompletion, waiting);
413 let nextOrigin = yield* Ref.get(origin);
414 if (snapshotRequired) {
415 // The rows stay on screen but reload before the next resume; the cache keeps the old
416 // origin until that reload saves, which costs at most one more refusal.
417 nextOrigin = undefined;
418 yield* Ref.set(origin, nextOrigin);
419 yield* Queue.offer(reloadRequests, undefined);
420 } else if (receivedAuthoritativeSnapshot) {
421 nextOrigin =
422 identity === null ? undefined : { ...identity, snapshotAt: yield* Clock.currentTimeMillis };
423 yield* Ref.set(origin, nextOrigin);
424 }
425 if (next === initial) return;
426 if (pendingLinkIds !== undefined && Option.isSome(next.snapshot)) {
427 pendingLinkRows = new Set(
428 next.snapshot.value.threads.filter((thread) => pendingLinkIds.has(thread.id)),
429 );
430 }
431 if (Option.isSome(next.snapshot)) {
432 yield* Ref.set(
433 latestLive,
434 Option.some({ snapshot: next.snapshot.value, origin: nextOrigin }),
435 );
436 }
437 yield* SubscriptionRef.set(state, next);
438 if (next.snapshot !== initial.snapshot && Option.isSome(next.snapshot)) {
439 yield* Queue.offer(persistence, next.snapshot.value);
440 }
441 });
442
443 const applyItems = Effect.fn("EnvironmentShellState.applyItems")(function* (
444 entries: ReadonlyArray<readonly [RpcSession, OrchestrationV2ShellStreamItem]>,
445 ) {
446 // Read under the lock: items buffered across a session change must not land on the
447 // rows the next session loaded.
448 const subscription = yield* Ref.get(activeSubscription);
449 yield* applyLocked(
450 entries.flatMap(([session, item]) => (session === subscription?.session ? [item] : [])),
451 subscription?.identity ?? null,
452 );
453 }, snapshotWriteLock.withPermit);
454
455 const stateScope = yield* Effect.scope;
456 // Each full snapshot supersedes the previous one's fill; links from an older snapshot must
457 // not land on rows a newer snapshot reused.
458
459 let activeFill: Fiber.Fiber<void> | undefined;
460 const cancelActiveFill = Effect.suspend(() => {
461 const fill = activeFill;
462 activeFill = undefined;
463 return fill === undefined ? Effect.void : Fiber.interrupt(fill);
464 });
465 const fillDeferredPullRequests = Effect.fnUntraced(function* (
466 source: DeferredShellSnapshot,
467 applied: OrchestrationV2ShellSnapshot,
468 ) {
469 yield* cancelActiveFill;
470 if (source.loadPullRequests === undefined) return;
471 const arrivedRows = new Set(applied.threads);
472 const arrivedIds = new Set(source.threads.map((thread) => thread.id));
473 pendingLinkRows = new Set(applied.threads.filter((thread) => arrivedIds.has(thread.id)));
474 activeFill = yield* source.loadPullRequests.pipe(
475 Effect.flatMap((linksByThreadId) =>
476 writeFilledLinks(linksByThreadId, arrivedRows, arrivedIds),
477 ),
478 Effect.forkIn(stateScope),
479 );
480 });
481 const writeFilledLinks = Effect.fnUntraced(
482 function* (
483 linksByThreadId: ReadonlyMap<ThreadId, ReadonlyArray<ThreadPullRequestLink>>,
484 arrivedRows: ReadonlySet<OrchestrationV2ThreadShell>,
485 arrivedIds: ReadonlySet<ThreadId>,
486 ) {
487 const filled = yield* SubscriptionRef.modify(
488 state,
489 (current): [Option.Option<OrchestrationV2ShellSnapshot>, EnvironmentShellState] => {
490 if (Option.isNone(current.snapshot)) return [Option.none(), current];
491 const snapshot = current.snapshot.value;
492 let changed = false;
493 const threads = snapshot.threads.map((thread) => {
494 if (!arrivedRows.has(thread) || !arrivedIds.has(thread.id)) return thread;
495 const links = linksByThreadId.get(thread.id);
496 if (sameThreadPullRequests(thread.pullRequests, links)) return thread;
497 changed = true;
498 if (links === undefined) {
499 const { pullRequests: _previous, ...row } = thread;
500 return row;
501 }
502 return { ...thread, pullRequests: links };
503 });
504 if (!changed) return [Option.none(), current];
505 const next = { ...snapshot, threads };
506 return [Option.some(next), { ...current, snapshot: Option.some(next) }];
507 },
508 );
509 pendingLinkRows = new Set();
510 const live = yield* Ref.get(latestLive);
511 if (Option.isNone(live)) return;
512 const latest = Option.isSome(filled) ? filled.value : live.value.snapshot;
513 yield* Ref.set(latestLive, Option.some({ snapshot: latest, origin: live.value.origin }));
514 yield* Queue.offer(persistence, latest);
515 },
516 (effect) => snapshotWriteLock.withPermit(effect),
517 );
518 if (Option.isSome(cached) && Option.isSome(cachedSnapshot)) {
519 yield* fillDeferredPullRequests(cached.value, cachedSnapshot.value);
520 }
521
522 const applyHttpSnapshot = Effect.fnUntraced(function* (
523 loaded: ShellSnapshotLoader.ShellHttpSnapshot,
524 identity: ShellOriginIdentity | null,
525 ) {
526 const { projectIdentities: _identities, ...deferred } = loaded;
527 yield* cancelActiveFill;
528 const previous = yield* SubscriptionRef.get(state);
529 const snapshot = reuseUnchangedThreadShells(
530 Option.getOrNull(previous.snapshot),
531 withoutDeferredPullRequests(deferred),
532 );
533 const pendingLinkIds = new Set(
534 deferred.loadPullRequests === undefined ? [] : deferred.threads.map((thread) => thread.id),
535 );
536 yield* snapshotWriteLock.withPermit(
537 applyLocked([{ kind: "snapshot", snapshot }], identity, pendingLinkIds),
538 );
539 const current = yield* SubscriptionRef.get(state);
540 if (Option.isSome(current.snapshot)) {
541 yield* fillDeferredPullRequests(deferred, current.snapshot.value);
542 }
543 }, Effect.uninterruptible);
544
545 /**
546 * One request to the HTTP shell route. Held rows that may resume are named, so the server
547 * answers that they still can, in a few bytes, or sends the snapshot that replaces them.
548 */
549 const loadOverHttp = Effect.fn("EnvironmentShellState.loadOverHttp")(function* (
550 prepared: PreparedConnection,
551 identity: ShellOriginIdentity | null,
552 ) {
553 const held = yield* SubscriptionRef.get(state);
554 const resumeFrom =
555 Option.isSome(held.snapshot) &&
556 canResumeFrom(yield* Ref.get(origin), identity, yield* Clock.currentTimeMillis)
557 ? held.snapshot.value.snapshotSequence
558 : undefined;
559 // HTTP and the socket must agree, or omitted children would return through the socket.
560 const answer = yield* snapshotLoader.load(prepared, {
561 omitIdleSubagents: identity?.omitIdleSubagents === true,
562 omitOlderSettled: identity?.omitOlderSettled === true,
563 ...(resumeFrom === undefined ? {} : { resumeFrom }),
564 });
565 if (Option.isNone(answer)) return { kind: "failed" } satisfies HttpShellOutcome;
566 if ("resumable" in answer.value) return { kind: "resumable" } satisfies HttpShellOutcome;
567 yield* applyHttpSnapshot(answer.value, identity);
568 return {
569 kind: "snapshot",
570 projectIdentities: answer.value.projectIdentities,
571 } satisfies HttpShellOutcome;
572 });
573
574 // A server whose descriptor names its shell flags is asked for the shell as soon as the
575 // connection is prepared, while the socket opens and the config downloads. The subscription
576 // claims that load, and reloads when the live config disagrees with the descriptor.
577 const earlyLoad = yield* SynchronizedRef.make<EarlyShellLoad | null>(null);
578 const useEarlyLoad = (prepared: PreparedConnection | null, claim: boolean) =>
579 SynchronizedRef.modifyEffect(
580 earlyLoad,
581 Effect.fnUntraced(function* (current) {
582 // A rotated credential replaces the prepared connection of a session that stays up.
583 if (current !== null && prepared !== null && sameConnection(current.prepared, prepared)) {
584 const next = { ...current, prepared, claimed: current.claimed || claim };
585 // A claimed load that still runs is handed out again. A second request could
586 // answer first, and this one would then replace its rows under a passed cursor.
587 const done = current.fiber.pollUnsafe() !== undefined;
588 return [current.claimed && done ? null : current, next] as const;
589 }
590 if (current !== null) yield* Fiber.interrupt(current.fiber);
591 const identity = descriptorShellIdentity(prepared?.descriptor);
592 if (prepared === null || identity === null) return [null, null] as const;
593 // Items a closed session still has in flight must not land on the rows this loads.
594 yield* Ref.set(activeSubscription, null);
595 const fiber = yield* loadOverHttp(prepared, identity).pipe(Effect.forkIn(stateScope));
596 const next: EarlyShellLoad = { prepared, identity, fiber, claimed: claim };
597 return [next, next] as const;
598 }),
599 ).pipe(
600 // Covers the store too. A cancel that lands during the wait above would otherwise take
601 // effect before the store, and the load just started would run on with no record.
602 Effect.uninterruptible,
603 );
604 /**
605 * The subscription waits for the early load, so its answer is applied before the socket
606 * moves the rows on. Held rows that can resume wait a limited time only: after that the
607 * load is ended, so a late answer applies nothing, and the socket resumes them.
608 */
609 const awaitEarlyLoad = Effect.fnUntraced(function* (
610 early: EarlyShellLoad,
611 identity: ShellOriginIdentity | null,
612 ) {
613 const resumable =
614 Option.isSome((yield* SubscriptionRef.get(state)).snapshot) &&
615 canResumeFrom(yield* Ref.get(origin), identity, yield* Clock.currentTimeMillis);
616 if (!resumable) return yield* Fiber.await(early.fiber);
617 const answered = yield* Fiber.await(early.fiber).pipe(Effect.timeoutOption(EARLY_LOAD_GRACE));
618 if (Option.isSome(answered)) return answered.value;
619 // Returns after an answer that is being applied has finished, so the cursor below is read
620 // from rows that no longer change under it.
621 yield* Fiber.interrupt(early.fiber);
622 return yield* Fiber.await(early.fiber);
623 });
624
625 yield* SubscriptionRef.changes(supervisor.prepared).pipe(
626 // Reads the connection of this moment: a change handled late must not start a load for a
627 // connection that ended, which would also drop the items of the session that replaced it.
628 Stream.runForEach(() =>
629 SubscriptionRef.get(supervisor.prepared).pipe(
630 Effect.flatMap((prepared) => useEarlyLoad(Option.getOrNull(prepared), false)),
631 ),
632 ),
633 Effect.forkScoped,
634 );
635
636 const resubscriptions = Stream.merge(
637 Stream.fromQueue(reloadRequests),
638 Option.match(wakeups, {
639 onNone: () => Stream.never,
640 onSome: (service) =>
641 service.changes.pipe(Stream.filter(ConnectionWakeups.shouldResubscribeAfterWakeup)),
642 }),
643 );
644
645 yield* setSynchronizing;
646 yield* Effect.forkScoped(
647 subscribeDynamicWithSession(
648 ORCHESTRATION_V2_WS_METHODS.subscribeShell,
649 Effect.fn("EnvironmentShellState.makeSubscribeInput")(function* (session) {
650 const identity = yield* session.initialConfig.pipe(
651 Effect.map((config) => shellIdentity(config.environment, config)),
652 Effect.orElseSucceed(() => null),
653 );
654 const { omitIdleSubagents, omitOlderSettled } = identity ?? {
655 omitIdleSubagents: false,
656 omitOlderSettled: false,
657 };
658 const early = yield* useEarlyLoad(
659 Option.getOrNull(yield* SubscriptionRef.get(supervisor.prepared)),
660 true,
661 );
662 const earlyExit = early === null ? null : yield* awaitEarlyLoad(early, identity);
663 // Rows the descriptor's flags or build loaded are not kept when the live config differs:
664 // their origin then cannot resume, so the load below replaces them.
665 let loaded =
666 early !== null &&
667 earlyExit !== null &&
668 Exit.isSuccess(earlyExit) &&
669 identity !== null &&
670 sameShellIdentity(early.identity, identity)
671 ? earlyExit.value
672 : null;
673 yield* Ref.set(activeSubscription, { session, identity });
674 yield* Ref.set(awaitingCompletion, true);
675 yield* setSynchronizing;
676
677 // Rows from a recent server snapshot with the same omissions and server build resume
678 // from their cursor, in memory or from the cache. Anything else reloads the HTTP
679 // snapshot so a valid cursor cannot preserve stale or incomplete data. A `resumable`
680 // answer is checked again too: the rows can pass their age limit while the socket opens.
681 const resumingHeldRows =
682 loaded?.kind !== "snapshot" &&
683 Option.isSome((yield* SubscriptionRef.get(state)).snapshot) &&
684 canResumeFrom(yield* Ref.get(origin), identity, yield* Clock.currentTimeMillis);
685 if (!resumingHeldRows && loaded === null) {
686 const prepared = yield* SubscriptionRef.get(supervisor.prepared).pipe(
687 Effect.flatMap(
688 Option.match({
689 onSome: Effect.succeed,
690 onNone: () =>
691 SubscriptionRef.changes(supervisor.prepared).pipe(
692 Stream.filter(Option.isSome),
693 Stream.map((value) => value.value),
694 Stream.runHead,
695 Effect.map(Option.getOrThrow),
696 ),
697 }),
698 ),
699 );
700 loaded = yield* loadOverHttp(prepared, identity);
701 }
702
703 const current = yield* SubscriptionRef.get(state);
704 const omission = {
705 ...(omitIdleSubagents ? { omitIdleSubagents: true as const } : {}),
706 ...(omitOlderSettled ? { omitOlderSettled: true as const } : {}),
707 };
708 if (Option.isNone(current.snapshot) || !(resumingHeldRows || loaded?.kind === "snapshot")) {
709 return { ...omission, requestCompletionMarker: true as const };
710 }
711 return {
712 afterSequence: current.snapshot.value.snapshotSequence,
713 // Only rows the client already held may be refused; a cursor from the snapshot just
714 // loaded falls back to the socket snapshot, so a refusal cannot loop.
715 ...(resumingHeldRows ? { httpSnapshotFallback: true as const } : {}),
716 // No stream item has touched the snapshot just loaded, so its identities still hold.
717 ...(loaded?.kind === "snapshot" && loaded.projectIdentities !== undefined
718 ? { knownProjectIdentities: loaded.projectIdentities }
719 : {}),
720 ...omission,
721 requestCompletionMarker: true as const,
722 };
723 }),
724 {
725 // A defect parks the stream, so resubscribe after a backoff rather than wait for a wakeup.
726 onDefect: (cause) =>
727 setStreamError(Cause.squash(cause)).pipe(
728 Effect.andThen(Effect.sleep(subscriptionRetryDelay("250 millis", defectRetries++))),
729 Effect.andThen(Queue.offer(reloadRequests, undefined)),
730 ),
731 onExpectedFailure: (cause) => setStreamError(Cause.squash(cause)),
732 retryExpectedFailureAfter: "250 millis",
733 resubscribe: resubscriptions,
734 },
735 ).pipe(
736 Stream.runForEachArray((entries) =>
737 applyItems(entries).pipe(
738 Effect.andThen(
739 Effect.sync(() => {
740 defectRetries = 0;
741 }),
742 ),
743 ),
744 ),
745 ),
746 );
747 yield* SubscriptionRef.changes(supervisor.state).pipe(
748 Stream.runForEach((connectionState) => {
749 switch (connectionProjectionPhase(connectionState)) {
750 case "synchronizing":
751 return setSynchronizing;
752 case "disconnected":
753 return setDisconnected;
754 case "ready":
755 return setReady;
756 }
757 }),
758 Effect.forkScoped,
759 );
760
761 return state;
762});
763
764function shellStateChanges(environmentId: EnvironmentId) {
765 return followStreamInEnvironment(
766 environmentId,
767 Stream.unwrap(makeEnvironmentShellState().pipe(Effect.map(SubscriptionRef.changes))),
768 );
769}
770
771export interface EnvironmentShellSummary {
772 readonly hasSnapshot: boolean;
773 readonly hasSynchronizingShell: boolean;
774 readonly firstError: string | null;
775}
776
777const EMPTY_ENVIRONMENT_SHELL_SUMMARY: EnvironmentShellSummary = Object.freeze({
778 hasSnapshot: false,
779 hasSynchronizingShell: false,
780 firstError: null,
781});
782
783const EMPTY_SERVER_CONFIGS: ReadonlyMap<EnvironmentId, ServerConfig> = new Map();
784
785function shellSummariesEqual(
786 left: EnvironmentShellSummary,
787 right: EnvironmentShellSummary,
788): boolean {
789 return (
790 left.hasSnapshot === right.hasSnapshot &&
791 left.hasSynchronizingShell === right.hasSynchronizingShell &&
792 left.firstError === right.firstError
793 );
794}
795
796function mapsEqual<K, V>(left: ReadonlyMap<K, V>, right: ReadonlyMap<K, V>): boolean {
797 if (left.size !== right.size) {
798 return false;
799 }
800 for (const [key, value] of left) {
801 if (right.get(key) !== value) {
802 return false;
803 }
804 }
805 return true;
806}
807
808export function createEnvironmentShellSummaryAtom(input: {
809 readonly catalogValueAtom: Atom.Atom<EnvironmentCatalogState>;
810 readonly shellStateValueAtom: (environmentId: EnvironmentId) => Atom.Atom<EnvironmentShellState>;
811}) {
812 let previousSummary = EMPTY_ENVIRONMENT_SHELL_SUMMARY;
813 return Atom.make((get) => {
814 let hasSnapshot = false;
815 let hasSynchronizingShell = false;
816 let firstError: string | null = null;
817
818 for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
819 const state = get(input.shellStateValueAtom(environmentId));
820 hasSynchronizingShell ||= state.status === "synchronizing";
821 if (firstError === null) {
822 firstError = Option.getOrNull(state.error);
823 }
824 if (Option.isNone(state.snapshot)) {
825 continue;
826 }
827 hasSnapshot = true;
828 }
829
830 const next: EnvironmentShellSummary = {
831 hasSnapshot,
832 hasSynchronizingShell,
833 firstError,
834 };
835 if (shellSummariesEqual(previousSummary, next)) {
836 return previousSummary;
837 }
838 previousSummary = next;
839 return previousSummary;
840 }).pipe(Atom.withLabel("environment-shell-summary"));
841}
842
843export function createEnvironmentServerConfigsAtom(input: {
844 readonly catalogValueAtom: Atom.Atom<EnvironmentCatalogState>;
845 readonly serverConfigValueAtom: (environmentId: EnvironmentId) => Atom.Atom<ServerConfig | null>;
846}) {
847 let previousServerConfigs = EMPTY_SERVER_CONFIGS;
848 return Atom.make((get) => {
849 const next = new Map<EnvironmentId, ServerConfig>();
850 for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
851 const config = get(input.serverConfigValueAtom(environmentId));
852 if (config !== null) {
853 next.set(environmentId, config);
854 }
855 }
856 if (mapsEqual(previousServerConfigs, next)) {
857 return previousServerConfigs;
858 }
859 previousServerConfigs = next;
860 return previousServerConfigs;
861 }).pipe(Atom.withLabel("environment-server-configs"));
862}
863
864/**
865 * Every shell push replaces the state, so views that gate on load progress read these
866 * primitives instead and stay put while threads stream.
867 */
868function createEnvironmentShellProgressAtoms(
869 stateValueAtom: (environmentId: EnvironmentId) => Atom.Atom<EnvironmentShellState>,
870) {
871 return {
872 statusAtom: Atom.family((environmentId: EnvironmentId) =>
873 Atom.make((get) => get(stateValueAtom(environmentId)).status).pipe(
874 Atom.withLabel(`environment-shell-status:${environmentId}`),
875 ),
876 ),
877 hasSnapshotAtom: Atom.family((environmentId: EnvironmentId) =>
878 Atom.make((get) => Option.isSome(get(stateValueAtom(environmentId)).snapshot)).pipe(
879 Atom.withLabel(`environment-shell-has-snapshot:${environmentId}`),
880 ),
881 ),
882 };
883}
884
885export function createEnvironmentShellAtoms<R, E>(
886 runtime: Atom.AtomRuntime<
887 | EnvironmentRegistry.EnvironmentRegistry
888 | Persistence.EnvironmentCacheStore
889 | ShellSnapshotLoader.ShellSnapshotLoader
890 | R,
891 E
892 >,
893) {
894 const stateAtom = Atom.family((environmentId: EnvironmentId) =>
895 runtime.atom(shellStateChanges(environmentId), {
896 initialValue: EMPTY_SHELL_STATE,
897 }),
898 );
899
900 const stateValueAtom = Atom.family((environmentId: EnvironmentId) =>
901 Atom.make((get) =>
902 AsyncResult.getOrElse(get(stateAtom(environmentId)), () => EMPTY_SHELL_STATE),
903 ).pipe(Atom.withLabel(`environment-shell-state-value:${environmentId}`)),
904 );
905
906 const { statusAtom, hasSnapshotAtom } = createEnvironmentShellProgressAtoms(stateValueAtom);
907
908 return {
909 stateAtom,
910 stateValueAtom,
911 statusAtom,
912 hasSnapshotAtom,
913 };
914}
915
916export * from "./models.ts";
917export * from "./shellCommands.ts";
918export * from "./shellReducer.ts";
919export * from "./shellPullRequests.ts";
920export * as ShellSnapshotLoader from "./shellSnapshotHttp.ts";
921export * from "./snapshots.ts";
922export * from "./steadyShells.ts";