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

shell-sync.test.ts

870 lines34.8 KB

1import {
2 EnvironmentId,
3 ORCHESTRATION_V2_WS_METHODS,
4 type OrchestrationV2ShellSnapshot,
5 type OrchestrationV2ShellStreamItem,
6} from "@t3tools/contracts";
7import { describe, expect, it } from "@effect/vitest";
8import * as Deferred from "effect/Deferred";
9import * as Effect from "effect/Effect";
10import * as Exit from "effect/Exit";
11import * as Fiber from "effect/Fiber";
12import * as Option from "effect/Option";
13import * as Queue from "effect/Queue";
14import * as Ref from "effect/Ref";
15import * as Scope from "effect/Scope";
16import * as Stream from "effect/Stream";
17import * as SubscriptionRef from "effect/SubscriptionRef";
18​
19import {
20 AVAILABLE_CONNECTION_STATE,
21 PrimaryConnectionTarget,
22 type PreparedConnection,
23} from "../connection/model.ts";
24import * as EnvironmentSupervisor from "../connection/supervisor.ts";
25import * as ConnectionWakeups from "../connection/wakeups.ts";
26import * as Persistence from "../platform/persistence.ts";
27import * as RpcSession from "../rpc/session.ts";
28import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
29import { makeEnvironmentShellState, ShellSnapshotLoader } from "./shell.ts";
30import { v2Project, v2ShellSnapshot } from "./orchestrationV2TestFixtures.ts";
31​
32const TARGET = new PrimaryConnectionTarget({
33 environmentId: EnvironmentId.make("environment-1"),
34 label: "Test environment",
35 httpBaseUrl: "https://environment.example.test",
36 wsBaseUrl: "wss://environment.example.test",
37});
38​
39const PREPARED: PreparedConnection = {
40 environmentId: TARGET.environmentId,
41 label: TARGET.label,
42 httpBaseUrl: TARGET.httpBaseUrl,
43 socketUrl: TARGET.wsBaseUrl,
44 httpAuthorization: null,
45 target: TARGET,
46};
47​
48const LIVE_SHELL_SNAPSHOT: OrchestrationV2ShellSnapshot = {
49 ...v2ShellSnapshot,
50 snapshotSequence: 1,
51};
52​
53function session(client: WsRpcProtocolClient): RpcSession.RpcSession {
54 return {
55 client,
56 initialConfig: Effect.succeed({ shellResumeCompletionMarker: true } as never),
57 subscribeServerConfig: (input) => client.subscribeServerConfig(input),
58 ready: Effect.void,
59 probe: Effect.void,
60 closed: Effect.never,
61 };
63​
64describe("environment shell synchronization", () => {
65 it.effect("publishes live state before persistence and preserves it when ready", () =>
66 Effect.gen(function* () {
67 const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
68 const client = {
69 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () => Stream.fromQueue(events),
70 } as unknown as WsRpcProtocolClient;
71 const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
72 const activeSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
73 Option.some(session(client)),
74 );
75 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
76 target: TARGET,
77 state: supervisorState,
78 session: activeSession,
79 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
80 connect: Effect.void,
81 disconnect: Effect.void,
82 retryNow: Effect.void,
83 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
84 const cache = Persistence.EnvironmentCacheStore.of({
85 loadShell: () => Effect.succeed(Option.none()),
86 saveShell: () => Effect.void,
87 loadThread: () => Effect.succeed(Option.none()),
88 saveThread: () => Effect.void,
89 removeThread: () => Effect.void,
90 loadServerConfig: () => Effect.succeed(Option.none()),
91 saveServerConfig: () => Effect.void,
92 loadVcsRefs: () => Effect.succeed(Option.none()),
93 saveVcsRefs: () => Effect.void,
94 removeVcsRefs: () => Effect.void,
95 clearVcsRefs: () => Effect.void,
96 clear: () => Effect.void,
97 });
98 // Cold cache with no HTTP snapshot available → falls back to the
99 // socket-embedded snapshot.
100 const snapshotLoader = ShellSnapshotLoader.of({
101 load: () => Effect.succeed(Option.none()),
102 });
103 const shellState = yield* makeEnvironmentShellState().pipe(
104 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
105 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
106 Effect.provideService(ShellSnapshotLoader, snapshotLoader),
107 );
108​
109 yield* SubscriptionRef.set(supervisorState, {
110 desired: true,
111 network: "online",
112 phase: "connecting",
113 stage: "synchronizing",
114 attempt: 1,
115 generation: 0,
116 lastFailure: null,
117 retryAt: null,
118 });
119 yield* Queue.offer(events, {
120 kind: "snapshot",
121 snapshot: LIVE_SHELL_SNAPSHOT,
122 });
123 const synchronizing = yield* SubscriptionRef.changes(shellState).pipe(
124 Stream.filter((state) => state.status === "synchronizing" && Option.isSome(state.snapshot)),
125 Stream.runHead,
126 );
127 expect(Option.getOrThrow(Option.getOrThrow(synchronizing).snapshot)).toEqual(
128 LIVE_SHELL_SNAPSHOT,
129 );
130​
131 yield* Queue.offer(events, { kind: "synchronized" });
132 yield* SubscriptionRef.changes(shellState).pipe(
133 Stream.filter((state) => state.status === "live"),
134 Stream.runHead,
135 );
136​
137 yield* SubscriptionRef.set(supervisorState, {
138 desired: true,
139 network: "online",
140 phase: "connected",
141 stage: null,
142 attempt: 1,
143 generation: 1,
144 lastFailure: null,
145 retryAt: null,
146 });
147 for (let index = 0; index < 10; index += 1) {
148 yield* Effect.yieldNow;
149 }
150​
151 const state = yield* SubscriptionRef.get(shellState);
152 expect(state.status).toBe("live");
153 expect(Option.getOrThrow(state.snapshot)).toEqual(LIVE_SHELL_SNAPSHOT);
154 }),
155 );
156​
157 it.live.each([
158 { bufferSize: Infinity, expectedSequences: [51] },
159 // RpcClient defaults to a 16-event buffer, which splits larger server chunks.
160 { bufferSize: 16, expectedSequences: [17, 33, 49, 51] },
161 ])("batches live events with a $bufferSize event buffer", ({ bufferSize, expectedSequences }) =>
162 Effect.gen(function* () {
163 const events = yield* Queue.bounded<OrchestrationV2ShellStreamItem>(bufferSize);
164 const batchSnapshot = { ...LIVE_SHELL_SNAPSHOT, threads: [] };
165 const client = {
166 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () => Stream.fromQueue(events),
167 } as unknown as WsRpcProtocolClient;
168 const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
169 const activeSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
170 Option.some(session(client)),
171 );
172 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
173 target: TARGET,
174 state: supervisorState,
175 session: activeSession,
176 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
177 connect: Effect.void,
178 disconnect: Effect.void,
179 retryNow: Effect.void,
180 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
181 const cache = Persistence.EnvironmentCacheStore.of({
182 loadShell: () => Effect.succeed(Option.none()),
183 saveShell: () => Effect.void,
184 loadThread: () => Effect.succeed(Option.none()),
185 saveThread: () => Effect.void,
186 removeThread: () => Effect.void,
187 loadServerConfig: () => Effect.succeed(Option.none()),
188 saveServerConfig: () => Effect.void,
189 loadVcsRefs: () => Effect.succeed(Option.none()),
190 saveVcsRefs: () => Effect.void,
191 removeVcsRefs: () => Effect.void,
192 clearVcsRefs: () => Effect.void,
193 clear: () => Effect.void,
194 });
195 const shellState = yield* makeEnvironmentShellState().pipe(
196 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
197 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
198 Effect.provideService(
199 ShellSnapshotLoader,
200 ShellSnapshotLoader.of({ load: () => Effect.succeed(Option.none()) }),
201 ),
202 );
203 yield* SubscriptionRef.set(supervisorState, {
204 desired: true,
205 network: "online",
206 phase: "connected",
207 stage: null,
208 attempt: 1,
209 generation: 1,
210 lastFailure: null,
211 retryAt: null,
212 });
213 yield* Queue.offer(events, { kind: "snapshot", snapshot: batchSnapshot });
214 yield* Queue.offer(events, { kind: "synchronized" });
215 yield* SubscriptionRef.changes(shellState).pipe(
216 Stream.filter((state) => state.status === "live"),
217 Stream.runHead,
218 );
219​
220 // Observe before publishing so no batch can arrive before the subscription.
221 const observed = yield* SubscriptionRef.changes(shellState).pipe(
222 Stream.drop(1),
223 Stream.takeUntil(
224 (state) => Option.isSome(state.snapshot) && state.snapshot.value.threads.length === 50,
225 ),
226 Stream.runCollect,
227 Effect.forkScoped({ startImmediately: true }),
228 );
229 yield* Queue.offerAll(
230 events,
231 Array.from({ length: 50 }, (_, index) => ({
232 kind: "thread.updated" as const,
233 sequence: 2 + index,
234 location: "active" as const,
235 thread: { ...v2ShellSnapshot.threads[0]!, id: `thread-${index}` } as never,
236 })),
237 );
238 const states = yield* Fiber.join(observed);
239 const snapshots = states.map((state) => Option.getOrThrow(state.snapshot));
240 expect(snapshots.map((snapshot) => snapshot.snapshotSequence)).toEqual(expectedSequences);
241 expect(snapshots.at(-1)!.threads.map((thread) => thread.id)).toEqual(
242 Array.from({ length: 50 }, (_, index) => `thread-${index}`),
243 );
244 }).pipe(Effect.scoped),
245 );
246​
247 it.effect("refreshes a warm shell cache from HTTP before resuming", () =>
248 Effect.gen(function* () {
249 const cachedSnapshot: OrchestrationV2ShellSnapshot = {
250 ...v2ShellSnapshot,
251 snapshotSequence: 5,
252 };
253 const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
254 const capturedAfterSequence = yield* SubscriptionRef.make<number | undefined>(undefined);
255 const capturedCompletionMarker = yield* Ref.make(false);
256 const loaderCalls = yield* SubscriptionRef.make(0);
257 const httpSnapshot: OrchestrationV2ShellSnapshot = {
258 ...v2ShellSnapshot,
259 snapshotSequence: 9,
260 };
261 const client = {
262 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: (input: {
263 readonly afterSequence?: number;
264 readonly requestCompletionMarker?: true;
265 }) =>
266 Stream.unwrap(
267 Effect.all([
268 Ref.set(capturedCompletionMarker, input.requestCompletionMarker === true),
269 SubscriptionRef.set(capturedAfterSequence, input.afterSequence),
270 ]).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.succeed(Option.some(cachedSnapshot)),
288 saveShell: () => Effect.void,
289 loadThread: () => Effect.succeed(Option.none()),
290 saveThread: () => Effect.void,
291 removeThread: () => Effect.void,
292 loadServerConfig: () => Effect.succeed(Option.none()),
293 saveServerConfig: () => Effect.void,
294 loadVcsRefs: () => Effect.succeed(Option.none()),
295 saveVcsRefs: () => Effect.void,
296 removeVcsRefs: () => Effect.void,
297 clearVcsRefs: () => Effect.void,
298 clear: () => Effect.void,
299 });
300 const snapshotLoader = ShellSnapshotLoader.of({
301 load: () =>
302 SubscriptionRef.update(loaderCalls, (count) => count + 1).pipe(
303 Effect.as(Option.some(httpSnapshot)),
304 ),
305 });
306 const shellState = yield* makeEnvironmentShellState().pipe(
307 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
308 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
309 Effect.provideService(ShellSnapshotLoader, snapshotLoader),
310 );
311​
312 // Wait until the subscription is established from the warm cache.
313 yield* SubscriptionRef.changes(capturedAfterSequence).pipe(
314 Stream.filter((value) => value !== undefined),
315 Stream.runHead,
316 );
317​
318 expect(yield* SubscriptionRef.get(capturedAfterSequence)).toBe(9);
319 expect(yield* Ref.get(capturedCompletionMarker)).toBe(true);
320 expect(yield* SubscriptionRef.get(loaderCalls)).toBe(1);
321 const synchronizing = yield* SubscriptionRef.get(shellState);
322 expect(synchronizing.status).toBe("synchronizing");
323 expect(Option.getOrThrow(synchronizing.snapshot)).toEqual(httpSnapshot);
324​
325 yield* Queue.offer(events, { kind: "synchronized" });
326 yield* SubscriptionRef.changes(shellState).pipe(
327 Stream.filter((value) => value.status === "live"),
328 Stream.runHead,
329 );
330 }),
331 );
332​
333 it.effect("resubscribes from the in-memory shell cursor when the app becomes active", () =>
334 Effect.gen(function* () {
335 const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
336 const wakeups = yield* Queue.unbounded<ConnectionWakeups.ConnectionWakeup>();
337 const loaderCalls = yield* Ref.make(0);
338 const capturedAfterSequences = yield* Ref.make<ReadonlyArray<number | undefined>>([]);
339 const client = {
340 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: (input: {
341 readonly afterSequence?: number;
342 }) =>
343 Stream.unwrap(
344 Ref.update(capturedAfterSequences, (captured) => [
345 ...captured,
346 input.afterSequence,
347 ]).pipe(Effect.as(Stream.fromQueue(events))),
348 ),
349 } as unknown as WsRpcProtocolClient;
350 const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
351 const activeSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
352 Option.some(session(client)),
353 );
354 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
355 target: TARGET,
356 state: supervisorState,
357 session: activeSession,
358 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
359 connect: Effect.void,
360 disconnect: Effect.void,
361 retryNow: Effect.void,
362 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
363 const cache = Persistence.EnvironmentCacheStore.of({
364 loadShell: () => Effect.succeed(Option.some(LIVE_SHELL_SNAPSHOT)),
365 saveShell: () => Effect.void,
366 loadThread: () => Effect.succeed(Option.none()),
367 saveThread: () => Effect.void,
368 removeThread: () => Effect.void,
369 loadServerConfig: () => Effect.succeed(Option.none()),
370 saveServerConfig: () => Effect.void,
371 loadVcsRefs: () => Effect.succeed(Option.none()),
372 saveVcsRefs: () => Effect.void,
373 removeVcsRefs: () => Effect.void,
374 clearVcsRefs: () => Effect.void,
375 clear: () => Effect.void,
376 });
377 const snapshotLoader = ShellSnapshotLoader.of({
378 load: () =>
379 Ref.updateAndGet(loaderCalls, (count) => count + 1).pipe(
380 Effect.map((count) =>
381 Option.some({ ...LIVE_SHELL_SNAPSHOT, snapshotSequence: count * 10 }),
382 ),
383 ),
384 });
385 const shellState = yield* makeEnvironmentShellState().pipe(
386 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
387 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
388 Effect.provideService(ShellSnapshotLoader, snapshotLoader),
389 Effect.provideService(
390 ConnectionWakeups.ConnectionWakeups,
391 ConnectionWakeups.ConnectionWakeups.of({ changes: Stream.fromQueue(wakeups) }),
392 ),
393 );
394​
395 // A new session starts from an authoritative HTTP snapshot.
396 for (let attempt = 0; attempt < 100; attempt += 1) {
397 if ((yield* Ref.get(capturedAfterSequences)).length >= 1) break;
398 yield* Effect.yieldNow;
399 }
400 expect(yield* Ref.get(capturedAfterSequences)).toEqual([10]);
401 yield* Queue.offer(events, { kind: "synchronized" });
402 yield* SubscriptionRef.changes(shellState).pipe(
403 Stream.filter((value) => value.status === "live"),
404 Stream.runHead,
405 );
406​
407 // A newer snapshot arrives on the stream and advances the cursor.
408 yield* Queue.offer(events, {
409 kind: "snapshot",
410 snapshot: { ...LIVE_SHELL_SNAPSHOT, snapshotSequence: 40 },
411 });
412 yield* SubscriptionRef.changes(shellState).pipe(
413 Stream.filter(
414 (value) => Option.isSome(value.snapshot) && value.snapshot.value.snapshotSequence === 40,
415 ),
416 Stream.runHead,
417 );
418​
419 yield* Queue.offer(wakeups, "application-active");
420 for (let attempt = 0; attempt < 100; attempt += 1) {
421 if ((yield* Ref.get(capturedAfterSequences)).length >= 2) break;
422 yield* Effect.yieldNow;
423 }
424 expect(yield* Ref.get(capturedAfterSequences)).toEqual([10, 40]);
425 yield* Queue.offer(events, { kind: "synchronized" });
426​
427 yield* Queue.offer(wakeups, "application-active-probe");
428 for (let attempt = 0; attempt < 100; attempt += 1) {
429 if ((yield* Ref.get(capturedAfterSequences)).length >= 3) break;
430 yield* Effect.yieldNow;
431 }
432 expect(yield* Ref.get(capturedAfterSequences)).toEqual([10, 40, 40]);
433​
434 yield* Queue.offer(wakeups, "application-active-reconnect");
435 for (let attempt = 0; attempt < 10; attempt += 1) {
436 yield* Effect.yieldNow;
437 }
438 expect((yield* Ref.get(capturedAfterSequences)).length).toBe(3);
439 expect(yield* Ref.get(loaderCalls)).toBe(1);
440​
441 // Replacing the session performs another authoritative refresh.
442 yield* SubscriptionRef.set(activeSession, Option.some(session(client)));
443 for (let attempt = 0; attempt < 100; attempt += 1) {
444 if ((yield* Ref.get(capturedAfterSequences)).length >= 4) break;
445 yield* Effect.yieldNow;
446 }
447 expect(yield* Ref.get(capturedAfterSequences)).toEqual([10, 40, 40, 20]);
448 expect(yield* Ref.get(loaderCalls)).toBe(2);
449 }),
450 );
451​
452 it.effect("flushes the latest live snapshot without blocking connection state updates", () =>
453 Effect.gen(function* () {
454 const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
455 const saved = yield* Ref.make<ReadonlyArray<OrchestrationV2ShellSnapshot>>([]);
456 const saveStarted = yield* Deferred.make<void>();
457 const releaseSave = yield* Deferred.make<void>();
458 const client = {
459 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () => Stream.fromQueue(events),
460 } as unknown as WsRpcProtocolClient;
461 const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
462 const activeSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
463 Option.some(session(client)),
464 );
465 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
466 target: TARGET,
467 state: supervisorState,
468 session: activeSession,
469 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
470 connect: Effect.void,
471 disconnect: Effect.void,
472 retryNow: Effect.void,
473 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
474 const cache = Persistence.EnvironmentCacheStore.of({
475 loadShell: () => Effect.succeed(Option.none()),
476 saveShell: (_environmentId, snapshot) =>
477 Deferred.succeed(saveStarted, undefined).pipe(
478 Effect.andThen(Deferred.await(releaseSave)),
479 Effect.andThen(Ref.update(saved, (values) => [...values, snapshot])),
480 ),
481 loadThread: () => Effect.succeed(Option.none()),
482 saveThread: () => Effect.void,
483 removeThread: () => Effect.void,
484 loadServerConfig: () => Effect.succeed(Option.none()),
485 saveServerConfig: () => Effect.void,
486 loadVcsRefs: () => Effect.succeed(Option.none()),
487 saveVcsRefs: () => Effect.void,
488 removeVcsRefs: () => Effect.void,
489 clearVcsRefs: () => Effect.void,
490 clear: () => Effect.void,
491 });
492 const snapshotLoader = ShellSnapshotLoader.of({
493 load: () => Effect.succeed(Option.none()),
494 });
495​
496 const shellState = yield* makeEnvironmentShellState().pipe(
497 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
498 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
499 Effect.provideService(ShellSnapshotLoader, snapshotLoader),
500 );
501​
502 yield* SubscriptionRef.set(supervisorState, {
503 desired: true,
504 network: "online",
505 phase: "connecting",
506 stage: "synchronizing",
507 attempt: 1,
508 generation: 0,
509 lastFailure: null,
510 retryAt: null,
511 });
512 yield* Queue.offer(events, {
513 kind: "snapshot",
514 snapshot: LIVE_SHELL_SNAPSHOT,
515 });
516 yield* Queue.offer(events, { kind: "synchronized" });
517 yield* SubscriptionRef.changes(shellState).pipe(
518 Stream.filter((state) => state.status === "live"),
519 Stream.runHead,
520 );
521​
522 yield* SubscriptionRef.set(supervisorState, {
523 desired: true,
524 network: "online",
525 phase: "connecting",
526 stage: "synchronizing",
527 attempt: 2,
528 generation: 1,
529 lastFailure: null,
530 retryAt: null,
531 });
532 yield* SubscriptionRef.set(supervisorState, {
533 desired: false,
534 network: "online",
535 phase: "available",
536 stage: null,
537 attempt: 2,
538 generation: 2,
539 lastFailure: null,
540 retryAt: null,
541 });
542 yield* Deferred.await(saveStarted);
543​
544 yield* SubscriptionRef.set(supervisorState, {
545 desired: true,
546 network: "online",
547 phase: "connecting",
548 stage: "synchronizing",
549 attempt: 3,
550 generation: 3,
551 lastFailure: null,
552 retryAt: null,
553 });
554 for (let index = 0; index < 100; index += 1) {
555 if ((yield* SubscriptionRef.get(shellState)).status === "synchronizing") break;
556 yield* Effect.yieldNow;
557 }
558​
559 expect((yield* SubscriptionRef.get(shellState)).status).toBe("synchronizing");
560 expect(yield* Ref.get(saved)).toEqual([]);
561​
562 yield* Deferred.succeed(releaseSave, undefined);
563 for (let index = 0; index < 100; index += 1) {
564 if ((yield* Ref.get(saved)).length > 0) break;
565 yield* Effect.yieldNow;
566 }
567​
568 expect(yield* Ref.get(saved)).toEqual([LIVE_SHELL_SNAPSHOT]);
569 }),
570 );
571​
572 it.effect("re-persists same-sequence enrichment when an older in-flight save completes", () =>
573 Effect.gen(function* () {
574 const repositoryIdentity = {
575 canonicalKey: "github.com/example/repo",
576 locator: {
577 source: "git-remote" as const,
578 remoteName: "origin",
579 remoteUrl: "https://github.com/example/repo.git",
580 },
581 };
582 const unenrichedSnapshot: OrchestrationV2ShellSnapshot = {
583 ...LIVE_SHELL_SNAPSHOT,
584 snapshotSequence: 1,
585 projects: [{ ...v2Project, repositoryIdentity: null }],
586 };
587 const enrichedSnapshot: OrchestrationV2ShellSnapshot = {
588 ...LIVE_SHELL_SNAPSHOT,
589 snapshotSequence: 1,
590 projects: [{ ...v2Project, repositoryIdentity }],
591 };
592​
593 const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
594 const saved = yield* Ref.make<ReadonlyArray<OrchestrationV2ShellSnapshot>>([]);
595 const unenrichedSaveStarted = yield* Deferred.make<void>();
596 const releaseUnenrichedSave = yield* Deferred.make<void>();
597 const client = {
598 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () => Stream.fromQueue(events),
599 } as unknown as WsRpcProtocolClient;
600 const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
601 const activeSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
602 Option.some(session(client)),
603 );
604 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
605 target: TARGET,
606 state: supervisorState,
607 session: activeSession,
608 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
609 connect: Effect.void,
610 disconnect: Effect.void,
611 retryNow: Effect.void,
612 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
613 const cache = Persistence.EnvironmentCacheStore.of({
614 loadShell: () => Effect.succeed(Option.none()),
615 saveShell: (_environmentId, snapshot) =>
616 Effect.gen(function* () {
617 if (snapshot.projects[0]?.repositoryIdentity == null) {
618 yield* Deferred.succeed(unenrichedSaveStarted, undefined);
619 yield* Deferred.await(releaseUnenrichedSave);
620 }
621 yield* Ref.update(saved, (values) => [...values, snapshot]);
622 }),
623 loadThread: () => Effect.succeed(Option.none()),
624 saveThread: () => Effect.void,
625 removeThread: () => Effect.void,
626 loadServerConfig: () => Effect.succeed(Option.none()),
627 saveServerConfig: () => Effect.void,
628 loadVcsRefs: () => Effect.succeed(Option.none()),
629 saveVcsRefs: () => Effect.void,
630 removeVcsRefs: () => Effect.void,
631 clearVcsRefs: () => Effect.void,
632 clear: () => Effect.void,
633 });
634 const snapshotLoader = ShellSnapshotLoader.of({
635 load: () => Effect.succeed(Option.none()),
636 });
637​
638 const shellState = yield* makeEnvironmentShellState().pipe(
639 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
640 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
641 Effect.provideService(ShellSnapshotLoader, snapshotLoader),
642 );
643​
644 yield* SubscriptionRef.set(supervisorState, {
645 desired: true,
646 network: "online",
647 phase: "connecting",
648 stage: "synchronizing",
649 attempt: 1,
650 generation: 0,
651 lastFailure: null,
652 retryAt: null,
653 });
654 yield* Queue.offer(events, {
655 kind: "snapshot",
656 snapshot: unenrichedSnapshot,
657 });
658 yield* Queue.offer(events, { kind: "synchronized" });
659 yield* SubscriptionRef.changes(shellState).pipe(
660 Stream.filter((state) => state.status === "live"),
661 Stream.runHead,
662 );
663​
664 // Disconnect flush starts an immediate persist of the unenriched snapshot
665 // (debounced path needs TestClock advancement; flush does not).
666 yield* SubscriptionRef.set(supervisorState, {
667 desired: false,
668 network: "online",
669 phase: "available",
670 stage: null,
671 attempt: 1,
672 generation: 1,
673 lastFailure: null,
674 retryAt: null,
675 });
676 yield* Deferred.await(unenrichedSaveStarted);
677​
678 // Same sequence, different content. Session stays open so the stream can
679 // still apply enrichment while the older save is in flight.
680 yield* Queue.offer(events, {
681 kind: "snapshot",
682 snapshot: enrichedSnapshot,
683 });
684 yield* SubscriptionRef.changes(shellState).pipe(
685 Stream.filter(
686 (state) =>
687 Option.isSome(state.snapshot) &&
688 state.snapshot.value.projects[0]?.repositoryIdentity != null,
689 ),
690 Stream.runHead,
691 );
692​
693 // Completing the older same-sequence save must re-persist the latest object.
694 yield* Deferred.succeed(releaseUnenrichedSave, undefined);
695 for (let index = 0; index < 100; index += 1) {
696 const values = yield* Ref.get(saved);
697 if (values.length > 0 && values.at(-1)?.projects[0]?.repositoryIdentity != null) {
698 break;
699 }
700 yield* Effect.yieldNow;
701 }
702​
703 const finalSaved = (yield* Ref.get(saved)).at(-1);
704 expect(finalSaved?.snapshotSequence).toBe(1);
705 expect(finalSaved?.projects[0]?.repositoryIdentity).toEqual(repositoryIdentity);
706 }),
707 );
708​
709 it.effect("scope teardown flush stays stable while a save is blocked", () =>
710 Effect.gen(function* () {
711 const lateSnapshot: OrchestrationV2ShellSnapshot = {
712 ...LIVE_SHELL_SNAPSHOT,
713 snapshotSequence: 2,
714 projects: [{ ...v2Project, title: "Late stream event" }],
715 };
716 const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
717 const saved = yield* Ref.make<ReadonlyArray<OrchestrationV2ShellSnapshot>>([]);
718 const saveStarted = yield* Deferred.make<void>();
719 const releaseSave = yield* Deferred.make<void>();
720 const client = {
721 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () => Stream.fromQueue(events),
722 } as unknown as WsRpcProtocolClient;
723 const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
724 const activeSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
725 Option.some(session(client)),
726 );
727 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
728 target: TARGET,
729 state: supervisorState,
730 session: activeSession,
731 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
732 connect: Effect.void,
733 disconnect: Effect.void,
734 retryNow: Effect.void,
735 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
736 const cache = Persistence.EnvironmentCacheStore.of({
737 loadShell: () => Effect.succeed(Option.none()),
738 saveShell: (_environmentId, snapshot) =>
739 Deferred.succeed(saveStarted, undefined).pipe(
740 Effect.andThen(Deferred.await(releaseSave)),
741 Effect.andThen(Ref.update(saved, (values) => [...values, snapshot])),
742 ),
743 loadThread: () => Effect.succeed(Option.none()),
744 saveThread: () => Effect.void,
745 removeThread: () => Effect.void,
746 loadServerConfig: () => Effect.succeed(Option.none()),
747 saveServerConfig: () => Effect.void,
748 loadVcsRefs: () => Effect.succeed(Option.none()),
749 saveVcsRefs: () => Effect.void,
750 removeVcsRefs: () => Effect.void,
751 clearVcsRefs: () => Effect.void,
752 clear: () => Effect.void,
753 });
754 const snapshotLoader = ShellSnapshotLoader.of({
755 load: () => Effect.succeed(Option.none()),
756 });
757​
758 const scope = yield* Scope.make();
759 const shellState = yield* makeEnvironmentShellState().pipe(
760 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
761 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
762 Effect.provideService(ShellSnapshotLoader, snapshotLoader),
763 Scope.provide(scope),
764 );
765​
766 yield* SubscriptionRef.set(supervisorState, {
767 desired: true,
768 network: "online",
769 phase: "connecting",
770 stage: "synchronizing",
771 attempt: 1,
772 generation: 0,
773 lastFailure: null,
774 retryAt: null,
775 });
776 yield* Queue.offer(events, {
777 kind: "snapshot",
778 snapshot: LIVE_SHELL_SNAPSHOT,
779 });
780 yield* Queue.offer(events, { kind: "synchronized" });
781 yield* SubscriptionRef.changes(shellState).pipe(
782 Stream.filter((state) => state.status === "live"),
783 Stream.runHead,
784 );
785​
786 // Close scope so the finalizer flush blocks on save. Workers must be
787 // interrupted before that flush; late stream events must not extend it.
788 const closeFiber = yield* Effect.forkChild(Scope.close(scope, Exit.void));
789 yield* Deferred.await(saveStarted);
790 yield* Queue.offer(events, {
791 kind: "snapshot",
792 snapshot: lateSnapshot,
793 });
794 for (let index = 0; index < 50; index += 1) {
795 yield* Effect.yieldNow;
796 }
797 yield* Deferred.succeed(releaseSave, undefined);
798 yield* Fiber.join(closeFiber);
799​
800 const values = yield* Ref.get(saved);
801 expect(values.length).toBeGreaterThan(0);
802 expect(values.every((snapshot) => snapshot.snapshotSequence === 1)).toBe(true);
803 expect(values.every((snapshot) => snapshot.projects[0]?.title !== "Late stream event")).toBe(
804 true,
805 );
806 }),
807 );
808​
809 it.effect("applies authoritative lower-sequence HTTP resets over client-ahead cache", () =>
810 Effect.gen(function* () {
811 const cachedSnapshot: OrchestrationV2ShellSnapshot = {
812 ...v2ShellSnapshot,
813 snapshotSequence: 20,
814 projects: [{ ...v2Project, title: "Client ahead" }],
815 };
816 const httpSnapshot: OrchestrationV2ShellSnapshot = {
817 ...v2ShellSnapshot,
818 snapshotSequence: 4,
819 projects: [{ ...v2Project, title: "Server reset" }],
820 };
821 const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
822 const client = {
823 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () => Stream.fromQueue(events),
824 } as unknown as WsRpcProtocolClient;
825 const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
826 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
827 target: TARGET,
828 state: supervisorState,
829 session: yield* SubscriptionRef.make(Option.some(session(client))),
830 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
831 connect: Effect.void,
832 disconnect: Effect.void,
833 retryNow: Effect.void,
834 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
835 const cache = Persistence.EnvironmentCacheStore.of({
836 loadShell: () => Effect.succeed(Option.some(cachedSnapshot)),
837 saveShell: () => Effect.void,
838 loadThread: () => Effect.succeed(Option.none()),
839 saveThread: () => Effect.void,
840 removeThread: () => Effect.void,
841 loadServerConfig: () => Effect.succeed(Option.none()),
842 saveServerConfig: () => Effect.void,
843 loadVcsRefs: () => Effect.succeed(Option.none()),
844 saveVcsRefs: () => Effect.void,
845 removeVcsRefs: () => Effect.void,
846 clearVcsRefs: () => Effect.void,
847 clear: () => Effect.void,
848 });
849 const snapshotLoader = ShellSnapshotLoader.of({
850 load: () => Effect.succeed(Option.some(httpSnapshot)),
851 });
852 const shellState = yield* makeEnvironmentShellState().pipe(
853 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
854 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
855 Effect.provideService(ShellSnapshotLoader, snapshotLoader),
856 );
857​
858 yield* SubscriptionRef.changes(shellState).pipe(
859 Stream.filter(
860 (state) => Option.isSome(state.snapshot) && state.snapshot.value.snapshotSequence === 4,
861 ),
862 Stream.runHead,
863 );
864​
865 const state = yield* SubscriptionRef.get(shellState);
866 expect(Option.getOrThrow(state.snapshot).snapshotSequence).toBe(4);
867 expect(Option.getOrThrow(state.snapshot).projects[0]?.title).toBe("Server reset");
868 }),
869 );
870});