@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 44 lines 1.88 KB
Raw
1 import * as Deferred from "effect/Deferred";
2 import * as Effect from "effect/Effect";
3 import * as Fiber from "effect/Fiber";
4 import * as Scope from "effect/Scope";
5
6 /**
7 * A lazily evaluated, memoized effect whose computation runs in a fiber of
8 * its own, owned by `scope`.
9 *
10 * `Effect.cached` evaluates on the fiber of whichever caller gets there
11 * first. When that caller is interrupted while others are waiting — a
12 * concurrent plan cancelling sibling diffs — every waiter fails
13 * interrupt-only and the cache stays poisoned for the rest of the process.
14 * A computation that many fibers share must not have that failure mode: here
15 * it runs detached from every caller, so interrupting a waiter never touches
16 * it, and only closing `scope` cancels it (its waiters then see the
17 * interruption, as they should).
18 *
19 * Requirements are captured from the first caller, exactly as
20 * `Effect.cached` does.
21 */
22 export const cachedInScope =
23 (scope: Scope.Scope) =>
24 <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<Effect.Effect<A, E>, never, R> =>
25 Effect.gen(function* () {
26 const context = yield* Effect.context<R>();
27 const deferred = yield* Deferred.make<A, E>();
28 let started = false;
29 return Effect.suspend(() => {
30 if (started) return Deferred.await(deferred);
31 started = true;
32 return effect.pipe(
33 Effect.provideContext(context),
34 // `onExit` also runs on interruption, so the waiters always learn
35 // how the computation ended.
36 Effect.onExit((exit) => Deferred.done(deferred, exit)),
37 // Not a child of the caller: the caller's interruption must not
38 // reach it. The scope owns its lifetime instead.
39 Effect.forkDetach,
40 Effect.flatMap((fiber) => Scope.addFinalizer(scope, Fiber.interrupt(fiber))),
41 Effect.andThen(Deferred.await(deferred)),
42 );
43 });
44 });