Open History to see the last commit
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 };
80}
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 it("settles when its caller aborts a waiting query", async () => {
688 const registry = AtomRegistry.make();
689 const controller = new AbortController();
690 const resultPromise = executeAtomQuery(registry, Atom.make(Effect.never), {
691 reportDefect: false,
692 signal: controller.signal,
693 });
694
695 controller.abort();
696
697 const result = await resultPromise;
698 expect(result._tag).toBe("Failure");
699 if (result._tag === "Failure") {
700 expect(Cause.hasInterruptsOnly(result.cause)).toBe(true);
701 }
702 registry.dispose();
703 });
704});
705
706describe("runtime command runner", () => {
707 it("encodes custom command rejections as defects", async () => {
708 const defect = new Error("custom command rejected");
709 const registry = AtomRegistry.make();
710 const result = await runAtomCommand(
711 registry,
712 {
713 label: "test.rejected-command",
714 run: () => Promise.reject(defect),
715 },
716 undefined,
717 { reportDefect: false },
718 );
719
720 expect(result._tag).toBe("Failure");
721 if (result._tag === "Failure") {
722 expect(Cause.hasDies(result.cause)).toBe(true);
723 expect(Cause.squash(result.cause)).toBe(defect);
724 }
725 registry.dispose();
726 });
727
728 it("settles generated command scheduler defects from direct callers", async () => {
729 const defect = new Error("invalid command key");
730 const runtime = Atom.runtime(Layer.empty);
731 const command = createRuntimeCommand(runtime, {
732 label: "test.invalid-key",
733 concurrency: {
734 mode: "serial",
735 key: () => {
736 throw defect;
737 },
738 },
739 execute: () => Effect.void,
740 });
741 const registry = AtomRegistry.make();
742
743 const result = await command.run(registry, undefined);
744 expect(result._tag).toBe("Failure");
745 if (result._tag === "Failure") {
746 expect(Cause.hasDies(result.cause)).toBe(true);
747 expect(Cause.squash(result.cause)).toBe(defect);
748 }
749 registry.dispose();
750 });
751
752 it("correlates parallel invocation results", async () => {
753 const firstLatch = Latch.makeUnsafe();
754 const secondLatch = Latch.makeUnsafe();
755 const runtime = Atom.runtime(Layer.empty);
756 const command = createRuntimeCommand(runtime, {
757 label: "test.parallel",
758 execute: (id: "first" | "second") =>
759 (id === "first" ? firstLatch : secondLatch).await.pipe(Effect.as(id)),
760 });
761 const registry = AtomRegistry.make();
762
763 const first = command.run(registry, "first");
764 const second = command.run(registry, "second");
765 secondLatch.openUnsafe();
766 firstLatch.openUnsafe();
767
768 expect(await first).toMatchObject({ _tag: "Success", value: "first", waiting: false });
769 expect(await second).toMatchObject({ _tag: "Success", value: "second", waiting: false });
770 registry.dispose();
771 });
772
773 it("serializes commands that share a scheduler and lane", async () => {
774 const firstLatch = Latch.makeUnsafe();
775 const events: string[] = [];
776 const runtime = Atom.runtime(Layer.empty);
777 const scheduler = createAtomCommandScheduler();
778 const concurrency = { mode: "serial" as const, key: () => "shared" };
779 const firstCommand = createRuntimeCommand(runtime, {
780 label: "test.first",
781 scheduler,
782 concurrency,
783 execute: () =>
784 Effect.sync(() => events.push("first:start")).pipe(
785 Effect.andThen(firstLatch.await),
786 Effect.tap(() => Effect.sync(() => events.push("first:end"))),
787 ),
788 });
789 const secondCommand = createRuntimeCommand(runtime, {
790 label: "test.second",
791 scheduler,
792 concurrency,
793 execute: () => Effect.sync(() => events.push("second:start")),
794 });
795 const registry = AtomRegistry.make();
796
797 const first = firstCommand.run(registry, undefined);
798 const second = secondCommand.run(registry, undefined);
799 await Promise.resolve();
800 expect(events).toEqual(["first:start"]);
801
802 firstLatch.openUnsafe();
803 await Promise.all([first, second]);
804 expect(events).toEqual(["first:start", "first:end", "second:start"]);
805 registry.dispose();
806 });
807
808 it.effect("releases a shared scheduler lane before the outer command finishes", () =>
809 Effect.gen(function* () {
810 const handoffStarted = Latch.makeUnsafe();
811 const handoffComplete = Latch.makeUnsafe();
812 const resumeComplete = Latch.makeUnsafe();
813 const runtime = Atom.runtime(Layer.empty);
814 const scheduler = createAtomCommandScheduler();
815 const concurrency = { mode: "serial" as const, key: () => "shared" };
816 const updateCommand = createRuntimeCommand(runtime, {
817 label: "test.update",
818 execute: (_input: void, registry) =>
819 scheduleAtomCommandEffect(
820 registry,
821 scheduler,
822 concurrency,
823 undefined,
824 Effect.sync(() => handoffStarted.openUnsafe()).pipe(
825 Effect.andThen(handoffComplete.await),
826 ),
827 ).pipe(Effect.andThen(resumeComplete.await)),
828 });
829 const configCommand = createRuntimeCommand(runtime, {
830 label: "test.config",
831 scheduler,
832 concurrency,
833 execute: () => Effect.succeed("configured"),
834 });
835 const registry = AtomRegistry.make();
836
837 const update = updateCommand.run(registry, undefined);
838 yield* handoffStarted.await;
839 const config = configCommand.run(registry, undefined);
840 handoffComplete.openUnsafe();
841
842 expect(yield* Effect.promise(() => config)).toMatchObject({
843 _tag: "Success",
844 value: "configured",
845 waiting: false,
846 });
847 resumeComplete.openUnsafe();
848 expect(yield* Effect.promise(() => update)).toMatchObject({
849 _tag: "Success",
850 waiting: false,
851 });
852 registry.dispose();
853 }),
854 );
855
856 it.effect("keeps an outer reconnect observer alive after a scheduled handoff returns", () =>
857 Effect.gen(function* () {
858 const commitStarting = yield* Deferred.make<void>();
859 const observerArmed = yield* Deferred.make<void>();
860 const reconnected = yield* Deferred.make<void>();
861 const states = yield* Queue.unbounded<{ readonly phase: string }>();
862 yield* Queue.offer(states, { phase: "connected" });
863 const runtime = Atom.runtime(Layer.empty);
864 const scheduler = createAtomCommandScheduler();
865 const concurrency = { mode: "serial" as const, key: () => "shared" };
866 const command = createRuntimeCommand(runtime, {
867 label: "test.desktop-update-handoff",
868 execute: (_input: void, registry) =>
869 Effect.gen(function* () {
870 yield* Deferred.await(commitStarting).pipe(
871 Effect.andThen(
872 Stream.fromQueue(states).pipe(
873 Stream.tap(() => Deferred.succeed(observerArmed, undefined)),
874 Stream.dropWhile((state) => state.phase === "connected"),
875 Stream.filter((state) => state.phase === "connected"),
876 Stream.runHead,
877 ),
878 ),
879 Effect.andThen(Deferred.succeed(reconnected, undefined)),
880 Effect.forkChild,
881 );
882 yield* scheduleAtomCommandEffect(
883 registry,
884 scheduler,
885 concurrency,
886 undefined,
887 Deferred.succeed(commitStarting, undefined).pipe(
888 Effect.andThen(Deferred.await(observerArmed)),
889 ),
890 );
891 yield* Queue.offer(states, { phase: "backoff" });
892 yield* Queue.offer(states, { phase: "connected" });
893 yield* Deferred.await(reconnected);
894 }),
895 });
896 const registry = AtomRegistry.make();
897
898 expect(yield* Effect.promise(() => command.run(registry, undefined))).toMatchObject({
899 _tag: "Success",
900 });
901 registry.dispose();
902 }),
903 );
904
905 it("deduplicates single-flight commands by key", async () => {
906 const latch = Latch.makeUnsafe();
907 let executions = 0;
908 const runtime = Atom.runtime(Layer.empty);
909 const command = createRuntimeCommand(runtime, {
910 label: "test.single-flight",
911 concurrency: { mode: "singleFlight", key: (key: string) => key },
912 execute: () =>
913 Effect.sync(() => executions++).pipe(Effect.andThen(latch.await), Effect.as("done")),
914 });
915 const registry = AtomRegistry.make();
916
917 const first = command.run(registry, "same");
918 const second = command.run(registry, "same");
919 latch.openUnsafe();
920
921 expect(await first).toMatchObject({ _tag: "Success", value: "done", waiting: false });
922 expect(await second).toMatchObject({ _tag: "Success", value: "done", waiting: false });
923 expect(executions).toBe(1);
924 registry.dispose();
925 });
926
927 it("coalesces pending latest-value commands without interrupting the active call", async () => {
928 const firstLatch = Latch.makeUnsafe();
929 const executed: number[] = [];
930 const runtime = Atom.runtime(Layer.empty);
931 const command = createRuntimeCommand(runtime, {
932 label: "test.latest",
933 concurrency: { mode: "latest", key: () => "shared" },
934 execute: (value: number) =>
935 Effect.sync(() => executed.push(value)).pipe(
936 Effect.andThen(value === 1 ? firstLatch.await : Effect.void),
937 Effect.as(value),
938 ),
939 });
940 const registry = AtomRegistry.make();
941
942 const first = command.run(registry, 1);
943 await Promise.resolve();
944 const second = command.run(registry, 2);
945 const third = command.run(registry, 3);
946 firstLatch.openUnsafe();
947
948 expect(await first).toMatchObject({ _tag: "Success", value: 1, waiting: false });
949 expect(await second).toMatchObject({ _tag: "Success", value: 3, waiting: false });
950 expect(await third).toMatchObject({ _tag: "Success", value: 3, waiting: false });
951 expect(executed).toEqual([1, 3]);
952 registry.dispose();
953 });
954});