Open History to see the last commit
1import {
2 RelayClientTracer,
3 withLocalTracing,
4 withRelayClientTracing,
5} from "@t3tools/shared/relayTracing";
6import * as Clock from "effect/Clock";
7import * as Context from "effect/Context";
8import * as Effect from "effect/Effect";
9import * as Exit from "effect/Exit";
10import * as Option from "effect/Option";
11import * as Tracer from "effect/Tracer";
12import { HttpServerRequest, HttpTraceContext } from "effect/http";
13
14export const traceRelayRequest = <A, E, R>(
15 effect: Effect.Effect<A, E, R>,
16): Effect.Effect<A, E, R> => effect.pipe(withRelayClientTracing);
17
18/**
19 * Call it only after the session is verified as T3 Connect: an unverified
20 * request must not add spans to a trace it names. Authentication therefore
21 * runs on the local tracer, and its timing is recorded here afterwards.
22 */
23export const traceAuthenticatedRelayRequest = <A, E, R>(
24 effect: Effect.Effect<A, E, R>,
25 authentication: { readonly startTime: bigint; readonly endTime: bigint },
26): Effect.Effect<A, E, R | HttpServerRequest.HttpServerRequest> =>
27 Effect.all([RelayClientTracer, HttpServerRequest.HttpServerRequest]).pipe(
28 Effect.flatMap(([tracer, request]): Effect.Effect<A, E, R> => {
29 if (Option.isNone(tracer)) return effect;
30 const parent = HttpTraceContext.fromHeaders(request.headers);
31 const sampled = Option.isNone(parent) || parent.value.sampled;
32 const startSpan = (
33 name: string,
34 kind: Tracer.SpanKind,
35 parent: Option.Option<Tracer.AnySpan>,
36 ) =>
37 tracer.value.span({
38 name,
39 parent,
40 annotations: Context.empty(),
41 links: [],
42 startTime: authentication.startTime,
43 kind,
44 root: Option.isNone(parent),
45 sampled,
46 });
47 const span = startSpan("environment.relay.request", "server", parent);
48 startSpan("EnvironmentAuth.authenticateHttpRequest", "internal", Option.some(span)).end(
49 authentication.endTime,
50 Exit.void,
51 );
52 return effect.pipe(
53 Effect.withParentSpan(span),
54 Effect.onExit((exit) =>
55 Clock.currentTimeNanos.pipe(Effect.map((endTime) => span.end(endTime, exit))),
56 ),
57 withRelayClientTracing,
58 );
59 }),
60 );
61
62export const traceLocalHandlerWork = withLocalTracing;