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

runtime.test.ts

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