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

shell-sync.test.ts

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