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