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