Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

👷 build(observability-otel): support to trace and meter for tRPC (#10086)

Neko9f762e12bed0
diff --git a/packages/obervability-otel/package.json b/packages/obervability-otel/package.json
index 20d0866b86f..0de0ab0a8ee 100644
--- a/packages/obervability-otel/package.json
+++ b/packages/obervability-otel/package.json
@@ -3,7 +3,9 @@
"version": "1.0.0",
"private": true,
"exports": {
- "./node": "./src/node.ts"
+ "./node": "./src/node.ts",
+ "./api": "./src/api.ts",
+ "./trpc": "./src/trpc/index.ts"
},
"dependencies": {
"@opentelemetry/api": "^1.9.0",
diff --git a/packages/obervability-otel/src/api.ts b/packages/obervability-otel/src/api.ts
new file mode 100644
index 00000000000..d3fede9e748
--- /dev/null
+++ b/packages/obervability-otel/src/api.ts
@@ -0,0 +1,2 @@
+export type { Attributes, Span } from '@opentelemetry/api';
+export { diag, metrics, SpanKind, SpanStatusCode, trace } from '@opentelemetry/api';
diff --git a/packages/obervability-otel/src/trpc/convention.ts b/packages/obervability-otel/src/trpc/convention.ts
new file mode 100644
index 00000000000..3ea08c370a0
--- /dev/null
+++ b/packages/obervability-otel/src/trpc/convention.ts
@@ -0,0 +1,16 @@
+export enum TRPCAttribute {
+ RPC_METHOD = 'rpc.method',
+ RPC_SERVICE = 'rpc.service',
+ RPC_SYSTEM = 'rpc.system',
+ RPC_TRPC_PATH = 'rpc.trpc.path',
+ RPC_TRPC_STATUS_CODE = 'rpc.trpc.status_code',
+ RPC_TRPC_SUCCESS = 'rpc.trpc.success',
+ RPC_TRPC_TYPE = 'rpc.trpc.type',
+}
+
+export {
+ ATTR_ERROR_TYPE,
+ ATTR_EXCEPTION_MESSAGE,
+ ATTR_EXCEPTION_STACKTRACE,
+ ATTR_EXCEPTION_TYPE,
+} from '@opentelemetry/semantic-conventions';
diff --git a/packages/obervability-otel/src/trpc/index.test.ts b/packages/obervability-otel/src/trpc/index.test.ts
new file mode 100644
index 00000000000..35e26c1fdd8
--- /dev/null
+++ b/packages/obervability-otel/src/trpc/index.test.ts
@@ -0,0 +1,38 @@
+import { parseTRPCPath, tRPCConventionFromPathAndType } from './';
+
+describe('splitRpcPath', () => {
+ it('should split path into service and method with url', () => {
+ const { method, service } = parseTRPCPath('/trpc/lambda/someService.someMethod');
+ expect(method).toBe('someMethod');
+ expect(service).toBe('someService');
+ });
+
+ it('should split path into service and method without url', () => {
+ const { method, service } = parseTRPCPath('someService.someMethod');
+ expect(method).toBe('someMethod');
+ expect(service).toBe('someService');
+ });
+});
+
+describe('createBaseAttributes', () => {
+ it('should create base attributes with service and method', () => {
+ const attributes = tRPCConventionFromPathAndType('someService.someMethod', 'query');
+ expect(attributes).toEqual({
+ 'rpc.system': 'trpc',
+ 'rpc.trpc.path': 'someService.someMethod',
+ 'rpc.trpc.type': 'query',
+ 'rpc.service': 'someService',
+ 'rpc.method': 'someMethod',
+ });
+ });
+
+ it('should create base attributes without service', () => {
+ const attributes = tRPCConventionFromPathAndType('someMethod', 'mutation');
+ expect(attributes).toEqual({
+ 'rpc.system': 'trpc',
+ 'rpc.trpc.path': 'someMethod',
+ 'rpc.trpc.type': 'mutation',
+ 'rpc.method': 'someMethod',
+ });
+ });
+});
diff --git a/packages/obervability-otel/src/trpc/index.ts b/packages/obervability-otel/src/trpc/index.ts
new file mode 100644
index 00000000000..8c7b69b59e8
--- /dev/null
+++ b/packages/obervability-otel/src/trpc/index.ts
@@ -0,0 +1,62 @@
+import { Attributes } from '@opentelemetry/api';
+
+import { TRPCAttribute } from './convention';
+
+export const DEFAULT_ERROR_CODE = 'UNKNOWN_ERROR';
+export const DEFAULT_SUCCESS_STATUS = 'OK';
+
+const textEncoder = new TextEncoder();
+
+export function parseTRPCPath(path: string) {
+ const parts = path?.split('.') ?? [];
+ if (parts.length <= 1) {
+ return { method: path, service: undefined };
+ }
+
+ const method = parts.at(-1);
+ const service = parts.slice(0, -1).join('.').split('/').pop();
+ return { method, service };
+}
+
+export function tRPCConventionFromPathAndType(path: string, type: string): Attributes {
+ const { method, service } = parseTRPCPath(path);
+
+ const attributes: Attributes = {
+ [TRPCAttribute.RPC_SYSTEM]: 'trpc',
+ [TRPCAttribute.RPC_TRPC_PATH]: path,
+ [TRPCAttribute.RPC_TRPC_TYPE]: type,
+ };
+
+ if (service) {
+ attributes[TRPCAttribute.RPC_SERVICE] = service;
+ }
+ if (method) {
+ attributes[TRPCAttribute.RPC_METHOD] = method;
+ }
+
+ return attributes;
+}
+
+export const getPayloadSize = (payload: unknown): number | undefined => {
+ if (payload === undefined || payload === null) return undefined;
+
+ try {
+ const serialized = JSON.stringify(payload);
+ return textEncoder.encode(serialized).length;
+ } catch {
+ return undefined;
+ }
+};
+
+export const createAttributesForMetrics = (
+ baseAttributes: Attributes,
+ statusCode: string,
+ extraAttributes?: Attributes,
+): Attributes => ({
+ ...baseAttributes,
+ [TRPCAttribute.RPC_TRPC_STATUS_CODE]: statusCode,
+ ...extraAttributes,
+});
+
+export * from './convention';
+export * from './metrics';
diff --git a/packages/obervability-otel/src/trpc/metrics.ts b/packages/obervability-otel/src/trpc/metrics.ts
new file mode 100644
index 00000000000..624c5608a66
--- /dev/null
+++ b/packages/obervability-otel/src/trpc/metrics.ts
@@ -0,0 +1,31 @@
+import { metrics } from '@opentelemetry/api';
+
+const meter = metrics.getMeter('trpc-server');
+
+export const serverDurationHistogram = meter.createHistogram('rpc.server.duration', {
+ description: 'Measures the duration of inbound RPC.',
+ unit: 'ms',
+});
+
+export const serverRequestSizeHistogram = meter.createHistogram('rpc.server.request.size', {
+ description: 'Measures the size of RPC request messages (uncompressed).',
+ unit: 'By',
+});
+
+export const serverResponseSizeHistogram = meter.createHistogram('rpc.server.response.size', {
+ description: 'Measures the size of RPC response messages (uncompressed).',
+ unit: 'By',
+});
+
+export const serverRequestsPerRpcHistogram = meter.createHistogram('rpc.server.requests_per_rpc', {
+ description: 'Measures the number of messages received per RPC.',
+ unit: '{count}',
+});
+
+export const serverResponsesPerRpcHistogram = meter.createHistogram(
+ 'rpc.server.responses_per_rpc',
+ {
+ description: 'Measures the number of messages sent per RPC.',
+ unit: '{count}',
+ },
+);
diff --git a/src/libs/trpc/lambda/index.ts b/src/libs/trpc/lambda/index.ts
index fced42b8266..21f0dcc2f18 100644
--- a/src/libs/trpc/lambda/index.ts
+++ b/src/libs/trpc/lambda/index.ts
@@ -10,6 +10,7 @@
import { DESKTOP_USER_ID } from '@/const/desktop';
import { isDesktop } from '@/const/version';
+import { openTelemetry } from '../middleware/openTelemetry';
import { userAuth } from '../middleware/userAuth';
import { trpc } from './init';
import { oidcAuth } from './middleware/oidcAuth';
@@ -24,14 +25,16 @@ export const router = trpc.router;
* Create an unprotected procedure
* @link https://trpc.io/docs/v11/procedures
**/
-export const publicProcedure = trpc.procedure.use(({ next, ctx }) => {
+const baseProcedure = trpc.procedure.use(openTelemetry);
+
+export const publicProcedure = baseProcedure.use(({ next, ctx }) => {
return next({
ctx: { ...ctx, userId: isDesktop ? DESKTOP_USER_ID : ctx.userId },
});
});
// procedure that asserts that the user is logged in
-export const authedProcedure = trpc.procedure.use(oidcAuth).use(userAuth);
+export const authedProcedure = baseProcedure.use(oidcAuth).use(userAuth);
/**
* Create a server-side caller
diff --git a/src/libs/trpc/middleware/openTelemetry.ts b/src/libs/trpc/middleware/openTelemetry.ts
new file mode 100644
index 00000000000..299e70d12ba
--- /dev/null
+++ b/src/libs/trpc/middleware/openTelemetry.ts
@@ -0,0 +1,141 @@
+import type { Attributes, Span } from '@lobechat/observability-otel/api';
+import { SpanKind, SpanStatusCode, diag, trace } from '@lobechat/observability-otel/api';
+import {
+ ATTR_ERROR_TYPE,
+ ATTR_EXCEPTION_MESSAGE,
+ ATTR_EXCEPTION_STACKTRACE,
+ DEFAULT_ERROR_CODE,
+ DEFAULT_SUCCESS_STATUS,
+ TRPCAttribute,
+ createAttributesForMetrics,
+ getPayloadSize,
+ serverDurationHistogram,
+ serverRequestSizeHistogram,
+ serverRequestsPerRpcHistogram,
+ serverResponseSizeHistogram,
+ serverResponsesPerRpcHistogram,
+ tRPCConventionFromPathAndType,
+} from '@lobechat/observability-otel/trpc';
+import { TRPCError } from '@trpc/server';
+import { env } from 'node:process';
+
+import { name } from '../../../../package.json';
+import { trpc } from '../lambda/init';
+
+const tracer = trace.getTracer('trpc-server');
+
+const recordRpcServerMetrics = ({
+ attributes,
+ durationMs,
+ requestSize,
+ responseSize,
+}: {
+ attributes: Attributes;
+ durationMs: number;
+ requestSize?: number;
+ responseSize?: number;
+}) => {
+ serverDurationHistogram.record(durationMs, attributes);
+ serverRequestsPerRpcHistogram.record(1, attributes);
+ serverResponsesPerRpcHistogram.record(1, attributes);
+
+ if (typeof requestSize === 'number') {
+ serverRequestSizeHistogram.record(requestSize, attributes);
+ }
+
+ if (typeof responseSize === 'number') {
+ serverResponseSizeHistogram.record(responseSize, attributes);
+ }
+};
+
+const finalizeSpanWithError = (span: Span, error: unknown) => {
+ span.setStatus({
+ code: SpanStatusCode.ERROR,
+ message: error instanceof Error ? error.message : 'Unknown error',
+ });
+
+ if (error instanceof Error) {
+ span.recordException(error);
+ span.setAttribute(ATTR_ERROR_TYPE, error.constructor.name);
+ span.setAttribute(ATTR_EXCEPTION_MESSAGE, error.message);
+ span.setAttribute(ATTR_EXCEPTION_STACKTRACE, error.stack || '');
+ }
+};
+
+export const openTelemetry = trpc.middleware(async ({ path, type, next, getRawInput }) => {
+ if (!env.ENABLE_TELEMETRY) {
+ diag.debug(name, 'telemetry disabled', env.ENABLE_TELEMETRY);
+
+ return next();
+ }
+
+ diag.debug(name, 'tRPC instrumentation', 'incomingRequest');
+
+ const spanName = `tRPC ${type.toUpperCase()} ${path}`;
+ const baseAttributes = tRPCConventionFromPathAndType(path, type);
+ const input = getRawInput();
+ const requestSize = getPayloadSize(input);
+
+ const span = tracer.startSpan(spanName, {
+ attributes: baseAttributes,
+ kind: SpanKind.SERVER,
+ });
+
+ const startTimestamp = Date.now();
+
+ try {
+ const result = await next();
+ diag.debug(name, 'tRPC instrumentation', 'requestHandled');
+
+ const responseSize = getPayloadSize(result.ok ? result.data : result.error);
+
+ const durationMs = Date.now() - startTimestamp;
+ const statusCode = result.ok ? DEFAULT_SUCCESS_STATUS : result.error.code;
+ span.setAttribute(TRPCAttribute.RPC_TRPC_STATUS_CODE, statusCode);
+
+ if (result.ok) {
+ span.setStatus({ code: SpanStatusCode.OK });
+ } else {
+ finalizeSpanWithError(span, result.error);
+ }
+
+ recordRpcServerMetrics({
+ attributes: createAttributesForMetrics(baseAttributes, statusCode, {
+ [TRPCAttribute.RPC_TRPC_SUCCESS]: result.ok,
+ ...(result.ok ? undefined : { [ATTR_ERROR_TYPE]: result.error.code }),
+ }),
+ durationMs,
+ requestSize,
+ responseSize,
+ });
+
+ diag.debug(name, 'tRPC instrumentation', 'metrics recorded');
+
+ return result;
+ } catch (error) {
+ diag.error(name, 'tRPC instrumentation', 'requestError', error);
+
+ const durationMs = Date.now() - startTimestamp;
+ const trpcError = error instanceof TRPCError ? error : undefined;
+ const statusCode = trpcError ? trpcError.code : DEFAULT_ERROR_CODE;
+
+ span.setAttribute(TRPCAttribute.RPC_TRPC_STATUS_CODE, statusCode);
+ finalizeSpanWithError(span, error);
+
+ recordRpcServerMetrics({
+ attributes: createAttributesForMetrics(baseAttributes, statusCode, {
+ [TRPCAttribute.RPC_TRPC_SUCCESS]: false,
+ ...(trpcError ? { [ATTR_ERROR_TYPE]: trpcError.code } : undefined),
+ }),
+ durationMs,
+ requestSize,
+ responseSize: getPayloadSize(trpcError ? trpcError : error),
+ });
+
+ diag.error(name, 'tRPC instrumentation', 'metrics recorded with error', error);
+
+ throw error;
+ } finally {
+ span.end();
+ }
+});