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

shell.ts

387 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) => service.changes.pipe(Stream.filter(ConnectionWakeups.wakeupResubscribes)),
175 });
176​
177 yield* setSynchronizing;
178 yield* Effect.forkScoped(
179 subscribeDynamic(
180 ORCHESTRATION_WS_METHODS.subscribeShell,
181 Effect.fn("EnvironmentShellState.makeSubscribeInput")(function* (session) {
182 const supportsCompletionMarker = yield* session.initialConfig.pipe(
183 Effect.map((config) => config.shellResumeCompletionMarker === true),
184 Effect.orElseSucceed(() => false),
185 );
186 yield* Ref.set(awaitingCompletion, supportsCompletionMarker);
187 yield* setSynchronizing;
188​
189 const prepared = yield* SubscriptionRef.get(supervisor.prepared).pipe(
190 Effect.flatMap(
191 Option.match({
192 onSome: Effect.succeed,
193 onNone: () =>
194 SubscriptionRef.changes(supervisor.prepared).pipe(
195 Stream.filter(Option.isSome),
196 Stream.map((value) => value.value),
197 Stream.runHead,
198 Effect.map(Option.getOrThrow),
199 ),
200 }),
201 ),
202 );
203 const httpSnapshot = yield* snapshotLoader.load(prepared);
204 if (Option.isSome(httpSnapshot)) {
205 yield* applyItem({ kind: "snapshot", snapshot: httpSnapshot.value });
206 return {
207 afterSequence: httpSnapshot.value.snapshotSequence,
208 ...(supportsCompletionMarker ? { requestCompletionMarker: true as const } : {}),
209 };
210 }
211​
212 return supportsCompletionMarker ? { requestCompletionMarker: true as const } : {};
213 }),
214 {
215 onExpectedFailure: (cause) => setStreamError(Cause.squash(cause)),
216 retryExpectedFailureAfter: "250 millis",
217 resubscribe: foregroundResubscriptions,
218 },
219 ).pipe(Stream.runForEach(applyItem)),
220 );
221 yield* SubscriptionRef.changes(supervisor.state).pipe(
222 Stream.runForEach((connectionState) => {
223 switch (connectionProjectionPhase(connectionState)) {
224 case "synchronizing":
225 return setSynchronizing;
226 case "disconnected":
227 return setDisconnected;
228 case "ready":
229 return setReady;
230 }
231 }),
232 Effect.forkScoped,
233 );
234​
235 return state;
236});
237​
238export function shellStateChanges(environmentId: EnvironmentId) {
239 return followStreamInEnvironment(
240 environmentId,
241 Stream.unwrap(makeEnvironmentShellState().pipe(Effect.map(SubscriptionRef.changes))),
242 );
244​
245export interface EnvironmentShellSummary {
246 readonly hasSnapshot: boolean;
247 readonly hasSynchronizingShell: boolean;
248 readonly hasCachedShell: boolean;
249 readonly hasLiveShell: boolean;
250 readonly firstError: string | null;
251 readonly latestSnapshotUpdatedAt: string | null;
253​
254const EMPTY_ENVIRONMENT_SHELL_SUMMARY: EnvironmentShellSummary = Object.freeze({
255 hasSnapshot: false,
256 hasSynchronizingShell: false,
257 hasCachedShell: false,
258 hasLiveShell: false,
259 firstError: null,
260 latestSnapshotUpdatedAt: null,
261});
262​
263const EMPTY_SERVER_CONFIGS: ReadonlyMap<EnvironmentId, ServerConfig> = new Map();
264​
265function shellSummariesEqual(
266 left: EnvironmentShellSummary,
267 right: EnvironmentShellSummary,
268): boolean {
269 return (
270 left.hasSnapshot === right.hasSnapshot &&
271 left.hasSynchronizingShell === right.hasSynchronizingShell &&
272 left.hasCachedShell === right.hasCachedShell &&
273 left.hasLiveShell === right.hasLiveShell &&
274 left.firstError === right.firstError &&
275 left.latestSnapshotUpdatedAt === right.latestSnapshotUpdatedAt
276 );
278​
279function mapsEqual<K, V>(left: ReadonlyMap<K, V>, right: ReadonlyMap<K, V>): boolean {
280 if (left.size !== right.size) {
281 return false;
282 }
283 for (const [key, value] of left) {
284 if (right.get(key) !== value) {
285 return false;
286 }
287 }
288 return true;
290​
291export function createEnvironmentShellSummaryAtom(input: {
292 readonly catalogValueAtom: Atom.Atom<EnvironmentCatalogState>;
293 readonly shellStateValueAtom: (environmentId: EnvironmentId) => Atom.Atom<EnvironmentShellState>;
294}) {
295 let previousSummary = EMPTY_ENVIRONMENT_SHELL_SUMMARY;
296 return Atom.make((get) => {
297 let hasSnapshot = false;
298 let hasSynchronizingShell = false;
299 let hasCachedShell = false;
300 let hasLiveShell = false;
301 let firstError: string | null = null;
302 let latestSnapshotUpdatedAt: string | null = null;
303​
304 for (const environmentId of get(input.catalogValueAtom).entries.keys()) {
305 const state = get(input.shellStateValueAtom(environmentId));
306 hasSynchronizingShell ||= state.status === "synchronizing";
307 hasCachedShell ||= state.status === "cached";
308 hasLiveShell ||= state.status === "live";
309 if (firstError === null) {
310 firstError = Option.getOrNull(state.error);
311 }
312 if (Option.isNone(state.snapshot)) {
313 continue;
314 }
315 hasSnapshot = true;
316 const updatedAt = state.snapshot.value.updatedAt;
317 if (latestSnapshotUpdatedAt === null || updatedAt > latestSnapshotUpdatedAt) {
318 latestSnapshotUpdatedAt = updatedAt;
319 }
320 }
321​
322 const next: EnvironmentShellSummary = {
323 hasSnapshot,
324 hasSynchronizingShell,
325 hasCachedShell,
326 hasLiveShell,
327 firstError,
328 latestSnapshotUpdatedAt,
329 };
330 if (shellSummariesEqual(previousSummary, next)) {
331 return previousSummary;
332 }
333 previousSummary = next;
334 return previousSummary;
335 }).pipe(Atom.withLabel("environment-shell-summary"));
337​
338export function createEnvironmentServerConfigsAtom(input: {
339 readonly catalogValueAtom: Atom.Atom<EnvironmentCatalogState>;
340 readonly serverConfigValueAtom: (environmentId: EnvironmentId) => Atom.Atom<ServerConfig | null>;
341}) {
342 let previousServerConfigs = EMPTY_SERVER_CONFIGS;
343 return Atom.make((get) => {
344 const next = new Map<EnvironmentId, ServerConfig>();
345 for (const environmentId of get(input.catalogValueAtom).entries.keys()) {
346 const config = get(input.serverConfigValueAtom(environmentId));
347 if (config !== null) {
348 next.set(environmentId, config);
349 }
350 }
351 if (mapsEqual(previousServerConfigs, next)) {
352 return previousServerConfigs;
353 }
354 previousServerConfigs = next;
355 return previousServerConfigs;
356 }).pipe(Atom.withLabel("environment-server-configs"));
358​
359export function createEnvironmentShellAtoms<R, E>(
360 runtime: Atom.AtomRuntime<
361 EnvironmentRegistry | EnvironmentCacheStore | ShellSnapshotLoader | R,
362 E
363 >,
364) {
365 const stateAtom = Atom.family((environmentId: EnvironmentId) =>
366 runtime.atom(shellStateChanges(environmentId), {
367 initialValue: EMPTY_SHELL_STATE,
368 }),
369 );
370​
371 const stateValueAtom = Atom.family((environmentId: EnvironmentId) =>
372 Atom.make((get) =>
373 Option.getOrElse(AsyncResult.value(get(stateAtom(environmentId))), () => EMPTY_SHELL_STATE),
374 ).pipe(Atom.withLabel(`environment-shell-state-value:${environmentId}`)),
375 );
376​
377 return {
378 stateAtom,
379 stateValueAtom,
380 };
382​
383export * from "./models.ts";
384export * from "./shellCommands.ts";
385export * from "./shellReducer.ts";
386export * from "./shellSnapshotHttp.ts";
387export * from "./snapshots.ts";