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

runtime.test.ts

885 lines29.4 KB

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