Open History to see the last commit
1import * as Context from "effect/Context";
2import * as Deferred from "effect/Deferred";
3import * as Effect from "effect/Effect";
4import type * as Fiber from "effect/Fiber";
5import type * as Scope from "effect/Scope";
6import * as Tracer from "effect/Tracer";
7
8export class ServerActivation extends Context.Reference<Effect.Effect<void> | undefined>(
9 "t3/serverActivation",
10 { defaultValue: () => undefined },
11) {}
12
13// Background work outlives its caller's span; parenting to it puts every run in one endless trace.
14export const withoutParentSpan = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
15 effect.pipe(
16 // ParentSpan is optional to every reader, so removing it leaves R satisfied.
17 Effect.updateContext(
18 (context: Context.Context<R>) =>
19 Context.omit(Tracer.ParentSpan)(context) as Context.Context<R>,
20 ),
21 );
22
23export const forkParkedFiber = Effect.fnUntraced(function* <A, E, R>(
24 input: Effect.Effect<A, E, R>,
25): Effect.fn.Return<Fiber.Fiber<A, E>, never, Scope.Scope | R> {
26 const effect = withoutParentSpan(input);
27 const activation = yield* ServerActivation;
28 if (activation === undefined) {
29 return yield* Effect.forkScoped(effect);
30 }
31 const parked = yield* Deferred.make<void>();
32 const fiber = yield* Effect.forkScoped(
33 Deferred.succeed(parked, undefined).pipe(Effect.andThen(activation), Effect.andThen(effect)),
34 );
35 yield* Deferred.await(parked);
36 return fiber;
37});
38
39export const forkParked = <A, E, R>(
40 effect: Effect.Effect<A, E, R>,
41): Effect.Effect<void, never, Scope.Scope | R> => forkParkedFiber(effect).pipe(Effect.asVoid);