@open-mercato/telemetry 0.11.1-develop.9114.1.e26ee64834 → 0.11.1-develop.9121.1.1b6d34f5d8

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.
@@ -1,4 +1,20 @@
1
1
  import { redactAttributes, redactSpanName } from "../facade/redact.js";
2
+ const SANITIZED_POSTGRES_ERROR_RE = /^PostgreSQL error of type '[A-Za-z0-9_]{1,64}' occurred \(code: [A-Za-z0-9_]{1,16}\)$/;
3
+ function sanitizedPostgresErrorMessage(value) {
4
+ return typeof value === "string" && SANITIZED_POSTGRES_ERROR_RE.test(value) ? value : void 0;
5
+ }
6
+ function redactPostgresException(event) {
7
+ if (event.name !== "exception" || !event.attributes) return event;
8
+ const attributes = { ...event.attributes };
9
+ if (!sanitizedPostgresErrorMessage(attributes["exception.message"])) delete attributes["exception.message"];
10
+ delete attributes["exception.stacktrace"];
11
+ return { ...event, attributes };
12
+ }
13
+ function redactPostgresStatus(status, events) {
14
+ if (status.message === void 0) return status;
15
+ const classification = events.map((event) => event.name === "exception" ? sanitizedPostgresErrorMessage(event.attributes?.["exception.message"]) : void 0).find((message) => message !== void 0);
16
+ return classification ? { code: status.code, message: classification } : { code: status.code };
17
+ }
2
18
  function createRedactingSpanProcessor(processor) {
3
19
  return {
4
20
  onStart: (span, parentContext) => processor.onStart(span, parentContext),
@@ -8,6 +24,8 @@ function createRedactingSpanProcessor(processor) {
8
24
  for (const [key, value] of Object.entries(span.attributes)) {
9
25
  attributes[key] = typeof value === "string" ? redactAttributes({ [key]: value })[key] : Array.isArray(value) ? value.map((entry) => typeof entry === "string" ? String(redactAttributes({ [key]: entry })[key]) : entry) : value;
10
26
  }
27
+ const isPostgresSpan = span.instrumentationScope?.name === "@opentelemetry/instrumentation-pg";
28
+ const events = isPostgresSpan ? span.events.map(redactPostgresException) : span.events;
11
29
  processor.onEnd({
12
30
  name: redactSpanName(span.name),
13
31
  attributes,
@@ -16,9 +34,9 @@ function createRedactingSpanProcessor(processor) {
16
34
  parentSpanContext: span.parentSpanContext,
17
35
  startTime: span.startTime,
18
36
  endTime: span.endTime,
19
- status: span.status,
37
+ status: isPostgresSpan ? redactPostgresStatus(span.status, events) : span.status,
20
38
  links: span.links,
21
- events: span.events,
39
+ events,
22
40
  resource: span.resource,
23
41
  instrumentationScope: span.instrumentationScope,
24
42
  duration: span.duration,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/provider/redacting-span-processor.ts"],
4
- "sourcesContent": ["import type { ReadableSpan, SpanProcessor } from '@opentelemetry/sdk-trace-node'\nimport { redactAttributes, redactSpanName } from '../facade/redact'\n\nexport function createRedactingSpanProcessor(processor: SpanProcessor): SpanProcessor {\n return {\n onStart: (span, parentContext) => processor.onStart(span, parentContext),\n onEnding: (span) => processor.onEnding?.(span),\n onEnd(span) {\n const attributes: ReadableSpan['attributes'] = {}\n for (const [key, value] of Object.entries(span.attributes)) {\n attributes[key] = typeof value === 'string'\n ? redactAttributes({ [key]: value })[key]\n : Array.isArray(value)\n ? value.map((entry) => typeof entry === 'string'\n ? String(redactAttributes({ [key]: entry })[key])\n : entry) as typeof value\n : value\n }\n processor.onEnd({\n name: redactSpanName(span.name),\n attributes,\n spanContext: () => span.spanContext(),\n kind: span.kind,\n parentSpanContext: span.parentSpanContext,\n startTime: span.startTime,\n endTime: span.endTime,\n status: span.status,\n links: span.links,\n events: span.events,\n resource: span.resource,\n instrumentationScope: span.instrumentationScope,\n duration: span.duration,\n ended: span.ended,\n droppedAttributesCount: span.droppedAttributesCount,\n droppedEventsCount: span.droppedEventsCount,\n droppedLinksCount: span.droppedLinksCount,\n })\n },\n forceFlush: () => processor.forceFlush(),\n shutdown: () => processor.shutdown(),\n }\n}\n"],
5
- "mappings": "AACA,SAAS,kBAAkB,sBAAsB;AAE1C,SAAS,6BAA6B,WAAyC;AACpF,SAAO;AAAA,IACL,SAAS,CAAC,MAAM,kBAAkB,UAAU,QAAQ,MAAM,aAAa;AAAA,IACvE,UAAU,CAAC,SAAS,UAAU,WAAW,IAAI;AAAA,IAC7C,MAAM,MAAM;AACV,YAAM,aAAyC,CAAC;AAChD,iBAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,KAAK,UAAU,GAAG;AAC1D,mBAAW,GAAG,IAAI,OAAO,UAAU,WAC/B,iBAAiB,EAAE,CAAC,GAAG,GAAG,MAAM,CAAC,EAAE,GAAG,IACtC,MAAM,QAAQ,KAAK,IACjB,MAAM,IAAI,CAAC,UAAU,OAAO,UAAU,WACpC,OAAO,iBAAiB,EAAE,CAAC,GAAG,GAAG,MAAM,CAAC,EAAE,GAAG,CAAC,IAC9C,KAAK,IACP;AAAA,MACR;AACA,gBAAU,MAAM;AAAA,QACd,MAAM,eAAe,KAAK,IAAI;AAAA,QAC9B;AAAA,QACA,aAAa,MAAM,KAAK,YAAY;AAAA,QACpC,MAAM,KAAK;AAAA,QACX,mBAAmB,KAAK;AAAA,QACxB,WAAW,KAAK;AAAA,QAChB,SAAS,KAAK;AAAA,QACd,QAAQ,KAAK;AAAA,QACb,OAAO,KAAK;AAAA,QACZ,QAAQ,KAAK;AAAA,QACb,UAAU,KAAK;AAAA,QACf,sBAAsB,KAAK;AAAA,QAC3B,UAAU,KAAK;AAAA,QACf,OAAO,KAAK;AAAA,QACZ,wBAAwB,KAAK;AAAA,QAC7B,oBAAoB,KAAK;AAAA,QACzB,mBAAmB,KAAK;AAAA,MAC1B,CAAC;AAAA,IACH;AAAA,IACA,YAAY,MAAM,UAAU,WAAW;AAAA,IACvC,UAAU,MAAM,UAAU,SAAS;AAAA,EACrC;AACF;",
4
+ "sourcesContent": ["import type { ReadableSpan, SpanProcessor } from '@opentelemetry/sdk-trace-node'\nimport { redactAttributes, redactSpanName } from '../facade/redact'\n\nconst SANITIZED_POSTGRES_ERROR_RE = /^PostgreSQL error of type '[A-Za-z0-9_]{1,64}' occurred \\(code: [A-Za-z0-9_]{1,16}\\)$/\n\nfunction sanitizedPostgresErrorMessage(value: unknown): string | undefined {\n return typeof value === 'string' && SANITIZED_POSTGRES_ERROR_RE.test(value) ? value : undefined\n}\n\nfunction redactPostgresException(event: ReadableSpan['events'][number]): ReadableSpan['events'][number] {\n if (event.name !== 'exception' || !event.attributes) return event\n const attributes = { ...event.attributes }\n if (!sanitizedPostgresErrorMessage(attributes['exception.message'])) delete attributes['exception.message']\n delete attributes['exception.stacktrace']\n return { ...event, attributes }\n}\n\nfunction redactPostgresStatus(\n status: ReadableSpan['status'],\n events: ReadableSpan['events'],\n): ReadableSpan['status'] {\n if (status.message === undefined) return status\n const classification = events\n .map((event) => event.name === 'exception' ? sanitizedPostgresErrorMessage(event.attributes?.['exception.message']) : undefined)\n .find((message) => message !== undefined)\n return classification ? { code: status.code, message: classification } : { code: status.code }\n}\n\nexport function createRedactingSpanProcessor(processor: SpanProcessor): SpanProcessor {\n return {\n onStart: (span, parentContext) => processor.onStart(span, parentContext),\n onEnding: (span) => processor.onEnding?.(span),\n onEnd(span) {\n const attributes: ReadableSpan['attributes'] = {}\n for (const [key, value] of Object.entries(span.attributes)) {\n attributes[key] = typeof value === 'string'\n ? redactAttributes({ [key]: value })[key]\n : Array.isArray(value)\n ? value.map((entry) => typeof entry === 'string'\n ? String(redactAttributes({ [key]: entry })[key])\n : entry) as typeof value\n : value\n }\n const isPostgresSpan = span.instrumentationScope?.name === '@opentelemetry/instrumentation-pg'\n const events = isPostgresSpan ? span.events.map(redactPostgresException) : span.events\n processor.onEnd({\n name: redactSpanName(span.name),\n attributes,\n spanContext: () => span.spanContext(),\n kind: span.kind,\n parentSpanContext: span.parentSpanContext,\n startTime: span.startTime,\n endTime: span.endTime,\n status: isPostgresSpan ? redactPostgresStatus(span.status, events) : span.status,\n links: span.links,\n events,\n resource: span.resource,\n instrumentationScope: span.instrumentationScope,\n duration: span.duration,\n ended: span.ended,\n droppedAttributesCount: span.droppedAttributesCount,\n droppedEventsCount: span.droppedEventsCount,\n droppedLinksCount: span.droppedLinksCount,\n })\n },\n forceFlush: () => processor.forceFlush(),\n shutdown: () => processor.shutdown(),\n }\n}\n"],
5
+ "mappings": "AACA,SAAS,kBAAkB,sBAAsB;AAEjD,MAAM,8BAA8B;AAEpC,SAAS,8BAA8B,OAAoC;AACzE,SAAO,OAAO,UAAU,YAAY,4BAA4B,KAAK,KAAK,IAAI,QAAQ;AACxF;AAEA,SAAS,wBAAwB,OAAuE;AACtG,MAAI,MAAM,SAAS,eAAe,CAAC,MAAM,WAAY,QAAO;AAC5D,QAAM,aAAa,EAAE,GAAG,MAAM,WAAW;AACzC,MAAI,CAAC,8BAA8B,WAAW,mBAAmB,CAAC,EAAG,QAAO,WAAW,mBAAmB;AAC1G,SAAO,WAAW,sBAAsB;AACxC,SAAO,EAAE,GAAG,OAAO,WAAW;AAChC;AAEA,SAAS,qBACP,QACA,QACwB;AACxB,MAAI,OAAO,YAAY,OAAW,QAAO;AACzC,QAAM,iBAAiB,OACpB,IAAI,CAAC,UAAU,MAAM,SAAS,cAAc,8BAA8B,MAAM,aAAa,mBAAmB,CAAC,IAAI,MAAS,EAC9H,KAAK,CAAC,YAAY,YAAY,MAAS;AAC1C,SAAO,iBAAiB,EAAE,MAAM,OAAO,MAAM,SAAS,eAAe,IAAI,EAAE,MAAM,OAAO,KAAK;AAC/F;AAEO,SAAS,6BAA6B,WAAyC;AACpF,SAAO;AAAA,IACL,SAAS,CAAC,MAAM,kBAAkB,UAAU,QAAQ,MAAM,aAAa;AAAA,IACvE,UAAU,CAAC,SAAS,UAAU,WAAW,IAAI;AAAA,IAC7C,MAAM,MAAM;AACV,YAAM,aAAyC,CAAC;AAChD,iBAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,KAAK,UAAU,GAAG;AAC1D,mBAAW,GAAG,IAAI,OAAO,UAAU,WAC/B,iBAAiB,EAAE,CAAC,GAAG,GAAG,MAAM,CAAC,EAAE,GAAG,IACtC,MAAM,QAAQ,KAAK,IACjB,MAAM,IAAI,CAAC,UAAU,OAAO,UAAU,WACpC,OAAO,iBAAiB,EAAE,CAAC,GAAG,GAAG,MAAM,CAAC,EAAE,GAAG,CAAC,IAC9C,KAAK,IACP;AAAA,MACR;AACA,YAAM,iBAAiB,KAAK,sBAAsB,SAAS;AAC3D,YAAM,SAAS,iBAAiB,KAAK,OAAO,IAAI,uBAAuB,IAAI,KAAK;AAChF,gBAAU,MAAM;AAAA,QACd,MAAM,eAAe,KAAK,IAAI;AAAA,QAC9B;AAAA,QACA,aAAa,MAAM,KAAK,YAAY;AAAA,QACpC,MAAM,KAAK;AAAA,QACX,mBAAmB,KAAK;AAAA,QACxB,WAAW,KAAK;AAAA,QAChB,SAAS,KAAK;AAAA,QACd,QAAQ,iBAAiB,qBAAqB,KAAK,QAAQ,MAAM,IAAI,KAAK;AAAA,QAC1E,OAAO,KAAK;AAAA,QACZ;AAAA,QACA,UAAU,KAAK;AAAA,QACf,sBAAsB,KAAK;AAAA,QAC3B,UAAU,KAAK;AAAA,QACf,OAAO,KAAK;AAAA,QACZ,wBAAwB,KAAK;AAAA,QAC7B,oBAAoB,KAAK;AAAA,QACzB,mBAAmB,KAAK;AAAA,MAC1B,CAAC;AAAA,IACH;AAAA,IACA,YAAY,MAAM,UAAU,WAAW;AAAA,IACvC,UAAU,MAAM,UAAU,SAAS;AAAA,EACrC;AACF;",
6
6
  "names": []
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/telemetry",
3
- "version": "0.11.1-develop.9114.1.e26ee64834",
3
+ "version": "0.11.1-develop.9121.1.1b6d34f5d8",
4
4
  "license": "MIT",
5
5
  "description": "Vendor-neutral spans, metrics, and error reporting backed by a pluggable OTLP provider. Off by default; the telemetry runtime is loaded only when explicitly enabled.",
6
6
  "type": "module",
@@ -38,7 +38,7 @@
38
38
  }
39
39
  },
40
40
  "dependencies": {
41
- "@open-mercato/shared": "0.11.1-develop.9114.1.e26ee64834"
41
+ "@open-mercato/shared": "0.11.1-develop.9121.1.1b6d34f5d8"
42
42
  },
43
43
  "peerDependencies": {
44
44
  "react": ">=18.0.0"
@@ -15,6 +15,9 @@ import path from 'node:path'
15
15
  * `instrumentations: []` for that reason). No database is needed — a connection to
16
16
  * a dead port still drives the query path, and the instrumentation records the
17
17
  * span before the underlying call fails.
18
+ * The server-error case uses a minimal in-process PostgreSQL wire server that
19
+ * answers every query with an ErrorResponse echoing a sentinel, so the export of
20
+ * a real server-side failure is checked without a database.
18
21
  */
19
22
  const pkgRoot = path.resolve(__dirname, '../..')
20
23
  const PROBE_TIMEOUT_MS = 120_000
@@ -76,14 +79,96 @@ try {
76
79
  }
77
80
  `
78
81
 
79
- type ProbeSpan = { name: string; attributes: Record<string, unknown> }
82
+ const SERVER_ERROR_SCRIPT = `
83
+ import net from 'node:net'
84
+ const { OtlpProvider } = await import('@open-mercato/telemetry/provider/otlp-provider')
85
+ const { InMemorySpanExporter, SimpleSpanProcessor } = await import('@opentelemetry/sdk-trace-base')
86
+
87
+ const exporter = new InMemorySpanExporter()
88
+ const processor = new SimpleSpanProcessor(exporter)
89
+ const provider = new OtlpProvider({ spanProcessors: [processor], logRecordProcessors: [], metricReaders: [] })
90
+ await provider.start()
91
+
92
+ const cstr = (value) => Buffer.concat([Buffer.from(value), Buffer.alloc(1)])
93
+ const frame = (type, body) => {
94
+ const header = Buffer.alloc(5)
95
+ header.write(type, 0)
96
+ header.writeInt32BE(body.length + 4, 1)
97
+ return Buffer.concat([header, body])
98
+ }
99
+ const int32 = (value) => { const buffer = Buffer.alloc(4); buffer.writeInt32BE(value); return buffer }
100
+ const readyForQuery = frame('Z', Buffer.from('I'))
101
+ const errorResponse = frame('E', Buffer.concat([
102
+ Buffer.from('S'), cstr('ERROR'),
103
+ Buffer.from('V'), cstr('ERROR'),
104
+ Buffer.from('C'), cstr('22P02'),
105
+ Buffer.from('M'), cstr('invalid input syntax for type uuid: "pii-sentinel-value"'),
106
+ Buffer.alloc(1),
107
+ ]))
80
108
 
81
- function runChild(order: string): ProbeSpan[] {
109
+ const server = net.createServer((socket) => {
110
+ let pending = Buffer.alloc(0)
111
+ let started = false
112
+ socket.on('data', (chunk) => {
113
+ pending = Buffer.concat([pending, chunk])
114
+ while (true) {
115
+ if (!started) {
116
+ if (pending.length < 4) return
117
+ const length = pending.readInt32BE(0)
118
+ if (pending.length < length) return
119
+ pending = pending.subarray(length)
120
+ started = true
121
+ socket.write(Buffer.concat([frame('R', int32(0)), readyForQuery]))
122
+ continue
123
+ }
124
+ if (pending.length < 5) return
125
+ const type = String.fromCharCode(pending[0])
126
+ const length = pending.readInt32BE(1)
127
+ if (pending.length < length + 1) return
128
+ pending = pending.subarray(length + 1)
129
+ if (type === 'X') { socket.end(); return }
130
+ if (type === 'Q' || type === 'S') socket.write(Buffer.concat([errorResponse, readyForQuery]))
131
+ }
132
+ })
133
+ })
134
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve))
135
+
136
+ const pgModule = await import('pg')
137
+ const Client = (pgModule.default ?? pgModule).Client
138
+ const client = new Client({ host: '127.0.0.1', port: server.address().port, user: 'telemetry-probe', database: 'telemetry-probe' })
139
+ try {
140
+ await client.connect()
141
+ const failures = []
142
+ for (const [text, values] of [['SELECT $1::uuid', ['pii-sentinel-value']], ["select 'pii-sentinel-value'::uuid", undefined]]) {
143
+ try { await client.query(text, values) } catch (error) { failures.push(error.code) }
144
+ }
145
+ if (failures.join(',') !== '22P02,22P02') throw new Error('[internal] fake server did not fail both queries: ' + failures.join(','))
146
+ await processor.forceFlush()
147
+ const spans = exporter.getFinishedSpans().map((span) => ({
148
+ name: span.name,
149
+ attributes: span.attributes,
150
+ status: span.status,
151
+ events: span.events.map((event) => ({ name: event.name, attributes: event.attributes })),
152
+ }))
153
+ console.log('SPANS=' + JSON.stringify(spans))
154
+ } finally {
155
+ await client.end().catch(() => undefined)
156
+ server.close()
157
+ await provider.shutdown()
158
+ }
159
+ `
160
+
161
+ type ProbeSpan = { name: string; attributes: Record<string, unknown>
162
+ status?: { code: number; message?: string }
163
+ events?: Array<{ name: string; attributes?: Record<string, unknown> }>
164
+ }
165
+
166
+ function runChild(order: string, script = CHILD_SCRIPT): ProbeSpan[] {
82
167
  // The script must live inside the package tree: ESM resolves bare specifiers
83
168
  // (`@open-mercato/telemetry`, `@opentelemetry/*`, `pg`) relative to the file's
84
169
  // location, not the process cwd.
85
170
  const scriptFile = path.join(pkgRoot, `.pg-instrumentation-probe.${process.pid}.mjs`)
86
- fs.writeFileSync(scriptFile, CHILD_SCRIPT)
171
+ fs.writeFileSync(scriptFile, script)
87
172
  try {
88
173
  const result = spawnSync(process.execPath, [scriptFile, order], {
89
174
  cwd: pkgRoot,
@@ -121,4 +206,20 @@ describe('OTLP provider pg instrumentation', () => {
121
206
  },
122
207
  PROBE_TIMEOUT_MS + 10_000,
123
208
  )
209
+
210
+ it(
211
+ 'exports a failed pg query with the SQLSTATE classification and without the value the server echoed',
212
+ () => {
213
+ const spans = runChild('server-error', SERVER_ERROR_SCRIPT).filter((span) => span.name.startsWith('pg.query'))
214
+ expect(spans).toHaveLength(2)
215
+ expect(JSON.stringify(spans)).not.toContain('pii-sentinel-value')
216
+ for (const span of spans) {
217
+ expect(span.status).toEqual({ code: 2, message: "PostgreSQL error of type 'error' occurred (code: 22P02)" })
218
+ expect(span.events).toEqual([
219
+ { name: 'exception', attributes: { 'exception.message': "PostgreSQL error of type 'error' occurred (code: 22P02)" } },
220
+ ])
221
+ }
222
+ },
223
+ PROBE_TIMEOUT_MS + 10_000,
224
+ )
124
225
  })
@@ -1,4 +1,4 @@
1
- import { ROOT_CONTEXT } from '@opentelemetry/api'
1
+ import { ROOT_CONTEXT, SpanStatusCode } from '@opentelemetry/api'
2
2
  import { BasicTracerProvider, type ReadableSpan, type SpanProcessor } from '@opentelemetry/sdk-trace-base'
3
3
  import { createRedactingSpanProcessor } from '../provider/redacting-span-processor'
4
4
 
@@ -76,6 +76,62 @@ describe('redacting span processor', () => {
76
76
  }
77
77
  })
78
78
 
79
+ it('drops value-echoing PostgreSQL error text but keeps the sanitized SQLSTATE classification', async () => {
80
+ const processor = recordingProcessor()
81
+ const provider = new BasicTracerProvider({ spanProcessors: [createRedactingSpanProcessor(processor)] })
82
+ try {
83
+ const driverMessage = 'invalid input syntax for type uuid: "pii-sentinel-value"'
84
+ const sanitizedMessage = "PostgreSQL error of type 'error' occurred (code: 22P02)"
85
+ const postgresSpan = provider.getTracer('@opentelemetry/instrumentation-pg').startSpan('pg.query:SELECT')
86
+ postgresSpan.recordException(sanitizedMessage)
87
+ postgresSpan.setStatus({ code: SpanStatusCode.ERROR, message: driverMessage })
88
+ postgresSpan.addEvent('query.finished')
89
+ postgresSpan.end()
90
+
91
+ const applicationSpan = provider.getTracer('application').startSpan('application.operation')
92
+ applicationSpan.setStatus({ code: SpanStatusCode.ERROR, message: driverMessage })
93
+ applicationSpan.recordException(new Error(driverMessage))
94
+ applicationSpan.end()
95
+
96
+ const [[cleanedPostgresSpan], [cleanedApplicationSpan]] = processor.onEnd.mock.calls
97
+ expect(JSON.stringify({ status: cleanedPostgresSpan.status, events: cleanedPostgresSpan.events })).not.toContain('pii-sentinel-value')
98
+ expect(cleanedPostgresSpan.status).toEqual({ code: SpanStatusCode.ERROR, message: sanitizedMessage })
99
+ expect(cleanedPostgresSpan.events).toEqual([
100
+ expect.objectContaining({ name: 'exception', attributes: { 'exception.message': sanitizedMessage } }),
101
+ expect.objectContaining({ name: 'query.finished' }),
102
+ ])
103
+ expect(cleanedApplicationSpan.status).toEqual({ code: SpanStatusCode.ERROR, message: driverMessage })
104
+ expect(cleanedApplicationSpan.events[0].attributes?.['exception.message']).toBe(driverMessage)
105
+ const originalPostgresSpan = processor.onStart.mock.calls[0][0] as ReadableSpan
106
+ expect(originalPostgresSpan.status.message).toBe(driverMessage)
107
+ } finally {
108
+ await provider.shutdown()
109
+ }
110
+ })
111
+
112
+ it('fails closed when a PostgreSQL exception message is not the sanitized classification', async () => {
113
+ const processor = recordingProcessor()
114
+ const provider = new BasicTracerProvider({ spanProcessors: [createRedactingSpanProcessor(processor)] })
115
+ try {
116
+ const driverMessage = 'duplicate key value violates unique constraint, Key (email)=(pii-sentinel-value) already exists.'
117
+ const postgresSpan = provider.getTracer('@opentelemetry/instrumentation-pg').startSpan('pg.query:INSERT')
118
+ postgresSpan.recordException(new Error(driverMessage))
119
+ postgresSpan.recordException(`PostgreSQL error of type 'error' occurred (code: 23505) ${driverMessage}`)
120
+ postgresSpan.setStatus({ code: SpanStatusCode.ERROR, message: driverMessage })
121
+ postgresSpan.end()
122
+
123
+ const [[cleanedPostgresSpan]] = processor.onEnd.mock.calls
124
+ expect(JSON.stringify({ status: cleanedPostgresSpan.status, events: cleanedPostgresSpan.events })).not.toContain('pii-sentinel-value')
125
+ expect(cleanedPostgresSpan.status).toEqual({ code: SpanStatusCode.ERROR })
126
+ expect(cleanedPostgresSpan.events.map((event) => event.attributes)).toEqual([
127
+ { 'exception.type': 'Error' },
128
+ {},
129
+ ])
130
+ } finally {
131
+ await provider.shutdown()
132
+ }
133
+ })
134
+
79
135
  it('exports quote paths and span names with credentials redacted', async () => {
80
136
  const processor = recordingProcessor()
81
137
  const provider = new BasicTracerProvider({ spanProcessors: [createRedactingSpanProcessor(processor)] })
@@ -1,6 +1,31 @@
1
1
  import type { ReadableSpan, SpanProcessor } from '@opentelemetry/sdk-trace-node'
2
2
  import { redactAttributes, redactSpanName } from '../facade/redact'
3
3
 
4
+ const SANITIZED_POSTGRES_ERROR_RE = /^PostgreSQL error of type '[A-Za-z0-9_]{1,64}' occurred \(code: [A-Za-z0-9_]{1,16}\)$/
5
+
6
+ function sanitizedPostgresErrorMessage(value: unknown): string | undefined {
7
+ return typeof value === 'string' && SANITIZED_POSTGRES_ERROR_RE.test(value) ? value : undefined
8
+ }
9
+
10
+ function redactPostgresException(event: ReadableSpan['events'][number]): ReadableSpan['events'][number] {
11
+ if (event.name !== 'exception' || !event.attributes) return event
12
+ const attributes = { ...event.attributes }
13
+ if (!sanitizedPostgresErrorMessage(attributes['exception.message'])) delete attributes['exception.message']
14
+ delete attributes['exception.stacktrace']
15
+ return { ...event, attributes }
16
+ }
17
+
18
+ function redactPostgresStatus(
19
+ status: ReadableSpan['status'],
20
+ events: ReadableSpan['events'],
21
+ ): ReadableSpan['status'] {
22
+ if (status.message === undefined) return status
23
+ const classification = events
24
+ .map((event) => event.name === 'exception' ? sanitizedPostgresErrorMessage(event.attributes?.['exception.message']) : undefined)
25
+ .find((message) => message !== undefined)
26
+ return classification ? { code: status.code, message: classification } : { code: status.code }
27
+ }
28
+
4
29
  export function createRedactingSpanProcessor(processor: SpanProcessor): SpanProcessor {
5
30
  return {
6
31
  onStart: (span, parentContext) => processor.onStart(span, parentContext),
@@ -16,6 +41,8 @@ export function createRedactingSpanProcessor(processor: SpanProcessor): SpanProc
16
41
  : entry) as typeof value
17
42
  : value
18
43
  }
44
+ const isPostgresSpan = span.instrumentationScope?.name === '@opentelemetry/instrumentation-pg'
45
+ const events = isPostgresSpan ? span.events.map(redactPostgresException) : span.events
19
46
  processor.onEnd({
20
47
  name: redactSpanName(span.name),
21
48
  attributes,
@@ -24,9 +51,9 @@ export function createRedactingSpanProcessor(processor: SpanProcessor): SpanProc
24
51
  parentSpanContext: span.parentSpanContext,
25
52
  startTime: span.startTime,
26
53
  endTime: span.endTime,
27
- status: span.status,
54
+ status: isPostgresSpan ? redactPostgresStatus(span.status, events) : span.status,
28
55
  links: span.links,
29
- events: span.events,
56
+ events,
30
57
  resource: span.resource,
31
58
  instrumentationScope: span.instrumentationScope,
32
59
  duration: span.duration,