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

shell-sync.test.ts

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