|
| 1 | +import { trace, metrics, SpanStatusCode } from "@opentelemetry/api"; |
| 2 | +import type { RpcClient } from "./client.ts"; |
| 3 | + |
| 4 | +const tracer = trace.getTracer("vow-witness"); |
| 5 | +const meter = metrics.getMeter("vow-witness"); |
| 6 | + |
| 7 | +const durationHistogram = meter.createHistogram("vow.rpc.duration", { |
| 8 | + description: "RPC call duration in milliseconds", |
| 9 | + unit: "ms", |
| 10 | +}); |
| 11 | + |
| 12 | +const errorsCounter = meter.createCounter("vow.rpc.errors", { |
| 13 | + description: "RPC call error count", |
| 14 | +}); |
| 15 | + |
| 16 | +type RpcMethod = "getBlock" | "getLogs" | "getBlockNumber"; |
| 17 | + |
| 18 | +function wrapMethod<T extends (...args: any[]) => Promise<any>>( |
| 19 | + method: T, |
| 20 | + name: RpcMethod, |
| 21 | + attrs: { "rpc.url": string; "chain.id": number } |
| 22 | +): T { |
| 23 | + return (async (...args: any[]) => { |
| 24 | + const spanAttrs = { "rpc.method": name, ...attrs }; |
| 25 | + const start = Date.now(); |
| 26 | + |
| 27 | + return tracer.startActiveSpan(`rpc.${name}`, { attributes: spanAttrs }, async (span) => { |
| 28 | + try { |
| 29 | + const result = await method(...args); |
| 30 | + durationHistogram.record(Date.now() - start, spanAttrs); |
| 31 | + return result; |
| 32 | + } catch (err: any) { |
| 33 | + durationHistogram.record(Date.now() - start, spanAttrs); |
| 34 | + errorsCounter.add(1, { ...spanAttrs, "error.type": err?.constructor?.name ?? "Error" }); |
| 35 | + span.recordException(err); |
| 36 | + span.setStatus({ code: SpanStatusCode.ERROR }); |
| 37 | + throw err; |
| 38 | + } finally { |
| 39 | + span.end(); |
| 40 | + } |
| 41 | + }); |
| 42 | + }) as T; |
| 43 | +} |
| 44 | + |
| 45 | +export function instrumentRpcClient( |
| 46 | + client: RpcClient, |
| 47 | + attrs: { url: string; chainId: number } |
| 48 | +): RpcClient { |
| 49 | + const commonAttrs = { "rpc.url": attrs.url, "chain.id": attrs.chainId }; |
| 50 | + return { |
| 51 | + getBlock: wrapMethod(client.getBlock.bind(client), "getBlock", commonAttrs), |
| 52 | + getLogs: wrapMethod(client.getLogs.bind(client), "getLogs", commonAttrs), |
| 53 | + getBlockNumber: wrapMethod(client.getBlockNumber.bind(client), "getBlockNumber", commonAttrs), |
| 54 | + }; |
| 55 | +} |
0 commit comments