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

shell.ts

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