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("keeps a query pending when it loses its session before the atom sees the change", () =>
521 Effect.scoped(
522 Effect.gen(function* () {
523 const firstStarted = Latch.makeUnsafe();
524 const failFirst = Latch.makeUnsafe();
525 const firstSettled = Latch.makeUnsafe();
526 let executions = 0;
527 const execute = Effect.suspend(() => {
528 executions += 1;
529 if (executions > 1) {
530 return Effect.succeed("recovered");
531 }
532 firstStarted.openUnsafe();
533 return failFirst.await.pipe(
534 Effect.andThen(
535 Effect.fail(
536 new EnvironmentRpcUnavailableError({
537 environmentId: QUERY_ENVIRONMENT.environmentId,
538 message: "Query environment is not connected.",
539 }),
540 ),
541 ),
542 Effect.ensuring(
543 Effect.sync(() => {
544 firstSettled.openUnsafe();
545 }),
546 ),
547 );
548 });
549 const harness = yield* makeEnvironmentQueryHarness(execute);
550 const registry = AtomRegistry.make();
551 const observed: Array<AsyncResult.AsyncResult<string, unknown>> = [];
552 const unsubscribe = registry.subscribe(
553 harness.atom,
554 (result) => {
555 observed.push(result);
556 },
557 { immediate: true },
558 );
559 yield* Effect.addFinalizer(() =>
560 Effect.sync(() => {
561 unsubscribe();
562 registry.dispose();
563 }),
564 );
565
566 yield* firstStarted.await;
567 // No yield before the failure: the request finds its session gone
568 // before the atom has processed the session change.
569 yield* SubscriptionRef.set(harness.supervisorSession, Option.none());
570 failFirst.openUnsafe();
571 yield* firstSettled.await;
572 yield* Effect.yieldNow;
573
574 expect(observed.some(AsyncResult.isFailure)).toBe(false);
575
576 yield* SubscriptionRef.set(harness.supervisorSession, Option.some(QUERY_RPC_SESSION));
577 yield* SubscriptionRef.set(
578 harness.supervisorState,
579 queryConnectionState({ generation: 2 }),
580 );
581 expect(
582 yield* AtomRegistry.getResult(registry, harness.atom, {
583 suspendOnWaiting: true,
584 }),
585 ).toBe("recovered");
586 expect(observed.some(AsyncResult.isFailure)).toBe(false);
587 }),
588 ),
589 );
590
591 it.effect("fails a query that reports unavailable while its session is still live", () =>
592 Effect.scoped(
593 Effect.gen(function* () {
594 const unavailable = new EnvironmentRpcUnavailableError({
595 environmentId: QUERY_ENVIRONMENT.environmentId,
596 message: "The environment did not respond to the request.",
597 });
598 const harness = yield* makeEnvironmentQueryHarness(Effect.fail(unavailable));
599 const registry = yield* mountEnvironmentQuery(harness.atom);
600
601 const exit = yield* AtomRegistry.getResult(registry, harness.atom, {
602 suspendOnWaiting: true,
603 }).pipe(Effect.exit);
604
605 expect(exit).toStrictEqual(Exit.fail(unavailable));
606 }),
607 ),
608 );
609
610 it.effect.each([
611 {
612 condition: "after a manual disconnect",
613 state: queryConnectionState({
614 desired: false,
615 phase: "available",
616 stage: null,
617 attempt: 0,
618 }),
619 expectedFailure: null,
620 },
621 {
622 condition: "while the environment is offline",
623 state: queryConnectionState({
624 network: "offline",
625 phase: "offline",
626 stage: null,
627 lastFailure: OFFLINE_QUERY_FAILURE,
628 }),
629 expectedFailure: OFFLINE_QUERY_FAILURE,
630 },
631 {
632 condition: "when connection recovery is blocked",
633 state: queryConnectionState({
634 phase: "blocked",
635 stage: null,
636 lastFailure: BLOCKED_QUERY_FAILURE,
637 }),
638 expectedFailure: BLOCKED_QUERY_FAILURE,
639 },
640 ] as const)("settles as unavailable $condition", ({ state, expectedFailure }) =>
641 Effect.scoped(
642 Effect.gen(function* () {
643 const harness = yield* makeEnvironmentQueryHarness(Effect.succeed("connected"));
644 const registry = yield* mountEnvironmentQuery(harness.atom);
645
646 expect(
647 yield* AtomRegistry.getResult(registry, harness.atom, {
648 suspendOnWaiting: true,
649 }),
650 ).toBe("connected");
651
652 yield* SubscriptionRef.set(harness.supervisorState, state);
653 yield* Effect.yieldNow;
654
655 const result = registry.get(harness.atom);
656 expect(AsyncResult.isFailure(result)).toBe(true);
657 expect(result.waiting).toBe(false);
658 if (AsyncResult.isFailure(result) && expectedFailure !== null) {
659 expect(Cause.squash(result.cause)).toBe(expectedFailure);
660 }
661 }),
662 ),
663 );
664
665 it.effect("keeps a genuine query failure settled while reconnecting", () =>
666 Effect.scoped(
667 Effect.gen(function* () {
668 const expectedFailure = new TestQueryError({ message: "Query failed." });
669 const firstStarted = Latch.makeUnsafe();
670 const failFirst = Latch.makeUnsafe();
671 const refreshStarted = Latch.makeUnsafe();
672 const finishRefresh = Latch.makeUnsafe();
673 let executions = 0;
674 const execute = Effect.suspend(() => {
675 executions += 1;
676 if (executions === 1) {
677 firstStarted.openUnsafe();
678 return failFirst.await.pipe(Effect.andThen(Effect.fail(expectedFailure)));
679 }
680 refreshStarted.openUnsafe();
681 return finishRefresh.await.pipe(Effect.as("recovered"));
682 });
683 const harness = yield* makeEnvironmentQueryHarness(execute);
684 const registry = yield* mountEnvironmentQuery(harness.atom);
685
686 yield* firstStarted.await;
687 failFirst.openUnsafe();
688 const initial = yield* AtomRegistry.getResult(registry, harness.atom, {
689 suspendOnWaiting: true,
690 }).pipe(Effect.exit);
691 expect(Exit.isFailure(initial)).toBe(true);
692 if (Exit.isFailure(initial)) {
693 expect(Cause.squash(initial.cause)).toBe(expectedFailure);
694 }
695
696 yield* SubscriptionRef.set(
697 harness.supervisorState,
698 queryConnectionState({ phase: "connecting", stage: "opening" }),
699 );
700 yield* Effect.yieldNow;
701
702 const refreshing = registry.get(harness.atom);
703 expect(AsyncResult.isFailure(refreshing)).toBe(true);
704 expect(refreshing.waiting).toBe(true);
705 if (AsyncResult.isFailure(refreshing)) {
706 expect(Cause.squash(refreshing.cause)).toBe(expectedFailure);
707 }
708
709 yield* SubscriptionRef.set(
710 harness.supervisorState,
711 queryConnectionState({ generation: 2 }),
712 );
713 yield* refreshStarted.await;
714 finishRefresh.openUnsafe();
715 expect(
716 yield* AtomRegistry.getResult(registry, harness.atom, {
717 suspendOnWaiting: true,
718 }),
719 ).toBe("recovered");
720 }),
721 ),
722 );
723
724 it.effect("retains the last successful value while reconnecting", () =>
725 Effect.scoped(
726 Effect.gen(function* () {
727 const refreshStarted = Latch.makeUnsafe();
728 const finishRefresh = Latch.makeUnsafe();
729 let executions = 0;
730 const execute = Effect.suspend(() => {
731 executions += 1;
732 if (executions === 1) {
733 return Effect.succeed("cached");
734 }
735 refreshStarted.openUnsafe();
736 return finishRefresh.await.pipe(Effect.as("updated"));
737 });
738 const harness = yield* makeEnvironmentQueryHarness(execute);
739 const registry = yield* mountEnvironmentQuery(harness.atom);
740
741 expect(
742 yield* AtomRegistry.getResult(registry, harness.atom, {
743 suspendOnWaiting: true,
744 }),
745 ).toBe("cached");
746
747 yield* SubscriptionRef.set(
748 harness.supervisorState,
749 queryConnectionState({ phase: "connecting", stage: "opening" }),
750 );
751 yield* Effect.yieldNow;
752 expect(registry.get(harness.atom)).toMatchObject({
753 _tag: "Success",
754 value: "cached",
755 waiting: true,
756 });
757
758 yield* SubscriptionRef.set(
759 harness.supervisorState,
760 queryConnectionState({
761 phase: "backoff",
762 stage: null,
763 lastFailure: new ConnectionTransientError({
764 reason: "transport",
765 detail: "Retrying.",
766 }),
767 retryAt: 1,
768 }),
769 );
770 yield* Effect.yieldNow;
771 expect(registry.get(harness.atom)).toMatchObject({
772 _tag: "Success",
773 value: "cached",
774 waiting: true,
775 });
776
777 yield* SubscriptionRef.set(
778 harness.supervisorState,
779 queryConnectionState({ generation: 2 }),
780 );
781 yield* refreshStarted.await;
782 expect(registry.get(harness.atom)).toMatchObject({
783 _tag: "Success",
784 value: "cached",
785 waiting: true,
786 });
787
788 finishRefresh.openUnsafe();
789 expect(
790 yield* AtomRegistry.getResult(registry, harness.atom, {
791 suspendOnWaiting: true,
792 }),
793 ).toBe("updated");
794 }),
795 ),
796 );
797
798 it.effect("refreshes on its trigger while read, and once on its next read when idle", () =>
799 Effect.scoped(
800 Effect.gen(function* () {
801 let executions = 0;
802 const trigger = Atom.make(0).pipe(Atom.keepAlive);
803 const harness = yield* makeEnvironmentQueryHarness(
804 Effect.sync(() => (executions += 1)),
805 { refreshTrigger: trigger },
806 );
807 const registry = AtomRegistry.make();
808 yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
809 const read = readEnvironmentQuery(registry, harness.atom);
810
811 const unmount = registry.mount(harness.atom);
812 expect(yield* read).toBe(1);
813 registry.set(trigger, 1);
814 expect(yield* read).toBe(2);
815
816 unmount();
817 registry.set(trigger, 2);
818 registry.set(trigger, 3);
819 expect(executions).toBe(2);
820
821 expect(yield* read).toBe(3);
822 }),
823 ),
824 );
825
826 it.effect("stops refreshing on its trigger once the value is final", () =>
827 Effect.scoped(
828 Effect.gen(function* () {
829 let executions = 0;
830 const trigger = Atom.make(0).pipe(Atom.keepAlive);
831 const harness = yield* makeEnvironmentQueryHarness(
832 Effect.sync(() => (executions += 1)),
833 { refreshTrigger: trigger, isFinal: (value) => value >= 2 },
834 );
835 const registry = AtomRegistry.make();
836 yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
837 const read = readEnvironmentQuery(registry, harness.atom);
838
839 registry.mount(harness.atom);
840 expect(yield* read).toBe(1);
841 registry.set(trigger, 1);
842 expect(yield* read).toBe(2);
843 registry.set(trigger, 2);
844 expect(yield* read).toBe(2);
845 expect(executions).toBe(2);
846 }),
847 ),
848 );
849
850 it.effect("keeps an idle query when its trigger recomputes to the same value", () =>
851 Effect.scoped(
852 Effect.gen(function* () {
853 let executions = 0;
854 const settings = Atom.make({ theme: "dark" }).pipe(Atom.keepAlive);
855 const trigger = Atom.make((get) => JSON.stringify([get(settings) !== null]));
856 const harness = yield* makeEnvironmentQueryHarness(
857 Effect.sync(() => (executions += 1)),
858 { refreshTrigger: trigger },
859 );
860 const registry = AtomRegistry.make();
861 yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
862 const read = readEnvironmentQuery(registry, harness.atom);
863
864 const unmount = registry.mount(harness.atom);
865 expect(yield* read).toBe(1);
866 unmount();
867 registry.set(settings, { theme: "light" });
868 expect(yield* read).toBe(1);
869 expect(executions).toBe(1);
870 }),
871 ),
872 );
873
874 it.effect("refreshes an idle query the registry swept and rebuilt after its trigger moved", () =>
875 Effect.scoped(
876 Effect.gen(function* () {
877 vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "Date"] });
878 yield* Effect.addFinalizer(() => Effect.sync(() => vi.useRealTimers()));
879 let executions = 0;
880 const trigger = Atom.make(0).pipe(Atom.keepAlive);
881 const harness = yield* makeEnvironmentQueryHarness(
882 Effect.sync(() => (executions += 1)),
883 { refreshTrigger: trigger, idleTtlMs: 1_000 },
884 );
885 const registry = AtomRegistry.make({ timeoutResolution: 100 });
886 yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose()));
887 const read = readEnvironmentQuery(registry, harness.atom);
888
889 const unmount = registry.mount(harness.atom);
890 expect(yield* read).toBe(1);
891 unmount();
892 yield* Effect.yieldNow;
893 vi.advanceTimersByTime(500);
894 registry.set(trigger, 1);
895 yield* Effect.yieldNow;
896 vi.advanceTimersByTime(700);
897 expect(executions).toBe(1);
898
899 expect(yield* read).toBe(2);
900 }),
901 ),
902 );
903});
904
905describe("Atom.fn mutation semantics", () => {
906 it.effect("interrupts the previous invocation when the same mutation atom is written again", () =>
907 Effect.gen(function* () {
908 const firstLatch = Latch.makeUnsafe();
909 const secondLatch = Latch.makeUnsafe();
910 const interrupted: string[] = [];
911 const mutation = Atom.fn((id: "first" | "second") =>
912 (id === "first" ? firstLatch : secondLatch).await.pipe(
913 Effect.as(id),
914 Effect.onInterrupt(() =>
915 Effect.sync(() => {
916 interrupted.push(id);
917 }),
918 ),
919 ),
920 );
921 const registry = AtomRegistry.make();
922 const unmount = registry.mount(mutation);
923
924 registry.set(mutation, "first");
925 registry.set(mutation, "second");
926 yield* Effect.yieldNow;
927
928 expect(interrupted).toEqual(["first"]);
929
930 secondLatch.openUnsafe();
931 expect(
932 yield* AtomRegistry.getResult(registry, mutation, {
933 suspendOnWaiting: true,
934 }),
935 ).toBe("second");
936
937 unmount();
938 registry.dispose();
939 }),
940 );
941
942 it.effect("keeps stream mutations waiting until the final emitted value", () =>
943 Effect.gen(function* () {
944 const completionLatch = Latch.makeUnsafe();
945 const mutation = Atom.fn(() =>
946 Stream.make("progress").pipe(
947 Stream.concat(Stream.fromEffect(completionLatch.await.pipe(Effect.as("done")))),
948 ),
949 );
950 const registry = AtomRegistry.make();
951 const unmount = registry.mount(mutation);
952
953 registry.set(mutation, undefined);
954
955 const progress = registry.get(mutation);
956 expect(AsyncResult.isSuccess(progress)).toBe(true);
957 if (AsyncResult.isSuccess(progress)) {
958 expect(progress.value).toBe("progress");
959 expect(progress.waiting).toBe(true);
960 }
961
962 completionLatch.openUnsafe();
963 expect(
964 yield* AtomRegistry.getResult(registry, mutation, {
965 suspendOnWaiting: true,
966 }),
967 ).toBe("done");
968
969 unmount();
970 registry.dispose();
971 }),
972 );
973
974 it.effect(
975 "allows concurrent effects to finish but does not correlate results to individual writes",
976 () =>
977 Effect.gen(function* () {
978 const firstLatch = Latch.makeUnsafe();
979 const secondLatch = Latch.makeUnsafe();
980 const mutation = Atom.fn<never, "first" | "second", "first" | "second">(
981 (id: "first" | "second") =>
982 (id === "first" ? firstLatch : secondLatch).await.pipe(Effect.as(id)),
983 { concurrent: true },
984 );
985 const registry = AtomRegistry.make();
986 const unmount = registry.mount(mutation);
987
988 registry.set(mutation, "first");
989 const firstResult = yield* AtomRegistry.getResult(registry, mutation, {
990 suspendOnWaiting: true,
991 }).pipe(Effect.forkChild({ startImmediately: true }));
992 registry.set(mutation, "second");
993 const secondResult = yield* AtomRegistry.getResult(registry, mutation, {
994 suspendOnWaiting: true,
995 }).pipe(Effect.forkChild({ startImmediately: true }));
996
997 secondLatch.openUnsafe();
998 yield* Effect.yieldNow;
999
1000 const stillWaiting = registry.get(mutation);
1001 expect(stillWaiting.waiting).toBe(true);
1002
1003 firstLatch.openUnsafe();
1004
1005 expect(yield* Fiber.join(firstResult)).toBe("first");
1006 expect(yield* Fiber.join(secondResult)).toBe("first");
1007
1008 unmount();
1009 registry.dispose();
1010 }),
1011 );
1012});
1013
1014describe("executeAtomQuery", () => {
1015 it("keeps concurrent query results correlated to their atoms", async () => {
1016 const firstLatch = Latch.makeUnsafe();
1017 const secondLatch = Latch.makeUnsafe();
1018 const firstAtom = Atom.make(firstLatch.await.pipe(Effect.as("first")));
1019 const secondAtom = Atom.make(secondLatch.await.pipe(Effect.as("second")));
1020 const registry = AtomRegistry.make();
1021
1022 const firstResult = executeAtomQuery(registry, firstAtom);
1023 const secondResult = executeAtomQuery(registry, secondAtom);
1024
1025 secondLatch.openUnsafe();
1026 firstLatch.openUnsafe();
1027
1028 const [first, second] = await Promise.all([firstResult, secondResult]);
1029 expect(first._tag).toBe("Success");
1030 expect(second._tag).toBe("Success");
1031 if (first._tag === "Success" && second._tag === "Success") {
1032 expect(first.value).toBe("first");
1033 expect(second.value).toBe("second");
1034 }
1035
1036 registry.dispose();
1037 });
1038
1039 it("settles when its caller aborts a waiting query", async () => {
1040 const registry = AtomRegistry.make();
1041 const controller = new AbortController();
1042 const resultPromise = executeAtomQuery(registry, Atom.make(Effect.never), {
1043 reportDefect: false,
1044 signal: controller.signal,
1045 });
1046
1047 controller.abort();
1048
1049 const result = await resultPromise;
1050 expect(result._tag).toBe("Failure");
1051 if (result._tag === "Failure") {
1052 expect(Cause.hasInterruptsOnly(result.cause)).toBe(true);
1053 }
1054 registry.dispose();
1055 });
1056});
1057
1058describe("runtime command runner", () => {
1059 it("encodes custom command rejections as defects", async () => {
1060 const defect = new Error("custom command rejected");
1061 const registry = AtomRegistry.make();
1062 const result = await runAtomCommand(
1063 registry,
1064 {
1065 label: "test.rejected-command",
1066 run: () => Promise.reject(defect),
1067 },
1068 undefined,
1069 { reportDefect: false },
1070 );
1071
1072 expect(result._tag).toBe("Failure");
1073 if (result._tag === "Failure") {
1074 expect(Cause.hasDies(result.cause)).toBe(true);
1075 expect(Cause.squash(result.cause)).toBe(defect);
1076 }
1077 registry.dispose();
1078 });
1079
1080 it("settles generated command scheduler defects from direct callers", async () => {
1081 const defect = new Error("invalid command key");
1082 const runtime = Atom.runtime(Layer.empty);
1083 const command = createRuntimeCommand(runtime, {
1084 label: "test.invalid-key",
1085 concurrency: {
1086 mode: "serial",
1087 key: () => {
1088 throw defect;
1089 },
1090 },
1091 execute: () => Effect.void,
1092 });
1093 const registry = AtomRegistry.make();
1094
1095 const result = await command.run(registry, undefined);
1096 expect(result._tag).toBe("Failure");
1097 if (result._tag === "Failure") {
1098 expect(Cause.hasDies(result.cause)).toBe(true);
1099 expect(Cause.squash(result.cause)).toBe(defect);
1100 }
1101 registry.dispose();
1102 });
1103
1104 it("correlates parallel invocation results", async () => {
1105 const firstLatch = Latch.makeUnsafe();
1106 const secondLatch = Latch.makeUnsafe();
1107 const runtime = Atom.runtime(Layer.empty);
1108 const command = createRuntimeCommand(runtime, {
1109 label: "test.parallel",
1110 execute: (id: "first" | "second") =>
1111 (id === "first" ? firstLatch : secondLatch).await.pipe(Effect.as(id)),
1112 });
1113 const registry = AtomRegistry.make();
1114
1115 const first = command.run(registry, "first");
1116 const second = command.run(registry, "second");
1117 secondLatch.openUnsafe();
1118 firstLatch.openUnsafe();
1119
1120 expect(await first).toMatchObject({ _tag: "Success", value: "first", waiting: false });
1121 expect(await second).toMatchObject({ _tag: "Success", value: "second", waiting: false });
1122 registry.dispose();
1123 });
1124
1125 it("serializes commands that share a scheduler and lane", async () => {
1126 const firstLatch = Latch.makeUnsafe();
1127 const events: string[] = [];
1128 const runtime = Atom.runtime(Layer.empty);
1129 const scheduler = createAtomCommandScheduler();
1130 const concurrency = { mode: "serial" as const, key: () => "shared" };
1131 const firstCommand = createRuntimeCommand(runtime, {
1132 label: "test.first",
1133 scheduler,
1134 concurrency,
1135 execute: () =>
1136 Effect.sync(() => events.push("first:start")).pipe(
1137 Effect.andThen(firstLatch.await),
1138 Effect.tap(() => Effect.sync(() => events.push("first:end"))),
1139 ),
1140 });
1141 const secondCommand = createRuntimeCommand(runtime, {
1142 label: "test.second",
1143 scheduler,
1144 concurrency,
1145 execute: () => Effect.sync(() => events.push("second:start")),
1146 });
1147 const registry = AtomRegistry.make();
1148
1149 const first = firstCommand.run(registry, undefined);
1150 const second = secondCommand.run(registry, undefined);
1151 await Promise.resolve();
1152 expect(events).toEqual(["first:start"]);
1153
1154 firstLatch.openUnsafe();
1155 await Promise.all([first, second]);
1156 expect(events).toEqual(["first:start", "first:end", "second:start"]);
1157 registry.dispose();
1158 });
1159
1160 it.effect("releases a shared scheduler lane before the outer command finishes", () =>
1161 Effect.gen(function* () {
1162 const handoffStarted = Latch.makeUnsafe();
1163 const handoffComplete = Latch.makeUnsafe();
1164 const resumeComplete = Latch.makeUnsafe();
1165 const runtime = Atom.runtime(Layer.empty);
1166 const scheduler = createAtomCommandScheduler();
1167 const concurrency = { mode: "serial" as const, key: () => "shared" };
1168 const updateCommand = createRuntimeCommand(runtime, {
1169 label: "test.update",
1170 execute: (_input: void, registry) =>
1171 scheduleAtomCommandEffect(
1172 registry,
1173 scheduler,
1174 concurrency,
1175 undefined,
1176 Effect.sync(() => handoffStarted.openUnsafe()).pipe(
1177 Effect.andThen(handoffComplete.await),
1178 ),
1179 ).pipe(Effect.andThen(resumeComplete.await)),
1180 });
1181 const configCommand = createRuntimeCommand(runtime, {
1182 label: "test.config",
1183 scheduler,
1184 concurrency,
1185 execute: () => Effect.succeed("configured"),
1186 });
1187 const registry = AtomRegistry.make();
1188
1189 const update = updateCommand.run(registry, undefined);
1190 yield* handoffStarted.await;
1191 const config = configCommand.run(registry, undefined);
1192 handoffComplete.openUnsafe();
1193
1194 expect(yield* Effect.promise(() => config)).toMatchObject({
1195 _tag: "Success",
1196 value: "configured",
1197 waiting: false,
1198 });
1199 resumeComplete.openUnsafe();
1200 expect(yield* Effect.promise(() => update)).toMatchObject({
1201 _tag: "Success",
1202 waiting: false,
1203 });
1204 registry.dispose();
1205 }),
1206 );
1207
1208 it.effect("keeps an outer reconnect observer alive after a scheduled handoff returns", () =>
1209 Effect.gen(function* () {
1210 const commitStarting = yield* Deferred.make<void>();
1211 const observerArmed = yield* Deferred.make<void>();
1212 const reconnected = yield* Deferred.make<void>();
1213 const states = yield* Queue.unbounded<{ readonly phase: string }>();
1214 yield* Queue.offer(states, { phase: "connected" });
1215 const runtime = Atom.runtime(Layer.empty);
1216 const scheduler = createAtomCommandScheduler();
1217 const concurrency = { mode: "serial" as const, key: () => "shared" };
1218 const command = createRuntimeCommand(runtime, {
1219 label: "test.desktop-update-handoff",
1220 execute: (_input: void, registry) =>
1221 Effect.gen(function* () {
1222 yield* Deferred.await(commitStarting).pipe(
1223 Effect.andThen(
1224 Stream.fromQueue(states).pipe(
1225 Stream.tap(() => Deferred.succeed(observerArmed, undefined)),
1226 Stream.dropWhile((state) => state.phase === "connected"),
1227 Stream.filter((state) => state.phase === "connected"),
1228 Stream.runHead,
1229 ),
1230 ),
1231 Effect.andThen(Deferred.succeed(reconnected, undefined)),
1232 Effect.forkChild,
1233 );
1234 yield* scheduleAtomCommandEffect(
1235 registry,
1236 scheduler,
1237 concurrency,
1238 undefined,
1239 Deferred.succeed(commitStarting, undefined).pipe(
1240 Effect.andThen(Deferred.await(observerArmed)),
1241 ),
1242 );
1243 yield* Queue.offer(states, { phase: "backoff" });
1244 yield* Queue.offer(states, { phase: "connected" });
1245 yield* Deferred.await(reconnected);
1246 }),
1247 });
1248 const registry = AtomRegistry.make();
1249
1250 expect(yield* Effect.promise(() => command.run(registry, undefined))).toMatchObject({
1251 _tag: "Success",
1252 });
1253 registry.dispose();
1254 }),
1255 );
1256
1257 it("deduplicates single-flight commands by key", async () => {
1258 const latch = Latch.makeUnsafe();
1259 let executions = 0;
1260 const runtime = Atom.runtime(Layer.empty);
1261 const command = createRuntimeCommand(runtime, {
1262 label: "test.single-flight",
1263 concurrency: { mode: "singleFlight", key: (key: string) => key },
1264 execute: () =>
1265 Effect.sync(() => executions++).pipe(Effect.andThen(latch.await), Effect.as("done")),
1266 });
1267 const registry = AtomRegistry.make();
1268
1269 const first = command.run(registry, "same");
1270 const second = command.run(registry, "same");
1271 latch.openUnsafe();
1272
1273 expect(await first).toMatchObject({ _tag: "Success", value: "done", waiting: false });
1274 expect(await second).toMatchObject({ _tag: "Success", value: "done", waiting: false });
1275 expect(executions).toBe(1);
1276 registry.dispose();
1277 });
1278
1279 it("coalesces pending latest-value commands without interrupting the active call", async () => {
1280 const firstLatch = Latch.makeUnsafe();
1281 const executed: number[] = [];
1282 const runtime = Atom.runtime(Layer.empty);
1283 const command = createRuntimeCommand(runtime, {
1284 label: "test.latest",
1285 concurrency: { mode: "latest", key: () => "shared" },
1286 execute: (value: number) =>
1287 Effect.sync(() => executed.push(value)).pipe(
1288 Effect.andThen(value === 1 ? firstLatch.await : Effect.void),
1289 Effect.as(value),
1290 ),
1291 });
1292 const registry = AtomRegistry.make();
1293
1294 const first = command.run(registry, 1);
1295 await Promise.resolve();
1296 const second = command.run(registry, 2);
1297 const third = command.run(registry, 3);
1298 firstLatch.openUnsafe();
1299
1300 expect(await first).toMatchObject({ _tag: "Success", value: 1, waiting: false });
1301 expect(await second).toMatchObject({ _tag: "Success", value: 3, waiting: false });
1302 expect(await third).toMatchObject({ _tag: "Success", value: 3, waiting: false });
1303 expect(executed).toEqual([1, 3]);
1304 registry.dispose();
1305 });
1306});
1307
1308describe("persisted environment queries", () => {
1309 it.effect(
1310 "restores cached data in a new registry while offline, then refreshes on reconnect",
1311 () =>
1312 Effect.scoped(
1313 Effect.gen(function* () {
1314 let saved = Option.none<string>();
1315 const persistence: QueryPersistence<string> = {
1316 load: () => Effect.sync(() => saved),
1317 save: (_environmentId, _key, value) =>
1318 Effect.sync(() => {
1319 saved = Option.some(value);
1320 }),
1321 };
1322 const first = yield* makeEnvironmentQueryHarness(Effect.succeed("first"), {
1323 persistence,
1324 });
1325 const firstRegistry = yield* mountEnvironmentQuery(first.atom);
1326 expect(yield* readEnvironmentQuery(firstRegistry, first.atom)).toBe("first");
1327 expect(saved).toEqual(Option.some("first"));
1328
1329 const restarted = yield* makeEnvironmentQueryHarness(Effect.succeed("updated"), {
1330 persistence,
1331 initialState: queryConnectionState({ phase: "offline", network: "offline" }),
1332 });
1333 const registry = yield* mountEnvironmentQuery(restarted.atom);
1334 expect(yield* readEnvironmentQuery(registry, restarted.atom)).toBe("first");
1335 yield* SubscriptionRef.set(restarted.supervisorState, queryConnectionState());
1336 yield* Effect.yieldNow;
1337 expect(yield* readEnvironmentQuery(registry, restarted.atom)).toBe("updated");
1338 expect(saved).toEqual(Option.some("updated"));
1339 }),
1340 ),
1341 );
1342
1343 it.effect("keeps cached content available when revalidation fails", () =>
1344 Effect.scoped(
1345 Effect.gen(function* () {
1346 const harness = yield* makeEnvironmentQueryHarness(
1347 Effect.fail(new TestQueryError({ message: "failed" })),
1348 {
1349 persistence: { load: () => Effect.succeedSome("cached"), save: () => Effect.void },
1350 },
1351 );
1352 const registry = yield* mountEnvironmentQuery(harness.atom);
1353 yield* Effect.result(readEnvironmentQuery(registry, harness.atom));
1354 expect(Option.getOrNull(AsyncResult.value(registry.get(harness.atom)))).toBe("cached");
1355 }),
1356 ),
1357 );
1358
1359 it.effect("shows persisted data before a live request finishes", () =>
1360 Effect.scoped(
1361 Effect.gen(function* () {
1362 const response = yield* Deferred.make<string>();
1363 const seeded = yield* Deferred.make<void>();
1364 const refreshed = yield* Deferred.make<void>();
1365 const harness = yield* makeEnvironmentQueryHarness(Deferred.await(response), {
1366 persistence: {
1367 load: () => Effect.succeedSome("cached"),
1368 save: () => Effect.void,
1369 },
1370 });
1371 const registry = yield* mountEnvironmentQuery(harness.atom);
1372 const unsubscribe = registry.subscribe(
1373 harness.atom,
1374 (value) => {
1375 if (Option.getOrNull(AsyncResult.value(value)) === "cached")
1376 Deferred.doneUnsafe(seeded, Exit.void);
1377 if (Option.getOrNull(AsyncResult.value(value)) === "fresh")
1378 Deferred.doneUnsafe(refreshed, Exit.void);
1379 },
1380 { immediate: true },
1381 );
1382 yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));
1383 yield* Deferred.await(seeded);
1384 expect(Option.getOrNull(AsyncResult.value(registry.get(harness.atom)))).toBe("cached");
1385 yield* Deferred.succeed(response, "fresh");
1386 yield* Deferred.await(refreshed);
1387 expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("fresh");
1388 }),
1389 ),
1390 );
1391});