Open History to see the last commit
1import {
2 ORCHESTRATION_V2_WS_METHODS,
3 type EnvironmentId,
4 type OrchestrationV2ShellSnapshot,
5 type OrchestrationV2ShellStreamItem,
6 type ServerConfig,
7} from "@t3tools/contracts";
8import * as Cause from "effect/Cause";
9import * as DateTime from "effect/DateTime";
10import * as Effect from "effect/Effect";
11import * as Option from "effect/Option";
12import * as Queue from "effect/Queue";
13import * as Ref from "effect/Ref";
14import * as Stream from "effect/Stream";
15import * as SubscriptionRef from "effect/SubscriptionRef";
16import { AsyncResult, Atom } from "effect/unstable/reactivity";
17
18import { EnvironmentRegistry } from "../connection/registry.ts";
19import { connectionProjectionPhase } from "../connection/model.ts";
20import { EnvironmentSupervisor } from "../connection/supervisor.ts";
21import * as ConnectionWakeups from "../connection/wakeups.ts";
22import { safeErrorLogAttributes } from "../errors/safeLog.ts";
23import { EnvironmentCacheStore } from "../platform/persistence.ts";
24import { subscribeDynamic } from "../rpc/client.ts";
25import type { RpcSession } from "../rpc/session.ts";
26import { ShellSnapshotLoader } from "./shellSnapshotHttp.ts";
27import { applyShellStreamEvent, mergeShellSnapshotProjects } from "./shellReducer.ts";
28import type { EnvironmentCatalogState } from "./connections.ts";
29import { followStreamInEnvironment } from "./runtime.ts";
30
31export type EnvironmentShellStatus = "empty" | "cached" | "synchronizing" | "live";
32
33export interface EnvironmentShellState {
34 readonly snapshot: Option.Option<OrchestrationV2ShellSnapshot>;
35 readonly status: EnvironmentShellStatus;
36 readonly error: Option.Option<string>;
37}
38
39const EMPTY_SHELL_STATE: EnvironmentShellState = {
40 snapshot: Option.none(),
41 status: "empty",
42 error: Option.none(),
43};
44
45function shellStatusForSnapshot(
46 snapshot: Option.Option<OrchestrationV2ShellSnapshot>,
47): EnvironmentShellStatus {
48 return Option.isSome(snapshot) ? "cached" : "empty";
49}
50
51const SHELL_SYNCHRONIZATION_ERROR_MESSAGE = "Could not synchronize environment data.";
52
53export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")(function* () {
54 const supervisor = yield* EnvironmentSupervisor;
55 const cache = yield* EnvironmentCacheStore;
56 const snapshotLoader = yield* ShellSnapshotLoader;
57 const wakeups = yield* Effect.serviceOption(ConnectionWakeups.ConnectionWakeups);
58 const environmentId = supervisor.target.environmentId;
59 const cachedSnapshot = yield* cache.loadShell(environmentId).pipe(
60 Effect.catch((error) =>
61 Effect.logWarning("Could not load cached environment shell.").pipe(
62 Effect.annotateLogs({
63 environmentId,
64 ...safeErrorLogAttributes(error),
65 }),
66 Effect.as(Option.none<OrchestrationV2ShellSnapshot>()),
67 ),
68 ),
69 );
70 const state = yield* SubscriptionRef.make<EnvironmentShellState>({
71 snapshot: cachedSnapshot,
72 status: shellStatusForSnapshot(cachedSnapshot),
73 error: Option.none(),
74 });
75 const awaitingCompletion = yield* Ref.make(false);
76 const lastAuthoritativeSession = yield* Ref.make<RpcSession | null>(null);
77 const activeSubscriptionSession = yield* Ref.make<RpcSession | null>(null);
78 const latestLiveSnapshot = yield* Ref.make<Option.Option<OrchestrationV2ShellSnapshot>>(
79 Option.none(),
80 );
81 const persistence = yield* Queue.sliding<OrchestrationV2ShellSnapshot>(1);
82
83 const persist = Effect.fn("EnvironmentShellState.persist")(function* (
84 snapshot: OrchestrationV2ShellSnapshot,
85 ) {
86 let nextSnapshot = snapshot;
87 while (true) {
88 yield* cache.saveShell(environmentId, nextSnapshot).pipe(
89 Effect.catch((error) =>
90 Effect.logWarning("Could not persist environment shell cache.").pipe(
91 Effect.annotateLogs({
92 environmentId,
93 ...safeErrorLogAttributes(error),
94 }),
95 ),
96 ),
97 );
98
99 const latestSnapshot = yield* Ref.get(latestLiveSnapshot);
100 // Same sequence can still mean newer content (e.g. repository enrichment).
101 if (Option.isNone(latestSnapshot) || latestSnapshot.value === nextSnapshot) {
102 return;
103 }
104 nextSnapshot = latestSnapshot.value;
105 }
106 });
107
108 const flushLiveShellSnapshot = Effect.gen(function* () {
109 const snapshot = yield* Ref.get(latestLiveSnapshot);
110 if (Option.isNone(snapshot)) {
111 return;
112 }
113 yield* persist(snapshot.value);
114 });
115
116 // Register before scoped worker fibers so reverse finalizer order interrupts
117 // those fibers first and this flush sees a stable latestLiveSnapshot.
118 yield* Effect.addFinalizer(() => flushLiveShellSnapshot);
119
120 yield* Stream.fromQueue(persistence).pipe(
121 Stream.debounce("500 millis"),
122 Stream.runForEach(persist),
123 Effect.forkScoped,
124 );
125
126 const setDisconnected = Ref.set(awaitingCompletion, false).pipe(
127 Effect.andThen(
128 SubscriptionRef.update(state, (current) => ({
129 ...current,
130 status: shellStatusForSnapshot(current.snapshot),
131 })),
132 ),
133 Effect.andThen(flushLiveShellSnapshot.pipe(Effect.forkScoped)),
134 Effect.asVoid,
135 );
136 const setSynchronizing = SubscriptionRef.update(state, (current) => ({
137 ...current,
138 status: "synchronizing" as const,
139 error: Option.none(),
140 }));
141 const setReady = SubscriptionRef.update(state, (current) =>
142 current.status === "live"
143 ? current
144 : {
145 ...current,
146 status: "synchronizing" as const,
147 error: Option.none(),
148 },
149 );
150 const setStreamError = (error: unknown) =>
151 Ref.set(awaitingCompletion, false).pipe(
152 Effect.andThen(Effect.logWarning("Could not synchronize the environment shell.")),
153 Effect.annotateLogs({
154 environmentId,
155 ...safeErrorLogAttributes(error),
156 }),
157 Effect.andThen(
158 SubscriptionRef.update(state, (current) => ({
159 ...current,
160 status: shellStatusForSnapshot(current.snapshot),
161 error: Option.some(SHELL_SYNCHRONIZATION_ERROR_MESSAGE),
162 })),
163 ),
164 );
165
166 const applyItem = Effect.fn("EnvironmentShellState.applyItem")(function* (
167 item: OrchestrationV2ShellStreamItem,
168 ) {
169 if (item.kind === "synchronized") {
170 yield* Ref.set(awaitingCompletion, false);
171 yield* SubscriptionRef.update(state, (current) =>
172 Option.isSome(current.snapshot)
173 ? { ...current, status: "live" as const, error: Option.none() }
174 : current,
175 );
176 return;
177 }
178
179 const current = yield* SubscriptionRef.get(state);
180 const nextSnapshot =
181 item.kind === "snapshot"
182 ? mergeShellSnapshotProjects(
183 Option.getOrNull(current.snapshot),
184 item.snapshot,
185 item.resolvedRepositoryIdentityRoots === undefined
186 ? undefined
187 : {
188 resolvedRepositoryIdentityRoots: item.resolvedRepositoryIdentityRoots,
189 },
190 )
191 : Option.match(current.snapshot, {
192 onNone: () => null,
193 onSome: (snapshot) =>
194 item.sequence > snapshot.snapshotSequence
195 ? applyShellStreamEvent(snapshot, item)
196 : snapshot,
197 });
198 if (nextSnapshot === null) {
199 return;
200 }
201
202 yield* Ref.set(latestLiveSnapshot, Option.some(nextSnapshot));
203 const waiting = yield* Ref.get(awaitingCompletion);
204 yield* SubscriptionRef.set(state, {
205 snapshot: Option.some(nextSnapshot),
206 status: waiting ? "synchronizing" : "live",
207 error: Option.none(),
208 });
209 if (item.kind === "snapshot") {
210 const session = yield* Ref.get(activeSubscriptionSession);
211 if (session !== null) {
212 yield* Ref.set(lastAuthoritativeSession, session);
213 }
214 }
215 yield* Queue.offer(persistence, nextSnapshot);
216 });
217
218 const foregroundResubscriptions = Option.match(wakeups, {
219 onNone: () => Stream.never,
220 onSome: (service) =>
221 service.changes.pipe(Stream.filter(ConnectionWakeups.shouldResubscribeAfterWakeup)),
222 });
223
224 yield* setSynchronizing;
225 yield* Effect.forkScoped(
226 subscribeDynamic(
227 ORCHESTRATION_V2_WS_METHODS.subscribeShell,
228 Effect.fn("EnvironmentShellState.makeSubscribeInput")(function* (session) {
229 yield* Ref.set(activeSubscriptionSession, session);
230 const supportsCompletionMarker = yield* session.initialConfig.pipe(
231 Effect.map((config) => config.shellResumeCompletionMarker === true),
232 Effect.orElseSucceed(() => false),
233 );
234 yield* Ref.set(awaitingCompletion, supportsCompletionMarker);
235 yield* setSynchronizing;
236
237 // Foreground resubscriptions on the same live session can resume from
238 // the in-memory cursor. A new session reloads the authoritative HTTP
239 // snapshot so a valid cursor cannot preserve incomplete cached data.
240 const hasAuthoritativeSnapshot = (yield* Ref.get(lastAuthoritativeSession)) === session;
241 let canResume = hasAuthoritativeSnapshot;
242 let current = yield* SubscriptionRef.get(state);
243 if (!hasAuthoritativeSnapshot || Option.isNone(current.snapshot)) {
244 const prepared = yield* SubscriptionRef.get(supervisor.prepared).pipe(
245 Effect.flatMap(
246 Option.match({
247 onSome: Effect.succeed,
248 onNone: () =>
249 SubscriptionRef.changes(supervisor.prepared).pipe(
250 Stream.filter(Option.isSome),
251 Stream.map((value) => value.value),
252 Stream.runHead,
253 Effect.map(Option.getOrThrow),
254 ),
255 }),
256 ),
257 );
258 const httpSnapshot = yield* snapshotLoader.load(prepared);
259 if (Option.isSome(httpSnapshot)) {
260 yield* applyItem({ kind: "snapshot", snapshot: httpSnapshot.value });
261 canResume = true;
262 current = yield* SubscriptionRef.get(state);
263 }
264 }
265
266 // If the authoritative refresh failed, omit the cached cursor so the
267 // socket fallback sends a complete snapshot for this new session.
268 if (!canResume || Option.isNone(current.snapshot)) {
269 return supportsCompletionMarker ? { requestCompletionMarker: true as const } : {};
270 }
271 if (!supportsCompletionMarker) {
272 // Without a completion marker there is no synchronized signal for a
273 // resumed subscription, so report live immediately, like threads.
274 yield* SubscriptionRef.update(state, (value) => ({
275 ...value,
276 status: "live" as const,
277 error: Option.none(),
278 }));
279 }
280 return {
281 afterSequence: current.snapshot.value.snapshotSequence,
282 ...(supportsCompletionMarker ? { requestCompletionMarker: true as const } : {}),
283 };
284 }),
285 {
286 onExpectedFailure: (cause) => setStreamError(Cause.squash(cause)),
287 retryExpectedFailureAfter: "250 millis",
288 resubscribe: foregroundResubscriptions,
289 },
290 ).pipe(Stream.runForEach(applyItem)),
291 );
292 yield* SubscriptionRef.changes(supervisor.state).pipe(
293 Stream.runForEach((connectionState) => {
294 switch (connectionProjectionPhase(connectionState)) {
295 case "synchronizing":
296 return setSynchronizing;
297 case "disconnected":
298 return setDisconnected;
299 case "ready":
300 return setReady;
301 }
302 }),
303 Effect.forkScoped,
304 );
305
306 return state;
307});
308
309export function shellStateChanges(environmentId: EnvironmentId) {
310 return followStreamInEnvironment(
311 environmentId,
312 Stream.unwrap(makeEnvironmentShellState().pipe(Effect.map(SubscriptionRef.changes))),
313 );
314}
315
316export interface EnvironmentShellSummary {
317 readonly hasSnapshot: boolean;
318 readonly hasSynchronizingShell: boolean;
319 readonly hasCachedShell: boolean;
320 readonly hasLiveShell: boolean;
321 readonly firstError: string | null;
322 readonly latestSnapshotUpdatedAt: string | null;
323}
324
325const EMPTY_ENVIRONMENT_SHELL_SUMMARY: EnvironmentShellSummary = Object.freeze({
326 hasSnapshot: false,
327 hasSynchronizingShell: false,
328 hasCachedShell: false,
329 hasLiveShell: false,
330 firstError: null,
331 latestSnapshotUpdatedAt: null,
332});
333
334const EMPTY_SERVER_CONFIGS: ReadonlyMap<EnvironmentId, ServerConfig> = new Map();
335
336function shellSummariesEqual(
337 left: EnvironmentShellSummary,
338 right: EnvironmentShellSummary,
339): boolean {
340 return (
341 left.hasSnapshot === right.hasSnapshot &&
342 left.hasSynchronizingShell === right.hasSynchronizingShell &&
343 left.hasCachedShell === right.hasCachedShell &&
344 left.hasLiveShell === right.hasLiveShell &&
345 left.firstError === right.firstError &&
346 left.latestSnapshotUpdatedAt === right.latestSnapshotUpdatedAt
347 );
348}
349
350function mapsEqual<K, V>(left: ReadonlyMap<K, V>, right: ReadonlyMap<K, V>): boolean {
351 if (left.size !== right.size) {
352 return false;
353 }
354 for (const [key, value] of left) {
355 if (right.get(key) !== value) {
356 return false;
357 }
358 }
359 return true;
360}
361
362export function createEnvironmentShellSummaryAtom(input: {
363 readonly catalogValueAtom: Atom.Atom<EnvironmentCatalogState>;
364 readonly shellStateValueAtom: (environmentId: EnvironmentId) => Atom.Atom<EnvironmentShellState>;
365}) {
366 let previousSummary = EMPTY_ENVIRONMENT_SHELL_SUMMARY;
367 return Atom.make((get) => {
368 let hasSnapshot = false;
369 let hasSynchronizingShell = false;
370 let hasCachedShell = false;
371 let hasLiveShell = false;
372 let firstError: string | null = null;
373 let latestSnapshotUpdatedAt: string | null = null;
374
375 for (const environmentId of get(input.catalogValueAtom).entries.keys()) {
376 const state = get(input.shellStateValueAtom(environmentId));
377 hasSynchronizingShell ||= state.status === "synchronizing";
378 hasCachedShell ||= state.status === "cached";
379 hasLiveShell ||= state.status === "live";
380 if (firstError === null) {
381 firstError = Option.getOrNull(state.error);
382 }
383 if (Option.isNone(state.snapshot)) {
384 continue;
385 }
386 hasSnapshot = true;
387 const snapshot = state.snapshot.value;
388 const updatedAt = snapshot.threads.concat(snapshot.archivedThreads).reduce<string | null>(
389 (latest, thread) => {
390 const value = DateTime.formatIso(thread.updatedAt);
391 return latest === null || value > latest ? value : latest;
392 },
393 snapshot.projects.reduce<string | null>((latest, project) => {
394 return latest === null || project.updatedAt > latest ? project.updatedAt : latest;
395 }, null),
396 );
397 if (
398 updatedAt !== null &&
399 (latestSnapshotUpdatedAt === null || updatedAt > latestSnapshotUpdatedAt)
400 ) {
401 latestSnapshotUpdatedAt = updatedAt;
402 }
403 }
404
405 const next: EnvironmentShellSummary = {
406 hasSnapshot,
407 hasSynchronizingShell,
408 hasCachedShell,
409 hasLiveShell,
410 firstError,
411 latestSnapshotUpdatedAt,
412 };
413 if (shellSummariesEqual(previousSummary, next)) {
414 return previousSummary;
415 }
416 previousSummary = next;
417 return previousSummary;
418 }).pipe(Atom.withLabel("environment-shell-summary"));
419}
420
421export function createEnvironmentServerConfigsAtom(input: {
422 readonly catalogValueAtom: Atom.Atom<EnvironmentCatalogState>;
423 readonly serverConfigValueAtom: (environmentId: EnvironmentId) => Atom.Atom<ServerConfig | null>;
424}) {
425 let previousServerConfigs = EMPTY_SERVER_CONFIGS;
426 return Atom.make((get) => {
427 const next = new Map<EnvironmentId, ServerConfig>();
428 for (const environmentId of get(input.catalogValueAtom).entries.keys()) {
429 const config = get(input.serverConfigValueAtom(environmentId));
430 if (config !== null) {
431 next.set(environmentId, config);
432 }
433 }
434 if (mapsEqual(previousServerConfigs, next)) {
435 return previousServerConfigs;
436 }
437 previousServerConfigs = next;
438 return previousServerConfigs;
439 }).pipe(Atom.withLabel("environment-server-configs"));
440}
441
442export function createEnvironmentShellAtoms<R, E>(
443 runtime: Atom.AtomRuntime<
444 EnvironmentRegistry | EnvironmentCacheStore | ShellSnapshotLoader | R,
445 E
446 >,
447) {
448 const stateAtom = Atom.family((environmentId: EnvironmentId) =>
449 runtime.atom(shellStateChanges(environmentId), {
450 initialValue: EMPTY_SHELL_STATE,
451 }),
452 );
453
454 const stateValueAtom = Atom.family((environmentId: EnvironmentId) =>
455 Atom.make((get) =>
456 Option.getOrElse(AsyncResult.value(get(stateAtom(environmentId))), () => EMPTY_SHELL_STATE),
457 ).pipe(Atom.withLabel(`environment-shell-state-value:${environmentId}`)),
458 );
459
460 return {
461 stateAtom,
462 stateValueAtom,
463 };
464}
465
466export * from "./models.ts";
467export * from "./shellCommands.ts";
468export * from "./shellReducer.ts";
469export * from "./shellSnapshotHttp.ts";
470export * from "./snapshots.ts";