|
| 1 | +import fastifyPlugin from 'fastify-plugin' |
| 2 | +import { isIP } from 'net' |
| 3 | +import { getTenantConfig } from '@internal/database' |
| 4 | + |
| 5 | +import { getConfig } from '../../config' |
| 6 | +import { context, trace } from '@opentelemetry/api' |
| 7 | +import { traceCollector } from '@internal/monitoring/otel-processor' |
| 8 | +import { ReadableSpan } from '@opentelemetry/sdk-trace-base' |
| 9 | +import { logger, logSchema } from '@internal/monitoring' |
| 10 | + |
| 11 | +declare module 'fastify' { |
| 12 | + interface FastifyRequest { |
| 13 | + tracingMode?: string |
| 14 | + serverTimings?: { spanName: string; duration: number }[] |
| 15 | + } |
| 16 | +} |
| 17 | + |
| 18 | +const { |
| 19 | + isMultitenant, |
| 20 | + tracingEnabled, |
| 21 | + tracingMode: defaultTracingMode, |
| 22 | + tracingReturnServerTimings, |
| 23 | +} = getConfig() |
| 24 | + |
| 25 | +export const tracing = fastifyPlugin(async function tracingMode(fastify) { |
| 26 | + if (!tracingEnabled) { |
| 27 | + return |
| 28 | + } |
| 29 | + fastify.register(traceServerTime) |
| 30 | + |
| 31 | + fastify.addHook('onRequest', async (request) => { |
| 32 | + if (isMultitenant && request.tenantId) { |
| 33 | + const tenantConfig = await getTenantConfig(request.tenantId) |
| 34 | + request.tracingMode = tenantConfig.tracingMode |
| 35 | + } else { |
| 36 | + request.tracingMode = defaultTracingMode |
| 37 | + } |
| 38 | + }) |
| 39 | +}) |
| 40 | + |
| 41 | +export const traceServerTime = fastifyPlugin(async function traceServerTime(fastify) { |
| 42 | + if (!tracingEnabled) { |
| 43 | + return |
| 44 | + } |
| 45 | + fastify.addHook('onResponse', async (request, reply) => { |
| 46 | + const traceId = trace.getSpan(context.active())?.spanContext().traceId |
| 47 | + |
| 48 | + if (traceId) { |
| 49 | + const spans = traceCollector.getSpansForTrace(traceId) |
| 50 | + if (spans) { |
| 51 | + try { |
| 52 | + const serverTimingHeaders = spansToServerTimings(spans) |
| 53 | + |
| 54 | + request.serverTimings = serverTimingHeaders |
| 55 | + |
| 56 | + // Return Server-Timing if enabled |
| 57 | + if (tracingReturnServerTimings) { |
| 58 | + const httpServerTimes = serverTimingHeaders |
| 59 | + .map(({ spanName, duration }) => { |
| 60 | + return `${spanName};dur=${duration.toFixed(3)}` // Convert to milliseconds |
| 61 | + }) |
| 62 | + .join(',') |
| 63 | + reply.header('Server-Timing', httpServerTimes) |
| 64 | + } |
| 65 | + } catch (e) { |
| 66 | + logSchema.error(logger, 'failed parsing server times', { error: e, type: 'otel' }) |
| 67 | + } |
| 68 | + |
| 69 | + traceCollector.clearTrace(traceId) |
| 70 | + } |
| 71 | + } |
| 72 | + }) |
| 73 | + |
| 74 | + fastify.addHook('onRequestAbort', async (req) => { |
| 75 | + const traceId = trace.getSpan(context.active())?.spanContext().traceId |
| 76 | + |
| 77 | + if (traceId) { |
| 78 | + const spans = traceCollector.getSpansForTrace(traceId) |
| 79 | + if (spans) { |
| 80 | + req.serverTimings = spansToServerTimings(spans) |
| 81 | + } |
| 82 | + traceCollector.clearTrace(traceId) |
| 83 | + } |
| 84 | + }) |
| 85 | +}) |
| 86 | + |
| 87 | +function enrichSpanName(spanName: string, span: ReadableSpan) { |
| 88 | + if (span.attributes['knex.version']) { |
| 89 | + const queryOperation = (span.attributes['db.operation'] as string)?.split(' ').shift() |
| 90 | + return ( |
| 91 | + `pg_query_` + |
| 92 | + queryOperation?.toUpperCase() + |
| 93 | + (span.attributes['db.sql.table'] ? '_' + span.attributes['db.sql.table'] : '_postgres') |
| 94 | + ) |
| 95 | + } |
| 96 | + |
| 97 | + if (['GET', 'PUT', 'HEAD', 'DELETE', 'POST'].includes(spanName)) { |
| 98 | + return `HTTP_${spanName}` |
| 99 | + } |
| 100 | + |
| 101 | + return spanName |
| 102 | +} |
| 103 | + |
| 104 | +function spansToServerTimings(spans: ReadableSpan[]) { |
| 105 | + return spans |
| 106 | + .sort((a, b) => { |
| 107 | + return a.startTime[1] - b.startTime[1] |
| 108 | + }) |
| 109 | + .map((span) => { |
| 110 | + const duration = span.duration[1] // Duration in nanoseconds |
| 111 | + |
| 112 | + let spanName = |
| 113 | + span.name |
| 114 | + .split('->') |
| 115 | + .pop() |
| 116 | + ?.trimStart() |
| 117 | + .replaceAll('\n', '') |
| 118 | + .replaceAll('.', '_') |
| 119 | + .replaceAll(' ', '_') |
| 120 | + .replaceAll('-', '_') |
| 121 | + .replaceAll('___', '_') |
| 122 | + .replaceAll(':', '_') |
| 123 | + .replaceAll('_undefined', '') || 'UNKNOWN' |
| 124 | + |
| 125 | + spanName = enrichSpanName(spanName, span) |
| 126 | + const hostName = span.attributes['net.peer.name'] as string | undefined |
| 127 | + |
| 128 | + return { |
| 129 | + spanName, |
| 130 | + duration: duration / 1e6, |
| 131 | + action: span.attributes['db.statement'], |
| 132 | + host: hostName |
| 133 | + ? isIP(hostName) |
| 134 | + ? hostName |
| 135 | + : hostName?.split('.').slice(-3).join('.') |
| 136 | + : undefined, |
| 137 | + } |
| 138 | + }) |
| 139 | +} |
0 commit comments