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

lazyService.ts

30 lines1.1 KB

1import * as Effect from "effect/Effect";
2import * as Exit from "effect/Exit";
3import * as Fiber from "effect/Fiber";
4import * as Scope from "effect/Scope";
5import * as Semaphore from "effect/Semaphore";
6​
7/** Share acquisition in the owner's scope; retry failures on the next use. */
8export const cacheInOwnerScope = <A, E, R>(make: Effect.Effect<A, E, R>) =>
9 Effect.gen(function* () {
10 const context = yield* Effect.context<R | Scope.Scope>();
11 const scope = yield* Scope.Scope;
12 const lock = yield* Semaphore.make(1);
13 let current: Fiber.Fiber<A, E> | undefined;
14 const start = make.pipe(
15 Effect.provideContext(context),
16 Effect.forkIn(scope),
17 Effect.tap((fiber) =>
18 Effect.sync(() => {
19 current = fiber;
20 fiber.addObserver((exit) => {
21 if (Exit.isFailure(exit) && current === fiber) current = undefined;
22 });
23 }),
24 ),
25 );
26 const fiber = lock.withPermits(1)(
27 Effect.suspend(() => (current ? Effect.succeed(current) : start)),
28 );
29 return fiber.pipe(Effect.flatMap(Fiber.join));
30 });