Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/api/src/middleware/sentryTracing.ts
T

164 lines
5.5 KiB
TypeScript

/**
* Per-request Sentry tracing middleware for the Hono API.
*
* Hono has no first-party Sentry integration, so we wrap each request in a
* manual `Sentry.startSpan({ op: 'http.server', ... })`. The span name uses
* the matched route pattern (`c.req.routePath`) when available — falling
* back to the literal path — so high-cardinality URLs (`/v1/widgets/:id`)
* group correctly in the Sentry Performance UI.
*
* The middleware self-disables when `SENTRY_DSN_API` is empty: it simply
* calls `next()` without touching the Sentry SDK. This keeps local dev
* and Sentry-less staging environments noise-free.
*
* @see docs/improvement-plan/02-observability/sentry-wiring-api-worker.md
*/
import type { Context, MiddlewareHandler } from "hono";
export type SentryStartSpanArgs = {
op: string;
name: string;
attributes?: Record<string, string | number | boolean | undefined>;
};
export type SentrySpan = {
setAttribute(key: string, value: string | number | boolean | undefined): void;
setStatus?(status: { code: number; message?: string }): void;
};
export type SentryLikeForTracing = {
startSpan: <T>(args: SentryStartSpanArgs, callback: (span: SentrySpan) => Promise<T> | T) => Promise<T> | T;
captureException: (error: unknown, captureContext?: Record<string, unknown>) => void;
};
export interface SentryTracingMiddlewareOptions {
/**
* Set to false to short-circuit the middleware (used when `SENTRY_DSN_API`
* is empty). Defaults to true.
*/
enabled?: boolean;
/**
* Optional Sentry-like module. Production code injects `@sentry/node`;
* tests pass a fake.
*/
sentry?: SentryLikeForTracing | undefined;
/**
* Optional override for the loader used when `sentry` is not provided.
* Defaults to a dynamic `import('@sentry/node')`.
*/
loadSentry?: () => Promise<SentryLikeForTracing | undefined>;
}
let cachedSentry: SentryLikeForTracing | undefined;
let cachedLoad: Promise<SentryLikeForTracing | undefined> | undefined;
async function defaultLoadSentry(): Promise<SentryLikeForTracing | undefined> {
if (cachedSentry) return cachedSentry;
if (!cachedLoad) {
cachedLoad = (async () => {
try {
const moduleName = "@sentry/node";
const loaded = (await import(/* @vite-ignore */ moduleName)) as SentryLikeForTracing & {
default?: SentryLikeForTracing;
};
const resolved =
typeof loaded?.startSpan === "function"
? loaded
: typeof loaded?.default?.startSpan === "function"
? loaded.default
: undefined;
cachedSentry = resolved;
return resolved;
} catch {
return undefined;
}
})();
}
return cachedLoad;
}
export function createSentryTracingMiddleware(options: SentryTracingMiddlewareOptions = {}): MiddlewareHandler {
const enabled = options.enabled ?? Boolean(process.env.SENTRY_DSN_API);
return async function sentryTracingMiddleware(c: Context, next) {
if (!enabled) {
await next();
return;
}
const sentry = options.sentry ?? (await (options.loadSentry ?? defaultLoadSentry)());
if (!sentry) {
await next();
return;
}
const method = c.req.method;
const routePattern = getRoutePattern(c);
const requestId = c.get("requestId");
await sentry.startSpan(
{
op: "http.server",
name: `${method} ${routePattern}`,
attributes: {
"http.method": method,
"http.target": c.req.path,
"http.route": routePattern,
...(typeof requestId === "string" && requestId ? { "toolctrl.request_id": requestId } : {}),
},
},
async (span) => {
let thrownError: unknown;
try {
await next();
} catch (error) {
thrownError = error;
}
// Hono routes throws through `app.onError`, leaving the dispatched
// error attached to `c.error` rather than propagating it through
// the middleware chain. We treat either signal as an unhandled
// exception and forward it to Sentry with span context.
const honoError = (c as unknown as { error?: unknown }).error;
const errorForCapture = thrownError ?? honoError;
const status = c.res?.status ?? (errorForCapture ? 500 : 200);
span.setAttribute("http.status_code", status);
if (status >= 500 || errorForCapture) {
span.setStatus?.({ code: 2, message: "internal_error" });
} else if (status >= 400) {
span.setStatus?.({ code: 1, message: "client_error" });
}
if (errorForCapture) {
sentry.captureException(errorForCapture, {
tags: {
component: "api",
"http.method": method,
"http.route": routePattern,
},
});
}
if (thrownError) {
throw thrownError;
}
}
);
};
}
function getRoutePattern(c: Context): string {
// Hono exposes `routePath` via the underlying request shape when a route
// matched; otherwise we degrade to the literal path. Both branches keep
// cardinality bounded for the Sentry transaction-name field.
const candidate = (c as unknown as { req: { routePath?: string; matchedPath?: string; path: string } }).req;
return candidate.routePath ?? candidate.matchedPath ?? candidate.path;
}
/** Test-only: reset the lazy `@sentry/node` cache. */
export function __resetSentryTracingForTests(): void {
cachedSentry = undefined;
cachedLoad = undefined;
}