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

shell-sync.test.ts

365 lines14.8 KB

1import {
2 EnvironmentId,
3 ORCHESTRATION_WS_METHODS,
4 type OrchestrationShellSnapshot,
5 type OrchestrationShellStreamItem,
6} from "@t3tools/contracts";
7import { describe, expect, it } from "@effect/vitest";
8import * as Effect from "effect/Effect";
9import * as Option from "effect/Option";
10import * as Queue from "effect/Queue";
11import * as Ref from "effect/Ref";
12import * as Stream from "effect/Stream";
13import * as SubscriptionRef from "effect/SubscriptionRef";
14​
15import {
16 AVAILABLE_CONNECTION_STATE,
17 PrimaryConnectionTarget,
18 type PreparedConnection,
19} from "../connection/model.ts";
20import * as EnvironmentSupervisor from "../connection/supervisor.ts";
21import * as ConnectionWakeups from "../connection/wakeups.ts";
22import * as Persistence from "../platform/persistence.ts";
23import * as RpcSession from "../rpc/session.ts";
24import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
25import { makeEnvironmentShellState, ShellSnapshotLoader } from "./shell.ts";
26​
27const TARGET = new PrimaryConnectionTarget({
28 environmentId: EnvironmentId.make("environment-1"),
29 label: "Test environment",
30 httpBaseUrl: "https://environment.example.test",
31 wsBaseUrl: "wss://environment.example.test",
32});
33​
34const PREPARED: PreparedConnection = {
35 environmentId: TARGET.environmentId,
36 label: TARGET.label,
37 httpBaseUrl: TARGET.httpBaseUrl,
38 socketUrl: TARGET.wsBaseUrl,
39 httpAuthorization: null,
40 target: TARGET,
41};
42​
43const LIVE_SHELL_SNAPSHOT: OrchestrationShellSnapshot = {
44 snapshotSequence: 1,
45 projects: [],
46 threads: [],
47 updatedAt: "2026-06-06T00:00:00.000Z",
48};
49​
50function session(client: WsRpcProtocolClient): RpcSession.RpcSession {
51 return {
52 client,
53 initialConfig: Effect.succeed({ shellResumeCompletionMarker: true } as never),
54 subscribeServerConfig: (input) => client.subscribeServerConfig(input),
55 ready: Effect.void,
56 probe: Effect.void,
57 closed: Effect.never,
58 };
60​
61describe("environment shell synchronization", () => {
62 it.effect("publishes live state before persistence and preserves it when ready", () =>
63 Effect.gen(function* () {
64 const events = yield* Queue.unbounded<OrchestrationShellStreamItem>();
65 const client = {
66 [ORCHESTRATION_WS_METHODS.subscribeShell]: () => Stream.fromQueue(events),
67 } as unknown as WsRpcProtocolClient;
68 const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
69 const activeSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
70 Option.some(session(client)),
71 );
72 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
73 target: TARGET,
74 state: supervisorState,
75 session: activeSession,
76 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
77 connect: Effect.void,
78 disconnect: Effect.void,
79 retryNow: Effect.void,
80 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
81 const cache = Persistence.EnvironmentCacheStore.of({
82 loadShell: () => Effect.succeed(Option.none()),
83 saveShell: () => Effect.never,
84 loadThread: () => Effect.succeed(Option.none()),
85 saveThread: () => Effect.void,
86 removeThread: () => Effect.void,
87 loadServerConfig: () => Effect.succeed(Option.none()),
88 saveServerConfig: () => Effect.void,
89 loadVcsRefs: () => Effect.succeed(Option.none()),
90 saveVcsRefs: () => Effect.void,
91 removeVcsRefs: () => Effect.void,
92 clearVcsRefs: () => Effect.void,
93 clear: () => Effect.void,
94 });
95 // Cold cache with no HTTP snapshot available → falls back to the
96 // socket-embedded snapshot.
97 const snapshotLoader = ShellSnapshotLoader.of({
98 load: () => Effect.succeed(Option.none()),
99 });
100 const shellState = yield* makeEnvironmentShellState().pipe(
101 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
102 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
103 Effect.provideService(ShellSnapshotLoader, snapshotLoader),
104 );
105​
106 yield* SubscriptionRef.set(supervisorState, {
107 desired: true,
108 network: "online",
109 phase: "connecting",
110 stage: "synchronizing",
111 attempt: 1,
112 generation: 0,
113 lastFailure: null,
114 retryAt: null,
115 });
116 yield* Queue.offer(events, {
117 kind: "snapshot",
118 snapshot: LIVE_SHELL_SNAPSHOT,
119 });
120 const synchronizing = yield* SubscriptionRef.changes(shellState).pipe(
121 Stream.filter((state) => state.status === "synchronizing" && Option.isSome(state.snapshot)),
122 Stream.runHead,
123 );
124 expect(Option.getOrThrow(Option.getOrThrow(synchronizing).snapshot)).toEqual(
125 LIVE_SHELL_SNAPSHOT,
126 );
127​
128 yield* Queue.offer(events, { kind: "synchronized" });
129 yield* SubscriptionRef.changes(shellState).pipe(
130 Stream.filter((state) => state.status === "live"),
131 Stream.runHead,
132 );
133​
134 yield* SubscriptionRef.set(supervisorState, {
135 desired: true,
136 network: "online",
137 phase: "connected",
138 stage: null,
139 attempt: 1,
140 generation: 1,
141 lastFailure: null,
142 retryAt: null,
143 });
144 for (let index = 0; index < 10; index += 1) {
145 yield* Effect.yieldNow;
146 }
147​
148 const state = yield* SubscriptionRef.get(shellState);
149 expect(state.status).toBe("live");
150 expect(Option.getOrThrow(state.snapshot)).toEqual(LIVE_SHELL_SNAPSHOT);
151 }),
152 );
153​
154 it.effect("requests a full socket snapshot when the HTTP refresh fails", () =>
155 Effect.gen(function* () {
156 const cachedSnapshot: OrchestrationShellSnapshot = {
157 snapshotSequence: 5,
158 projects: [],
159 threads: [{ id: "cached-thread" } as never],
160 updatedAt: "2026-06-06T00:00:00.000Z",
161 };
162 const resetSnapshot: OrchestrationShellSnapshot = {
163 ...cachedSnapshot,
164 snapshotSequence: 9_999,
165 threads: [],
166 updatedAt: "2026-06-07T00:00:00.000Z",
167 };
168 const events = yield* Queue.unbounded<OrchestrationShellStreamItem>();
169 const wakeups = yield* Queue.unbounded<ConnectionWakeups.ConnectionWakeup>();
170 const subscribeInputs = yield* Queue.unbounded<{
171 readonly afterSequence?: number;
172 readonly requestCompletionMarker?: boolean;
173 }>();
174 const loaderCalls = yield* Ref.make(0);
175 const client = {
176 [ORCHESTRATION_WS_METHODS.subscribeShell]: (input: {
177 readonly afterSequence?: number;
178 readonly requestCompletionMarker?: boolean;
179 }) =>
180 Stream.unwrap(
181 Queue.offer(subscribeInputs, input).pipe(Effect.as(Stream.fromQueue(events))),
182 ),
183 } as unknown as WsRpcProtocolClient;
184 const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
185 const activeSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
186 Option.some(session(client)),
187 );
188 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
189 target: TARGET,
190 state: supervisorState,
191 session: activeSession,
192 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
193 connect: Effect.void,
194 disconnect: Effect.void,
195 retryNow: Effect.void,
196 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
197 const cache = Persistence.EnvironmentCacheStore.of({
198 loadShell: () => Effect.succeed(Option.some(cachedSnapshot)),
199 saveShell: () => Effect.void,
200 loadThread: () => Effect.succeed(Option.none()),
201 saveThread: () => Effect.void,
202 removeThread: () => Effect.void,
203 loadServerConfig: () => Effect.succeed(Option.none()),
204 saveServerConfig: () => Effect.void,
205 loadVcsRefs: () => Effect.succeed(Option.none()),
206 saveVcsRefs: () => Effect.void,
207 removeVcsRefs: () => Effect.void,
208 clearVcsRefs: () => Effect.void,
209 clear: () => Effect.void,
210 });
211 const snapshotLoader = ShellSnapshotLoader.of({
212 load: () => Ref.update(loaderCalls, (count) => count + 1).pipe(Effect.as(Option.none())),
213 });
214 const shellState = yield* makeEnvironmentShellState().pipe(
215 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
216 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
217 Effect.provideService(ShellSnapshotLoader, snapshotLoader),
218 Effect.provideService(
219 ConnectionWakeups.ConnectionWakeups,
220 ConnectionWakeups.ConnectionWakeups.of({ changes: Stream.fromQueue(wakeups) }),
221 ),
222 );
223​
224 const subscribeInput = yield* Queue.take(subscribeInputs);
225 expect(subscribeInput.afterSequence).toBeUndefined();
226 expect(subscribeInput.requestCompletionMarker).toBe(true);
227 expect(yield* Ref.get(loaderCalls)).toBe(1);
228 const synchronizing = yield* SubscriptionRef.get(shellState);
229 expect(synchronizing.status).toBe("synchronizing");
230 expect(Option.getOrThrow(synchronizing.snapshot)).toEqual(cachedSnapshot);
231​
232 yield* Queue.offer(events, { kind: "snapshot", snapshot: resetSnapshot });
233 yield* Queue.offer(events, { kind: "synchronized" });
234 yield* SubscriptionRef.changes(shellState).pipe(
235 Stream.filter((value) => value.status === "live"),
236 Stream.runHead,
237 );
238​
239 const live = yield* SubscriptionRef.get(shellState);
240 expect(Option.getOrThrow(live.snapshot)).toEqual(resetSnapshot);
241 expect(yield* Ref.get(loaderCalls)).toBe(1);
242​
243 yield* Queue.offer(wakeups, "application-active");
244 const resumedInput = yield* Queue.take(subscribeInputs);
245 expect(resumedInput.afterSequence).toBe(resetSnapshot.snapshotSequence);
246 expect(resumedInput.requestCompletionMarker).toBe(true);
247 expect(yield* Ref.get(loaderCalls)).toBe(1);
248 }),
249 );
250​
251 it.effect("resubscribes from the in-memory shell cursor when the app becomes active", () =>
252 Effect.gen(function* () {
253 const events = yield* Queue.unbounded<OrchestrationShellStreamItem>();
254 const wakeups = yield* Queue.unbounded<ConnectionWakeups.ConnectionWakeup>();
255 const loaderCalls = yield* Ref.make(0);
256 const capturedAfterSequences = yield* Ref.make<ReadonlyArray<number | undefined>>([]);
257 const client = {
258 [ORCHESTRATION_WS_METHODS.subscribeShell]: (input: { readonly afterSequence?: number }) =>
259 Stream.unwrap(
260 Ref.update(capturedAfterSequences, (captured) => [
261 ...captured,
262 input.afterSequence,
263 ]).pipe(Effect.as(Stream.fromQueue(events))),
264 ),
265 } as unknown as WsRpcProtocolClient;
266 const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
267 const activeSession = yield* SubscriptionRef.make(Option.some(session(client)));
268 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
269 target: TARGET,
270 state: supervisorState,
271 session: activeSession,
272 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
273 connect: Effect.void,
274 disconnect: Effect.void,
275 retryNow: Effect.void,
276 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
277 const cache = Persistence.EnvironmentCacheStore.of({
278 loadShell: () => Effect.succeed(Option.some(LIVE_SHELL_SNAPSHOT)),
279 saveShell: () => Effect.void,
280 loadThread: () => Effect.succeed(Option.none()),
281 saveThread: () => Effect.void,
282 removeThread: () => Effect.void,
283 loadServerConfig: () => Effect.succeed(Option.none()),
284 saveServerConfig: () => Effect.void,
285 loadVcsRefs: () => Effect.succeed(Option.none()),
286 saveVcsRefs: () => Effect.void,
287 removeVcsRefs: () => Effect.void,
288 clearVcsRefs: () => Effect.void,
289 clear: () => Effect.void,
290 });
291 const snapshotLoader = ShellSnapshotLoader.of({
292 load: () =>
293 Ref.updateAndGet(loaderCalls, (count) => count + 1).pipe(
294 Effect.map((count) =>
295 Option.some({ ...LIVE_SHELL_SNAPSHOT, snapshotSequence: count * 10 }),
296 ),
297 ),
298 });
299 const shellState = yield* makeEnvironmentShellState().pipe(
300 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
301 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
302 Effect.provideService(ShellSnapshotLoader, snapshotLoader),
303 Effect.provideService(
304 ConnectionWakeups.ConnectionWakeups,
305 ConnectionWakeups.ConnectionWakeups.of({ changes: Stream.fromQueue(wakeups) }),
306 ),
307 );
308​
309 // A new session starts from an authoritative HTTP snapshot.
310 for (let attempt = 0; attempt < 100; attempt += 1) {
311 if ((yield* Ref.get(capturedAfterSequences)).length >= 1) break;
312 yield* Effect.yieldNow;
313 }
314 expect(yield* Ref.get(capturedAfterSequences)).toEqual([10]);
315 yield* Queue.offer(events, { kind: "synchronized" });
316 yield* SubscriptionRef.changes(shellState).pipe(
317 Stream.filter((value) => value.status === "live"),
318 Stream.runHead,
319 );
320​
321 // A newer snapshot arrives on the stream and advances the cursor.
322 yield* Queue.offer(events, {
323 kind: "snapshot",
324 snapshot: { ...LIVE_SHELL_SNAPSHOT, snapshotSequence: 40 },
325 });
326 yield* SubscriptionRef.changes(shellState).pipe(
327 Stream.filter(
328 (value) => Option.isSome(value.snapshot) && value.snapshot.value.snapshotSequence === 40,
329 ),
330 Stream.runHead,
331 );
332​
333 yield* Queue.offer(wakeups, "application-active");
334 for (let attempt = 0; attempt < 100; attempt += 1) {
335 if ((yield* Ref.get(capturedAfterSequences)).length >= 2) break;
336 yield* Effect.yieldNow;
337 }
338 expect(yield* Ref.get(capturedAfterSequences)).toEqual([10, 40]);
339 yield* Queue.offer(events, { kind: "synchronized" });
340​
341 yield* Queue.offer(wakeups, "application-active-probe");
342 for (let attempt = 0; attempt < 100; attempt += 1) {
343 if ((yield* Ref.get(capturedAfterSequences)).length >= 3) break;
344 yield* Effect.yieldNow;
345 }
346 expect(yield* Ref.get(capturedAfterSequences)).toEqual([10, 40, 40]);
347​
348 yield* Queue.offer(wakeups, "application-active-reconnect");
349 for (let attempt = 0; attempt < 10; attempt += 1) {
350 yield* Effect.yieldNow;
351 }
352 expect((yield* Ref.get(capturedAfterSequences)).length).toBe(3);
353 expect(yield* Ref.get(loaderCalls)).toBe(1);
354​
355 // Replacing the session performs another authoritative refresh.
356 yield* SubscriptionRef.set(activeSession, Option.some(session(client)));
357 for (let attempt = 0; attempt < 100; attempt += 1) {
358 if ((yield* Ref.get(capturedAfterSequences)).length >= 4) break;
359 yield* Effect.yieldNow;
360 }
361 expect(yield* Ref.get(capturedAfterSequences)).toEqual([10, 40, 40, 20]);
362 expect(yield* Ref.get(loaderCalls)).toBe(2);
363 }),
364 );
365});