Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

runtime.test.ts

1,128 lines39.1 KB

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