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