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

runtime.test.ts

936 lines31.5 KB

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