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