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";
7import * as NodeCrypto from "node:crypto";
8
9export class ServerActivation extends Context.Reference<Effect.Effect<void> | undefined>(
10 "t3/serverActivation",
11 { defaultValue: () => undefined },
12) {}
13
14// Replace and flatten the context before forking: Context.add retains the old
15// parent in its overlay, while providing inside the child retains a restoration
16// frame for the lifetime of the work. The external root does not collect children.
17export const forkScopedDetached = <A, E, R>(
18 effect: Effect.Effect<A, E, R>,
19): Effect.Effect<Fiber.Fiber<A, E>, never, Scope.Scope | Exclude<R, Tracer.ParentSpan>> =>
20 Effect.updateContext(
21 Effect.forkScoped(effect),
22 (context: Context.Context<Scope.Scope | Exclude<R, Tracer.ParentSpan>>) => {
23 const traceId = NodeCrypto.randomUUID().replaceAll("-", "");
24 const root = Tracer.externalSpan({
25 traceId,
26 spanId: traceId.slice(0, 16),
27 sampled: true,
28 });
29 const detached = Context.add(context, Tracer.ParentSpan, root);
30 return Context.makeUnsafe<Scope.Scope | R>(new Map(detached.mapUnsafe));
31 },
32 );
33
34/** Forks a long-running root before commit and proves it is parked at the activation boundary. */
35export const forkParked = <A, E, R>(
36 effect: Effect.Effect<A, E, R>,
37): Effect.Effect<void, never, Scope.Scope | Exclude<R, Tracer.ParentSpan>> =>
38 Effect.gen(function* () {
39 const activation = yield* ServerActivation;
40 if (activation === undefined) {
41 yield* forkScopedDetached(effect);
42 return;
43 }
44 const parked = yield* Deferred.make<void>();
45 yield* forkScopedDetached(
46 Deferred.succeed(parked, undefined).pipe(Effect.andThen(activation), Effect.andThen(effect)),
47 );
48 yield* Deferred.await(parked);
49 });