@open-mercato/telemetry 0.9.1-develop.7575.1.8480826a9b → 0.10.0

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/src/init.ts CHANGED
@@ -17,11 +17,14 @@ import { withSpan } from './facade/tracer'
17
17
  import { recordHttpDuration } from './facade/http'
18
18
  import { histogram } from './facade/meter'
19
19
  import { reportError } from './facade/report-error'
20
+ import { startRuntimeMetrics } from './runtime-metrics'
20
21
 
21
22
  let initialized = false
23
+ let initializing: Promise<void> | undefined
22
24
  let activeProvider: TelemetryProvider | undefined
23
25
  let disposeLoggerExtension: (() => void) | undefined
24
26
  let disposeRuntime: (() => void) | undefined
27
+ let disposeRuntimeMetrics: (() => void) | undefined
25
28
 
26
29
  const logger = createLogger('telemetry')
27
30
  const OTLP_DEPENDENCY_UNAVAILABLE = Symbol.for('open-mercato.telemetry.otlp-dependency-unavailable')
@@ -46,7 +49,17 @@ class OtlpDependencyUnavailableError extends Error {
46
49
  */
47
50
  export async function initTelemetry(): Promise<void> {
48
51
  if (initialized) return
52
+ if (initializing) return initializing
49
53
 
54
+ let pending: Promise<void>
55
+ pending = initializeTelemetry().finally(() => {
56
+ if (initializing === pending) initializing = undefined
57
+ })
58
+ initializing = pending
59
+ return pending
60
+ }
61
+
62
+ async function initializeTelemetry(): Promise<void> {
50
63
  // Drop any env snapshot memoized BEFORE the host loaded its `.env` (the CLI
51
64
  // binary imports this package before dotenv runs) so init resolves the backend
52
65
  // from the actual, fully-loaded environment.
@@ -75,6 +88,7 @@ export async function initTelemetry(): Promise<void> {
75
88
  activeProvider = provider
76
89
  disposeLoggerExtension = registerTelemetryLogger(provider)
77
90
  disposeRuntime = registerTelemetryRuntime(createRuntime(provider))
91
+ disposeRuntimeMetrics = startRuntimeMetrics()
78
92
  initialized = true
79
93
 
80
94
  logger.info('Telemetry initialized', {
@@ -111,11 +125,26 @@ async function loadOtlpProvider(backend: TelemetryBackendName): Promise<Telemetr
111
125
 
112
126
  /** Flush + tear down the active backend (shutdown hook / `after()`). */
113
127
  export async function shutdownTelemetry(): Promise<void> {
128
+ if (initializing) {
129
+ try {
130
+ await initializing
131
+ } catch (err) {
132
+ try {
133
+ reportError(err, {
134
+ module: 'telemetry',
135
+ code: 'telemetry.initialization_failed',
136
+ })
137
+ } catch {}
138
+ logger.warn('Telemetry initialization failed before shutdown', { err })
139
+ }
140
+ }
114
141
  const provider = activeProvider
115
142
  activeProvider = undefined
116
143
  initialized = false
117
144
  disposeLoggerExtension?.()
118
145
  disposeLoggerExtension = undefined
146
+ disposeRuntimeMetrics?.()
147
+ disposeRuntimeMetrics = undefined
119
148
  disposeRuntime?.()
120
149
  disposeRuntime = undefined
121
150
  clearActiveProvider()
@@ -131,6 +160,7 @@ function createRuntime(provider: TelemetryProvider): TelemetryRuntime {
131
160
  continueTrace: (carrier, name, fn, options) =>
132
161
  continueTrace(carrier, name, () => fn(), options),
133
162
  withSpan: (name, fn, options) => withSpan(name, fn, options),
163
+ recordMetric: (point) => provider.recordMetric(point),
134
164
  recordHistogram: histogram,
135
165
  recordHttpDuration,
136
166
  reportError,
@@ -141,9 +171,12 @@ function createRuntime(provider: TelemetryProvider): TelemetryRuntime {
141
171
  /** Test-only: allow re-init in jest. */
142
172
  export function resetTelemetryInit(): void {
143
173
  initialized = false
174
+ initializing = undefined
144
175
  activeProvider = undefined
145
176
  disposeLoggerExtension?.()
146
177
  disposeLoggerExtension = undefined
178
+ disposeRuntimeMetrics?.()
179
+ disposeRuntimeMetrics = undefined
147
180
  disposeRuntime?.()
148
181
  disposeRuntime = undefined
149
182
  }
@@ -68,6 +68,12 @@ async function otelApiIsRegistered(page: Page): Promise<boolean> {
68
68
 
69
69
  test.describe('TC-TELEMETRY-002: browser RUM runtime', () => {
70
70
  test('exports document-load and fetch spans without breaking either fetch path', async ({ page, baseURL }) => {
71
+ // The server ignores the opt-in cookie unless the app runs with this variable; lanes that
72
+ // start the app from their own env (the standalone app) do not set it, so there is no SDK to boot.
73
+ test.skip(
74
+ process.env.OM_TEST_BROWSER_TELEMETRY_MODE !== 'opt-in',
75
+ 'OM_TEST_BROWSER_TELEMETRY_MODE=opt-in is not configured for this lane.',
76
+ )
71
77
  const origin = new URL(baseURL ?? 'http://localhost:3000').origin
72
78
  await page.context().addCookies([{ name: OPT_IN_COOKIE, value: 'on', url: origin }])
73
79
  const ingest = recordIngest(page)
@@ -23,6 +23,7 @@ import {
23
23
  type Counter,
24
24
  type Histogram,
25
25
  type Gauge,
26
+ type MetricOptions,
26
27
  } from '@opentelemetry/api'
27
28
  import { W3CTraceContextPropagator } from '@opentelemetry/core'
28
29
  import { logs, SeverityNumber } from '@opentelemetry/api-logs'
@@ -41,9 +42,10 @@ import { OTLPLogExporter } from '@opentelemetry/exporter-logs-otlp-http'
41
42
  import { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-http'
42
43
  import { BatchLogRecordProcessor, type LogRecordProcessor } from '@opentelemetry/sdk-logs'
43
44
  import { PeriodicExportingMetricReader, type IMetricReader } from '@opentelemetry/sdk-metrics'
44
- import { PgInstrumentation } from '@opentelemetry/instrumentation-pg'
45
+ import { PgInstrumentation, type PgInstrumentationConfig } from '@opentelemetry/instrumentation-pg'
45
46
  import { UndiciInstrumentation } from '@opentelemetry/instrumentation-undici'
46
47
 
48
+ import { REDACTED_SQL_STATEMENT, sanitizeSqlStatement } from './sanitize-sql'
47
49
  import type {
48
50
  Attributes,
49
51
  AttributeValue,
@@ -220,14 +222,47 @@ export type OtlpProviderOptions = {
220
222
  instrumentations?: Instrumentation[]
221
223
  }
222
224
 
225
+ /**
226
+ * Statement attribute keys written by `@opentelemetry/instrumentation-pg`:
227
+ * `db.query.text` (stable semconv, 0.73+) and `db.statement` (older releases).
228
+ */
229
+ export const PG_STATEMENT_ATTRIBUTE_KEYS = ['db.query.text', 'db.statement'] as const
230
+
223
231
  /**
224
232
  * PII guard (telemetry spec Privacy / R12). The single source of truth for pg
225
- * instrumentation config: `enhancedDatabaseReporting: false` means bound SQL
226
- * parameter VALUES are NOT captured — only the statement shape ($1, $2). User
227
- * data lives in those params, so this must never be flipped on. Asserted by a
228
- * regression test.
233
+ * instrumentation config. Two layers, both asserted by regression tests:
234
+ *
235
+ * - `enhancedDatabaseReporting: false` keeps the bound parameter VALUES array
236
+ * off the span. This must never be flipped on.
237
+ * - `requestHook` rewrites the statement text with every literal replaced by
238
+ * `?`. MikroORM inlines parameters into the SQL before it reaches `pg`, so
239
+ * without this the statement itself carries record content and ids. When the
240
+ * text cannot be tokenized the hook fails closed with a fixed marker.
241
+ */
242
+ export const PG_INSTRUMENTATION_OPTIONS = {
243
+ enhancedDatabaseReporting: false,
244
+ requestHook: (span, { query }) => {
245
+ if (typeof query.text !== 'string' || query.text.length === 0) return
246
+ const statement = sanitizeSqlStatement(query.text) ?? REDACTED_SQL_STATEMENT
247
+ for (const key of PG_STATEMENT_ATTRIBUTE_KEYS) span.setAttribute(key, statement)
248
+ },
249
+ } as const satisfies PgInstrumentationConfig
250
+
251
+ /**
252
+ * Bucket boundaries for every histogram recorded in seconds. Without explicit
253
+ * advice the SDK falls back to millisecond-scaled defaults (0, 5, 10 … 10000),
254
+ * which puts every realistic latency in the first bucket and leaves percentiles
255
+ * uncomputable. A superset of the semconv HTTP-duration advice, plus a 1 ms
256
+ * bucket for sub-millisecond pool acquisitions.
229
257
  */
230
- export const PG_INSTRUMENTATION_OPTIONS = { enhancedDatabaseReporting: false } as const
258
+ export const SECONDS_HISTOGRAM_BUCKETS: readonly number[] = [
259
+ 0.001, 0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10,
260
+ ]
261
+
262
+ function histogramOptions(unit: string | undefined): MetricOptions | undefined {
263
+ if (unit !== 's') return unit ? { unit } : undefined
264
+ return { unit, advice: { explicitBucketBoundaries: [...SECONDS_HISTOGRAM_BUCKETS] } }
265
+ }
231
266
 
232
267
  export class OtlpProvider implements TelemetryProvider {
233
268
  /** The configured backend name (signoz | newrelic | otlp) — all OTLP, vendor differs only by endpoint. */
@@ -339,7 +374,7 @@ export class OtlpProvider implements TelemetryProvider {
339
374
  point.kind === 'counter'
340
375
  ? meter.createCounter(point.name, opts)
341
376
  : point.kind === 'histogram'
342
- ? meter.createHistogram(point.name, opts)
377
+ ? meter.createHistogram(point.name, histogramOptions(point.unit))
343
378
  : meter.createGauge(point.name, opts)
344
379
  this.instruments.set(key, instrument)
345
380
  }
@@ -0,0 +1,168 @@
1
+ /**
2
+ * Replaces every literal in a Postgres statement with `?` so span attributes
3
+ * keep the query shape but never the values. MikroORM inlines bound parameters
4
+ * into the SQL text before it reaches `pg`, so `enhancedDatabaseReporting: false`
5
+ * alone cannot keep record content, user ids or session ids out of spans.
6
+ *
7
+ * Kept: keywords, `"quoted identifiers"`, `$1` placeholders, operators.
8
+ * Replaced: quoted strings (including `E'…'`, `B'…'`, `X'…'`, `N'…'`),
9
+ * dollar-quoted strings, numeric literals and `true` / `false`.
10
+ * Dropped: comments, since they can carry arbitrary text.
11
+ *
12
+ * Returns `undefined` when the text cannot be tokenized (an unterminated
13
+ * quote or comment) so the caller can fail closed instead of exporting it.
14
+ */
15
+ export const REDACTED_SQL_STATEMENT = '[redacted]'
16
+
17
+ const LITERAL_PLACEHOLDER = '?'
18
+ const STRING_PREFIXES = new Set(['e', 'b', 'x', 'n'])
19
+ const BOOLEAN_LITERALS = new Set(['true', 'false'])
20
+ const NUMBER_PATTERN = /^(?:\d[\d_]*(?:\.[\d_]*)?|\.\d[\d_]*)(?:[eE][+-]?\d+)?[A-Za-z0-9_\u0080-\uFFFF]*/
21
+ const DOLLAR_TAG_PATTERN = /^\$(?:[A-Za-z_\u0080-\uFFFF][A-Za-z0-9_\u0080-\uFFFF]*)?\$/
22
+ const WORD_PATTERN = /^[A-Za-z_\u0080-\uFFFF][A-Za-z0-9_$\u0080-\uFFFF]*/
23
+ const WORD_START_PATTERN = /[A-Za-z_\u0080-\uFFFF]/
24
+ const IDENTIFIER_CHAR_PATTERN = /[A-Za-z0-9_$\u0080-\uFFFF]/
25
+
26
+ function isIdentifierChar(char: string | undefined): boolean {
27
+ return char !== undefined && IDENTIFIER_CHAR_PATTERN.test(char)
28
+ }
29
+
30
+ function skipBlockComment(text: string, start: number): number | undefined {
31
+ let depth = 0
32
+ let index = start
33
+ while (index < text.length) {
34
+ if (text[index] === '/' && text[index + 1] === '*') {
35
+ depth += 1
36
+ index += 2
37
+ continue
38
+ }
39
+ if (text[index] === '*' && text[index + 1] === '/') {
40
+ depth -= 1
41
+ index += 2
42
+ if (depth === 0) return index
43
+ continue
44
+ }
45
+ index += 1
46
+ }
47
+ return undefined
48
+ }
49
+
50
+ function skipQuotedString(text: string, start: number, backslashEscapes: boolean): number | undefined {
51
+ let index = start + 1
52
+ while (index < text.length) {
53
+ const char = text[index]
54
+ if (backslashEscapes && char === '\\') {
55
+ index += 2
56
+ continue
57
+ }
58
+ if (char === "'") {
59
+ if (text[index + 1] === "'") {
60
+ index += 2
61
+ continue
62
+ }
63
+ return index + 1
64
+ }
65
+ index += 1
66
+ }
67
+ return undefined
68
+ }
69
+
70
+ function skipQuotedIdentifier(text: string, start: number): number | undefined {
71
+ let index = start + 1
72
+ while (index < text.length) {
73
+ if (text[index] === '"') {
74
+ if (text[index + 1] === '"') {
75
+ index += 2
76
+ continue
77
+ }
78
+ return index + 1
79
+ }
80
+ index += 1
81
+ }
82
+ return undefined
83
+ }
84
+
85
+ export function sanitizeSqlStatement(text: string): string | undefined {
86
+ let output = ''
87
+ let index = 0
88
+ while (index < text.length) {
89
+ const char = text[index]
90
+ const previous = index > 0 ? text[index - 1] : undefined
91
+
92
+ if (char === "'") {
93
+ const end = skipQuotedString(text, index, false)
94
+ if (end === undefined) return undefined
95
+ output += LITERAL_PLACEHOLDER
96
+ index = end
97
+ continue
98
+ }
99
+
100
+ if (char === '"') {
101
+ const end = skipQuotedIdentifier(text, index)
102
+ if (end === undefined) return undefined
103
+ output += text.slice(index, end)
104
+ index = end
105
+ continue
106
+ }
107
+
108
+ if (char === '-' && text[index + 1] === '-') {
109
+ const newline = text.indexOf('\n', index)
110
+ index = newline === -1 ? text.length : newline
111
+ continue
112
+ }
113
+
114
+ if (char === '/' && text[index + 1] === '*') {
115
+ const end = skipBlockComment(text, index)
116
+ if (end === undefined) return undefined
117
+ output += ' '
118
+ index = end
119
+ continue
120
+ }
121
+
122
+ if (char === '$' && !isIdentifierChar(previous)) {
123
+ const placeholder = /^\$\d+/.exec(text.slice(index))
124
+ if (placeholder) {
125
+ output += placeholder[0]
126
+ index += placeholder[0].length
127
+ continue
128
+ }
129
+ const tag = DOLLAR_TAG_PATTERN.exec(text.slice(index))
130
+ if (tag) {
131
+ const end = text.indexOf(tag[0], index + tag[0].length)
132
+ if (end === -1) return undefined
133
+ output += LITERAL_PLACEHOLDER
134
+ index = end + tag[0].length
135
+ continue
136
+ }
137
+ }
138
+
139
+ if (!isIdentifierChar(previous) && /[0-9.]/.test(char)) {
140
+ const number = NUMBER_PATTERN.exec(text.slice(index))
141
+ if (number) {
142
+ output += LITERAL_PLACEHOLDER
143
+ index += number[0].length
144
+ continue
145
+ }
146
+ }
147
+
148
+ if (!isIdentifierChar(previous) && WORD_START_PATTERN.test(char)) {
149
+ const word = WORD_PATTERN.exec(text.slice(index))?.[0] ?? char
150
+ const lowered = word.toLowerCase()
151
+ const afterWord = index + word.length
152
+ if (STRING_PREFIXES.has(lowered) && text[afterWord] === "'") {
153
+ const end = skipQuotedString(text, afterWord, lowered === 'e')
154
+ if (end === undefined) return undefined
155
+ output += LITERAL_PLACEHOLDER
156
+ index = end
157
+ continue
158
+ }
159
+ output += BOOLEAN_LITERALS.has(lowered) ? LITERAL_PLACEHOLDER : word
160
+ index = afterWord
161
+ continue
162
+ }
163
+
164
+ output += char
165
+ index += 1
166
+ }
167
+ return output
168
+ }
@@ -0,0 +1,179 @@
1
+ import { monitorEventLoopDelay, performance, type EventLoopUtilization } from 'node:perf_hooks'
2
+ import { getHeapSpaceStatistics } from 'node:v8'
3
+ import {
4
+ collectTelemetryMetrics,
5
+ getTelemetryRuntime,
6
+ recordTelemetryMetric,
7
+ } from '@open-mercato/shared/lib/telemetry/runtime'
8
+ import { createLogger } from '@open-mercato/shared/lib/logger'
9
+
10
+ const SAMPLE_INTERVAL_MS = 10_000
11
+ const DELAY_RESOLUTION_MS = 20
12
+ const NANOSECONDS_PER_SECOND = 1_000_000_000
13
+ const GLOBAL_KEY = Symbol.for('@open-mercato/telemetry.runtimeMetrics')
14
+
15
+ export type EventLoopDelayMonitor = {
16
+ enable(): void
17
+ disable(): void
18
+ percentile(percentile: number): number
19
+ reset(): void
20
+ }
21
+
22
+ export type HeapSpaceSample = {
23
+ space_name: string
24
+ space_used_size: number
25
+ }
26
+
27
+ export type RuntimeMetricSources = {
28
+ createEventLoopDelayMonitor(): EventLoopDelayMonitor
29
+ eventLoopUtilization(
30
+ first?: EventLoopUtilization,
31
+ second?: EventLoopUtilization,
32
+ ): EventLoopUtilization
33
+ memoryUsage(): { rss: number }
34
+ heapSpaceStatistics(): HeapSpaceSample[]
35
+ setInterval(handler: () => void, intervalMs: number): ReturnType<typeof setInterval>
36
+ clearInterval(interval: ReturnType<typeof setInterval>): void
37
+ }
38
+
39
+ type ActiveRuntimeSampler = {
40
+ references: number
41
+ dispose(): void
42
+ }
43
+
44
+ type RuntimeMetricsStore = {
45
+ active?: ActiveRuntimeSampler
46
+ }
47
+
48
+ const logger = createLogger('telemetry').child({ component: 'runtime-metrics' })
49
+
50
+ const defaultSources: RuntimeMetricSources = {
51
+ createEventLoopDelayMonitor: () => monitorEventLoopDelay({ resolution: DELAY_RESOLUTION_MS }),
52
+ eventLoopUtilization: (first, second) => performance.eventLoopUtilization(first, second),
53
+ memoryUsage: () => process.memoryUsage(),
54
+ heapSpaceStatistics: () => getHeapSpaceStatistics(),
55
+ setInterval: (handler, intervalMs) => setInterval(handler, intervalMs),
56
+ clearInterval: (interval) => clearInterval(interval),
57
+ }
58
+
59
+ function store(): RuntimeMetricsStore {
60
+ const globalStore = globalThis as unknown as Record<symbol, RuntimeMetricsStore | undefined>
61
+ let current = globalStore[GLOBAL_KEY]
62
+ if (!current) {
63
+ current = {}
64
+ globalStore[GLOBAL_KEY] = current
65
+ }
66
+ return current
67
+ }
68
+
69
+ function secondsFromNanoseconds(value: number): number {
70
+ return Number.isFinite(value) ? Math.max(0, value) / NANOSECONDS_PER_SECOND : 0
71
+ }
72
+
73
+ export function createRuntimeMetricsSampler(
74
+ sources: RuntimeMetricSources = defaultSources,
75
+ ): () => void {
76
+ const delay = sources.createEventLoopDelayMonitor()
77
+ let previousUtilization = sources.eventLoopUtilization()
78
+ delay.enable()
79
+
80
+ const sample = () => {
81
+ try {
82
+ const currentUtilization = sources.eventLoopUtilization()
83
+ const intervalUtilization = sources.eventLoopUtilization(
84
+ currentUtilization,
85
+ previousUtilization,
86
+ )
87
+ previousUtilization = currentUtilization
88
+
89
+ recordTelemetryMetric({
90
+ kind: 'gauge',
91
+ name: 'nodejs.eventloop.utilization',
92
+ value: intervalUtilization.utilization,
93
+ unit: '1',
94
+ })
95
+ for (const percentile of [50, 90, 99]) {
96
+ recordTelemetryMetric({
97
+ kind: 'gauge',
98
+ name: `nodejs.eventloop.delay.p${percentile}`,
99
+ value: secondsFromNanoseconds(delay.percentile(percentile)),
100
+ unit: 's',
101
+ })
102
+ }
103
+
104
+ recordTelemetryMetric({
105
+ kind: 'gauge',
106
+ name: 'process.memory.usage',
107
+ value: sources.memoryUsage().rss,
108
+ unit: 'By',
109
+ })
110
+ for (const heapSpace of sources.heapSpaceStatistics()) {
111
+ recordTelemetryMetric({
112
+ kind: 'gauge',
113
+ name: 'v8js.memory.heap.used',
114
+ value: heapSpace.space_used_size,
115
+ labels: { 'v8js.heap.space.name': heapSpace.space_name },
116
+ unit: 'By',
117
+ })
118
+ }
119
+
120
+ collectTelemetryMetrics((err) => {
121
+ logger.warn('Runtime metric collector failed', { err })
122
+ })
123
+ } catch (err) {
124
+ try {
125
+ getTelemetryRuntime()?.reportError(err, {
126
+ module: 'telemetry',
127
+ code: 'telemetry.runtime_sampling_failed',
128
+ })
129
+ } catch {}
130
+ logger.warn('Runtime metric sampling failed', { err })
131
+ } finally {
132
+ delay.reset()
133
+ }
134
+ }
135
+
136
+ const interval = sources.setInterval(sample, SAMPLE_INTERVAL_MS)
137
+ interval.unref?.()
138
+
139
+ let disposed = false
140
+ return () => {
141
+ if (disposed) return
142
+ disposed = true
143
+ sources.clearInterval(interval)
144
+ delay.disable()
145
+ }
146
+ }
147
+
148
+ export function startRuntimeMetrics(
149
+ sources: RuntimeMetricSources = defaultSources,
150
+ ): () => void {
151
+ const current = store()
152
+ if (!current.active) {
153
+ current.active = {
154
+ references: 0,
155
+ dispose: createRuntimeMetricsSampler(sources),
156
+ }
157
+ }
158
+
159
+ const active = current.active
160
+ active.references += 1
161
+ let released = false
162
+
163
+ return () => {
164
+ if (released) return
165
+ released = true
166
+ active.references -= 1
167
+ if (active.references > 0) return
168
+ active.dispose()
169
+ const latest = store()
170
+ if (latest.active === active) latest.active = undefined
171
+ }
172
+ }
173
+
174
+ /** Test-only: tear down the process-wide sampler regardless of reference count. */
175
+ export function resetRuntimeMetrics(): void {
176
+ const current = store()
177
+ current.active?.dispose()
178
+ current.active = undefined
179
+ }