@watchtowerobservability/node 0.8.0 → 0.8.1
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/CHANGELOG.md +7 -0
- package/README.md +26 -2
- package/dist/cjs/diagnostics.d.ts +37 -0
- package/dist/cjs/diagnostics.js +92 -0
- package/dist/cjs/index.js +14 -7
- package/dist/cjs/integrations/db.js +4 -2
- package/dist/cjs/integrations/next-build.d.ts +3 -1
- package/dist/cjs/integrations/next-build.js +5 -2
- package/dist/cjs/integrations/next-edge.d.ts +4 -0
- package/dist/cjs/integrations/next-edge.js +4 -0
- package/dist/cjs/integrations/next.d.ts +11 -4
- package/dist/cjs/integrations/next.js +12 -6
- package/dist/cjs/late.d.ts +7 -0
- package/dist/cjs/late.js +28 -0
- package/dist/cjs/metrics.d.ts +1 -1
- package/dist/cjs/metrics.js +3 -1
- package/dist/cjs/register.js +2 -0
- package/dist/cjs/version.d.ts +1 -1
- package/dist/cjs/version.js +1 -1
- package/dist/esm/diagnostics.d.ts +37 -0
- package/dist/esm/diagnostics.js +79 -0
- package/dist/esm/index.js +15 -8
- package/dist/esm/integrations/db.js +5 -3
- package/dist/esm/integrations/next-build.d.ts +3 -1
- package/dist/esm/integrations/next-build.js +5 -2
- package/dist/esm/integrations/next-edge.d.ts +4 -0
- package/dist/esm/integrations/next-edge.js +4 -0
- package/dist/esm/integrations/next.d.ts +11 -4
- package/dist/esm/integrations/next.js +12 -4
- package/dist/esm/late.d.ts +7 -0
- package/dist/esm/late.js +22 -0
- package/dist/esm/metrics.d.ts +1 -1
- package/dist/esm/metrics.js +3 -1
- package/dist/esm/register.js +2 -0
- package/dist/esm/version.d.ts +1 -1
- package/dist/esm/version.js +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.8.1 (2026-11-18)
|
|
4
|
+
|
|
5
|
+
- New: a `[watchtower] loaded too late: http was already imported, so its requests are not traced. Start node with --import @watchtowerobservability/node/register` warning, once per process, when `register` or `init()` loads after `http`/`https` (an ES module app that imports `register` from app code links `http` first, and its requests are then silently untraced). The check reads `process.moduleLoadList` in the first module the SDK evaluates, before its own dependencies load. Silent under Next.js and test runners. Verified: a bare `node --import` process has neither module loaded (no false positive on correct use), and a unit test covers the warning and its once-only guard.
|
|
6
|
+
- New: after the first exports the SDK prints one line, `[watchtower] <service> → <host> traces:ok logs:ok metrics:ok release=<release>` (`pending` until a signal exported, `fail(<status or error>)` for a failed one, `off` for a disabled one; it prints when every signal has a result, at the first failure, or after 90 s). `WT_DEBUG=1` (or `WATCHTOWER_DEBUG=1`) also logs the exporter endpoints (the key as its first 8 characters only), each export result (signal, item count, status or error) and a per-minute count of dropped Next.js internal spans and parentless DB queries. The default OTLP exporters are wrapped, not replaced. Verified with unit tests on the wrappers, line states and the debug output.
|
|
7
|
+
- The startup line `requireParent on; queries outside a span are not recorded` is gone. The first query actually dropped for lack of a parent span prints `[watchtower] dropped a DB query outside any span (requireParent on; WATCHTOWER_DB_REQUIRE_PARENT=0 to keep them)` once (the count is in the `WT_DEBUG` summary). Verified by a test that drops two queries and sees one line.
|
|
8
|
+
- `@watchtowerobservability/node/next` and `/next-build` are marked `@deprecated`: use `@watchtowerobservability/next` (`withWatchtower()` in next.config, `register` in `instrumentation.ts`, `npx wt-next-doctor` after `next build`). They work unchanged. The README gains a "Docker builds and source maps" note: pass the `ci:write` key with `--mount=type=secret`, never as a build `ARG`.
|
|
9
|
+
|
|
3
10
|
## 0.8.0 (2026-11-16)
|
|
4
11
|
|
|
5
12
|
- `init()` never throws. A missing OpenTelemetry package, a missing key or any startup error logs one `[watchtower] telemetry is OFF` warning (listing every missing package and the install command), leaves every helper a no-op and returns a no-op client, so the app boots. Under pnpm this fixes the crash at the first import of `main.ts`.
|
package/README.md
CHANGED
|
@@ -44,6 +44,13 @@ Pass `urlScrubbing: false` to record URLs as the instrumentation produced them.
|
|
|
44
44
|
|
|
45
45
|
## Auto-instrumentation and preload
|
|
46
46
|
|
|
47
|
+
The SDK prints one line once the first exports have gone out: `[watchtower] <service> → <host> traces:ok logs:ok metrics:ok release=<release>`
|
|
48
|
+
(`pending` until a signal has exported, `fail(<status>)` when it failed, `off` when switched off). `WT_DEBUG=1` (or `WATCHTOWER_DEBUG=1`)
|
|
49
|
+
also logs the exporter endpoints (the key as its first 8 characters only), every export result (signal, item count, HTTP status or error)
|
|
50
|
+
and a per-minute count of what the SDK dropped (Next.js internal spans under `nextInternals`, DB queries without a parent span).
|
|
51
|
+
If `http` or `https` was already imported when the SDK loaded (an ES module graph that imports `register` from app code links `http` first), it prints
|
|
52
|
+
`[watchtower] loaded too late: http was already imported, so its requests are not traced` once; start with `--import` instead.
|
|
53
|
+
|
|
47
54
|
`instrument: 'auto'` (or `WT_INSTRUMENT=auto`) also patches whichever of postgres.js, better-sqlite3 and mysql2
|
|
48
55
|
(`@opentelemetry/instrumentation-mysql2`) is installed, and prints one line (`[watchtower] instrumented: http, undici, pg, better-sqlite3`);
|
|
49
56
|
silence it with `instrumentLog: false` or `WT_INSTRUMENT_LOG=0`.
|
|
@@ -82,6 +89,13 @@ node --import @watchtowerobservability/node/register app.mjs # ESM app
|
|
|
82
89
|
|
|
83
90
|
## Next.js
|
|
84
91
|
|
|
92
|
+
Use **`@watchtowerobservability/next`**: `register` / `onRequestError` in `instrumentation.ts`, `withWatchtower()` in `next.config.mjs`
|
|
93
|
+
(`import { withWatchtower } from '@watchtowerobservability/next/config'`; `output: 'standalone'` is handled with no other config), and after
|
|
94
|
+
`next build` run `npx wt-next-doctor` to check that `.next/standalone` can load the SDK and its OpenTelemetry packages. See that package's README.
|
|
95
|
+
|
|
96
|
+
`@watchtowerobservability/node/next` (`makeRegister`, `register`, `withWatchtower`) and `@watchtowerobservability/node/next-build` are
|
|
97
|
+
deprecated (`@deprecated use @watchtowerobservability/next`). They keep working unchanged; the examples below still use them.
|
|
98
|
+
|
|
85
99
|
```ts
|
|
86
100
|
// instrumentation.ts
|
|
87
101
|
import { makeRegister } from '@watchtowerobservability/node/next';
|
|
@@ -94,12 +108,22 @@ own spans (those with a `next.span_type` attribute: load route module, prepare r
|
|
|
94
108
|
response, middleware, generateMetadata). Root (parentless) internals such as `LoadComponents.loadRouteModule` are sampled like the rest. Request, route handler, render, server action and fetch spans, all SERVER/CLIENT
|
|
95
109
|
spans and errored spans are always kept; children of a dropped internal span stay in the trace.
|
|
96
110
|
|
|
111
|
+
**Docker builds and source maps.** Pass the `ci:write` key to the build with a BuildKit secret, never as a build `ARG` (an `ARG` lands in the image history):
|
|
112
|
+
|
|
113
|
+
```dockerfile
|
|
114
|
+
RUN --mount=type=secret,id=wt_ci_key WT_API_KEY=$(cat /run/secrets/wt_ci_key) npx wt-next-sourcemaps
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
```sh
|
|
118
|
+
docker build --secret id=wt_ci_key,env=WT_CI_KEY .
|
|
119
|
+
```
|
|
120
|
+
|
|
97
121
|
**Source maps.** `next.config.js`: `module.exports = withWatchtower(nextConfig, { sourcemaps: true })` (from
|
|
98
122
|
`@watchtowerobservability/node/next`) turns on `productionBrowserSourceMaps`. Build with
|
|
99
123
|
`"build": "next build && wt-next-sourcemaps"`: the `wt-next-sourcemaps` bin (or `uploadSourcemaps()`) uploads every `.map` under
|
|
100
124
|
`.next/static` as `_next/static/<path>` for release `$WT_RELEASE` (the upload creates the release when it does not exist; it must equal
|
|
101
125
|
the browser SDK's `release`), with `$WT_API_KEY` and `$WT_PROJECT` (and `$WT_API_URL`, default `https://watchtowerops.net`; the old `$WT_API` still works with a warning), then deletes the `.map` files so they are
|
|
102
|
-
never served. Maps go up in one `POST /artifacts/bundle` request (a tar.gz plus manifest; about
|
|
126
|
+
never served. Maps go up in one `POST /artifacts/bundle` request (a tar.gz plus manifest; about 32 MB per request) and fall back to single uploads, 8 at a time, when the server has no bundle route. Requests retry 429/5xx with backoff (honoring `Retry-After`) and continue past failures; the run prints `{uploaded, skipped, failed}` (`skipped`: the server already had the same bytes, HTTP 200) and exits 1 when any failed, leaving the files. Each map is sent with `for=<chunk path>` read from the chunk's `//# sourceMappingURL=` comment or the map's `file` field. A wrong host fails at once with a message naming it. Bodies are sent gzipped. **Key scope: `ci:write`** (it covers releases and
|
|
103
127
|
artifacts; `admin:write` also works). Ingest keys cannot upload. Turbopack and webpack both emit these maps; Next does not inject
|
|
104
128
|
debug ids, so maps match by release and file name.
|
|
105
129
|
|
|
@@ -451,7 +475,7 @@ Development: `npm install`, `npm run typecheck`, `npm test` (vitest), `npm run b
|
|
|
451
475
|
|
|
452
476
|
### Datastore spans without a parent
|
|
453
477
|
|
|
454
|
-
With `requireParent` on, a query run outside any span is dropped. Each drop increments the counter `wt.sdk.db.dropped_spans` (exported with the SDK's metrics, readable in-process with `droppedDbSpans()`) and the first one
|
|
478
|
+
With `requireParent` on, a query run outside any span is dropped. Each drop increments the counter `wt.sdk.db.dropped_spans` (exported with the SDK's metrics, readable in-process with `droppedDbSpans()`) and the first one prints `[watchtower] dropped a DB query outside any span (requireParent on; WATCHTOWER_DB_REQUIRE_PARENT=0 to keep them)` (nothing is printed at startup; `WT_DEBUG=1` adds a per-minute count); a rising count means work (a cron, a worker) runs outside `observe`/a request span.
|
|
455
479
|
|
|
456
480
|
### Release detection order
|
|
457
481
|
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { SpanExporter } from '@opentelemetry/sdk-trace';
|
|
2
|
+
import type { LogRecordExporter } from '@opentelemetry/sdk-logs';
|
|
3
|
+
import type { PushMetricExporter } from '@opentelemetry/sdk-metrics';
|
|
4
|
+
export type Signal = 'traces' | 'logs' | 'metrics';
|
|
5
|
+
type Result = {
|
|
6
|
+
code: number;
|
|
7
|
+
error?: Error;
|
|
8
|
+
};
|
|
9
|
+
export declare const debugOn: () => boolean;
|
|
10
|
+
/** First 8 characters only. */
|
|
11
|
+
export declare const keyHint: (k: string) => string;
|
|
12
|
+
export declare const debug: (m: string) => void;
|
|
13
|
+
/** HTTP status or error text of a failed export (the OTLP exporters put the status in `code` or the message). */
|
|
14
|
+
export declare function failure(e: (Error & {
|
|
15
|
+
code?: unknown;
|
|
16
|
+
}) | undefined): string;
|
|
17
|
+
export declare class StatusLine {
|
|
18
|
+
private readonly o;
|
|
19
|
+
private readonly out;
|
|
20
|
+
private st;
|
|
21
|
+
private printed;
|
|
22
|
+
constructor(o: {
|
|
23
|
+
service: string;
|
|
24
|
+
endpoint: string;
|
|
25
|
+
release?: string;
|
|
26
|
+
off?: Signal[];
|
|
27
|
+
}, out?: (m: string) => void);
|
|
28
|
+
/** One result for `signal`: the first failure and the last pending signal turning ok both print the line. */
|
|
29
|
+
record(signal: Signal, items: number, r: Result): void;
|
|
30
|
+
print(): void;
|
|
31
|
+
}
|
|
32
|
+
export declare const watchSpans: (e: SpanExporter, l: StatusLine) => SpanExporter;
|
|
33
|
+
export declare const watchLogs: (e: LogRecordExporter, l: StatusLine) => LogRecordExporter;
|
|
34
|
+
export declare const watchMetrics: (e: PushMetricExporter, l: StatusLine) => PushMetricExporter;
|
|
35
|
+
export declare function noteDrop(kind: string): void;
|
|
36
|
+
export declare function flushDrops(): void;
|
|
37
|
+
export {};
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.watchMetrics = exports.watchLogs = exports.watchSpans = exports.StatusLine = exports.debug = exports.keyHint = exports.debugOn = void 0;
|
|
4
|
+
exports.failure = failure;
|
|
5
|
+
exports.noteDrop = noteDrop;
|
|
6
|
+
exports.flushDrops = flushDrops;
|
|
7
|
+
const debugOn = () => ['1', 'true', 'on', 'yes'].includes((process.env.WT_DEBUG ?? process.env.WATCHTOWER_DEBUG ?? '').trim().toLowerCase());
|
|
8
|
+
exports.debugOn = debugOn;
|
|
9
|
+
/** First 8 characters only. */
|
|
10
|
+
const keyHint = (k) => `${k.slice(0, 8)}…`;
|
|
11
|
+
exports.keyHint = keyHint;
|
|
12
|
+
const debug = (m) => { if ((0, exports.debugOn)())
|
|
13
|
+
console.info(`[watchtower:debug] ${m}`); };
|
|
14
|
+
exports.debug = debug;
|
|
15
|
+
/** HTTP status or error text of a failed export (the OTLP exporters put the status in `code` or the message). */
|
|
16
|
+
function failure(e) {
|
|
17
|
+
const m = /\bstatus(?: code)?:? (\d{3})\b/i.exec(e?.message ?? '');
|
|
18
|
+
return String((typeof e?.code === 'number' ? e.code : undefined) ?? m?.[1] ?? e?.message ?? 'error').split('\n')[0].slice(0, 80);
|
|
19
|
+
}
|
|
20
|
+
const quiet = () => process.env.NODE_ENV === 'test' && !(0, exports.debugOn)();
|
|
21
|
+
class StatusLine {
|
|
22
|
+
o;
|
|
23
|
+
out;
|
|
24
|
+
st;
|
|
25
|
+
printed = false;
|
|
26
|
+
constructor(o, out = (m) => { if (!quiet())
|
|
27
|
+
console.info(m); }) {
|
|
28
|
+
this.o = o;
|
|
29
|
+
this.out = out;
|
|
30
|
+
this.st = { traces: 'pending', logs: 'pending', metrics: 'pending' };
|
|
31
|
+
for (const s of o.off ?? [])
|
|
32
|
+
this.st[s] = 'off';
|
|
33
|
+
// a signal that never fires (no logs yet, metrics every 60 s) must not hide the line forever
|
|
34
|
+
const t = setTimeout(() => this.print(), 90_000);
|
|
35
|
+
t.unref?.();
|
|
36
|
+
}
|
|
37
|
+
/** One result for `signal`: the first failure and the last pending signal turning ok both print the line. */
|
|
38
|
+
record(signal, items, r) {
|
|
39
|
+
const fail = r.code !== 0;
|
|
40
|
+
const why = fail ? failure(r.error) : '';
|
|
41
|
+
(0, exports.debug)(`export ${signal} items=${items} ${fail ? `fail(${why})` : 'ok'}`);
|
|
42
|
+
if (fail) {
|
|
43
|
+
if (this.st[signal] !== 'ok')
|
|
44
|
+
this.st[signal] = `fail(${why})`;
|
|
45
|
+
this.print();
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
this.st[signal] = 'ok';
|
|
49
|
+
if (Object.values(this.st).every((s) => s !== 'pending'))
|
|
50
|
+
this.print();
|
|
51
|
+
}
|
|
52
|
+
print() {
|
|
53
|
+
if (this.printed)
|
|
54
|
+
return;
|
|
55
|
+
this.printed = true;
|
|
56
|
+
let host = this.o.endpoint;
|
|
57
|
+
try {
|
|
58
|
+
host = new URL(this.o.endpoint).host;
|
|
59
|
+
}
|
|
60
|
+
catch { /* keep as given */ }
|
|
61
|
+
const s = this.st;
|
|
62
|
+
this.out(`[watchtower] ${this.o.service} → ${host} traces:${s.traces} logs:${s.logs} metrics:${s.metrics} release=${this.o.release ?? 'none'}`);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
exports.StatusLine = StatusLine;
|
|
66
|
+
const countMetrics = (m) => (m?.scopeMetrics ?? []).reduce((n, s) => n + s.metrics.length, 0);
|
|
67
|
+
function watch(inner, signal, line, count) {
|
|
68
|
+
const wrapped = Object.create(inner); // keeps every other exporter method (selectAggregation etc.)
|
|
69
|
+
wrapped.export = (items, done) => inner.export(items, (r) => { line.record(signal, count(items), r); done(r); });
|
|
70
|
+
return wrapped;
|
|
71
|
+
}
|
|
72
|
+
const watchSpans = (e, l) => watch(e, 'traces', l, (i) => i.length);
|
|
73
|
+
exports.watchSpans = watchSpans;
|
|
74
|
+
const watchLogs = (e, l) => watch(e, 'logs', l, (i) => i.length);
|
|
75
|
+
exports.watchLogs = watchLogs;
|
|
76
|
+
const watchMetrics = (e, l) => watch(e, 'metrics', l, countMetrics);
|
|
77
|
+
exports.watchMetrics = watchMetrics;
|
|
78
|
+
// Drop counters: Next-internal spans (sampling) and DB queries without a parent span. Summarised per minute under WT_DEBUG.
|
|
79
|
+
const drops = new Map();
|
|
80
|
+
let timer;
|
|
81
|
+
function noteDrop(kind) {
|
|
82
|
+
drops.set(kind, (drops.get(kind) ?? 0) + 1);
|
|
83
|
+
if (!timer && (0, exports.debugOn)()) {
|
|
84
|
+
timer = setInterval(flushDrops, 60_000);
|
|
85
|
+
timer.unref?.();
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
function flushDrops() {
|
|
89
|
+
if (drops.size)
|
|
90
|
+
(0, exports.debug)(`dropped in the last minute: ${[...drops].map(([k, n]) => `${n} ${k}`).join(', ')}`);
|
|
91
|
+
drops.clear();
|
|
92
|
+
}
|
package/dist/cjs/index.js
CHANGED
|
@@ -39,6 +39,7 @@ exports.safeResource = safeResource;
|
|
|
39
39
|
exports.init = init;
|
|
40
40
|
// Thin Watchtower layer over the OpenTelemetry Node SDK: key header, endpoint default,
|
|
41
41
|
// offline buffer, wt.*-safe resource attributes, redaction hook, getPrompt/score/evaluate/observe.
|
|
42
|
+
const late_js_1 = require("./late.js"); // first: snapshots which builtins were loaded before the SDK
|
|
42
43
|
const node_util_1 = require("node:util");
|
|
43
44
|
const api_1 = require("@opentelemetry/api");
|
|
44
45
|
Object.defineProperty(exports, "metrics", { enumerable: true, get: function () { return api_1.metrics; } });
|
|
@@ -53,6 +54,7 @@ const attach_js_1 = require("./attach.js");
|
|
|
53
54
|
const scrub_js_1 = require("./scrub.js");
|
|
54
55
|
const filter_js_1 = require("./filter.js");
|
|
55
56
|
const next_filter_js_1 = require("./next-filter.js");
|
|
57
|
+
const diagnostics_js_1 = require("./diagnostics.js");
|
|
56
58
|
const checkin_js_1 = require("./checkin.js");
|
|
57
59
|
const monitor_js_1 = require("./cron/monitor.js");
|
|
58
60
|
const shutdown_js_1 = require("./shutdown.js");
|
|
@@ -154,6 +156,11 @@ class Client {
|
|
|
154
156
|
this.redact = red.hook;
|
|
155
157
|
this.scrubUrls = o.urlScrubbing ?? red.preset !== 'off';
|
|
156
158
|
this.logCaller = o.logCaller ?? env.WATCHTOWER_LOG_CALLER === '1';
|
|
159
|
+
const logsOn = (0, metrics_js_1.switchOn)('WATCHTOWER_LOGS', 'OTEL_LOGS_EXPORTER', o.logs ?? (o.logExporter ? true : undefined));
|
|
160
|
+
const metricsOn = (0, metrics_js_1.switchOn)('WATCHTOWER_METRICS', 'OTEL_METRICS_EXPORTER', o.metrics ?? (o.metricExporter ? true : undefined));
|
|
161
|
+
// one status line per process, fed by the default OTLP exporters (explicit test exporters are left alone)
|
|
162
|
+
const line = new diagnostics_js_1.StatusLine({ service: String(resource.attributes['service.name']), endpoint: this.endpoint, release, off: [...(logsOn ? [] : ['logs']), ...(metricsOn ? [] : ['metrics'])] });
|
|
163
|
+
(0, diagnostics_js_1.debug)(`exporters: ${this.endpoint}/v1/traces, /v1/logs, /v1/metrics key=${(0, diagnostics_js_1.keyHint)(apiKey)}`);
|
|
157
164
|
let exporter = o.exporter;
|
|
158
165
|
if (!exporter) {
|
|
159
166
|
const url = `${this.endpoint}/v1/traces`;
|
|
@@ -162,6 +169,7 @@ class Client {
|
|
|
162
169
|
// spans and log records spool to their own subdirectories
|
|
163
170
|
if (o.bufferDir)
|
|
164
171
|
exporter = new buffer_js_1.SpoolExporter(exporter, nodePath.join(o.bufferDir, 'traces'), url, this.headers, this.fetch);
|
|
172
|
+
exporter = (0, diagnostics_js_1.watchSpans)(exporter, line);
|
|
165
173
|
}
|
|
166
174
|
const keepNoisy = o.noisySpans ?? env.WT_NOISY_SPANS === '1';
|
|
167
175
|
const user = o.spanFilter;
|
|
@@ -199,7 +207,6 @@ class Client {
|
|
|
199
207
|
}
|
|
200
208
|
this.tracer = this.provider.getTracer('watchtower');
|
|
201
209
|
// an explicit exporter never switches the other signals off: only `logs` / `metrics` / the env switches do
|
|
202
|
-
const logsOn = (0, metrics_js_1.switchOn)('WATCHTOWER_LOGS', 'OTEL_LOGS_EXPORTER', o.logs ?? (o.logExporter ? true : undefined));
|
|
203
210
|
this.logs = logsOn ? 'ok' : 'disabled';
|
|
204
211
|
let logExporter = logsOn ? o.logExporter : undefined;
|
|
205
212
|
if (logsOn && !logExporter) {
|
|
@@ -208,6 +215,7 @@ class Client {
|
|
|
208
215
|
logExporter = new OTLPLogExporter({ url, headers: this.headers });
|
|
209
216
|
if (o.bufferDir)
|
|
210
217
|
logExporter = (0, buffer_js_1.spoolLogs)(logExporter, nodePath.join(o.bufferDir, 'logs'), url, this.headers, this.fetch);
|
|
218
|
+
logExporter = (0, diagnostics_js_1.watchLogs)(logExporter, line);
|
|
211
219
|
}
|
|
212
220
|
const { LoggerProvider: LP, BatchLogRecordProcessor } = (0, load_js_1.need)('@opentelemetry/sdk-logs');
|
|
213
221
|
this.loggerProvider = new LP({
|
|
@@ -215,8 +223,8 @@ class Client {
|
|
|
215
223
|
processors: !logExporter ? [] : [new BatchLogRecordProcessor({ exporter: logExporter })],
|
|
216
224
|
});
|
|
217
225
|
this.logger = this.loggerProvider.getLogger('watchtower');
|
|
218
|
-
if (
|
|
219
|
-
const m = (0, metrics_js_1.startMetrics)(this.endpoint, this.headers, resource, o.bufferDir, this.fetch, o.metricExporter);
|
|
226
|
+
if (metricsOn) {
|
|
227
|
+
const m = (0, metrics_js_1.startMetrics)(this.endpoint, this.headers, resource, o.bufferDir, this.fetch, o.metricExporter, (e) => (0, diagnostics_js_1.watchMetrics)(e, line));
|
|
220
228
|
this.meterProvider = m.provider;
|
|
221
229
|
this.stopRuntime = m.stop;
|
|
222
230
|
}
|
|
@@ -436,10 +444,12 @@ function turnOff(why) {
|
|
|
436
444
|
return offClient();
|
|
437
445
|
}
|
|
438
446
|
function start(opts) {
|
|
447
|
+
(0, late_js_1.checkLate)();
|
|
439
448
|
(0, env_js_1.defaultResourceDetectors)(); // before any NodeSDK reads OTEL_NODE_RESOURCE_DETECTORS
|
|
440
449
|
const nextMode = opts?.nextInternals ?? (process.env.NEXT_RUNTIME ? 'sample' : undefined);
|
|
441
450
|
if (nextMode) {
|
|
442
|
-
const
|
|
451
|
+
const base = (0, next_filter_js_1.nextInternalsFilter)(nextMode, opts?.nextInternalsRate);
|
|
452
|
+
const own = (s) => base(s) || ((0, diagnostics_js_1.noteDrop)('Next.js internal spans (nextInternals sampling)'), false);
|
|
443
453
|
const user = opts.spanFilter;
|
|
444
454
|
opts = { ...opts, nextInternals: undefined, spanFilter: user ? (s) => own(s) && user(s) : own }; // cleared: a second init() never stacks the filter
|
|
445
455
|
}
|
|
@@ -458,9 +468,6 @@ function start(opts) {
|
|
|
458
468
|
if (mode === 'auto' && logOn) {
|
|
459
469
|
console.info(`[watchtower] instrumented: ${names.map((n) => n.replace('@opentelemetry/instrumentation-', '')).join(', ') || 'nothing (no supported package found)'}`);
|
|
460
470
|
}
|
|
461
|
-
if (logOn && (0, db_js_1.dbRequireParent)(undefined)) {
|
|
462
|
-
console.info('watchtower: requireParent on; queries outside a span are not recorded (WATCHTOWER_DB_REQUIRE_PARENT=0 to keep them)');
|
|
463
|
-
}
|
|
464
471
|
}
|
|
465
472
|
if (process.env.WT_PROFILING === '1') {
|
|
466
473
|
const attrs = c.resource.attributes;
|
|
@@ -51,6 +51,7 @@ exports.sizeOf = sizeOf;
|
|
|
51
51
|
const fs = __importStar(require("node:fs"));
|
|
52
52
|
const nodePath = __importStar(require("node:path"));
|
|
53
53
|
const api_1 = require("@opentelemetry/api");
|
|
54
|
+
const diagnostics_js_1 = require("../diagnostics.js");
|
|
54
55
|
const sql_js_1 = require("../sql.js");
|
|
55
56
|
/** Set inside an instrumented call so a wrapper the library calls internally adds no second span. */
|
|
56
57
|
const INSIDE = (0, api_1.createContextKey)('watchtower.db.inside');
|
|
@@ -95,10 +96,11 @@ let droppedCounter;
|
|
|
95
96
|
/** Datastore spans dropped so far because `requireParent` found no active parent span. */
|
|
96
97
|
const droppedDbSpans = () => droppedSpans;
|
|
97
98
|
exports.droppedDbSpans = droppedDbSpans;
|
|
98
|
-
/** Count a dropped span: the `wt.sdk.db.dropped_spans` counter (exported with the SDK's metrics) and one
|
|
99
|
+
/** Count a dropped span: the `wt.sdk.db.dropped_spans` counter (exported with the SDK's metrics) and one console line (the first drop). */
|
|
99
100
|
function dropped() {
|
|
100
101
|
if (droppedSpans++ === 0)
|
|
101
|
-
|
|
102
|
+
console.info('[watchtower] dropped a DB query outside any span (requireParent on; WATCHTOWER_DB_REQUIRE_PARENT=0 to keep them)');
|
|
103
|
+
(0, diagnostics_js_1.noteDrop)('DB queries outside any span');
|
|
102
104
|
droppedCounter ??= api_1.metrics.getMeter('watchtower').createCounter('wt.sdk.db.dropped_spans', { description: 'Datastore spans dropped for lack of a parent span (requireParent)' });
|
|
103
105
|
droppedCounter.add(1);
|
|
104
106
|
return api_1.trace.wrapSpanContext(api_1.INVALID_SPAN_CONTEXT);
|
|
@@ -51,16 +51,18 @@ export declare function tracingIncludes(ids: string[], cwd?: string): string[];
|
|
|
51
51
|
* the SDK starts whichever entry instrumentation imports. Sets `NEXT_PUBLIC_WT_RELEASE`. With `sourcemaps` it turns on
|
|
52
52
|
* `productionBrowserSourceMaps` (webpack and Turbopack); `{ upload: true }` uploads and deletes them after the webpack
|
|
53
53
|
* client build, otherwise run `wt-next-sourcemaps` after `next build` (`"build": "next build && wt-next-sourcemaps"`).
|
|
54
|
+
* @deprecated use `withWatchtower` from `@watchtowerobservability/next`
|
|
54
55
|
*/
|
|
55
56
|
export declare function withWatchtower(config?: ConfigOrFn, opts?: WatchtowerNextOptions): ConfigOrFn;
|
|
56
57
|
/** A ustar archive of `[name, bytes]` (names up to 100 bytes). */
|
|
57
58
|
export declare function makeTar(files: [string, Buffer][]): Buffer;
|
|
58
59
|
/**
|
|
59
|
-
* Upload every `.map` under `dir` as `_next/static/<path>` for the release: one `POST /artifacts/bundle` per ~
|
|
60
|
+
* Upload every `.map` under `dir` as `_next/static/<path>` for the release: one `POST /artifacts/bundle` per ~32 MB
|
|
60
61
|
* batch (tar.gz plus manifest), falling back to single uploads (8 at a time) when the server has no bundle route.
|
|
61
62
|
* 429/5xx are retried with backoff honoring Retry-After; a failed map does not stop the others. The maps are deleted when none failed. Returns
|
|
62
63
|
* `{uploaded, skipped, failed}`: `skipped` = the server already had those exact bytes (HTTP 200). Bodies are sent
|
|
63
64
|
* gzipped (`Content-Encoding: gzip`).
|
|
65
|
+
* @deprecated use `@watchtowerobservability/next`
|
|
64
66
|
*/
|
|
65
67
|
export declare function uploadSourcemaps(o?: SourcemapOptions): Promise<{
|
|
66
68
|
uploaded: number;
|
|
@@ -39,6 +39,7 @@ exports.tracingIncludes = tracingIncludes;
|
|
|
39
39
|
exports.withWatchtower = withWatchtower;
|
|
40
40
|
exports.makeTar = makeTar;
|
|
41
41
|
exports.uploadSourcemaps = uploadSourcemaps;
|
|
42
|
+
// Deprecated entry (`@watchtowerobservability/node/next-build`): use `@watchtowerobservability/next`. Still works unchanged.
|
|
42
43
|
// Build-time helpers for Next.js: `withWatchtower` (next.config) and `uploadSourcemaps` (after `next build`).
|
|
43
44
|
const fs = __importStar(require("node:fs"));
|
|
44
45
|
const nodePath = __importStar(require("node:path"));
|
|
@@ -123,6 +124,7 @@ const SHA_ENV = ['WT_RELEASE', 'GITHUB_SHA', 'CI_COMMIT_SHA', 'VERCEL_GIT_COMMIT
|
|
|
123
124
|
* the SDK starts whichever entry instrumentation imports. Sets `NEXT_PUBLIC_WT_RELEASE`. With `sourcemaps` it turns on
|
|
124
125
|
* `productionBrowserSourceMaps` (webpack and Turbopack); `{ upload: true }` uploads and deletes them after the webpack
|
|
125
126
|
* client build, otherwise run `wt-next-sourcemaps` after `next build` (`"build": "next build && wt-next-sourcemaps"`).
|
|
127
|
+
* @deprecated use `withWatchtower` from `@watchtowerobservability/next`
|
|
126
128
|
*/
|
|
127
129
|
function withWatchtower(config = {}, opts = {}) {
|
|
128
130
|
const sm = opts.sourcemaps === true ? {} : opts.sourcemaps || undefined;
|
|
@@ -218,11 +220,12 @@ function chunkFor(mapFile, name) {
|
|
|
218
220
|
return undefined;
|
|
219
221
|
}
|
|
220
222
|
/**
|
|
221
|
-
* Upload every `.map` under `dir` as `_next/static/<path>` for the release: one `POST /artifacts/bundle` per ~
|
|
223
|
+
* Upload every `.map` under `dir` as `_next/static/<path>` for the release: one `POST /artifacts/bundle` per ~32 MB
|
|
222
224
|
* batch (tar.gz plus manifest), falling back to single uploads (8 at a time) when the server has no bundle route.
|
|
223
225
|
* 429/5xx are retried with backoff honoring Retry-After; a failed map does not stop the others. The maps are deleted when none failed. Returns
|
|
224
226
|
* `{uploaded, skipped, failed}`: `skipped` = the server already had those exact bytes (HTTP 200). Bodies are sent
|
|
225
227
|
* gzipped (`Content-Encoding: gzip`).
|
|
228
|
+
* @deprecated use `@watchtowerobservability/next`
|
|
226
229
|
*/
|
|
227
230
|
async function uploadSourcemaps(o = {}) {
|
|
228
231
|
const env = process.env;
|
|
@@ -306,7 +309,7 @@ async function uploadSourcemaps(o = {}) {
|
|
|
306
309
|
};
|
|
307
310
|
// One request per batch (tar.gz + manifest). A server without the bundle route (or a request that
|
|
308
311
|
// never got through) falls back to concurrent single uploads for that batch.
|
|
309
|
-
const BATCH_BYTES =
|
|
312
|
+
const BATCH_BYTES = 32 * 1024 * 1024; // smaller requests keep the API's upload memory low
|
|
310
313
|
const batches = [];
|
|
311
314
|
let cur = [], curBytes = 0;
|
|
312
315
|
for (const e of entries) {
|
|
@@ -2,8 +2,12 @@ type Opts = Record<string, unknown>;
|
|
|
2
2
|
export type NextOptions = Opts;
|
|
3
3
|
export type SourcemapOptions = Opts;
|
|
4
4
|
export type TunnelOptions = Opts;
|
|
5
|
+
/** @deprecated use `@watchtowerobservability/next` */
|
|
5
6
|
export declare const makeRegister: (_options?: NextOptions) => (() => Promise<void>);
|
|
7
|
+
/** @deprecated use `@watchtowerobservability/next` */
|
|
6
8
|
export declare const register: () => Promise<void>;
|
|
9
|
+
/** @deprecated use `@watchtowerobservability/next` */
|
|
7
10
|
export declare function onRequestError(_err?: unknown, _request?: unknown, _context?: unknown): Promise<void>;
|
|
11
|
+
/** @deprecated use `@watchtowerobservability/next` */
|
|
8
12
|
export declare const withWatchtower: <T>(config: T, _opts?: Opts) => T;
|
|
9
13
|
export {};
|
|
@@ -2,9 +2,13 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.withWatchtower = exports.register = exports.makeRegister = void 0;
|
|
4
4
|
exports.onRequestError = onRequestError;
|
|
5
|
+
/** @deprecated use `@watchtowerobservability/next` */
|
|
5
6
|
const makeRegister = (_options = {}) => async () => { };
|
|
6
7
|
exports.makeRegister = makeRegister;
|
|
8
|
+
/** @deprecated use `@watchtowerobservability/next` */
|
|
7
9
|
exports.register = (0, exports.makeRegister)();
|
|
10
|
+
/** @deprecated use `@watchtowerobservability/next` */
|
|
8
11
|
async function onRequestError(_err, _request, _context) { }
|
|
12
|
+
/** @deprecated use `@watchtowerobservability/next` */
|
|
9
13
|
const withWatchtower = (config, _opts) => config;
|
|
10
14
|
exports.withWatchtower = withWatchtower;
|
|
@@ -1,15 +1,22 @@
|
|
|
1
1
|
import * as wt from '../index.js';
|
|
2
|
-
|
|
2
|
+
import * as build from './next-build.js';
|
|
3
|
+
/** @deprecated use `withWatchtower` from `@watchtowerobservability/next` */
|
|
4
|
+
export declare const withWatchtower: typeof build.withWatchtower;
|
|
5
|
+
/** @deprecated use `uploadSourcemaps` from `@watchtowerobservability/next` */
|
|
6
|
+
export declare const uploadSourcemaps: typeof build.uploadSourcemaps;
|
|
3
7
|
export type { SourcemapOptions } from './next-build.js';
|
|
4
8
|
export { isNextInternal, nextInternalsFilter } from '../next-filter.js';
|
|
5
9
|
export { tunnelHandler } from './next-tunnel.js';
|
|
6
10
|
export type { TunnelOptions } from './next-tunnel.js';
|
|
7
11
|
export type NextOptions = wt.InitOptions;
|
|
8
|
-
/**
|
|
12
|
+
/** @deprecated use `register` from `@watchtowerobservability/next`.
|
|
13
|
+
* Build a Next.js instrumentation `register` that passes `options` to `init`; no-op off the Node.js runtime or without a key. */
|
|
9
14
|
export declare function makeRegister(options?: NextOptions): () => Promise<void>;
|
|
10
|
-
/**
|
|
15
|
+
/** @deprecated use `register` from `@watchtowerobservability/next`.
|
|
16
|
+
* Next.js instrumentation hook: init from WT_* env on the Node.js runtime; no-op without WT_INGEST_KEY. */
|
|
11
17
|
export declare const register: () => Promise<void>;
|
|
12
|
-
/**
|
|
18
|
+
/** @deprecated use `onRequestError` from `@watchtowerobservability/next`.
|
|
19
|
+
* Next.js onRequestError: server render, route handler and server action errors. */
|
|
13
20
|
export declare function onRequestError(err: unknown, request?: {
|
|
14
21
|
path?: string;
|
|
15
22
|
method?: string;
|
|
@@ -36,18 +36,22 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
36
36
|
exports.register = exports.tunnelHandler = exports.nextInternalsFilter = exports.isNextInternal = exports.uploadSourcemaps = exports.withWatchtower = void 0;
|
|
37
37
|
exports.makeRegister = makeRegister;
|
|
38
38
|
exports.onRequestError = onRequestError;
|
|
39
|
+
// Deprecated entry: use `@watchtowerobservability/next` (register, onRequestError, withWatchtower). Still works unchanged.
|
|
39
40
|
// instrumentation.js: module.exports = require('@watchtowerobservability/node/next');
|
|
40
41
|
// or, with options: export const register = makeRegister({ redact }); export { onRequestError } from '@watchtowerobservability/node/next';
|
|
41
42
|
const wt = __importStar(require("../index.js"));
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
43
|
+
const build = __importStar(require("./next-build.js"));
|
|
44
|
+
/** @deprecated use `withWatchtower` from `@watchtowerobservability/next` */
|
|
45
|
+
exports.withWatchtower = build.withWatchtower;
|
|
46
|
+
/** @deprecated use `uploadSourcemaps` from `@watchtowerobservability/next` */
|
|
47
|
+
exports.uploadSourcemaps = build.uploadSourcemaps;
|
|
45
48
|
var next_filter_js_1 = require("../next-filter.js");
|
|
46
49
|
Object.defineProperty(exports, "isNextInternal", { enumerable: true, get: function () { return next_filter_js_1.isNextInternal; } });
|
|
47
50
|
Object.defineProperty(exports, "nextInternalsFilter", { enumerable: true, get: function () { return next_filter_js_1.nextInternalsFilter; } });
|
|
48
51
|
var next_tunnel_js_1 = require("./next-tunnel.js");
|
|
49
52
|
Object.defineProperty(exports, "tunnelHandler", { enumerable: true, get: function () { return next_tunnel_js_1.tunnelHandler; } });
|
|
50
|
-
/**
|
|
53
|
+
/** @deprecated use `register` from `@watchtowerobservability/next`.
|
|
54
|
+
* Build a Next.js instrumentation `register` that passes `options` to `init`; no-op off the Node.js runtime or without a key. */
|
|
51
55
|
function makeRegister(options = {}) {
|
|
52
56
|
return async function register() {
|
|
53
57
|
const rt = process.env.NEXT_RUNTIME;
|
|
@@ -56,9 +60,11 @@ function makeRegister(options = {}) {
|
|
|
56
60
|
wt.init({ ...options, nextInternals: options.nextInternals ?? 'sample' }); // init() applies the filter (once)
|
|
57
61
|
};
|
|
58
62
|
}
|
|
59
|
-
/**
|
|
63
|
+
/** @deprecated use `register` from `@watchtowerobservability/next`.
|
|
64
|
+
* Next.js instrumentation hook: init from WT_* env on the Node.js runtime; no-op without WT_INGEST_KEY. */
|
|
60
65
|
exports.register = makeRegister();
|
|
61
|
-
/**
|
|
66
|
+
/** @deprecated use `onRequestError` from `@watchtowerobservability/next`.
|
|
67
|
+
* Next.js onRequestError: server render, route handler and server action errors. */
|
|
62
68
|
async function onRequestError(err, request, context) {
|
|
63
69
|
const c = context || {};
|
|
64
70
|
wt.captureException(err, {
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** Which of http/https are in `list` (default: this process's loaded builtins). */
|
|
2
|
+
export declare const lateModules: (list?: readonly string[]) => string[];
|
|
3
|
+
export declare const LATE_HINT = "Start node with --import @watchtowerobservability/node/register";
|
|
4
|
+
/** Prints once per process (global flag, so the CJS and ESM copies share it). */
|
|
5
|
+
export declare function warnLate(mods: string[], out?: (m: string) => void): void;
|
|
6
|
+
/** The entry points call this: silent under Next (it loads http before instrumentation runs) and in test runners. */
|
|
7
|
+
export declare function checkLate(): void;
|
package/dist/cjs/late.js
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.LATE_HINT = exports.lateModules = void 0;
|
|
4
|
+
exports.warnLate = warnLate;
|
|
5
|
+
exports.checkLate = checkLate;
|
|
6
|
+
// "Loaded too late" detector. Import this FIRST in the entry modules (register.ts, index.ts): ES imports evaluate in order, so
|
|
7
|
+
// the snapshot below is taken before the SDK's own dependencies load anything. Under `node --import .../register` nothing
|
|
8
|
+
// but Node's bootstrap has run yet, so http/https are absent from process.moduleLoadList (checked on Node 26).
|
|
9
|
+
/** Which of http/https are in `list` (default: this process's loaded builtins). */
|
|
10
|
+
const lateModules = (list = process.moduleLoadList ?? []) => ['http', 'https'].filter((m) => list.includes(`NativeModule ${m}`));
|
|
11
|
+
exports.lateModules = lateModules;
|
|
12
|
+
const early = (0, exports.lateModules)();
|
|
13
|
+
const KEY = Symbol.for('watchtower.node.late-warned');
|
|
14
|
+
exports.LATE_HINT = 'Start node with --import @watchtowerobservability/node/register';
|
|
15
|
+
/** Prints once per process (global flag, so the CJS and ESM copies share it). */
|
|
16
|
+
function warnLate(mods, out = (m) => console.warn(m)) {
|
|
17
|
+
const g = globalThis;
|
|
18
|
+
if (!mods.length || g[KEY])
|
|
19
|
+
return;
|
|
20
|
+
g[KEY] = true;
|
|
21
|
+
out(`[watchtower] loaded too late: ${mods[0]} was already imported, so its requests are not traced. ${exports.LATE_HINT}`);
|
|
22
|
+
}
|
|
23
|
+
/** The entry points call this: silent under Next (it loads http before instrumentation runs) and in test runners. */
|
|
24
|
+
function checkLate() {
|
|
25
|
+
if (process.env.NEXT_RUNTIME || process.env.NODE_ENV === 'test' || process.env.VITEST)
|
|
26
|
+
return;
|
|
27
|
+
warnLate(early);
|
|
28
|
+
}
|
package/dist/cjs/metrics.d.ts
CHANGED
|
@@ -6,4 +6,4 @@ export interface Metrics {
|
|
|
6
6
|
provider: MeterProvider;
|
|
7
7
|
stop(): void;
|
|
8
8
|
}
|
|
9
|
-
export declare function startMetrics(endpoint: string, headers: Record<string, string>, resource: Resource, bufferDir: string | undefined, fetch: typeof globalThis.fetch, exporter?: PushMetricExporter): Metrics;
|
|
9
|
+
export declare function startMetrics(endpoint: string, headers: Record<string, string>, resource: Resource, bufferDir: string | undefined, fetch: typeof globalThis.fetch, exporter?: PushMetricExporter, wrap?: (e: PushMetricExporter) => PushMetricExporter): Metrics;
|
package/dist/cjs/metrics.js
CHANGED
|
@@ -51,7 +51,7 @@ function switchOn(name, otelExporterEnv, flag) {
|
|
|
51
51
|
return false;
|
|
52
52
|
return !['off', 'false', '0', 'no'].includes((env[name] || 'on').trim().toLowerCase());
|
|
53
53
|
}
|
|
54
|
-
function startMetrics(endpoint, headers, resource, bufferDir, fetch, exporter) {
|
|
54
|
+
function startMetrics(endpoint, headers, resource, bufferDir, fetch, exporter, wrap) {
|
|
55
55
|
const sdk = (0, load_js_1.need)('@opentelemetry/sdk-metrics');
|
|
56
56
|
const url = `${endpoint}/v1/metrics`;
|
|
57
57
|
let exp = exporter;
|
|
@@ -62,6 +62,8 @@ function startMetrics(endpoint, headers, resource, bufferDir, fetch, exporter) {
|
|
|
62
62
|
exp = new OTLPMetricExporter({ url, headers, ...delta });
|
|
63
63
|
if (bufferDir)
|
|
64
64
|
exp = new buffer_js_1.MetricSpool(exp, nodePath.join(bufferDir, 'metrics'), url, headers, fetch);
|
|
65
|
+
if (wrap)
|
|
66
|
+
exp = wrap(exp);
|
|
65
67
|
}
|
|
66
68
|
const interval = Number(process.env.OTEL_METRIC_EXPORT_INTERVAL) || 60000;
|
|
67
69
|
const reader = new sdk.PeriodicExportingMetricReader({
|
package/dist/cjs/register.js
CHANGED
|
@@ -3,10 +3,12 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
// Preload entry: `node --import @watchtowerobservability/node/register app.mjs` (ESM) or `node -r @watchtowerobservability/node/register app.js` (CommonJS).
|
|
4
4
|
// Starts the SDK from WT_*/OTEL_* env before the app loads, so http, fetch, pg and ioredis are patched in time.
|
|
5
5
|
// Without WT_INGEST_KEY it starts nothing and says so.
|
|
6
|
+
const late_js_1 = require("./late.js"); // first: snapshots which builtins were loaded before the SDK
|
|
6
7
|
const node_url_1 = require("node:url");
|
|
7
8
|
const node_module_1 = require("node:module");
|
|
8
9
|
const index_js_1 = require("./index.js");
|
|
9
10
|
const load_js_1 = require("./load.js");
|
|
11
|
+
(0, late_js_1.checkLate)();
|
|
10
12
|
if (process.env.WT_INGEST_KEY || process.env.OTEL_EXPORTER_OTLP_HEADERS) {
|
|
11
13
|
try {
|
|
12
14
|
// ESM modules (node:http imported from an ES module) are only patched through OpenTelemetry's loader hook
|
package/dist/cjs/version.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/** This package's version (test/distro.test.ts checks it against package.json); sent as `telemetry.distro.version`. */
|
|
2
|
-
export declare const VERSION = "0.8.
|
|
2
|
+
export declare const VERSION = "0.8.1";
|
package/dist/cjs/version.js
CHANGED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { SpanExporter } from '@opentelemetry/sdk-trace';
|
|
2
|
+
import type { LogRecordExporter } from '@opentelemetry/sdk-logs';
|
|
3
|
+
import type { PushMetricExporter } from '@opentelemetry/sdk-metrics';
|
|
4
|
+
export type Signal = 'traces' | 'logs' | 'metrics';
|
|
5
|
+
type Result = {
|
|
6
|
+
code: number;
|
|
7
|
+
error?: Error;
|
|
8
|
+
};
|
|
9
|
+
export declare const debugOn: () => boolean;
|
|
10
|
+
/** First 8 characters only. */
|
|
11
|
+
export declare const keyHint: (k: string) => string;
|
|
12
|
+
export declare const debug: (m: string) => void;
|
|
13
|
+
/** HTTP status or error text of a failed export (the OTLP exporters put the status in `code` or the message). */
|
|
14
|
+
export declare function failure(e: (Error & {
|
|
15
|
+
code?: unknown;
|
|
16
|
+
}) | undefined): string;
|
|
17
|
+
export declare class StatusLine {
|
|
18
|
+
private readonly o;
|
|
19
|
+
private readonly out;
|
|
20
|
+
private st;
|
|
21
|
+
private printed;
|
|
22
|
+
constructor(o: {
|
|
23
|
+
service: string;
|
|
24
|
+
endpoint: string;
|
|
25
|
+
release?: string;
|
|
26
|
+
off?: Signal[];
|
|
27
|
+
}, out?: (m: string) => void);
|
|
28
|
+
/** One result for `signal`: the first failure and the last pending signal turning ok both print the line. */
|
|
29
|
+
record(signal: Signal, items: number, r: Result): void;
|
|
30
|
+
print(): void;
|
|
31
|
+
}
|
|
32
|
+
export declare const watchSpans: (e: SpanExporter, l: StatusLine) => SpanExporter;
|
|
33
|
+
export declare const watchLogs: (e: LogRecordExporter, l: StatusLine) => LogRecordExporter;
|
|
34
|
+
export declare const watchMetrics: (e: PushMetricExporter, l: StatusLine) => PushMetricExporter;
|
|
35
|
+
export declare function noteDrop(kind: string): void;
|
|
36
|
+
export declare function flushDrops(): void;
|
|
37
|
+
export {};
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
export const debugOn = () => ['1', 'true', 'on', 'yes'].includes((process.env.WT_DEBUG ?? process.env.WATCHTOWER_DEBUG ?? '').trim().toLowerCase());
|
|
2
|
+
/** First 8 characters only. */
|
|
3
|
+
export const keyHint = (k) => `${k.slice(0, 8)}…`;
|
|
4
|
+
export const debug = (m) => { if (debugOn())
|
|
5
|
+
console.info(`[watchtower:debug] ${m}`); };
|
|
6
|
+
/** HTTP status or error text of a failed export (the OTLP exporters put the status in `code` or the message). */
|
|
7
|
+
export function failure(e) {
|
|
8
|
+
const m = /\bstatus(?: code)?:? (\d{3})\b/i.exec(e?.message ?? '');
|
|
9
|
+
return String((typeof e?.code === 'number' ? e.code : undefined) ?? m?.[1] ?? e?.message ?? 'error').split('\n')[0].slice(0, 80);
|
|
10
|
+
}
|
|
11
|
+
const quiet = () => process.env.NODE_ENV === 'test' && !debugOn();
|
|
12
|
+
export class StatusLine {
|
|
13
|
+
o;
|
|
14
|
+
out;
|
|
15
|
+
st;
|
|
16
|
+
printed = false;
|
|
17
|
+
constructor(o, out = (m) => { if (!quiet())
|
|
18
|
+
console.info(m); }) {
|
|
19
|
+
this.o = o;
|
|
20
|
+
this.out = out;
|
|
21
|
+
this.st = { traces: 'pending', logs: 'pending', metrics: 'pending' };
|
|
22
|
+
for (const s of o.off ?? [])
|
|
23
|
+
this.st[s] = 'off';
|
|
24
|
+
// a signal that never fires (no logs yet, metrics every 60 s) must not hide the line forever
|
|
25
|
+
const t = setTimeout(() => this.print(), 90_000);
|
|
26
|
+
t.unref?.();
|
|
27
|
+
}
|
|
28
|
+
/** One result for `signal`: the first failure and the last pending signal turning ok both print the line. */
|
|
29
|
+
record(signal, items, r) {
|
|
30
|
+
const fail = r.code !== 0;
|
|
31
|
+
const why = fail ? failure(r.error) : '';
|
|
32
|
+
debug(`export ${signal} items=${items} ${fail ? `fail(${why})` : 'ok'}`);
|
|
33
|
+
if (fail) {
|
|
34
|
+
if (this.st[signal] !== 'ok')
|
|
35
|
+
this.st[signal] = `fail(${why})`;
|
|
36
|
+
this.print();
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
this.st[signal] = 'ok';
|
|
40
|
+
if (Object.values(this.st).every((s) => s !== 'pending'))
|
|
41
|
+
this.print();
|
|
42
|
+
}
|
|
43
|
+
print() {
|
|
44
|
+
if (this.printed)
|
|
45
|
+
return;
|
|
46
|
+
this.printed = true;
|
|
47
|
+
let host = this.o.endpoint;
|
|
48
|
+
try {
|
|
49
|
+
host = new URL(this.o.endpoint).host;
|
|
50
|
+
}
|
|
51
|
+
catch { /* keep as given */ }
|
|
52
|
+
const s = this.st;
|
|
53
|
+
this.out(`[watchtower] ${this.o.service} → ${host} traces:${s.traces} logs:${s.logs} metrics:${s.metrics} release=${this.o.release ?? 'none'}`);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
const countMetrics = (m) => (m?.scopeMetrics ?? []).reduce((n, s) => n + s.metrics.length, 0);
|
|
57
|
+
function watch(inner, signal, line, count) {
|
|
58
|
+
const wrapped = Object.create(inner); // keeps every other exporter method (selectAggregation etc.)
|
|
59
|
+
wrapped.export = (items, done) => inner.export(items, (r) => { line.record(signal, count(items), r); done(r); });
|
|
60
|
+
return wrapped;
|
|
61
|
+
}
|
|
62
|
+
export const watchSpans = (e, l) => watch(e, 'traces', l, (i) => i.length);
|
|
63
|
+
export const watchLogs = (e, l) => watch(e, 'logs', l, (i) => i.length);
|
|
64
|
+
export const watchMetrics = (e, l) => watch(e, 'metrics', l, countMetrics);
|
|
65
|
+
// Drop counters: Next-internal spans (sampling) and DB queries without a parent span. Summarised per minute under WT_DEBUG.
|
|
66
|
+
const drops = new Map();
|
|
67
|
+
let timer;
|
|
68
|
+
export function noteDrop(kind) {
|
|
69
|
+
drops.set(kind, (drops.get(kind) ?? 0) + 1);
|
|
70
|
+
if (!timer && debugOn()) {
|
|
71
|
+
timer = setInterval(flushDrops, 60_000);
|
|
72
|
+
timer.unref?.();
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
export function flushDrops() {
|
|
76
|
+
if (drops.size)
|
|
77
|
+
debug(`dropped in the last minute: ${[...drops].map(([k, n]) => `${n} ${k}`).join(', ')}`);
|
|
78
|
+
drops.clear();
|
|
79
|
+
}
|
package/dist/esm/index.js
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
// Thin Watchtower layer over the OpenTelemetry Node SDK: key header, endpoint default,
|
|
2
2
|
// offline buffer, wt.*-safe resource attributes, redaction hook, getPrompt/score/evaluate/observe.
|
|
3
|
+
import { checkLate } from './late.js'; // first: snapshots which builtins were loaded before the SDK
|
|
3
4
|
import { inspect } from 'node:util';
|
|
4
5
|
import { context, diag, metrics, propagation, trace } from '@opentelemetry/api';
|
|
5
6
|
import { missingPeers, need as needPeer, STANDALONE_HINT } from './load.js';
|
|
6
7
|
import { defaultResourceDetectors, otelEnv, resolveRelease } from './env.js';
|
|
7
|
-
import {
|
|
8
|
+
import { setHttpServerActive } from './integrations/db.js';
|
|
8
9
|
import { instrumentAll } from './instrument.js';
|
|
9
10
|
import { LOG_BODY_KEY, redactor } from './redact.js';
|
|
10
11
|
import { resolveRedact } from './redact-presets.js';
|
|
@@ -12,6 +13,7 @@ import { foreignProvider, attachProcessors } from './attach.js';
|
|
|
12
13
|
import { scrubUrl, urlScrubber } from './scrub.js';
|
|
13
14
|
import { filterExporter, isNoisySpan, quotaWarnExporter } from './filter.js';
|
|
14
15
|
import { nextInternalsFilter } from './next-filter.js';
|
|
16
|
+
import { debug, keyHint, noteDrop, StatusLine, watchLogs, watchMetrics, watchSpans } from './diagnostics.js';
|
|
15
17
|
import { checkin as runCheckin } from './checkin.js';
|
|
16
18
|
import { checkIn as checkInFor, withMonitor as withMonitorFor } from './cron/monitor.js';
|
|
17
19
|
import { installSignalFlush } from './shutdown.js';
|
|
@@ -107,6 +109,11 @@ export class Client {
|
|
|
107
109
|
this.redact = red.hook;
|
|
108
110
|
this.scrubUrls = o.urlScrubbing ?? red.preset !== 'off';
|
|
109
111
|
this.logCaller = o.logCaller ?? env.WATCHTOWER_LOG_CALLER === '1';
|
|
112
|
+
const logsOn = switchOn('WATCHTOWER_LOGS', 'OTEL_LOGS_EXPORTER', o.logs ?? (o.logExporter ? true : undefined));
|
|
113
|
+
const metricsOn = switchOn('WATCHTOWER_METRICS', 'OTEL_METRICS_EXPORTER', o.metrics ?? (o.metricExporter ? true : undefined));
|
|
114
|
+
// one status line per process, fed by the default OTLP exporters (explicit test exporters are left alone)
|
|
115
|
+
const line = new StatusLine({ service: String(resource.attributes['service.name']), endpoint: this.endpoint, release, off: [...(logsOn ? [] : ['logs']), ...(metricsOn ? [] : ['metrics'])] });
|
|
116
|
+
debug(`exporters: ${this.endpoint}/v1/traces, /v1/logs, /v1/metrics key=${keyHint(apiKey)}`);
|
|
110
117
|
let exporter = o.exporter;
|
|
111
118
|
if (!exporter) {
|
|
112
119
|
const url = `${this.endpoint}/v1/traces`;
|
|
@@ -115,6 +122,7 @@ export class Client {
|
|
|
115
122
|
// spans and log records spool to their own subdirectories
|
|
116
123
|
if (o.bufferDir)
|
|
117
124
|
exporter = new SpoolExporter(exporter, nodePath.join(o.bufferDir, 'traces'), url, this.headers, this.fetch);
|
|
125
|
+
exporter = watchSpans(exporter, line);
|
|
118
126
|
}
|
|
119
127
|
const keepNoisy = o.noisySpans ?? env.WT_NOISY_SPANS === '1';
|
|
120
128
|
const user = o.spanFilter;
|
|
@@ -152,7 +160,6 @@ export class Client {
|
|
|
152
160
|
}
|
|
153
161
|
this.tracer = this.provider.getTracer('watchtower');
|
|
154
162
|
// an explicit exporter never switches the other signals off: only `logs` / `metrics` / the env switches do
|
|
155
|
-
const logsOn = switchOn('WATCHTOWER_LOGS', 'OTEL_LOGS_EXPORTER', o.logs ?? (o.logExporter ? true : undefined));
|
|
156
163
|
this.logs = logsOn ? 'ok' : 'disabled';
|
|
157
164
|
let logExporter = logsOn ? o.logExporter : undefined;
|
|
158
165
|
if (logsOn && !logExporter) {
|
|
@@ -161,6 +168,7 @@ export class Client {
|
|
|
161
168
|
logExporter = new OTLPLogExporter({ url, headers: this.headers });
|
|
162
169
|
if (o.bufferDir)
|
|
163
170
|
logExporter = spoolLogs(logExporter, nodePath.join(o.bufferDir, 'logs'), url, this.headers, this.fetch);
|
|
171
|
+
logExporter = watchLogs(logExporter, line);
|
|
164
172
|
}
|
|
165
173
|
const { LoggerProvider: LP, BatchLogRecordProcessor } = needPeer('@opentelemetry/sdk-logs');
|
|
166
174
|
this.loggerProvider = new LP({
|
|
@@ -168,8 +176,8 @@ export class Client {
|
|
|
168
176
|
processors: !logExporter ? [] : [new BatchLogRecordProcessor({ exporter: logExporter })],
|
|
169
177
|
});
|
|
170
178
|
this.logger = this.loggerProvider.getLogger('watchtower');
|
|
171
|
-
if (
|
|
172
|
-
const m = startMetrics(this.endpoint, this.headers, resource, o.bufferDir, this.fetch, o.metricExporter);
|
|
179
|
+
if (metricsOn) {
|
|
180
|
+
const m = startMetrics(this.endpoint, this.headers, resource, o.bufferDir, this.fetch, o.metricExporter, (e) => watchMetrics(e, line));
|
|
173
181
|
this.meterProvider = m.provider;
|
|
174
182
|
this.stopRuntime = m.stop;
|
|
175
183
|
}
|
|
@@ -388,10 +396,12 @@ function turnOff(why) {
|
|
|
388
396
|
return offClient();
|
|
389
397
|
}
|
|
390
398
|
function start(opts) {
|
|
399
|
+
checkLate();
|
|
391
400
|
defaultResourceDetectors(); // before any NodeSDK reads OTEL_NODE_RESOURCE_DETECTORS
|
|
392
401
|
const nextMode = opts?.nextInternals ?? (process.env.NEXT_RUNTIME ? 'sample' : undefined);
|
|
393
402
|
if (nextMode) {
|
|
394
|
-
const
|
|
403
|
+
const base = nextInternalsFilter(nextMode, opts?.nextInternalsRate);
|
|
404
|
+
const own = (s) => base(s) || (noteDrop('Next.js internal spans (nextInternals sampling)'), false);
|
|
395
405
|
const user = opts.spanFilter;
|
|
396
406
|
opts = { ...opts, nextInternals: undefined, spanFilter: user ? (s) => own(s) && user(s) : own }; // cleared: a second init() never stacks the filter
|
|
397
407
|
}
|
|
@@ -410,9 +420,6 @@ function start(opts) {
|
|
|
410
420
|
if (mode === 'auto' && logOn) {
|
|
411
421
|
console.info(`[watchtower] instrumented: ${names.map((n) => n.replace('@opentelemetry/instrumentation-', '')).join(', ') || 'nothing (no supported package found)'}`);
|
|
412
422
|
}
|
|
413
|
-
if (logOn && dbRequireParent(undefined)) {
|
|
414
|
-
console.info('watchtower: requireParent on; queries outside a span are not recorded (WATCHTOWER_DB_REQUIRE_PARENT=0 to keep them)');
|
|
415
|
-
}
|
|
416
423
|
}
|
|
417
424
|
if (process.env.WT_PROFILING === '1') {
|
|
418
425
|
const attrs = c.resource.attributes;
|
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
// statement hash and N+1 hint, connection-pool metrics and embedded-store gauges.
|
|
3
3
|
import * as fs from 'node:fs';
|
|
4
4
|
import * as nodePath from 'node:path';
|
|
5
|
-
import { context, createContextKey,
|
|
5
|
+
import { context, createContextKey, INVALID_SPAN_CONTEXT, metrics, trace, SpanKind, SpanStatusCode } from '@opentelemetry/api';
|
|
6
|
+
import { noteDrop } from '../diagnostics.js';
|
|
6
7
|
import { isPgDialect, normalizeAndHash, querySummary } from '../sql.js';
|
|
7
8
|
/** Set inside an instrumented call so a wrapper the library calls internally adds no second span. */
|
|
8
9
|
const INSIDE = createContextKey('watchtower.db.inside');
|
|
@@ -43,10 +44,11 @@ let droppedSpans = 0;
|
|
|
43
44
|
let droppedCounter;
|
|
44
45
|
/** Datastore spans dropped so far because `requireParent` found no active parent span. */
|
|
45
46
|
export const droppedDbSpans = () => droppedSpans;
|
|
46
|
-
/** Count a dropped span: the `wt.sdk.db.dropped_spans` counter (exported with the SDK's metrics) and one
|
|
47
|
+
/** Count a dropped span: the `wt.sdk.db.dropped_spans` counter (exported with the SDK's metrics) and one console line (the first drop). */
|
|
47
48
|
function dropped() {
|
|
48
49
|
if (droppedSpans++ === 0)
|
|
49
|
-
|
|
50
|
+
console.info('[watchtower] dropped a DB query outside any span (requireParent on; WATCHTOWER_DB_REQUIRE_PARENT=0 to keep them)');
|
|
51
|
+
noteDrop('DB queries outside any span');
|
|
50
52
|
droppedCounter ??= metrics.getMeter('watchtower').createCounter('wt.sdk.db.dropped_spans', { description: 'Datastore spans dropped for lack of a parent span (requireParent)' });
|
|
51
53
|
droppedCounter.add(1);
|
|
52
54
|
return trace.wrapSpanContext(INVALID_SPAN_CONTEXT);
|
|
@@ -51,16 +51,18 @@ export declare function tracingIncludes(ids: string[], cwd?: string): string[];
|
|
|
51
51
|
* the SDK starts whichever entry instrumentation imports. Sets `NEXT_PUBLIC_WT_RELEASE`. With `sourcemaps` it turns on
|
|
52
52
|
* `productionBrowserSourceMaps` (webpack and Turbopack); `{ upload: true }` uploads and deletes them after the webpack
|
|
53
53
|
* client build, otherwise run `wt-next-sourcemaps` after `next build` (`"build": "next build && wt-next-sourcemaps"`).
|
|
54
|
+
* @deprecated use `withWatchtower` from `@watchtowerobservability/next`
|
|
54
55
|
*/
|
|
55
56
|
export declare function withWatchtower(config?: ConfigOrFn, opts?: WatchtowerNextOptions): ConfigOrFn;
|
|
56
57
|
/** A ustar archive of `[name, bytes]` (names up to 100 bytes). */
|
|
57
58
|
export declare function makeTar(files: [string, Buffer][]): Buffer;
|
|
58
59
|
/**
|
|
59
|
-
* Upload every `.map` under `dir` as `_next/static/<path>` for the release: one `POST /artifacts/bundle` per ~
|
|
60
|
+
* Upload every `.map` under `dir` as `_next/static/<path>` for the release: one `POST /artifacts/bundle` per ~32 MB
|
|
60
61
|
* batch (tar.gz plus manifest), falling back to single uploads (8 at a time) when the server has no bundle route.
|
|
61
62
|
* 429/5xx are retried with backoff honoring Retry-After; a failed map does not stop the others. The maps are deleted when none failed. Returns
|
|
62
63
|
* `{uploaded, skipped, failed}`: `skipped` = the server already had those exact bytes (HTTP 200). Bodies are sent
|
|
63
64
|
* gzipped (`Content-Encoding: gzip`).
|
|
65
|
+
* @deprecated use `@watchtowerobservability/next`
|
|
64
66
|
*/
|
|
65
67
|
export declare function uploadSourcemaps(o?: SourcemapOptions): Promise<{
|
|
66
68
|
uploaded: number;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
// Deprecated entry (`@watchtowerobservability/node/next-build`): use `@watchtowerobservability/next`. Still works unchanged.
|
|
1
2
|
// Build-time helpers for Next.js: `withWatchtower` (next.config) and `uploadSourcemaps` (after `next build`).
|
|
2
3
|
import * as fs from 'node:fs';
|
|
3
4
|
import * as nodePath from 'node:path';
|
|
@@ -82,6 +83,7 @@ const SHA_ENV = ['WT_RELEASE', 'GITHUB_SHA', 'CI_COMMIT_SHA', 'VERCEL_GIT_COMMIT
|
|
|
82
83
|
* the SDK starts whichever entry instrumentation imports. Sets `NEXT_PUBLIC_WT_RELEASE`. With `sourcemaps` it turns on
|
|
83
84
|
* `productionBrowserSourceMaps` (webpack and Turbopack); `{ upload: true }` uploads and deletes them after the webpack
|
|
84
85
|
* client build, otherwise run `wt-next-sourcemaps` after `next build` (`"build": "next build && wt-next-sourcemaps"`).
|
|
86
|
+
* @deprecated use `withWatchtower` from `@watchtowerobservability/next`
|
|
85
87
|
*/
|
|
86
88
|
export function withWatchtower(config = {}, opts = {}) {
|
|
87
89
|
const sm = opts.sourcemaps === true ? {} : opts.sourcemaps || undefined;
|
|
@@ -177,11 +179,12 @@ function chunkFor(mapFile, name) {
|
|
|
177
179
|
return undefined;
|
|
178
180
|
}
|
|
179
181
|
/**
|
|
180
|
-
* Upload every `.map` under `dir` as `_next/static/<path>` for the release: one `POST /artifacts/bundle` per ~
|
|
182
|
+
* Upload every `.map` under `dir` as `_next/static/<path>` for the release: one `POST /artifacts/bundle` per ~32 MB
|
|
181
183
|
* batch (tar.gz plus manifest), falling back to single uploads (8 at a time) when the server has no bundle route.
|
|
182
184
|
* 429/5xx are retried with backoff honoring Retry-After; a failed map does not stop the others. The maps are deleted when none failed. Returns
|
|
183
185
|
* `{uploaded, skipped, failed}`: `skipped` = the server already had those exact bytes (HTTP 200). Bodies are sent
|
|
184
186
|
* gzipped (`Content-Encoding: gzip`).
|
|
187
|
+
* @deprecated use `@watchtowerobservability/next`
|
|
185
188
|
*/
|
|
186
189
|
export async function uploadSourcemaps(o = {}) {
|
|
187
190
|
const env = process.env;
|
|
@@ -265,7 +268,7 @@ export async function uploadSourcemaps(o = {}) {
|
|
|
265
268
|
};
|
|
266
269
|
// One request per batch (tar.gz + manifest). A server without the bundle route (or a request that
|
|
267
270
|
// never got through) falls back to concurrent single uploads for that batch.
|
|
268
|
-
const BATCH_BYTES =
|
|
271
|
+
const BATCH_BYTES = 32 * 1024 * 1024; // smaller requests keep the API's upload memory low
|
|
269
272
|
const batches = [];
|
|
270
273
|
let cur = [], curBytes = 0;
|
|
271
274
|
for (const e of entries) {
|
|
@@ -2,8 +2,12 @@ type Opts = Record<string, unknown>;
|
|
|
2
2
|
export type NextOptions = Opts;
|
|
3
3
|
export type SourcemapOptions = Opts;
|
|
4
4
|
export type TunnelOptions = Opts;
|
|
5
|
+
/** @deprecated use `@watchtowerobservability/next` */
|
|
5
6
|
export declare const makeRegister: (_options?: NextOptions) => (() => Promise<void>);
|
|
7
|
+
/** @deprecated use `@watchtowerobservability/next` */
|
|
6
8
|
export declare const register: () => Promise<void>;
|
|
9
|
+
/** @deprecated use `@watchtowerobservability/next` */
|
|
7
10
|
export declare function onRequestError(_err?: unknown, _request?: unknown, _context?: unknown): Promise<void>;
|
|
11
|
+
/** @deprecated use `@watchtowerobservability/next` */
|
|
8
12
|
export declare const withWatchtower: <T>(config: T, _opts?: Opts) => T;
|
|
9
13
|
export {};
|
|
@@ -1,4 +1,8 @@
|
|
|
1
|
+
/** @deprecated use `@watchtowerobservability/next` */
|
|
1
2
|
export const makeRegister = (_options = {}) => async () => { };
|
|
3
|
+
/** @deprecated use `@watchtowerobservability/next` */
|
|
2
4
|
export const register = makeRegister();
|
|
5
|
+
/** @deprecated use `@watchtowerobservability/next` */
|
|
3
6
|
export async function onRequestError(_err, _request, _context) { }
|
|
7
|
+
/** @deprecated use `@watchtowerobservability/next` */
|
|
4
8
|
export const withWatchtower = (config, _opts) => config;
|
|
@@ -1,15 +1,22 @@
|
|
|
1
1
|
import * as wt from '../index.js';
|
|
2
|
-
|
|
2
|
+
import * as build from './next-build.js';
|
|
3
|
+
/** @deprecated use `withWatchtower` from `@watchtowerobservability/next` */
|
|
4
|
+
export declare const withWatchtower: typeof build.withWatchtower;
|
|
5
|
+
/** @deprecated use `uploadSourcemaps` from `@watchtowerobservability/next` */
|
|
6
|
+
export declare const uploadSourcemaps: typeof build.uploadSourcemaps;
|
|
3
7
|
export type { SourcemapOptions } from './next-build.js';
|
|
4
8
|
export { isNextInternal, nextInternalsFilter } from '../next-filter.js';
|
|
5
9
|
export { tunnelHandler } from './next-tunnel.js';
|
|
6
10
|
export type { TunnelOptions } from './next-tunnel.js';
|
|
7
11
|
export type NextOptions = wt.InitOptions;
|
|
8
|
-
/**
|
|
12
|
+
/** @deprecated use `register` from `@watchtowerobservability/next`.
|
|
13
|
+
* Build a Next.js instrumentation `register` that passes `options` to `init`; no-op off the Node.js runtime or without a key. */
|
|
9
14
|
export declare function makeRegister(options?: NextOptions): () => Promise<void>;
|
|
10
|
-
/**
|
|
15
|
+
/** @deprecated use `register` from `@watchtowerobservability/next`.
|
|
16
|
+
* Next.js instrumentation hook: init from WT_* env on the Node.js runtime; no-op without WT_INGEST_KEY. */
|
|
11
17
|
export declare const register: () => Promise<void>;
|
|
12
|
-
/**
|
|
18
|
+
/** @deprecated use `onRequestError` from `@watchtowerobservability/next`.
|
|
19
|
+
* Next.js onRequestError: server render, route handler and server action errors. */
|
|
13
20
|
export declare function onRequestError(err: unknown, request?: {
|
|
14
21
|
path?: string;
|
|
15
22
|
method?: string;
|
|
@@ -1,10 +1,16 @@
|
|
|
1
|
+
// Deprecated entry: use `@watchtowerobservability/next` (register, onRequestError, withWatchtower). Still works unchanged.
|
|
1
2
|
// instrumentation.js: module.exports = require('@watchtowerobservability/node/next');
|
|
2
3
|
// or, with options: export const register = makeRegister({ redact }); export { onRequestError } from '@watchtowerobservability/node/next';
|
|
3
4
|
import * as wt from '../index.js';
|
|
4
|
-
|
|
5
|
+
import * as build from './next-build.js';
|
|
6
|
+
/** @deprecated use `withWatchtower` from `@watchtowerobservability/next` */
|
|
7
|
+
export const withWatchtower = build.withWatchtower;
|
|
8
|
+
/** @deprecated use `uploadSourcemaps` from `@watchtowerobservability/next` */
|
|
9
|
+
export const uploadSourcemaps = build.uploadSourcemaps;
|
|
5
10
|
export { isNextInternal, nextInternalsFilter } from '../next-filter.js';
|
|
6
11
|
export { tunnelHandler } from './next-tunnel.js';
|
|
7
|
-
/**
|
|
12
|
+
/** @deprecated use `register` from `@watchtowerobservability/next`.
|
|
13
|
+
* Build a Next.js instrumentation `register` that passes `options` to `init`; no-op off the Node.js runtime or without a key. */
|
|
8
14
|
export function makeRegister(options = {}) {
|
|
9
15
|
return async function register() {
|
|
10
16
|
const rt = process.env.NEXT_RUNTIME;
|
|
@@ -13,9 +19,11 @@ export function makeRegister(options = {}) {
|
|
|
13
19
|
wt.init({ ...options, nextInternals: options.nextInternals ?? 'sample' }); // init() applies the filter (once)
|
|
14
20
|
};
|
|
15
21
|
}
|
|
16
|
-
/**
|
|
22
|
+
/** @deprecated use `register` from `@watchtowerobservability/next`.
|
|
23
|
+
* Next.js instrumentation hook: init from WT_* env on the Node.js runtime; no-op without WT_INGEST_KEY. */
|
|
17
24
|
export const register = makeRegister();
|
|
18
|
-
/**
|
|
25
|
+
/** @deprecated use `onRequestError` from `@watchtowerobservability/next`.
|
|
26
|
+
* Next.js onRequestError: server render, route handler and server action errors. */
|
|
19
27
|
export async function onRequestError(err, request, context) {
|
|
20
28
|
const c = context || {};
|
|
21
29
|
wt.captureException(err, {
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** Which of http/https are in `list` (default: this process's loaded builtins). */
|
|
2
|
+
export declare const lateModules: (list?: readonly string[]) => string[];
|
|
3
|
+
export declare const LATE_HINT = "Start node with --import @watchtowerobservability/node/register";
|
|
4
|
+
/** Prints once per process (global flag, so the CJS and ESM copies share it). */
|
|
5
|
+
export declare function warnLate(mods: string[], out?: (m: string) => void): void;
|
|
6
|
+
/** The entry points call this: silent under Next (it loads http before instrumentation runs) and in test runners. */
|
|
7
|
+
export declare function checkLate(): void;
|
package/dist/esm/late.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// "Loaded too late" detector. Import this FIRST in the entry modules (register.ts, index.ts): ES imports evaluate in order, so
|
|
2
|
+
// the snapshot below is taken before the SDK's own dependencies load anything. Under `node --import .../register` nothing
|
|
3
|
+
// but Node's bootstrap has run yet, so http/https are absent from process.moduleLoadList (checked on Node 26).
|
|
4
|
+
/** Which of http/https are in `list` (default: this process's loaded builtins). */
|
|
5
|
+
export const lateModules = (list = process.moduleLoadList ?? []) => ['http', 'https'].filter((m) => list.includes(`NativeModule ${m}`));
|
|
6
|
+
const early = lateModules();
|
|
7
|
+
const KEY = Symbol.for('watchtower.node.late-warned');
|
|
8
|
+
export const LATE_HINT = 'Start node with --import @watchtowerobservability/node/register';
|
|
9
|
+
/** Prints once per process (global flag, so the CJS and ESM copies share it). */
|
|
10
|
+
export function warnLate(mods, out = (m) => console.warn(m)) {
|
|
11
|
+
const g = globalThis;
|
|
12
|
+
if (!mods.length || g[KEY])
|
|
13
|
+
return;
|
|
14
|
+
g[KEY] = true;
|
|
15
|
+
out(`[watchtower] loaded too late: ${mods[0]} was already imported, so its requests are not traced. ${LATE_HINT}`);
|
|
16
|
+
}
|
|
17
|
+
/** The entry points call this: silent under Next (it loads http before instrumentation runs) and in test runners. */
|
|
18
|
+
export function checkLate() {
|
|
19
|
+
if (process.env.NEXT_RUNTIME || process.env.NODE_ENV === 'test' || process.env.VITEST)
|
|
20
|
+
return;
|
|
21
|
+
warnLate(early);
|
|
22
|
+
}
|
package/dist/esm/metrics.d.ts
CHANGED
|
@@ -6,4 +6,4 @@ export interface Metrics {
|
|
|
6
6
|
provider: MeterProvider;
|
|
7
7
|
stop(): void;
|
|
8
8
|
}
|
|
9
|
-
export declare function startMetrics(endpoint: string, headers: Record<string, string>, resource: Resource, bufferDir: string | undefined, fetch: typeof globalThis.fetch, exporter?: PushMetricExporter): Metrics;
|
|
9
|
+
export declare function startMetrics(endpoint: string, headers: Record<string, string>, resource: Resource, bufferDir: string | undefined, fetch: typeof globalThis.fetch, exporter?: PushMetricExporter, wrap?: (e: PushMetricExporter) => PushMetricExporter): Metrics;
|
package/dist/esm/metrics.js
CHANGED
|
@@ -14,7 +14,7 @@ export function switchOn(name, otelExporterEnv, flag) {
|
|
|
14
14
|
return false;
|
|
15
15
|
return !['off', 'false', '0', 'no'].includes((env[name] || 'on').trim().toLowerCase());
|
|
16
16
|
}
|
|
17
|
-
export function startMetrics(endpoint, headers, resource, bufferDir, fetch, exporter) {
|
|
17
|
+
export function startMetrics(endpoint, headers, resource, bufferDir, fetch, exporter, wrap) {
|
|
18
18
|
const sdk = need('@opentelemetry/sdk-metrics');
|
|
19
19
|
const url = `${endpoint}/v1/metrics`;
|
|
20
20
|
let exp = exporter;
|
|
@@ -25,6 +25,8 @@ export function startMetrics(endpoint, headers, resource, bufferDir, fetch, expo
|
|
|
25
25
|
exp = new OTLPMetricExporter({ url, headers, ...delta });
|
|
26
26
|
if (bufferDir)
|
|
27
27
|
exp = new MetricSpool(exp, nodePath.join(bufferDir, 'metrics'), url, headers, fetch);
|
|
28
|
+
if (wrap)
|
|
29
|
+
exp = wrap(exp);
|
|
28
30
|
}
|
|
29
31
|
const interval = Number(process.env.OTEL_METRIC_EXPORT_INTERVAL) || 60000;
|
|
30
32
|
const reader = new sdk.PeriodicExportingMetricReader({
|
package/dist/esm/register.js
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
// Preload entry: `node --import @watchtowerobservability/node/register app.mjs` (ESM) or `node -r @watchtowerobservability/node/register app.js` (CommonJS).
|
|
2
2
|
// Starts the SDK from WT_*/OTEL_* env before the app loads, so http, fetch, pg and ioredis are patched in time.
|
|
3
3
|
// Without WT_INGEST_KEY it starts nothing and says so.
|
|
4
|
+
import { checkLate } from './late.js'; // first: snapshots which builtins were loaded before the SDK
|
|
4
5
|
import { pathToFileURL } from 'node:url';
|
|
5
6
|
import { register as registerHooks } from 'node:module';
|
|
6
7
|
import { init, setOffReason } from './index.js';
|
|
7
8
|
import { searchPaths } from './load.js';
|
|
9
|
+
checkLate();
|
|
8
10
|
if (process.env.WT_INGEST_KEY || process.env.OTEL_EXPORTER_OTLP_HEADERS) {
|
|
9
11
|
try {
|
|
10
12
|
// ESM modules (node:http imported from an ES module) are only patched through OpenTelemetry's loader hook
|
package/dist/esm/version.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/** This package's version (test/distro.test.ts checks it against package.json); sent as `telemetry.distro.version`. */
|
|
2
|
-
export declare const VERSION = "0.8.
|
|
2
|
+
export declare const VERSION = "0.8.1";
|
package/dist/esm/version.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/** This package's version (test/distro.test.ts checks it against package.json); sent as `telemetry.distro.version`. */
|
|
2
|
-
export const VERSION = '0.8.
|
|
2
|
+
export const VERSION = '0.8.1';
|