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