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