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

shell.ts

479 lines17.0 KB

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, enabledEnvironmentIds } 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>;
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";
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 // Apply each received batch with one state write. The RPC client's bounded
167 // buffer can split a server chunk, so a bulk action can still need several
168 // writes, but each write includes every event in that batch.
169 const applyItems = Effect.fn("EnvironmentShellState.applyItems")(function* (
170 items: ReadonlyArray<OrchestrationV2ShellStreamItem>,
171 ) {
172 const initial = yield* SubscriptionRef.get(state);
173 let waiting = yield* Ref.get(awaitingCompletion);
174 let next = initial;
175 let receivedSnapshot = false;
176 for (const item of items) {
177 if (item.kind === "synchronized") {
178 waiting = false;
179 if (Option.isSome(next.snapshot)) {
180 next = { ...next, status: "live", error: Option.none() };
181 }
182 continue;
183 }
184 const nextSnapshot =
185 item.kind === "snapshot"
186 ? mergeShellSnapshotProjects(
187 Option.getOrNull(next.snapshot),
188 item.snapshot,
189 item.resolvedRepositoryIdentityRoots === undefined
190 ? undefined
191 : {
192 resolvedRepositoryIdentityRoots: item.resolvedRepositoryIdentityRoots,
193 },
194 )
195 : Option.match(next.snapshot, {
196 onNone: () => null,
197 onSome: (snapshot) =>
198 item.sequence > snapshot.snapshotSequence
199 ? applyShellStreamEvent(snapshot, item)
200 : snapshot,
201 });
202 if (nextSnapshot === null) continue;
203 receivedSnapshot ||= item.kind === "snapshot";
204 next = {
205 snapshot: Option.some(nextSnapshot),
206 status: waiting ? "synchronizing" : "live",
207 error: Option.none(),
208 };
209 }
210 yield* Ref.set(awaitingCompletion, waiting);
211 if (next === initial) return;
212 if (Option.isSome(next.snapshot)) {
213 yield* Ref.set(latestLiveSnapshot, next.snapshot);
214 }
215 yield* SubscriptionRef.set(state, next);
216 if (receivedSnapshot) {
217 const session = yield* Ref.get(activeSubscriptionSession);
218 if (session !== null) {
219 yield* Ref.set(lastAuthoritativeSession, session);
220 }
221 }
222 if (next.snapshot !== initial.snapshot && Option.isSome(next.snapshot)) {
223 yield* Queue.offer(persistence, next.snapshot.value);
224 }
225 });
226​
227 const foregroundResubscriptions = Option.match(wakeups, {
228 onNone: () => Stream.never,
229 onSome: (service) =>
230 service.changes.pipe(Stream.filter(ConnectionWakeups.shouldResubscribeAfterWakeup)),
231 });
232​
233 yield* setSynchronizing;
234 yield* Effect.forkScoped(
235 subscribeDynamic(
236 ORCHESTRATION_V2_WS_METHODS.subscribeShell,
237 Effect.fn("EnvironmentShellState.makeSubscribeInput")(function* (session) {
238 yield* Ref.set(activeSubscriptionSession, session);
239 const supportsCompletionMarker = yield* session.initialConfig.pipe(
240 Effect.map((config) => config.shellResumeCompletionMarker === true),
241 Effect.orElseSucceed(() => false),
242 );
243 yield* Ref.set(awaitingCompletion, supportsCompletionMarker);
244 yield* setSynchronizing;
245​
246 // Foreground resubscriptions on the same live session can resume from
247 // the in-memory cursor. A new session reloads the authoritative HTTP
248 // snapshot so a valid cursor cannot preserve incomplete cached data.
249 const hasAuthoritativeSnapshot = (yield* Ref.get(lastAuthoritativeSession)) === session;
250 let canResume = hasAuthoritativeSnapshot;
251 let current = yield* SubscriptionRef.get(state);
252 if (!hasAuthoritativeSnapshot || Option.isNone(current.snapshot)) {
253 const prepared = yield* SubscriptionRef.get(supervisor.prepared).pipe(
254 Effect.flatMap(
255 Option.match({
256 onSome: Effect.succeed,
257 onNone: () =>
258 SubscriptionRef.changes(supervisor.prepared).pipe(
259 Stream.filter(Option.isSome),
260 Stream.map((value) => value.value),
261 Stream.runHead,
262 Effect.map(Option.getOrThrow),
263 ),
264 }),
265 ),
266 );
267 const httpSnapshot = yield* snapshotLoader.load(prepared);
268 if (Option.isSome(httpSnapshot)) {
269 yield* applyItems([{ kind: "snapshot", snapshot: httpSnapshot.value }]);
270 canResume = true;
271 current = yield* SubscriptionRef.get(state);
272 }
273 }
274​
275 // If the authoritative refresh failed, omit the cached cursor so the
276 // socket fallback sends a complete snapshot for this new session.
277 if (!canResume || Option.isNone(current.snapshot)) {
278 return supportsCompletionMarker ? { requestCompletionMarker: true as const } : {};
279 }
280 if (!supportsCompletionMarker) {
281 // Without a completion marker there is no synchronized signal for a
282 // resumed subscription, so report live immediately, like threads.
283 yield* SubscriptionRef.update(state, (value) => ({
284 ...value,
285 status: "live" as const,
286 error: Option.none(),
287 }));
288 }
289 return {
290 afterSequence: current.snapshot.value.snapshotSequence,
291 ...(supportsCompletionMarker ? { requestCompletionMarker: true as const } : {}),
292 };
293 }),
294 {
295 onExpectedFailure: (cause) => setStreamError(Cause.squash(cause)),
296 retryExpectedFailureAfter: "250 millis",
297 resubscribe: foregroundResubscriptions,
298 },
299 ).pipe(Stream.runForEachArray(applyItems)),
300 );
301 yield* SubscriptionRef.changes(supervisor.state).pipe(
302 Stream.runForEach((connectionState) => {
303 switch (connectionProjectionPhase(connectionState)) {
304 case "synchronizing":
305 return setSynchronizing;
306 case "disconnected":
307 return setDisconnected;
308 case "ready":
309 return setReady;
310 }
311 }),
312 Effect.forkScoped,
313 );
314​
315 return state;
316});
317​
318function shellStateChanges(environmentId: EnvironmentId) {
319 return followStreamInEnvironment(
320 environmentId,
321 Stream.unwrap(makeEnvironmentShellState().pipe(Effect.map(SubscriptionRef.changes))),
322 );
324​
325export interface EnvironmentShellSummary {
326 readonly hasSnapshot: boolean;
327 readonly hasSynchronizingShell: boolean;
328 readonly hasCachedShell: boolean;
329 readonly hasLiveShell: boolean;
330 readonly firstError: string | null;
331 readonly latestSnapshotUpdatedAt: string | null;
333​
334const EMPTY_ENVIRONMENT_SHELL_SUMMARY: EnvironmentShellSummary = Object.freeze({
335 hasSnapshot: false,
336 hasSynchronizingShell: false,
337 hasCachedShell: false,
338 hasLiveShell: false,
339 firstError: null,
340 latestSnapshotUpdatedAt: null,
341});
342​
343const EMPTY_SERVER_CONFIGS: ReadonlyMap<EnvironmentId, ServerConfig> = new Map();
344​
345function shellSummariesEqual(
346 left: EnvironmentShellSummary,
347 right: EnvironmentShellSummary,
348): boolean {
349 return (
350 left.hasSnapshot === right.hasSnapshot &&
351 left.hasSynchronizingShell === right.hasSynchronizingShell &&
352 left.hasCachedShell === right.hasCachedShell &&
353 left.hasLiveShell === right.hasLiveShell &&
354 left.firstError === right.firstError &&
355 left.latestSnapshotUpdatedAt === right.latestSnapshotUpdatedAt
356 );
358​
359function mapsEqual<K, V>(left: ReadonlyMap<K, V>, right: ReadonlyMap<K, V>): boolean {
360 if (left.size !== right.size) {
361 return false;
362 }
363 for (const [key, value] of left) {
364 if (right.get(key) !== value) {
365 return false;
366 }
367 }
368 return true;
370​
371export function createEnvironmentShellSummaryAtom(input: {
372 readonly catalogValueAtom: Atom.Atom<EnvironmentCatalogState>;
373 readonly shellStateValueAtom: (environmentId: EnvironmentId) => Atom.Atom<EnvironmentShellState>;
374}) {
375 let previousSummary = EMPTY_ENVIRONMENT_SHELL_SUMMARY;
376 return Atom.make((get) => {
377 let hasSnapshot = false;
378 let hasSynchronizingShell = false;
379 let hasCachedShell = false;
380 let hasLiveShell = false;
381 let firstError: string | null = null;
382 let latestSnapshotUpdatedAt: string | null = null;
383​
384 for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
385 const state = get(input.shellStateValueAtom(environmentId));
386 hasSynchronizingShell ||= state.status === "synchronizing";
387 hasCachedShell ||= state.status === "cached";
388 hasLiveShell ||= state.status === "live";
389 if (firstError === null) {
390 firstError = Option.getOrNull(state.error);
391 }
392 if (Option.isNone(state.snapshot)) {
393 continue;
394 }
395 hasSnapshot = true;
396 const snapshot = state.snapshot.value;
397 const updatedAt = snapshot.threads.concat(snapshot.archivedThreads).reduce<string | null>(
398 (latest, thread) => {
399 const value = DateTime.formatIso(thread.updatedAt);
400 return latest === null || value > latest ? value : latest;
401 },
402 snapshot.projects.reduce<string | null>((latest, project) => {
403 return latest === null || project.updatedAt > latest ? project.updatedAt : latest;
404 }, null),
405 );
406 if (
407 updatedAt !== null &&
408 (latestSnapshotUpdatedAt === null || updatedAt > latestSnapshotUpdatedAt)
409 ) {
410 latestSnapshotUpdatedAt = updatedAt;
411 }
412 }
413​
414 const next: EnvironmentShellSummary = {
415 hasSnapshot,
416 hasSynchronizingShell,
417 hasCachedShell,
418 hasLiveShell,
419 firstError,
420 latestSnapshotUpdatedAt,
421 };
422 if (shellSummariesEqual(previousSummary, next)) {
423 return previousSummary;
424 }
425 previousSummary = next;
426 return previousSummary;
427 }).pipe(Atom.withLabel("environment-shell-summary"));
429​
430export function createEnvironmentServerConfigsAtom(input: {
431 readonly catalogValueAtom: Atom.Atom<EnvironmentCatalogState>;
432 readonly serverConfigValueAtom: (environmentId: EnvironmentId) => Atom.Atom<ServerConfig | null>;
433}) {
434 let previousServerConfigs = EMPTY_SERVER_CONFIGS;
435 return Atom.make((get) => {
436 const next = new Map<EnvironmentId, ServerConfig>();
437 for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) {
438 const config = get(input.serverConfigValueAtom(environmentId));
439 if (config !== null) {
440 next.set(environmentId, config);
441 }
442 }
443 if (mapsEqual(previousServerConfigs, next)) {
444 return previousServerConfigs;
445 }
446 previousServerConfigs = next;
447 return previousServerConfigs;
448 }).pipe(Atom.withLabel("environment-server-configs"));
450​
451export function createEnvironmentShellAtoms<R, E>(
452 runtime: Atom.AtomRuntime<
453 EnvironmentRegistry | EnvironmentCacheStore | ShellSnapshotLoader | R,
454 E
455 >,
456) {
457 const stateAtom = Atom.family((environmentId: EnvironmentId) =>
458 runtime.atom(shellStateChanges(environmentId), {
459 initialValue: EMPTY_SHELL_STATE,
460 }),
461 );
462​
463 const stateValueAtom = Atom.family((environmentId: EnvironmentId) =>
464 Atom.make((get) =>
465 Option.getOrElse(AsyncResult.value(get(stateAtom(environmentId))), () => EMPTY_SHELL_STATE),
466 ).pipe(Atom.withLabel(`environment-shell-state-value:${environmentId}`)),
467 );
468​
469 return {
470 stateAtom,
471 stateValueAtom,
472 };
474​
475export * from "./models.ts";
476export * from "./shellCommands.ts";
477export * from "./shellReducer.ts";
478export * from "./shellSnapshotHttp.ts";
479export * from "./snapshots.ts";