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

RpcInstrumentation.ts

89 lines2.7 KB

1import { Duration, Effect, Exit, Metric, Stream } from "effect";
2​
3import { outcomeFromExit } from "./Attributes.ts";
4import { metricAttributes, rpcRequestDuration, rpcRequestsTotal, withMetrics } from "./Metrics.ts";
5​
6const annotateRpcSpan = (
7 method: string,
8 traceAttributes?: Readonly<Record<string, unknown>>,
9): Effect.Effect<void, never, never> =>
10 Effect.annotateCurrentSpan({
11 "rpc.method": method,
12 ...traceAttributes,
13 });
14​
15const recordRpcStreamMetrics = <E>(
16 method: string,
17 startedAt: number,
18 exit: Exit.Exit<unknown, E>,
19): Effect.Effect<void, never, never> =>
20 Effect.gen(function* () {
21 yield* Metric.update(
22 Metric.withAttributes(rpcRequestDuration, metricAttributes({ method })),
23 Duration.millis(Math.max(0, Date.now() - startedAt)),
24 );
25 yield* Metric.update(
26 Metric.withAttributes(
27 rpcRequestsTotal,
28 metricAttributes({
29 method,
30 outcome: outcomeFromExit(exit),
31 }),
32 ),
33 1,
34 );
35 });
36​
37export const observeRpcEffect = <A, E, R>(
38 method: string,
39 effect: Effect.Effect<A, E, R>,
40 traceAttributes?: Readonly<Record<string, unknown>>,
41): Effect.Effect<A, E, R> =>
42 Effect.gen(function* () {
43 yield* annotateRpcSpan(method, traceAttributes);
44​
45 return yield* effect.pipe(
46 withMetrics({
47 counter: rpcRequestsTotal,
48 timer: rpcRequestDuration,
49 attributes: {
50 method,
51 },
52 }),
53 );
54 });
55​
56export const observeRpcStream = <A, E, R>(
57 method: string,
58 stream: Stream.Stream<A, E, R>,
59 traceAttributes?: Readonly<Record<string, unknown>>,
60): Stream.Stream<A, E, R> =>
61 Stream.unwrap(
62 Effect.gen(function* () {
63 yield* annotateRpcSpan(method, traceAttributes);
64 const startedAt = Date.now();
65 return stream.pipe(Stream.onExit((exit) => recordRpcStreamMetrics(method, startedAt, exit)));
66 }),
67 );
68​
69export const observeRpcStreamEffect = <A, StreamError, StreamContext, EffectError, EffectContext>(
70 method: string,
71 effect: Effect.Effect<Stream.Stream<A, StreamError, StreamContext>, EffectError, EffectContext>,
72 traceAttributes?: Readonly<Record<string, unknown>>,
73): Stream.Stream<A, StreamError | EffectError, StreamContext | EffectContext> =>
74 Stream.unwrap(
75 Effect.gen(function* () {
76 yield* annotateRpcSpan(method, traceAttributes);
77 const startedAt = Date.now();
78 const exit = yield* Effect.exit(effect);
79​
80 if (Exit.isFailure(exit)) {
81 yield* recordRpcStreamMetrics(method, startedAt, exit);
82 return yield* Effect.failCause(exit.cause);
83 }
84​
85 return exit.value.pipe(
86 Stream.onExit((streamExit) => recordRpcStreamMetrics(method, startedAt, streamExit)),
87 );
88 }),
89 );