@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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/provider/otlp-provider.ts"],
4
- "sourcesContent": ["/**\n * The ONLY file in this package that imports `@opentelemetry/*`. Loaded via\n * dynamic `import()` from `init.ts` (so the heavy SDK never loads when telemetry\n * is off), and the OTEL packages live in `optionalDependencies`.\n *\n * Serves any OTLP backend \u2014 the endpoint + headers come from the standard\n * `OTEL_EXPORTER_OTLP_*` env vars, read by the exporters directly.\n */\nimport {\n trace,\n metrics,\n context,\n isSpanContextValid,\n defaultTextMapGetter,\n defaultTextMapSetter,\n ROOT_CONTEXT,\n SpanStatusCode,\n SpanKind as OtelSpanKind,\n type Link,\n type Span as OtelApiSpan,\n type SpanOptions as OtelSpanOptions,\n type TextMapPropagator,\n type Counter,\n type Histogram,\n type Gauge,\n} from '@opentelemetry/api'\nimport { W3CTraceContextPropagator } from '@opentelemetry/core'\nimport { logs, SeverityNumber } from '@opentelemetry/api-logs'\nimport { NodeSDK } from '@opentelemetry/sdk-node'\nimport type { Instrumentation } from '@opentelemetry/instrumentation'\nimport { resourceFromAttributes } from '@opentelemetry/resources'\nimport { ATTR_SERVICE_NAME } from '@opentelemetry/semantic-conventions'\nimport {\n BatchSpanProcessor,\n ParentBasedSampler,\n TraceIdRatioBasedSampler,\n type SpanProcessor,\n} from '@opentelemetry/sdk-trace-node'\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'\nimport { OTLPLogExporter } from '@opentelemetry/exporter-logs-otlp-http'\nimport { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-http'\nimport { BatchLogRecordProcessor, type LogRecordProcessor } from '@opentelemetry/sdk-logs'\nimport { PeriodicExportingMetricReader, type IMetricReader } from '@opentelemetry/sdk-metrics'\nimport { PgInstrumentation } from '@opentelemetry/instrumentation-pg'\nimport { UndiciInstrumentation } from '@opentelemetry/instrumentation-undici'\n\nimport type {\n Attributes,\n AttributeValue,\n LogLevel,\n LogRecord,\n MetricPoint,\n Span,\n SpanKind,\n SpanOptions,\n TelemetryProvider,\n TelemetrySignal,\n TraceCarrier,\n TraceContext,\n} from '../types'\nimport { readTelemetryEnv } from '../env'\nimport { BACKUP_TRACEPARENT_HEADER, BACKUP_TRACESTATE_HEADER } from '../trace-headers'\nimport { redactAttributes, redactPii } from '../facade/redact'\nimport { serializeError } from '../facade/serialize'\nimport { runSpan } from './run-span'\n\nconst TRACER_NAME = 'open-mercato'\n\n/**\n * Queue/event trace propagation rides a dedicated W3C propagator on the payload\n * `_trace` carrier \u2014 deliberately NOT the global propagator below.\n */\nconst queuePropagator = new W3CTraceContextPropagator()\n\nconst W3C_TRACEPARENT = 'traceparent'\nconst W3C_TRACESTATE = 'tracestate'\n// Backup headers that mirror the W3C context but a proxy/LB won't rewrite.\nconst BACKUP_TRACEPARENT = BACKUP_TRACEPARENT_HEADER\nconst BACKUP_TRACESTATE = BACKUP_TRACESTATE_HEADER\n\n/**\n * Global propagator: standard W3C plus a backup copy\n * (`x-original-traceparent`), with explicit inbound trust.\n *\n * The problem: a load balancer (e.g. GCP's) reads the inbound `traceparent`,\n * creates its own span, and **rewrites** `traceparent` to point at that span \u2014\n * which our backend never sees. With plain W3C extraction every request becomes a\n * child of that unexported span: no request is a root, and root-span / trace-group\n * views come up empty.\n *\n * The fix (the industry \"backup header\" pattern): on inject we also write\n * `x-original-traceparent`, which the LB leaves untouched. A backup header is\n * still caller-controlled at an HTTP boundary, so its mere\n * presence is not proof that one of our services created it. Extraction ignores\n * both standard and backup headers by default.\n *\n * `TELEMETRY_TRUST_INBOUND_TRACE=true` enables both extraction paths for a\n * deployment behind a trusted upstream. Our dedicated queue/event carrier is\n * unaffected \u2014 it uses `queuePropagator` directly, not this global one.\n */\nconst backupHeaderPropagator: TextMapPropagator = {\n inject(ctx, carrier, setter) {\n // Inject into a plain temp carrier so we can mirror the values regardless of\n // the real carrier's setter shape, then copy both standard + backup headers.\n const tmp: Record<string, string> = {}\n queuePropagator.inject(ctx, tmp, defaultTextMapSetter)\n for (const [key, value] of Object.entries(tmp)) setter.set(carrier, key, value)\n if (tmp[W3C_TRACEPARENT]) setter.set(carrier, BACKUP_TRACEPARENT, tmp[W3C_TRACEPARENT])\n if (tmp[W3C_TRACESTATE]) setter.set(carrier, BACKUP_TRACESTATE, tmp[W3C_TRACESTATE])\n },\n extract(ctx, carrier, getter) {\n // Both the standard and backup headers are caller-controlled at an HTTP\n // boundary. Trust neither unless the deployment explicitly opts in.\n if (!readTelemetryEnv().trustInboundTrace) return ctx\n const first = (value: string | string[] | undefined): string | undefined =>\n Array.isArray(value) ? value[0] : value\n const backupTraceparent = first(getter.get(carrier, BACKUP_TRACEPARENT))\n if (backupTraceparent) {\n const backupCarrier: Record<string, string> = { [W3C_TRACEPARENT]: backupTraceparent }\n const backupTracestate = first(getter.get(carrier, BACKUP_TRACESTATE))\n if (backupTracestate) backupCarrier[W3C_TRACESTATE] = backupTracestate\n return queuePropagator.extract(ctx, backupCarrier, defaultTextMapGetter)\n }\n return queuePropagator.extract(ctx, carrier, getter)\n },\n fields: () => [...queuePropagator.fields(), BACKUP_TRACEPARENT, BACKUP_TRACESTATE],\n}\n\nfunction cleanAttributes(attributes?: Attributes): Record<string, AttributeValue> {\n const out: Record<string, AttributeValue> = {}\n if (!attributes) return out\n for (const [key, value] of Object.entries(redactAttributes(attributes))) {\n if (value !== undefined) out[key] = value\n }\n return out\n}\n\nconst SPAN_KIND: Record<SpanKind, OtelSpanKind> = {\n internal: OtelSpanKind.INTERNAL,\n server: OtelSpanKind.SERVER,\n client: OtelSpanKind.CLIENT,\n producer: OtelSpanKind.PRODUCER,\n consumer: OtelSpanKind.CONSUMER,\n}\n\n/**\n * Resolve `links` carriers to span contexts. Extraction runs against\n * `ROOT_CONTEXT`, never the active one \u2014 otherwise an empty carrier would\n * silently link a span to its own ambient parent instead of yielding no link.\n */\nfunction spanLinks(carriers?: TraceCarrier[]): Link[] | undefined {\n if (!carriers?.length) return undefined\n const links: Link[] = []\n for (const carrier of carriers) {\n const linked = trace.getSpanContext(queuePropagator.extract(ROOT_CONTEXT, carrier, defaultTextMapGetter))\n if (linked && isSpanContextValid(linked)) links.push({ context: linked })\n }\n return links.length ? links : undefined\n}\n\n/**\n * Translate the vendor-neutral options to OTEL's. `root: true` makes OTEL drop\n * the parent from the context it samples against, so the span starts a new trace\n * and the `ParentBasedSampler` falls through to its ratio-based root sampler.\n */\nfunction toOtelSpanOptions(options: SpanOptions): OtelSpanOptions {\n return {\n kind: options.kind ? SPAN_KIND[options.kind] : undefined,\n attributes: cleanAttributes(options.attributes),\n root: options.root,\n links: spanLinks(options.links),\n }\n}\n\nconst SEVERITY: Record<LogLevel, SeverityNumber> = {\n debug: SeverityNumber.DEBUG,\n info: SeverityNumber.INFO,\n warn: SeverityNumber.WARN,\n error: SeverityNumber.ERROR,\n}\n\n/** Adapts an OTEL span to the vendor-neutral `Span` interface. */\nclass OtelSpan implements Span {\n constructor(private readonly span: OtelApiSpan) {}\n setAttribute(key: string, value: AttributeValue): void {\n const redacted = cleanAttributes({ [key]: value })[key]\n if (redacted !== undefined) this.span.setAttribute(key, redacted)\n }\n setAttributes(attributes: Attributes): void {\n this.span.setAttributes(cleanAttributes(attributes))\n }\n updateName(name: string): void {\n this.span.updateName(name)\n }\n recordException(error: unknown): void {\n // Redact message + stack before they leave the process (Privacy): the auto\n // record-on-throw path (run-span) and reportError both pass raw errors here.\n this.span.recordException(serializeError(error))\n }\n setStatus(status: 'ok' | 'error', message?: string): void {\n this.span.setStatus({\n code: status === 'error' ? SpanStatusCode.ERROR : SpanStatusCode.OK,\n message: message ? redactPii(message) : undefined,\n })\n }\n end(): void {\n this.span.end()\n }\n}\n\n/**\n * Test seam: override the SDK's exporters/instrumentations so tests can use\n * in-memory exporters (deterministic, no network) instead of the OTLP defaults.\n * Production passes nothing \u2014 the OTLP defaults apply.\n */\nexport type OtlpProviderOptions = {\n spanProcessors?: SpanProcessor[]\n logRecordProcessors?: LogRecordProcessor[]\n metricReaders?: IMetricReader[]\n instrumentations?: Instrumentation[]\n}\n\n/**\n * PII guard (telemetry spec Privacy / R12). The single source of truth for pg\n * instrumentation config: `enhancedDatabaseReporting: false` means bound SQL\n * parameter VALUES are NOT captured \u2014 only the statement shape ($1, $2). User\n * data lives in those params, so this must never be flipped on. Asserted by a\n * regression test.\n */\nexport const PG_INSTRUMENTATION_OPTIONS = { enhancedDatabaseReporting: false } as const\n\nexport class OtlpProvider implements TelemetryProvider {\n /** The configured backend name (signoz | newrelic | otlp) \u2014 all OTLP, vendor differs only by endpoint. */\n readonly name: string\n readonly supports: readonly TelemetrySignal[] = ['traces', 'metrics', 'logs', 'errors']\n\n private sdk: NodeSDK | undefined\n private readonly instruments = new Map<string, Counter | Histogram | Gauge>()\n\n constructor(private readonly options: OtlpProviderOptions = {}, name = 'otlp') {\n this.name = name\n }\n\n async start(): Promise<void> {\n if (this.sdk) return\n const env = readTelemetryEnv()\n\n this.sdk = new NodeSDK({\n resource: resourceFromAttributes({ [ATTR_SERVICE_NAME]: env.serviceName }),\n // Global propagation roots requests by default. Both standard and backup\n // inbound headers are honored only when TELEMETRY_TRUST_INBOUND_TRACE is\n // explicitly enabled behind trusted infrastructure.\n textMapPropagator: backupHeaderPropagator,\n // Parent-based so child spans follow the trace's sampling decision; root\n // spans sample at the configured ratio.\n sampler: new ParentBasedSampler({ root: new TraceIdRatioBasedSampler(env.samplingRatio) }),\n spanProcessors: this.options.spanProcessors ?? [new BatchSpanProcessor(new OTLPTraceExporter())],\n logRecordProcessors: this.options.logRecordProcessors ?? [\n new BatchLogRecordProcessor({ exporter: new OTLPLogExporter() }),\n ],\n metricReaders: this.options.metricReaders ?? [\n new PeriodicExportingMetricReader({ exporter: new OTLPMetricExporter() }),\n ],\n instrumentations: this.options.instrumentations ?? [\n new PgInstrumentation(PG_INSTRUMENTATION_OPTIONS),\n new UndiciInstrumentation(),\n ],\n })\n this.sdk.start()\n }\n\n async shutdown(): Promise<void> {\n if (!this.sdk) return\n await this.sdk.shutdown()\n this.sdk = undefined\n }\n\n runInSpan<T>(name: string, options: SpanOptions, fn: (span: Span) => T): T {\n const tracer = trace.getTracer(TRACER_NAME)\n return tracer.startActiveSpan(name, toOtelSpanOptions(options), (otelSpan) =>\n runSpan(new OtelSpan(otelSpan), fn),\n )\n }\n\n activeSpan(): Span | undefined {\n const active = trace.getActiveSpan()\n return active ? new OtelSpan(active) : undefined\n }\n\n activeTraceContext(): TraceContext | undefined {\n const ctx = trace.getActiveSpan()?.spanContext()\n if (!ctx || !isSpanContextValid(ctx)) return undefined\n return { traceId: ctx.traceId, spanId: ctx.spanId }\n }\n\n inject(carrier: TraceCarrier): void {\n queuePropagator.inject(context.active(), carrier, defaultTextMapSetter)\n }\n\n runInRemoteSpan<T>(carrier: TraceCarrier, name: string, options: SpanOptions, fn: (span: Span) => T): T {\n const parent = queuePropagator.extract(context.active(), carrier, defaultTextMapGetter)\n const tracer = trace.getTracer(TRACER_NAME)\n return context.with(parent, () =>\n tracer.startActiveSpan(name, toOtelSpanOptions(options), (otelSpan) =>\n runSpan(new OtelSpan(otelSpan), fn),\n ),\n )\n }\n\n emitLog(record: LogRecord): void {\n const attributes: Record<string, AttributeValue> = cleanAttributes(record.attributes)\n if (record.error) {\n attributes['exception.type'] = redactPii(record.error.name)\n attributes['exception.message'] = redactPii(record.error.message)\n if (record.error.stack) attributes['exception.stacktrace'] = redactPii(record.error.stack)\n }\n logs.getLogger(TRACER_NAME).emit({\n severityNumber: SEVERITY[record.level],\n severityText: record.level,\n body: redactPii(record.message),\n attributes,\n })\n }\n\n recordMetric(point: MetricPoint): void {\n const labels = cleanAttributes(point.labels)\n const instrument = this.getInstrument(point)\n if (point.kind === 'counter') (instrument as Counter).add(point.value, labels)\n else (instrument as Histogram | Gauge).record(point.value, labels)\n }\n\n private getInstrument(point: MetricPoint): Counter | Histogram | Gauge {\n const key = `${point.kind}:${point.name}`\n let instrument = this.instruments.get(key)\n if (!instrument) {\n const meter = metrics.getMeter(TRACER_NAME)\n const opts = point.unit ? { unit: point.unit } : undefined\n instrument =\n point.kind === 'counter'\n ? meter.createCounter(point.name, opts)\n : point.kind === 'histogram'\n ? meter.createHistogram(point.name, opts)\n : meter.createGauge(point.name, opts)\n this.instruments.set(key, instrument)\n }\n return instrument\n }\n}\n"],
5
- "mappings": "AAQA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,YAAY;AAAA,OAQP;AACP,SAAS,iCAAiC;AAC1C,SAAS,MAAM,sBAAsB;AACrC,SAAS,eAAe;AAExB,SAAS,8BAA8B;AACvC,SAAS,yBAAyB;AAClC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,yBAAyB;AAClC,SAAS,uBAAuB;AAChC,SAAS,0BAA0B;AACnC,SAAS,+BAAwD;AACjE,SAAS,qCAAyD;AAClE,SAAS,yBAAyB;AAClC,SAAS,6BAA6B;AAgBtC,SAAS,wBAAwB;AACjC,SAAS,2BAA2B,gCAAgC;AACpE,SAAS,kBAAkB,iBAAiB;AAC5C,SAAS,sBAAsB;AAC/B,SAAS,eAAe;AAExB,MAAM,cAAc;AAMpB,MAAM,kBAAkB,IAAI,0BAA0B;AAEtD,MAAM,kBAAkB;AACxB,MAAM,iBAAiB;AAEvB,MAAM,qBAAqB;AAC3B,MAAM,oBAAoB;AAsB1B,MAAM,yBAA4C;AAAA,EAChD,OAAO,KAAK,SAAS,QAAQ;AAG3B,UAAM,MAA8B,CAAC;AACrC,oBAAgB,OAAO,KAAK,KAAK,oBAAoB;AACrD,eAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,GAAG,EAAG,QAAO,IAAI,SAAS,KAAK,KAAK;AAC9E,QAAI,IAA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OAAO,KAAK;AAAA,MACrC,cAAc,OAAO;AAAA,MACrB,MAAM,UAAU,OAAO,OAAO;AAAA,MAC9B;AAAA,IACF,CAAC;AAAA,EACH;AAAA,EAEA,aAAa,OAA0B;AACrC,UAAM,SAAS,gBAAgB,MAAM,MAAM;AAC3C,UAAM,aAAa,KAAK,cAAc,KAAK;AAC3C,QAAI,MAAM,SAAS,UAAW,CAAC,WAAuB,IAAI,MAAM,OAAO,MAAM;AAAA,QACxE,CAAC,WAAiC,OAAO,MAAM,OAAO,MAAM;AAAA,EACnE;AAAA,EAEQ,cAAc,OAAiD;AACrE,UAAM,MAAM,GAAG,MAAM,IAAI,IAAI,MAAM,IAAI;AACvC,QAAI,aAAa,KAAK,YAAY,IAAI,GAAG;AACzC,QAAI,CAAC,YAAY;AACf,YAAM,QAAQ,QAAQ,SAAS,WAAW;AAC1C,YAAM,OAAO,MAAM,OAAO,EAAE,MAAM,MAAM,KAAK,IAAI;AACjD,mBACE,MAAM,SAAS,YACX,MAAM,cAAc,MAAM,MAAM,IAAI,IACpC,MAAM,SAAS,cACb,MAAM,gBAAgB,MAAM,MAAM,IAAI,IACtC,MAAM,YAAY,MAAM,MAAM,IAAI;AAC1C,WAAK,YAAY,IAAI,KAAK,UAAU;AAAA,IACtC;AACA,WAAO;AAAA,EACT;AACF;",
4
+ "sourcesContent": ["/**\n * The ONLY file in this package that imports `@opentelemetry/*`. Loaded via\n * dynamic `import()` from `init.ts` (so the heavy SDK never loads when telemetry\n * is off), and the OTEL packages live in `optionalDependencies`.\n *\n * Serves any OTLP backend \u2014 the endpoint + headers come from the standard\n * `OTEL_EXPORTER_OTLP_*` env vars, read by the exporters directly.\n */\nimport {\n trace,\n metrics,\n context,\n isSpanContextValid,\n defaultTextMapGetter,\n defaultTextMapSetter,\n ROOT_CONTEXT,\n SpanStatusCode,\n SpanKind as OtelSpanKind,\n type Link,\n type Span as OtelApiSpan,\n type SpanOptions as OtelSpanOptions,\n type TextMapPropagator,\n type Counter,\n type Histogram,\n type Gauge,\n type MetricOptions,\n} from '@opentelemetry/api'\nimport { W3CTraceContextPropagator } from '@opentelemetry/core'\nimport { logs, SeverityNumber } from '@opentelemetry/api-logs'\nimport { NodeSDK } from '@opentelemetry/sdk-node'\nimport type { Instrumentation } from '@opentelemetry/instrumentation'\nimport { resourceFromAttributes } from '@opentelemetry/resources'\nimport { ATTR_SERVICE_NAME } from '@opentelemetry/semantic-conventions'\nimport {\n BatchSpanProcessor,\n ParentBasedSampler,\n TraceIdRatioBasedSampler,\n type SpanProcessor,\n} from '@opentelemetry/sdk-trace-node'\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'\nimport { OTLPLogExporter } from '@opentelemetry/exporter-logs-otlp-http'\nimport { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-http'\nimport { BatchLogRecordProcessor, type LogRecordProcessor } from '@opentelemetry/sdk-logs'\nimport { PeriodicExportingMetricReader, type IMetricReader } from '@opentelemetry/sdk-metrics'\nimport { PgInstrumentation, type PgInstrumentationConfig } from '@opentelemetry/instrumentation-pg'\nimport { UndiciInstrumentation } from '@opentelemetry/instrumentation-undici'\n\nimport { REDACTED_SQL_STATEMENT, sanitizeSqlStatement } from './sanitize-sql'\nimport type {\n Attributes,\n AttributeValue,\n LogLevel,\n LogRecord,\n MetricPoint,\n Span,\n SpanKind,\n SpanOptions,\n TelemetryProvider,\n TelemetrySignal,\n TraceCarrier,\n TraceContext,\n} from '../types'\nimport { readTelemetryEnv } from '../env'\nimport { BACKUP_TRACEPARENT_HEADER, BACKUP_TRACESTATE_HEADER } from '../trace-headers'\nimport { redactAttributes, redactPii } from '../facade/redact'\nimport { serializeError } from '../facade/serialize'\nimport { runSpan } from './run-span'\n\nconst TRACER_NAME = 'open-mercato'\n\n/**\n * Queue/event trace propagation rides a dedicated W3C propagator on the payload\n * `_trace` carrier \u2014 deliberately NOT the global propagator below.\n */\nconst queuePropagator = new W3CTraceContextPropagator()\n\nconst W3C_TRACEPARENT = 'traceparent'\nconst W3C_TRACESTATE = 'tracestate'\n// Backup headers that mirror the W3C context but a proxy/LB won't rewrite.\nconst BACKUP_TRACEPARENT = BACKUP_TRACEPARENT_HEADER\nconst BACKUP_TRACESTATE = BACKUP_TRACESTATE_HEADER\n\n/**\n * Global propagator: standard W3C plus a backup copy\n * (`x-original-traceparent`), with explicit inbound trust.\n *\n * The problem: a load balancer (e.g. GCP's) reads the inbound `traceparent`,\n * creates its own span, and **rewrites** `traceparent` to point at that span \u2014\n * which our backend never sees. With plain W3C extraction every request becomes a\n * child of that unexported span: no request is a root, and root-span / trace-group\n * views come up empty.\n *\n * The fix (the industry \"backup header\" pattern): on inject we also write\n * `x-original-traceparent`, which the LB leaves untouched. A backup header is\n * still caller-controlled at an HTTP boundary, so its mere\n * presence is not proof that one of our services created it. Extraction ignores\n * both standard and backup headers by default.\n *\n * `TELEMETRY_TRUST_INBOUND_TRACE=true` enables both extraction paths for a\n * deployment behind a trusted upstream. Our dedicated queue/event carrier is\n * unaffected \u2014 it uses `queuePropagator` directly, not this global one.\n */\nconst backupHeaderPropagator: TextMapPropagator = {\n inject(ctx, carrier, setter) {\n // Inject into a plain temp carrier so we can mirror the values regardless of\n // the real carrier's setter shape, then copy both standard + backup headers.\n const tmp: Record<string, string> = {}\n queuePropagator.inject(ctx, tmp, defaultTextMapSetter)\n for (const [key, value] of Object.entries(tmp)) setter.set(carrier, key, value)\n if (tmp[W3C_TRACEPARENT]) setter.set(carrier, BACKUP_TRACEPARENT, tmp[W3C_TRACEPARENT])\n if (tmp[W3C_TRACESTATE]) setter.set(carrier, BACKUP_TRACESTATE, tmp[W3C_TRACESTATE])\n },\n extract(ctx, carrier, getter) {\n // Both the standard and backup headers are caller-controlled at an HTTP\n // boundary. Trust neither unless the deployment explicitly opts in.\n if (!readTelemetryEnv().trustInboundTrace) return ctx\n const first = (value: string | string[] | undefined): string | undefined =>\n Array.isArray(value) ? value[0] : value\n const backupTraceparent = first(getter.get(carrier, BACKUP_TRACEPARENT))\n if (backupTraceparent) {\n const backupCarrier: Record<string, string> = { [W3C_TRACEPARENT]: backupTraceparent }\n const backupTracestate = first(getter.get(carrier, BACKUP_TRACESTATE))\n if (backupTracestate) backupCarrier[W3C_TRACESTATE] = backupTracestate\n return queuePropagator.extract(ctx, backupCarrier, defaultTextMapGetter)\n }\n return queuePropagator.extract(ctx, carrier, getter)\n },\n fields: () => [...queuePropagator.fields(), BACKUP_TRACEPARENT, BACKUP_TRACESTATE],\n}\n\nfunction cleanAttributes(attributes?: Attributes): Record<string, AttributeValue> {\n const out: Record<string, AttributeValue> = {}\n if (!attributes) return out\n for (const [key, value] of Object.entries(redactAttributes(attributes))) {\n if (value !== undefined) out[key] = value\n }\n return out\n}\n\nconst SPAN_KIND: Record<SpanKind, OtelSpanKind> = {\n internal: OtelSpanKind.INTERNAL,\n server: OtelSpanKind.SERVER,\n client: OtelSpanKind.CLIENT,\n producer: OtelSpanKind.PRODUCER,\n consumer: OtelSpanKind.CONSUMER,\n}\n\n/**\n * Resolve `links` carriers to span contexts. Extraction runs against\n * `ROOT_CONTEXT`, never the active one \u2014 otherwise an empty carrier would\n * silently link a span to its own ambient parent instead of yielding no link.\n */\nfunction spanLinks(carriers?: TraceCarrier[]): Link[] | undefined {\n if (!carriers?.length) return undefined\n const links: Link[] = []\n for (const carrier of carriers) {\n const linked = trace.getSpanContext(queuePropagator.extract(ROOT_CONTEXT, carrier, defaultTextMapGetter))\n if (linked && isSpanContextValid(linked)) links.push({ context: linked })\n }\n return links.length ? links : undefined\n}\n\n/**\n * Translate the vendor-neutral options to OTEL's. `root: true` makes OTEL drop\n * the parent from the context it samples against, so the span starts a new trace\n * and the `ParentBasedSampler` falls through to its ratio-based root sampler.\n */\nfunction toOtelSpanOptions(options: SpanOptions): OtelSpanOptions {\n return {\n kind: options.kind ? SPAN_KIND[options.kind] : undefined,\n attributes: cleanAttributes(options.attributes),\n root: options.root,\n links: spanLinks(options.links),\n }\n}\n\nconst SEVERITY: Record<LogLevel, SeverityNumber> = {\n debug: SeverityNumber.DEBUG,\n info: SeverityNumber.INFO,\n warn: SeverityNumber.WARN,\n error: SeverityNumber.ERROR,\n}\n\n/** Adapts an OTEL span to the vendor-neutral `Span` interface. */\nclass OtelSpan implements Span {\n constructor(private readonly span: OtelApiSpan) {}\n setAttribute(key: string, value: AttributeValue): void {\n const redacted = cleanAttributes({ [key]: value })[key]\n if (redacted !== undefined) this.span.setAttribute(key, redacted)\n }\n setAttributes(attributes: Attributes): void {\n this.span.setAttributes(cleanAttributes(attributes))\n }\n updateName(name: string): void {\n this.span.updateName(name)\n }\n recordException(error: unknown): void {\n // Redact message + stack before they leave the process (Privacy): the auto\n // record-on-throw path (run-span) and reportError both pass raw errors here.\n this.span.recordException(serializeError(error))\n }\n setStatus(status: 'ok' | 'error', message?: string): void {\n this.span.setStatus({\n code: status === 'error' ? SpanStatusCode.ERROR : SpanStatusCode.OK,\n message: message ? redactPii(message) : undefined,\n })\n }\n end(): void {\n this.span.end()\n }\n}\n\n/**\n * Test seam: override the SDK's exporters/instrumentations so tests can use\n * in-memory exporters (deterministic, no network) instead of the OTLP defaults.\n * Production passes nothing \u2014 the OTLP defaults apply.\n */\nexport type OtlpProviderOptions = {\n spanProcessors?: SpanProcessor[]\n logRecordProcessors?: LogRecordProcessor[]\n metricReaders?: IMetricReader[]\n instrumentations?: Instrumentation[]\n}\n\n/**\n * Statement attribute keys written by `@opentelemetry/instrumentation-pg`:\n * `db.query.text` (stable semconv, 0.73+) and `db.statement` (older releases).\n */\nexport const PG_STATEMENT_ATTRIBUTE_KEYS = ['db.query.text', 'db.statement'] as const\n\n/**\n * PII guard (telemetry spec Privacy / R12). The single source of truth for pg\n * instrumentation config. Two layers, both asserted by regression tests:\n *\n * - `enhancedDatabaseReporting: false` keeps the bound parameter VALUES array\n * off the span. This must never be flipped on.\n * - `requestHook` rewrites the statement text with every literal replaced by\n * `?`. MikroORM inlines parameters into the SQL before it reaches `pg`, so\n * without this the statement itself carries record content and ids. When the\n * text cannot be tokenized the hook fails closed with a fixed marker.\n */\nexport const PG_INSTRUMENTATION_OPTIONS = {\n enhancedDatabaseReporting: false,\n requestHook: (span, { query }) => {\n if (typeof query.text !== 'string' || query.text.length === 0) return\n const statement = sanitizeSqlStatement(query.text) ?? REDACTED_SQL_STATEMENT\n for (const key of PG_STATEMENT_ATTRIBUTE_KEYS) span.setAttribute(key, statement)\n },\n} as const satisfies PgInstrumentationConfig\n\n/**\n * Bucket boundaries for every histogram recorded in seconds. Without explicit\n * advice the SDK falls back to millisecond-scaled defaults (0, 5, 10 \u2026 10000),\n * which puts every realistic latency in the first bucket and leaves percentiles\n * uncomputable. A superset of the semconv HTTP-duration advice, plus a 1 ms\n * bucket for sub-millisecond pool acquisitions.\n */\nexport const SECONDS_HISTOGRAM_BUCKETS: readonly number[] = [\n 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,\n]\n\nfunction histogramOptions(unit: string | undefined): MetricOptions | undefined {\n if (unit !== 's') return unit ? { unit } : undefined\n return { unit, advice: { explicitBucketBoundaries: [...SECONDS_HISTOGRAM_BUCKETS] } }\n}\n\nexport class OtlpProvider implements TelemetryProvider {\n /** The configured backend name (signoz | newrelic | otlp) \u2014 all OTLP, vendor differs only by endpoint. */\n readonly name: string\n readonly supports: readonly TelemetrySignal[] = ['traces', 'metrics', 'logs', 'errors']\n\n private sdk: NodeSDK | undefined\n private readonly instruments = new Map<string, Counter | Histogram | Gauge>()\n\n constructor(private readonly options: OtlpProviderOptions = {}, name = 'otlp') {\n this.name = name\n }\n\n async start(): Promise<void> {\n if (this.sdk) return\n const env = readTelemetryEnv()\n\n this.sdk = new NodeSDK({\n resource: resourceFromAttributes({ [ATTR_SERVICE_NAME]: env.serviceName }),\n // Global propagation roots requests by default. Both standard and backup\n // inbound headers are honored only when TELEMETRY_TRUST_INBOUND_TRACE is\n // explicitly enabled behind trusted infrastructure.\n textMapPropagator: backupHeaderPropagator,\n // Parent-based so child spans follow the trace's sampling decision; root\n // spans sample at the configured ratio.\n sampler: new ParentBasedSampler({ root: new TraceIdRatioBasedSampler(env.samplingRatio) }),\n spanProcessors: this.options.spanProcessors ?? [new BatchSpanProcessor(new OTLPTraceExporter())],\n logRecordProcessors: this.options.logRecordProcessors ?? [\n new BatchLogRecordProcessor({ exporter: new OTLPLogExporter() }),\n ],\n metricReaders: this.options.metricReaders ?? [\n new PeriodicExportingMetricReader({ exporter: new OTLPMetricExporter() }),\n ],\n instrumentations: this.options.instrumentations ?? [\n new PgInstrumentation(PG_INSTRUMENTATION_OPTIONS),\n new UndiciInstrumentation(),\n ],\n })\n this.sdk.start()\n }\n\n async shutdown(): Promise<void> {\n if (!this.sdk) return\n await this.sdk.shutdown()\n this.sdk = undefined\n }\n\n runInSpan<T>(name: string, options: SpanOptions, fn: (span: Span) => T): T {\n const tracer = trace.getTracer(TRACER_NAME)\n return tracer.startActiveSpan(name, toOtelSpanOptions(options), (otelSpan) =>\n runSpan(new OtelSpan(otelSpan), fn),\n )\n }\n\n activeSpan(): Span | undefined {\n const active = trace.getActiveSpan()\n return active ? new OtelSpan(active) : undefined\n }\n\n activeTraceContext(): TraceContext | undefined {\n const ctx = trace.getActiveSpan()?.spanContext()\n if (!ctx || !isSpanContextValid(ctx)) return undefined\n return { traceId: ctx.traceId, spanId: ctx.spanId }\n }\n\n inject(carrier: TraceCarrier): void {\n queuePropagator.inject(context.active(), carrier, defaultTextMapSetter)\n }\n\n runInRemoteSpan<T>(carrier: TraceCarrier, name: string, options: SpanOptions, fn: (span: Span) => T): T {\n const parent = queuePropagator.extract(context.active(), carrier, defaultTextMapGetter)\n const tracer = trace.getTracer(TRACER_NAME)\n return context.with(parent, () =>\n tracer.startActiveSpan(name, toOtelSpanOptions(options), (otelSpan) =>\n runSpan(new OtelSpan(otelSpan), fn),\n ),\n )\n }\n\n emitLog(record: LogRecord): void {\n const attributes: Record<string, AttributeValue> = cleanAttributes(record.attributes)\n if (record.error) {\n attributes['exception.type'] = redactPii(record.error.name)\n attributes['exception.message'] = redactPii(record.error.message)\n if (record.error.stack) attributes['exception.stacktrace'] = redactPii(record.error.stack)\n }\n logs.getLogger(TRACER_NAME).emit({\n severityNumber: SEVERITY[record.level],\n severityText: record.level,\n body: redactPii(record.message),\n attributes,\n })\n }\n\n recordMetric(point: MetricPoint): void {\n const labels = cleanAttributes(point.labels)\n const instrument = this.getInstrument(point)\n if (point.kind === 'counter') (instrument as Counter).add(point.value, labels)\n else (instrument as Histogram | Gauge).record(point.value, labels)\n }\n\n private getInstrument(point: MetricPoint): Counter | Histogram | Gauge {\n const key = `${point.kind}:${point.name}`\n let instrument = this.instruments.get(key)\n if (!instrument) {\n const meter = metrics.getMeter(TRACER_NAME)\n const opts = point.unit ? { unit: point.unit } : undefined\n instrument =\n point.kind === 'counter'\n ? meter.createCounter(point.name, opts)\n : point.kind === 'histogram'\n ? meter.createHistogram(point.name, histogramOptions(point.unit))\n : meter.createGauge(point.name, opts)\n this.instruments.set(key, instrument)\n }\n return instrument\n }\n}\n"],
5
+ "mappings": "AAQA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,YAAY;AAAA,OASP;AACP,SAAS,iCAAiC;AAC1C,SAAS,MAAM,sBAAsB;AACrC,SAAS,eAAe;AAExB,SAAS,8BAA8B;AACvC,SAAS,yBAAyB;AAClC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,yBAAyB;AAClC,SAAS,uBAAuB;AAChC,SAAS,0BAA0B;AACnC,SAAS,+BAAwD;AACjE,SAAS,qCAAyD;AAClE,SAAS,yBAAuD;AAChE,SAAS,6BAA6B;AAEtC,SAAS,wBAAwB,4BAA4B;AAe7D,SAAS,wBAAwB;AACjC,SAAS,2BAA2B,gCAAgC;AACpE,SAAS,kBAAkB,iBAAiB;AAC5C,SAAS,sBAAsB;AAC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AAc,KAAK;AAC3C,QAAI,MAAM,SAAS,UAAW,CAAC,WAAuB,IAAI,MAAM,OAAO,MAAM;AAAA,QACxE,CAAC,WAAiC,OAAO,MAAM,OAAO,MAAM;AAAA,EACnE;AAAA,EAEQ,cAAc,OAAiD;AACrE,UAAM,MAAM,GAAG,MAAM,IAAI,IAAI,MAAM,IAAI;AACvC,QAAI,aAAa,KAAK,YAAY,IAAI,GAAG;AACzC,QAAI,CAAC,YAAY;AACf,YAAM,QAAQ,QAAQ,SAAS,WAAW;AAC1C,YAAM,OAAO,MAAM,OAAO,EAAE,MAAM,MAAM,KAAK,IAAI;AACjD,mBACE,MAAM,SAAS,YACX,MAAM,cAAc,MAAM,MAAM,IAAI,IACpC,MAAM,SAAS,cACb,MAAM,gBAAgB,MAAM,MAAM,iBAAiB,MAAM,IAAI,CAAC,IAC9D,MAAM,YAAY,MAAM,MAAM,IAAI;AAC1C,WAAK,YAAY,IAAI,KAAK,UAAU;AAAA,IACtC;AACA,WAAO;AAAA,EACT;AACF;",
6
6
  "names": []
7
7
  }
@@ -0,0 +1,145 @@
1
+ const REDACTED_SQL_STATEMENT = "[redacted]";
2
+ const LITERAL_PLACEHOLDER = "?";
3
+ const STRING_PREFIXES = /* @__PURE__ */ new Set(["e", "b", "x", "n"]);
4
+ const BOOLEAN_LITERALS = /* @__PURE__ */ new Set(["true", "false"]);
5
+ const NUMBER_PATTERN = /^(?:\d[\d_]*(?:\.[\d_]*)?|\.\d[\d_]*)(?:[eE][+-]?\d+)?[A-Za-z0-9_\u0080-\uFFFF]*/;
6
+ const DOLLAR_TAG_PATTERN = /^\$(?:[A-Za-z_\u0080-\uFFFF][A-Za-z0-9_\u0080-\uFFFF]*)?\$/;
7
+ const WORD_PATTERN = /^[A-Za-z_\u0080-\uFFFF][A-Za-z0-9_$\u0080-\uFFFF]*/;
8
+ const WORD_START_PATTERN = /[A-Za-z_\u0080-\uFFFF]/;
9
+ const IDENTIFIER_CHAR_PATTERN = /[A-Za-z0-9_$\u0080-\uFFFF]/;
10
+ function isIdentifierChar(char) {
11
+ return char !== void 0 && IDENTIFIER_CHAR_PATTERN.test(char);
12
+ }
13
+ function skipBlockComment(text, start) {
14
+ let depth = 0;
15
+ let index = start;
16
+ while (index < text.length) {
17
+ if (text[index] === "/" && text[index + 1] === "*") {
18
+ depth += 1;
19
+ index += 2;
20
+ continue;
21
+ }
22
+ if (text[index] === "*" && text[index + 1] === "/") {
23
+ depth -= 1;
24
+ index += 2;
25
+ if (depth === 0) return index;
26
+ continue;
27
+ }
28
+ index += 1;
29
+ }
30
+ return void 0;
31
+ }
32
+ function skipQuotedString(text, start, backslashEscapes) {
33
+ let index = start + 1;
34
+ while (index < text.length) {
35
+ const char = text[index];
36
+ if (backslashEscapes && char === "\\") {
37
+ index += 2;
38
+ continue;
39
+ }
40
+ if (char === "'") {
41
+ if (text[index + 1] === "'") {
42
+ index += 2;
43
+ continue;
44
+ }
45
+ return index + 1;
46
+ }
47
+ index += 1;
48
+ }
49
+ return void 0;
50
+ }
51
+ function skipQuotedIdentifier(text, start) {
52
+ let index = start + 1;
53
+ while (index < text.length) {
54
+ if (text[index] === '"') {
55
+ if (text[index + 1] === '"') {
56
+ index += 2;
57
+ continue;
58
+ }
59
+ return index + 1;
60
+ }
61
+ index += 1;
62
+ }
63
+ return void 0;
64
+ }
65
+ function sanitizeSqlStatement(text) {
66
+ let output = "";
67
+ let index = 0;
68
+ while (index < text.length) {
69
+ const char = text[index];
70
+ const previous = index > 0 ? text[index - 1] : void 0;
71
+ if (char === "'") {
72
+ const end = skipQuotedString(text, index, false);
73
+ if (end === void 0) return void 0;
74
+ output += LITERAL_PLACEHOLDER;
75
+ index = end;
76
+ continue;
77
+ }
78
+ if (char === '"') {
79
+ const end = skipQuotedIdentifier(text, index);
80
+ if (end === void 0) return void 0;
81
+ output += text.slice(index, end);
82
+ index = end;
83
+ continue;
84
+ }
85
+ if (char === "-" && text[index + 1] === "-") {
86
+ const newline = text.indexOf("\n", index);
87
+ index = newline === -1 ? text.length : newline;
88
+ continue;
89
+ }
90
+ if (char === "/" && text[index + 1] === "*") {
91
+ const end = skipBlockComment(text, index);
92
+ if (end === void 0) return void 0;
93
+ output += " ";
94
+ index = end;
95
+ continue;
96
+ }
97
+ if (char === "$" && !isIdentifierChar(previous)) {
98
+ const placeholder = /^\$\d+/.exec(text.slice(index));
99
+ if (placeholder) {
100
+ output += placeholder[0];
101
+ index += placeholder[0].length;
102
+ continue;
103
+ }
104
+ const tag = DOLLAR_TAG_PATTERN.exec(text.slice(index));
105
+ if (tag) {
106
+ const end = text.indexOf(tag[0], index + tag[0].length);
107
+ if (end === -1) return void 0;
108
+ output += LITERAL_PLACEHOLDER;
109
+ index = end + tag[0].length;
110
+ continue;
111
+ }
112
+ }
113
+ if (!isIdentifierChar(previous) && /[0-9.]/.test(char)) {
114
+ const number = NUMBER_PATTERN.exec(text.slice(index));
115
+ if (number) {
116
+ output += LITERAL_PLACEHOLDER;
117
+ index += number[0].length;
118
+ continue;
119
+ }
120
+ }
121
+ if (!isIdentifierChar(previous) && WORD_START_PATTERN.test(char)) {
122
+ const word = WORD_PATTERN.exec(text.slice(index))?.[0] ?? char;
123
+ const lowered = word.toLowerCase();
124
+ const afterWord = index + word.length;
125
+ if (STRING_PREFIXES.has(lowered) && text[afterWord] === "'") {
126
+ const end = skipQuotedString(text, afterWord, lowered === "e");
127
+ if (end === void 0) return void 0;
128
+ output += LITERAL_PLACEHOLDER;
129
+ index = end;
130
+ continue;
131
+ }
132
+ output += BOOLEAN_LITERALS.has(lowered) ? LITERAL_PLACEHOLDER : word;
133
+ index = afterWord;
134
+ continue;
135
+ }
136
+ output += char;
137
+ index += 1;
138
+ }
139
+ return output;
140
+ }
141
+ export {
142
+ REDACTED_SQL_STATEMENT,
143
+ sanitizeSqlStatement
144
+ };
145
+ //# sourceMappingURL=sanitize-sql.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/provider/sanitize-sql.ts"],
4
+ "sourcesContent": ["/**\n * Replaces every literal in a Postgres statement with `?` so span attributes\n * keep the query shape but never the values. MikroORM inlines bound parameters\n * into the SQL text before it reaches `pg`, so `enhancedDatabaseReporting: false`\n * alone cannot keep record content, user ids or session ids out of spans.\n *\n * Kept: keywords, `\"quoted identifiers\"`, `$1` placeholders, operators.\n * Replaced: quoted strings (including `E'\u2026'`, `B'\u2026'`, `X'\u2026'`, `N'\u2026'`),\n * dollar-quoted strings, numeric literals and `true` / `false`.\n * Dropped: comments, since they can carry arbitrary text.\n *\n * Returns `undefined` when the text cannot be tokenized (an unterminated\n * quote or comment) so the caller can fail closed instead of exporting it.\n */\nexport const REDACTED_SQL_STATEMENT = '[redacted]'\n\nconst LITERAL_PLACEHOLDER = '?'\nconst STRING_PREFIXES = new Set(['e', 'b', 'x', 'n'])\nconst BOOLEAN_LITERALS = new Set(['true', 'false'])\nconst NUMBER_PATTERN = /^(?:\\d[\\d_]*(?:\\.[\\d_]*)?|\\.\\d[\\d_]*)(?:[eE][+-]?\\d+)?[A-Za-z0-9_\\u0080-\\uFFFF]*/\nconst DOLLAR_TAG_PATTERN = /^\\$(?:[A-Za-z_\\u0080-\\uFFFF][A-Za-z0-9_\\u0080-\\uFFFF]*)?\\$/\nconst WORD_PATTERN = /^[A-Za-z_\\u0080-\\uFFFF][A-Za-z0-9_$\\u0080-\\uFFFF]*/\nconst WORD_START_PATTERN = /[A-Za-z_\\u0080-\\uFFFF]/\nconst IDENTIFIER_CHAR_PATTERN = /[A-Za-z0-9_$\\u0080-\\uFFFF]/\n\nfunction isIdentifierChar(char: string | undefined): boolean {\n return char !== undefined && IDENTIFIER_CHAR_PATTERN.test(char)\n}\n\nfunction skipBlockComment(text: string, start: number): number | undefined {\n let depth = 0\n let index = start\n while (index < text.length) {\n if (text[index] === '/' && text[index + 1] === '*') {\n depth += 1\n index += 2\n continue\n }\n if (text[index] === '*' && text[index + 1] === '/') {\n depth -= 1\n index += 2\n if (depth === 0) return index\n continue\n }\n index += 1\n }\n return undefined\n}\n\nfunction skipQuotedString(text: string, start: number, backslashEscapes: boolean): number | undefined {\n let index = start + 1\n while (index < text.length) {\n const char = text[index]\n if (backslashEscapes && char === '\\\\') {\n index += 2\n continue\n }\n if (char === \"'\") {\n if (text[index + 1] === \"'\") {\n index += 2\n continue\n }\n return index + 1\n }\n index += 1\n }\n return undefined\n}\n\nfunction skipQuotedIdentifier(text: string, start: number): number | undefined {\n let index = start + 1\n while (index < text.length) {\n if (text[index] === '\"') {\n if (text[index + 1] === '\"') {\n index += 2\n continue\n }\n return index + 1\n }\n index += 1\n }\n return undefined\n}\n\nexport function sanitizeSqlStatement(text: string): string | undefined {\n let output = ''\n let index = 0\n while (index < text.length) {\n const char = text[index]\n const previous = index > 0 ? text[index - 1] : undefined\n\n if (char === \"'\") {\n const end = skipQuotedString(text, index, false)\n if (end === undefined) return undefined\n output += LITERAL_PLACEHOLDER\n index = end\n continue\n }\n\n if (char === '\"') {\n const end = skipQuotedIdentifier(text, index)\n if (end === undefined) return undefined\n output += text.slice(index, end)\n index = end\n continue\n }\n\n if (char === '-' && text[index + 1] === '-') {\n const newline = text.indexOf('\\n', index)\n index = newline === -1 ? text.length : newline\n continue\n }\n\n if (char === '/' && text[index + 1] === '*') {\n const end = skipBlockComment(text, index)\n if (end === undefined) return undefined\n output += ' '\n index = end\n continue\n }\n\n if (char === '$' && !isIdentifierChar(previous)) {\n const placeholder = /^\\$\\d+/.exec(text.slice(index))\n if (placeholder) {\n output += placeholder[0]\n index += placeholder[0].length\n continue\n }\n const tag = DOLLAR_TAG_PATTERN.exec(text.slice(index))\n if (tag) {\n const end = text.indexOf(tag[0], index + tag[0].length)\n if (end === -1) return undefined\n output += LITERAL_PLACEHOLDER\n index = end + tag[0].length\n continue\n }\n }\n\n if (!isIdentifierChar(previous) && /[0-9.]/.test(char)) {\n const number = NUMBER_PATTERN.exec(text.slice(index))\n if (number) {\n output += LITERAL_PLACEHOLDER\n index += number[0].length\n continue\n }\n }\n\n if (!isIdentifierChar(previous) && WORD_START_PATTERN.test(char)) {\n const word = WORD_PATTERN.exec(text.slice(index))?.[0] ?? char\n const lowered = word.toLowerCase()\n const afterWord = index + word.length\n if (STRING_PREFIXES.has(lowered) && text[afterWord] === \"'\") {\n const end = skipQuotedString(text, afterWord, lowered === 'e')\n if (end === undefined) return undefined\n output += LITERAL_PLACEHOLDER\n index = end\n continue\n }\n output += BOOLEAN_LITERALS.has(lowered) ? LITERAL_PLACEHOLDER : word\n index = afterWord\n continue\n }\n\n output += char\n index += 1\n }\n return output\n}\n"],
5
+ "mappings": "AAcO,MAAM,yBAAyB;AAEtC,MAAM,sBAAsB;AAC5B,MAAM,kBAAkB,oBAAI,IAAI,CAAC,KAAK,KAAK,KAAK,GAAG,CAAC;AACpD,MAAM,mBAAmB,oBAAI,IAAI,CAAC,QAAQ,OAAO,CAAC;AAClD,MAAM,iBAAiB;AACvB,MAAM,qBAAqB;AAC3B,MAAM,eAAe;AACrB,MAAM,qBAAqB;AAC3B,MAAM,0BAA0B;AAEhC,SAAS,iBAAiB,MAAmC;AAC3D,SAAO,SAAS,UAAa,wBAAwB,KAAK,IAAI;AAChE;AAEA,SAAS,iBAAiB,MAAc,OAAmC;AACzE,MAAI,QAAQ;AACZ,MAAI,QAAQ;AACZ,SAAO,QAAQ,KAAK,QAAQ;AAC1B,QAAI,KAAK,KAAK,MAAM,OAAO,KAAK,QAAQ,CAAC,MAAM,KAAK;AAClD,eAAS;AACT,eAAS;AACT;AAAA,IACF;AACA,QAAI,KAAK,KAAK,MAAM,OAAO,KAAK,QAAQ,CAAC,MAAM,KAAK;AAClD,eAAS;AACT,eAAS;AACT,UAAI,UAAU,EAAG,QAAO;AACxB;AAAA,IACF;AACA,aAAS;AAAA,EACX;AACA,SAAO;AACT;AAEA,SAAS,iBAAiB,MAAc,OAAe,kBAA+C;AACpG,MAAI,QAAQ,QAAQ;AACpB,SAAO,QAAQ,KAAK,QAAQ;AAC1B,UAAM,OAAO,KAAK,KAAK;A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S;AAAA,EACX;AACA,SAAO;AACT;",
6
+ "names": []
7
+ }
@@ -0,0 +1,132 @@
1
+ import { monitorEventLoopDelay, performance } 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
+ const SAMPLE_INTERVAL_MS = 1e4;
10
+ const DELAY_RESOLUTION_MS = 20;
11
+ const NANOSECONDS_PER_SECOND = 1e9;
12
+ const GLOBAL_KEY = /* @__PURE__ */ Symbol.for("@open-mercato/telemetry.runtimeMetrics");
13
+ const logger = createLogger("telemetry").child({ component: "runtime-metrics" });
14
+ const defaultSources = {
15
+ createEventLoopDelayMonitor: () => monitorEventLoopDelay({ resolution: DELAY_RESOLUTION_MS }),
16
+ eventLoopUtilization: (first, second) => performance.eventLoopUtilization(first, second),
17
+ memoryUsage: () => process.memoryUsage(),
18
+ heapSpaceStatistics: () => getHeapSpaceStatistics(),
19
+ setInterval: (handler, intervalMs) => setInterval(handler, intervalMs),
20
+ clearInterval: (interval) => clearInterval(interval)
21
+ };
22
+ function store() {
23
+ const globalStore = globalThis;
24
+ let current = globalStore[GLOBAL_KEY];
25
+ if (!current) {
26
+ current = {};
27
+ globalStore[GLOBAL_KEY] = current;
28
+ }
29
+ return current;
30
+ }
31
+ function secondsFromNanoseconds(value) {
32
+ return Number.isFinite(value) ? Math.max(0, value) / NANOSECONDS_PER_SECOND : 0;
33
+ }
34
+ function createRuntimeMetricsSampler(sources = defaultSources) {
35
+ const delay = sources.createEventLoopDelayMonitor();
36
+ let previousUtilization = sources.eventLoopUtilization();
37
+ delay.enable();
38
+ const sample = () => {
39
+ try {
40
+ const currentUtilization = sources.eventLoopUtilization();
41
+ const intervalUtilization = sources.eventLoopUtilization(
42
+ currentUtilization,
43
+ previousUtilization
44
+ );
45
+ previousUtilization = currentUtilization;
46
+ recordTelemetryMetric({
47
+ kind: "gauge",
48
+ name: "nodejs.eventloop.utilization",
49
+ value: intervalUtilization.utilization,
50
+ unit: "1"
51
+ });
52
+ for (const percentile of [50, 90, 99]) {
53
+ recordTelemetryMetric({
54
+ kind: "gauge",
55
+ name: `nodejs.eventloop.delay.p${percentile}`,
56
+ value: secondsFromNanoseconds(delay.percentile(percentile)),
57
+ unit: "s"
58
+ });
59
+ }
60
+ recordTelemetryMetric({
61
+ kind: "gauge",
62
+ name: "process.memory.usage",
63
+ value: sources.memoryUsage().rss,
64
+ unit: "By"
65
+ });
66
+ for (const heapSpace of sources.heapSpaceStatistics()) {
67
+ recordTelemetryMetric({
68
+ kind: "gauge",
69
+ name: "v8js.memory.heap.used",
70
+ value: heapSpace.space_used_size,
71
+ labels: { "v8js.heap.space.name": heapSpace.space_name },
72
+ unit: "By"
73
+ });
74
+ }
75
+ collectTelemetryMetrics((err) => {
76
+ logger.warn("Runtime metric collector failed", { err });
77
+ });
78
+ } catch (err) {
79
+ try {
80
+ getTelemetryRuntime()?.reportError(err, {
81
+ module: "telemetry",
82
+ code: "telemetry.runtime_sampling_failed"
83
+ });
84
+ } catch {
85
+ }
86
+ logger.warn("Runtime metric sampling failed", { err });
87
+ } finally {
88
+ delay.reset();
89
+ }
90
+ };
91
+ const interval = sources.setInterval(sample, SAMPLE_INTERVAL_MS);
92
+ interval.unref?.();
93
+ let disposed = false;
94
+ return () => {
95
+ if (disposed) return;
96
+ disposed = true;
97
+ sources.clearInterval(interval);
98
+ delay.disable();
99
+ };
100
+ }
101
+ function startRuntimeMetrics(sources = defaultSources) {
102
+ const current = store();
103
+ if (!current.active) {
104
+ current.active = {
105
+ references: 0,
106
+ dispose: createRuntimeMetricsSampler(sources)
107
+ };
108
+ }
109
+ const active = current.active;
110
+ active.references += 1;
111
+ let released = false;
112
+ return () => {
113
+ if (released) return;
114
+ released = true;
115
+ active.references -= 1;
116
+ if (active.references > 0) return;
117
+ active.dispose();
118
+ const latest = store();
119
+ if (latest.active === active) latest.active = void 0;
120
+ };
121
+ }
122
+ function resetRuntimeMetrics() {
123
+ const current = store();
124
+ current.active?.dispose();
125
+ current.active = void 0;
126
+ }
127
+ export {
128
+ createRuntimeMetricsSampler,
129
+ resetRuntimeMetrics,
130
+ startRuntimeMetrics
131
+ };
132
+ //# sourceMappingURL=runtime-metrics.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/runtime-metrics.ts"],
4
+ "sourcesContent": ["import { monitorEventLoopDelay, performance, type EventLoopUtilization } from 'node:perf_hooks'\nimport { getHeapSpaceStatistics } from 'node:v8'\nimport {\n collectTelemetryMetrics,\n getTelemetryRuntime,\n recordTelemetryMetric,\n} from '@open-mercato/shared/lib/telemetry/runtime'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst SAMPLE_INTERVAL_MS = 10_000\nconst DELAY_RESOLUTION_MS = 20\nconst NANOSECONDS_PER_SECOND = 1_000_000_000\nconst GLOBAL_KEY = Symbol.for('@open-mercato/telemetry.runtimeMetrics')\n\nexport type EventLoopDelayMonitor = {\n enable(): void\n disable(): void\n percentile(percentile: number): number\n reset(): void\n}\n\nexport type HeapSpaceSample = {\n space_name: string\n space_used_size: number\n}\n\nexport type RuntimeMetricSources = {\n createEventLoopDelayMonitor(): EventLoopDelayMonitor\n eventLoopUtilization(\n first?: EventLoopUtilization,\n second?: EventLoopUtilization,\n ): EventLoopUtilization\n memoryUsage(): { rss: number }\n heapSpaceStatistics(): HeapSpaceSample[]\n setInterval(handler: () => void, intervalMs: number): ReturnType<typeof setInterval>\n clearInterval(interval: ReturnType<typeof setInterval>): void\n}\n\ntype ActiveRuntimeSampler = {\n references: number\n dispose(): void\n}\n\ntype RuntimeMetricsStore = {\n active?: ActiveRuntimeSampler\n}\n\nconst logger = createLogger('telemetry').child({ component: 'runtime-metrics' })\n\nconst defaultSources: RuntimeMetricSources = {\n createEventLoopDelayMonitor: () => monitorEventLoopDelay({ resolution: DELAY_RESOLUTION_MS }),\n eventLoopUtilization: (first, second) => performance.eventLoopUtilization(first, second),\n memoryUsage: () => process.memoryUsage(),\n heapSpaceStatistics: () => getHeapSpaceStatistics(),\n setInterval: (handler, intervalMs) => setInterval(handler, intervalMs),\n clearInterval: (interval) => clearInterval(interval),\n}\n\nfunction store(): RuntimeMetricsStore {\n const globalStore = globalThis as unknown as Record<symbol, RuntimeMetricsStore | undefined>\n let current = globalStore[GLOBAL_KEY]\n if (!current) {\n current = {}\n globalStore[GLOBAL_KEY] = current\n }\n return current\n}\n\nfunction secondsFromNanoseconds(value: number): number {\n return Number.isFinite(value) ? Math.max(0, value) / NANOSECONDS_PER_SECOND : 0\n}\n\nexport function createRuntimeMetricsSampler(\n sources: RuntimeMetricSources = defaultSources,\n): () => void {\n const delay = sources.createEventLoopDelayMonitor()\n let previousUtilization = sources.eventLoopUtilization()\n delay.enable()\n\n const sample = () => {\n try {\n const currentUtilization = sources.eventLoopUtilization()\n const intervalUtilization = sources.eventLoopUtilization(\n currentUtilization,\n previousUtilization,\n )\n previousUtilization = currentUtilization\n\n recordTelemetryMetric({\n kind: 'gauge',\n name: 'nodejs.eventloop.utilization',\n value: intervalUtilization.utilization,\n unit: '1',\n })\n for (const percentile of [50, 90, 99]) {\n recordTelemetryMetric({\n kind: 'gauge',\n name: `nodejs.eventloop.delay.p${percentile}`,\n value: secondsFromNanoseconds(delay.percentile(percentile)),\n unit: 's',\n })\n }\n\n recordTelemetryMetric({\n kind: 'gauge',\n name: 'process.memory.usage',\n value: sources.memoryUsage().rss,\n unit: 'By',\n })\n for (const heapSpace of sources.heapSpaceStatistics()) {\n recordTelemetryMetric({\n kind: 'gauge',\n name: 'v8js.memory.heap.used',\n value: heapSpace.space_used_size,\n labels: { 'v8js.heap.space.name': heapSpace.space_name },\n unit: 'By',\n })\n }\n\n collectTelemetryMetrics((err) => {\n logger.warn('Runtime metric collector failed', { err })\n })\n } catch (err) {\n try {\n getTelemetryRuntime()?.reportError(err, {\n module: 'telemetry',\n code: 'telemetry.runtime_sampling_failed',\n })\n } catch {}\n logger.warn('Runtime metric sampling failed', { err })\n } finally {\n delay.reset()\n }\n }\n\n const interval = sources.setInterval(sample, SAMPLE_INTERVAL_MS)\n interval.unref?.()\n\n let disposed = false\n return () => {\n if (disposed) return\n disposed = true\n sources.clearInterval(interval)\n delay.disable()\n }\n}\n\nexport function startRuntimeMetrics(\n sources: RuntimeMetricSources = defaultSources,\n): () => void {\n const current = store()\n if (!current.active) {\n current.active = {\n references: 0,\n dispose: createRuntimeMetricsSampler(sources),\n }\n }\n\n const active = current.active\n active.references += 1\n let released = false\n\n return () => {\n if (released) return\n released = true\n active.references -= 1\n if (active.references > 0) return\n active.dispose()\n const latest = store()\n if (latest.active === active) latest.active = undefined\n }\n}\n\n/** Test-only: tear down the process-wide sampler regardless of reference count. */\nexport function resetRuntimeMetrics(): void {\n const current = store()\n current.active?.dispose()\n current.active = undefined\n}\n"],
5
+ "mappings": "AAAA,SAAS,uBAAuB,mBAA8C;AAC9E,SAAS,8BAA8B;AACvC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,oBAAoB;AAE7B,MAAM,qBAAqB;AAC3B,MAAM,sBAAsB;AAC5B,MAAM,yBAAyB;AAC/B,MAAM,aAAa,uBAAO,IAAI,wCAAwC;AAmCtE,MAAM,SAAS,aAAa,WAAW,EAAE,MAAM,EAAE,WAAW,kBAAkB,CAAC;AAE/E,MAAM,iBAAuC;AAAA,EAC3C,6BAA6B,MAAM,sBAAsB,EAAE,YAAY,oBAAoB,CAAC;AAAA,EAC5F,sBAAsB,CAAC,OAAO,WAAW,YAAY,qBAAqB,OAAO,MAAM;AAAA,EACvF,aAAa,MAAM,QAAQ,YAAY;AAAA,EACvC,qBAAqB,MAAM,uBAAuB;AAAA,EAClD,aAAa,CAAC,SAAS,eAAe,YAAY,SAAS,UAAU;AAAA,EACrE,eAAe,CAAC,aAAa,cAAc,QAAQ;AACrD;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mCAAmC,EAAE,IAAI,CAAC;AAAA,MACxD,CAAC;AAAA,IACH,SAAS,KAAK;AACZ,UAAI;AACF,4BAAoB,GAAG,YAAY,KAAK;AAAA,UACtC,QAAQ;AAAA,UACR,MAAM;AAAA,QACR,CAAC;AAAA,MACH,QAAQ;AAAA,MAAC;AACT,aAAO,KAAK,kCAAkC,EAAE,IAAI,CAAC;AAAA,IACvD,UAAE;AACA,YAAM,MAAM;AAAA,IACd;AAAA,EACF;AAEA,QAAM,WAAW,QAAQ,YAAY,QAAQ,kBAAkB;AAC/D,WAAS,QAAQ;AAEjB,MAAI,WAAW;AACf,SAAO,MAAM;AACX,QAAI,SAAU;AACd,eAAW;AACX,YAAQ,cAAc,QAAQ;AAC9B,UAAM,QAAQ;AAAA,EAChB;AACF;AAEO,SAAS,oBACd,UAAgC,gBACpB;AACZ,QAAM,UAAU,MAAM;AACtB,MAAI,CAAC,QAAQ,QAAQ;AACnB,YAAQ,SAAS;AAAA,MACf,YAAY;AAAA,MACZ,SAAS,4BAA4B,OAAO;AAAA,IAC9C;AAAA,EACF;AAEA,QAAM,SAAS,QAAQ;AACvB,SAAO,cAAc;AACrB,MAAI,WAAW;AAEf,SAAO,MAAM;AACX,QAAI,SAAU;AACd,eAAW;AACX,WAAO,cAAc;AACrB,QAAI,OAAO,aAAa,EAAG;AAC3B,WAAO,QAAQ;AACf,UAAM,SAAS,MAAM;AACrB,QAAI,OAAO,WAAW,OAAQ,QAAO,SAAS;AAAA,EAChD;AACF;AAGO,SAAS,sBAA4B;AAC1C,QAAM,UAAU,MAAM;AACtB,UAAQ,QAAQ,QAAQ;AACxB,UAAQ,SAAS;AACnB;",
6
+ "names": []
7
+ }
package/jest.config.cjs CHANGED
@@ -6,6 +6,9 @@ module.exports = {
6
6
  testEnvironment: 'node',
7
7
  watchman: false,
8
8
  rootDir: '.',
9
+ moduleNameMapper: {
10
+ '^@open-mercato/shared/(.*)$': '<rootDir>/../shared/src/$1',
11
+ },
9
12
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json'],
10
13
  transform: {
11
14
  '^.+\\.(t|j)sx?$': [
@@ -20,7 +23,7 @@ module.exports = {
20
23
  ],
21
24
  },
22
25
  transformIgnorePatterns: [
23
- 'node_modules/(?!(@mikro-orm|kysely)/)',
26
+ 'node_modules/(?!(sanitize-html|htmlparser2|domhandler|domutils|dom-serializer|domelementtype|entities|@mikro-orm|kysely)/)',
24
27
  ],
25
28
  testMatch: ['<rootDir>/src/**/__tests__/**/*.test.(ts|tsx)'],
26
29
  passWithNoTests: true,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/telemetry",
3
- "version": "0.9.1-develop.7575.1.8480826a9b",
3
+ "version": "0.10.0",
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.9.1-develop.7575.1.8480826a9b"
41
+ "@open-mercato/shared": "0.10.0"
42
42
  },
43
43
  "peerDependencies": {
44
44
  "react": ">=18.0.0"
@@ -49,7 +49,7 @@
49
49
  }
50
50
  },
51
51
  "optionalDependencies": {
52
- "@opentelemetry/api": "^1.9.1",
52
+ "@opentelemetry/api": "~1.9.1",
53
53
  "@opentelemetry/api-logs": "^0.220.0",
54
54
  "@opentelemetry/core": "^2.9.0",
55
55
  "@opentelemetry/exporter-logs-otlp-http": "^0.220.0",
@@ -70,6 +70,7 @@
70
70
  "@opentelemetry/semantic-conventions": "^1.41.1"
71
71
  },
72
72
  "devDependencies": {
73
+ "@mikro-orm/postgresql": "^7.1.14",
73
74
  "@testing-library/dom": "^10.4.1",
74
75
  "@testing-library/react": "^16.3.1",
75
76
  "@types/jest": "^30.0.0",
@@ -89,6 +90,5 @@
89
90
  "type": "git",
90
91
  "url": "https://github.com/open-mercato/open-mercato",
91
92
  "directory": "packages/telemetry"
92
- },
93
- "stableVersion": "0.9.0"
93
+ }
94
94
  }
@@ -3,7 +3,7 @@ import {
3
3
  getTelemetryRuntime,
4
4
  resetTelemetryRuntime,
5
5
  } from '@open-mercato/shared/lib/telemetry/runtime'
6
- import { initTelemetry, resetTelemetryInit } from '../init'
6
+ import { initTelemetry, resetTelemetryInit, shutdownTelemetry } from '../init'
7
7
  import {
8
8
  getActiveProvider,
9
9
  registerProvider,
@@ -12,6 +12,7 @@ import {
12
12
  import { resetTelemetryEnvCache } from '../env'
13
13
  import type { TelemetryProvider } from '../types'
14
14
  import { NOOP_SPAN } from '../provider/noop-provider'
15
+ import * as errorReporting from '../facade/report-error'
15
16
 
16
17
  function provider(name = 'noop'): TelemetryProvider {
17
18
  return {
@@ -31,6 +32,7 @@ function provider(name = 'noop'): TelemetryProvider {
31
32
 
32
33
  describe('telemetry explicit opt-in boundary', () => {
33
34
  beforeEach(() => {
35
+ jest.useFakeTimers()
34
36
  delete process.env.TELEMETRY_BACKEND
35
37
  resetTelemetryEnvCache()
36
38
  resetTelemetryInit()
@@ -39,6 +41,12 @@ describe('telemetry explicit opt-in boundary', () => {
39
41
  resetTelemetryRuntime()
40
42
  })
41
43
 
44
+ afterEach(() => {
45
+ jest.restoreAllMocks()
46
+ resetTelemetryInit()
47
+ jest.useRealTimers()
48
+ })
49
+
42
50
  it('does not resolve a custom provider or register runtime hooks while off', async () => {
43
51
  const customNoop = provider()
44
52
  registerProvider(customNoop)
@@ -49,6 +57,7 @@ describe('telemetry explicit opt-in boundary', () => {
49
57
  expect(getActiveProvider().name).toBe('noop')
50
58
  expect(getLoggerExtension()).toBeUndefined()
51
59
  expect(getTelemetryRuntime()).toBeUndefined()
60
+ expect(jest.getTimerCount()).toBe(0)
52
61
  })
53
62
 
54
63
  it('can initialize after dotenv sets an enabled backend following an off call', async () => {
@@ -63,6 +72,7 @@ describe('telemetry explicit opt-in boundary', () => {
63
72
  expect(getActiveProvider()).toBe(customConsole)
64
73
  expect(getLoggerExtension()).toBeDefined()
65
74
  expect(getTelemetryRuntime()).toBeDefined()
75
+ expect(jest.getTimerCount()).toBe(1)
66
76
  })
67
77
 
68
78
  it('initializes an explicitly registered custom backend', async () => {
@@ -78,6 +88,69 @@ describe('telemetry explicit opt-in boundary', () => {
78
88
  expect(getTelemetryRuntime()).toBeDefined()
79
89
  })
80
90
 
91
+ it('shares concurrent initialization and releases the sampler on shutdown', async () => {
92
+ const customConsole = provider('console')
93
+ registerProvider(customConsole)
94
+ process.env.TELEMETRY_BACKEND = 'console'
95
+
96
+ await Promise.all([initTelemetry(), initTelemetry()])
97
+
98
+ expect(customConsole.start).toHaveBeenCalledTimes(1)
99
+ expect(jest.getTimerCount()).toBe(1)
100
+
101
+ await shutdownTelemetry()
102
+
103
+ expect(customConsole.shutdown).toHaveBeenCalledTimes(1)
104
+ expect(getTelemetryRuntime()).toBeUndefined()
105
+ expect(jest.getTimerCount()).toBe(0)
106
+ })
107
+
108
+ it.each([false, true])('reports rejected initialization during shutdown and permits recovery (reporting throws: %s)', async (reportingThrows) => {
109
+ const failure = new Error('[internal] telemetry provider startup failed')
110
+ let rejectStart!: (reason: unknown) => void
111
+ const startup = new Promise<void>((_resolve, reject) => { rejectStart = reject })
112
+ const customConsole = provider('console')
113
+ customConsole.start = jest.fn(() => startup)
114
+ registerProvider(customConsole)
115
+ process.env.TELEMETRY_BACKEND = 'console'
116
+ const reportError = jest.spyOn(errorReporting, 'reportError')
117
+ if (reportingThrows) {
118
+ reportError.mockImplementation(() => { throw new Error('[internal] reporting unavailable') })
119
+ }
120
+
121
+ const initialization = initTelemetry()
122
+ const initializationFailure = expect(initialization).rejects.toBe(failure)
123
+ const shutdown = shutdownTelemetry()
124
+ expect(customConsole.start).toHaveBeenCalledTimes(1)
125
+ expect(reportError).not.toHaveBeenCalled()
126
+
127
+ rejectStart(failure)
128
+ await initializationFailure
129
+ await expect(shutdown).resolves.toBeUndefined()
130
+
131
+ expect(reportError).toHaveBeenCalledTimes(1)
132
+ expect(reportError).toHaveBeenCalledWith(failure, {
133
+ module: 'telemetry',
134
+ code: 'telemetry.initialization_failed',
135
+ })
136
+ expect(customConsole.shutdown).not.toHaveBeenCalled()
137
+ expect(getActiveProvider().name).toBe('noop')
138
+ expect(getLoggerExtension()).toBeUndefined()
139
+ expect(getTelemetryRuntime()).toBeUndefined()
140
+ expect(jest.getTimerCount()).toBe(0)
141
+
142
+ const recoveredProvider = provider('console')
143
+ registerProvider(recoveredProvider)
144
+ await initTelemetry()
145
+ expect(recoveredProvider.start).toHaveBeenCalledTimes(1)
146
+ expect(jest.getTimerCount()).toBe(1)
147
+ await shutdownTelemetry()
148
+ expect(recoveredProvider.shutdown).toHaveBeenCalledTimes(1)
149
+ expect(getLoggerExtension()).toBeUndefined()
150
+ expect(getTelemetryRuntime()).toBeUndefined()
151
+ expect(jest.getTimerCount()).toBe(0)
152
+ })
153
+
81
154
  it('wires shared runtime histograms to the active provider', async () => {
82
155
  const customConsole = provider('console')
83
156
  registerProvider(customConsole)