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

shell-sync.test.ts

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