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

serverActivation.ts

43 lines1.5 KB

1import * as Context from "effect/Context";
2import * as Deferred from "effect/Deferred";
3import * as Effect from "effect/Effect";
4import type * as Scope from "effect/Scope";
5import * as Tracer from "effect/Tracer";
6​
7export class ServerActivation extends Context.Reference<Effect.Effect<void> | undefined>(
8 "t3/serverActivation",
9 { defaultValue: () => undefined },
10) {}
11​
12// Clear inherited ParentSpan so long-lived forks don't pin short-lived startup spans (#5410).
13export const withoutAmbientParentSpan = <A, E, R>(
14 effect: Effect.Effect<A, E, R>,
15): Effect.Effect<A, E, Exclude<R, Tracer.ParentSpan>> =>
16 Effect.updateContext(
17 effect,
18 (context) =>
19 Context.omit(Tracer.ParentSpan)(context) as Context.Context<
20 Exclude<NoInfer<R>, Tracer.ParentSpan>
21 >,
22 );
23​
24/** Forks a long-running root before commit and proves it is parked at the activation boundary. */
25export const forkParked = <A, E, R>(
26 effect: Effect.Effect<A, E, R>,
27): Effect.Effect<void, never, Scope.Scope | R> =>
28 Effect.gen(function* () {
29 const activation = yield* ServerActivation;
30 const detached = withoutAmbientParentSpan(effect);
31 if (activation === undefined) {
32 yield* Effect.forkScoped(detached);
33 return;
34 }
35 const parked = yield* Deferred.make<void>();
36 yield* Effect.forkScoped(
37 Deferred.succeed(parked, undefined).pipe(
38 Effect.andThen(activation),
39 Effect.andThen(detached),
40 ),
41 );
42 yield* Deferred.await(parked);
43 });