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