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