@open-mercato/telemetry 0.9.1-develop.7574.1.837288eec1 → 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.
@@ -8,9 +8,15 @@ import { SpanStatusCode, propagation, trace, context, defaultTextMapSetter, ROOT
8
8
  import { W3CTraceContextPropagator } from '@opentelemetry/core'
9
9
  import { InMemorySpanExporter, SimpleSpanProcessor, type ReadableSpan } from '@opentelemetry/sdk-trace-base'
10
10
  import { InMemoryLogRecordExporter, SimpleLogRecordProcessor } from '@opentelemetry/sdk-logs'
11
- import { InMemoryMetricExporter, PeriodicExportingMetricReader, AggregationTemporality } from '@opentelemetry/sdk-metrics'
12
-
13
- import { OtlpProvider } from '../provider/otlp-provider'
11
+ import {
12
+ InMemoryMetricExporter,
13
+ PeriodicExportingMetricReader,
14
+ AggregationTemporality,
15
+ DataPointType,
16
+ type Histogram,
17
+ } from '@opentelemetry/sdk-metrics'
18
+
19
+ import { OtlpProvider, SECONDS_HISTOGRAM_BUCKETS } from '../provider/otlp-provider'
14
20
  import { createBackupHeaderPropagator } from '../browser/propagator'
15
21
  import {
16
22
  createLogger,
@@ -20,7 +26,7 @@ import {
20
26
  import { setActiveProvider, resetActiveProvider } from '../provider/registry'
21
27
  import { resetTelemetryEnvCache } from '../env'
22
28
  import { registerTelemetryLogger } from '../facade/logger-bridge'
23
- import { withSpan, captureTraceContext, continueTrace, reportError, counter } from '../index'
29
+ import { withSpan, captureTraceContext, continueTrace, reportError, counter, histogram } from '../index'
24
30
 
25
31
  const spanExporter = new InMemorySpanExporter()
26
32
  const logExporter = new InMemoryLogRecordExporter()
@@ -357,4 +363,28 @@ describe('OtlpProvider (in-memory exporters)', () => {
357
363
  .flatMap((rm) => rm.scopeMetrics.flatMap((sm) => sm.metrics.map((m) => m.descriptor.name)))
358
364
  expect(metricNames).toContain('om.errors')
359
365
  })
366
+
367
+ it('aggregates second-unit histograms with second-scaled buckets', async () => {
368
+ histogram('om.test.wait_time', 0.003, { pool: 'primary' }, 's')
369
+ histogram('om.test.wait_time', 0.0002, { pool: 'primary' }, 's')
370
+ histogram('om.test.payload_size', 3, undefined, 'By')
371
+ await metricReader.forceFlush()
372
+
373
+ const histogramPoint = (name: string) => {
374
+ const metric = metricExporter
375
+ .getMetrics()
376
+ .flatMap((rm) => rm.scopeMetrics.flatMap((sm) => sm.metrics))
377
+ .find((candidate) => candidate.descriptor.name === name)
378
+ expect(metric?.dataPointType).toBe(DataPointType.HISTOGRAM)
379
+ return metric?.dataPoints[0]?.value as Histogram | undefined
380
+ }
381
+
382
+ const seconds = histogramPoint('om.test.wait_time')
383
+ expect(seconds?.buckets.boundaries).toEqual([...SECONDS_HISTOGRAM_BUCKETS])
384
+ expect(seconds?.buckets.counts.slice(0, 3)).toEqual([1, 1, 0])
385
+ expect(seconds?.count).toBe(2)
386
+
387
+ const bytes = histogramPoint('om.test.payload_size')
388
+ expect(bytes?.buckets.boundaries).not.toEqual([...SECONDS_HISTOGRAM_BUCKETS])
389
+ })
360
390
  })
@@ -16,10 +16,13 @@ import path from 'node:path'
16
16
  * a dead port still drives the query path, and the instrumentation records the
17
17
  * span before the underlying call fails.
18
18
  */
19
- const distProvider = path.resolve(__dirname, '../../dist/provider/otlp-provider.js')
20
19
  const pkgRoot = path.resolve(__dirname, '../..')
21
20
 
22
21
  const CHILD_SCRIPT = `
22
+ import assert from 'node:assert/strict'
23
+ import { writeSync } from 'node:fs'
24
+ const stage = (name) => writeSync(2, 'STAGE=' + name + '\\n')
25
+ stage('import-provider')
23
26
  const { OtlpProvider } = await import('@open-mercato/telemetry/provider/otlp-provider')
24
27
  const { setActiveProvider } = await import('@open-mercato/telemetry/provider/registry')
25
28
  const { InMemorySpanExporter, SimpleSpanProcessor } = await import('@opentelemetry/sdk-trace-base')
@@ -27,34 +30,61 @@ const { InMemorySpanExporter, SimpleSpanProcessor } = await import('@opentelemet
27
30
  // No 'instrumentations' override: the provider's DEFAULT list must include the
28
31
  // pg instrumentation (with PII-safe options), or this probe records no span.
29
32
  const exporter = new InMemorySpanExporter()
33
+ const processor = new SimpleSpanProcessor(exporter)
30
34
  const provider = new OtlpProvider({
31
- spanProcessors: [new SimpleSpanProcessor(exporter)],
35
+ spanProcessors: [processor],
36
+ logRecordProcessors: [],
37
+ metricReaders: [],
32
38
  })
33
39
  // start() BEFORE pg is imported — the ordering the CLI bootstrap guarantees.
40
+ stage('start-provider')
34
41
  await provider.start()
35
42
  setActiveProvider(provider)
36
43
 
44
+ stage('import-pg')
37
45
  const pgModule = await import('pg')
38
46
  const Client = (pgModule.default ?? pgModule).Client
39
- const client = new Client({ host: '127.0.0.1', port: 1, connectionTimeoutMillis: 200 })
40
- try { await client.connect() } catch {}
41
- try { await client.query('SELECT $1::text', ['pii-sentinel-value']) } catch {}
42
- await new Promise((resolve) => setTimeout(resolve, 250))
43
- const spans = exporter.getFinishedSpans().map((s) => ({ name: s.name, attributes: s.attributes }))
44
- console.log('SPANS=' + JSON.stringify(spans))
45
- process.exit(0)
47
+ const client = new Client({
48
+ host: '127.0.0.1', port: 1, connectionTimeoutMillis: 200,
49
+ user: 'telemetry-probe', database: 'telemetry-probe',
50
+ })
51
+ const ended = new Promise((resolve) => client.once('end', resolve))
52
+ try {
53
+ stage('connect')
54
+ await assert.rejects(client.connect())
55
+ if (process.argv[2] === 'socket-ended') {
56
+ stage('wait-socket-end')
57
+ await ended
58
+ }
59
+ stage('close-client')
60
+ await client.end()
61
+ stage('query')
62
+ await assert.rejects(client.query('SELECT $1::text', ['pii-sentinel-value']))
63
+ stage('inlined-query')
64
+ await assert.rejects(client.query('select "s0".* from "sessions" as "s0" where "s0"."id" = \\'pii-sentinel-value\\' limit 1'))
65
+ stage('flush-spans')
66
+ await processor.forceFlush()
67
+ const spans = exporter.getFinishedSpans().map((span) => ({ name: span.name, attributes: span.attributes }))
68
+ stage('shutdown-provider')
69
+ await provider.shutdown()
70
+ stage('shutdown-finished')
71
+ console.log('SPANS=' + JSON.stringify(spans))
72
+ } finally {
73
+ await client.end()
74
+ await provider.shutdown()
75
+ }
46
76
  `
47
77
 
48
78
  type ProbeSpan = { name: string; attributes: Record<string, unknown> }
49
79
 
50
- function runChild(): ProbeSpan[] {
80
+ function runChild(order: string): ProbeSpan[] {
51
81
  // The script must live inside the package tree: ESM resolves bare specifiers
52
82
  // (`@open-mercato/telemetry`, `@opentelemetry/*`, `pg`) relative to the file's
53
83
  // location, not the process cwd.
54
84
  const scriptFile = path.join(pkgRoot, `.pg-instrumentation-probe.${process.pid}.mjs`)
55
85
  fs.writeFileSync(scriptFile, CHILD_SCRIPT)
56
86
  try {
57
- const result = spawnSync(process.execPath, [scriptFile], {
87
+ const result = spawnSync(process.execPath, [scriptFile, order], {
58
88
  cwd: pkgRoot,
59
89
  encoding: 'utf8',
60
90
  env: {
@@ -65,24 +95,29 @@ function runChild(): ProbeSpan[] {
65
95
  },
66
96
  timeout: 30_000,
67
97
  })
68
- const line = (result.stdout || '').split('\n').find((l) => l.startsWith('SPANS='))
69
- if (!line) throw new Error(`child produced no SPANS output.\nstdout: ${result.stdout}\nstderr: ${result.stderr}`)
98
+ const line = (result.stdout || '').split('\n').find((candidate) => candidate.startsWith('SPANS='))
99
+ if (result.error || result.status !== 0 || result.signal || !line) {
100
+ throw new Error(`[internal] child probe failed.\nerror: ${result.error?.message ?? 'none'}\nstatus: ${result.status}\nsignal: ${result.signal}\nstdout: ${result.stdout}\nstderr: ${result.stderr}`)
101
+ }
70
102
  return JSON.parse(line.slice('SPANS='.length)) as ProbeSpan[]
71
103
  } finally {
72
104
  fs.rmSync(scriptFile, { force: true })
73
105
  }
74
106
  }
75
107
 
76
- // The build output must exist (the child imports the compiled provider). Runs in
77
- // CI after build:packages; skip locally when the package hasn't been built yet.
78
- const maybe = fs.existsSync(distProvider) ? describe : describe.skip
79
-
80
- maybe('OTLP provider pg instrumentation', () => {
81
- it('emits a pg query span (default instrumentations) without leaking bound parameter values', () => {
82
- const spans = runChild()
83
- expect(spans.some((span) => span.name.startsWith('pg.query'))).toBe(true)
84
- // enhancedDatabaseReporting must stay off in the provider's default wiring:
85
- // the statement text may appear, bound values must not.
86
- expect(JSON.stringify(spans)).not.toContain('pii-sentinel-value')
87
- }, 35_000)
108
+ describe('OTLP provider pg instrumentation', () => {
109
+ it.each(['connect-rejected', 'socket-ended'])(
110
+ 'emits a pg query span without leaking bound parameter values after %s',
111
+ (order) => {
112
+ const spans = runChild(order)
113
+ expect(spans.some((span) => span.name.startsWith('pg.query'))).toBe(true)
114
+ // enhancedDatabaseReporting must stay off in the provider's default wiring,
115
+ // and values inlined into the SQL text (as MikroORM sends every query) must
116
+ // be sanitized out: the statement shape may appear, the values must not.
117
+ expect(JSON.stringify(spans)).not.toContain('pii-sentinel-value')
118
+ const statements = spans.flatMap((span) => [span.attributes['db.query.text'], span.attributes['db.statement']])
119
+ expect(statements).toContain('select "s0".* from "sessions" as "s0" where "s0"."id" = ? limit ?')
120
+ },
121
+ 35_000,
122
+ )
88
123
  })
@@ -0,0 +1,239 @@
1
+ import {
2
+ registerTelemetryMetricCollector,
3
+ registerTelemetryRuntime,
4
+ resetTelemetryMetricCollectors,
5
+ resetTelemetryRuntime,
6
+ type TelemetryMetricPoint,
7
+ type TelemetryRuntime,
8
+ } from '@open-mercato/shared/lib/telemetry/runtime'
9
+ import {
10
+ createRuntimeMetricsSampler,
11
+ resetRuntimeMetrics,
12
+ startRuntimeMetrics,
13
+ type EventLoopDelayMonitor,
14
+ type RuntimeMetricSources,
15
+ } from '../runtime-metrics'
16
+ import type { EventLoopUtilization } from 'node:perf_hooks'
17
+
18
+ function createRuntime(recordMetric: (point: TelemetryMetricPoint) => void): TelemetryRuntime {
19
+ return {
20
+ canUseGlobalTracePropagation: () => false,
21
+ captureTraceContext: () => ({}),
22
+ continueTrace: (_carrier, _name, fn) => fn(),
23
+ recordMetric,
24
+ recordHttpDuration: () => {},
25
+ reportError: () => {},
26
+ shutdown: async () => {},
27
+ }
28
+ }
29
+
30
+ describe('runtime metrics sampler', () => {
31
+ afterEach(() => {
32
+ resetRuntimeMetrics()
33
+ resetTelemetryMetricCollectors()
34
+ resetTelemetryRuntime()
35
+ })
36
+
37
+ it('records interval runtime values and invokes shared metric collectors', () => {
38
+ const points: TelemetryMetricPoint[] = []
39
+ registerTelemetryRuntime(createRuntime((point) => points.push(point)))
40
+ const collectPool = jest.fn()
41
+ registerTelemetryMetricCollector(collectPool)
42
+
43
+ const delay: EventLoopDelayMonitor = {
44
+ enable: jest.fn(),
45
+ disable: jest.fn(),
46
+ percentile: jest.fn((percentile) => percentile * 1_000_000),
47
+ reset: jest.fn(),
48
+ }
49
+ const utilization: EventLoopUtilization[] = [
50
+ { idle: 10, active: 10, utilization: 0.5 },
51
+ { idle: 15, active: 25, utilization: 0.625 },
52
+ { idle: 5, active: 15, utilization: 0.75 },
53
+ ]
54
+ let sample = () => {}
55
+ const interval = { unref: jest.fn() } as unknown as ReturnType<typeof setInterval>
56
+ const sources: RuntimeMetricSources = {
57
+ createEventLoopDelayMonitor: () => delay,
58
+ eventLoopUtilization: jest.fn(() => utilization.shift() ?? {
59
+ idle: 0,
60
+ active: 0,
61
+ utilization: 0,
62
+ }),
63
+ memoryUsage: () => ({ rss: 123_456 }),
64
+ heapSpaceStatistics: () => [{
65
+ space_name: 'old_space',
66
+ space_used_size: 78_900,
67
+ }],
68
+ setInterval: (handler, intervalMs) => {
69
+ expect(intervalMs).toBe(10_000)
70
+ sample = handler
71
+ return interval
72
+ },
73
+ clearInterval: jest.fn(),
74
+ }
75
+
76
+ const dispose = createRuntimeMetricsSampler(sources)
77
+ sample()
78
+
79
+ expect(delay.enable).toHaveBeenCalledTimes(1)
80
+ expect(interval.unref).toHaveBeenCalledTimes(1)
81
+ expect(points).toEqual([
82
+ {
83
+ kind: 'gauge',
84
+ name: 'nodejs.eventloop.utilization',
85
+ value: 0.75,
86
+ unit: '1',
87
+ },
88
+ {
89
+ kind: 'gauge',
90
+ name: 'nodejs.eventloop.delay.p50',
91
+ value: 0.05,
92
+ unit: 's',
93
+ },
94
+ {
95
+ kind: 'gauge',
96
+ name: 'nodejs.eventloop.delay.p90',
97
+ value: 0.09,
98
+ unit: 's',
99
+ },
100
+ {
101
+ kind: 'gauge',
102
+ name: 'nodejs.eventloop.delay.p99',
103
+ value: 0.099,
104
+ unit: 's',
105
+ },
106
+ {
107
+ kind: 'gauge',
108
+ name: 'process.memory.usage',
109
+ value: 123_456,
110
+ unit: 'By',
111
+ },
112
+ {
113
+ kind: 'gauge',
114
+ name: 'v8js.memory.heap.used',
115
+ value: 78_900,
116
+ labels: { 'v8js.heap.space.name': 'old_space' },
117
+ unit: 'By',
118
+ },
119
+ ])
120
+ expect(collectPool).toHaveBeenCalledTimes(1)
121
+ expect(delay.reset).toHaveBeenCalledTimes(1)
122
+
123
+ dispose()
124
+
125
+ expect(sources.clearInterval).toHaveBeenCalledWith(interval)
126
+ expect(delay.disable).toHaveBeenCalledTimes(1)
127
+ })
128
+
129
+ it('normalizes non-finite delay percentiles to zero', () => {
130
+ const points: TelemetryMetricPoint[] = []
131
+ registerTelemetryRuntime(createRuntime((point) => points.push(point)))
132
+ let sample = () => {}
133
+ const interval = { unref: jest.fn() } as unknown as ReturnType<typeof setInterval>
134
+ const delay: EventLoopDelayMonitor = {
135
+ enable: jest.fn(),
136
+ disable: jest.fn(),
137
+ percentile: () => Number.NaN,
138
+ reset: jest.fn(),
139
+ }
140
+ const sources: RuntimeMetricSources = {
141
+ createEventLoopDelayMonitor: () => delay,
142
+ eventLoopUtilization: () => ({ idle: 0, active: 0, utilization: 0 }),
143
+ memoryUsage: () => ({ rss: 0 }),
144
+ heapSpaceStatistics: () => [],
145
+ setInterval: (handler) => {
146
+ sample = handler
147
+ return interval
148
+ },
149
+ clearInterval: jest.fn(),
150
+ }
151
+
152
+ const dispose = createRuntimeMetricsSampler(sources)
153
+ sample()
154
+ dispose()
155
+
156
+ expect(points.filter((point) => point.name.startsWith('nodejs.eventloop.delay.')))
157
+ .toEqual([
158
+ { kind: 'gauge', name: 'nodejs.eventloop.delay.p50', value: 0, unit: 's' },
159
+ { kind: 'gauge', name: 'nodejs.eventloop.delay.p90', value: 0, unit: 's' },
160
+ { kind: 'gauge', name: 'nodejs.eventloop.delay.p99', value: 0, unit: 's' },
161
+ ])
162
+ })
163
+
164
+ it.each([false, true])('reports sampling failures, recovers, and disposes once (reporting throws: %s)', (reportingThrows) => {
165
+ const failure = new Error('[internal] memory sample failed')
166
+ const reportError = jest.fn(() => {
167
+ if (reportingThrows) throw new Error('[internal] reporting sink failed')
168
+ })
169
+ const points: TelemetryMetricPoint[] = []
170
+ registerTelemetryRuntime({ ...createRuntime((point) => points.push(point)), reportError })
171
+ let sample = () => {}
172
+ const interval = { unref: jest.fn() } as unknown as ReturnType<typeof setInterval>
173
+ const delay: EventLoopDelayMonitor = {
174
+ enable: jest.fn(),
175
+ disable: jest.fn(),
176
+ percentile: () => 0,
177
+ reset: jest.fn(),
178
+ }
179
+ const sources: RuntimeMetricSources = {
180
+ createEventLoopDelayMonitor: () => delay,
181
+ eventLoopUtilization: () => ({ idle: 0, active: 0, utilization: 0 }),
182
+ memoryUsage: jest.fn().mockImplementationOnce(() => { throw failure }).mockReturnValue({ rss: 123 }),
183
+ heapSpaceStatistics: () => [],
184
+ setInterval: (handler) => {
185
+ sample = handler
186
+ return interval
187
+ },
188
+ clearInterval: jest.fn(),
189
+ }
190
+
191
+ const dispose = createRuntimeMetricsSampler(sources)
192
+ expect(sample).not.toThrow()
193
+ expect(sample).not.toThrow()
194
+ dispose()
195
+ dispose()
196
+
197
+ expect(reportError).toHaveBeenCalledWith(failure, {
198
+ module: 'telemetry',
199
+ code: 'telemetry.runtime_sampling_failed',
200
+ })
201
+ expect(points).toContainEqual({ kind: 'gauge', name: 'process.memory.usage', value: 123, unit: 'By' })
202
+ expect(delay.reset).toHaveBeenCalledTimes(2)
203
+ expect(delay.disable).toHaveBeenCalledTimes(1)
204
+ expect(sources.clearInterval).toHaveBeenCalledTimes(1)
205
+ })
206
+
207
+ it('shares one process sampler until every owner releases it', () => {
208
+ const interval = { unref: jest.fn() } as unknown as ReturnType<typeof setInterval>
209
+ const delay: EventLoopDelayMonitor = {
210
+ enable: jest.fn(),
211
+ disable: jest.fn(),
212
+ percentile: () => 0,
213
+ reset: jest.fn(),
214
+ }
215
+ const sources: RuntimeMetricSources = {
216
+ createEventLoopDelayMonitor: jest.fn(() => delay),
217
+ eventLoopUtilization: () => ({ idle: 0, active: 0, utilization: 0 }),
218
+ memoryUsage: () => ({ rss: 0 }),
219
+ heapSpaceStatistics: () => [],
220
+ setInterval: jest.fn(() => interval),
221
+ clearInterval: jest.fn(),
222
+ }
223
+
224
+ const releaseFirst = startRuntimeMetrics(sources)
225
+ const releaseSecond = startRuntimeMetrics(sources)
226
+
227
+ expect(sources.createEventLoopDelayMonitor).toHaveBeenCalledTimes(1)
228
+ expect(sources.setInterval).toHaveBeenCalledTimes(1)
229
+
230
+ releaseFirst()
231
+ expect(sources.clearInterval).not.toHaveBeenCalled()
232
+
233
+ releaseSecond()
234
+ releaseSecond()
235
+
236
+ expect(sources.clearInterval).toHaveBeenCalledTimes(1)
237
+ expect(delay.disable).toHaveBeenCalledTimes(1)
238
+ })
239
+ })
@@ -0,0 +1,121 @@
1
+ import { PostgreSqlPlatform } from '@mikro-orm/postgresql'
2
+ import { sanitizeSqlStatement } from '../provider/sanitize-sql'
3
+ import { PG_INSTRUMENTATION_OPTIONS, PG_STATEMENT_ATTRIBUTE_KEYS } from '../provider/otlp-provider'
4
+
5
+ const SENTINEL = 'pii-sentinel-value'
6
+ const platform = new PostgreSqlPlatform()
7
+
8
+ describe('sanitizeSqlStatement', () => {
9
+ it('strips values MikroORM inlines into an insert, keeping the shape', () => {
10
+ const formatted = platform.formatQuery(
11
+ 'insert into "comments" ("tenant_id", "body", "attempts", "is_public", "created_at") values (?, ?, ?, ?, ?) returning "id"',
12
+ ['c68d875e-b431-48c4-85ef-a8ce6d1c5540', SENTINEL, 42, true, new Date('2026-11-18T08:04:43.385Z')],
13
+ )
14
+ expect(formatted).toContain(SENTINEL)
15
+ expect(sanitizeSqlStatement(formatted)).toBe(
16
+ 'insert into "comments" ("tenant_id", "body", "attempts", "is_public", "created_at") values (?, ?, ?, ?, ?) returning "id"',
17
+ )
18
+ })
19
+
20
+ it('strips an id literal from a MikroORM findOne-style select', () => {
21
+ const formatted = platform.formatQuery(
22
+ 'select "s0".* from "sessions" as "s0" where "s0"."id" = ? and "s0"."user_id" = ? limit ?',
23
+ [SENTINEL, '405da1c6-ddf1-4c4b-9f1e-a7cdead1749c', 1],
24
+ )
25
+ const sanitized = sanitizeSqlStatement(formatted)
26
+ expect(sanitized).toBe('select "s0".* from "sessions" as "s0" where "s0"."id" = ? and "s0"."user_id" = ? limit ?')
27
+ expect(sanitized).not.toContain(SENTINEL)
28
+ })
29
+
30
+ it('strips escape strings that MikroORM emits for values with quotes and backslashes', () => {
31
+ const formatted = platform.formatQuery('update "notes" set "body" = ? where "id" = ?', [`O'Brien \\ ${SENTINEL} '`, 7])
32
+ expect(formatted).toContain(" E'")
33
+ expect(sanitizeSqlStatement(formatted)).toBe('update "notes" set "body" = ? where "id" = ?')
34
+ })
35
+
36
+ it('strips JSON and array literals', () => {
37
+ const formatted = platform.formatQuery('select * from "t" where "data" @> ? and "id" in (?)', [
38
+ JSON.stringify({ email: SENTINEL }),
39
+ [SENTINEL, 'other'],
40
+ ])
41
+ const sanitized = sanitizeSqlStatement(formatted)
42
+ expect(sanitized).toBe('select * from "t" where "data" @> ? and "id" in (?, ?)')
43
+ })
44
+
45
+ it('keeps placeholders, quoted identifiers, and numbers inside identifiers', () => {
46
+ const statement = `select "u1"."id", t0.x$1 from "it's ""odd"""."x" as t0 where id = $1 and n = $12`
47
+ expect(sanitizeSqlStatement(statement)).toBe(statement)
48
+ })
49
+
50
+ it('strips numeric, boolean, prefixed and dollar-quoted literals', () => {
51
+ expect(sanitizeSqlStatement("select 1, -2.5, .5e3, TRUE, false, B'0101', X'ff', N'abc', $$x$$, $tag$y$tag$")).toBe(
52
+ 'select ?, -?, ?, ?, ?, ?, ?, ?, ?, ?',
53
+ )
54
+ })
55
+
56
+ it('strips non-decimal, underscored and suffixed numbers whole', () => {
57
+ expect(sanitizeSqlStatement('select 0x1F, 0o17, 0b101, 1_000_000, 123abc, 1.5e3')).toBe('select ?, ?, ?, ?, ?, ?')
58
+ })
59
+
60
+ it('strips dollar-quoted strings with non-ASCII tags and keeps non-ASCII identifiers whole', () => {
61
+ expect(sanitizeSqlStatement(`select $é$ ${SENTINEL} $é$ from zamówienia1`)).toBe('select ? from zamówienia1')
62
+ })
63
+
64
+ it.each(['$🔐$', '$e\u0301$', '$€$'])('strips Postgres high-bit dollar tags: %s', (tag) => {
65
+ expect(sanitizeSqlStatement(`select ${tag}${SENTINEL}${tag}`)).toBe('select ?')
66
+ expect(sanitizeSqlStatement(`select ${tag}${SENTINEL}`)).toBeUndefined()
67
+ })
68
+
69
+ it('keeps non-ASCII identifier characters adjacent to dollar signs whole', () => {
70
+ const statement = 'select 🔐$1, e\u0301$2 from t'
71
+ expect(sanitizeSqlStatement(statement)).toBe(statement)
72
+ })
73
+
74
+ it('drops nested block comments in full', () => {
75
+ expect(sanitizeSqlStatement(`select 1 /* outer /* inner */ ${SENTINEL} */ from t`)).toBe('select ? from t')
76
+ })
77
+
78
+ it('drops comments, which can carry arbitrary text', () => {
79
+ expect(sanitizeSqlStatement(`select 1 -- ${SENTINEL}\nfrom t /* ${SENTINEL} */ where a = b`)).toBe(
80
+ 'select ? \nfrom t where a = b',
81
+ )
82
+ })
83
+
84
+ it.each([
85
+ `select '${SENTINEL}`,
86
+ `select E'${SENTINEL}\\'`,
87
+ 'select "unterminated',
88
+ `select $$${SENTINEL}`,
89
+ `select 1 /* ${SENTINEL}`,
90
+ `select 1 /* a /* b */ ${SENTINEL}`,
91
+ ])('fails closed on %s', (text) => {
92
+ expect(sanitizeSqlStatement(text)).toBeUndefined()
93
+ })
94
+ })
95
+
96
+ describe('PG_INSTRUMENTATION_OPTIONS.requestHook', () => {
97
+ function runHook(text: unknown) {
98
+ const attributes: Record<string, unknown> = {}
99
+ const span = { setAttribute: (key: string, value: unknown) => { attributes[key] = value } }
100
+ const hook = PG_INSTRUMENTATION_OPTIONS.requestHook as (span: unknown, info: unknown) => void
101
+ hook(span, { connection: {}, query: { text } })
102
+ return attributes
103
+ }
104
+
105
+ it('overwrites every statement attribute key with the sanitized text', () => {
106
+ const attributes = runHook(`select * from "users" where "id" = '${SENTINEL}'`)
107
+ for (const key of PG_STATEMENT_ATTRIBUTE_KEYS) {
108
+ expect(attributes[key]).toBe('select * from "users" where "id" = ?')
109
+ }
110
+ })
111
+
112
+ it('writes a fixed marker when the text cannot be tokenized', () => {
113
+ const attributes = runHook(`select '${SENTINEL}`)
114
+ expect(JSON.stringify(attributes)).not.toContain(SENTINEL)
115
+ expect(attributes['db.query.text']).toBe('[redacted]')
116
+ })
117
+
118
+ it('leaves the span alone when there is no statement text', () => {
119
+ expect(runHook(undefined)).toEqual({})
120
+ })
121
+ })
@@ -17,29 +17,35 @@
17
17
  * - **It can never break the app.** Every failure is swallowed. No
18
18
  * user-facing surface, no retry.
19
19
  *
20
- * This file, `config.ts`, and `propagator.ts` are the only parts of
21
- * `@open-mercato/telemetry` a client bundle may reach (via the `/browser` entry).
22
- * None of them may import the server facade (`node:async_hooks`) or the
20
+ * The `/browser` entry and its pure serialization/redaction helpers must not
21
+ * import the server facade (`node:async_hooks`) or the
23
22
  * env-reading `browser/server.ts`; the two wirings are independent and meet only
24
23
  * at the collector.
25
24
  */
26
25
 
27
26
  import * as React from 'react'
27
+ import { registerTelemetryErrorReporter, type TelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'
28
+ import { groupableCode } from '@open-mercato/shared/lib/telemetry/error-code'
29
+ import { serializeError } from '../facade/serialize'
30
+ import { redactAttributes } from '../facade/redact'
28
31
  import type { BrowserTelemetryConfig } from './config'
29
32
  import { createBackupHeaderPropagator } from './propagator'
30
33
 
31
34
  /** Module-level so React StrictMode's double-invoke (and any remount) cannot start a second SDK. */
32
35
  let bootstrapped = false
36
+ let disposeErrorReporter: (() => void) | undefined
33
37
 
34
38
  /**
35
39
  * Test seam. Production has exactly one bootstrap per page load, so nothing else
36
40
  * may call this — a second bootstrap would double every span.
37
41
  */
38
42
  export function resetBrowserTelemetryBootstrap(): void {
43
+ disposeErrorReporter?.()
44
+ disposeErrorReporter = undefined
39
45
  bootstrapped = false
40
46
  }
41
47
 
42
- async function startBrowserTelemetry(config: BrowserTelemetryConfig): Promise<void> {
48
+ async function startBrowserTelemetry(config: BrowserTelemetryConfig): Promise<TelemetryRuntime['reportError']> {
43
49
  const [
44
50
  { WebTracerProvider },
45
51
  { BatchSpanProcessor, ParentBasedSampler, TraceIdRatioBasedSampler },
@@ -49,7 +55,7 @@ async function startBrowserTelemetry(config: BrowserTelemetryConfig): Promise<vo
49
55
  { DocumentLoadInstrumentation },
50
56
  { FetchInstrumentation },
51
57
  { W3CTraceContextPropagator },
52
- { defaultTextMapSetter },
58
+ { defaultTextMapSetter, SpanStatusCode },
53
59
  ] = await Promise.all([
54
60
  import('@opentelemetry/sdk-trace-web'),
55
61
  import('@opentelemetry/sdk-trace-base'),
@@ -170,6 +176,22 @@ async function startBrowserTelemetry(config: BrowserTelemetryConfig): Promise<vo
170
176
  if (document.visibilityState === 'hidden') flush()
171
177
  })
172
178
  window.addEventListener('pagehide', flush)
179
+
180
+ const tracer = provider.getTracer('@open-mercato/telemetry/browser')
181
+ return (error, context) => {
182
+ const serialized = serializeError(error)
183
+ const attributes = redactAttributes({ ...context?.attributes, module: context?.module })
184
+ delete attributes['error.code']
185
+ const code = groupableCode(context?.code)
186
+ if (code) attributes['error.code'] = code
187
+ const span = tracer.startSpan('browser.error', { attributes })
188
+ try {
189
+ span.recordException(serialized)
190
+ span.setStatus({ code: SpanStatusCode.ERROR })
191
+ } finally {
192
+ span.end()
193
+ }
194
+ }
173
195
  }
174
196
 
175
197
  function escapeRegExp(value: string): string {
@@ -185,7 +207,13 @@ export function BrowserTelemetry({ config }: { config: BrowserTelemetryConfig |
185
207
  React.useEffect(() => {
186
208
  if (!config || bootstrapped) return
187
209
  bootstrapped = true
188
- void startBrowserTelemetry(config).catch(() => {
210
+ const reporter = startBrowserTelemetry(config)
211
+ const dispose = registerTelemetryErrorReporter((...args) => {
212
+ void reporter.then((reportError) => reportError(...args)).catch(() => {})
213
+ })
214
+ disposeErrorReporter = dispose
215
+ void reporter.catch(() => {
216
+ dispose()
189
217
  // Telemetry must never degrade the app it measures: stay silent and stay down (no retry).
190
218
  })
191
219
  }, [config])
@@ -44,6 +44,7 @@ jest.mock('@opentelemetry/sdk-trace-web', () =>
44
44
  WebTracerProvider: class {
45
45
  register = jest.fn()
46
46
  forceFlush = jest.fn(async () => {})
47
+ getTracer = jest.fn(() => ({ startSpan: jest.fn() }))
47
48
  constructor(options: Record<string, unknown>) {
48
49
  mockProviderInstances.push({ options, register: this.register, forceFlush: this.forceFlush })
49
50
  }