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
14/**
15 * Exports every span of a handler that is itself T3 Connect work (the token
16 * exchange, the environment descriptor, credential minting), so the whole
17 * connection path can be measured.
18 */
19export const traceRelayRequest = <A, E, R>(
20 effect: Effect.Effect<A, E, R>,
21): Effect.Effect<A, E, R> => effect.pipe(withRelayClientTracing);
22
23/**
24 * Traces a request that arrived over T3 Connect, continuing the client's
25 * trace. The request's span and its authentication timing are exported, so
26 * their latency and errors are visible; what the handler then does on the
27 * user's machine (database reads, project indexing, processes) is not, unless
28 * the handler is connection work and opts back in with {@link traceRelayRequest}.
29 *
30 * Call it only after the session is verified as T3 Connect: an unverified
31 * request must not add spans to a trace it names. Authentication therefore
32 * runs on the local tracer, and its timing is recorded here afterwards.
33 */
34export const traceAuthenticatedRelayRequest = <A, E, R>(
35 effect: Effect.Effect<A, E, R>,
36 authentication: { readonly startTime: bigint; readonly endTime: bigint },
37): Effect.Effect<A, E, R | HttpServerRequest.HttpServerRequest> =>
38 Effect.all([RelayClientTracer, HttpServerRequest.HttpServerRequest]).pipe(
39 Effect.flatMap(([tracer, request]): Effect.Effect<A, E, R> => {
40 if (Option.isNone(tracer)) return effect;
41 const parent = HttpTraceContext.fromHeaders(request.headers);
42 const sampled = Option.isNone(parent) || parent.value.sampled;
43 const startSpan = (
44 name: string,
45 kind: Tracer.SpanKind,
46 parent: Option.Option<Tracer.AnySpan>,
47 ) =>
48 tracer.value.span({
49 name,
50 parent,
51 annotations: Context.empty(),
52 links: [],
53 startTime: authentication.startTime,
54 kind,
55 root: Option.isNone(parent),
56 sampled,
57 });
58 const span = startSpan("environment.relay.request", "server", parent);
59 startSpan("EnvironmentAuth.authenticateHttpRequest", "internal", Option.some(span)).end(
60 authentication.endTime,
61 Exit.void,
62 );
63 return effect.pipe(
64 Effect.withParentSpan(span),
65 Effect.onExit((exit) =>
66 Clock.currentTimeNanos.pipe(Effect.map((endTime) => span.end(endTime, exit))),
67 ),
68 withRelayClientTracing,
69 );
70 }),
71 );
72
73/**
74 * Keeps the work inside a relay-traced handler on the local tracer. The
75 * handler's span still records the timing and outcome.
76 */
77export const traceLocalHandlerWork = withLocalTracing;