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

shell.ts

601 lines22.1 KB

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, restoreShellPullRequestStacks } 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>;
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";
61​
62function withoutDeferredPullRequests(value: DeferredShellSnapshot): OrchestrationV2ShellSnapshot {
63 if (value.loadPullRequests === undefined) return value;
64 const { loadPullRequests: _deferred, ...snapshot } = value;
65 return snapshot;
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 if (!flush) return;
126 }
127 }, persistenceLock.withPermit);
128 const persist = () => persistLatest(false);
129 const flushLiveShellSnapshot = persistLatest(true);
130​
131 // Register before scoped worker fibers so reverse finalizer order interrupts
132 // those fibers first and this flush sees a stable latestLiveSnapshot.
133 yield* Effect.addFinalizer(() => flushLiveShellSnapshot);
134​
135 yield* runCachePersistence(persistence, persist).pipe(Effect.forkScoped);
136​
137 const setDisconnected = Ref.set(awaitingCompletion, false).pipe(
138 Effect.andThen(
139 SubscriptionRef.update(state, (current) => ({
140 ...current,
141 status: shellStatusForSnapshot(current.snapshot),
142 })),
143 ),
144 Effect.andThen(flushLiveShellSnapshot.pipe(Effect.forkScoped)),
145 Effect.asVoid,
146 );
147 const setSynchronizing = SubscriptionRef.update(state, (current) => ({
148 ...current,
149 status: "synchronizing" as const,
150 error: Option.none(),
151 }));
152 const setReady = SubscriptionRef.update(state, (current) =>
153 current.status === "live"
154 ? current
155 : {
156 ...current,
157 status: "synchronizing" as const,
158 error: Option.none(),
159 },
160 );
161 const setStreamError = (error: unknown) =>
162 Ref.set(awaitingCompletion, false).pipe(
163 Effect.andThen(Effect.logWarning("Could not synchronize the environment shell.")),
164 Effect.annotateLogs({
165 environmentId,
166 ...safeErrorLogAttributes(error),
167 }),
168 Effect.andThen(
169 SubscriptionRef.update(state, (current) => ({
170 ...current,
171 status: shellStatusForSnapshot(current.snapshot),
172 error: Option.some(SHELL_SYNCHRONIZATION_ERROR_MESSAGE),
173 })),
174 ),
175 );
176​
177 // Server items and deferred link fills both read the snapshot and write it back; one at a
178 // time, so neither can overwrite what the other wrote in between.
179 const snapshotWriteLock = yield* Semaphore.make(1);
180​
181 const applyItems = Effect.fn("EnvironmentShellState.applyItems")(function* (
182 items: ReadonlyArray<OrchestrationV2ShellStreamItem>,
183 pendingLinkIds?: ReadonlySet<ThreadId>,
184 ) {
185 const initial = yield* SubscriptionRef.get(state);
186 let waiting = yield* Ref.get(awaitingCompletion);
187 let next = initial;
188 let receivedSnapshot = false;
189 for (const received of items) {
190 const item =
191 received.kind === "snapshot"
192 ? {
193 ...received,
194 snapshot: {
195 ...received.snapshot,
196 threads: received.snapshot.threads.map(restoreShellPullRequestStacks),
197 archivedThreads: received.snapshot.archivedThreads.map(
198 restoreShellPullRequestStacks,
199 ),
200 },
201 }
202 : received.kind === "thread.updated"
203 ? { ...received, thread: restoreShellPullRequestStacks(received.thread) }
204 : received;
205 if (item.kind === "synchronized") {
206 waiting = false;
207 if (Option.isSome(next.snapshot)) {
208 next = { ...next, status: "live", error: Option.none() };
209 }
210 continue;
211 }
212 const nextSnapshot =
213 item.kind === "snapshot"
214 ? mergeShellSnapshotProjects(
215 Option.getOrNull(next.snapshot),
216 item.snapshot,
217 item.resolvedRepositoryIdentityRoots === undefined
218 ? undefined
219 : {
220 resolvedRepositoryIdentityRoots: item.resolvedRepositoryIdentityRoots,
221 },
222 )
223 : Option.match(next.snapshot, {
224 onNone: () => null,
225 onSome: (snapshot) =>
226 item.sequence > snapshot.snapshotSequence
227 ? applyShellStreamEvent(snapshot, item)
228 : snapshot,
229 });
230 if (nextSnapshot === null) continue;
231 receivedSnapshot ||= item.kind === "snapshot";
232 next = {
233 snapshot: Option.some(nextSnapshot),
234 status: waiting ? "synchronizing" : "live",
235 error: Option.none(),
236 };
237 }
238 yield* Ref.set(awaitingCompletion, waiting);
239 if (next === initial) return;
240 if (pendingLinkIds !== undefined && Option.isSome(next.snapshot)) {
241 pendingLinkRows = new Set(
242 next.snapshot.value.threads.filter((thread) => pendingLinkIds.has(thread.id)),
243 );
244 }
245 if (Option.isSome(next.snapshot)) {
246 yield* Ref.set(latestLiveSnapshot, next.snapshot);
247 }
248 yield* SubscriptionRef.set(state, next);
249 if (receivedSnapshot) {
250 const session = yield* Ref.get(activeSubscriptionSession);
251 if (session !== null) {
252 yield* Ref.set(lastAuthoritativeSession, session);
253 }
254 }
255 if (next.snapshot !== initial.snapshot && Option.isSome(next.snapshot)) {
256 yield* Queue.offer(persistence, next.snapshot.value);
257 }
258 }, snapshotWriteLock.withPermit);
259​
260 const stateScope = yield* Effect.scope;
261 // Each full snapshot supersedes the previous one's fill; links from an older snapshot must
262 // not land on rows a newer snapshot reused.
263​
264 let activeFill: Fiber.Fiber<void> | undefined;
265 const cancelActiveFill = Effect.suspend(() => {
266 const fill = activeFill;
267 activeFill = undefined;
268 return fill === undefined ? Effect.void : Fiber.interrupt(fill);
269 });
270 const fillDeferredPullRequests = Effect.fnUntraced(function* (
271 source: DeferredShellSnapshot,
272 applied: OrchestrationV2ShellSnapshot,
273 ) {
274 yield* cancelActiveFill;
275 if (source.loadPullRequests === undefined) return;
276 const arrivedRows = new Set(applied.threads);
277 const arrivedIds = new Set(source.threads.map((thread) => thread.id));
278 pendingLinkRows = new Set(applied.threads.filter((thread) => arrivedIds.has(thread.id)));
279 activeFill = yield* source.loadPullRequests.pipe(
280 Effect.flatMap((linksByThreadId) =>
281 writeFilledLinks(linksByThreadId, arrivedRows, arrivedIds),
282 ),
283 Effect.forkIn(stateScope),
284 );
285 });
286 const writeFilledLinks = Effect.fnUntraced(
287 function* (
288 linksByThreadId: ReadonlyMap<ThreadId, ReadonlyArray<ThreadPullRequestLink>>,
289 arrivedRows: ReadonlySet<OrchestrationV2ThreadShell>,
290 arrivedIds: ReadonlySet<ThreadId>,
291 ) {
292 const filled = yield* SubscriptionRef.modify(
293 state,
294 (current): [Option.Option<OrchestrationV2ShellSnapshot>, EnvironmentShellState] => {
295 if (Option.isNone(current.snapshot)) return [Option.none(), current];
296 const snapshot = current.snapshot.value;
297 let changed = false;
298 const threads = snapshot.threads.map((thread) => {
299 if (!arrivedRows.has(thread) || !arrivedIds.has(thread.id)) return thread;
300 const links = linksByThreadId.get(thread.id);
301 if (sameThreadPullRequests(thread.pullRequests, links)) return thread;
302 changed = true;
303 if (links === undefined) {
304 const { pullRequests: _previous, ...row } = thread;
305 return row;
306 }
307 return { ...thread, pullRequests: links };
308 });
309 if (!changed) return [Option.none(), current];
310 const next = { ...snapshot, threads };
311 return [Option.some(next), { ...current, snapshot: Option.some(next) }];
312 },
313 );
314 pendingLinkRows = new Set();
315 const live = yield* Ref.get(latestLiveSnapshot);
316 if (Option.isNone(live)) return;
317 const latest = Option.isSome(filled) ? filled : live;
318 yield* Ref.set(latestLiveSnapshot, latest);
319 yield* Queue.offer(persistence, latest.value);
320 },
321 (effect) => snapshotWriteLock.withPermit(effect),
322 );
323 if (Option.isSome(cached) && Option.isSome(cachedSnapshot)) {
324 yield* fillDeferredPullRequests(cached.value, cachedSnapshot.value);
325 }
326​
327 const foregroundResubscriptions = Option.match(wakeups, {
328 onNone: () => Stream.never,
329 onSome: (service) =>
330 service.changes.pipe(Stream.filter(ConnectionWakeups.shouldResubscribeAfterWakeup)),
331 });
332​
333 yield* setSynchronizing;
334 yield* Effect.forkScoped(
335 subscribeDynamic(
336 ORCHESTRATION_V2_WS_METHODS.subscribeShell,
337 Effect.fn("EnvironmentShellState.makeSubscribeInput")(function* (session) {
338 yield* Ref.set(activeSubscriptionSession, session);
339 const supportsCompletionMarker = yield* session.initialConfig.pipe(
340 Effect.map((config) => config.shellResumeCompletionMarker === true),
341 Effect.orElseSucceed(() => false),
342 );
343 yield* Ref.set(awaitingCompletion, supportsCompletionMarker);
344 yield* setSynchronizing;
345​
346 // Foreground resubscriptions on the same live session can resume from
347 // the in-memory cursor. A new session reloads the authoritative HTTP
348 // snapshot so a valid cursor cannot preserve incomplete cached data.
349 const hasAuthoritativeSnapshot = (yield* Ref.get(lastAuthoritativeSession)) === session;
350 let canResume = hasAuthoritativeSnapshot;
351 let current = yield* SubscriptionRef.get(state);
352 if (!hasAuthoritativeSnapshot || Option.isNone(current.snapshot)) {
353 const prepared = yield* SubscriptionRef.get(supervisor.prepared).pipe(
354 Effect.flatMap(
355 Option.match({
356 onSome: Effect.succeed,
357 onNone: () =>
358 SubscriptionRef.changes(supervisor.prepared).pipe(
359 Stream.filter(Option.isSome),
360 Stream.map((value) => value.value),
361 Stream.runHead,
362 Effect.map(Option.getOrThrow),
363 ),
364 }),
365 ),
366 );
367 const httpSnapshot = yield* snapshotLoader.load(prepared);
368 if (Option.isSome(httpSnapshot)) {
369 yield* cancelActiveFill;
370 const previous = yield* SubscriptionRef.get(state);
371 const snapshot = reuseUnchangedThreadShells(
372 Option.getOrNull(previous.snapshot),
373 withoutDeferredPullRequests(httpSnapshot.value),
374 );
375 const pendingLinkIds = new Set(
376 httpSnapshot.value.loadPullRequests === undefined
377 ? []
378 : httpSnapshot.value.threads.map((thread) => thread.id),
379 );
380 yield* applyItems([{ kind: "snapshot", snapshot }], pendingLinkIds);
381 canResume = true;
382 current = yield* SubscriptionRef.get(state);
383 if (Option.isSome(current.snapshot)) {
384 yield* fillDeferredPullRequests(httpSnapshot.value, current.snapshot.value);
385 }
386 }
387 }
388​
389 if (!canResume || Option.isNone(current.snapshot)) {
390 return {
391 compactPullRequests: true,
392 ...(supportsCompletionMarker ? { requestCompletionMarker: true as const } : {}),
393 };
394 }
395 if (!supportsCompletionMarker) {
396 yield* SubscriptionRef.update(state, (value) => ({
397 ...value,
398 status: "live" as const,
399 error: Option.none(),
400 }));
401 }
402 return {
403 afterSequence: current.snapshot.value.snapshotSequence,
404 compactPullRequests: true,
405 ...(supportsCompletionMarker ? { requestCompletionMarker: true as const } : {}),
406 };
407 }),
408 {
409 onExpectedFailure: (cause) => setStreamError(Cause.squash(cause)),
410 retryExpectedFailureAfter: "250 millis",
411 resubscribe: foregroundResubscriptions,
412 },
413 ).pipe(Stream.runForEachArray((items) => applyItems(items))),
414 );
415 yield* SubscriptionRef.changes(supervisor.state).pipe(
416 Stream.runForEach((connectionState) => {
417 switch (connectionProjectionPhase(connectionState)) {
418 case "synchronizing":
419 return setSynchronizing;
420 case "disconnected":
421 return setDisconnected;
422 case "ready":
423 return setReady;
424 }
425 }),
426 Effect.forkScoped,
427 );
428​
429 return state;
430});
431​
432function shellStateChanges(environmentId: EnvironmentId) {
433 return followStreamInEnvironment(
434 environmentId,
435 Stream.unwrap(makeEnvironmentShellState().pipe(Effect.map(SubscriptionRef.changes))),
436 );
438​
439export interface EnvironmentShellSummary {
440 readonly hasSnapshot: boolean;
441 readonly hasSynchronizingShell: boolean;
442 readonly hasCachedShell: boolean;
443 readonly hasLiveShell: boolean;
444 readonly firstError: string | null;
446​
447const EMPTY_ENVIRONMENT_SHELL_SUMMARY: EnvironmentShellSummary = Object.freeze({
448 hasSnapshot: false,
449 hasSynchronizingShell: false,
450 hasCachedShell: false,
451 hasLiveShell: false,
452 firstError: null,
453});
454​
455const EMPTY_SERVER_CONFIGS: ReadonlyMap<EnvironmentId, ServerConfig> = new Map();
456​
457function shellSummariesEqual(
458 left: EnvironmentShellSummary,
459 right: EnvironmentShellSummary,
460): boolean {
461 return (
462 left.hasSnapshot === right.hasSnapshot &&
463 left.hasSynchronizingShell === right.hasSynchronizingShell &&
464 left.hasCachedShell === right.hasCachedShell &&
465 left.hasLiveShell === right.hasLiveShell &&
466 left.firstError === right.firstError
467 );
469​
470function mapsEqual<K, V>(left: ReadonlyMap<K, V>, right: ReadonlyMap<K, V>): boolean {
471 if (left.size !== right.size) {
472 return false;
473 }
474 for (const [key, value] of left) {
475 if (right.get(key) !== value) {
476 return false;
477 }
478 }
479 return true;
481​
482export function createEnvironmentShellSummaryAtom(input: {
483 readonly catalogValueAtom: Atom.Atom<EnvironmentCatalogState>;
484 readonly shellStateValueAtom: (environmentId: EnvironmentId) => Atom.Atom<EnvironmentShellState>;
485}) {
486 let previousSummary = EMPTY_ENVIRONMENT_SHELL_SUMMARY;
487 return Atom.make((get) => {
488 let hasSnapshot = false;
489 let hasSynchronizingShell = false;
490 let hasCachedShell = false;
491 let hasLiveShell = false;
492 let firstError: string | null = null;
493​
494 for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
495 const state = get(input.shellStateValueAtom(environmentId));
496 hasSynchronizingShell ||= state.status === "synchronizing";
497 hasCachedShell ||= state.status === "cached";
498 hasLiveShell ||= state.status === "live";
499 if (firstError === null) {
500 firstError = Option.getOrNull(state.error);
501 }
502 if (Option.isNone(state.snapshot)) {
503 continue;
504 }
505 hasSnapshot = true;
506 }
507​
508 const next: EnvironmentShellSummary = {
509 hasSnapshot,
510 hasSynchronizingShell,
511 hasCachedShell,
512 hasLiveShell,
513 firstError,
514 };
515 if (shellSummariesEqual(previousSummary, next)) {
516 return previousSummary;
517 }
518 previousSummary = next;
519 return previousSummary;
520 }).pipe(Atom.withLabel("environment-shell-summary"));
522​
523export function createEnvironmentServerConfigsAtom(input: {
524 readonly catalogValueAtom: Atom.Atom<EnvironmentCatalogState>;
525 readonly serverConfigValueAtom: (environmentId: EnvironmentId) => Atom.Atom<ServerConfig | null>;
526}) {
527 let previousServerConfigs = EMPTY_SERVER_CONFIGS;
528 return Atom.make((get) => {
529 const next = new Map<EnvironmentId, ServerConfig>();
530 for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
531 const config = get(input.serverConfigValueAtom(environmentId));
532 if (config !== null) {
533 next.set(environmentId, config);
534 }
535 }
536 if (mapsEqual(previousServerConfigs, next)) {
537 return previousServerConfigs;
538 }
539 previousServerConfigs = next;
540 return previousServerConfigs;
541 }).pipe(Atom.withLabel("environment-server-configs"));
543​
544/**
545 * Every shell push replaces the state, so views that gate on load progress read these
546 * primitives instead and stay put while threads stream.
547 */
548export function createEnvironmentShellProgressAtoms(
549 stateValueAtom: (environmentId: EnvironmentId) => Atom.Atom<EnvironmentShellState>,
550) {
551 return {
552 statusAtom: Atom.family((environmentId: EnvironmentId) =>
553 Atom.make((get) => get(stateValueAtom(environmentId)).status).pipe(
554 Atom.withLabel(`environment-shell-status:${environmentId}`),
555 ),
556 ),
557 hasSnapshotAtom: Atom.family((environmentId: EnvironmentId) =>
558 Atom.make((get) => Option.isSome(get(stateValueAtom(environmentId)).snapshot)).pipe(
559 Atom.withLabel(`environment-shell-has-snapshot:${environmentId}`),
560 ),
561 ),
562 };
564​
565export function createEnvironmentShellAtoms<R, E>(
566 runtime: Atom.AtomRuntime<
567 | EnvironmentRegistry.EnvironmentRegistry
568 | Persistence.EnvironmentCacheStore
569 | ShellSnapshotLoader.ShellSnapshotLoader
570 | R,
571 E
572 >,
573) {
574 const stateAtom = Atom.family((environmentId: EnvironmentId) =>
575 runtime.atom(shellStateChanges(environmentId), {
576 initialValue: EMPTY_SHELL_STATE,
577 }),
578 );
579​
580 const stateValueAtom = Atom.family((environmentId: EnvironmentId) =>
581 Atom.make((get) =>
582 Option.getOrElse(AsyncResult.value(get(stateAtom(environmentId))), () => EMPTY_SHELL_STATE),
583 ).pipe(Atom.withLabel(`environment-shell-state-value:${environmentId}`)),
584 );
585​
586 const { statusAtom, hasSnapshotAtom } = createEnvironmentShellProgressAtoms(stateValueAtom);
587​
588 return {
589 stateAtom,
590 stateValueAtom,
591 statusAtom,
592 hasSnapshotAtom,
593 };
595​
596export * from "./models.ts";
597export * from "./shellCommands.ts";
598export * from "./shellReducer.ts";
599export * from "./shellPullRequests.ts";
600export * as ShellSnapshotLoader from "./shellSnapshotHttp.ts";
601export * from "./snapshots.ts";