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

runtime.test.ts

451 lines15.2 KB

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