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

runtime.test.ts

1,223 lines43.8 KB

1import { describe, expect, it } from "@effect/vitest";
2import {
3 EnvironmentId,
4 type PreviewEvent,
5 type TerminalAttachInput,
6 type TerminalAttachStreamEvent,
7 type TerminalMetadataStreamEvent,
8 type TerminalSummary,
9 WS_METHODS,
10} from "@t3tools/contracts";
11import * as Cause from "effect/Cause";
12import * as Deferred from "effect/Deferred";
13import * as Effect from "effect/Effect";
14import * as Exit from "effect/Exit";
15import * as Latch from "effect/Latch";
16import * as Layer from "effect/Layer";
17import * as Option from "effect/Option";
18import * as Queue from "effect/Queue";
19import * as Schema from "effect/Schema";
20import * as Stream from "effect/Stream";
21import * as SubscriptionRef from "effect/SubscriptionRef";
22import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
23​
24import {
25 AVAILABLE_CONNECTION_STATE,
26 ConnectionBlockedError,
27 ConnectionTransientError,
28 PrimaryConnectionTarget,
29 type PreparedConnection,
30 type SupervisorConnectionState,
31} from "../connection/model.ts";
32import * as EnvironmentRegistry from "../connection/registry.ts";
33import * as EnvironmentSupervisor from "../connection/supervisor.ts";
34import { EnvironmentRpcUnavailableError } from "../rpc/client.ts";
35import type * as RpcSession from "../rpc/session.ts";
36import { createPreviewEnvironmentAtoms } from "./preview.ts";
37import type { QueryPersistence } from "./queryPersistence.ts";
38import { createTerminalEnvironmentAtoms } from "./terminal.ts";
39import {
40 createAtomCommandScheduler,
41 createEnvironmentQueryAtomFamily,
42 selectEnvironmentQueryData,
43 createEnvironmentSubscriptionAtomFamily,
44 createRuntimeCommand,
45 scheduleAtomCommandEffect,
46 executeAtomQuery,
47 type QueryAnswerHandler,
48} from "./runtime.ts";
49​
50const QUERY_ENVIRONMENT = new PrimaryConnectionTarget({
51 environmentId: EnvironmentId.make("query-environment"),
52 label: "Query environment",
53 httpBaseUrl: "https://query.example.test",
54 wsBaseUrl: "wss://query.example.test",
55});
56​
57const QUERY_RPC_SESSION = {} as RpcSession.RpcSession;
58​
59class TestQueryError extends Schema.TaggedError<TestQueryError>()("TestQueryError", {
60 message: Schema.String,
61}) {}
62​
63const OFFLINE_QUERY_FAILURE = new ConnectionTransientError({
64 reason: "transport",
65 detail: "Relay is unavailable.",
66});
67​
68const BLOCKED_QUERY_FAILURE = new ConnectionBlockedError({
69 reason: "permission",
70 detail: "Access denied.",
71});
72​
73function queryConnectionState(
74 overrides: Partial<SupervisorConnectionState> = {},
75): SupervisorConnectionState {
76 return {
77 ...AVAILABLE_CONNECTION_STATE,
78 desired: true,
79 network: "online",
80 phase: "connected",
81 attempt: 1,
82 generation: 1,
83 ...overrides,
84 };
86​
87const makeEnvironmentQueryHarness = Effect.fn("TestEnvironmentQuery.makeHarness")(function* <A, E>(
88 execute: Effect.Effect<A, E>,
89 {
90 refreshTrigger,
91 idleTtlMs,
92 persistence,
93 initialState,
94 rpcSession,
95 isFinal,
96 onAnswer,
97 }: {
98 readonly refreshTrigger?: Atom.Atom<unknown>;
99 readonly onAnswer?: QueryAnswerHandler<undefined, A>;
100 readonly isFinal?: (value: A) => boolean;
101 readonly idleTtlMs?: number;
102 readonly persistence?: QueryPersistence<A>;
103 readonly initialState?: SupervisorConnectionState;
104 readonly rpcSession?: RpcSession.RpcSession;
105 } = {},
106) {
107 const supervisorState = yield* SubscriptionRef.make(initialState ?? queryConnectionState());
108 const supervisorSession = yield* SubscriptionRef.make(
109 Option.some(rpcSession ?? QUERY_RPC_SESSION),
110 );
111 const streamGeneration = yield* SubscriptionRef.make(0);
112 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
113 target: QUERY_ENVIRONMENT,
114 state: supervisorState,
115 session: supervisorSession,
116 prepared: yield* SubscriptionRef.make<Option.Option<PreparedConnection>>(Option.none()),
117 connect: Effect.void,
118 disconnect: Effect.void,
119 retryNow: Effect.void,
120 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
121 const run: EnvironmentRegistry.EnvironmentRegistry["Service"]["run"] = (_environmentId, effect) =>
122 Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor);
123 const followStream: EnvironmentRegistry.EnvironmentRegistry["Service"]["followStream"] = (
124 _environmentId,
125 stream,
126 ) =>
127 SubscriptionRef.changes(streamGeneration).pipe(
128 Stream.switchMap(() =>
129 Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
130 ),
131 );
132 const environmentRegistry = EnvironmentRegistry.EnvironmentRegistry.of({
133 run,
134 followStream,
135 stateChanges: () => SubscriptionRef.changes(supervisorState),
136 } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]);
137 const runtime = Atom.runtime(
138 Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
139 );
140 const family = createEnvironmentQueryAtomFamily(runtime, {
141 label: "test.environment-query",
142 staleTimeMs: 60_000,
143 ...(persistence === undefined ? {} : { persistence }),
144 execute: () => execute,
145 ...(refreshTrigger === undefined ? {} : { refreshTrigger: () => refreshTrigger }),
146 ...(idleTtlMs === undefined ? {} : { idleTtlMs }),
147 ...(isFinal === undefined ? {} : { isFinal }),
148 ...(onAnswer === undefined ? {} : { onAnswer }),
149 });
150​
151 return {
152 runtime,
153 atom: family({ environmentId: QUERY_ENVIRONMENT.environmentId, input: undefined }),
154 supervisorSession,
155 supervisorState,
156 streamGeneration,
157 };
158});
159​
160/**
161 * `getResult` resumes from inside the query's listener, so it only unsubscribes
162 * once the reader yields.
163 */
164const readEnvironmentQuery = <A, E>(
165 registry: AtomRegistry.AtomRegistry,
166 atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>,
167) =>
168 AtomRegistry.getResult(registry, atom, { suspendOnWaiting: true }).pipe(
169 Effect.tap(() => Effect.yieldNow),
170 );
171​
172const mountEnvironmentQuery = Effect.fn("TestEnvironmentQuery.mount")(function* <A, E>(
173 atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>,
174) {
175 const registry = AtomRegistry.make();
176 const unmount = registry.mount(atom);
177 yield* Effect.addFinalizer(() =>
178 Effect.sync(() => {
179 unmount();
180 registry.dispose();
181 }),
182 );
183 return registry;
184});
185​
186describe("preview event subscriptions", () => {
187 it.effect("delivers every open and close when RPC events arrive in batches", () =>
188 Effect.scoped(
189 Effect.gen(function* () {
190 const opened: PreviewEvent[] = ["thread-a", "thread-b"].map((threadId, index) => ({
191 type: "opened",
192 threadId,
193 tabId: `tab-${index}`,
194 serverEpoch: "epoch-1",
195 revision: index + 1,
196 createdAt: "2026-10-02T00:00:00.000Z",
197 snapshot: {
198 threadId,
199 tabId: `tab-${index}`,
200 navStatus: { _tag: "Idle" },
201 canGoBack: false,
202 canGoForward: false,
203 updatedAt: "2026-10-02T00:00:00.000Z",
204 },
205 }));
206 const closed: PreviewEvent[] = opened.map((event, index) => ({
207 type: "closed",
208 threadId: event.threadId,
209 tabId: event.tabId,
210 serverEpoch: event.serverEpoch,
211 revision: opened.length + index + 1,
212 createdAt: event.createdAt,
213 }));
214 const releaseEvents = yield* Deferred.make<void>();
215 // Each iterable is one RPC chunk; separate emissions would hide lost events.
216 const stream = Stream.fromEffect(Deferred.await(releaseEvents)).pipe(
217 Stream.flatMap(() =>
218 Stream.fromIterable(opened).pipe(
219 Stream.concat(Stream.fromIterable(closed)),
220 Stream.concat(Stream.never),
221 ),
222 ),
223 );
224 const harness = yield* makeEnvironmentQueryHarness(Effect.void, {
225 rpcSession: {
226 client: { [WS_METHODS.subscribePreviewEvents]: () => stream },
227 } as unknown as RpcSession.RpcSession,
228 });
229 const atom = createPreviewEnvironmentAtoms(harness.runtime).events({
230 environmentId: QUERY_ENVIRONMENT.environmentId,
231 input: {},
232 });
233 const registry = AtomRegistry.make();
234 const observed: PreviewEvent[] = [];
235 const sawLast = yield* Deferred.make<void>();
236 const unsubscribe = registry.subscribe(
237 atom,
238 (result) => {
239 if (!AsyncResult.isSuccess(result)) return;
240 observed.push(result.value);
241 if (result.value === closed[closed.length - 1]) {
242 Deferred.doneUnsafe(sawLast, Exit.void);
243 }
244 },
245 { immediate: true },
246 );
247 yield* Effect.addFinalizer(() =>
248 Effect.sync(() => {
249 unsubscribe();
250 registry.dispose();
251 }),
252 );
253​
254 yield* Deferred.succeed(releaseEvents, undefined);
255 yield* Deferred.await(sawLast);
256 expect(observed).toEqual([...opened, ...closed]);
257 }),
258 ),
259 );
260});
261​
262describe("finite environment subscription lifecycle", () => {
263 it.effect(
264 "exposes early values and settles on the terminal value without waiting for a reconnect",
265 () =>
266 Effect.scoped(
267 Effect.gen(function* () {
268 const releaseFinal = yield* Deferred.make<void>();
269 const sawEarly = yield* Deferred.make<void>();
270 const sawFinal = yield* Deferred.make<void>();
271 const closed = yield* Deferred.make<void>();
272 const stream = Stream.concat(
273 Stream.succeed({ complete: false, count: 1 }),
274 Stream.fromEffect(
275 Deferred.await(releaseFinal).pipe(Effect.as({ complete: true, count: 123 })),
276 ),
277 ).pipe(Stream.ensuring(Deferred.succeed(closed, undefined)));
278 const environmentRegistry = EnvironmentRegistry.EnvironmentRegistry.of({
279 followStream: (_environmentId: EnvironmentId, source: typeof stream) =>
280 Stream.concat(source, Stream.never),
281 } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]);
282 const runtime = Atom.runtime(
283 Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
284 );
285 const family = createEnvironmentSubscriptionAtomFamily(runtime, {
286 label: "test.finite-subscription",
287 subscribe: () => stream,
288 completeWhen: (value) => value.complete,
289 idleTtlMs: 0,
290 });
291 const atom = family({ environmentId: QUERY_ENVIRONMENT.environmentId, input: undefined });
292 const registry = AtomRegistry.make();
293 const observed: Array<
294 AsyncResult.AsyncResult<{ complete: boolean; count: number }, unknown>
295 > = [];
296 const unsubscribe = registry.subscribe(
297 atom,
298 (result) => {
299 observed.push(result);
300 if (AsyncResult.isSuccess(result)) {
301 if (!result.value.complete) Deferred.doneUnsafe(sawEarly, Exit.void);
302 if (result.value.complete && !result.waiting)
303 Deferred.doneUnsafe(sawFinal, Exit.void);
304 }
305 },
306 { immediate: true },
307 );
308 yield* Effect.addFinalizer(() =>
309 Effect.sync(() => {
310 unsubscribe();
311 registry.dispose();
312 }),
313 );
314 yield* Deferred.await(sawEarly);
315 const early = registry.get(atom);
316 expect(AsyncResult.isSuccess(early) && early.value.count).toBe(1);
317 expect(early.waiting).toBe(true);
318 yield* Deferred.succeed(releaseFinal, undefined);
319 yield* Deferred.await(sawFinal);
320 yield* Deferred.await(closed);
321 const final = registry.get(atom);
322 expect(AsyncResult.isSuccess(final) && final.value.count).toBe(123);
323 expect(final.waiting).toBe(false);
324 expect(observed.some((result) => AsyncResult.isFailure(result))).toBe(false);
325 }),
326 ),
327 );
328});
329​
330describe("environment query lifecycle", () => {
331 it.effect(
332 "terminal metadata waits for snapshots and retains known sessions across restarts",
333 () =>
334 Effect.gen(function* () {
335 const harness = yield* makeEnvironmentQueryHarness(Effect.void);
336 const started = yield* Queue.unbounded<void>();
337 const events = yield* Queue.unbounded<TerminalMetadataStreamEvent>();
338 const receivedCheckout = yield* Deferred.make<void>();
339 const receivedEmpty = yield* Deferred.make<void>();
340 const checkout: TerminalSummary = {
341 threadId: "thread-1",
342 terminalId: "terminal-1",
343 cwd: "/repo/root/packages/app",
344 worktreePath: null,
345 status: "running",
346 pid: 123,
347 exitCode: null,
348 exitSignal: null,
349 hasRunningSubprocess: false,
350 label: "Terminal 1",
351 updatedAt: "2026-04-01T00:00:00.000Z",
352 };
353 const client = {
354 [WS_METHODS.subscribeTerminalMetadata]: () =>
355 Stream.fromEffect(Queue.offer(started, undefined)).pipe(
356 Stream.drain,
357 Stream.concat(Stream.fromQueue(events)),
358 ),
359 } as unknown as RpcSession.RpcSession["client"];
360 const session = { ...QUERY_RPC_SESSION, client };
361 yield* SubscriptionRef.set(harness.supervisorSession, Option.some(session));
362 const atoms = createTerminalEnvironmentAtoms(harness.runtime);
363 const atom = atoms.metadata({
364 environmentId: QUERY_ENVIRONMENT.environmentId,
365 input: null,
366 });
367 const registry = AtomRegistry.make();
368 const observed: Array<ReadonlyArray<TerminalSummary>> = [];
369 const unsubscribe = registry.subscribe(
370 atom,
371 (result) => {
372 if (!AsyncResult.isSuccess(result)) return;
373 observed.push(result.value);
374 if (result.value.length > 0) Deferred.doneUnsafe(receivedCheckout, Exit.void);
375 else Deferred.doneUnsafe(receivedEmpty, Exit.void);
376 },
377 { immediate: true },
378 );
379 yield* Effect.addFinalizer(() =>
380 Effect.sync(() => {
381 unsubscribe();
382 registry.dispose();
383 }),
384 );
385​
386 yield* Queue.take(started);
387 expect(selectEnvironmentQueryData(registry.get(atom))).toBeNull();
388 expect(observed).toEqual([]);
389​
390 yield* Queue.offer(events, { type: "snapshot", terminals: [checkout] });
391 yield* Deferred.await(receivedCheckout);
392 expect(selectEnvironmentQueryData(registry.get(atom))).toEqual([checkout]);
393​
394 yield* SubscriptionRef.set(harness.supervisorSession, Option.some({ ...session }));
395 yield* Queue.take(started);
396 expect(selectEnvironmentQueryData(registry.get(atom))).toEqual([checkout]);
397​
398 yield* SubscriptionRef.update(harness.streamGeneration, (generation) => generation + 1);
399 yield* Queue.take(started);
400 expect(selectEnvironmentQueryData(registry.get(atom))).toEqual([checkout]);
401​
402 yield* Queue.offer(events, { type: "snapshot", terminals: [] });
403 yield* Deferred.await(receivedEmpty);
404 expect(selectEnvironmentQueryData(registry.get(atom))).toEqual([]);
405 }),
406 );
407​
408 it.effect("terminal attach resubscribes with resume only after the stream replied", () =>
409 Effect.gen(function* () {
410 const harness = yield* makeEnvironmentQueryHarness(Effect.void);
411 const inputs = yield* Queue.unbounded<TerminalAttachInput>();
412 const events = yield* Queue.unbounded<TerminalAttachStreamEvent>();
413 const received = yield* Deferred.make<void>();
414 const client = {
415 [WS_METHODS.terminalAttach]: (input: TerminalAttachInput) =>
416 Stream.fromEffect(Queue.offer(inputs, input)).pipe(
417 Stream.drain,
418 Stream.concat(Stream.fromQueue(events)),
419 ),
420 } as unknown as RpcSession.RpcSession["client"];
421 const firstSession = { ...QUERY_RPC_SESSION, client };
422 yield* SubscriptionRef.set(harness.supervisorSession, Option.some(firstSession));
423 const input = {
424 threadId: "thread-1",
425 terminalId: "terminal-1",
426 cwd: "/tmp/project",
427 restartIfNotRunning: true,
428 };
429 const atoms = createTerminalEnvironmentAtoms(harness.runtime);
430 const registry = AtomRegistry.make();
431 const atom = atoms.attach({ environmentId: QUERY_ENVIRONMENT.environmentId, input });
432 const unmount = registry.subscribe(
433 atom,
434 (result) => {
435 if (AsyncResult.isSuccess(result) && result.value.version > 0) {
436 Deferred.doneUnsafe(received, Exit.void);
437 }
438 },
439 { immediate: true },
440 );
441 yield* Effect.addFinalizer(() =>
442 Effect.sync(() => {
443 unmount();
444 registry.dispose();
445 }),
446 );
447​
448 expect(yield* Queue.take(inputs)).toEqual(input);
449 yield* SubscriptionRef.set(harness.supervisorSession, Option.some({ ...firstSession }));
450 expect(yield* Queue.take(inputs)).toEqual(input);
451 yield* Queue.offer(events, {
452 type: "closed",
453 threadId: input.threadId,
454 terminalId: input.terminalId,
455 });
456 yield* Deferred.await(received);
457​
458 yield* SubscriptionRef.set(harness.supervisorSession, Option.some({ ...firstSession }));
459 expect(yield* Queue.take(inputs)).toEqual({ ...input, resume: true });
460 // Catalog replacements rerun the same stream through followStream's switchMap.
461 yield* SubscriptionRef.update(harness.streamGeneration, (generation) => generation + 1);
462 expect(yield* Queue.take(inputs)).toEqual({ ...input, resume: true });
463​
464 unmount();
465 registry.dispose();
466 const remountedRegistry = AtomRegistry.make();
467 const remount = remountedRegistry.subscribe(atom, () => {}, { immediate: true });
468 yield* Effect.addFinalizer(() =>
469 Effect.sync(() => {
470 remount();
471 remountedRegistry.dispose();
472 }),
473 );
474 expect(yield* Queue.take(inputs)).toEqual(input);
475 }),
476 );
477​
478 it.effect(
479 "retries an interrupted query without exposing a failure during session replacement",
480 () =>
481 Effect.scoped(
482 Effect.gen(function* () {
483 const firstStarted = Latch.makeUnsafe();
484 const failFirst = Latch.makeUnsafe();
485 const firstSettled = Latch.makeUnsafe();
486 const unavailable = new EnvironmentRpcUnavailableError({
487 environmentId: QUERY_ENVIRONMENT.environmentId,
488 message: "Query environment is not connected.",
489 });
490 let executions = 0;
491 const execute = Effect.suspend(() => {
492 executions += 1;
493 if (executions > 1) {
494 return Effect.succeed("recovered");
495 }
496 firstStarted.openUnsafe();
497 return failFirst.await.pipe(
498 Effect.andThen(Effect.fail(unavailable)),
499 Effect.ensuring(
500 Effect.sync(() => {
501 firstSettled.openUnsafe();
502 }),
503 ),
504 );
505 });
506 const harness = yield* makeEnvironmentQueryHarness(execute);
507 const registry = AtomRegistry.make();
508 const observed: Array<AsyncResult.AsyncResult<string, unknown>> = [];
509 const unsubscribe = registry.subscribe(
510 harness.atom,
511 (result) => {
512 observed.push(result);
513 },
514 { immediate: true },
515 );
516 yield* Effect.addFinalizer(() =>
517 Effect.sync(() => {
518 unsubscribe();
519 registry.dispose();
520 }),
521 );
522​
523 yield* firstStarted.await;
524 yield* SubscriptionRef.set(harness.supervisorSession, Option.none());
525 yield* Effect.yieldNow;
526 failFirst.openUnsafe();
527 yield* firstSettled.await;
528 yield* Effect.yieldNow;
529​
530 expect(observed.some(AsyncResult.isFailure)).toBe(false);
531​
532 yield* SubscriptionRef.set(
533 harness.supervisorState,
534 queryConnectionState({ phase: "connecting", stage: "preparing" }),
535 );
536 yield* Effect.yieldNow;
537 yield* SubscriptionRef.set(
538 harness.supervisorState,
539 queryConnectionState({
540 phase: "backoff",
541 stage: null,
542 lastFailure: new ConnectionTransientError({
543 reason: "transport",
544 detail: "Relay session is reconnecting.",
545 }),
546 retryAt: 1,
547 }),
548 );
549 yield* Effect.yieldNow;
550​
551 yield* SubscriptionRef.set(harness.supervisorSession, Option.some(QUERY_RPC_SESSION));
552 yield* SubscriptionRef.set(
553 harness.supervisorState,
554 queryConnectionState({ generation: 2 }),
555 );
556 expect(
557 yield* AtomRegistry.getResult(registry, harness.atom, {
558 suspendOnWaiting: true,
559 }),
560 ).toBe("recovered");
561 }),
562 ),
563 );
564​
565 it.effect("keeps a query pending when it loses its session before the atom sees the change", () =>
566 Effect.scoped(
567 Effect.gen(function* () {
568 const firstStarted = Latch.makeUnsafe();
569 const failFirst = Latch.makeUnsafe();
570 const firstSettled = Latch.makeUnsafe();
571 let executions = 0;
572 const execute = Effect.suspend(() => {
573 executions += 1;
574 if (executions > 1) {
575 return Effect.succeed("recovered");
576 }
577 firstStarted.openUnsafe();
578 return failFirst.await.pipe(
579 Effect.andThen(
580 Effect.fail(
581 new EnvironmentRpcUnavailableError({
582 environmentId: QUERY_ENVIRONMENT.environmentId,
583 message: "Query environment is not connected.",
584 }),
585 ),
586 ),
587 Effect.ensuring(
588 Effect.sync(() => {
589 firstSettled.openUnsafe();
590 }),
591 ),
592 );
593 });
594 const harness = yield* makeEnvironmentQueryHarness(execute);
595 const registry = AtomRegistry.make();
596 const observed: Array<AsyncResult.AsyncResult<string, unknown>> = [];
597 const unsubscribe = registry.subscribe(
598 harness.atom,
599 (result) => {
600 observed.push(result);
601 },
602 { immediate: true },
603 );
604 yield* Effect.addFinalizer(() =>
605 Effect.sync(() => {
606 unsubscribe();
607 registry.dispose();
608 }),
609 );
610​
611 yield* firstStarted.await;
612 // No yield before the failure: the request finds its session gone
613 // before the atom has processed the session change.
614 yield* SubscriptionRef.set(harness.supervisorSession, Option.none());
615 failFirst.openUnsafe();
616 yield* firstSettled.await;
617 yield* Effect.yieldNow;
618​
619 expect(observed.some(AsyncResult.isFailure)).toBe(false);
620​
621 yield* SubscriptionRef.set(harness.supervisorSession, Option.some(QUERY_RPC_SESSION));
622 yield* SubscriptionRef.set(
623 harness.supervisorState,
624 queryConnectionState({ generation: 2 }),
625 );
626 expect(
627 yield* AtomRegistry.getResult(registry, harness.atom, {
628 suspendOnWaiting: true,
629 }),
630 ).toBe("recovered");
631 expect(observed.some(AsyncResult.isFailure)).toBe(false);
632 }),
633 ),
634 );
635​
636 it.effect("fails a query that reports unavailable while its session is still live", () =>
637 Effect.scoped(
638 Effect.gen(function* () {
639 const unavailable = new EnvironmentRpcUnavailableError({
640 environmentId: QUERY_ENVIRONMENT.environmentId,
641 message: "The environment did not respond to the request.",
642 });
643 const harness = yield* makeEnvironmentQueryHarness(Effect.fail(unavailable));
644 const registry = yield* mountEnvironmentQuery(harness.atom);
645​
646 const exit = yield* AtomRegistry.getResult(registry, harness.atom, {
647 suspendOnWaiting: true,
648 }).pipe(Effect.exit);
649​
650 expect(exit).toStrictEqual(Exit.fail(unavailable));
651 }),
652 ),
653 );
654​
655 it.effect.each([
656 {
657 condition: "after a manual disconnect",
658 state: queryConnectionState({
659 desired: false,
660 phase: "available",
661 stage: null,
662 attempt: 0,
663 }),
664 expectedFailure: null,
665 },
666 {
667 condition: "while the environment is offline",
668 state: queryConnectionState({
669 network: "offline",
670 phase: "offline",
671 stage: null,
672 lastFailure: OFFLINE_QUERY_FAILURE,
673 }),
674 expectedFailure: OFFLINE_QUERY_FAILURE,
675 },
676 {
677 condition: "when connection recovery is blocked",
678 state: queryConnectionState({
679 phase: "blocked",
680 stage: null,
681 lastFailure: BLOCKED_QUERY_FAILURE,
682 }),
683 expectedFailure: BLOCKED_QUERY_FAILURE,
684 },
685 ] as const)("settles as unavailable $condition", ({ state, expectedFailure }) =>
686 Effect.scoped(
687 Effect.gen(function* () {
688 const harness = yield* makeEnvironmentQueryHarness(Effect.succeed("connected"));
689 const registry = yield* mountEnvironmentQuery(harness.atom);
690​
691 expect(
692 yield* AtomRegistry.getResult(registry, harness.atom, {
693 suspendOnWaiting: true,
694 }),
695 ).toBe("connected");
696​
697 yield* SubscriptionRef.set(harness.supervisorState, state);
698 yield* Effect.yieldNow;
699​
700 const result = registry.get(harness.atom);
701 expect(AsyncResult.isFailure(result)).toBe(true);
702 expect(result.waiting).toBe(false);
703 if (AsyncResult.isFailure(result) && expectedFailure !== null) {
704 expect(Cause.squash(result.cause)).toBe(expectedFailure);
705 }
706 }),
707 ),
708 );
709​
710 it.effect("keeps a genuine query failure settled while reconnecting", () =>
711 Effect.scoped(
712 Effect.gen(function* () {
713 const expectedFailure = new TestQueryError({ message: "Query failed." });
714 const firstStarted = Latch.makeUnsafe();
715 const failFirst = Latch.makeUnsafe();
716 const refreshStarted = Latch.makeUnsafe();
717 const finishRefresh = Latch.makeUnsafe();
718 let executions = 0;
719 const execute = Effect.suspend(() => {
720 executions += 1;
721 if (executions === 1) {
722 firstStarted.openUnsafe();
723 return failFirst.await.pipe(Effect.andThen(Effect.fail(expectedFailure)));
724 }
725 refreshStarted.openUnsafe();
726 return finishRefresh.await.pipe(Effect.as("recovered"));
727 });
728 const harness = yield* makeEnvironmentQueryHarness(execute);
729 const registry = yield* mountEnvironmentQuery(harness.atom);
730​
731 yield* firstStarted.await;
732 failFirst.openUnsafe();
733 const initial = yield* AtomRegistry.getResult(registry, harness.atom, {
734 suspendOnWaiting: true,
735 }).pipe(Effect.exit);
736 expect(Exit.isFailure(initial)).toBe(true);
737 if (Exit.isFailure(initial)) {
738 expect(Cause.squash(initial.cause)).toBe(expectedFailure);
739 }
740​
741 yield* SubscriptionRef.set(
742 harness.supervisorState,
743 queryConnectionState({ phase: "connecting", stage: "opening" }),
744 );
745 yield* Effect.yieldNow;
746​
747 const refreshing = registry.get(harness.atom);
748 expect(AsyncResult.isFailure(refreshing)).toBe(true);
749 expect(refreshing.waiting).toBe(true);
750 if (AsyncResult.isFailure(refreshing)) {
751 expect(Cause.squash(refreshing.cause)).toBe(expectedFailure);
752 }
753​
754 yield* SubscriptionRef.set(
755 harness.supervisorState,
756 queryConnectionState({ generation: 2 }),
757 );
758 yield* refreshStarted.await;
759 finishRefresh.openUnsafe();
760 expect(
761 yield* AtomRegistry.getResult(registry, harness.atom, {
762 suspendOnWaiting: true,
763 }),
764 ).toBe("recovered");
765 }),
766 ),
767 );
768​
769 it.effect("retains the last successful value while reconnecting", () =>
770 Effect.scoped(
771 Effect.gen(function* () {
772 const refreshStarted = Latch.makeUnsafe();
773 const finishRefresh = Latch.makeUnsafe();
774 let executions = 0;
775 const execute = Effect.suspend(() => {
776 executions += 1;
777 if (executions === 1) {
778 return Effect.succeed("cached");
779 }
780 refreshStarted.openUnsafe();
781 return finishRefresh.await.pipe(Effect.as("updated"));
782 });
783 const harness = yield* makeEnvironmentQueryHarness(execute);
784 const registry = yield* mountEnvironmentQuery(harness.atom);
785​
786 expect(
787 yield* AtomRegistry.getResult(registry, harness.atom, {
788 suspendOnWaiting: true,
789 }),
790 ).toBe("cached");
791​
792 yield* SubscriptionRef.set(
793 harness.supervisorState,
794 queryConnectionState({ phase: "connecting", stage: "opening" }),
795 );
796 yield* Effect.yieldNow;
797 expect(registry.get(harness.atom)).toMatchObject({
798 _tag: "Success",
799 value: "cached",
800 waiting: true,
801 });
802​
803 yield* SubscriptionRef.set(
804 harness.supervisorState,
805 queryConnectionState({
806 phase: "backoff",
807 stage: null,
808 lastFailure: new ConnectionTransientError({
809 reason: "transport",
810 detail: "Retrying.",
811 }),
812 retryAt: 1,
813 }),
814 );
815 yield* Effect.yieldNow;
816 expect(registry.get(harness.atom)).toMatchObject({
817 _tag: "Success",
818 value: "cached",
819 waiting: true,
820 });
821​
822 yield* SubscriptionRef.set(
823 harness.supervisorState,
824 queryConnectionState({ generation: 2 }),
825 );
826 yield* refreshStarted.await;
827 expect(registry.get(harness.atom)).toMatchObject({
828 _tag: "Success",
829 value: "cached",
830 waiting: true,
831 });
832​
833 finishRefresh.openUnsafe();
834 expect(
835 yield* AtomRegistry.getResult(registry, harness.atom, {
836 suspendOnWaiting: true,
837 }),
838 ).toBe("updated");
839 }),
840 ),
841 );
842​
843 it.effect("refreshes on its trigger while read, and once on its next read when idle", () =>
844 Effect.scoped(
845 Effect.gen(function* () {
846 let executions = 0;
847 const trigger = Atom.make(0).pipe(Atom.keepAlive);
848 const harness = yield* makeEnvironmentQueryHarness(
849 Effect.sync(() => (executions += 1)),
850 { refreshTrigger: trigger },
851 );
852 const registry = AtomRegistry.make();
853 yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
854 const read = readEnvironmentQuery(registry, harness.atom);
855​
856 const unmount = registry.mount(harness.atom);
857 expect(yield* read).toBe(1);
858 registry.set(trigger, 1);
859 expect(yield* read).toBe(2);
860​
861 unmount();
862 registry.set(trigger, 2);
863 registry.set(trigger, 3);
864 expect(executions).toBe(2);
865​
866 expect(yield* read).toBe(3);
867 }),
868 ),
869 );
870});
871​
872describe("executeAtomQuery", () => {
873 it("keeps concurrent query results correlated to their atoms", async () => {
874 const firstLatch = Latch.makeUnsafe();
875 const secondLatch = Latch.makeUnsafe();
876 const firstAtom = Atom.make(firstLatch.await.pipe(Effect.as("first")));
877 const secondAtom = Atom.make(secondLatch.await.pipe(Effect.as("second")));
878 const registry = AtomRegistry.make();
879​
880 const firstResult = executeAtomQuery(registry, firstAtom);
881 const secondResult = executeAtomQuery(registry, secondAtom);
882​
883 secondLatch.openUnsafe();
884 firstLatch.openUnsafe();
885​
886 const [first, second] = await Promise.all([firstResult, secondResult]);
887 expect(first._tag).toBe("Success");
888 expect(second._tag).toBe("Success");
889 if (first._tag === "Success" && second._tag === "Success") {
890 expect(first.value).toBe("first");
891 expect(second.value).toBe("second");
892 }
893​
894 registry.dispose();
895 });
896​
897 it("settles when its caller aborts a waiting query", async () => {
898 const registry = AtomRegistry.make();
899 const controller = new AbortController();
900 const resultPromise = executeAtomQuery(registry, Atom.make(Effect.never), {
901 reportDefect: false,
902 signal: controller.signal,
903 });
904​
905 controller.abort();
906​
907 const result = await resultPromise;
908 expect(result._tag).toBe("Failure");
909 if (result._tag === "Failure") {
910 expect(Cause.hasInterruptsOnly(result.cause)).toBe(true);
911 }
912 registry.dispose();
913 });
914});
915​
916describe("runtime command runner", () => {
917 it("settles generated command scheduler defects from direct callers", async () => {
918 const defect = new Error("invalid command key");
919 const runtime = Atom.runtime(Layer.empty);
920 const command = createRuntimeCommand(runtime, {
921 label: "test.invalid-key",
922 concurrency: {
923 mode: "serial",
924 key: () => {
925 throw defect;
926 },
927 },
928 execute: () => Effect.void,
929 });
930 const registry = AtomRegistry.make();
931​
932 const result = await command.run(registry, undefined);
933 expect(result._tag).toBe("Failure");
934 if (result._tag === "Failure") {
935 expect(Cause.hasDies(result.cause)).toBe(true);
936 expect(Cause.squash(result.cause)).toBe(defect);
937 }
938 registry.dispose();
939 });
940​
941 it("serializes commands that share a scheduler and lane", async () => {
942 const firstLatch = Latch.makeUnsafe();
943 const events: string[] = [];
944 const runtime = Atom.runtime(Layer.empty);
945 const scheduler = createAtomCommandScheduler();
946 const concurrency = { mode: "serial" as const, key: () => "shared" };
947 const firstCommand = createRuntimeCommand(runtime, {
948 label: "test.first",
949 scheduler,
950 concurrency,
951 execute: () =>
952 Effect.sync(() => events.push("first:start")).pipe(
953 Effect.andThen(firstLatch.await),
954 Effect.tap(() => Effect.sync(() => events.push("first:end"))),
955 ),
956 });
957 const secondCommand = createRuntimeCommand(runtime, {
958 label: "test.second",
959 scheduler,
960 concurrency,
961 execute: () => Effect.sync(() => events.push("second:start")),
962 });
963 const registry = AtomRegistry.make();
964​
965 const first = firstCommand.run(registry, undefined);
966 const second = secondCommand.run(registry, undefined);
967 await Promise.resolve();
968 expect(events).toEqual(["first:start"]);
969​
970 firstLatch.openUnsafe();
971 await Promise.all([first, second]);
972 expect(events).toEqual(["first:start", "first:end", "second:start"]);
973 registry.dispose();
974 });
975​
976 it.effect("releases a shared scheduler lane before the outer command finishes", () =>
977 Effect.gen(function* () {
978 const handoffStarted = Latch.makeUnsafe();
979 const handoffComplete = Latch.makeUnsafe();
980 const resumeComplete = Latch.makeUnsafe();
981 const runtime = Atom.runtime(Layer.empty);
982 const scheduler = createAtomCommandScheduler();
983 const concurrency = { mode: "serial" as const, key: () => "shared" };
984 const updateCommand = createRuntimeCommand(runtime, {
985 label: "test.update",
986 execute: (_input: void, registry) =>
987 scheduleAtomCommandEffect(
988 registry,
989 scheduler,
990 concurrency,
991 undefined,
992 Effect.sync(() => handoffStarted.openUnsafe()).pipe(
993 Effect.andThen(handoffComplete.await),
994 ),
995 ).pipe(Effect.andThen(resumeComplete.await)),
996 });
997 const configCommand = createRuntimeCommand(runtime, {
998 label: "test.config",
999 scheduler,
1000 concurrency,
1001 execute: () => Effect.succeed("configured"),
1002 });
1003 const registry = AtomRegistry.make();
1004​
1005 const update = updateCommand.run(registry, undefined);
1006 yield* handoffStarted.await;
1007 const config = configCommand.run(registry, undefined);
1008 handoffComplete.openUnsafe();
1009​
1010 expect(yield* Effect.promise(() => config)).toMatchObject({
1011 _tag: "Success",
1012 value: "configured",
1013 waiting: false,
1014 });
1015 resumeComplete.openUnsafe();
1016 expect(yield* Effect.promise(() => update)).toMatchObject({
1017 _tag: "Success",
1018 waiting: false,
1019 });
1020 registry.dispose();
1021 }),
1022 );
1023​
1024 it.effect("keeps an outer reconnect observer alive after a scheduled handoff returns", () =>
1025 Effect.gen(function* () {
1026 const commitStarting = yield* Deferred.make<void>();
1027 const observerArmed = yield* Deferred.make<void>();
1028 const reconnected = yield* Deferred.make<void>();
1029 const states = yield* Queue.unbounded<{ readonly phase: string }>();
1030 yield* Queue.offer(states, { phase: "connected" });
1031 const runtime = Atom.runtime(Layer.empty);
1032 const scheduler = createAtomCommandScheduler();
1033 const concurrency = { mode: "serial" as const, key: () => "shared" };
1034 const command = createRuntimeCommand(runtime, {
1035 label: "test.desktop-update-handoff",
1036 execute: (_input: void, registry) =>
1037 Effect.gen(function* () {
1038 yield* Deferred.await(commitStarting).pipe(
1039 Effect.andThen(
1040 Stream.fromQueue(states).pipe(
1041 Stream.tap(() => Deferred.succeed(observerArmed, undefined)),
1042 Stream.dropWhile((state) => state.phase === "connected"),
1043 Stream.filter((state) => state.phase === "connected"),
1044 Stream.runHead,
1045 ),
1046 ),
1047 Effect.andThen(Deferred.succeed(reconnected, undefined)),
1048 Effect.forkChild,
1049 );
1050 yield* scheduleAtomCommandEffect(
1051 registry,
1052 scheduler,
1053 concurrency,
1054 undefined,
1055 Deferred.succeed(commitStarting, undefined).pipe(
1056 Effect.andThen(Deferred.await(observerArmed)),
1057 ),
1058 );
1059 yield* Queue.offer(states, { phase: "backoff" });
1060 yield* Queue.offer(states, { phase: "connected" });
1061 yield* Deferred.await(reconnected);
1062 }),
1063 });
1064 const registry = AtomRegistry.make();
1065​
1066 expect(yield* Effect.promise(() => command.run(registry, undefined))).toMatchObject({
1067 _tag: "Success",
1068 });
1069 registry.dispose();
1070 }),
1071 );
1072​
1073 it("deduplicates single-flight commands by key", async () => {
1074 const latch = Latch.makeUnsafe();
1075 let executions = 0;
1076 const runtime = Atom.runtime(Layer.empty);
1077 const command = createRuntimeCommand(runtime, {
1078 label: "test.single-flight",
1079 concurrency: { mode: "singleFlight", key: (key: string) => key },
1080 execute: () =>
1081 Effect.sync(() => executions++).pipe(Effect.andThen(latch.await), Effect.as("done")),
1082 });
1083 const registry = AtomRegistry.make();
1084​
1085 const first = command.run(registry, "same");
1086 const second = command.run(registry, "same");
1087 latch.openUnsafe();
1088​
1089 expect(await first).toMatchObject({ _tag: "Success", value: "done", waiting: false });
1090 expect(await second).toMatchObject({ _tag: "Success", value: "done", waiting: false });
1091 expect(executions).toBe(1);
1092 registry.dispose();
1093 });
1094​
1095 it("coalesces pending latest-value commands without interrupting the active call", async () => {
1096 const firstLatch = Latch.makeUnsafe();
1097 const executed: number[] = [];
1098 const runtime = Atom.runtime(Layer.empty);
1099 const command = createRuntimeCommand(runtime, {
1100 label: "test.latest",
1101 concurrency: { mode: "latest", key: () => "shared" },
1102 execute: (value: number) =>
1103 Effect.sync(() => executed.push(value)).pipe(
1104 Effect.andThen(value === 1 ? firstLatch.await : Effect.void),
1105 Effect.as(value),
1106 ),
1107 });
1108 const registry = AtomRegistry.make();
1109​
1110 const first = command.run(registry, 1);
1111 await Promise.resolve();
1112 const second = command.run(registry, 2);
1113 const third = command.run(registry, 3);
1114 firstLatch.openUnsafe();
1115​
1116 expect(await first).toMatchObject({ _tag: "Success", value: 1, waiting: false });
1117 expect(await second).toMatchObject({ _tag: "Success", value: 3, waiting: false });
1118 expect(await third).toMatchObject({ _tag: "Success", value: 3, waiting: false });
1119 expect(executed).toEqual([1, 3]);
1120 registry.dispose();
1121 });
1122});
1123​
1124describe("persisted environment queries", () => {
1125 it.effect(
1126 "restores cached data in a new registry while offline, then refreshes on reconnect",
1127 () =>
1128 Effect.scoped(
1129 Effect.gen(function* () {
1130 let saved = Option.none<string>();
1131 const persistence: QueryPersistence<string> = {
1132 load: () => Effect.sync(() => saved),
1133 save: (_environmentId, _key, value) =>
1134 Effect.sync(() => {
1135 saved = Option.some(value);
1136 }),
1137 };
1138 const first = yield* makeEnvironmentQueryHarness(Effect.succeed("first"), {
1139 persistence,
1140 });
1141 const firstRegistry = yield* mountEnvironmentQuery(first.atom);
1142 expect(yield* readEnvironmentQuery(firstRegistry, first.atom)).toBe("first");
1143 expect(saved).toEqual(Option.some("first"));
1144​
1145 const restarted = yield* makeEnvironmentQueryHarness(Effect.succeed("updated"), {
1146 persistence,
1147 initialState: queryConnectionState({ phase: "offline", network: "offline" }),
1148 });
1149 const registry = yield* mountEnvironmentQuery(restarted.atom);
1150 expect(yield* readEnvironmentQuery(registry, restarted.atom)).toBe("first");
1151 yield* SubscriptionRef.set(restarted.supervisorState, queryConnectionState());
1152 yield* Effect.yieldNow;
1153 expect(yield* readEnvironmentQuery(registry, restarted.atom)).toBe("updated");
1154 expect(saved).toEqual(Option.some("updated"));
1155 }),
1156 ),
1157 );
1158​
1159 it.effect("hands each server answer to onAnswer before readers see it", () =>
1160 Effect.scoped(
1161 Effect.gen(function* () {
1162 const answers: Array<readonly [string, string | null]> = [];
1163 let served = 0;
1164 const recorded = Atom.make<string | null>(null).pipe(Atom.keepAlive);
1165 const harness = yield* makeEnvironmentQueryHarness(
1166 Effect.sync(() => `answer-${++served}`),
1168 onAnswer: (_target, value, registry) =>
1169 Effect.sync(() => {
1170 answers.push([value, registry.get(recorded)]);
1171 registry.set(recorded, value);
1172 }),
1173 },
1174 );
1175 const registry = yield* mountEnvironmentQuery(harness.atom);
1176 expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("answer-1");
1177 expect(registry.get(recorded)).toBe("answer-1");
1178 registry.refresh(harness.atom);
1179 expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("answer-2");
1180 expect(answers).toEqual([
1181 ["answer-1", null],
1182 ["answer-2", "answer-1"],
1183 ]);
1184 }),
1185 ),
1186 );
1187​
1188 it.effect("does not hand a value restored from persistence to onAnswer", () =>
1189 Effect.scoped(
1190 Effect.gen(function* () {
1191 const answers: Array<string> = [];
1192 const harness = yield* makeEnvironmentQueryHarness(Effect.succeed("server"), {
1193 persistence: { load: () => Effect.succeedSome("cached"), save: () => Effect.void },
1194 initialState: queryConnectionState({ phase: "offline", network: "offline" }),
1195 onAnswer: (_target, value) => Effect.sync(() => answers.push(value)),
1196 });
1197 const registry = yield* mountEnvironmentQuery(harness.atom);
1198 expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("cached");
1199 expect(answers).toEqual([]);
1200 yield* SubscriptionRef.set(harness.supervisorState, queryConnectionState());
1201 yield* Effect.yieldNow;
1202 expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("server");
1203 expect(answers).toEqual(["server"]);
1204 }),
1205 ),
1206 );
1207​
1208 it.effect("keeps cached content available when revalidation fails", () =>
1209 Effect.scoped(
1210 Effect.gen(function* () {
1211 const harness = yield* makeEnvironmentQueryHarness(
1212 Effect.fail(new TestQueryError({ message: "failed" })),
1214 persistence: { load: () => Effect.succeedSome("cached"), save: () => Effect.void },
1215 },
1216 );
1217 const registry = yield* mountEnvironmentQuery(harness.atom);
1218 yield* Effect.result(readEnvironmentQuery(registry, harness.atom));
1219 expect(Option.getOrNull(AsyncResult.value(registry.get(harness.atom)))).toBe("cached");
1220 }),
1221 ),
1222 );
1223});