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

shell.ts

903 lines36.0 KB

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