@watchtowerobservability/node 0.7.3 → 0.7.5

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.
Files changed (97) hide show
  1. package/CHANGELOG.md +40 -1
  2. package/README.md +96 -12
  3. package/dist/cjs/attach.d.ts +7 -0
  4. package/dist/cjs/attach.js +29 -0
  5. package/dist/cjs/checkin.js +4 -13
  6. package/dist/cjs/cron/monitor.d.ts +47 -0
  7. package/dist/cjs/cron/monitor.js +95 -0
  8. package/dist/cjs/cron/schedulers.d.ts +36 -0
  9. package/dist/cjs/cron/schedulers.js +65 -0
  10. package/dist/cjs/env.d.ts +10 -0
  11. package/dist/cjs/env.js +98 -1
  12. package/dist/cjs/index.d.ts +50 -6
  13. package/dist/cjs/index.js +114 -37
  14. package/dist/cjs/instrument-for.d.ts +17 -0
  15. package/dist/cjs/instrument-for.js +44 -0
  16. package/dist/cjs/instrument.d.ts +4 -0
  17. package/dist/cjs/instrument.js +32 -1
  18. package/dist/cjs/integrations/bullmq.d.ts +8 -2
  19. package/dist/cjs/integrations/bullmq.js +32 -5
  20. package/dist/cjs/integrations/db.d.ts +7 -2
  21. package/dist/cjs/integrations/db.js +32 -4
  22. package/dist/cjs/integrations/fastify.d.ts +1 -1
  23. package/dist/cjs/integrations/fastify.js +3 -2
  24. package/dist/cjs/integrations/logs.js +16 -5
  25. package/dist/cjs/integrations/next-build.d.ts +25 -8
  26. package/dist/cjs/integrations/next-build.js +159 -34
  27. package/dist/cjs/integrations/next-tunnel.d.ts +6 -1
  28. package/dist/cjs/integrations/next-tunnel.js +13 -2
  29. package/dist/cjs/integrations/postgres.d.ts +2 -0
  30. package/dist/cjs/integrations/postgres.js +43 -1
  31. package/dist/cjs/integrations/temporal.d.ts +97 -0
  32. package/dist/cjs/integrations/temporal.js +144 -0
  33. package/dist/cjs/integrations/util.d.ts +17 -0
  34. package/dist/cjs/integrations/util.js +38 -0
  35. package/dist/cjs/load.d.ts +6 -0
  36. package/dist/cjs/load.js +28 -4
  37. package/dist/cjs/next-doctor-cli.d.ts +2 -0
  38. package/dist/cjs/next-doctor-cli.js +15 -0
  39. package/dist/cjs/next-doctor.d.ts +2 -0
  40. package/dist/cjs/next-doctor.js +50 -0
  41. package/dist/cjs/pprof.d.ts +2 -0
  42. package/dist/cjs/pprof.js +18 -5
  43. package/dist/cjs/profiling.d.ts +31 -0
  44. package/dist/cjs/profiling.js +67 -11
  45. package/dist/cjs/redact-presets.d.ts +16 -0
  46. package/dist/cjs/redact-presets.js +66 -0
  47. package/dist/cjs/register.js +19 -6
  48. package/dist/cjs/version.d.ts +1 -1
  49. package/dist/cjs/version.js +1 -1
  50. package/dist/esm/attach.d.ts +7 -0
  51. package/dist/esm/attach.js +25 -0
  52. package/dist/esm/checkin.js +4 -13
  53. package/dist/esm/cron/monitor.d.ts +47 -0
  54. package/dist/esm/cron/monitor.js +85 -0
  55. package/dist/esm/cron/schedulers.d.ts +36 -0
  56. package/dist/esm/cron/schedulers.js +61 -0
  57. package/dist/esm/env.d.ts +10 -0
  58. package/dist/esm/env.js +62 -0
  59. package/dist/esm/index.d.ts +50 -6
  60. package/dist/esm/index.js +109 -39
  61. package/dist/esm/instrument-for.d.ts +17 -0
  62. package/dist/esm/instrument-for.js +41 -0
  63. package/dist/esm/instrument.d.ts +4 -0
  64. package/dist/esm/instrument.js +30 -1
  65. package/dist/esm/integrations/bullmq.d.ts +8 -2
  66. package/dist/esm/integrations/bullmq.js +32 -5
  67. package/dist/esm/integrations/db.d.ts +7 -2
  68. package/dist/esm/integrations/db.js +29 -4
  69. package/dist/esm/integrations/fastify.d.ts +1 -1
  70. package/dist/esm/integrations/fastify.js +4 -3
  71. package/dist/esm/integrations/logs.js +16 -5
  72. package/dist/esm/integrations/next-build.d.ts +25 -8
  73. package/dist/esm/integrations/next-build.js +158 -34
  74. package/dist/esm/integrations/next-tunnel.d.ts +6 -1
  75. package/dist/esm/integrations/next-tunnel.js +13 -2
  76. package/dist/esm/integrations/postgres.d.ts +2 -0
  77. package/dist/esm/integrations/postgres.js +43 -2
  78. package/dist/esm/integrations/temporal.d.ts +97 -0
  79. package/dist/esm/integrations/temporal.js +139 -0
  80. package/dist/esm/integrations/util.d.ts +17 -0
  81. package/dist/esm/integrations/util.js +35 -0
  82. package/dist/esm/load.d.ts +6 -0
  83. package/dist/esm/load.js +21 -3
  84. package/dist/esm/next-doctor-cli.d.ts +2 -0
  85. package/dist/esm/next-doctor-cli.js +13 -0
  86. package/dist/esm/next-doctor.d.ts +2 -0
  87. package/dist/esm/next-doctor.js +14 -0
  88. package/dist/esm/pprof.d.ts +2 -0
  89. package/dist/esm/pprof.js +17 -5
  90. package/dist/esm/profiling.d.ts +31 -0
  91. package/dist/esm/profiling.js +66 -12
  92. package/dist/esm/redact-presets.d.ts +16 -0
  93. package/dist/esm/redact-presets.js +58 -0
  94. package/dist/esm/register.js +20 -7
  95. package/dist/esm/version.d.ts +1 -1
  96. package/dist/esm/version.js +1 -1
  97. package/package.json +42 -1
@@ -34,12 +34,31 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.querySummary = void 0;
37
+ exports.postgresMajor = postgresMajor;
37
38
  exports.instrumentPostgres = instrumentPostgres;
38
39
  const dc = __importStar(require("node:diagnostics_channel"));
40
+ const node_fs_1 = require("node:fs");
41
+ const node_module_1 = require("node:module");
42
+ const node_path_1 = require("node:path");
39
43
  const api_1 = require("@opentelemetry/api");
44
+ const load_js_1 = require("../load.js");
40
45
  const sql_js_1 = require("../sql.js");
41
46
  Object.defineProperty(exports, "querySummary", { enumerable: true, get: function () { return sql_js_1.querySummary; } });
42
47
  const db_js_1 = require("./db.js");
48
+ let warned = false;
49
+ // Warn once, and only when postgres is installed (load is real, but cheap: cached): without tracingChannel nothing would ever be recorded.
50
+ function warnOnce() {
51
+ if (warned)
52
+ return;
53
+ warned = true;
54
+ try {
55
+ (0, load_js_1.load)('postgres');
56
+ }
57
+ catch {
58
+ return;
59
+ }
60
+ api_1.diag.warn('watchtower: instrumentPostgres() is a no-op: this Node has no diagnostics_channel.tracingChannel; postgres@>=4 on a Node that provides it is required');
61
+ }
43
62
  /**
44
63
  * postgres.js has no OTel instrumentation; since 4.0 it publishes each query on the
45
64
  * `postgres:query` diagnostics tracing channel. This turns those into CLIENT spans (child of the
@@ -48,9 +67,32 @@ const db_js_1 = require("./db.js");
48
67
  * failure. Works for ESM and CJS; returns an unsubscribe function (a no-op when this Node has no
49
68
  * tracing channels).
50
69
  */
70
+ /** Major version of the app's installed `postgres`, or undefined when absent or unreadable. */
71
+ function postgresMajor(from = process.cwd()) {
72
+ try {
73
+ // `postgres/package.json` is not exported, so walk up from the resolved entry.
74
+ let dir = (0, node_path_1.dirname)((0, node_module_1.createRequire)((0, node_path_1.join)(from, 'noop.js')).resolve('postgres'));
75
+ for (let i = 0; i < 6; i++, dir = (0, node_path_1.dirname)(dir)) {
76
+ try {
77
+ const pkg = JSON.parse((0, node_fs_1.readFileSync)((0, node_path_1.join)(dir, 'package.json'), 'utf8'));
78
+ if (pkg.name === 'postgres')
79
+ return Number.parseInt(pkg.version ?? '', 10);
80
+ }
81
+ catch { /* keep walking */ }
82
+ }
83
+ }
84
+ catch { /* not installed */ }
85
+ return undefined;
86
+ }
51
87
  function instrumentPostgres(opts) {
52
- if (typeof dc.tracingChannel !== 'function')
88
+ if (typeof dc.tracingChannel !== 'function') {
89
+ warnOnce();
53
90
  return () => { };
91
+ }
92
+ const major = postgresMajor();
93
+ if (major !== undefined && major < 4) {
94
+ api_1.diag.warn(`watchtower: instrumentPostgres() records nothing with postgres@${major}: the postgres:query channel exists only in postgres@>=4`);
95
+ }
54
96
  const ch = dc.tracingChannel('postgres:query');
55
97
  const spans = new WeakMap();
56
98
  const handlers = {
@@ -0,0 +1,97 @@
1
+ interface ActivityInfo {
2
+ activityType?: string;
3
+ activityId?: string;
4
+ attempt?: number;
5
+ taskQueue?: string;
6
+ workflowType?: string;
7
+ workflowExecution?: {
8
+ workflowId?: string;
9
+ runId?: string;
10
+ };
11
+ retryPolicy?: {
12
+ maximumAttempts?: number;
13
+ };
14
+ }
15
+ interface ActivityCtx {
16
+ info?: ActivityInfo;
17
+ }
18
+ type Next = (input: unknown) => Promise<unknown>;
19
+ export interface TemporalInterceptorOptions {
20
+ /** Retry cap when the activity info does not carry the retry policy; a failure on this attempt (or a non-retryable one) is captured. */
21
+ maxAttempts?: number;
22
+ }
23
+ /** Worker options fragment: `Worker.create({ ..., interceptors: temporalInterceptors() })`. Spans for each activity attempt; the exception is captured on the final attempt only. */
24
+ export declare function temporalInterceptors(o?: TemporalInterceptorOptions): {
25
+ activity: ((ctx: ActivityCtx) => {
26
+ inbound: {
27
+ execute(input: unknown, next: Next): Promise<unknown>;
28
+ };
29
+ })[];
30
+ };
31
+ interface Range {
32
+ start?: number;
33
+ end?: number;
34
+ step?: number;
35
+ }
36
+ type Calendar = Partial<Record<'minute' | 'hour' | 'dayOfMonth' | 'month' | 'dayOfWeek', Range[]>>;
37
+ interface WfRef {
38
+ workflowId?: string;
39
+ firstExecutionRunId?: string;
40
+ runId?: string;
41
+ }
42
+ interface ActionLike {
43
+ takenAt?: Date | string;
44
+ workflow?: WfRef;
45
+ action?: {
46
+ workflow?: WfRef;
47
+ };
48
+ }
49
+ interface Described {
50
+ spec?: {
51
+ cronExpressions?: string[];
52
+ calendars?: Calendar[];
53
+ timezoneName?: string;
54
+ };
55
+ info?: {
56
+ recentActions?: ActionLike[];
57
+ runningActions?: ActionLike[];
58
+ };
59
+ }
60
+ export interface TemporalClientLike {
61
+ options?: {
62
+ namespace?: string;
63
+ };
64
+ schedule: {
65
+ list(): AsyncIterable<{
66
+ scheduleId: string;
67
+ }>;
68
+ getHandle(id: string): {
69
+ describe(): Promise<Described>;
70
+ };
71
+ };
72
+ workflow: {
73
+ getHandle(id: string, runId?: string): {
74
+ describe(): Promise<{
75
+ status?: {
76
+ name?: string;
77
+ };
78
+ startTime?: Date;
79
+ closeTime?: Date;
80
+ }>;
81
+ };
82
+ };
83
+ }
84
+ export interface WatchSchedulesOptions {
85
+ /** Poll period; default 60_000. */
86
+ interval?: number;
87
+ /** Only watch when the client's namespace is one of these (a Temporal client is bound to one namespace). */
88
+ namespaces?: string[];
89
+ }
90
+ /** Crontab (5 fields) for a Temporal schedule spec, or undefined when it has none or is not expressible (intervals, several calendars). */
91
+ export declare function scheduleCron(spec: Described['spec']): {
92
+ cron: string;
93
+ timezone?: string;
94
+ } | undefined;
95
+ /** Poll Temporal Schedules and send a check-in per action (slug `temporal-<scheduleId>`). Returns a stop function. */
96
+ export declare function watchTemporalSchedules(client: TemporalClientLike, o?: WatchSchedulesOptions): () => void;
97
+ export {};
@@ -0,0 +1,144 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.temporalInterceptors = temporalInterceptors;
4
+ exports.scheduleCron = scheduleCron;
5
+ exports.watchTemporalSchedules = watchTemporalSchedules;
6
+ // Temporal: activity spans + final-attempt failure capture (worker interceptors), and Schedule check-ins (a poller).
7
+ // Duck-typed on purpose: nothing from @temporalio/* is imported, so there is no dependency and the SDK's workflow sandbox is untouched.
8
+ const api_1 = require("@opentelemetry/api");
9
+ const errors_js_1 = require("../errors.js");
10
+ const monitor_js_1 = require("../cron/monitor.js");
11
+ /** Worker options fragment: `Worker.create({ ..., interceptors: temporalInterceptors() })`. Spans for each activity attempt; the exception is captured on the final attempt only. */
12
+ function temporalInterceptors(o = {}) {
13
+ return {
14
+ activity: [
15
+ (ctx) => ({
16
+ inbound: {
17
+ async execute(input, next) {
18
+ const i = ctx.info ?? {};
19
+ const attempt = i.attempt ?? 1;
20
+ const span = api_1.trace.getTracer('watchtower').startSpan(`activity ${i.activityType ?? 'unknown'}`, {
21
+ kind: api_1.SpanKind.CONSUMER,
22
+ attributes: {
23
+ 'temporal.activity.type': i.activityType ?? '', 'temporal.activity.id': i.activityId ?? '', 'temporal.attempt': attempt,
24
+ 'temporal.task_queue': i.taskQueue ?? '', 'temporal.workflow.id': i.workflowExecution?.workflowId ?? '',
25
+ 'temporal.workflow.type': i.workflowType ?? '',
26
+ },
27
+ });
28
+ try {
29
+ return await api_1.context.with(api_1.trace.setSpan(api_1.context.active(), span), () => next(input));
30
+ }
31
+ catch (e) {
32
+ const max = o.maxAttempts ?? i.retryPolicy?.maximumAttempts;
33
+ const final = e?.nonRetryable === true || (!!max && attempt >= max);
34
+ if (final)
35
+ (0, errors_js_1.captureException)(e, { attributes: { 'temporal.activity.type': i.activityType, 'temporal.attempt': attempt, 'temporal.workflow.id': i.workflowExecution?.workflowId } });
36
+ else {
37
+ span.recordException(e);
38
+ span.setStatus({ code: api_1.SpanStatusCode.ERROR, message: e?.message });
39
+ }
40
+ throw e;
41
+ }
42
+ finally {
43
+ span.end();
44
+ }
45
+ },
46
+ },
47
+ }),
48
+ ],
49
+ };
50
+ }
51
+ const FULL = { dayOfMonth: [1, 31], month: [1, 12], dayOfWeek: [0, 6] };
52
+ function field(name, rs, dflt = '*') {
53
+ if (!rs?.length)
54
+ return dflt;
55
+ const full = FULL[name];
56
+ const parts = rs.map((r) => {
57
+ const s = r.start ?? 0, e = r.end ?? s, st = r.step && r.step > 1 ? r.step : 1;
58
+ if (full && s === full[0] && e === full[1] && st === 1)
59
+ return '*';
60
+ return s === e ? `${s}` : `${s}-${e}${st > 1 ? `/${st}` : ''}`;
61
+ });
62
+ return parts.includes('*') ? '*' : parts.join(',');
63
+ }
64
+ /** Crontab (5 fields) for a Temporal schedule spec, or undefined when it has none or is not expressible (intervals, several calendars). */
65
+ function scheduleCron(spec) {
66
+ let tz = spec?.timezoneName || undefined;
67
+ const raw = spec?.cronExpressions?.[0];
68
+ if (raw) {
69
+ const m = /^(?:CRON_TZ|TZ)=(\S+)\s+(.*)$/.exec(raw.trim());
70
+ if (m) {
71
+ tz = m[1];
72
+ }
73
+ return { cron: (0, monitor_js_1.normalizeCron)((m ? m[2] : raw).split(/\s+/).slice(0, 6).join(' ')), timezone: tz };
74
+ }
75
+ const cal = spec?.calendars;
76
+ if (cal?.length !== 1)
77
+ return undefined;
78
+ const c = cal[0];
79
+ return { cron: ['minute', 'hour', 'dayOfMonth', 'month', 'dayOfWeek'].map((k) => field(k, c[k], k === 'minute' || k === 'hour' ? '0' : '*')).join(' '), timezone: tz };
80
+ }
81
+ const OK = new Set(['COMPLETED']);
82
+ const BAD = new Set(['FAILED', 'TIMED_OUT', 'TERMINATED', 'CANCELLED']);
83
+ const ref = (a) => a.workflow ?? a.action?.workflow;
84
+ /** Poll Temporal Schedules and send a check-in per action (slug `temporal-<scheduleId>`). Returns a stop function. */
85
+ function watchTemporalSchedules(client, o = {}) {
86
+ if (o.namespaces && !o.namespaces.includes(client.options?.namespace ?? 'default'))
87
+ return () => undefined;
88
+ const seen = new Map(); // schedule + workflow run -> last status sent
89
+ let busy = false;
90
+ const poll = async () => {
91
+ const target = (0, monitor_js_1.currentTarget)();
92
+ if (!target || busy)
93
+ return;
94
+ busy = true;
95
+ try {
96
+ for await (const s of client.schedule.list()) {
97
+ const slug = `temporal-${(0, monitor_js_1.slugify)(s.scheduleId) || s.scheduleId}`;
98
+ const d = await client.schedule.getHandle(s.scheduleId).describe();
99
+ const cr = scheduleCron(d.spec);
100
+ const monitorConfig = cr && { schedule: { type: 'crontab', value: cr.cron }, ...(cr.timezone ? { timezone: cr.timezone } : {}) };
101
+ const send = (st, durationMs) => (0, monitor_js_1.checkIn)(target, slug, st, { wait: true, monitorConfig, durationMs });
102
+ const actions = [...(d.info?.runningActions ?? []), ...(d.info?.recentActions ?? [])];
103
+ for (const a of actions) {
104
+ const w = ref(a);
105
+ if (!w?.workflowId)
106
+ continue;
107
+ const key = `${s.scheduleId}\0${w.workflowId}\0${w.firstExecutionRunId ?? w.runId ?? ''}`;
108
+ if (seen.get(key) === 'done')
109
+ continue;
110
+ let name = 'RUNNING', dur;
111
+ try {
112
+ const wd = await client.workflow.getHandle(w.workflowId, w.firstExecutionRunId ?? w.runId).describe();
113
+ name = String(wd.status?.name ?? 'RUNNING');
114
+ if (wd.startTime && wd.closeTime)
115
+ dur = +new Date(wd.closeTime) - +new Date(wd.startTime);
116
+ }
117
+ catch {
118
+ continue;
119
+ } // describe failed: retry next poll
120
+ if (name === 'RUNNING') {
121
+ if (!seen.has(key)) {
122
+ seen.set(key, 'running');
123
+ await send('in_progress');
124
+ }
125
+ }
126
+ else if (OK.has(name) || BAD.has(name)) {
127
+ if (!seen.has(key))
128
+ await send('in_progress'); // short run seen only after it finished
129
+ seen.set(key, 'done');
130
+ await send(OK.has(name) ? 'ok' : 'error', dur);
131
+ }
132
+ }
133
+ }
134
+ }
135
+ catch { /* Temporal unreachable: try again next interval */ }
136
+ finally {
137
+ busy = false;
138
+ }
139
+ };
140
+ const t = setInterval(() => void poll(), o.interval ?? 60_000);
141
+ t.unref?.();
142
+ void poll();
143
+ return () => clearInterval(t);
144
+ }
@@ -7,3 +7,20 @@ export interface ServerSpan {
7
7
  /** Start a server span; finish(status, route) names it `METHOD route` and ends it once. */
8
8
  export declare function serverSpan(method: string, path?: string): ServerSpan;
9
9
  export declare const statusOf: (e: unknown) => number;
10
+ /** `/base/:id` from an Express (or Nest-on-Express) request: `baseUrl` plus the matched `route.path`; undefined when no string route matched. */
11
+ export declare function expressRoute(req: {
12
+ baseUrl?: string;
13
+ route?: {
14
+ path?: unknown;
15
+ };
16
+ }): string | undefined;
17
+ /** http instrumentation `applyCustomAttributesOnSpan` hook: when the response ends, name the server span `METHOD /route/:param`. Off with `WT_ROUTE_NAMES=0`. */
18
+ export declare function routeNamer(span: Span, req: {
19
+ method?: string;
20
+ baseUrl?: string;
21
+ route?: {
22
+ path?: unknown;
23
+ };
24
+ }): void;
25
+ /** The active span when it is a recording SERVER span (made by the http instrumentation), wrapped so finish() enriches it and never ends it; else undefined. */
26
+ export declare function adoptServerSpan(method: string): ServerSpan | undefined;
@@ -2,6 +2,9 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.statusOf = void 0;
4
4
  exports.serverSpan = serverSpan;
5
+ exports.expressRoute = expressRoute;
6
+ exports.routeNamer = routeNamer;
7
+ exports.adoptServerSpan = adoptServerSpan;
5
8
  const api_1 = require("@opentelemetry/api");
6
9
  /** Start a server span; finish(status, route) names it `METHOD route` and ends it once. */
7
10
  function serverSpan(method, path) {
@@ -35,3 +38,38 @@ const statusOf = (e) => {
35
38
  return (x && (x.status || x.statusCode)) || 500;
36
39
  };
37
40
  exports.statusOf = statusOf;
41
+ /** `/base/:id` from an Express (or Nest-on-Express) request: `baseUrl` plus the matched `route.path`; undefined when no string route matched. */
42
+ function expressRoute(req) {
43
+ const p = req.route?.path;
44
+ return typeof p === 'string' ? `${req.baseUrl || ''}${p}` : undefined;
45
+ }
46
+ /** http instrumentation `applyCustomAttributesOnSpan` hook: when the response ends, name the server span `METHOD /route/:param`. Off with `WT_ROUTE_NAMES=0`. */
47
+ function routeNamer(span, req) {
48
+ if (['0', 'off', 'false', 'no'].includes((process.env.WT_ROUTE_NAMES || '').trim().toLowerCase()))
49
+ return;
50
+ const route = expressRoute(req);
51
+ if (!route)
52
+ return;
53
+ span.updateName(`${req.method || 'GET'} ${route}`);
54
+ span.setAttribute('http.route', route);
55
+ }
56
+ /** The active span when it is a recording SERVER span (made by the http instrumentation), wrapped so finish() enriches it and never ends it; else undefined. */
57
+ function adoptServerSpan(method) {
58
+ const span = api_1.trace.getActiveSpan();
59
+ if (!span || !span.isRecording() || span.kind !== api_1.SpanKind.SERVER)
60
+ return undefined;
61
+ return {
62
+ span,
63
+ ctx: api_1.context.active(),
64
+ finish(status, route) {
65
+ if (route) {
66
+ span.updateName(`${method} ${route}`);
67
+ span.setAttribute('http.route', route);
68
+ }
69
+ if (status)
70
+ span.setAttribute('http.response.status_code', status);
71
+ if (status !== undefined && status >= 500)
72
+ span.setStatus({ code: api_1.SpanStatusCode.ERROR });
73
+ },
74
+ };
75
+ }
@@ -1,3 +1,9 @@
1
+ /** Where peers are searched, in order: the SDK's own location, the cwd, the entry script's directory (pnpm monorepo apps run from the repo root). */
2
+ export declare function searchPaths(): string[];
1
3
  export declare function load(id: string): unknown;
4
+ export declare const SDK_PEERS: string[];
2
5
  /** Load an OpenTelemetry SDK package (an optional peer); a missing one throws an error naming what to install. */
3
6
  export declare function need<T>(id: string): T;
7
+ export declare const STANDALONE_HINT = "use withWatchtower() from @watchtowerobservability/next, or add them to serverExternalPackages and outputFileTracingIncludes in next.config";
8
+ /** Required OpenTelemetry peers that cannot be loaded from the SDK's location or the app root. */
9
+ export declare function missingPeers(): string[];
package/dist/cjs/load.js CHANGED
@@ -1,16 +1,27 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.STANDALONE_HINT = exports.SDK_PEERS = void 0;
7
+ exports.searchPaths = searchPaths;
3
8
  exports.load = load;
4
9
  exports.need = need;
10
+ exports.missingPeers = missingPeers;
5
11
  // Optional-peer loader (same source for the CommonJS and ESM builds).
6
12
  const node_module_1 = require("node:module");
13
+ const node_path_1 = __importDefault(require("node:path"));
7
14
  // Bundlers must NOT follow this: an optional peer the app did not install would make webpack warn "Module not found",
8
15
  // and a bare require call on a variable id is a "Critical dependency" warning. createRequire() is opaque to webpack/esbuild/Next's tracer,
9
16
  // so peers resolve at run time from the SDK's own location, then from the app root (cwd). Install the peers in the app
10
17
  // (pnpm: as direct dependencies); for a Next standalone build add them to outputFileTracingIncludes.
18
+ /** Where peers are searched, in order: the SDK's own location, the cwd, the entry script's directory (pnpm monorepo apps run from the repo root). */
19
+ function searchPaths() {
20
+ const entry = process.argv[1] ? `${node_path_1.default.dirname(node_path_1.default.resolve(process.argv[1]))}/` : '';
21
+ return [typeof __filename === 'string' ? __filename : '', `${process.cwd()}/`, entry].filter(Boolean);
22
+ }
11
23
  function resolvers() {
12
- const from = [typeof __filename === 'string' ? __filename : '', `${process.cwd()}/`].filter(Boolean);
13
- return from.map((f) => (0, node_module_1.createRequire)(f));
24
+ return searchPaths().map((f) => (0, node_module_1.createRequire)(f));
14
25
  }
15
26
  function load(id) {
16
27
  let err;
@@ -26,7 +37,7 @@ function load(id) {
26
37
  }
27
38
  throw err;
28
39
  }
29
- const SDK_PEERS = [
40
+ exports.SDK_PEERS = [
30
41
  '@opentelemetry/context-async-hooks', '@opentelemetry/core', '@opentelemetry/exporter-logs-otlp-http',
31
42
  '@opentelemetry/exporter-metrics-otlp-http', '@opentelemetry/exporter-trace-otlp-http', '@opentelemetry/otlp-transformer',
32
43
  '@opentelemetry/resources', '@opentelemetry/sdk-logs', '@opentelemetry/sdk-metrics', '@opentelemetry/sdk-trace',
@@ -38,8 +49,21 @@ function need(id) {
38
49
  }
39
50
  catch (e) {
40
51
  if (e?.code === 'MODULE_NOT_FOUND' && String(e.message).includes(id)) {
41
- throw new Error(`@watchtowerobservability/node needs the OpenTelemetry SDK, which is not installed (missing ${id}). Run: npm install ${SDK_PEERS.join(' ')}`);
52
+ throw new Error(`@watchtowerobservability/node needs the OpenTelemetry SDK, which is not installed (missing ${id}). Run: npm install ${exports.SDK_PEERS.join(' ')}`);
42
53
  }
43
54
  throw e;
44
55
  }
45
56
  }
57
+ exports.STANDALONE_HINT = 'use withWatchtower() from @watchtowerobservability/next, or add them to serverExternalPackages and outputFileTracingIncludes in next.config';
58
+ /** Required OpenTelemetry peers that cannot be loaded from the SDK's location or the app root. */
59
+ function missingPeers() {
60
+ return exports.SDK_PEERS.filter((id) => {
61
+ try {
62
+ load(id);
63
+ return false;
64
+ }
65
+ catch {
66
+ return true;
67
+ }
68
+ });
69
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ // `wt-next-doctor [dir]`: exit 1 when .next/standalone lacks the SDK or an OpenTelemetry peer (see next-doctor.ts).
5
+ const next_doctor_js_1 = require("./next-doctor.js");
6
+ const load_js_1 = require("./load.js");
7
+ const missing = (0, next_doctor_js_1.standaloneMissing)(process.argv[2]);
8
+ if (!missing)
9
+ console.log('[watchtower] no .next/standalone found; nothing to check');
10
+ else if (missing.length) {
11
+ console.error(`[watchtower] missing from .next/standalone/node_modules: ${missing.join(', ')}\n[watchtower] fix: ${load_js_1.STANDALONE_HINT}`);
12
+ process.exit(1);
13
+ }
14
+ else
15
+ console.log('[watchtower] standalone build includes the SDK and its OpenTelemetry peers');
@@ -0,0 +1,2 @@
1
+ /** Packages missing from `<dir>/.next/standalone/node_modules`; undefined when there is no standalone build. */
2
+ export declare function standaloneMissing(dir?: string): string[] | undefined;
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.standaloneMissing = standaloneMissing;
37
+ // After `next build` with output 'standalone', check that the SDK and its OpenTelemetry peers were traced into
38
+ // .next/standalone/node_modules (npm layout, or pnpm's .pnpm store). Exits 1 when any is missing.
39
+ const fs = __importStar(require("node:fs"));
40
+ const nodePath = __importStar(require("node:path"));
41
+ const load_js_1 = require("./load.js");
42
+ /** Packages missing from `<dir>/.next/standalone/node_modules`; undefined when there is no standalone build. */
43
+ function standaloneMissing(dir = '.') {
44
+ const nm = nodePath.join(dir, '.next', 'standalone', 'node_modules');
45
+ if (!fs.existsSync(nodePath.join(dir, '.next', 'standalone')))
46
+ return undefined;
47
+ const pnpm = nodePath.join(nm, '.pnpm');
48
+ const store = fs.existsSync(pnpm) ? fs.readdirSync(pnpm) : [];
49
+ return ['@watchtowerobservability/node', ...load_js_1.SDK_PEERS].filter((id) => !fs.existsSync(nodePath.join(nm, id)) && !store.some((e) => e.startsWith(`${id.replace('/', '+')}@`)));
50
+ }
@@ -4,3 +4,5 @@
4
4
  * sample labels. Frame names keep their `(file:line)` suffix; one function per distinct frame.
5
5
  */
6
6
  export declare function foldedToPprof(counts: Map<string, number>, periodNs: number, startMs: number, durationMs: number): Uint8Array;
7
+ /** Live heap stacks (`a;b;c` root first) with `[objects, bytes]` to a pprof with inuse_objects/count and inuse_space/bytes. */
8
+ export declare function heapToPprof(stacks: Map<string, [number, number]>, periodBytes: number, startMs: number, durationMs: number): Uint8Array;
package/dist/cjs/pprof.js CHANGED
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.foldedToPprof = foldedToPprof;
4
+ exports.heapToPprof = heapToPprof;
4
5
  // Minimal pprof (profile.proto) encoder, no dependency: folded stacks in, gzipped protobuf out.
5
6
  const node_zlib_1 = require("node:zlib");
6
7
  /** Protobuf writer for the handful of field shapes profile.proto needs. */
@@ -44,6 +45,16 @@ class Pb {
44
45
  * sample labels. Frame names keep their `(file:line)` suffix; one function per distinct frame.
45
46
  */
46
47
  function foldedToPprof(counts, periodNs, startMs, durationMs) {
48
+ const rows = new Map();
49
+ for (const [k, n] of counts)
50
+ rows.set(k, [n, n * periodNs]);
51
+ return encodePprof([['samples', 'count'], ['cpu', 'nanoseconds']], rows, ['cpu', 'nanoseconds'], periodNs, startMs, durationMs);
52
+ }
53
+ /** Live heap stacks (`a;b;c` root first) with `[objects, bytes]` to a pprof with inuse_objects/count and inuse_space/bytes. */
54
+ function heapToPprof(stacks, periodBytes, startMs, durationMs) {
55
+ return encodePprof([['inuse_objects', 'count'], ['inuse_space', 'bytes']], stacks, ['space', 'bytes'], periodBytes, startMs, durationMs);
56
+ }
57
+ function encodePprof(types, counts, periodType, period, startMs, durationMs) {
47
58
  const strings = [''];
48
59
  const index = new Map([['', 0]]);
49
60
  const s = (x) => {
@@ -55,10 +66,12 @@ function foldedToPprof(counts, periodNs, startMs, durationMs) {
55
66
  }
56
67
  return i;
57
68
  };
58
- const vt = (type, unit) => new Pb().int(1, s(type)).int(2, s(unit));
69
+ const vt = ([type, unit]) => new Pb().int(1, s(type)).int(2, s(unit));
59
70
  const frames = new Map();
60
- const out = new Pb().msg(1, vt('samples', 'count')).msg(1, vt('cpu', 'nanoseconds'));
61
- for (const [key, n] of counts) {
71
+ const out = new Pb();
72
+ for (const t of types)
73
+ out.msg(1, vt(t));
74
+ for (const [key, values] of counts) {
62
75
  const tab = key.indexOf('\t');
63
76
  const labels = tab >= 0 ? key.slice(0, tab) : '';
64
77
  // pprof location ids are leaf first
@@ -68,7 +81,7 @@ function foldedToPprof(counts, periodNs, startMs, durationMs) {
68
81
  frames.set(f, (id = frames.size + 1));
69
82
  return id;
70
83
  });
71
- const sample = new Pb().packed(1, ids).packed(2, [n, n * periodNs]);
84
+ const sample = new Pb().packed(1, ids).packed(2, values);
72
85
  for (const kv of labels ? labels.split(',') : []) {
73
86
  const eq = kv.indexOf('=');
74
87
  if (eq > 0)
@@ -81,7 +94,7 @@ function foldedToPprof(counts, periodNs, startMs, durationMs) {
81
94
  out.msg(5, new Pb().int(1, id).int(2, s(f))); // Function{id, name}
82
95
  }
83
96
  out.int(9, BigInt(Math.round(startMs)) * 1000000n).int(10, BigInt(Math.round(durationMs)) * 1000000n);
84
- out.msg(11, vt('cpu', 'nanoseconds')).int(12, periodNs);
97
+ out.msg(11, vt(periodType)).int(12, period);
85
98
  for (const str of strings)
86
99
  out.bytes(6, Buffer.from(str));
87
100
  return new Uint8Array((0, node_zlib_1.gzipSync)(Uint8Array.from(out.b)));
@@ -38,7 +38,29 @@ export declare function withSpan<T>(fn: () => T, ids?: {
38
38
  }): T;
39
39
  /** Takes the intervals a profile up to `until` can need; open ones stay for the next profile. */
40
40
  export declare function takeIntervals(until: number): SpanInterval[];
41
+ /** V8's sampling heap profile: a tree of live (not yet collected) sampled allocations. */
42
+ export interface HeapProfileNode {
43
+ callFrame: CallFrame;
44
+ selfSize: number;
45
+ id: number;
46
+ children?: HeapProfileNode[];
47
+ }
48
+ export interface HeapProfile {
49
+ head: HeapProfileNode;
50
+ samples?: {
51
+ size: number;
52
+ nodeId: number;
53
+ ordinal: number;
54
+ }[];
55
+ }
56
+ export type ProfileType = 'cpu' | 'heap';
57
+ /** `cpu,heap` (WT_PROFILING_TYPES) to types; unknown names are ignored, nothing valid means cpu only. */
58
+ export declare function parseProfilingTypes(v?: string): ProfileType[];
41
59
  export interface ProfilerOptions {
60
+ /** Profile types (default: WT_PROFILING_TYPES, else `['cpu']`). `heap` adds V8's sampling heap profiler. */
61
+ types?: ProfileType[];
62
+ /** Heap sampling interval in bytes (default 524 288). */
63
+ heapIntervalBytes?: number;
42
64
  /** Ingest key; defaults to WT_INGEST_KEY. */
43
65
  apiKey?: string;
44
66
  /** Gateway base URL; defaults to WT_OTLP_ENDPOINT or http://localhost:4318. */
@@ -55,6 +77,11 @@ export interface ProfilerOptions {
55
77
  }
56
78
  /** Root-first folded stacks with their sample counts; V8's synthetic `(root)` is left out. */
57
79
  export declare function foldProfile(p: CpuProfile, spans?: SpanInterval[]): Map<string, number>;
80
+ /**
81
+ * Root-first stacks of live heap with `[objects, bytes]`: bytes are the node's self size, objects the
82
+ * number of sampled allocations that still live in it (at least 1 for a node with bytes).
83
+ */
84
+ export declare function foldHeap(p: HeapProfile): Map<string, [number, number]>;
58
85
  export declare function foldedBody(counts: Map<string, number>): string;
59
86
  /** `/v1/profiles?format=pprof&service=…&version=…` on the gateway. */
60
87
  export declare function profilesUrl(endpoint: string, service: string, version?: string): string;
@@ -69,6 +96,8 @@ export declare class Profiler {
69
96
  private readonly tags;
70
97
  private readonly intervalUs;
71
98
  private readonly periodMs;
99
+ private readonly types;
100
+ private readonly heapIntervalBytes;
72
101
  private session?;
73
102
  private timer?;
74
103
  private from;
@@ -77,7 +106,9 @@ export declare class Profiler {
77
106
  start(): Promise<this>;
78
107
  /** Stop the current profile, upload it and (when `restart`) start the next one. */
79
108
  flush(restart: boolean): Promise<void>;
109
+ uploadHeap(stacks: Map<string, [number, number]>, fromS: number, untilS: number): Promise<void>;
80
110
  upload(counts: Map<string, number>, fromS: number, untilS: number): Promise<void>;
111
+ private send;
81
112
  stop(): Promise<void>;
82
113
  }
83
114
  /** Start a [[Profiler]] with the SDK's environment defaults. */