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

shell-sync.test.ts

767 lines30.0 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("refreshes the authoritative shell snapshot 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 subscriptionCount = yield* Ref.make(0);
248 const client = {
249 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () =>
250 Stream.unwrap(
251 Ref.update(subscriptionCount, (count) => count + 1).pipe(
252 Effect.as(Stream.fromQueue(events)),
253 ),
254 ),
255 } as unknown as WsRpcProtocolClient;
256 const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
257 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
258 target: TARGET,
259 state: supervisorState,
260 session: yield* SubscriptionRef.make(Option.some(session(client))),
261 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
262 connect: Effect.void,
263 disconnect: Effect.void,
264 retryNow: Effect.void,
265 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
266 const cache = Persistence.EnvironmentCacheStore.of({
267 loadShell: () => Effect.succeed(Option.some(LIVE_SHELL_SNAPSHOT)),
268 saveShell: () => Effect.void,
269 loadThread: () => Effect.succeed(Option.none()),
270 saveThread: () => Effect.void,
271 removeThread: () => Effect.void,
272 loadServerConfig: () => Effect.succeed(Option.none()),
273 saveServerConfig: () => Effect.void,
274 loadVcsRefs: () => Effect.succeed(Option.none()),
275 saveVcsRefs: () => Effect.void,
276 removeVcsRefs: () => Effect.void,
277 clearVcsRefs: () => Effect.void,
278 clear: () => Effect.void,
279 });
280 const snapshotLoader = ShellSnapshotLoader.of({
281 load: () =>
282 Ref.updateAndGet(loaderCalls, (count) => count + 1).pipe(
283 Effect.map((count) =>
284 Option.some({ ...LIVE_SHELL_SNAPSHOT, snapshotSequence: count * 10 }),
285 ),
286 ),
287 });
288 const shellState = yield* makeEnvironmentShellState().pipe(
289 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
290 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
291 Effect.provideService(ShellSnapshotLoader, snapshotLoader),
292 Effect.provideService(
293 ConnectionWakeups.ConnectionWakeups,
294 ConnectionWakeups.ConnectionWakeups.of({ changes: Stream.fromQueue(wakeups) }),
295 ),
296 );
297​
298 yield* SubscriptionRef.changes(shellState).pipe(
299 Stream.filter(
300 (value) =>
301 value.status === "synchronizing" &&
302 Option.isSome(value.snapshot) &&
303 value.snapshot.value.snapshotSequence === 10,
304 ),
305 Stream.runHead,
306 );
307 yield* Queue.offer(events, { kind: "synchronized" });
308 yield* SubscriptionRef.changes(shellState).pipe(
309 Stream.filter((value) => value.status === "live"),
310 Stream.runHead,
311 );
312​
313 yield* Queue.offer(wakeups, "application-active");
314 yield* SubscriptionRef.changes(shellState).pipe(
315 Stream.filter(
316 (value) =>
317 value.status === "synchronizing" &&
318 Option.isSome(value.snapshot) &&
319 value.snapshot.value.snapshotSequence === 20,
320 ),
321 Stream.runHead,
322 );
323​
324 for (let attempt = 0; attempt < 100; attempt += 1) {
325 if ((yield* Ref.get(subscriptionCount)) >= 2) break;
326 yield* Effect.yieldNow;
327 }
328​
329 expect(yield* Ref.get(loaderCalls)).toBe(2);
330 expect(yield* Ref.get(subscriptionCount)).toBe(2);
331​
332 yield* Queue.offer(wakeups, "application-active-probe");
333 for (let attempt = 0; attempt < 100; attempt += 1) {
334 if ((yield* Ref.get(subscriptionCount)) >= 3) break;
335 yield* Effect.yieldNow;
336 }
337 expect(yield* Ref.get(loaderCalls)).toBe(3);
338 expect(yield* Ref.get(subscriptionCount)).toBe(3);
339​
340 yield* Queue.offer(wakeups, "application-active-reconnect");
341 for (let attempt = 0; attempt < 10; attempt += 1) {
342 yield* Effect.yieldNow;
343 }
344 expect(yield* Ref.get(loaderCalls)).toBe(3);
345 expect(yield* Ref.get(subscriptionCount)).toBe(3);
346 }),
347 );
348​
349 it.effect("flushes the latest live snapshot without blocking connection state updates", () =>
350 Effect.gen(function* () {
351 const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
352 const saved = yield* Ref.make<ReadonlyArray<OrchestrationV2ShellSnapshot>>([]);
353 const saveStarted = yield* Deferred.make<void>();
354 const releaseSave = yield* Deferred.make<void>();
355 const client = {
356 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () => Stream.fromQueue(events),
357 } as unknown as WsRpcProtocolClient;
358 const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
359 const activeSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
360 Option.some(session(client)),
361 );
362 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
363 target: TARGET,
364 state: supervisorState,
365 session: activeSession,
366 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
367 connect: Effect.void,
368 disconnect: Effect.void,
369 retryNow: Effect.void,
370 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
371 const cache = Persistence.EnvironmentCacheStore.of({
372 loadShell: () => Effect.succeed(Option.none()),
373 saveShell: (_environmentId, snapshot) =>
374 Deferred.succeed(saveStarted, undefined).pipe(
375 Effect.andThen(Deferred.await(releaseSave)),
376 Effect.andThen(Ref.update(saved, (values) => [...values, snapshot])),
377 ),
378 loadThread: () => Effect.succeed(Option.none()),
379 saveThread: () => Effect.void,
380 removeThread: () => Effect.void,
381 loadServerConfig: () => Effect.succeed(Option.none()),
382 saveServerConfig: () => Effect.void,
383 loadVcsRefs: () => Effect.succeed(Option.none()),
384 saveVcsRefs: () => Effect.void,
385 removeVcsRefs: () => Effect.void,
386 clearVcsRefs: () => Effect.void,
387 clear: () => Effect.void,
388 });
389 const snapshotLoader = ShellSnapshotLoader.of({
390 load: () => Effect.succeed(Option.none()),
391 });
392​
393 const shellState = yield* makeEnvironmentShellState().pipe(
394 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
395 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
396 Effect.provideService(ShellSnapshotLoader, snapshotLoader),
397 );
398​
399 yield* SubscriptionRef.set(supervisorState, {
400 desired: true,
401 network: "online",
402 phase: "connecting",
403 stage: "synchronizing",
404 attempt: 1,
405 generation: 0,
406 lastFailure: null,
407 retryAt: null,
408 });
409 yield* Queue.offer(events, {
410 kind: "snapshot",
411 snapshot: LIVE_SHELL_SNAPSHOT,
412 });
413 yield* Queue.offer(events, { kind: "synchronized" });
414 yield* SubscriptionRef.changes(shellState).pipe(
415 Stream.filter((state) => state.status === "live"),
416 Stream.runHead,
417 );
418​
419 yield* SubscriptionRef.set(supervisorState, {
420 desired: true,
421 network: "online",
422 phase: "connecting",
423 stage: "synchronizing",
424 attempt: 2,
425 generation: 1,
426 lastFailure: null,
427 retryAt: null,
428 });
429 yield* SubscriptionRef.set(supervisorState, {
430 desired: false,
431 network: "online",
432 phase: "available",
433 stage: null,
434 attempt: 2,
435 generation: 2,
436 lastFailure: null,
437 retryAt: null,
438 });
439 yield* Deferred.await(saveStarted);
440​
441 yield* SubscriptionRef.set(supervisorState, {
442 desired: true,
443 network: "online",
444 phase: "connecting",
445 stage: "synchronizing",
446 attempt: 3,
447 generation: 3,
448 lastFailure: null,
449 retryAt: null,
450 });
451 for (let index = 0; index < 100; index += 1) {
452 if ((yield* SubscriptionRef.get(shellState)).status === "synchronizing") break;
453 yield* Effect.yieldNow;
454 }
455​
456 expect((yield* SubscriptionRef.get(shellState)).status).toBe("synchronizing");
457 expect(yield* Ref.get(saved)).toEqual([]);
458​
459 yield* Deferred.succeed(releaseSave, undefined);
460 for (let index = 0; index < 100; index += 1) {
461 if ((yield* Ref.get(saved)).length > 0) break;
462 yield* Effect.yieldNow;
463 }
464​
465 expect(yield* Ref.get(saved)).toEqual([LIVE_SHELL_SNAPSHOT]);
466 }),
467 );
468​
469 it.effect("re-persists same-sequence enrichment when an older in-flight save completes", () =>
470 Effect.gen(function* () {
471 const repositoryIdentity = {
472 canonicalKey: "github.com/example/repo",
473 locator: {
474 source: "git-remote" as const,
475 remoteName: "origin",
476 remoteUrl: "https://github.com/example/repo.git",
477 },
478 };
479 const unenrichedSnapshot: OrchestrationV2ShellSnapshot = {
480 ...LIVE_SHELL_SNAPSHOT,
481 snapshotSequence: 1,
482 projects: [{ ...v2Project, repositoryIdentity: null }],
483 };
484 const enrichedSnapshot: OrchestrationV2ShellSnapshot = {
485 ...LIVE_SHELL_SNAPSHOT,
486 snapshotSequence: 1,
487 projects: [{ ...v2Project, repositoryIdentity }],
488 };
489​
490 const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
491 const saved = yield* Ref.make<ReadonlyArray<OrchestrationV2ShellSnapshot>>([]);
492 const unenrichedSaveStarted = yield* Deferred.make<void>();
493 const releaseUnenrichedSave = yield* Deferred.make<void>();
494 const client = {
495 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () => Stream.fromQueue(events),
496 } as unknown as WsRpcProtocolClient;
497 const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
498 const activeSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
499 Option.some(session(client)),
500 );
501 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
502 target: TARGET,
503 state: supervisorState,
504 session: activeSession,
505 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
506 connect: Effect.void,
507 disconnect: Effect.void,
508 retryNow: Effect.void,
509 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
510 const cache = Persistence.EnvironmentCacheStore.of({
511 loadShell: () => Effect.succeed(Option.none()),
512 saveShell: (_environmentId, snapshot) =>
513 Effect.gen(function* () {
514 if (snapshot.projects[0]?.repositoryIdentity == null) {
515 yield* Deferred.succeed(unenrichedSaveStarted, undefined);
516 yield* Deferred.await(releaseUnenrichedSave);
517 }
518 yield* Ref.update(saved, (values) => [...values, snapshot]);
519 }),
520 loadThread: () => Effect.succeed(Option.none()),
521 saveThread: () => Effect.void,
522 removeThread: () => Effect.void,
523 loadServerConfig: () => Effect.succeed(Option.none()),
524 saveServerConfig: () => Effect.void,
525 loadVcsRefs: () => Effect.succeed(Option.none()),
526 saveVcsRefs: () => Effect.void,
527 removeVcsRefs: () => Effect.void,
528 clearVcsRefs: () => Effect.void,
529 clear: () => Effect.void,
530 });
531 const snapshotLoader = ShellSnapshotLoader.of({
532 load: () => Effect.succeed(Option.none()),
533 });
534​
535 const shellState = yield* makeEnvironmentShellState().pipe(
536 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
537 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
538 Effect.provideService(ShellSnapshotLoader, snapshotLoader),
539 );
540​
541 yield* SubscriptionRef.set(supervisorState, {
542 desired: true,
543 network: "online",
544 phase: "connecting",
545 stage: "synchronizing",
546 attempt: 1,
547 generation: 0,
548 lastFailure: null,
549 retryAt: null,
550 });
551 yield* Queue.offer(events, {
552 kind: "snapshot",
553 snapshot: unenrichedSnapshot,
554 });
555 yield* Queue.offer(events, { kind: "synchronized" });
556 yield* SubscriptionRef.changes(shellState).pipe(
557 Stream.filter((state) => state.status === "live"),
558 Stream.runHead,
559 );
560​
561 // Disconnect flush starts an immediate persist of the unenriched snapshot
562 // (debounced path needs TestClock advancement; flush does not).
563 yield* SubscriptionRef.set(supervisorState, {
564 desired: false,
565 network: "online",
566 phase: "available",
567 stage: null,
568 attempt: 1,
569 generation: 1,
570 lastFailure: null,
571 retryAt: null,
572 });
573 yield* Deferred.await(unenrichedSaveStarted);
574​
575 // Same sequence, different content. Session stays open so the stream can
576 // still apply enrichment while the older save is in flight.
577 yield* Queue.offer(events, {
578 kind: "snapshot",
579 snapshot: enrichedSnapshot,
580 });
581 yield* SubscriptionRef.changes(shellState).pipe(
582 Stream.filter(
583 (state) =>
584 Option.isSome(state.snapshot) &&
585 state.snapshot.value.projects[0]?.repositoryIdentity != null,
586 ),
587 Stream.runHead,
588 );
589​
590 // Completing the older same-sequence save must re-persist the latest object.
591 yield* Deferred.succeed(releaseUnenrichedSave, undefined);
592 for (let index = 0; index < 100; index += 1) {
593 const values = yield* Ref.get(saved);
594 if (values.length > 0 && values.at(-1)?.projects[0]?.repositoryIdentity != null) {
595 break;
596 }
597 yield* Effect.yieldNow;
598 }
599​
600 const finalSaved = (yield* Ref.get(saved)).at(-1);
601 expect(finalSaved?.snapshotSequence).toBe(1);
602 expect(finalSaved?.projects[0]?.repositoryIdentity).toEqual(repositoryIdentity);
603 }),
604 );
605​
606 it.effect("scope teardown flush stays stable while a save is blocked", () =>
607 Effect.gen(function* () {
608 const lateSnapshot: OrchestrationV2ShellSnapshot = {
609 ...LIVE_SHELL_SNAPSHOT,
610 snapshotSequence: 2,
611 projects: [{ ...v2Project, title: "Late stream event" }],
612 };
613 const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
614 const saved = yield* Ref.make<ReadonlyArray<OrchestrationV2ShellSnapshot>>([]);
615 const saveStarted = yield* Deferred.make<void>();
616 const releaseSave = yield* Deferred.make<void>();
617 const client = {
618 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () => Stream.fromQueue(events),
619 } as unknown as WsRpcProtocolClient;
620 const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
621 const activeSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
622 Option.some(session(client)),
623 );
624 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
625 target: TARGET,
626 state: supervisorState,
627 session: activeSession,
628 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
629 connect: Effect.void,
630 disconnect: Effect.void,
631 retryNow: Effect.void,
632 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
633 const cache = Persistence.EnvironmentCacheStore.of({
634 loadShell: () => Effect.succeed(Option.none()),
635 saveShell: (_environmentId, snapshot) =>
636 Deferred.succeed(saveStarted, undefined).pipe(
637 Effect.andThen(Deferred.await(releaseSave)),
638 Effect.andThen(Ref.update(saved, (values) => [...values, snapshot])),
639 ),
640 loadThread: () => Effect.succeed(Option.none()),
641 saveThread: () => Effect.void,
642 removeThread: () => Effect.void,
643 loadServerConfig: () => Effect.succeed(Option.none()),
644 saveServerConfig: () => Effect.void,
645 loadVcsRefs: () => Effect.succeed(Option.none()),
646 saveVcsRefs: () => Effect.void,
647 removeVcsRefs: () => Effect.void,
648 clearVcsRefs: () => Effect.void,
649 clear: () => Effect.void,
650 });
651 const snapshotLoader = ShellSnapshotLoader.of({
652 load: () => Effect.succeed(Option.none()),
653 });
654​
655 const scope = yield* Scope.make();
656 const shellState = yield* makeEnvironmentShellState().pipe(
657 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
658 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
659 Effect.provideService(ShellSnapshotLoader, snapshotLoader),
660 Scope.provide(scope),
661 );
662​
663 yield* SubscriptionRef.set(supervisorState, {
664 desired: true,
665 network: "online",
666 phase: "connecting",
667 stage: "synchronizing",
668 attempt: 1,
669 generation: 0,
670 lastFailure: null,
671 retryAt: null,
672 });
673 yield* Queue.offer(events, {
674 kind: "snapshot",
675 snapshot: LIVE_SHELL_SNAPSHOT,
676 });
677 yield* Queue.offer(events, { kind: "synchronized" });
678 yield* SubscriptionRef.changes(shellState).pipe(
679 Stream.filter((state) => state.status === "live"),
680 Stream.runHead,
681 );
682​
683 // Close scope so the finalizer flush blocks on save. Workers must be
684 // interrupted before that flush; late stream events must not extend it.
685 const closeFiber = yield* Effect.forkChild(Scope.close(scope, Exit.void));
686 yield* Deferred.await(saveStarted);
687 yield* Queue.offer(events, {
688 kind: "snapshot",
689 snapshot: lateSnapshot,
690 });
691 for (let index = 0; index < 50; index += 1) {
692 yield* Effect.yieldNow;
693 }
694 yield* Deferred.succeed(releaseSave, undefined);
695 yield* Fiber.join(closeFiber);
696​
697 const values = yield* Ref.get(saved);
698 expect(values.length).toBeGreaterThan(0);
699 expect(values.every((snapshot) => snapshot.snapshotSequence === 1)).toBe(true);
700 expect(values.every((snapshot) => snapshot.projects[0]?.title !== "Late stream event")).toBe(
701 true,
702 );
703 }),
704 );
705​
706 it.effect("applies authoritative lower-sequence HTTP resets over client-ahead cache", () =>
707 Effect.gen(function* () {
708 const cachedSnapshot: OrchestrationV2ShellSnapshot = {
709 ...v2ShellSnapshot,
710 snapshotSequence: 20,
711 projects: [{ ...v2Project, title: "Client ahead" }],
712 };
713 const httpSnapshot: OrchestrationV2ShellSnapshot = {
714 ...v2ShellSnapshot,
715 snapshotSequence: 4,
716 projects: [{ ...v2Project, title: "Server reset" }],
717 };
718 const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
719 const client = {
720 [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () => Stream.fromQueue(events),
721 } as unknown as WsRpcProtocolClient;
722 const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE);
723 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
724 target: TARGET,
725 state: supervisorState,
726 session: yield* SubscriptionRef.make(Option.some(session(client))),
727 prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
728 connect: Effect.void,
729 disconnect: Effect.void,
730 retryNow: Effect.void,
731 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
732 const cache = Persistence.EnvironmentCacheStore.of({
733 loadShell: () => Effect.succeed(Option.some(cachedSnapshot)),
734 saveShell: () => Effect.void,
735 loadThread: () => Effect.succeed(Option.none()),
736 saveThread: () => Effect.void,
737 removeThread: () => Effect.void,
738 loadServerConfig: () => Effect.succeed(Option.none()),
739 saveServerConfig: () => Effect.void,
740 loadVcsRefs: () => Effect.succeed(Option.none()),
741 saveVcsRefs: () => Effect.void,
742 removeVcsRefs: () => Effect.void,
743 clearVcsRefs: () => Effect.void,
744 clear: () => Effect.void,
745 });
746 const snapshotLoader = ShellSnapshotLoader.of({
747 load: () => Effect.succeed(Option.some(httpSnapshot)),
748 });
749 const shellState = yield* makeEnvironmentShellState().pipe(
750 Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
751 Effect.provideService(Persistence.EnvironmentCacheStore, cache),
752 Effect.provideService(ShellSnapshotLoader, snapshotLoader),
753 );
754​
755 yield* SubscriptionRef.changes(shellState).pipe(
756 Stream.filter(
757 (state) => Option.isSome(state.snapshot) && state.snapshot.value.snapshotSequence === 4,
758 ),
759 Stream.runHead,
760 );
761​
762 const state = yield* SubscriptionRef.get(shellState);
763 expect(Option.getOrThrow(state.snapshot).snapshotSequence).toBe(4);
764 expect(Option.getOrThrow(state.snapshot).projects[0]?.title).toBe("Server reset");
765 }),
766 );
767});