trpc-monitoring-middleware 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,8 @@
1
+ Copyright 2026 Alexis Tacnet
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
8
+
package/README.md ADDED
@@ -0,0 +1,96 @@
1
+ # tRPC monitoring middleware
2
+
3
+ A simple tRPC middleware for monitoring and logging procedures.
4
+
5
+ ## Features
6
+
7
+ - OpenTelemetry integration for metrics and traces
8
+ - Requests logging
9
+
10
+ ## Installation
11
+
12
+ ```bash
13
+ npm install trpc-monitoring-middleware
14
+ ```
15
+
16
+ ## Usage
17
+
18
+ ```typescript
19
+ import { initTRPC } from "@trpc/server";
20
+ import { createMonitoringMiddleware } from "trpc-monitoring-middleware";
21
+
22
+ const t = initTRPC.create();
23
+
24
+ const monitoringMiddleware = createMonitoringMiddleware();
25
+
26
+ export const publicProcedure = procedure.concat(monitoringMiddleware);
27
+ ```
28
+
29
+ ## OpenTelemetry Integration
30
+
31
+ The middleware automatically exports the following metrics:
32
+
33
+ - `trpc.procedures`: Counter for the total number of tRPC procedure calls
34
+ - `trpc.time`: Histogram for the duration of tRPC procedure execution in milliseconds
35
+
36
+ These metrics are labeled with:
37
+
38
+ - `path`: The tRPC procedure path
39
+ - `type`: The procedure type (query/mutation/subscription)
40
+ - `ok`: Boolean indicating success/failure
41
+ - `error_code`: Error code for failed procedures
42
+
43
+ The middleware also creates OpenTelemetry traces for each procedure call with:
44
+
45
+ - Span name: `trpc/${path} (${type})`
46
+ - Attributes: path, type, ok status, and error details
47
+
48
+ ## Logging Integration
49
+
50
+ The middleware provides structured logging through a compatible logger interface. It is recommended to use [Pino](https://github.com/pinojs/pino) or [Winston](https://github.com/winstonjs/winston) as a logger.
51
+
52
+ - **Procedure-specific logging**: Each procedure gets a child logger with procedure context
53
+ - **Error logging**: Internal errors and unexpected errors are logged with full error details
54
+ - **Error classification**: Internal server errors are automatically detected and logged separately
55
+
56
+ Error codes classified as internal errors:
57
+
58
+ - `INTERNAL_SERVER_ERROR`
59
+ - `NOT_IMPLEMENTED`
60
+ - `BAD_GATEWAY`
61
+ - `SERVICE_UNAVAILABLE`
62
+ - `GATEWAY_TIMEOUT`
63
+
64
+ ## Configuration
65
+
66
+ ```typescript
67
+ import { createMonitoringMiddleware } from "trpc-monitoring-middleware";
68
+
69
+ const monitoringMiddleware = createMonitoringMiddleware({
70
+ onInternalError: (error: Error) => {
71
+ // Custom error handling
72
+ console.error("Internal error:", error);
73
+ },
74
+ logger: {
75
+ error: (errorData, message) => {
76
+ // Custom error logging
77
+ console.error(message, errorData);
78
+ },
79
+ child: (data) => {
80
+ // Return a new logger instance with additional context
81
+ return {
82
+ error: (errorData, message) => {
83
+ console.error(message, { ...data, ...errorData });
84
+ },
85
+ child: (additionalData) => {
86
+ return this.child({ ...data, ...additionalData });
87
+ },
88
+ };
89
+ },
90
+ },
91
+ });
92
+ ```
93
+
94
+ ## License
95
+
96
+ MIT
@@ -0,0 +1,21 @@
1
+ import * as _trpc_server0 from "@trpc/server";
2
+
3
+ //#region src/index.d.ts
4
+ interface MonitoringMiddlewareCompatibleLogger {
5
+ error: (error: Record<string, unknown>, message: string) => void;
6
+ child: (data: Record<string, unknown>) => MonitoringMiddlewareCompatibleLogger;
7
+ }
8
+ interface MonitoringMiddlewareOptions {
9
+ onInternalError?: (error: Error) => void;
10
+ logger?: MonitoringMiddlewareCompatibleLogger;
11
+ }
12
+ /**
13
+ * Creates a middleware for monitoring tRPC procedures using OpenTelemetry.
14
+ *
15
+ * @param pluginOpts - Optional configuration for the middleware.
16
+ */
17
+ declare function createMonitoringMiddleware(pluginOpts?: MonitoringMiddlewareOptions): _trpc_server0.TRPCProcedureBuilder<object, object, {
18
+ logger: MonitoringMiddlewareCompatibleLogger | undefined;
19
+ }, _trpc_server0.TRPCUnsetMarker, _trpc_server0.TRPCUnsetMarker, _trpc_server0.TRPCUnsetMarker, _trpc_server0.TRPCUnsetMarker, false>;
20
+ //#endregion
21
+ export { createMonitoringMiddleware };
package/dist/index.mjs ADDED
@@ -0,0 +1,86 @@
1
+ import { metrics, trace } from "@opentelemetry/api";
2
+ import { initTRPC } from "@trpc/server";
3
+
4
+ //#region src/index.ts
5
+ const INTERNAL_ERRORS = new Set([
6
+ "INTERNAL_SERVER_ERROR",
7
+ "NOT_IMPLEMENTED",
8
+ "BAD_GATEWAY",
9
+ "SERVICE_UNAVAILABLE",
10
+ "GATEWAY_TIMEOUT"
11
+ ]);
12
+ const tracer = trace.getTracer("trpc");
13
+ const meter = metrics.getMeter("trpc");
14
+ const trpcProcedures = meter.createCounter("trpc.procedures");
15
+ const trpcTime = meter.createHistogram("trpc.time");
16
+ function createSpanAttributes(path, type) {
17
+ return {
18
+ path,
19
+ type
20
+ };
21
+ }
22
+ function handleProcedureCompletion(span, procedure, meta, logger) {
23
+ span.setAttributes({ ok: procedure.ok });
24
+ if (!procedure.ok && procedure.error) {
25
+ const isInternalError = INTERNAL_ERRORS.has(procedure.error.code);
26
+ span.setAttributes({
27
+ error_code: procedure.error.code,
28
+ internal_error: isInternalError
29
+ });
30
+ if (isInternalError) logger?.error({ error: procedure.error }, "[trpc] Internal error");
31
+ trpcProcedures.add(1, {
32
+ ...meta,
33
+ error_code: procedure.error.code,
34
+ ok: false
35
+ });
36
+ } else trpcProcedures.add(1, {
37
+ ...meta,
38
+ ok: true
39
+ });
40
+ }
41
+ function handleUnexpectedError(error, span, meta, logger, onInternalError) {
42
+ span.setAttributes({
43
+ ok: false,
44
+ unexpected_error: true
45
+ });
46
+ logger?.error({ error }, "[trpc] Unexpected error");
47
+ trpcProcedures.add(1, {
48
+ ...meta,
49
+ ok: false,
50
+ error_code: "UNEXPECTED_ERROR"
51
+ });
52
+ onInternalError?.(error);
53
+ throw error;
54
+ }
55
+ /**
56
+ * Creates a middleware for monitoring tRPC procedures using OpenTelemetry.
57
+ *
58
+ * @param pluginOpts - Optional configuration for the middleware.
59
+ */
60
+ function createMonitoringMiddleware(pluginOpts) {
61
+ const t = initTRPC.create();
62
+ const { onInternalError, logger } = pluginOpts ?? {};
63
+ return t.procedure.use((opts) => {
64
+ return tracer.startActiveSpan(`trpc/${opts.path} (${opts.type})`, async (span) => {
65
+ const start = performance.now();
66
+ const meta = createSpanAttributes(opts.path, opts.type);
67
+ const procedureLogger = logger?.child({ procedure: meta });
68
+ span.setAttributes(meta);
69
+ try {
70
+ const procedure = await opts.next({ ctx: { logger: procedureLogger } });
71
+ handleProcedureCompletion(span, procedure, meta, procedureLogger);
72
+ return procedure;
73
+ } catch (error) {
74
+ handleUnexpectedError(error, span, meta, procedureLogger, onInternalError);
75
+ throw error;
76
+ } finally {
77
+ span.end();
78
+ const end = performance.now();
79
+ trpcTime.record(end - start, meta);
80
+ }
81
+ });
82
+ });
83
+ }
84
+
85
+ //#endregion
86
+ export { createMonitoringMiddleware };
package/package.json ADDED
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "trpc-monitoring-middleware",
3
+ "type": "module",
4
+ "version": "0.0.1",
5
+ "description": "A tRPC middleware for monitoring procedures",
6
+ "author": "Alexis Tacnet <alexistacnet@gmail.com>",
7
+ "license": "MIT",
8
+ "homepage": "https://github.com/fuegoio/trpc-monitoring-middleware#readme",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/fuegoio/trpc-monitoring-middleware.git"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/fuegoio/trpc-monitoring-middleware/issues"
15
+ },
16
+ "exports": {
17
+ ".": "./dist/index.mjs",
18
+ "./package.json": "./package.json"
19
+ },
20
+ "main": "./dist/index.mjs",
21
+ "module": "./dist/index.mjs",
22
+ "types": "./dist/index.d.mts",
23
+ "files": [
24
+ "dist"
25
+ ],
26
+ "scripts": {
27
+ "build": "tsdown",
28
+ "dev": "tsdown --watch",
29
+ "typecheck": "tsc --noEmit",
30
+ "prepublishOnly": "pnpm run build"
31
+ },
32
+ "devDependencies": {
33
+ "@types/node": "^25.0.3",
34
+ "bumpp": "^10.3.2",
35
+ "tsdown": "^0.18.1",
36
+ "typescript": "^5.9.3"
37
+ },
38
+ "peerDependencies": {
39
+ "@opentelemetry/api": "*",
40
+ "@trpc/server": "^11.0.0"
41
+ }
42
+ }