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