Open History to see the last commit
1import { WS_METHODS } from "@t3tools/contracts";
2import { Clock, Duration, Effect, Exit, Metric, References, Stream } from "effect";
3
4import { outcomeFromExit } from "./Attributes.ts";
5import { metricAttributes, rpcRequestDuration, rpcRequestsTotal, withMetrics } from "./Metrics.ts";
6
7const RPC_SPAN_PREFIX = "ws.rpc";
8const DEFAULT_RPC_SPAN_ATTRIBUTES = {
9 "rpc.transport": "websocket",
10 "rpc.system": "effect-rpc",
11} as const;
12const RPC_METHODS_WITH_TRACING_DISABLED: ReadonlySet<string> = new Set([
13 WS_METHODS.serverGetTraceDiagnostics,
14 WS_METHODS.serverGetProcessDiagnostics,
15 WS_METHODS.serverSignalProcess,
16]);
17
18function shouldTraceRpc(method: string): boolean {
19 return !RPC_METHODS_WITH_TRACING_DISABLED.has(method);
20}
21
22const rpcSpanAttributes = (
23 method: string,
24 traceAttributes?: Readonly<Record<string, unknown>>,
25): Record<string, unknown> => ({
26 ...DEFAULT_RPC_SPAN_ATTRIBUTES,
27 "rpc.method": method,
28 ...traceAttributes,
29});
30
31const withRpcEffectTracing = <A, E, R>(
32 method: string,
33 effect: Effect.Effect<A, E, R>,
34 traceAttributes?: Readonly<Record<string, unknown>>,
35): Effect.Effect<A, E, R> =>
36 shouldTraceRpc(method)
37 ? effect.pipe(
38 Effect.withSpan(`${RPC_SPAN_PREFIX}.${method}`, {
39 attributes: rpcSpanAttributes(method, traceAttributes),
40 }),
41 )
42 : effect.pipe(Effect.provideService(References.TracerEnabled, false));
43
44const withRpcStreamTracing = <A, E, R>(
45 method: string,
46 stream: Stream.Stream<A, E, R>,
47 traceAttributes?: Readonly<Record<string, unknown>>,
48): Stream.Stream<A, E, R> =>
49 shouldTraceRpc(method)
50 ? stream.pipe(
51 Stream.withSpan(`${RPC_SPAN_PREFIX}.${method}`, {
52 attributes: rpcSpanAttributes(method, traceAttributes),
53 }),
54 )
55 : stream.pipe(Stream.provideService(References.TracerEnabled, false));
56
57const recordRpcStreamMetrics = <E>(
58 method: string,
59 startedAt: bigint,
60 exit: Exit.Exit<unknown, E>,
61): Effect.Effect<void, never, never> =>
62 Effect.gen(function* () {
63 const endedAt = yield* Clock.currentTimeNanos;
64 const elapsedNanos = endedAt > startedAt ? endedAt - startedAt : 0n;
65
66 yield* Metric.update(
67 Metric.withAttributes(rpcRequestDuration, metricAttributes({ method })),
68 Duration.nanos(elapsedNanos),
69 );
70 yield* Metric.update(
71 Metric.withAttributes(
72 rpcRequestsTotal,
73 metricAttributes({
74 method,
75 outcome: outcomeFromExit(exit),
76 }),
77 ),
78 1,
79 );
80 });
81
82export const observeRpcEffect = <A, E, R>(
83 method: string,
84 effect: Effect.Effect<A, E, R>,
85 traceAttributes?: Readonly<Record<string, unknown>>,
86): Effect.Effect<A, E, R> => {
87 const instrumented = effect.pipe(
88 withMetrics({
89 counter: rpcRequestsTotal,
90 timer: rpcRequestDuration,
91 attributes: {
92 method,
93 },
94 }),
95 );
96
97 return withRpcEffectTracing(method, instrumented, traceAttributes);
98};
99
100export const observeRpcStream = <A, E, R>(
101 method: string,
102 stream: Stream.Stream<A, E, R>,
103 traceAttributes?: Readonly<Record<string, unknown>>,
104): Stream.Stream<A, E, R> => {
105 const instrumented = Stream.unwrap(
106 Effect.gen(function* () {
107 const startedAt = yield* Clock.currentTimeNanos;
108 return stream.pipe(Stream.onExit((exit) => recordRpcStreamMetrics(method, startedAt, exit)));
109 }),
110 );
111
112 return withRpcStreamTracing(method, instrumented, traceAttributes);
113};
114
115export const observeRpcStreamEffect = <A, StreamError, StreamContext, EffectError, EffectContext>(
116 method: string,
117 effect: Effect.Effect<Stream.Stream<A, StreamError, StreamContext>, EffectError, EffectContext>,
118 traceAttributes?: Readonly<Record<string, unknown>>,
119): Stream.Stream<A, StreamError | EffectError, StreamContext | EffectContext> => {
120 const instrumented = Stream.unwrap(
121 Effect.gen(function* () {
122 const startedAt = yield* Clock.currentTimeNanos;
123 const exit = yield* Effect.exit(effect);
124
125 if (Exit.isFailure(exit)) {
126 yield* recordRpcStreamMetrics(method, startedAt, exit);
127 return yield* Effect.failCause(exit.cause);
128 }
129
130 return exit.value.pipe(
131 Stream.onExit((streamExit) => recordRpcStreamMetrics(method, startedAt, streamExit)),
132 );
133 }),
134 );
135
136 return withRpcStreamTracing(method, instrumented, traceAttributes);
137};