Open History to see the last commit
1import { assert, describe, it } from "@effect/vitest";
2import * as Cache from "effect/Cache";
3import * as Deferred from "effect/Deferred";
4import * as Effect from "effect/Effect";
5import * as Exit from "effect/Exit";
6import * as Fiber from "effect/Fiber";
7
8import { getCached } from "./getCached.ts";
9
10describe("getCached", () => {
11 it.effect("a read that joins an abandoned lookup gets a fresh result", () =>
12 Effect.gen(function* () {
13 const started = yield* Deferred.make<void>();
14 const stopped = yield* Deferred.make<void>();
15 let lookups = 0;
16 const cache = yield* Cache.make<string, string>({
17 capacity: 10,
18 lookup: () =>
19 ++lookups === 1
20 ? // Like `gh`, the first lookup takes a moment to stop once interrupted.
21 Effect.yieldNow.pipe(
22 Effect.andThen(Deferred.succeed(started, undefined)),
23 Effect.andThen(Effect.never),
24 Effect.onInterrupt(() => Deferred.await(stopped)),
25 )
26 : Effect.succeed("fresh"),
27 });
28 const first = yield* getCached(cache, "detail").pipe(Effect.forkChild);
29 yield* Deferred.await(started);
30 yield* Fiber.interrupt(first).pipe(Effect.forkChild({ startImmediately: true }));
31 const second = yield* getCached(cache, "detail").pipe(
32 Effect.forkChild({ startImmediately: true }),
33 );
34 yield* Deferred.succeed(stopped, undefined);
35
36 assert.deepStrictEqual(yield* Fiber.await(second), Exit.succeed("fresh"));
37 assert.strictEqual(lookups, 2);
38 }),
39 );
40
41 it.effect("an interrupted read does not start another lookup", () =>
42 Effect.gen(function* () {
43 const started = yield* Deferred.make<void>();
44 let lookups = 0;
45 const cache = yield* Cache.make<string, string>({
46 capacity: 10,
47 lookup: () => {
48 lookups++;
49 return Deferred.succeed(started, undefined).pipe(Effect.andThen(Effect.never));
50 },
51 });
52 const read = yield* getCached(cache, "detail").pipe(Effect.forkChild);
53 yield* Deferred.await(started);
54
55 yield* Fiber.interrupt(read);
56
57 assert.isTrue(Exit.hasInterrupts(yield* Fiber.await(read)));
58 assert.strictEqual(lookups, 1);
59 }),
60 );
61});