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

shell.ts

388 lines12.8 KB

1import {
2 ORCHESTRATION_WS_METHODS,
3 type EnvironmentId,
4 type OrchestrationShellSnapshot,
5 type OrchestrationShellStreamItem,
6 type ServerConfig,
7} from "@t3tools/contracts";
8import * as Cause from "effect/Cause";
9import * as Effect from "effect/Effect";
10import * as Option from "effect/Option";
11import * as Queue from "effect/Queue";
12import * as Ref from "effect/Ref";
13import * as Stream from "effect/Stream";
14import * as SubscriptionRef from "effect/SubscriptionRef";
15import { AsyncResult, Atom } from "effect/unstable/reactivity";
16​
17import { EnvironmentRegistry } from "../connection/registry.ts";
18import { connectionProjectionPhase } from "../connection/model.ts";
19import { EnvironmentSupervisor } from "../connection/supervisor.ts";
20import * as ConnectionWakeups from "../connection/wakeups.ts";
21import { safeErrorLogAttributes } from "../errors/safeLog.ts";
22import { EnvironmentCacheStore } from "../platform/persistence.ts";
23import { subscribeDynamic } from "../rpc/client.ts";
24import { ShellSnapshotLoader } from "./shellSnapshotHttp.ts";
25import { applyShellStreamEvent } from "./shellReducer.ts";
26import type { EnvironmentCatalogState } from "./connections.ts";
27import { followStreamInEnvironment } from "./runtime.ts";
28​
29export type EnvironmentShellStatus = "empty" | "cached" | "synchronizing" | "live";
30​
31export interface EnvironmentShellState {
32 readonly snapshot: Option.Option<OrchestrationShellSnapshot>;
33 readonly status: EnvironmentShellStatus;
34 readonly error: Option.Option<string>;
36​
37const EMPTY_SHELL_STATE: EnvironmentShellState = {
38 snapshot: Option.none(),
39 status: "empty",
40 error: Option.none(),
41};
42​
43function shellStatusForSnapshot(
44 snapshot: Option.Option<OrchestrationShellSnapshot>,
45): EnvironmentShellStatus {
46 return Option.isSome(snapshot) ? "cached" : "empty";
48​
49const SHELL_SYNCHRONIZATION_ERROR_MESSAGE = "Could not synchronize environment data.";
50​
51export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")(function* () {
52 const supervisor = yield* EnvironmentSupervisor;
53 const cache = yield* EnvironmentCacheStore;
54 const snapshotLoader = yield* ShellSnapshotLoader;
55 const wakeups = yield* Effect.serviceOption(ConnectionWakeups.ConnectionWakeups);
56 const environmentId = supervisor.target.environmentId;
57 const cachedSnapshot = yield* cache.loadShell(environmentId).pipe(
58 Effect.catch((error) =>
59 Effect.logWarning("Could not load cached environment shell.").pipe(
60 Effect.annotateLogs({
61 environmentId,
62 ...safeErrorLogAttributes(error),
63 }),
64 Effect.as(Option.none<OrchestrationShellSnapshot>()),
65 ),
66 ),
67 );
68 const state = yield* SubscriptionRef.make<EnvironmentShellState>({
69 snapshot: cachedSnapshot,
70 status: shellStatusForSnapshot(cachedSnapshot),
71 error: Option.none(),
72 });
73 const awaitingCompletion = yield* Ref.make(false);
74 const persistence = yield* Queue.sliding<OrchestrationShellSnapshot>(1);
75​
76 const persist = Effect.fn("EnvironmentShellState.persist")(function* (
77 snapshot: OrchestrationShellSnapshot,
78 ) {
79 yield* cache.saveShell(environmentId, snapshot).pipe(
80 Effect.catch((error) =>
81 Effect.logWarning("Could not persist environment shell cache.").pipe(
82 Effect.annotateLogs({
83 environmentId,
84 ...safeErrorLogAttributes(error),
85 }),
86 ),
87 ),
88 );
89 });
90​
91 yield* Stream.fromQueue(persistence).pipe(
92 Stream.debounce("500 millis"),
93 Stream.runForEach(persist),
94 Effect.forkScoped,
95 );
96​
97 const setDisconnected = Ref.set(awaitingCompletion, false).pipe(
98 Effect.andThen(
99 SubscriptionRef.update(state, (current) => ({
100 ...current,
101 status: shellStatusForSnapshot(current.snapshot),
102 })),
103 ),
104 );
105 const setSynchronizing = SubscriptionRef.update(state, (current) => ({
106 ...current,
107 status: "synchronizing" as const,
108 error: Option.none(),
109 }));
110 const setReady = SubscriptionRef.update(state, (current) =>
111 current.status === "live"
112 ? current
113 : {
114 ...current,
115 status: "synchronizing" as const,
116 error: Option.none(),
117 },
118 );
119 const setStreamError = (error: unknown) =>
120 Ref.set(awaitingCompletion, false).pipe(
121 Effect.andThen(Effect.logWarning("Could not synchronize the environment shell.")),
122 Effect.annotateLogs({
123 environmentId,
124 ...safeErrorLogAttributes(error),
125 }),
126 Effect.andThen(
127 SubscriptionRef.update(state, (current) => ({
128 ...current,
129 status: shellStatusForSnapshot(current.snapshot),
130 error: Option.some(SHELL_SYNCHRONIZATION_ERROR_MESSAGE),
131 })),
132 ),
133 );
134​
135 const applyItem = Effect.fn("EnvironmentShellState.applyItem")(function* (
136 item: OrchestrationShellStreamItem,
137 ) {
138 if (item.kind === "synchronized") {
139 yield* Ref.set(awaitingCompletion, false);
140 yield* SubscriptionRef.update(state, (current) =>
141 Option.isSome(current.snapshot)
142 ? { ...current, status: "live" as const, error: Option.none() }
143 : current,
144 );
145 return;
146 }
147​
148 const current = yield* SubscriptionRef.get(state);
149 const nextSnapshot =
150 item.kind === "snapshot"
151 ? item.snapshot
152 : Option.match(current.snapshot, {
153 onNone: () => null,
154 onSome: (snapshot) =>
155 item.sequence > snapshot.snapshotSequence
156 ? applyShellStreamEvent(snapshot, item)
157 : snapshot,
158 });
159 if (nextSnapshot === null) {
160 return;
161 }
162​
163 const waiting = yield* Ref.get(awaitingCompletion);
164 yield* SubscriptionRef.set(state, {
165 snapshot: Option.some(nextSnapshot),
166 status: waiting ? "synchronizing" : "live",
167 error: Option.none(),
168 });
169 yield* Queue.offer(persistence, nextSnapshot);
170 });
171​
172 const foregroundResubscriptions = Option.match(wakeups, {
173 onNone: () => Stream.never,
174 onSome: (service) =>
175 service.changes.pipe(Stream.filter(ConnectionWakeups.shouldResubscribeAfterWakeup)),
176 });
177​
178 yield* setSynchronizing;
179 yield* Effect.forkScoped(
180 subscribeDynamic(
181 ORCHESTRATION_WS_METHODS.subscribeShell,
182 Effect.fn("EnvironmentShellState.makeSubscribeInput")(function* (session) {
183 const supportsCompletionMarker = yield* session.initialConfig.pipe(
184 Effect.map((config) => config.shellResumeCompletionMarker === true),
185 Effect.orElseSucceed(() => false),
186 );
187 yield* Ref.set(awaitingCompletion, supportsCompletionMarker);
188 yield* setSynchronizing;
189​
190 const prepared = yield* SubscriptionRef.get(supervisor.prepared).pipe(
191 Effect.flatMap(
192 Option.match({
193 onSome: Effect.succeed,
194 onNone: () =>
195 SubscriptionRef.changes(supervisor.prepared).pipe(
196 Stream.filter(Option.isSome),
197 Stream.map((value) => value.value),
198 Stream.runHead,
199 Effect.map(Option.getOrThrow),
200 ),
201 }),
202 ),
203 );
204 const httpSnapshot = yield* snapshotLoader.load(prepared);
205 if (Option.isSome(httpSnapshot)) {
206 yield* applyItem({ kind: "snapshot", snapshot: httpSnapshot.value });
207 return {
208 afterSequence: httpSnapshot.value.snapshotSequence,
209 ...(supportsCompletionMarker ? { requestCompletionMarker: true as const } : {}),
210 };
211 }
212​
213 return supportsCompletionMarker ? { requestCompletionMarker: true as const } : {};
214 }),
215 {
216 onExpectedFailure: (cause) => setStreamError(Cause.squash(cause)),
217 retryExpectedFailureAfter: "250 millis",
218 resubscribe: foregroundResubscriptions,
219 },
220 ).pipe(Stream.runForEach(applyItem)),
221 );
222 yield* SubscriptionRef.changes(supervisor.state).pipe(
223 Stream.runForEach((connectionState) => {
224 switch (connectionProjectionPhase(connectionState)) {
225 case "synchronizing":
226 return setSynchronizing;
227 case "disconnected":
228 return setDisconnected;
229 case "ready":
230 return setReady;
231 }
232 }),
233 Effect.forkScoped,
234 );
235​
236 return state;
237});
238​
239export function shellStateChanges(environmentId: EnvironmentId) {
240 return followStreamInEnvironment(
241 environmentId,
242 Stream.unwrap(makeEnvironmentShellState().pipe(Effect.map(SubscriptionRef.changes))),
243 );
245​
246export interface EnvironmentShellSummary {
247 readonly hasSnapshot: boolean;
248 readonly hasSynchronizingShell: boolean;
249 readonly hasCachedShell: boolean;
250 readonly hasLiveShell: boolean;
251 readonly firstError: string | null;
252 readonly latestSnapshotUpdatedAt: string | null;
254​
255const EMPTY_ENVIRONMENT_SHELL_SUMMARY: EnvironmentShellSummary = Object.freeze({
256 hasSnapshot: false,
257 hasSynchronizingShell: false,
258 hasCachedShell: false,
259 hasLiveShell: false,
260 firstError: null,
261 latestSnapshotUpdatedAt: null,
262});
263​
264const EMPTY_SERVER_CONFIGS: ReadonlyMap<EnvironmentId, ServerConfig> = new Map();
265​
266function shellSummariesEqual(
267 left: EnvironmentShellSummary,
268 right: EnvironmentShellSummary,
269): boolean {
270 return (
271 left.hasSnapshot === right.hasSnapshot &&
272 left.hasSynchronizingShell === right.hasSynchronizingShell &&
273 left.hasCachedShell === right.hasCachedShell &&
274 left.hasLiveShell === right.hasLiveShell &&
275 left.firstError === right.firstError &&
276 left.latestSnapshotUpdatedAt === right.latestSnapshotUpdatedAt
277 );
279​
280function mapsEqual<K, V>(left: ReadonlyMap<K, V>, right: ReadonlyMap<K, V>): boolean {
281 if (left.size !== right.size) {
282 return false;
283 }
284 for (const [key, value] of left) {
285 if (right.get(key) !== value) {
286 return false;
287 }
288 }
289 return true;
291​
292export function createEnvironmentShellSummaryAtom(input: {
293 readonly catalogValueAtom: Atom.Atom<EnvironmentCatalogState>;
294 readonly shellStateValueAtom: (environmentId: EnvironmentId) => Atom.Atom<EnvironmentShellState>;
295}) {
296 let previousSummary = EMPTY_ENVIRONMENT_SHELL_SUMMARY;
297 return Atom.make((get) => {
298 let hasSnapshot = false;
299 let hasSynchronizingShell = false;
300 let hasCachedShell = false;
301 let hasLiveShell = false;
302 let firstError: string | null = null;
303 let latestSnapshotUpdatedAt: string | null = null;
304​
305 for (const environmentId of get(input.catalogValueAtom).entries.keys()) {
306 const state = get(input.shellStateValueAtom(environmentId));
307 hasSynchronizingShell ||= state.status === "synchronizing";
308 hasCachedShell ||= state.status === "cached";
309 hasLiveShell ||= state.status === "live";
310 if (firstError === null) {
311 firstError = Option.getOrNull(state.error);
312 }
313 if (Option.isNone(state.snapshot)) {
314 continue;
315 }
316 hasSnapshot = true;
317 const updatedAt = state.snapshot.value.updatedAt;
318 if (latestSnapshotUpdatedAt === null || updatedAt > latestSnapshotUpdatedAt) {
319 latestSnapshotUpdatedAt = updatedAt;
320 }
321 }
322​
323 const next: EnvironmentShellSummary = {
324 hasSnapshot,
325 hasSynchronizingShell,
326 hasCachedShell,
327 hasLiveShell,
328 firstError,
329 latestSnapshotUpdatedAt,
330 };
331 if (shellSummariesEqual(previousSummary, next)) {
332 return previousSummary;
333 }
334 previousSummary = next;
335 return previousSummary;
336 }).pipe(Atom.withLabel("environment-shell-summary"));
338​
339export function createEnvironmentServerConfigsAtom(input: {
340 readonly catalogValueAtom: Atom.Atom<EnvironmentCatalogState>;
341 readonly serverConfigValueAtom: (environmentId: EnvironmentId) => Atom.Atom<ServerConfig | null>;
342}) {
343 let previousServerConfigs = EMPTY_SERVER_CONFIGS;
344 return Atom.make((get) => {
345 const next = new Map<EnvironmentId, ServerConfig>();
346 for (const environmentId of get(input.catalogValueAtom).entries.keys()) {
347 const config = get(input.serverConfigValueAtom(environmentId));
348 if (config !== null) {
349 next.set(environmentId, config);
350 }
351 }
352 if (mapsEqual(previousServerConfigs, next)) {
353 return previousServerConfigs;
354 }
355 previousServerConfigs = next;
356 return previousServerConfigs;
357 }).pipe(Atom.withLabel("environment-server-configs"));
359​
360export function createEnvironmentShellAtoms<R, E>(
361 runtime: Atom.AtomRuntime<
362 EnvironmentRegistry | EnvironmentCacheStore | ShellSnapshotLoader | R,
363 E
364 >,
365) {
366 const stateAtom = Atom.family((environmentId: EnvironmentId) =>
367 runtime.atom(shellStateChanges(environmentId), {
368 initialValue: EMPTY_SHELL_STATE,
369 }),
370 );
371​
372 const stateValueAtom = Atom.family((environmentId: EnvironmentId) =>
373 Atom.make((get) =>
374 Option.getOrElse(AsyncResult.value(get(stateAtom(environmentId))), () => EMPTY_SHELL_STATE),
375 ).pipe(Atom.withLabel(`environment-shell-state-value:${environmentId}`)),
376 );
377​
378 return {
379 stateAtom,
380 stateValueAtom,
381 };
383​
384export * from "./models.ts";
385export * from "./shellCommands.ts";
386export * from "./shellReducer.ts";
387export * from "./shellSnapshotHttp.ts";
388export * from "./snapshots.ts";