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 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 Stream from "effect/Stream";
10import { AsyncResult, Atom, AtomRegistry } from "effect/unstable/reactivity";
11
12import {
13 environmentRpcKey,
14 createAtomCommandScheduler,
15 createRuntimeCommand,
16 scheduleAtomCommandEffect,
17 executeAtomCommand,
18 executeAtomQuery,
19 isAtomCommandInterrupted,
20 mapAtomCommandResult,
21 runAtomCommand,
22 settleAsyncResult,
23 settlePromise,
24 squashAtomCommandFailure,
25} from "./runtime.ts";
26
27describe("settleAsyncResult", () => {
28 it("preserves successful values and typed failures", async () => {
29 const success = await settleAsyncResult(() => Promise.resolve(Exit.succeed("done")));
30 expect(AsyncResult.isSuccess(success)).toBe(true);
31 if (AsyncResult.isSuccess(success)) {
32 expect(success.value).toBe("done");
33 }
34
35 const expectedFailure = new Error("request failed");
36 const failure = await settleAsyncResult(() => Promise.resolve(Exit.fail(expectedFailure)));
37 expect(AsyncResult.isFailure(failure)).toBe(true);
38 if (AsyncResult.isFailure(failure)) {
39 expect(Cause.hasDies(failure.cause)).toBe(false);
40 expect(Cause.squash(failure.cause)).toBe(expectedFailure);
41 }
42 });
43
44 it("encodes thrown and rejected promises as defects", async () => {
45 const thrownDefect = new Error("thrown defect");
46 const thrown = await settleAsyncResult<void, never>(() => {
47 throw thrownDefect;
48 });
49 expect(AsyncResult.isFailure(thrown)).toBe(true);
50 if (AsyncResult.isFailure(thrown)) {
51 expect(Cause.hasDies(thrown.cause)).toBe(true);
52 expect(Cause.squash(thrown.cause)).toBe(thrownDefect);
53 }
54
55 const rejectedDefect = new Error("rejected defect");
56 const rejected = await settleAsyncResult<void, never>(() => Promise.reject(rejectedDefect));
57 expect(AsyncResult.isFailure(rejected)).toBe(true);
58 if (AsyncResult.isFailure(rejected)) {
59 expect(Cause.hasDies(rejected.cause)).toBe(true);
60 expect(Cause.squash(rejected.cause)).toBe(rejectedDefect);
61 }
62 });
63});
64
65describe("atom command result helpers", () => {
66 it("maps successful command values", () => {
67 const result = mapAtomCommandResult(AsyncResult.success(2), (value) => value * 3);
68
69 expect(result._tag).toBe("Success");
70 if (result._tag === "Success") {
71 expect(result.value).toBe(6);
72 }
73 });
74
75 it("preserves failures while mapping", () => {
76 const result = mapAtomCommandResult(
77 AsyncResult.failure<number, string>(Cause.fail("nope")),
78 (value) => value * 3,
79 );
80
81 expect(result._tag).toBe("Failure");
82 if (result._tag === "Failure") {
83 expect(Cause.squash(result.cause)).toBe("nope");
84 }
85 });
86
87 it("distinguishes interruption from other failures", () => {
88 const interrupted = AsyncResult.failure(Cause.interrupt(1));
89 const failed = AsyncResult.failure(Cause.fail("nope"));
90
91 expect(isAtomCommandInterrupted(interrupted)).toBe(true);
92 expect(isAtomCommandInterrupted(failed)).toBe(false);
93 expect(squashAtomCommandFailure(failed)).toBe("nope");
94 });
95
96 it("settles raw promise boundaries as successes or defects", async () => {
97 const success = await settlePromise(() => Promise.resolve("done"));
98 expect(success._tag).toBe("Success");
99
100 const defect = new Error("raw promise rejected");
101 const failure = await settlePromise(() => Promise.reject(defect));
102 expect(failure._tag).toBe("Failure");
103 if (failure._tag === "Failure") {
104 expect(Cause.hasDies(failure.cause)).toBe(true);
105 expect(Cause.squash(failure.cause)).toBe(defect);
106 }
107 });
108
109 it("reports expected failures and defects through separate policies", async () => {
110 const warnings: string[] = [];
111 const errors: string[] = [];
112 const reporter = {
113 warn: (message: string) => {
114 warnings.push(message);
115 },
116 error: (message: string) => {
117 errors.push(message);
118 },
119 };
120
121 await executeAtomCommand(() => Promise.resolve(Exit.fail("nope")), { label: "save" }, reporter);
122 await executeAtomCommand(
123 () => Promise.resolve(Exit.fail("ignored")),
124 { label: "quiet save", reportFailure: false },
125 reporter,
126 );
127 await executeAtomCommand(
128 () => Promise.reject(new Error("defect")),
129 { label: "quiet save", reportFailure: false },
130 reporter,
131 );
132 await executeAtomCommand(
133 () => Promise.resolve(Exit.interrupt(1)),
134 { label: "interrupted" },
135 reporter,
136 );
137
138 expect(warnings).toEqual(["[atom-command] save failed"]);
139 expect(errors).toEqual(["[atom-command] quiet save defected"]);
140 });
141});
142
143describe("environmentRpcKey", () => {
144 it("isolates subscription state by environment and cwd", () => {
145 const environmentId = EnvironmentId.make("environment-1");
146 const originalTarget = {
147 environmentId,
148 input: { cwd: "/repo/original" },
149 };
150 const nextTarget = {
151 environmentId,
152 input: { cwd: "/repo/next" },
153 };
154
155 expect(environmentRpcKey(originalTarget)).not.toBe(environmentRpcKey(nextTarget));
156 expect(environmentRpcKey(originalTarget)).toBe(environmentRpcKey({ ...originalTarget }));
157 expect(
158 environmentRpcKey({
159 environmentId: EnvironmentId.make("environment-2"),
160 input: originalTarget.input,
161 }),
162 ).not.toBe(environmentRpcKey(originalTarget));
163 });
164});
165
166describe("Atom.fn mutation semantics", () => {
167 it.effect("interrupts the previous invocation when the same mutation atom is written again", () =>
168 Effect.gen(function* () {
169 const firstLatch = Latch.makeUnsafe();
170 const secondLatch = Latch.makeUnsafe();
171 const interrupted: string[] = [];
172 const mutation = Atom.fn((id: "first" | "second") =>
173 (id === "first" ? firstLatch : secondLatch).await.pipe(
174 Effect.as(id),
175 Effect.onInterrupt(() =>
176 Effect.sync(() => {
177 interrupted.push(id);
178 }),
179 ),
180 ),
181 );
182 const registry = AtomRegistry.make();
183 const unmount = registry.mount(mutation);
184
185 registry.set(mutation, "first");
186 registry.set(mutation, "second");
187 yield* Effect.yieldNow;
188
189 expect(interrupted).toEqual(["first"]);
190
191 secondLatch.openUnsafe();
192 expect(
193 yield* AtomRegistry.getResult(registry, mutation, {
194 suspendOnWaiting: true,
195 }),
196 ).toBe("second");
197
198 unmount();
199 registry.dispose();
200 }),
201 );
202
203 it.effect("keeps stream mutations waiting until the final emitted value", () =>
204 Effect.gen(function* () {
205 const completionLatch = Latch.makeUnsafe();
206 const mutation = Atom.fn(() =>
207 Stream.make("progress").pipe(
208 Stream.concat(Stream.fromEffect(completionLatch.await.pipe(Effect.as("done")))),
209 ),
210 );
211 const registry = AtomRegistry.make();
212 const unmount = registry.mount(mutation);
213
214 registry.set(mutation, undefined);
215
216 const progress = registry.get(mutation);
217 expect(AsyncResult.isSuccess(progress)).toBe(true);
218 if (AsyncResult.isSuccess(progress)) {
219 expect(progress.value).toBe("progress");
220 expect(progress.waiting).toBe(true);
221 }
222
223 completionLatch.openUnsafe();
224 expect(
225 yield* AtomRegistry.getResult(registry, mutation, {
226 suspendOnWaiting: true,
227 }),
228 ).toBe("done");
229
230 unmount();
231 registry.dispose();
232 }),
233 );
234
235 it.effect(
236 "allows concurrent effects to finish but does not correlate results to individual writes",
237 () =>
238 Effect.gen(function* () {
239 const firstLatch = Latch.makeUnsafe();
240 const secondLatch = Latch.makeUnsafe();
241 const mutation = Atom.fn<never, "first" | "second", "first" | "second">(
242 (id: "first" | "second") =>
243 (id === "first" ? firstLatch : secondLatch).await.pipe(Effect.as(id)),
244 { concurrent: true },
245 );
246 const registry = AtomRegistry.make();
247 const unmount = registry.mount(mutation);
248
249 registry.set(mutation, "first");
250 const firstResult = yield* AtomRegistry.getResult(registry, mutation, {
251 suspendOnWaiting: true,
252 }).pipe(Effect.forkChild({ startImmediately: true }));
253 registry.set(mutation, "second");
254 const secondResult = yield* AtomRegistry.getResult(registry, mutation, {
255 suspendOnWaiting: true,
256 }).pipe(Effect.forkChild({ startImmediately: true }));
257
258 secondLatch.openUnsafe();
259 yield* Effect.yieldNow;
260
261 const stillWaiting = registry.get(mutation);
262 expect(stillWaiting.waiting).toBe(true);
263
264 firstLatch.openUnsafe();
265
266 expect(yield* Fiber.join(firstResult)).toBe("first");
267 expect(yield* Fiber.join(secondResult)).toBe("first");
268
269 unmount();
270 registry.dispose();
271 }),
272 );
273});
274
275describe("executeAtomQuery", () => {
276 it("keeps concurrent query results correlated to their atoms", async () => {
277 const firstLatch = Latch.makeUnsafe();
278 const secondLatch = Latch.makeUnsafe();
279 const firstAtom = Atom.make(firstLatch.await.pipe(Effect.as("first")));
280 const secondAtom = Atom.make(secondLatch.await.pipe(Effect.as("second")));
281 const registry = AtomRegistry.make();
282
283 const firstResult = executeAtomQuery(registry, firstAtom);
284 const secondResult = executeAtomQuery(registry, secondAtom);
285
286 secondLatch.openUnsafe();
287 firstLatch.openUnsafe();
288
289 const [first, second] = await Promise.all([firstResult, secondResult]);
290 expect(first._tag).toBe("Success");
291 expect(second._tag).toBe("Success");
292 if (first._tag === "Success" && second._tag === "Success") {
293 expect(first.value).toBe("first");
294 expect(second.value).toBe("second");
295 }
296
297 registry.dispose();
298 });
299});
300
301describe("runtime command runner", () => {
302 it("encodes custom command rejections as defects", async () => {
303 const defect = new Error("custom command rejected");
304 const registry = AtomRegistry.make();
305 const result = await runAtomCommand(
306 registry,
307 {
308 label: "test.rejected-command",
309 run: () => Promise.reject(defect),
310 },
311 undefined,
312 { reportDefect: false },
313 );
314
315 expect(result._tag).toBe("Failure");
316 if (result._tag === "Failure") {
317 expect(Cause.hasDies(result.cause)).toBe(true);
318 expect(Cause.squash(result.cause)).toBe(defect);
319 }
320 registry.dispose();
321 });
322
323 it("settles generated command scheduler defects from direct callers", async () => {
324 const defect = new Error("invalid command key");
325 const runtime = Atom.runtime(Layer.empty);
326 const command = createRuntimeCommand(runtime, {
327 label: "test.invalid-key",
328 concurrency: {
329 mode: "serial",
330 key: () => {
331 throw defect;
332 },
333 },
334 execute: () => Effect.void,
335 });
336 const registry = AtomRegistry.make();
337
338 const result = await command.run(registry, undefined);
339 expect(result._tag).toBe("Failure");
340 if (result._tag === "Failure") {
341 expect(Cause.hasDies(result.cause)).toBe(true);
342 expect(Cause.squash(result.cause)).toBe(defect);
343 }
344 registry.dispose();
345 });
346
347 it("correlates parallel invocation results", async () => {
348 const firstLatch = Latch.makeUnsafe();
349 const secondLatch = Latch.makeUnsafe();
350 const runtime = Atom.runtime(Layer.empty);
351 const command = createRuntimeCommand(runtime, {
352 label: "test.parallel",
353 execute: (id: "first" | "second") =>
354 (id === "first" ? firstLatch : secondLatch).await.pipe(Effect.as(id)),
355 });
356 const registry = AtomRegistry.make();
357
358 const first = command.run(registry, "first");
359 const second = command.run(registry, "second");
360 secondLatch.openUnsafe();
361 firstLatch.openUnsafe();
362
363 expect(await first).toMatchObject({ _tag: "Success", value: "first", waiting: false });
364 expect(await second).toMatchObject({ _tag: "Success", value: "second", waiting: false });
365 registry.dispose();
366 });
367
368 it("serializes commands that share a scheduler and lane", async () => {
369 const firstLatch = Latch.makeUnsafe();
370 const events: string[] = [];
371 const runtime = Atom.runtime(Layer.empty);
372 const scheduler = createAtomCommandScheduler();
373 const concurrency = { mode: "serial" as const, key: () => "shared" };
374 const firstCommand = createRuntimeCommand(runtime, {
375 label: "test.first",
376 scheduler,
377 concurrency,
378 execute: () =>
379 Effect.sync(() => events.push("first:start")).pipe(
380 Effect.andThen(firstLatch.await),
381 Effect.tap(() => Effect.sync(() => events.push("first:end"))),
382 ),
383 });
384 const secondCommand = createRuntimeCommand(runtime, {
385 label: "test.second",
386 scheduler,
387 concurrency,
388 execute: () => Effect.sync(() => events.push("second:start")),
389 });
390 const registry = AtomRegistry.make();
391
392 const first = firstCommand.run(registry, undefined);
393 const second = secondCommand.run(registry, undefined);
394 await Promise.resolve();
395 expect(events).toEqual(["first:start"]);
396
397 firstLatch.openUnsafe();
398 await Promise.all([first, second]);
399 expect(events).toEqual(["first:start", "first:end", "second:start"]);
400 registry.dispose();
401 });
402
403 it.effect("releases a shared scheduler lane before the outer command finishes", () =>
404 Effect.gen(function* () {
405 const handoffStarted = Latch.makeUnsafe();
406 const handoffComplete = Latch.makeUnsafe();
407 const resumeComplete = Latch.makeUnsafe();
408 const runtime = Atom.runtime(Layer.empty);
409 const scheduler = createAtomCommandScheduler();
410 const concurrency = { mode: "serial" as const, key: () => "shared" };
411 const updateCommand = createRuntimeCommand(runtime, {
412 label: "test.update",
413 execute: (_input: void, registry) =>
414 scheduleAtomCommandEffect(
415 registry,
416 scheduler,
417 concurrency,
418 undefined,
419 Effect.sync(() => handoffStarted.openUnsafe()).pipe(
420 Effect.andThen(handoffComplete.await),
421 ),
422 ).pipe(Effect.andThen(resumeComplete.await)),
423 });
424 const configCommand = createRuntimeCommand(runtime, {
425 label: "test.config",
426 scheduler,
427 concurrency,
428 execute: () => Effect.succeed("configured"),
429 });
430 const registry = AtomRegistry.make();
431
432 const update = updateCommand.run(registry, undefined);
433 yield* handoffStarted.await;
434 const config = configCommand.run(registry, undefined);
435 handoffComplete.openUnsafe();
436
437 expect(yield* Effect.promise(() => config)).toMatchObject({
438 _tag: "Success",
439 value: "configured",
440 waiting: false,
441 });
442 resumeComplete.openUnsafe();
443 expect(yield* Effect.promise(() => update)).toMatchObject({
444 _tag: "Success",
445 waiting: false,
446 });
447 registry.dispose();
448 }),
449 );
450
451 it("deduplicates single-flight commands by key", async () => {
452 const latch = Latch.makeUnsafe();
453 let executions = 0;
454 const runtime = Atom.runtime(Layer.empty);
455 const command = createRuntimeCommand(runtime, {
456 label: "test.single-flight",
457 concurrency: { mode: "singleFlight", key: (key: string) => key },
458 execute: () =>
459 Effect.sync(() => executions++).pipe(Effect.andThen(latch.await), Effect.as("done")),
460 });
461 const registry = AtomRegistry.make();
462
463 const first = command.run(registry, "same");
464 const second = command.run(registry, "same");
465 latch.openUnsafe();
466
467 expect(await first).toMatchObject({ _tag: "Success", value: "done", waiting: false });
468 expect(await second).toMatchObject({ _tag: "Success", value: "done", waiting: false });
469 expect(executions).toBe(1);
470 registry.dispose();
471 });
472
473 it("coalesces pending latest-value commands without interrupting the active call", async () => {
474 const firstLatch = Latch.makeUnsafe();
475 const executed: number[] = [];
476 const runtime = Atom.runtime(Layer.empty);
477 const command = createRuntimeCommand(runtime, {
478 label: "test.latest",
479 concurrency: { mode: "latest", key: () => "shared" },
480 execute: (value: number) =>
481 Effect.sync(() => executed.push(value)).pipe(
482 Effect.andThen(value === 1 ? firstLatch.await : Effect.void),
483 Effect.as(value),
484 ),
485 });
486 const registry = AtomRegistry.make();
487
488 const first = command.run(registry, 1);
489 await Promise.resolve();
490 const second = command.run(registry, 2);
491 const third = command.run(registry, 3);
492 firstLatch.openUnsafe();
493
494 expect(await first).toMatchObject({ _tag: "Success", value: 1, waiting: false });
495 expect(await second).toMatchObject({ _tag: "Success", value: 3, waiting: false });
496 expect(await third).toMatchObject({ _tag: "Success", value: 3, waiting: false });
497 expect(executed).toEqual([1, 3]);
498 registry.dispose();
499 });
500});