@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.
- package/.turbo/turbo-build.log +1 -1
- package/AGENTS.md +8 -1
- package/README.md +51 -0
- package/dist/browser/BrowserTelemetry.js +31 -2
- package/dist/browser/BrowserTelemetry.js.map +2 -2
- package/dist/init.js +33 -0
- package/dist/init.js.map +2 -2
- package/dist/modules/telemetry/__integration__/TC-TELEMETRY-002.spec.js +4 -0
- package/dist/modules/telemetry/__integration__/TC-TELEMETRY-002.spec.js.map +2 -2
- package/dist/provider/otlp-provider.js +35 -3
- package/dist/provider/otlp-provider.js.map +2 -2
- package/dist/provider/sanitize-sql.js +145 -0
- package/dist/provider/sanitize-sql.js.map +7 -0
- package/dist/runtime-metrics.js +132 -0
- package/dist/runtime-metrics.js.map +7 -0
- package/jest.config.cjs +4 -1
- package/package.json +6 -6
- package/src/__tests__/env-load-order.test.ts +74 -1
- package/src/__tests__/otlp-integration.test.ts +34 -4
- package/src/__tests__/pg-instrumentation.test.ts +60 -25
- package/src/__tests__/runtime-metrics.test.ts +239 -0
- package/src/__tests__/sanitize-sql.test.ts +121 -0
- package/src/browser/BrowserTelemetry.tsx +34 -6
- package/src/browser/__tests__/browser-telemetry.test.tsx +1 -0
- package/src/init.ts +33 -0
- package/src/modules/telemetry/__integration__/TC-TELEMETRY-002.spec.ts +6 -0
- package/src/provider/otlp-provider.ts +42 -7
- package/src/provider/sanitize-sql.ts +168 -0
- package/src/runtime-metrics.ts +179 -0
package/.turbo/turbo-build.log
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
[build:telemetry] found
|
|
1
|
+
[build:telemetry] found 32 entry points
|
|
2
2
|
[build:telemetry] built successfully
|
package/AGENTS.md
CHANGED
|
@@ -25,7 +25,12 @@ off by default. Spec:
|
|
|
25
25
|
- Emit spans from packages that must not depend on this one via
|
|
26
26
|
`withTelemetrySpan` / `captureTelemetryTrace` from
|
|
27
27
|
`@open-mercato/shared/lib/telemetry/runtime`, never a direct import.
|
|
28
|
-
- Use semantic-convention metric/attribute names when available
|
|
28
|
+
- Use semantic-convention metric/attribute names when available, unless an
|
|
29
|
+
auto-instrumentation the OTLP provider registers already emits that name
|
|
30
|
+
(`PgInstrumentation` owns `db.client.connection.*`); use `om.*` then, since
|
|
31
|
+
two instruments must never share a name.
|
|
32
|
+
- Keep the built-in metric names, units, and fixed labels synchronized with the
|
|
33
|
+
catalog in `packages/telemetry/README.md`.
|
|
29
34
|
- Keep metric labels low-cardinality. Tenant, organization, and user IDs belong
|
|
30
35
|
on span attributes, never metric labels.
|
|
31
36
|
- Apply redaction at the provider boundary as well as at facade call sites.
|
|
@@ -106,6 +111,8 @@ host/queue shared runtime bridge ── absent while off
|
|
|
106
111
|
- `src/provider/*`: noop/console/OTLP providers and global provider registry.
|
|
107
112
|
- `src/init.ts`: explicit-enabled initialization and process-wide bridge
|
|
108
113
|
registration.
|
|
114
|
+
- `src/runtime-metrics.ts`: enabled-only process sampler and the single
|
|
115
|
+
interval that invokes shared periodic metric collectors.
|
|
109
116
|
- `src/nextjs-config.ts`: build-time constants only; no runtime imports.
|
|
110
117
|
- `src/nextjs.ts`: enabled runtime helper.
|
|
111
118
|
- `src/browser/*`: browser RUM. `config.ts` (shared, env-free contract) and
|
package/README.md
CHANGED
|
@@ -285,6 +285,50 @@ implementation, where you can decide what a dropped report means.
|
|
|
285
285
|
`attributes`, so putting it in both `tags` and `extra`, as the snippet above does
|
|
286
286
|
with `tags`, is your choice rather than an accident of the payload.
|
|
287
287
|
|
|
288
|
+
### Built-in runtime metrics
|
|
289
|
+
|
|
290
|
+
An active provider starts one process-wide 10-second sampler. Disabled/noop
|
|
291
|
+
telemetry starts no interval or event-loop monitor. The sampler also invokes
|
|
292
|
+
shared metric collectors, which lets the primary PostgreSQL pool report state
|
|
293
|
+
without making `@open-mercato/shared` depend on this package.
|
|
294
|
+
|
|
295
|
+
| Metric | Kind | Unit | Labels |
|
|
296
|
+
| --- | --- | --- | --- |
|
|
297
|
+
| `om.db.pool.connections` | gauge | `{connection}` | `pool=primary`, `state=idle\|used` |
|
|
298
|
+
| `om.db.pool.pending_requests` | gauge | `{request}` | `pool=primary` |
|
|
299
|
+
| `om.db.pool.max` | gauge | `{connection}` | `pool=primary` |
|
|
300
|
+
| `om.db.pool.wait_time` | histogram | `s` | `pool=primary` |
|
|
301
|
+
| `nodejs.eventloop.utilization` | gauge | `1` | none |
|
|
302
|
+
| `nodejs.eventloop.delay.p50` / `p90` / `p99` | gauge | `s` | none |
|
|
303
|
+
| `process.memory.usage` | gauge | `By` | none |
|
|
304
|
+
| `v8js.memory.heap.used` | gauge | `By` | `v8js.heap.space.name` |
|
|
305
|
+
|
|
306
|
+
Pool acquisition wait is recorded per `pool.connect` call, including failed
|
|
307
|
+
promise and callback acquisitions, and includes opening a new connection when
|
|
308
|
+
the pool grows. Connection-state values are sampled; sum `idle` and `used` for
|
|
309
|
+
the current open-connection total.
|
|
310
|
+
|
|
311
|
+
The pool metrics use the `om.db.pool.*` namespace on purpose. Under an OTLP
|
|
312
|
+
backend `@opentelemetry/instrumentation-pg` already emits the semantic-convention
|
|
313
|
+
`db.client.connection.count` and `db.client.connection.pending_requests` as
|
|
314
|
+
UpDownCounters labelled `db.client.connection.state` /
|
|
315
|
+
`db.client.connection.pool.name`. Reusing those names would export two streams
|
|
316
|
+
per name with conflicting types and label keys. Query `om.db.pool.*` for the
|
|
317
|
+
sampled view, which is also available under the `console` backend.
|
|
318
|
+
|
|
319
|
+
The event-loop delay percentiles come from `monitorEventLoopDelay` with a 20 ms
|
|
320
|
+
resolution, which records the whole timer interval rather than the overshoot.
|
|
321
|
+
An idle process therefore reports about 0.020 s, not 0. Subtract 0.020 s before
|
|
322
|
+
you compare against a real-delay budget: an alert at 0.050 s fires at about
|
|
323
|
+
30 ms of actual blocking.
|
|
324
|
+
|
|
325
|
+
Under an OTLP backend, every histogram recorded in seconds
|
|
326
|
+
(`om.db.pool.wait_time`, `http.server.request.duration`,
|
|
327
|
+
`om.enricher.duration`) is exported with explicit boundaries of 1 ms, 5 ms, 10 ms, 25 ms, 50 ms, 75 ms, 100 ms, 250 ms,
|
|
328
|
+
500 ms, 750 ms, 1 s, 2.5 s, 5 s, 7.5 s and 10 s, so backends can compute
|
|
329
|
+
percentiles. The SDK default is millisecond-scaled and would put every
|
|
330
|
+
realistic latency in its first bucket.
|
|
331
|
+
|
|
288
332
|
### Long-lived jobs: root spans
|
|
289
333
|
|
|
290
334
|
Trace context propagates from the request that triggered a job through the queue
|
|
@@ -355,6 +399,13 @@ consumer.
|
|
|
355
399
|
fields, span attributes, and metric labels.
|
|
356
400
|
- Postgres parameter-value capture is locked off with
|
|
357
401
|
`enhancedDatabaseReporting: false`.
|
|
402
|
+
- Postgres statement text (`db.query.text` / `db.statement`) keeps the query
|
|
403
|
+
shape only. MikroORM inlines parameter values into the SQL before it reaches
|
|
404
|
+
`pg`, so a pg `requestHook` replaces every string, numeric and boolean
|
|
405
|
+
literal with `?` and drops comments. A statement that cannot be tokenized is
|
|
406
|
+
exported as `[redacted]` rather than as-is.
|
|
407
|
+
- Not yet covered: the error message of a failed query (span status and
|
|
408
|
+
exception event) can still quote a value, e.g. a duplicate-key detail.
|
|
358
409
|
- Metric labels must remain low-cardinality and must never contain tenant,
|
|
359
410
|
organization, or user IDs.
|
|
360
411
|
|
|
@@ -1,8 +1,15 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import * as React from "react";
|
|
3
|
+
import { registerTelemetryErrorReporter } from "@open-mercato/shared/lib/telemetry/runtime";
|
|
4
|
+
import { groupableCode } from "@open-mercato/shared/lib/telemetry/error-code";
|
|
5
|
+
import { serializeError } from "../facade/serialize.js";
|
|
6
|
+
import { redactAttributes } from "../facade/redact.js";
|
|
3
7
|
import { createBackupHeaderPropagator } from "./propagator.js";
|
|
4
8
|
let bootstrapped = false;
|
|
9
|
+
let disposeErrorReporter;
|
|
5
10
|
function resetBrowserTelemetryBootstrap() {
|
|
11
|
+
disposeErrorReporter?.();
|
|
12
|
+
disposeErrorReporter = void 0;
|
|
6
13
|
bootstrapped = false;
|
|
7
14
|
}
|
|
8
15
|
async function startBrowserTelemetry(config) {
|
|
@@ -15,7 +22,7 @@ async function startBrowserTelemetry(config) {
|
|
|
15
22
|
{ DocumentLoadInstrumentation },
|
|
16
23
|
{ FetchInstrumentation },
|
|
17
24
|
{ W3CTraceContextPropagator },
|
|
18
|
-
{ defaultTextMapSetter }
|
|
25
|
+
{ defaultTextMapSetter, SpanStatusCode }
|
|
19
26
|
] = await Promise.all([
|
|
20
27
|
import("@opentelemetry/sdk-trace-web"),
|
|
21
28
|
import("@opentelemetry/sdk-trace-base"),
|
|
@@ -90,6 +97,21 @@ async function startBrowserTelemetry(config) {
|
|
|
90
97
|
if (document.visibilityState === "hidden") flush();
|
|
91
98
|
});
|
|
92
99
|
window.addEventListener("pagehide", flush);
|
|
100
|
+
const tracer = provider.getTracer("@open-mercato/telemetry/browser");
|
|
101
|
+
return (error, context) => {
|
|
102
|
+
const serialized = serializeError(error);
|
|
103
|
+
const attributes = redactAttributes({ ...context?.attributes, module: context?.module });
|
|
104
|
+
delete attributes["error.code"];
|
|
105
|
+
const code = groupableCode(context?.code);
|
|
106
|
+
if (code) attributes["error.code"] = code;
|
|
107
|
+
const span = tracer.startSpan("browser.error", { attributes });
|
|
108
|
+
try {
|
|
109
|
+
span.recordException(serialized);
|
|
110
|
+
span.setStatus({ code: SpanStatusCode.ERROR });
|
|
111
|
+
} finally {
|
|
112
|
+
span.end();
|
|
113
|
+
}
|
|
114
|
+
};
|
|
93
115
|
}
|
|
94
116
|
function escapeRegExp(value) {
|
|
95
117
|
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
@@ -98,7 +120,14 @@ function BrowserTelemetry({ config }) {
|
|
|
98
120
|
React.useEffect(() => {
|
|
99
121
|
if (!config || bootstrapped) return;
|
|
100
122
|
bootstrapped = true;
|
|
101
|
-
|
|
123
|
+
const reporter = startBrowserTelemetry(config);
|
|
124
|
+
const dispose = registerTelemetryErrorReporter((...args) => {
|
|
125
|
+
void reporter.then((reportError) => reportError(...args)).catch(() => {
|
|
126
|
+
});
|
|
127
|
+
});
|
|
128
|
+
disposeErrorReporter = dispose;
|
|
129
|
+
void reporter.catch(() => {
|
|
130
|
+
dispose();
|
|
102
131
|
});
|
|
103
132
|
}, [config]);
|
|
104
133
|
return null;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/browser/BrowserTelemetry.tsx"],
|
|
4
|
-
"sourcesContent": ["'use client'\n\n/**\n * Browser RUM. Boots the OpenTelemetry web SDK once per page load and exports\n * spans through the same-origin proxy (`/api/telemetry/browser-traces`).\n *\n * Why this exists: server traces can only prove where the time *isn't*. A page\n * can render an API answer in 50 ms yet leave the user waiting seconds before\n * the request is even sent \u2014 bundle download, hydration, or a click handler\n * stuck behind a re-render are all invisible to every server span.\n *\n * Two rules this file lives by:\n * - **The SDK is `import()`ed, never statically imported.** RUM often\n * diagnoses routes suspected to be bundle-bound; shipping the SDK in the\n * critical path would be self-defeating. Document-load timings survive the\n * late start because they are read back from the PerformanceTimeline.\n * - **It can never break the app.** Every failure is swallowed. No\n * user-facing surface, no retry.\n *\n * This file, `config.ts`, and `propagator.ts` are the only parts of\n * `@open-mercato/telemetry` a client bundle may reach (via the `/browser` entry).\n * None of them may import the server facade (`node:async_hooks`) or the\n * env-reading `browser/server.ts`; the two wirings are independent and meet only\n * at the collector.\n */\n\nimport * as React from 'react'\nimport type { BrowserTelemetryConfig } from './config'\nimport { createBackupHeaderPropagator } from './propagator'\n\n/** Module-level so React StrictMode's double-invoke (and any remount) cannot start a second SDK. */\nlet bootstrapped = false\n\n/**\n * Test seam. Production has exactly one bootstrap per page load, so nothing else\n * may call this \u2014 a second bootstrap would double every span.\n */\nexport function resetBrowserTelemetryBootstrap(): void {\n bootstrapped = false\n}\n\nasync function startBrowserTelemetry(config: BrowserTelemetryConfig): Promise<void> {\n const [\n { WebTracerProvider },\n { BatchSpanProcessor, ParentBasedSampler, TraceIdRatioBasedSampler },\n { OTLPTraceExporter },\n { resourceFromAttributes },\n { registerInstrumentations },\n { DocumentLoadInstrumentation },\n { FetchInstrumentation },\n { W3CTraceContextPropagator },\n { defaultTextMapSetter },\n ] = await Promise.all([\n import('@opentelemetry/sdk-trace-web'),\n import('@opentelemetry/sdk-trace-base'),\n import('@opentelemetry/exporter-trace-otlp-http'),\n import('@opentelemetry/resources'),\n import('@opentelemetry/instrumentation'),\n import('@opentelemetry/instrumentation-document-load'),\n import('@opentelemetry/instrumentation-fetch'),\n import('@opentelemetry/core'),\n import('@opentelemetry/api'),\n ])\n\n const provider = new WebTracerProvider({\n resource: resourceFromAttributes({\n 'service.name': config.serviceName,\n // Plain attribute name (not the semconv `deployment.environment.name`) so browser spans sort\n // alongside the server spans, which use OTEL_RESOURCE_ATTRIBUTES.\n ...(config.environment ? { 'deployment.environment': config.environment } : {}),\n 'user_agent.original': navigator.userAgent,\n }),\n sampler: new ParentBasedSampler({\n root: new TraceIdRatioBasedSampler(config.samplingRatio),\n }),\n spanProcessors: [\n new BatchSpanProcessor(\n new OTLPTraceExporter({ url: config.endpoint }),\n // The interesting spans arrive in bursts around a navigation; a short delay keeps them\n // close together in the trace view without one request per span.\n { scheduledDelayMillis: 3_000, maxQueueSize: 512 },\n ),\n ],\n })\n\n // Standard `traceparent` plus the backup copy the server continues once\n // TELEMETRY_TRUST_INBOUND_TRACE is on \u2014 see `propagator.ts` for why that flag is the supported\n // way to get one end-to-end trace, and what happens without it.\n provider.register({\n propagator: createBackupHeaderPropagator(new W3CTraceContextPropagator(), defaultTextMapSetter),\n })\n\n // \u2500\u2500 The fetch-patch dance (do not simplify) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // `@open-mercato/ui`'s api utils install a global wrapper at module load so that stray\n // `fetch()` calls still get the 401 session-refresh / 403 banner behaviour:\n // w.__omOriginalFetch = window.fetch // pristine native fetch\n // window.fetch = (i, x) => apiFetch(i, x)\n // and `apiFetch` then calls `__omOriginalFetch` to avoid recursing into itself. Since the whole\n // backoffice (DataTable, CrudForm, react-query queryFns\u2026) imports `apiFetch` DIRECTLY, those\n // calls never touch `window.fetch` \u2014 so instrumenting `window.fetch` alone yields document-load\n // spans and almost no API spans, which is worse than none at all: it looks like it works.\n //\n // Fix: let the instrumentation patch the *native* fetch, then hand the patched version back as\n // the stash. Both paths end up instrumented exactly once:\n // apiFetch \u2192 __omOriginalFetch = OTel(native) \u2713\n // window.fetch \u2192 apiFetch wrapper \u2192 OTel(native) \u2713\n // Assigning `__omOriginalFetch = window.fetch` instead would loop forever\n // (apiFetch \u2192 wrapper \u2192 apiFetch \u2192 \u2026). The swap is synchronous \u2014 `registerInstrumentations`\n // calls `enable()` inline \u2014 so no caller can observe the intermediate state.\n const patchTarget = window as Window & { __omOriginalFetch?: typeof window.fetch }\n const frameworkFetch = patchTarget.__omOriginalFetch ? window.fetch : null\n if (frameworkFetch && patchTarget.__omOriginalFetch) {\n window.fetch = patchTarget.__omOriginalFetch\n }\n\n // `finally`, not a plain sequence: the instrumentation constructors below are evaluated inside\n // this window, and a throw from any of them (SDK version skew, a browser missing an API an\n // instrumentation touches) would otherwise leave `window.fetch` as the raw native fetch stashed\n // above. `apiFetch` would keep working \u2014 it reads `__omOriginalFetch` \u2014 but every stray\n // `window.fetch(...)` would silently bypass the framework wrapper's 401 session-refresh and 403\n // banner behaviour for the rest of the page's life. This is the one path where the file's\n // \"every failure is swallowed\" rule would leave global state degraded.\n try {\n registerInstrumentations({\n tracerProvider: provider,\n instrumentations: [\n // Navigation + resource timings: chunk download vs. parse vs. hydrate.\n new DocumentLoadInstrumentation(),\n // The client-side START of each API call \u2014 the number the server can never see.\n new FetchInstrumentation({\n // Never instrument our own export, or each batch would generate the next one.\n ignoreUrls: [new RegExp(escapeRegExp(config.endpoint))],\n clearTimingResources: true,\n }),\n // No `UserInteractionInstrumentation` here, deliberately. It works by patching\n // `addEventListener` when `enable()` runs, but React attaches a SINGLE delegated `click`\n // listener to the root container during `createRoot`/hydration \u2014 and this SDK boots from\n // `useEffect`, which React runs strictly after hydration. The patch would land after the\n // only listener that will ever see a backoffice click, so it produces no spans at all\n // (confirmed in manual QA). Booting early enough to beat hydration would mean putting the\n // SDK back on the critical path, which is the one thing this file refuses to do. An\n // instrumentation that silently produces nothing is worse than an absent one: an empty\n // interaction view reads as \"nobody clicks\" rather than \"this is broken\".\n ],\n })\n } finally {\n if (frameworkFetch) {\n // On the success path `window.fetch` is OTel's patched native fetch; on the throw path it is\n // the pristine native one. Either way this restores the framework wrapper on top of whatever\n // the stash should now hold, so the pre-swap contract holds in both.\n patchTarget.__omOriginalFetch = window.fetch\n window.fetch = frameworkFetch\n }\n }\n\n // BatchSpanProcessor would otherwise drop whatever is still queued when the user navigates away\n // \u2014 which is exactly when a slow page gets abandoned, i.e. the spans we most want.\n //\n // `forceFlush` exports through the OTLP fetch transport, which sets `keepalive: true` on the\n // request whenever the payload and the number of in-flight requests are within the browser's\n // limits \u2014 so the batch survives the page going away. That is the durable path here;\n // `sendBeacon` would be the other candidate, but upstream deprecated its export delegate in\n // favour of the fetch one, so reaching for it would trade a supported API for a doomed one.\n //\n // Both events, because neither alone covers every exit: `visibilitychange` misses some bfcache\n // entries, and `pagehide` does not fire when a tab is merely backgrounded. A second flush with\n // an empty queue is a no-op, so the overlap costs nothing.\n const flush = () => void provider.forceFlush().catch(() => {})\n document.addEventListener('visibilitychange', () => {\n if (document.visibilityState === 'hidden') flush()\n })\n window.addEventListener('pagehide', flush)\n}\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\n/**\n * Renders nothing. `config` is resolved server-side (`resolveBrowserTelemetryConfig()`) and is\n * `null` whenever browser telemetry is disabled for the environment \u2014 which is the default, and\n * keeps the SDK chunk from ever being requested.\n */\nexport function BrowserTelemetry({ config }: { config: BrowserTelemetryConfig | null }) {\n React.useEffect(() => {\n if (!config || bootstrapped) return\n bootstrapped = true\n void startBrowserTelemetry(config).catch(() => {\n // Telemetry must never degrade the app it measures: stay silent and stay down (no retry).\n })\n }, [config])\n\n return null\n}\n"],
|
|
5
|
-
"mappings": ";
|
|
4
|
+
"sourcesContent": ["'use client'\n\n/**\n * Browser RUM. Boots the OpenTelemetry web SDK once per page load and exports\n * spans through the same-origin proxy (`/api/telemetry/browser-traces`).\n *\n * Why this exists: server traces can only prove where the time *isn't*. A page\n * can render an API answer in 50 ms yet leave the user waiting seconds before\n * the request is even sent \u2014 bundle download, hydration, or a click handler\n * stuck behind a re-render are all invisible to every server span.\n *\n * Two rules this file lives by:\n * - **The SDK is `import()`ed, never statically imported.** RUM often\n * diagnoses routes suspected to be bundle-bound; shipping the SDK in the\n * critical path would be self-defeating. Document-load timings survive the\n * late start because they are read back from the PerformanceTimeline.\n * - **It can never break the app.** Every failure is swallowed. No\n * user-facing surface, no retry.\n *\n * The `/browser` entry and its pure serialization/redaction helpers must not\n * import the server facade (`node:async_hooks`) or the\n * env-reading `browser/server.ts`; the two wirings are independent and meet only\n * at the collector.\n */\n\nimport * as React from 'react'\nimport { registerTelemetryErrorReporter, type TelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'\nimport { groupableCode } from '@open-mercato/shared/lib/telemetry/error-code'\nimport { serializeError } from '../facade/serialize'\nimport { redactAttributes } from '../facade/redact'\nimport type { BrowserTelemetryConfig } from './config'\nimport { createBackupHeaderPropagator } from './propagator'\n\n/** Module-level so React StrictMode's double-invoke (and any remount) cannot start a second SDK. */\nlet bootstrapped = false\nlet disposeErrorReporter: (() => void) | undefined\n\n/**\n * Test seam. Production has exactly one bootstrap per page load, so nothing else\n * may call this \u2014 a second bootstrap would double every span.\n */\nexport function resetBrowserTelemetryBootstrap(): void {\n disposeErrorReporter?.()\n disposeErrorReporter = undefined\n bootstrapped = false\n}\n\nasync function startBrowserTelemetry(config: BrowserTelemetryConfig): Promise<TelemetryRuntime['reportError']> {\n const [\n { WebTracerProvider },\n { BatchSpanProcessor, ParentBasedSampler, TraceIdRatioBasedSampler },\n { OTLPTraceExporter },\n { resourceFromAttributes },\n { registerInstrumentations },\n { DocumentLoadInstrumentation },\n { FetchInstrumentation },\n { W3CTraceContextPropagator },\n { defaultTextMapSetter, SpanStatusCode },\n ] = await Promise.all([\n import('@opentelemetry/sdk-trace-web'),\n import('@opentelemetry/sdk-trace-base'),\n import('@opentelemetry/exporter-trace-otlp-http'),\n import('@opentelemetry/resources'),\n import('@opentelemetry/instrumentation'),\n import('@opentelemetry/instrumentation-document-load'),\n import('@opentelemetry/instrumentation-fetch'),\n import('@opentelemetry/core'),\n import('@opentelemetry/api'),\n ])\n\n const provider = new WebTracerProvider({\n resource: resourceFromAttributes({\n 'service.name': config.serviceName,\n // Plain attribute name (not the semconv `deployment.environment.name`) so browser spans sort\n // alongside the server spans, which use OTEL_RESOURCE_ATTRIBUTES.\n ...(config.environment ? { 'deployment.environment': config.environment } : {}),\n 'user_agent.original': navigator.userAgent,\n }),\n sampler: new ParentBasedSampler({\n root: new TraceIdRatioBasedSampler(config.samplingRatio),\n }),\n spanProcessors: [\n new BatchSpanProcessor(\n new OTLPTraceExporter({ url: config.endpoint }),\n // The interesting spans arrive in bursts around a navigation; a short delay keeps them\n // close together in the trace view without one request per span.\n { scheduledDelayMillis: 3_000, maxQueueSize: 512 },\n ),\n ],\n })\n\n // Standard `traceparent` plus the backup copy the server continues once\n // TELEMETRY_TRUST_INBOUND_TRACE is on \u2014 see `propagator.ts` for why that flag is the supported\n // way to get one end-to-end trace, and what happens without it.\n provider.register({\n propagator: createBackupHeaderPropagator(new W3CTraceContextPropagator(), defaultTextMapSetter),\n })\n\n // \u2500\u2500 The fetch-patch dance (do not simplify) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n // `@open-mercato/ui`'s api utils install a global wrapper at module load so that stray\n // `fetch()` calls still get the 401 session-refresh / 403 banner behaviour:\n // w.__omOriginalFetch = window.fetch // pristine native fetch\n // window.fetch = (i, x) => apiFetch(i, x)\n // and `apiFetch` then calls `__omOriginalFetch` to avoid recursing into itself. Since the whole\n // backoffice (DataTable, CrudForm, react-query queryFns\u2026) imports `apiFetch` DIRECTLY, those\n // calls never touch `window.fetch` \u2014 so instrumenting `window.fetch` alone yields document-load\n // spans and almost no API spans, which is worse than none at all: it looks like it works.\n //\n // Fix: let the instrumentation patch the *native* fetch, then hand the patched version back as\n // the stash. Both paths end up instrumented exactly once:\n // apiFetch \u2192 __omOriginalFetch = OTel(native) \u2713\n // window.fetch \u2192 apiFetch wrapper \u2192 OTel(native) \u2713\n // Assigning `__omOriginalFetch = window.fetch` instead would loop forever\n // (apiFetch \u2192 wrapper \u2192 apiFetch \u2192 \u2026). The swap is synchronous \u2014 `registerInstrumentations`\n // calls `enable()` inline \u2014 so no caller can observe the intermediate state.\n const patchTarget = window as Window & { __omOriginalFetch?: typeof window.fetch }\n const frameworkFetch = patchTarget.__omOriginalFetch ? window.fetch : null\n if (frameworkFetch && patchTarget.__omOriginalFetch) {\n window.fetch = patchTarget.__omOriginalFetch\n }\n\n // `finally`, not a plain sequence: the instrumentation constructors below are evaluated inside\n // this window, and a throw from any of them (SDK version skew, a browser missing an API an\n // instrumentation touches) would otherwise leave `window.fetch` as the raw native fetch stashed\n // above. `apiFetch` would keep working \u2014 it reads `__omOriginalFetch` \u2014 but every stray\n // `window.fetch(...)` would silently bypass the framework wrapper's 401 session-refresh and 403\n // banner behaviour for the rest of the page's life. This is the one path where the file's\n // \"every failure is swallowed\" rule would leave global state degraded.\n try {\n registerInstrumentations({\n tracerProvider: provider,\n instrumentations: [\n // Navigation + resource timings: chunk download vs. parse vs. hydrate.\n new DocumentLoadInstrumentation(),\n // The client-side START of each API call \u2014 the number the server can never see.\n new FetchInstrumentation({\n // Never instrument our own export, or each batch would generate the next one.\n ignoreUrls: [new RegExp(escapeRegExp(config.endpoint))],\n clearTimingResources: true,\n }),\n // No `UserInteractionInstrumentation` here, deliberately. It works by patching\n // `addEventListener` when `enable()` runs, but React attaches a SINGLE delegated `click`\n // listener to the root container during `createRoot`/hydration \u2014 and this SDK boots from\n // `useEffect`, which React runs strictly after hydration. The patch would land after the\n // only listener that will ever see a backoffice click, so it produces no spans at all\n // (confirmed in manual QA). Booting early enough to beat hydration would mean putting the\n // SDK back on the critical path, which is the one thing this file refuses to do. An\n // instrumentation that silently produces nothing is worse than an absent one: an empty\n // interaction view reads as \"nobody clicks\" rather than \"this is broken\".\n ],\n })\n } finally {\n if (frameworkFetch) {\n // On the success path `window.fetch` is OTel's patched native fetch; on the throw path it is\n // the pristine native one. Either way this restores the framework wrapper on top of whatever\n // the stash should now hold, so the pre-swap contract holds in both.\n patchTarget.__omOriginalFetch = window.fetch\n window.fetch = frameworkFetch\n }\n }\n\n // BatchSpanProcessor would otherwise drop whatever is still queued when the user navigates away\n // \u2014 which is exactly when a slow page gets abandoned, i.e. the spans we most want.\n //\n // `forceFlush` exports through the OTLP fetch transport, which sets `keepalive: true` on the\n // request whenever the payload and the number of in-flight requests are within the browser's\n // limits \u2014 so the batch survives the page going away. That is the durable path here;\n // `sendBeacon` would be the other candidate, but upstream deprecated its export delegate in\n // favour of the fetch one, so reaching for it would trade a supported API for a doomed one.\n //\n // Both events, because neither alone covers every exit: `visibilitychange` misses some bfcache\n // entries, and `pagehide` does not fire when a tab is merely backgrounded. A second flush with\n // an empty queue is a no-op, so the overlap costs nothing.\n const flush = () => void provider.forceFlush().catch(() => {})\n document.addEventListener('visibilitychange', () => {\n if (document.visibilityState === 'hidden') flush()\n })\n window.addEventListener('pagehide', flush)\n\n const tracer = provider.getTracer('@open-mercato/telemetry/browser')\n return (error, context) => {\n const serialized = serializeError(error)\n const attributes = redactAttributes({ ...context?.attributes, module: context?.module })\n delete attributes['error.code']\n const code = groupableCode(context?.code)\n if (code) attributes['error.code'] = code\n const span = tracer.startSpan('browser.error', { attributes })\n try {\n span.recordException(serialized)\n span.setStatus({ code: SpanStatusCode.ERROR })\n } finally {\n span.end()\n }\n }\n}\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\n/**\n * Renders nothing. `config` is resolved server-side (`resolveBrowserTelemetryConfig()`) and is\n * `null` whenever browser telemetry is disabled for the environment \u2014 which is the default, and\n * keeps the SDK chunk from ever being requested.\n */\nexport function BrowserTelemetry({ config }: { config: BrowserTelemetryConfig | null }) {\n React.useEffect(() => {\n if (!config || bootstrapped) return\n bootstrapped = true\n const reporter = startBrowserTelemetry(config)\n const dispose = registerTelemetryErrorReporter((...args) => {\n void reporter.then((reportError) => reportError(...args)).catch(() => {})\n })\n disposeErrorReporter = dispose\n void reporter.catch(() => {\n dispose()\n // Telemetry must never degrade the app it measures: stay silent and stay down (no retry).\n })\n }, [config])\n\n return null\n}\n"],
|
|
5
|
+
"mappings": ";AAyBA,YAAY,WAAW;AACvB,SAAS,sCAA6D;AACtE,SAAS,qBAAqB;AAC9B,SAAS,sBAAsB;AAC/B,SAAS,wBAAwB;AAEjC,SAAS,oCAAoC;AAG7C,IAAI,eAAe;AACnB,IAAI;AAMG,SAAS,iCAAuC;AACrD,yBAAuB;AACvB,yBAAuB;AACvB,iBAAe;AACjB;AAEA,eAAe,sBAAsB,Q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AO,MAAM,QAAQ,uBAAuB,MAAM;AACpD;AAOO,SAAS,iBAAiB,EAAE,OAAO,GAA8C;AACtF,QAAM,UAAU,MAAM;AACpB,QAAI,CAAC,UAAU,aAAc;AAC7B,mBAAe;AACf,UAAM,WAAW,sBAAsB,MAAM;AAC7C,UAAM,UAAU,+BAA+B,IAAI,SAAS;AAC1D,WAAK,SAAS,KAAK,CAAC,gBAAgB,YAAY,GAAG,IAAI,CAAC,EAAE,MAAM,MAAM;AAAA,MAAC,CAAC;AAAA,IAC1E,CAAC;AACD,2BAAuB;AACvB,SAAK,SAAS,MAAM,MAAM;AACxB,cAAQ;AAAA,IAEV,CAAC;AAAA,EACH,GAAG,CAAC,MAAM,CAAC;AAEX,SAAO;AACT;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/init.js
CHANGED
|
@@ -15,10 +15,13 @@ import { withSpan } from "./facade/tracer.js";
|
|
|
15
15
|
import { recordHttpDuration } from "./facade/http.js";
|
|
16
16
|
import { histogram } from "./facade/meter.js";
|
|
17
17
|
import { reportError } from "./facade/report-error.js";
|
|
18
|
+
import { startRuntimeMetrics } from "./runtime-metrics.js";
|
|
18
19
|
let initialized = false;
|
|
20
|
+
let initializing;
|
|
19
21
|
let activeProvider;
|
|
20
22
|
let disposeLoggerExtension;
|
|
21
23
|
let disposeRuntime;
|
|
24
|
+
let disposeRuntimeMetrics;
|
|
22
25
|
const logger = createLogger("telemetry");
|
|
23
26
|
const OTLP_DEPENDENCY_UNAVAILABLE = /* @__PURE__ */ Symbol.for("open-mercato.telemetry.otlp-dependency-unavailable");
|
|
24
27
|
class OtlpDependencyUnavailableError extends Error {
|
|
@@ -33,6 +36,15 @@ class OtlpDependencyUnavailableError extends Error {
|
|
|
33
36
|
}
|
|
34
37
|
async function initTelemetry() {
|
|
35
38
|
if (initialized) return;
|
|
39
|
+
if (initializing) return initializing;
|
|
40
|
+
let pending;
|
|
41
|
+
pending = initializeTelemetry().finally(() => {
|
|
42
|
+
if (initializing === pending) initializing = void 0;
|
|
43
|
+
});
|
|
44
|
+
initializing = pending;
|
|
45
|
+
return pending;
|
|
46
|
+
}
|
|
47
|
+
async function initializeTelemetry() {
|
|
36
48
|
resetTelemetryEnvCache();
|
|
37
49
|
const env = readTelemetryEnv();
|
|
38
50
|
const configuredBackend = process.env.TELEMETRY_BACKEND?.trim().toLowerCase() ?? "";
|
|
@@ -50,6 +62,7 @@ async function initTelemetry() {
|
|
|
50
62
|
activeProvider = provider;
|
|
51
63
|
disposeLoggerExtension = registerTelemetryLogger(provider);
|
|
52
64
|
disposeRuntime = registerTelemetryRuntime(createRuntime(provider));
|
|
65
|
+
disposeRuntimeMetrics = startRuntimeMetrics();
|
|
53
66
|
initialized = true;
|
|
54
67
|
logger.info("Telemetry initialized", {
|
|
55
68
|
backend: provider.name,
|
|
@@ -73,11 +86,27 @@ async function loadOtlpProvider(backend) {
|
|
|
73
86
|
return new mod.OtlpProvider({}, backend);
|
|
74
87
|
}
|
|
75
88
|
async function shutdownTelemetry() {
|
|
89
|
+
if (initializing) {
|
|
90
|
+
try {
|
|
91
|
+
await initializing;
|
|
92
|
+
} catch (err) {
|
|
93
|
+
try {
|
|
94
|
+
reportError(err, {
|
|
95
|
+
module: "telemetry",
|
|
96
|
+
code: "telemetry.initialization_failed"
|
|
97
|
+
});
|
|
98
|
+
} catch {
|
|
99
|
+
}
|
|
100
|
+
logger.warn("Telemetry initialization failed before shutdown", { err });
|
|
101
|
+
}
|
|
102
|
+
}
|
|
76
103
|
const provider = activeProvider;
|
|
77
104
|
activeProvider = void 0;
|
|
78
105
|
initialized = false;
|
|
79
106
|
disposeLoggerExtension?.();
|
|
80
107
|
disposeLoggerExtension = void 0;
|
|
108
|
+
disposeRuntimeMetrics?.();
|
|
109
|
+
disposeRuntimeMetrics = void 0;
|
|
81
110
|
disposeRuntime?.();
|
|
82
111
|
disposeRuntime = void 0;
|
|
83
112
|
clearActiveProvider();
|
|
@@ -89,6 +118,7 @@ function createRuntime(provider) {
|
|
|
89
118
|
captureTraceContext,
|
|
90
119
|
continueTrace: (carrier, name, fn, options) => continueTrace(carrier, name, () => fn(), options),
|
|
91
120
|
withSpan: (name, fn, options) => withSpan(name, fn, options),
|
|
121
|
+
recordMetric: (point) => provider.recordMetric(point),
|
|
92
122
|
recordHistogram: histogram,
|
|
93
123
|
recordHttpDuration,
|
|
94
124
|
reportError,
|
|
@@ -97,9 +127,12 @@ function createRuntime(provider) {
|
|
|
97
127
|
}
|
|
98
128
|
function resetTelemetryInit() {
|
|
99
129
|
initialized = false;
|
|
130
|
+
initializing = void 0;
|
|
100
131
|
activeProvider = void 0;
|
|
101
132
|
disposeLoggerExtension?.();
|
|
102
133
|
disposeLoggerExtension = void 0;
|
|
134
|
+
disposeRuntimeMetrics?.();
|
|
135
|
+
disposeRuntimeMetrics = void 0;
|
|
103
136
|
disposeRuntime?.();
|
|
104
137
|
disposeRuntime = void 0;
|
|
105
138
|
}
|
package/dist/init.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/init.ts"],
|
|
4
|
-
"sourcesContent": ["import type { TelemetryBackendName, TelemetryProvider } from './types'\nimport { isOtlpBackend, readTelemetryEnv, resetTelemetryEnvCache } from './env'\nimport { ConsoleProvider } from './provider/console-provider'\nimport {\n getRegisteredProvider,\n clearActiveProvider,\n setActiveProvider,\n} from './provider/registry'\nimport {\n registerTelemetryRuntime,\n type TelemetryRuntime,\n} from '@open-mercato/shared/lib/telemetry/runtime'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { registerTelemetryLogger } from './facade/logger-bridge'\nimport { captureTraceContext, continueTrace } from './facade/propagation'\nimport { withSpan } from './facade/tracer'\nimport { recordHttpDuration } from './facade/http'\nimport { histogram } from './facade/meter'\nimport { reportError } from './facade/report-error'\n\nlet initialized = false\nlet activeProvider: TelemetryProvider | undefined\nlet disposeLoggerExtension: (() => void) | undefined\nlet disposeRuntime: (() => void) | undefined\n\nconst logger = createLogger('telemetry')\nconst OTLP_DEPENDENCY_UNAVAILABLE = Symbol.for('open-mercato.telemetry.otlp-dependency-unavailable')\n\nclass OtlpDependencyUnavailableError extends Error {\n constructor(backend: TelemetryBackendName, cause: unknown) {\n super(\n `[internal] OTLP telemetry backend \"${backend}\" cannot start because its OpenTelemetry runtime dependencies are unavailable. Install optional dependencies, set TELEMETRY_BACKEND=console, or unset TELEMETRY_BACKEND to disable telemetry.`,\n { cause },\n )\n this.name = 'OtlpDependencyUnavailableError'\n Object.defineProperty(this, OTLP_DEPENDENCY_UNAVAILABLE, { value: true })\n }\n}\n\n/**\n * One-shot bootstrap, invoked from `apps/mercato/instrumentation.ts` (web) and,\n * for cross-boundary propagation, from the queue/worker bootstrap. Resolves the\n * backend from `TELEMETRY_BACKEND`, starts it, and installs it as the active\n * provider. Idempotent and safe to call when telemetry is off (defaults to\n * no-op).\n */\nexport async function initTelemetry(): Promise<void> {\n if (initialized) return\n\n // Drop any env snapshot memoized BEFORE the host loaded its `.env` (the CLI\n // binary imports this package before dotenv runs) so init resolves the backend\n // from the actual, fully-loaded environment.\n resetTelemetryEnvCache()\n const env = readTelemetryEnv()\n const configuredBackend = process.env.TELEMETRY_BACKEND?.trim().toLowerCase() ?? ''\n const registeredProvider = configuredBackend && configuredBackend !== 'noop'\n ? getRegisteredProvider(configuredBackend)\n : undefined\n // Explicit off is absolute: do not resolve providers, register hooks, or\n // install process-wide bridges when the backend is unset/noop/unregistered.\n if (!env.enabled && !registeredProvider) return\n\n const provider = registeredProvider ?? await resolveProvider(env.backend)\n if (!provider) {\n logger.warn('Telemetry backend is unsupported; telemetry remains disabled', {\n backend: configuredBackend || env.backend,\n })\n return\n }\n\n // Only flag initialized AFTER start() succeeds \u2014 a throw here must leave\n // telemetry re-initializable, not stuck flagged-on with an unstarted provider.\n await provider.start()\n setActiveProvider(provider)\n activeProvider = provider\n disposeLoggerExtension = registerTelemetryLogger(provider)\n disposeRuntime = registerTelemetryRuntime(createRuntime(provider))\n initialized = true\n\n logger.info('Telemetry initialized', {\n backend: provider.name,\n samplingRatio: env.samplingRatio,\n })\n}\n\nasync function resolveProvider(backend: TelemetryBackendName): Promise<TelemetryProvider | undefined> {\n const registered = getRegisteredProvider(backend)\n if (registered) return registered\n\n if (backend === 'console') return new ConsoleProvider()\n // signoz | newrelic | otlp \u2014 same OTLP provider, vendor differs only by endpoint.\n if (isOtlpBackend(backend)) return await loadOtlpProvider(backend)\n return undefined\n}\n\n/**\n * Dynamically load the OTLP provider so `@opentelemetry/*` (optionalDependencies)\n * is imported only when an OTLP backend is selected. An explicit OTLP selection\n * must fail at startup when those packages are unavailable instead of silently\n * switching telemetry semantics.\n */\nasync function loadOtlpProvider(backend: TelemetryBackendName): Promise<TelemetryProvider> {\n let mod: typeof import('./provider/otlp-provider')\n try {\n mod = await import('./provider/otlp-provider')\n } catch (error) {\n throw new OtlpDependencyUnavailableError(backend, error)\n }\n return new mod.OtlpProvider({}, backend)\n}\n\n/** Flush + tear down the active backend (shutdown hook / `after()`). */\nexport async function shutdownTelemetry(): Promise<void> {\n const provider = activeProvider\n activeProvider = undefined\n initialized = false\n disposeLoggerExtension?.()\n disposeLoggerExtension = undefined\n disposeRuntime?.()\n disposeRuntime = undefined\n clearActiveProvider()\n if (provider) await provider.shutdown()\n}\n\nfunction createRuntime(provider: TelemetryProvider): TelemetryRuntime {\n return {\n canUseGlobalTracePropagation: () =>\n isOtlpBackend(provider.name as TelemetryBackendName)\n && readTelemetryEnv().trustInboundTrace,\n captureTraceContext,\n continueTrace: (carrier, name, fn, options) =>\n continueTrace(carrier, name, () => fn(), options),\n withSpan: (name, fn, options) => withSpan(name, fn, options),\n recordHistogram: histogram,\n recordHttpDuration,\n reportError,\n shutdown: shutdownTelemetry,\n }\n}\n\n/** Test-only: allow re-init in jest. */\nexport function resetTelemetryInit(): void {\n initialized = false\n activeProvider = undefined\n disposeLoggerExtension?.()\n disposeLoggerExtension = undefined\n disposeRuntime?.()\n disposeRuntime = undefined\n}\n"],
|
|
5
|
-
"mappings": "AACA,SAAS,eAAe,kBAAkB,8BAA8B;AACxE,SAAS,uBAAuB;AAChC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,OAEK;AACP,SAAS,oBAAoB;AAC7B,SAAS,+BAA+B;AACxC,SAAS,qBAAqB,qBAAqB;AACnD,SAAS,gBAAgB;AACzB,SAAS,0BAA0B;AACnC,SAAS,iBAAiB;AAC1B,SAAS,mBAAmB;
|
|
4
|
+
"sourcesContent": ["import type { TelemetryBackendName, TelemetryProvider } from './types'\nimport { isOtlpBackend, readTelemetryEnv, resetTelemetryEnvCache } from './env'\nimport { ConsoleProvider } from './provider/console-provider'\nimport {\n getRegisteredProvider,\n clearActiveProvider,\n setActiveProvider,\n} from './provider/registry'\nimport {\n registerTelemetryRuntime,\n type TelemetryRuntime,\n} from '@open-mercato/shared/lib/telemetry/runtime'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { registerTelemetryLogger } from './facade/logger-bridge'\nimport { captureTraceContext, continueTrace } from './facade/propagation'\nimport { withSpan } from './facade/tracer'\nimport { recordHttpDuration } from './facade/http'\nimport { histogram } from './facade/meter'\nimport { reportError } from './facade/report-error'\nimport { startRuntimeMetrics } from './runtime-metrics'\n\nlet initialized = false\nlet initializing: Promise<void> | undefined\nlet activeProvider: TelemetryProvider | undefined\nlet disposeLoggerExtension: (() => void) | undefined\nlet disposeRuntime: (() => void) | undefined\nlet disposeRuntimeMetrics: (() => void) | undefined\n\nconst logger = createLogger('telemetry')\nconst OTLP_DEPENDENCY_UNAVAILABLE = Symbol.for('open-mercato.telemetry.otlp-dependency-unavailable')\n\nclass OtlpDependencyUnavailableError extends Error {\n constructor(backend: TelemetryBackendName, cause: unknown) {\n super(\n `[internal] OTLP telemetry backend \"${backend}\" cannot start because its OpenTelemetry runtime dependencies are unavailable. Install optional dependencies, set TELEMETRY_BACKEND=console, or unset TELEMETRY_BACKEND to disable telemetry.`,\n { cause },\n )\n this.name = 'OtlpDependencyUnavailableError'\n Object.defineProperty(this, OTLP_DEPENDENCY_UNAVAILABLE, { value: true })\n }\n}\n\n/**\n * One-shot bootstrap, invoked from `apps/mercato/instrumentation.ts` (web) and,\n * for cross-boundary propagation, from the queue/worker bootstrap. Resolves the\n * backend from `TELEMETRY_BACKEND`, starts it, and installs it as the active\n * provider. Idempotent and safe to call when telemetry is off (defaults to\n * no-op).\n */\nexport async function initTelemetry(): Promise<void> {\n if (initialized) return\n if (initializing) return initializing\n\n let pending: Promise<void>\n pending = initializeTelemetry().finally(() => {\n if (initializing === pending) initializing = undefined\n })\n initializing = pending\n return pending\n}\n\nasync function initializeTelemetry(): Promise<void> {\n // Drop any env snapshot memoized BEFORE the host loaded its `.env` (the CLI\n // binary imports this package before dotenv runs) so init resolves the backend\n // from the actual, fully-loaded environment.\n resetTelemetryEnvCache()\n const env = readTelemetryEnv()\n const configuredBackend = process.env.TELEMETRY_BACKEND?.trim().toLowerCase() ?? ''\n const registeredProvider = configuredBackend && configuredBackend !== 'noop'\n ? getRegisteredProvider(configuredBackend)\n : undefined\n // Explicit off is absolute: do not resolve providers, register hooks, or\n // install process-wide bridges when the backend is unset/noop/unregistered.\n if (!env.enabled && !registeredProvider) return\n\n const provider = registeredProvider ?? await resolveProvider(env.backend)\n if (!provider) {\n logger.warn('Telemetry backend is unsupported; telemetry remains disabled', {\n backend: configuredBackend || env.backend,\n })\n return\n }\n\n // Only flag initialized AFTER start() succeeds \u2014 a throw here must leave\n // telemetry re-initializable, not stuck flagged-on with an unstarted provider.\n await provider.start()\n setActiveProvider(provider)\n activeProvider = provider\n disposeLoggerExtension = registerTelemetryLogger(provider)\n disposeRuntime = registerTelemetryRuntime(createRuntime(provider))\n disposeRuntimeMetrics = startRuntimeMetrics()\n initialized = true\n\n logger.info('Telemetry initialized', {\n backend: provider.name,\n samplingRatio: env.samplingRatio,\n })\n}\n\nasync function resolveProvider(backend: TelemetryBackendName): Promise<TelemetryProvider | undefined> {\n const registered = getRegisteredProvider(backend)\n if (registered) return registered\n\n if (backend === 'console') return new ConsoleProvider()\n // signoz | newrelic | otlp \u2014 same OTLP provider, vendor differs only by endpoint.\n if (isOtlpBackend(backend)) return await loadOtlpProvider(backend)\n return undefined\n}\n\n/**\n * Dynamically load the OTLP provider so `@opentelemetry/*` (optionalDependencies)\n * is imported only when an OTLP backend is selected. An explicit OTLP selection\n * must fail at startup when those packages are unavailable instead of silently\n * switching telemetry semantics.\n */\nasync function loadOtlpProvider(backend: TelemetryBackendName): Promise<TelemetryProvider> {\n let mod: typeof import('./provider/otlp-provider')\n try {\n mod = await import('./provider/otlp-provider')\n } catch (error) {\n throw new OtlpDependencyUnavailableError(backend, error)\n }\n return new mod.OtlpProvider({}, backend)\n}\n\n/** Flush + tear down the active backend (shutdown hook / `after()`). */\nexport async function shutdownTelemetry(): Promise<void> {\n if (initializing) {\n try {\n await initializing\n } catch (err) {\n try {\n reportError(err, {\n module: 'telemetry',\n code: 'telemetry.initialization_failed',\n })\n } catch {}\n logger.warn('Telemetry initialization failed before shutdown', { err })\n }\n }\n const provider = activeProvider\n activeProvider = undefined\n initialized = false\n disposeLoggerExtension?.()\n disposeLoggerExtension = undefined\n disposeRuntimeMetrics?.()\n disposeRuntimeMetrics = undefined\n disposeRuntime?.()\n disposeRuntime = undefined\n clearActiveProvider()\n if (provider) await provider.shutdown()\n}\n\nfunction createRuntime(provider: TelemetryProvider): TelemetryRuntime {\n return {\n canUseGlobalTracePropagation: () =>\n isOtlpBackend(provider.name as TelemetryBackendName)\n && readTelemetryEnv().trustInboundTrace,\n captureTraceContext,\n continueTrace: (carrier, name, fn, options) =>\n continueTrace(carrier, name, () => fn(), options),\n withSpan: (name, fn, options) => withSpan(name, fn, options),\n recordMetric: (point) => provider.recordMetric(point),\n recordHistogram: histogram,\n recordHttpDuration,\n reportError,\n shutdown: shutdownTelemetry,\n }\n}\n\n/** Test-only: allow re-init in jest. */\nexport function resetTelemetryInit(): void {\n initialized = false\n initializing = undefined\n activeProvider = undefined\n disposeLoggerExtension?.()\n disposeLoggerExtension = undefined\n disposeRuntimeMetrics?.()\n disposeRuntimeMetrics = undefined\n disposeRuntime?.()\n disposeRuntime = undefined\n}\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,eAAe,kBAAkB,8BAA8B;AACxE,SAAS,uBAAuB;AAChC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,OAEK;AACP,SAAS,oBAAoB;AAC7B,SAAS,+BAA+B;AACxC,SAAS,qBAAqB,qBAAqB;AACnD,SAAS,gBAAgB;AACzB,SAAS,0BAA0B;AACnC,SAAS,iBAAiB;AAC1B,SAAS,mBAAmB;AAC5B,SAAS,2BAA2B;AAEpC,IAAI,cAAc;AAClB,IAAI;AACJ,IAAI;AACJ,IAAI;AACJ,IAAI;AACJ,IAAI;AAEJ,MAAM,SAAS,aAAa,WAAW;AACvC,MAAM,8BAA8B,uBAAO,IAAI,oDAAoD;AAEnG,MAAM,uCAAuC,MAAM;AAAA,EACjD,YAAY,SAA+B,OAAgB;AACzD;AAAA,MACE,sCAAsC,OAAO;AAAA,MAC7C,EAAE,MAAM;AAAA,IACV;AACA,SAAK,OAAO;AACZ,WAAO,eAAe,MAAM,6BAA6B,EAAE,OAAO,KAAK,CAAC;AAAA,EAC1E;AACF;AASA,eAAsB,gBAA+B;AACnD,MAAI,YAAa;AACjB,MAAI,aAAc,QAAO;AAEzB,MAAI;AACJ,YAAU,oBAAoB,EAAE,QAAQ,MAAM;AAC5C,QAAI,iBAAiB,QAAS,gBAAe;AAAA,EAC/C,CAAC;AACD,iBAAe;AACf,SAAO;AACT;AAEA,eAAe,sBAAqC;AAIlD,yBAAuB;AACvB,QAAM,MAAM,iBAAiB;AAC7B,QAAM,oBAAoB,QAAQ,IAAI,mBAAmB,KAAK,EAAE,YAAY,KAAK;AACjF,QAAM,qBAAqB,qBAAqB,sBAAsB,SAClE,sB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,2BAAyB;AACzB,2BAAyB;AACzB,0BAAwB;AACxB,0BAAwB;AACxB,mBAAiB;AACjB,mBAAiB;AACjB,sBAAoB;AACpB,MAAI,SAAU,OAAM,SAAS,SAAS;AACxC;AAEA,SAAS,cAAc,UAA+C;AACpE,SAAO;AAAA,IACL,8BAA8B,MAC5B,cAAc,SAAS,IAA4B,KAChD,iBAAiB,EAAE;AAAA,IACxB;AAAA,IACA,eAAe,CAAC,SAAS,MAAM,IAAI,YACjC,cAAc,SAAS,MAAM,MAAM,GAAG,GAAG,OAAO;AAAA,IAClD,UAAU,CAAC,MAAM,IAAI,YAAY,SAAS,MAAM,IAAI,OAAO;AAAA,IAC3D,cAAc,CAAC,UAAU,SAAS,aAAa,KAAK;AAAA,IACpD,iBAAiB;AAAA,IACjB;AAAA,IACA;AAAA,IACA,UAAU;AAAA,EACZ;AACF;AAGO,SAAS,qBAA2B;AACzC,gBAAc;AACd,iBAAe;AACf,mBAAiB;AACjB,2BAAyB;AACzB,2BAAyB;AACzB,0BAAwB;AACxB,0BAAwB;AACxB,mBAAiB;AACjB,mBAAiB;AACnB;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -34,6 +34,10 @@ async function otelApiIsRegistered(page) {
|
|
|
34
34
|
}
|
|
35
35
|
test.describe("TC-TELEMETRY-002: browser RUM runtime", () => {
|
|
36
36
|
test("exports document-load and fetch spans without breaking either fetch path", async ({ page, baseURL }) => {
|
|
37
|
+
test.skip(
|
|
38
|
+
process.env.OM_TEST_BROWSER_TELEMETRY_MODE !== "opt-in",
|
|
39
|
+
"OM_TEST_BROWSER_TELEMETRY_MODE=opt-in is not configured for this lane."
|
|
40
|
+
);
|
|
37
41
|
const origin = new URL(baseURL ?? "http://localhost:3000").origin;
|
|
38
42
|
await page.context().addCookies([{ name: OPT_IN_COOKIE, value: "on", url: origin }]);
|
|
39
43
|
const ingest = recordIngest(page);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/telemetry/__integration__/TC-TELEMETRY-002.spec.ts"],
|
|
4
|
-
"sourcesContent": ["import { expect, test, type Page, type Request as PlaywrightRequest } from '@playwright/test'\nimport { login } from '@open-mercato/core/helpers/integration/auth'\n\n/**\n * TC-TELEMETRY-002: browser RUM in a real browser.\n *\n * TC-TELEMETRY-001 drives the proxy route with `request.post` \u2014 a useful API contract test that\n * never opens a page. This spec covers what only a browser can: that the SDK actually boots, that\n * the `__omOriginalFetch` patch dance leaves both fetch paths working (a recursion here hangs every\n * API call in the backoffice), that batches reach the proxy, and \u2014 the mirror image \u2014 that a\n * default environment ships none of it.\n *\n * Browser RUM is normally an environment-wide env switch, which a spec cannot flip for one page.\n * The integration environment therefore sets `OM_TEST_BROWSER_TELEMETRY_MODE=opt-in` on top of\n * `OM_TEST_MODE=1`, and only then does the server honour an `om_test_browser_telemetry=on` cookie.\n * Both variables are absent in production. Same escape hatch the auth rate limiter already uses.\n *\n * No collector is configured here, so the proxy answers 204 (accept-and-drop) rather than 202 \u2014\n * which is why the span assertions read the batch the *browser posted* instead of anything a sink\n * received. That is the stronger assertion anyway: it is the browser's output under test.\n */\n\nconst TRACES_PATH = '/api/telemetry/browser-traces'\nconst OPT_IN_COOKIE = 'om_test_browser_telemetry'\n\ntype IngestRecord = { status: number; body: string }\n\n/** Records every proxy call the page makes, with the payload the exporter actually produced. */\nfunction recordIngest(page: Page): IngestRecord[] {\n const records: IngestRecord[] = []\n page.on('response', async (response) => {\n if (!response.url().includes(TRACES_PATH)) return\n const request: PlaywrightRequest = response.request()\n if (request.method() !== 'POST') return\n records.push({ status: response.status(), body: request.postData() ?? '' })\n })\n return records\n}\n\n/**\n * Records the same-origin API GETs the backoffice itself made and that answered 200. Replaying a\n * real one beats naming an endpoint here: the set of routes is not this spec's business, and a\n * path that quietly stops existing would fail the test for the wrong reason.\n */\nfunction recordApiGets(page: Page): string[] {\n const urls: string[] = []\n page.on('response', (response) => {\n const request = response.request()\n if (request.method() !== 'GET') return\n if (response.status() !== 200) return\n try {\n const { pathname } = new URL(response.url())\n if (!pathname.startsWith('/api/') || pathname.startsWith(TRACES_PATH)) return\n urls.push(response.url())\n } catch {\n // A non-absolute or exotic URL is simply not a candidate for replay.\n }\n })\n return urls\n}\n\n/** The web SDK registers itself on this global symbol; its presence is the \"SDK booted\" signal. */\nasync function otelApiIsRegistered(page: Page): Promise<boolean> {\n return page.evaluate(() =>\n Object.getOwnPropertySymbols(globalThis).some((symbol) => symbol.toString().includes('opentelemetry.js.api')),\n )\n}\n\ntest.describe('TC-TELEMETRY-002: browser RUM runtime', () => {\n test('exports document-load and fetch spans without breaking either fetch path', async ({ page, baseURL }) => {\n const origin = new URL(baseURL ?? 'http://localhost:3000').origin\n await page.context().addCookies([{ name: OPT_IN_COOKIE, value: 'on', url: origin }])\n const ingest = recordIngest(page)\n const apiGets = recordApiGets(page)\n\n await login(page, 'admin')\n await page.goto('/backend')\n await expect.poll(() => otelApiIsRegistered(page), {\n message: 'the web SDK must boot once the server hands the layout a non-null config',\n timeout: 15_000,\n }).toBe(true)\n\n // The patch dance, asserted where it actually runs. `@open-mercato/ui`'s api utils stash the\n // pristine fetch on `__omOriginalFetch` and put a wrapper on `window.fetch`; the SDK has to\n // instrument the stash rather than the wrapper, or direct `apiFetch` callers (DataTable,\n // CrudForm, react-query) produce no spans at all.\n const patchState = await page.evaluate(() => {\n const w = window as Window & { __omOriginalFetch?: typeof window.fetch }\n return {\n hasStash: typeof w.__omOriginalFetch === 'function',\n // Identical would mean the wrapper was handed back to itself \u2014 an infinite recursion on\n // the first request through `apiFetch`.\n stashIsWrapper: w.__omOriginalFetch === window.fetch,\n }\n })\n expect(patchState.hasStash, '@open-mercato/ui installs the fetch wrapper on every backoffice page').toBe(true)\n expect(patchState.stashIsWrapper, 'instrumenting the wrapper instead of the native fetch recurses forever').toBe(false)\n\n // A DataTable page drives `apiFetch` (which reads the instrumented stash) end to end. Waiting\n // on the API call it makes, rather than on a DOM role, keeps this assertion about the thing\n // under test: that the swap left `apiFetch` able to reach the API at all.\n await expect.poll(() => apiGets.length, {\n message: 'the backoffice must still reach its own API through the patched fetch',\n timeout: 30_000,\n }).toBeGreaterThan(0)\n await page.goto('/backend/customers/people')\n await expect(page.locator('table, [role=\"grid\"]').first()).toBeVisible({ timeout: 30_000 })\n\n // Replay one of the page's OWN successful GETs down both paths. A hang here IS the recursion\n // bug, hence the tight budget; a non-200 means the swap broke the wrapper's auth handling.\n const replayUrl = apiGets[apiGets.length - 1]\n const replay = await page.evaluate(async (url: string) => {\n const w = window as Window & { __omOriginalFetch?: typeof window.fetch }\n const withTimeout = async (call: Promise<Response>) => {\n const timeout = new Promise<never>((_, reject) => setTimeout(() => reject(new Error('timeout')), 10_000))\n return (await Promise.race([call, timeout])).status\n }\n return {\n viaWindow: await withTimeout(window.fetch(url)),\n viaStash: await withTimeout(w.__omOriginalFetch!(url)),\n }\n }, replayUrl)\n expect(replay.viaWindow, `window.fetch must still reach ${replayUrl} through the framework wrapper`).toBe(200)\n expect(replay.viaStash, `the instrumented native fetch must still reach ${replayUrl}`).toBe(200)\n\n // Exports are batched on a 3s delay, and a flush is forced when the page is hidden.\n await page.evaluate(() => {\n Object.defineProperty(document, 'visibilityState', { value: 'hidden', configurable: true })\n document.dispatchEvent(new Event('visibilitychange'))\n })\n await expect.poll(() => ingest.length, {\n message: 'the exporter must post its batches to the same-origin proxy',\n timeout: 20_000,\n }).toBeGreaterThan(0)\n\n // Every answer must be one the OTLP exporter does NOT retry (429/502/503/504 would storm).\n for (const record of ingest) {\n expect([202, 204], `unexpected ingest status ${record.status}`).toContain(record.status)\n }\n\n const spanNames = ingest.flatMap((record) => {\n try {\n const payload = JSON.parse(record.body) as {\n resourceSpans?: Array<{\n resource?: { attributes?: Array<{ key: string; value?: { stringValue?: string } }> }\n scopeSpans?: Array<{ spans?: Array<{ name: string }> }>\n }>\n }\n for (const resourceSpan of payload.resourceSpans ?? []) {\n const serviceName = resourceSpan.resource?.attributes?.find((a) => a.key === 'service.name')\n expect(\n serviceName?.value?.stringValue,\n 'browser spans must carry their own service name so they sort apart from server spans',\n ).toMatch(/-browser$/)\n }\n return (payload.resourceSpans ?? []).flatMap((r) => (r.scopeSpans ?? []).flatMap((s) => s.spans ?? [])).map((s) => s.name)\n } catch {\n return []\n }\n })\n expect(spanNames, 'document-load instrumentation must produce the navigation span').toContain('documentLoad')\n expect(spanNames, 'document-load instrumentation must produce the document fetch span').toContain('documentFetch')\n })\n\n test('ships nothing at all without the opt-in \u2014 the default path must cost a disabled app zero bytes', async ({ page }) => {\n // No cookie: this is the shipped default, and the mirror image of the case above. It is the\n // assertion that protects the \"zero client-bundle cost while off\" promise from regressing.\n const ingest = recordIngest(page)\n\n await login(page, 'admin')\n await page.goto('/backend')\n await page.goto('/backend/customers/people')\n await expect(page.locator('table, [role=\"grid\"]').first()).toBeVisible({ timeout: 30_000 })\n await page.waitForTimeout(5_000)\n\n expect(await otelApiIsRegistered(page), 'the web SDK chunk must never be requested while RUM is off').toBe(false)\n expect(ingest, 'a disabled app must not post a single batch').toHaveLength(0)\n })\n})\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,QAAQ,YAA0D;AAC3E,SAAS,aAAa;AAqBtB,MAAM,cAAc;AACpB,MAAM,gBAAgB;AAKtB,SAAS,aAAa,MAA4B;AAChD,QAAM,UAA0B,CAAC;AACjC,OAAK,GAAG,YAAY,OAAO,aAAa;AACtC,QAAI,CAAC,SAAS,IAAI,EAAE,SAAS,WAAW,EAAG;AAC3C,UAAM,UAA6B,SAAS,QAAQ;AACpD,QAAI,QAAQ,OAAO,MAAM,OAAQ;AACjC,YAAQ,KAAK,EAAE,QAAQ,SAAS,OAAO,GAAG,MAAM,QAAQ,SAAS,KAAK,GAAG,CAAC;AAAA,EAC5E,CAAC;AACD,SAAO;AACT;AAOA,SAAS,cAAc,MAAsB;AAC3C,QAAM,OAAiB,CAAC;AACxB,OAAK,GAAG,YAAY,CAAC,aAAa;AAChC,UAAM,UAAU,SAAS,QAAQ;AACjC,QAAI,QAAQ,OAAO,MAAM,MAAO;AAChC,QAAI,SAAS,OAAO,MAAM,IAAK;AAC/B,QAAI;AACF,YAAM,EAAE,SAAS,IAAI,IAAI,IAAI,SAAS,IAAI,CAAC;AAC3C,UAAI,CAAC,SAAS,WAAW,OAAO,KAAK,SAAS,WAAW,WAAW,EAAG;AACvE,WAAK,KAAK,SAAS,IAAI,CAAC;AAAA,IAC1B,QAAQ;AAAA,IAER;AAAA,EACF,CAAC;AACD,SAAO;AACT;AAGA,eAAe,oBAAoB,MAA8B;AAC/D,SAAO,KAAK;AAAA,IAAS,MACnB,OAAO,sBAAsB,UAAU,EAAE,KAAK,CAAC,WAAW,OAAO,SAAS,EAAE,SAAS,sBAAsB,CAAC;AAAA,EAC9G;AACF;AAEA,KAAK,SAAS,yCAAyC,MAAM;AAC3D,OAAK,4EAA4E,OAAO,EAAE,MAAM,QAAQ,MAAM;
|
|
4
|
+
"sourcesContent": ["import { expect, test, type Page, type Request as PlaywrightRequest } from '@playwright/test'\nimport { login } from '@open-mercato/core/helpers/integration/auth'\n\n/**\n * TC-TELEMETRY-002: browser RUM in a real browser.\n *\n * TC-TELEMETRY-001 drives the proxy route with `request.post` \u2014 a useful API contract test that\n * never opens a page. This spec covers what only a browser can: that the SDK actually boots, that\n * the `__omOriginalFetch` patch dance leaves both fetch paths working (a recursion here hangs every\n * API call in the backoffice), that batches reach the proxy, and \u2014 the mirror image \u2014 that a\n * default environment ships none of it.\n *\n * Browser RUM is normally an environment-wide env switch, which a spec cannot flip for one page.\n * The integration environment therefore sets `OM_TEST_BROWSER_TELEMETRY_MODE=opt-in` on top of\n * `OM_TEST_MODE=1`, and only then does the server honour an `om_test_browser_telemetry=on` cookie.\n * Both variables are absent in production. Same escape hatch the auth rate limiter already uses.\n *\n * No collector is configured here, so the proxy answers 204 (accept-and-drop) rather than 202 \u2014\n * which is why the span assertions read the batch the *browser posted* instead of anything a sink\n * received. That is the stronger assertion anyway: it is the browser's output under test.\n */\n\nconst TRACES_PATH = '/api/telemetry/browser-traces'\nconst OPT_IN_COOKIE = 'om_test_browser_telemetry'\n\ntype IngestRecord = { status: number; body: string }\n\n/** Records every proxy call the page makes, with the payload the exporter actually produced. */\nfunction recordIngest(page: Page): IngestRecord[] {\n const records: IngestRecord[] = []\n page.on('response', async (response) => {\n if (!response.url().includes(TRACES_PATH)) return\n const request: PlaywrightRequest = response.request()\n if (request.method() !== 'POST') return\n records.push({ status: response.status(), body: request.postData() ?? '' })\n })\n return records\n}\n\n/**\n * Records the same-origin API GETs the backoffice itself made and that answered 200. Replaying a\n * real one beats naming an endpoint here: the set of routes is not this spec's business, and a\n * path that quietly stops existing would fail the test for the wrong reason.\n */\nfunction recordApiGets(page: Page): string[] {\n const urls: string[] = []\n page.on('response', (response) => {\n const request = response.request()\n if (request.method() !== 'GET') return\n if (response.status() !== 200) return\n try {\n const { pathname } = new URL(response.url())\n if (!pathname.startsWith('/api/') || pathname.startsWith(TRACES_PATH)) return\n urls.push(response.url())\n } catch {\n // A non-absolute or exotic URL is simply not a candidate for replay.\n }\n })\n return urls\n}\n\n/** The web SDK registers itself on this global symbol; its presence is the \"SDK booted\" signal. */\nasync function otelApiIsRegistered(page: Page): Promise<boolean> {\n return page.evaluate(() =>\n Object.getOwnPropertySymbols(globalThis).some((symbol) => symbol.toString().includes('opentelemetry.js.api')),\n )\n}\n\ntest.describe('TC-TELEMETRY-002: browser RUM runtime', () => {\n test('exports document-load and fetch spans without breaking either fetch path', async ({ page, baseURL }) => {\n // The server ignores the opt-in cookie unless the app runs with this variable; lanes that\n // start the app from their own env (the standalone app) do not set it, so there is no SDK to boot.\n test.skip(\n process.env.OM_TEST_BROWSER_TELEMETRY_MODE !== 'opt-in',\n 'OM_TEST_BROWSER_TELEMETRY_MODE=opt-in is not configured for this lane.',\n )\n const origin = new URL(baseURL ?? 'http://localhost:3000').origin\n await page.context().addCookies([{ name: OPT_IN_COOKIE, value: 'on', url: origin }])\n const ingest = recordIngest(page)\n const apiGets = recordApiGets(page)\n\n await login(page, 'admin')\n await page.goto('/backend')\n await expect.poll(() => otelApiIsRegistered(page), {\n message: 'the web SDK must boot once the server hands the layout a non-null config',\n timeout: 15_000,\n }).toBe(true)\n\n // The patch dance, asserted where it actually runs. `@open-mercato/ui`'s api utils stash the\n // pristine fetch on `__omOriginalFetch` and put a wrapper on `window.fetch`; the SDK has to\n // instrument the stash rather than the wrapper, or direct `apiFetch` callers (DataTable,\n // CrudForm, react-query) produce no spans at all.\n const patchState = await page.evaluate(() => {\n const w = window as Window & { __omOriginalFetch?: typeof window.fetch }\n return {\n hasStash: typeof w.__omOriginalFetch === 'function',\n // Identical would mean the wrapper was handed back to itself \u2014 an infinite recursion on\n // the first request through `apiFetch`.\n stashIsWrapper: w.__omOriginalFetch === window.fetch,\n }\n })\n expect(patchState.hasStash, '@open-mercato/ui installs the fetch wrapper on every backoffice page').toBe(true)\n expect(patchState.stashIsWrapper, 'instrumenting the wrapper instead of the native fetch recurses forever').toBe(false)\n\n // A DataTable page drives `apiFetch` (which reads the instrumented stash) end to end. Waiting\n // on the API call it makes, rather than on a DOM role, keeps this assertion about the thing\n // under test: that the swap left `apiFetch` able to reach the API at all.\n await expect.poll(() => apiGets.length, {\n message: 'the backoffice must still reach its own API through the patched fetch',\n timeout: 30_000,\n }).toBeGreaterThan(0)\n await page.goto('/backend/customers/people')\n await expect(page.locator('table, [role=\"grid\"]').first()).toBeVisible({ timeout: 30_000 })\n\n // Replay one of the page's OWN successful GETs down both paths. A hang here IS the recursion\n // bug, hence the tight budget; a non-200 means the swap broke the wrapper's auth handling.\n const replayUrl = apiGets[apiGets.length - 1]\n const replay = await page.evaluate(async (url: string) => {\n const w = window as Window & { __omOriginalFetch?: typeof window.fetch }\n const withTimeout = async (call: Promise<Response>) => {\n const timeout = new Promise<never>((_, reject) => setTimeout(() => reject(new Error('timeout')), 10_000))\n return (await Promise.race([call, timeout])).status\n }\n return {\n viaWindow: await withTimeout(window.fetch(url)),\n viaStash: await withTimeout(w.__omOriginalFetch!(url)),\n }\n }, replayUrl)\n expect(replay.viaWindow, `window.fetch must still reach ${replayUrl} through the framework wrapper`).toBe(200)\n expect(replay.viaStash, `the instrumented native fetch must still reach ${replayUrl}`).toBe(200)\n\n // Exports are batched on a 3s delay, and a flush is forced when the page is hidden.\n await page.evaluate(() => {\n Object.defineProperty(document, 'visibilityState', { value: 'hidden', configurable: true })\n document.dispatchEvent(new Event('visibilitychange'))\n })\n await expect.poll(() => ingest.length, {\n message: 'the exporter must post its batches to the same-origin proxy',\n timeout: 20_000,\n }).toBeGreaterThan(0)\n\n // Every answer must be one the OTLP exporter does NOT retry (429/502/503/504 would storm).\n for (const record of ingest) {\n expect([202, 204], `unexpected ingest status ${record.status}`).toContain(record.status)\n }\n\n const spanNames = ingest.flatMap((record) => {\n try {\n const payload = JSON.parse(record.body) as {\n resourceSpans?: Array<{\n resource?: { attributes?: Array<{ key: string; value?: { stringValue?: string } }> }\n scopeSpans?: Array<{ spans?: Array<{ name: string }> }>\n }>\n }\n for (const resourceSpan of payload.resourceSpans ?? []) {\n const serviceName = resourceSpan.resource?.attributes?.find((a) => a.key === 'service.name')\n expect(\n serviceName?.value?.stringValue,\n 'browser spans must carry their own service name so they sort apart from server spans',\n ).toMatch(/-browser$/)\n }\n return (payload.resourceSpans ?? []).flatMap((r) => (r.scopeSpans ?? []).flatMap((s) => s.spans ?? [])).map((s) => s.name)\n } catch {\n return []\n }\n })\n expect(spanNames, 'document-load instrumentation must produce the navigation span').toContain('documentLoad')\n expect(spanNames, 'document-load instrumentation must produce the document fetch span').toContain('documentFetch')\n })\n\n test('ships nothing at all without the opt-in \u2014 the default path must cost a disabled app zero bytes', async ({ page }) => {\n // No cookie: this is the shipped default, and the mirror image of the case above. It is the\n // assertion that protects the \"zero client-bundle cost while off\" promise from regressing.\n const ingest = recordIngest(page)\n\n await login(page, 'admin')\n await page.goto('/backend')\n await page.goto('/backend/customers/people')\n await expect(page.locator('table, [role=\"grid\"]').first()).toBeVisible({ timeout: 30_000 })\n await page.waitForTimeout(5_000)\n\n expect(await otelApiIsRegistered(page), 'the web SDK chunk must never be requested while RUM is off').toBe(false)\n expect(ingest, 'a disabled app must not post a single batch').toHaveLength(0)\n })\n})\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,QAAQ,YAA0D;AAC3E,SAAS,aAAa;AAqBtB,MAAM,cAAc;AACpB,MAAM,gBAAgB;AAKtB,SAAS,aAAa,MAA4B;AAChD,QAAM,UAA0B,CAAC;AACjC,OAAK,GAAG,YAAY,OAAO,aAAa;AACtC,QAAI,CAAC,SAAS,IAAI,EAAE,SAAS,WAAW,EAAG;AAC3C,UAAM,UAA6B,SAAS,QAAQ;AACpD,QAAI,QAAQ,OAAO,MAAM,OAAQ;AACjC,YAAQ,KAAK,EAAE,QAAQ,SAAS,OAAO,GAAG,MAAM,QAAQ,SAAS,KAAK,GAAG,CAAC;AAAA,EAC5E,CAAC;AACD,SAAO;AACT;AAOA,SAAS,cAAc,MAAsB;AAC3C,QAAM,OAAiB,CAAC;AACxB,OAAK,GAAG,YAAY,CAAC,aAAa;AAChC,UAAM,UAAU,SAAS,QAAQ;AACjC,QAAI,QAAQ,OAAO,MAAM,MAAO;AAChC,QAAI,SAAS,OAAO,MAAM,IAAK;AAC/B,QAAI;AACF,YAAM,EAAE,SAAS,IAAI,IAAI,IAAI,SAAS,IAAI,CAAC;AAC3C,UAAI,CAAC,SAAS,WAAW,OAAO,KAAK,SAAS,WAAW,WAAW,EAAG;AACvE,WAAK,KAAK,SAAS,IAAI,CAAC;AAAA,IAC1B,QAAQ;AAAA,IAER;AAAA,EACF,CAAC;AACD,SAAO;AACT;AAGA,eAAe,oBAAoB,MAA8B;AAC/D,SAAO,KAAK;AAAA,IAAS,MACnB,OAAO,sBAAsB,UAAU,EAAE,KAAK,CAAC,WAAW,OAAO,SAAS,EAAE,SAAS,sBAAsB,CAAC;AAAA,EAC9G;AACF;AAEA,KAAK,S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E,cAAc,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC,CAAC,EAAE,IAAI,CAAC,MAAM,EAAE,IAAI;AAAA,MAC3H,QAAQ;AACN,eAAO,CAAC;AAAA,MACV;AAAA,IACF,CAAC;AACD,WAAO,WAAW,gEAAgE,EAAE,UAAU,cAAc;AAC5G,WAAO,WAAW,oEAAoE,EAAE,UAAU,eAAe;AAAA,EACnH,CAAC;AAED,OAAK,uGAAkG,OAAO,EAAE,KAAK,MAAM;AAGzH,UAAM,SAAS,aAAa,IAAI;AAEhC,UAAM,MAAM,MAAM,OAAO;AACzB,UAAM,KAAK,KAAK,UAAU;AAC1B,UAAM,KAAK,KAAK,2BAA2B;AAC3C,UAAM,OAAO,KAAK,QAAQ,sBAAsB,EAAE,MAAM,CAAC,EAAE,YAAY,EAAE,SAAS,IAAO,CAAC;AAC1F,UAAM,KAAK,eAAe,GAAK;AAE/B,WAAO,MAAM,oBAAoB,IAAI,GAAG,4DAA4D,EAAE,KAAK,KAAK;AAChH,WAAO,QAAQ,6CAA6C,EAAE,aAAa,CAAC;AAAA,EAC9E,CAAC;AACH,CAAC;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -26,6 +26,7 @@ import { BatchLogRecordProcessor } from "@opentelemetry/sdk-logs";
|
|
|
26
26
|
import { PeriodicExportingMetricReader } from "@opentelemetry/sdk-metrics";
|
|
27
27
|
import { PgInstrumentation } from "@opentelemetry/instrumentation-pg";
|
|
28
28
|
import { UndiciInstrumentation } from "@opentelemetry/instrumentation-undici";
|
|
29
|
+
import { REDACTED_SQL_STATEMENT, sanitizeSqlStatement } from "./sanitize-sql.js";
|
|
29
30
|
import { readTelemetryEnv } from "../env.js";
|
|
30
31
|
import { BACKUP_TRACEPARENT_HEADER, BACKUP_TRACESTATE_HEADER } from "../trace-headers.js";
|
|
31
32
|
import { redactAttributes, redactPii } from "../facade/redact.js";
|
|
@@ -124,7 +125,36 @@ class OtelSpan {
|
|
|
124
125
|
this.span.end();
|
|
125
126
|
}
|
|
126
127
|
}
|
|
127
|
-
const
|
|
128
|
+
const PG_STATEMENT_ATTRIBUTE_KEYS = ["db.query.text", "db.statement"];
|
|
129
|
+
const PG_INSTRUMENTATION_OPTIONS = {
|
|
130
|
+
enhancedDatabaseReporting: false,
|
|
131
|
+
requestHook: (span, { query }) => {
|
|
132
|
+
if (typeof query.text !== "string" || query.text.length === 0) return;
|
|
133
|
+
const statement = sanitizeSqlStatement(query.text) ?? REDACTED_SQL_STATEMENT;
|
|
134
|
+
for (const key of PG_STATEMENT_ATTRIBUTE_KEYS) span.setAttribute(key, statement);
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
const SECONDS_HISTOGRAM_BUCKETS = [
|
|
138
|
+
1e-3,
|
|
139
|
+
5e-3,
|
|
140
|
+
0.01,
|
|
141
|
+
0.025,
|
|
142
|
+
0.05,
|
|
143
|
+
0.075,
|
|
144
|
+
0.1,
|
|
145
|
+
0.25,
|
|
146
|
+
0.5,
|
|
147
|
+
0.75,
|
|
148
|
+
1,
|
|
149
|
+
2.5,
|
|
150
|
+
5,
|
|
151
|
+
7.5,
|
|
152
|
+
10
|
|
153
|
+
];
|
|
154
|
+
function histogramOptions(unit) {
|
|
155
|
+
if (unit !== "s") return unit ? { unit } : void 0;
|
|
156
|
+
return { unit, advice: { explicitBucketBoundaries: [...SECONDS_HISTOGRAM_BUCKETS] } };
|
|
157
|
+
}
|
|
128
158
|
class OtlpProvider {
|
|
129
159
|
constructor(options = {}, name = "otlp") {
|
|
130
160
|
this.options = options;
|
|
@@ -221,7 +251,7 @@ class OtlpProvider {
|
|
|
221
251
|
if (!instrument) {
|
|
222
252
|
const meter = metrics.getMeter(TRACER_NAME);
|
|
223
253
|
const opts = point.unit ? { unit: point.unit } : void 0;
|
|
224
|
-
instrument = point.kind === "counter" ? meter.createCounter(point.name, opts) : point.kind === "histogram" ? meter.createHistogram(point.name,
|
|
254
|
+
instrument = point.kind === "counter" ? meter.createCounter(point.name, opts) : point.kind === "histogram" ? meter.createHistogram(point.name, histogramOptions(point.unit)) : meter.createGauge(point.name, opts);
|
|
225
255
|
this.instruments.set(key, instrument);
|
|
226
256
|
}
|
|
227
257
|
return instrument;
|
|
@@ -229,6 +259,8 @@ class OtlpProvider {
|
|
|
229
259
|
}
|
|
230
260
|
export {
|
|
231
261
|
OtlpProvider,
|
|
232
|
-
PG_INSTRUMENTATION_OPTIONS
|
|
262
|
+
PG_INSTRUMENTATION_OPTIONS,
|
|
263
|
+
PG_STATEMENT_ATTRIBUTE_KEYS,
|
|
264
|
+
SECONDS_HISTOGRAM_BUCKETS
|
|
233
265
|
};
|
|
234
266
|
//# sourceMappingURL=otlp-provider.js.map
|