|
| 1 | +import { AsyncLocalStorage } from 'async_hooks' |
| 2 | +import { randomBytes } from 'crypto' |
| 3 | +import { NextResponse } from 'next/server' |
| 4 | +import { logger } from '@/lib/logger' |
| 5 | + |
| 6 | +type RequestContext = { |
| 7 | + requestId: string |
| 8 | +} |
| 9 | + |
| 10 | +type RouteHandler = (...args: any[]) => unknown | Promise<unknown> |
| 11 | + |
| 12 | +const requestContext = new AsyncLocalStorage<RequestContext>() |
| 13 | +const LOGGER_PATCHED = Symbol.for('routes-b.logger.request-id-patched') |
| 14 | +const UUID_PATTERN = |
| 15 | + /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i |
| 16 | + |
| 17 | +function generateUuidV7(): string { |
| 18 | + const bytes = randomBytes(16) |
| 19 | + const timestamp = Date.now() |
| 20 | + |
| 21 | + bytes[0] = Math.floor(timestamp / 0x10000000000) & 0xff |
| 22 | + bytes[1] = Math.floor(timestamp / 0x100000000) & 0xff |
| 23 | + bytes[2] = Math.floor(timestamp / 0x1000000) & 0xff |
| 24 | + bytes[3] = Math.floor(timestamp / 0x10000) & 0xff |
| 25 | + bytes[4] = Math.floor(timestamp / 0x100) & 0xff |
| 26 | + bytes[5] = timestamp & 0xff |
| 27 | + bytes[6] = (bytes[6] & 0x0f) | 0x70 |
| 28 | + bytes[8] = (bytes[8] & 0x3f) | 0x80 |
| 29 | + |
| 30 | + const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('') |
| 31 | + return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}` |
| 32 | +} |
| 33 | + |
| 34 | +function isUuid(value: string | null): value is string { |
| 35 | + return Boolean(value && UUID_PATTERN.test(value)) |
| 36 | +} |
| 37 | + |
| 38 | +function getRequestHeader(args: any[], name: string): string | null { |
| 39 | + const request = args[0] |
| 40 | + return typeof request?.headers?.get === 'function' ? request.headers.get(name) : null |
| 41 | +} |
| 42 | + |
| 43 | +function resolveRequestId(args: any[]) { |
| 44 | + const clientRequestId = getRequestHeader(args, 'x-request-id') |
| 45 | + return isUuid(clientRequestId) ? clientRequestId : generateUuidV7() |
| 46 | +} |
| 47 | + |
| 48 | +export function getRequestId(): string | null { |
| 49 | + return requestContext.getStore()?.requestId ?? null |
| 50 | +} |
| 51 | + |
| 52 | +function patchLogger() { |
| 53 | + const target = logger as any |
| 54 | + if (target[LOGGER_PATCHED]) return |
| 55 | + |
| 56 | + for (const method of ['trace', 'debug', 'info', 'warn', 'error', 'fatal'] as const) { |
| 57 | + const original = target[method] |
| 58 | + if (typeof original !== 'function') continue |
| 59 | + if (original.mock || original._isMockFunction) continue |
| 60 | + |
| 61 | + target[method] = function requestIdLoggerMethod(this: unknown, ...args: any[]) { |
| 62 | + const requestId = getRequestId() |
| 63 | + if (requestId) { |
| 64 | + const first = args[0] |
| 65 | + if (first && typeof first === 'object' && !Array.isArray(first) && !(first instanceof Error)) { |
| 66 | + args[0] = { requestId, ...first } |
| 67 | + } else { |
| 68 | + args.unshift({ requestId }) |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + return original.apply(this, args) |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + target[LOGGER_PATCHED] = true |
| 77 | +} |
| 78 | + |
| 79 | +function responseWithRequestId(response: unknown, requestId: string): Response { |
| 80 | + const routeResponse = response instanceof Response |
| 81 | + ? response |
| 82 | + : new Response(null, { status: 204 }) |
| 83 | + |
| 84 | + routeResponse.headers.set('X-Request-Id', requestId) |
| 85 | + return routeResponse |
| 86 | +} |
| 87 | + |
| 88 | +patchLogger() |
| 89 | + |
| 90 | +export function withRequestId<T extends RouteHandler>(handler: T): (...args: any[]) => Promise<Response> { |
| 91 | + return (async (...args: any[]) => { |
| 92 | + const requestId = resolveRequestId(args) |
| 93 | + |
| 94 | + try { |
| 95 | + const response = await requestContext.run({ requestId }, () => handler(...args)) |
| 96 | + return responseWithRequestId(response, requestId) |
| 97 | + } catch (error) { |
| 98 | + logger.error({ err: error }, 'Routes B unhandled route error') |
| 99 | + return responseWithRequestId( |
| 100 | + NextResponse.json({ error: 'Internal server error' }, { status: 500 }), |
| 101 | + requestId, |
| 102 | + ) |
| 103 | + } |
| 104 | + }) |
| 105 | +} |
0 commit comments