1
-import { Effect } from 'effect';
1
+import { Deferred, Effect, Exit } from 'effect';
2
3
/**
4
* Memoizes an Effect per key for the lifetime of the process, sharing one run
5
- * between concurrent callers. A success stays cached; a failure, defect, or
6
- * interruption is dropped so the next caller retries instead of replaying it.
5
+ * between concurrent callers. A success stays cached; a failure or defect is
6
+ * delivered to the callers already waiting and then dropped so the next caller
7
+ * retries instead of replaying it.
8
+ *
9
+ * The run is owned by a detached fiber rather than by whichever caller arrived
10
+ * first. Interrupting a caller therefore cancels only that caller's wait: the
11
+ * run completes and every other waiter still receives its result. With
12
+ * `Effect.cached` the first caller owns the run, so interrupting it would store
13
+ * the interrupt and replay it to every fiber already parked on the cell.
14
*
15
* Meant for reads that cannot change within one CLI invocation (a tool's
16
* latest version, the user's connected accounts) but were being fetched more
20
readonly keyOf: (input: I) => string;
21
readonly make: (input: I) => Effect.Effect<A, E, R>;
22
}): ((input: I) => Effect.Effect<A, E, R>) => {
16
- const cache = new Map<string, Effect.Effect<A, E, R>>();
23
+ const cache = new Map<string, Deferred.Deferred<A, E>>();
24
+
25
+ const load = (input: I): Effect.Effect<A, E, R> =>
26
+ // The lookup, the insert, and the fork run without an interruption point
27
+ // between them, so a cell is never left in the map without an owner.
28
+ Effect.uninterruptible(
29
+ Effect.suspend(() => {
30
+ const key = options.keyOf(input);
31
+ const existing = cache.get(key);
32
+ if (existing) {
33
+ return Effect.succeed(existing);
34
+ }
35
18
- return input =>
19
- Effect.suspend(() => {
20
- const key = options.keyOf(input);
21
- const existing = cache.get(key);
22
- if (existing) {
23
- return existing;
24
- }
36
+ const cell = Deferred.makeUnsafe<A, E>();
37
+ cache.set(key, cell);
38
+ return options.make(input).pipe(
39
+ Effect.exit,
40
+ Effect.flatMap(exit => {
41
+ if (!Exit.isSuccess(exit) && cache.get(key) === cell) {
42
+ cache.delete(key);
43
+ }
44
+ return Deferred.done(cell, exit);
45
+ }),
46
+ Effect.forkDetach,
47
+ Effect.as(cell)
48
+ );
49
+ })
50
+ ).pipe(Effect.flatMap(cell => Deferred.await(cell)));
51
26
- // `Effect.cached` only allocates the memo cell; running it here is
27
- // synchronous, so the lookup and the insert cannot interleave with
28
- // another fiber.
29
- const cached = Effect.runSync(
30
- Effect.cached(
31
- options.make(input).pipe(Effect.onError(() => Effect.sync(() => cache.delete(key))))
32
- )
33
- );
34
- cache.set(key, cached);
35
- return cached;
36
- });
52
+ return load;
53
};