intellim-node-sdk 1.1.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +22 -5
  2. package/index.js +409 -65
  3. package/package.json +3 -2
package/README.md CHANGED
@@ -35,11 +35,18 @@ That's it — every request handled after this point is automatically traced.
35
35
 
36
36
  ## Distributed tracing across services
37
37
 
38
- If this app calls another IntelliM-instrumented service over HTTP, the
39
- current request's trace ID is automatically propagated onto that outgoing
40
- call — no extra code needed. The two services' spans show up correlated
41
- under one trace in the IntelliM dashboard, instead of two disconnected
42
- traces.
38
+ If this app calls another service over HTTP, the current request's trace
39
+ context is automatically propagated onto that outgoing call via the
40
+ standard [W3C Trace Context](https://www.w3.org/TR/trace-context/)
41
+ `traceparent` header — no extra code needed. This works whether the other
42
+ service is also running IntelliM, or any other OpenTelemetry-compatible
43
+ tool (Datadog, New Relic, SigNoz, a raw OTel SDK, etc.) — the trace
44
+ continues correctly either way, since `traceparent` is the same header
45
+ every compliant tool already reads. (A legacy `x-intellim-trace-id`/
46
+ `x-intellim-span-id` pair is also still sent, purely so an
47
+ already-deployed older IntelliM SDK instance on the other end of a call
48
+ keeps working during a gradual upgrade — new deployments should rely on
49
+ `traceparent`.)
43
50
 
44
51
  This works by patching Node's core `http`/`https` modules (not by patching
45
52
  whatever HTTP client library your app happens to use) — the two SDK
@@ -56,6 +63,16 @@ across the boundary regardless of which library made the actual call.
56
63
  | `backendUrl` | No | `http://localhost:3001` | Your IntelliM backend's URL |
57
64
  | `apiKey` | No* | `process.env.INTELLIM_API_KEY` | *Required for any data to actually be accepted — falls back to the env var if not passed explicitly |
58
65
  | `debug` | No | `false` | Logs `[NexusRUM]`-style debug lines to the console |
66
+ | `traceSampleRate` | No | `1` (100%) | Fraction of traces to send for successful, fast requests. **Errors and requests over 1s are always sent regardless of this setting** — sampling only thins out the "nothing went wrong" traces. Set e.g. `0.2` to send ~20% of routine traces on a high-traffic service. |
67
+
68
+ ## Overhead: batching
69
+
70
+ Traces, logs, and per-request metrics are buffered in memory and sent as a
71
+ single batched request every few seconds (or once 50 items queue up,
72
+ whichever comes first) — not one HTTP call per request. On a busy service
73
+ this is the difference between hundreds of outbound requests per second and
74
+ a handful. Buffered data is flushed immediately on graceful shutdown
75
+ (`SIGTERM`/`SIGINT`) so nothing queued is lost.
59
76
 
60
77
  ## License
61
78
 
package/index.js CHANGED
@@ -27,7 +27,10 @@
27
27
  const axios = require("axios");
28
28
  const http = require("http");
29
29
  const https = require("https");
30
+ const crypto = require("crypto");
31
+ const util = require("util");
30
32
  const { AsyncLocalStorage } = require("async_hooks");
33
+ const Hook = require("require-in-the-middle");
31
34
 
32
35
  let config = {};
33
36
  let requestCount = 0;
@@ -35,9 +38,14 @@ let errorCount = 0;
35
38
  let totalDuration = 0;
36
39
 
37
40
  const log = (msg) => console.log(`[IntelliM] ${msg}`);
38
- const genId = () =>
39
- Math.random().toString(36).slice(2, 12) +
40
- Math.random().toString(36).slice(2, 12);
41
+
42
+ // IDs generated with Node's crypto module, in the exact byte lengths the
43
+ // W3C Trace Context spec requires (see below) -- not just "random enough",
44
+ // the actual required SIZE: a trace ID is 16 bytes (32 hex chars), a span
45
+ // ID is 8 bytes (16 hex chars). The old genId() produced one ~20-char
46
+ // base36 string used for both, which was never valid in either slot.
47
+ const genTraceId = () => crypto.randomBytes(16).toString("hex");
48
+ const genSpanId = () => crypto.randomBytes(8).toString("hex");
41
49
 
42
50
  // Holds { traceId, spanId } for whichever request is currently being
43
51
  // handled, scoped correctly per-request even under concurrent async work —
@@ -49,8 +57,36 @@ const genId = () =>
49
57
  // traces instead of one correlated trace — this is the fix for that.
50
58
  const traceContext = new AsyncLocalStorage();
51
59
 
52
- const TRACE_ID_HEADER = "x-intellim-trace-id";
53
- const SPAN_ID_HEADER = "x-intellim-span-id";
60
+ // W3C Trace Context (https://www.w3.org/TR/trace-context/) -- the actual
61
+ // cross-vendor standard every real APM/OTel tool looks for, instead of a
62
+ // made-up header name only this SDK understood. Confirmed live
63
+ // (2026-10-15 audit): a trace crossing from an IntelliM-instrumented
64
+ // service into ANY differently-instrumented service (a competitor's
65
+ // agent, a raw OpenTelemetry SDK, a 3rd-party API) silently snapped into
66
+ // two disconnected traces at that boundary, because the other side never
67
+ // recognized x-intellim-trace-id/x-intellim-span-id at all. Format:
68
+ // "00-<32 hex trace id>-<16 hex parent span id>-<2 hex flags>".
69
+ const TRACEPARENT_HEADER = "traceparent";
70
+ const TRACEPARENT_RE = /^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;
71
+ const buildTraceparent = (traceId, spanId, sampled = true) => `00-${traceId}-${spanId}-${sampled ? "01" : "00"}`;
72
+ // Per spec, a traceparent that doesn't parse should be treated as if it
73
+ // were never sent (start a fresh trace), not crash the request or fall
74
+ // back to guessing -- a malformed header from some unrelated proxy/client
75
+ // should never take down the app it's supposed to be monitoring.
76
+ const parseTraceparent = (header) => {
77
+ const m = typeof header === "string" && header.match(TRACEPARENT_RE);
78
+ if (!m) return null;
79
+ // An all-zero trace/span ID is explicitly invalid per spec (reserved as
80
+ // "no trace"), same as a client that forgot to actually generate one.
81
+ if (/^0+$/.test(m[1]) || /^0+$/.test(m[2])) return null;
82
+ return { traceId: m[1], parentSpanId: m[2] };
83
+ };
84
+ // Kept as a fallback read (not written) so a request from an
85
+ // already-deployed older SDK instance mid-upgrade still continues its
86
+ // trace correctly instead of silently starting a new one the moment one
87
+ // side of a call updates before the other.
88
+ const LEGACY_TRACE_ID_HEADER = "x-intellim-trace-id";
89
+ const LEGACY_SPAN_ID_HEADER = "x-intellim-span-id";
54
90
 
55
91
  // Propagates the current request's trace context onto any outgoing HTTP
56
92
  // call the instrumented app makes (e.g. calling another instrumented
@@ -78,10 +114,52 @@ function patchOutgoingRequests() {
78
114
  if (_patched) return;
79
115
  _patched = true;
80
116
 
81
- const addTraceHeaders = (headers) => {
117
+ // Best-effort "what host is this call even going to" -- used only to
118
+ // record a breadcrumb (see calledHosts below), never to decide whether
119
+ // to add trace headers (that happens regardless of whether this parses).
120
+ const safeHost = (input) => {
121
+ try {
122
+ if (typeof input === "string") return new URL(input, "http://placeholder.invalid").host;
123
+ if (input instanceof URL) return input.host;
124
+ if (input && typeof input === "object") {
125
+ // Node's http.request options (and what axios builds internally)
126
+ // commonly carry `hostname` + `port` as two separate fields rather
127
+ // than one combined `host` -- confirmed live: without this, a call
128
+ // to "localhost:3003" was recorded as just "localhost", silently
129
+ // dropping the port, which matters since multiple local services
130
+ // on different ports is exactly the common case this is meant to
131
+ // disambiguate.
132
+ if (input.host) return input.host;
133
+ if (input.hostname) return input.port ? `${input.hostname}:${input.port}` : input.hostname;
134
+ }
135
+ } catch (_) {}
136
+ return "";
137
+ };
138
+
139
+ const addTraceHeaders = (headers, host) => {
82
140
  const ctx = traceContext.getStore();
83
141
  if (!ctx) return headers;
84
- return { ...(headers || {}), [TRACE_ID_HEADER]: ctx.traceId, [SPAN_ID_HEADER]: ctx.spanId };
142
+ // Item #2 of the tracing gaps ("uninstrumented hops silently break the
143
+ // trace chain") -- recorded here, not as a new span/request of its own
144
+ // (a prior version of this SDK did auto-record a span for every
145
+ // outgoing call and that caused a real feedback-loop bug, see this
146
+ // file's header comment; this carries no such risk since it only
147
+ // appends to data already being sent for the CURRENT request, nothing
148
+ // new is sent). If this host never calls back with a child span of its
149
+ // own, the frontend waterfall can at least show "called out here, nothing
150
+ // came back" instead of the trace just silently ending with no sign why.
151
+ if (host && ctx.calledHosts && !ctx.calledHosts.includes(host)) ctx.calledHosts.push(host);
152
+ return {
153
+ ...(headers || {}),
154
+ [TRACEPARENT_HEADER]: buildTraceparent(ctx.traceId, ctx.spanId),
155
+ // Kept alongside traceparent for one transition window -- lets an
156
+ // already-deployed older instance of THIS SDK (which only reads the
157
+ // legacy headers) on the other end of the call still continue the
158
+ // trace correctly during a gradual rollout, rather than only working
159
+ // once every service has upgraded simultaneously.
160
+ [LEGACY_TRACE_ID_HEADER]: ctx.traceId,
161
+ [LEGACY_SPAN_ID_HEADER]: ctx.spanId,
162
+ };
85
163
  };
86
164
 
87
165
  for (const mod of [http, https]) {
@@ -89,13 +167,13 @@ function patchOutgoingRequests() {
89
167
  mod.request = (...args) => {
90
168
  if (args[0] && typeof args[0] === "object" && !(args[0] instanceof URL)) {
91
169
  // request(options[, callback])
92
- args[0] = { ...args[0], headers: addTraceHeaders(args[0].headers) };
170
+ args[0] = { ...args[0], headers: addTraceHeaders(args[0].headers, safeHost(args[0])) };
93
171
  } else if (typeof args[1] === "object" && args[1] !== null) {
94
172
  // request(url, options[, callback])
95
- args[1] = { ...args[1], headers: addTraceHeaders(args[1].headers) };
173
+ args[1] = { ...args[1], headers: addTraceHeaders(args[1].headers, safeHost(args[0])) };
96
174
  } else {
97
175
  // request(url[, callback]) — no options object to merge into, insert one
98
- args.splice(1, 0, { headers: addTraceHeaders() });
176
+ args.splice(1, 0, { headers: addTraceHeaders(undefined, safeHost(args[0])) });
99
177
  }
100
178
  return originalRequest(...args);
101
179
  };
@@ -112,6 +190,192 @@ function patchOutgoingRequests() {
112
190
  }
113
191
  }
114
192
 
193
+ // Strips literal values out of a SQL query string before it's ever queued
194
+ // for sending -- the raw text can contain real customer data (emails,
195
+ // tokens, names) as inline literals, and sending that to this SDK's own
196
+ // backend would leak it straight into trace storage. Replaces every
197
+ // single-quoted string and bare number with "?", which also happens to
198
+ // group together queries that only differ by their literal values (the
199
+ // same query run a thousand times with different IDs reads as one query
200
+ // shape, not a thousand distinct ones).
201
+ const sanitizeSqlText = (text) => {
202
+ if (typeof text !== "string") return "";
203
+ return text
204
+ .replace(/'(?:[^'\\]|\\.)*'/g, "?")
205
+ .replace(/\b\d+\b/g, "?")
206
+ .slice(0, 500);
207
+ };
208
+
209
+ // Best-effort "which table is this query about" -- good enough for a UI
210
+ // label, not a real SQL parser. Matches the common FROM/INTO/UPDATE forms;
211
+ // anything fancier (CTEs, joins-only subqueries) just comes back empty,
212
+ // which is a reasonable fallback rather than guessing wrong.
213
+ const extractTableName = (text) => {
214
+ if (typeof text !== "string") return "";
215
+ const m = /\b(?:from|into|update)\s+"?([a-zA-Z_][\w.]*)"?/i.exec(text);
216
+ return m ? m[1] : "";
217
+ };
218
+
219
+ // Auto-instruments the `pg` (node-postgres) driver so every query made by
220
+ // the instrumented app shows up as a child span under whichever HTTP
221
+ // request triggered it -- item #1 of the tracing gaps ("Database query
222
+ // tracing -- not tracked at all"). Patches `Client.prototype.query`
223
+ // specifically (not `Pool.prototype.query`) because pg's own Pool
224
+ // internally checks out a real Client and calls its `.query()` to actually
225
+ // run anything, so this one patch point covers both direct-Client and
226
+ // Pool-based usage without needing two separate wrappers.
227
+ //
228
+ // Hooked via `require-in-the-middle` rather than this SDK calling
229
+ // `require("pg")` itself -- a plain `require("pg")` from inside this file
230
+ // resolves relative to THIS file's own location, which in a monorepo (or
231
+ // any dependency tree where "pg" ends up nested/duplicated rather than
232
+ // hoisted to one shared copy) can silently be a DIFFERENT copy of the `pg`
233
+ // module than the one the consuming app actually calls `.query()` on --
234
+ // patching that prototype then does nothing, with no error anywhere to
235
+ // show it. require-in-the-middle instead hooks Node's own module-loading
236
+ // machinery, so it intercepts and patches the actual `pg` module object
237
+ // returned to the FIRST real `require("pg")` call made anywhere in the
238
+ // process (by the app, by whatever ORM it uses, etc.), guaranteeing this
239
+ // patches the real thing in use. This only works if that first real
240
+ // `require("pg")` happens after this SDK's own init() -- the one-line
241
+ // usage this SDK has always asked for ("Load IntelliM SDK FIRST") already
242
+ // guarantees that ordering for anyone following it.
243
+ let _pgHookInstalled = false;
244
+ function patchPgQueries() {
245
+ if (_pgHookInstalled) return;
246
+ _pgHookInstalled = true;
247
+
248
+ Hook(["pg"], (exports) => {
249
+ if (!exports || !exports.Client || !exports.Client.prototype || exports.Client.prototype.__intellimPatched) {
250
+ return exports;
251
+ }
252
+ exports.Client.prototype.__intellimPatched = true;
253
+ const originalQuery = exports.Client.prototype.query;
254
+ exports.Client.prototype.query = function (...args) {
255
+ const ctx = traceContext.getStore();
256
+ const start = Date.now();
257
+ const queryConfig = args[0];
258
+ const queryText = typeof queryConfig === "string" ? queryConfig : (queryConfig && queryConfig.text) || "";
259
+
260
+ const recordSpan = (ok, err) => {
261
+ const duration = Date.now() - start;
262
+ // No active request context means this query ran outside any traced
263
+ // HTTP request (a background job, a startup migration) -- still
264
+ // worth recording, just as the root of its own trace rather than
265
+ // dropping it, since "query tracing silently does nothing outside
266
+ // a request" would be its own gap.
267
+ const traceId = (ctx && ctx.traceId) || genTraceId();
268
+ traceQueue.push({
269
+ service: config.serviceName,
270
+ traceId,
271
+ spanId: genSpanId(),
272
+ parentSpanId: (ctx && ctx.spanId) || "",
273
+ name: "pg.query",
274
+ kind: "db",
275
+ route: "",
276
+ method: "",
277
+ duration,
278
+ status: ok ? 200 : 500,
279
+ type: "trace",
280
+ version: config.version,
281
+ environment: config.environment,
282
+ tags: {
283
+ "db.system": "postgresql",
284
+ "db.statement": sanitizeSqlText(queryText),
285
+ "db.table": extractTableName(queryText),
286
+ ...(err ? { error: String((err && err.message) || err) } : {}),
287
+ },
288
+ timestamp: new Date().toISOString(),
289
+ });
290
+ if (traceQueue.length >= BATCH_MAX_SIZE) flushTraces();
291
+ };
292
+
293
+ // pg's Client.query supports two calling conventions -- promise-based
294
+ // (no callback, the common/modern form) and callback-based (last arg
295
+ // is a function, still valid and still used in plenty of real apps).
296
+ // Only one of these branches can know when the query actually finished:
297
+ // the callback form must wrap the callback itself, since the original
298
+ // call returns before the query completes either way.
299
+ const lastIdx = args.length - 1;
300
+ if (typeof args[lastIdx] === "function") {
301
+ const originalCallback = args[lastIdx];
302
+ const wrappedArgs = args.slice();
303
+ wrappedArgs[lastIdx] = function (err, res) {
304
+ recordSpan(!err, err);
305
+ return originalCallback.apply(this, arguments);
306
+ };
307
+ return originalQuery.apply(this, wrappedArgs);
308
+ }
309
+
310
+ const result = originalQuery.apply(this, args);
311
+ if (result && typeof result.then === "function") {
312
+ return result.then(
313
+ (res) => { recordSpan(true); return res; },
314
+ (err) => { recordSpan(false, err); throw err; }
315
+ );
316
+ }
317
+ // Neither a promise nor given a callback -- pg always returns one or
318
+ // the other for every supported call shape, but recording a span here
319
+ // rather than silently skipping keeps this correct even against a
320
+ // future pg version this wasn't written against.
321
+ recordSpan(true);
322
+ return result;
323
+ };
324
+ return exports;
325
+ });
326
+ }
327
+
328
+ // Captures arbitrary application log output -- item #1 of the log-
329
+ // management gaps ("only SDK-generated HTTP logs are captured, not
330
+ // application logs"). Previously the SDK only ever synthesized its own
331
+ // log events for specific HTTP outcomes (errors, slow requests); anything
332
+ // the app itself logged (console.*, or a logger like winston/pino, which
333
+ // write to console by default unless reconfigured) never reached this
334
+ // platform at all. Patches the global console methods directly rather than
335
+ // integrating per-logging-library (winston transport, pino hook, etc.) --
336
+ // virtually everything ends up at console one way or another, so this is
337
+ // the one place that catches the broadest range of real-world logging
338
+ // setups for a single patch, at the cost of not being a "native" winston/
339
+ // pino integration for anyone who wants structured metadata beyond what a
340
+ // formatted string carries.
341
+ let _consolePatched = false;
342
+ function patchConsole() {
343
+ if (_consolePatched) return;
344
+ _consolePatched = true;
345
+
346
+ const original = {};
347
+ const levelFor = { log: "INFO", info: "INFO", warn: "WARN", error: "ERROR", debug: "DEBUG" };
348
+
349
+ for (const method of Object.keys(levelFor)) {
350
+ if (typeof console[method] !== "function") continue;
351
+ original[method] = console[method].bind(console);
352
+
353
+ console[method] = (...args) => {
354
+ // The app's own console output must look and behave exactly as it
355
+ // always did -- this only ever ADDS a side effect (shipping a copy),
356
+ // never changes what actually gets printed or how.
357
+ original[method](...args);
358
+ try {
359
+ const message = util.format(...args);
360
+ // This SDK's own "[IntelliM] ..." status/debug lines (from the
361
+ // `log()` helper above, which calls console.log directly and has
362
+ // no way to know it's now wrapped) must never be captured as if
363
+ // they were the MONITORED APPLICATION's own output -- that would
364
+ // be a feedback loop of the same family as the outgoing-HTTP one
365
+ // already fixed once before in this file, just via console instead
366
+ // of via network calls.
367
+ if (message.startsWith("[IntelliM]")) return;
368
+ const ctx = traceContext.getStore();
369
+ sendLog(levelFor[method], message, ctx && ctx.traceId, ctx && ctx.spanId).catch(() => {});
370
+ } catch (_) {
371
+ // A logging failure must never take down (or even visibly affect)
372
+ // the app's own console output, which original[method] above has
373
+ // already completed by this point regardless.
374
+ }
375
+ };
376
+ }
377
+ }
378
+
115
379
  // Best-effort human-readable reason for a failed network call. Axios errors
116
380
  // normally have a real .message ("Request failed with status code 401",
117
381
  // "connect ECONNREFUSED ..."), but Node's dual-stack "happy eyeballs"
@@ -183,6 +447,30 @@ const init = (userConfig = {}) => {
183
447
  // sets APP_VERSION/NODE_ENV doesn't need a code change to pick this up.
184
448
  version: userConfig.version || process.env.APP_VERSION || "",
185
449
  environment: userConfig.environment || process.env.NODE_ENV || "",
450
+ // Fraction of SUCCESSFUL, FAST requests to actually send a trace for
451
+ // (1 = every one, the default -- no behavior change unless a customer
452
+ // opts in). Errors (4xx/5xx) and slow requests (>1s) are ALWAYS traced
453
+ // regardless of this setting -- sampling only ever thins out the
454
+ // "nothing went wrong" traces, which are the vast majority on a
455
+ // high-traffic service and the least individually informative.
456
+ // Confirmed live (2026-10-14 audit): before this, every single request
457
+ // fired its own unbatched HTTP POST for its trace/log/metric, which is
458
+ // real overhead added to the app being monitored -- this plus the
459
+ // batching below is the fix.
460
+ traceSampleRate: userConfig.traceSampleRate !== undefined ? userConfig.traceSampleRate : 1,
461
+ // On by default -- a no-op for any app that doesn't `require("pg")` at
462
+ // all (patchPgQueries just returns), so there's no cost to leaving it
463
+ // on for apps it doesn't apply to. An explicit false lets a customer
464
+ // opt out if they'd rather not have SQL text (even sanitized) leave
465
+ // their process.
466
+ instrumentDb: userConfig.instrumentDb !== false,
467
+ // On by default -- this is the actual fix for "a client's own
468
+ // application logs never reach the platform at all." An explicit
469
+ // false lets a customer opt out if their own log lines might carry
470
+ // sensitive data they don't want leaving their process (unlike the pg
471
+ // query sanitizer, arbitrary console output has no safe way to
472
+ // automatically redact unknown-shaped content).
473
+ captureConsole: userConfig.captureConsole !== false,
186
474
  };
187
475
 
188
476
  if (!config.apiKey && config.debug) {
@@ -193,8 +481,13 @@ const init = (userConfig = {}) => {
193
481
  checkBackendReachable();
194
482
 
195
483
  patchOutgoingRequests();
484
+ if (config.instrumentDb) patchPgQueries();
485
+ if (config.captureConsole) patchConsole();
196
486
 
197
487
  startMetricsReporter();
488
+ traceFlushTimer = setInterval(flushTraces, BATCH_FLUSH_INTERVAL_MS);
489
+ logFlushTimer = setInterval(flushLogs, BATCH_FLUSH_INTERVAL_MS);
490
+ metricFlushTimer = setInterval(flushMetrics, BATCH_FLUSH_INTERVAL_MS);
198
491
 
199
492
  announceIdentity();
200
493
  setInterval(announceIdentity, ANNOUNCE_INTERVAL_MS);
@@ -216,14 +509,25 @@ const middleware = (req, res, next) => {
216
509
  const start = Date.now();
217
510
  requestCount++;
218
511
 
219
- // A trace ID arriving on the incoming request means an upstream
220
- // instrumented service is already mid-trace and this request is just the
221
- // next hop — continue that same trace instead of starting a new one. No
222
- // header means this request is the root of a brand-new trace.
223
- const incomingTraceId = req.headers[TRACE_ID_HEADER];
224
- const incomingSpanId = req.headers[SPAN_ID_HEADER];
225
- const traceId = incomingTraceId || genId();
226
- const spanId = genId();
512
+ // A trace context arriving on the incoming request means an upstream
513
+ // service is already mid-trace and this request is just the next hop —
514
+ // continue that same trace instead of starting a new one. No valid
515
+ // context means this request is the root of a brand-new trace.
516
+ // Prefers the standard traceparent header; falls back to the legacy
517
+ // custom headers only if traceparent is absent (an older, not-yet-
518
+ // upgraded caller), so a request's trace doesn't snap in two just
519
+ // because one side of a call upgraded before the other.
520
+ const parsed = parseTraceparent(req.headers[TRACEPARENT_HEADER]);
521
+ const incomingTraceId = parsed ? parsed.traceId : req.headers[LEGACY_TRACE_ID_HEADER];
522
+ const incomingSpanId = parsed ? parsed.parentSpanId : req.headers[LEGACY_SPAN_ID_HEADER];
523
+ const traceId = incomingTraceId || genTraceId();
524
+ const spanId = genSpanId();
525
+ // Populated by the outgoing-request patch below (via traceContext,
526
+ // since that patch may run deep inside a route handler, not here) --
527
+ // every distinct host this request called out to, used only to flag a
528
+ // hop that never called back with its own child span (item #2 of the
529
+ // tracing gaps: "uninstrumented hops silently break the trace chain").
530
+ const calledHosts = [];
227
531
 
228
532
  res.on("finish", async () => {
229
533
  const duration = Date.now() - start;
@@ -234,17 +538,28 @@ const middleware = (req, res, next) => {
234
538
  log(`${req.method} ${req.path} → ${res.statusCode} (${duration}ms)`);
235
539
  }
236
540
 
237
- await sendTrace({
238
- service: config.serviceName,
239
- traceId,
240
- spanId,
241
- parentSpanId: incomingSpanId || "",
242
- route: req.path,
243
- method: req.method,
244
- duration,
245
- status: res.statusCode,
246
- type: "trace",
247
- });
541
+ // Errors and slow requests are ALWAYS traced regardless of
542
+ // traceSampleRate -- sampling only ever thins out the "nothing went
543
+ // wrong, nothing slow" traces, never the ones actually worth looking at.
544
+ const isNotable = res.statusCode >= 400 || duration > 1000;
545
+ if (isNotable || Math.random() < config.traceSampleRate) {
546
+ traceQueue.push({
547
+ service: config.serviceName,
548
+ traceId,
549
+ spanId,
550
+ parentSpanId: incomingSpanId || "",
551
+ route: req.path,
552
+ method: req.method,
553
+ duration,
554
+ status: res.statusCode,
555
+ type: "trace",
556
+ version: config.version,
557
+ environment: config.environment,
558
+ timestamp: new Date().toISOString(),
559
+ ...(calledHosts.length > 0 ? { tags: { calledHosts } } : {}),
560
+ });
561
+ if (traceQueue.length >= BATCH_MAX_SIZE) await flushTraces();
562
+ }
248
563
 
249
564
  await sendMetric("response_time", duration, "ms");
250
565
 
@@ -269,7 +584,7 @@ const middleware = (req, res, next) => {
269
584
  // Everything downstream (the actual route handler, and any axios calls
270
585
  // it makes to other services) runs inside this context so the outgoing
271
586
  // interceptor below can find the current traceId/spanId.
272
- traceContext.run({ traceId, spanId }, () => next());
587
+ traceContext.run({ traceId, spanId, calledHosts }, () => next());
273
588
  };
274
589
 
275
590
  // All ingestion endpoints (/api/metrics, /api/logs, /api/traces) require an
@@ -277,53 +592,75 @@ const middleware = (req, res, next) => {
277
592
  // silently 401'd once those routes started requiring authentication.
278
593
  const authHeaders = () => (config.apiKey ? { "x-api-key": config.apiKey } : {});
279
594
 
280
- const sendMetric = async (name, value, unit = "") => {
595
+ // ── Batching ──────────────────────────────────────────────────────────────
596
+ // Previously sendMetric/sendLog/sendTrace each fired its OWN HTTP POST
597
+ // immediately -- on a busy service, that's one outbound network call per
598
+ // request just for response_time, another for the trace, plus whatever
599
+ // logs that request triggered. Real, unbounded overhead added to the app
600
+ // being monitored. Now every call just pushes onto an in-memory queue;
601
+ // a timer (and a size cap, so a traffic burst can't grow these unbounded
602
+ // in memory) flushes each queue as ONE batched POST instead -- same
603
+ // {items:[...]} batch shape routes/ingestion.js now accepts, matching
604
+ // what otlp.js/rum.js already do. Flushed again synchronously on shutdown
605
+ // so nothing buffered is lost on a graceful exit.
606
+ const BATCH_FLUSH_INTERVAL_MS = 3000;
607
+ const BATCH_MAX_SIZE = 50;
608
+ let traceQueue = [];
609
+ let logQueue = [];
610
+ let metricQueue = [];
611
+ let traceFlushTimer = null;
612
+ let logFlushTimer = null;
613
+ let metricFlushTimer = null;
614
+
615
+ const flushQueue = async (queueRef, setQueueRef, endpoint, label) => {
616
+ const batch = queueRef;
617
+ if (batch.length === 0) return;
618
+ setQueueRef([]);
281
619
  try {
282
- await axios.post(`${config.backendUrl}/api/metrics`, {
283
- service: config.serviceName,
284
- name,
285
- value,
286
- unit,
287
- timestamp: new Date().toISOString(),
288
- version: config.version,
289
- environment: config.environment,
290
- }, { headers: authHeaders() });
620
+ await axios.post(`${config.backendUrl}${endpoint}`, { items: batch }, { headers: authHeaders() });
291
621
  } catch (err) {
292
- if (config.debug) log(`metric ${name} failed: ${describeError(err)}`);
622
+ if (config.debug) log(`${label} batch (${batch.length}) failed: ${describeError(err)}`);
293
623
  }
294
624
  };
625
+ const flushTraces = () => flushQueue(traceQueue, q => { traceQueue = q; }, "/api/traces", "trace");
626
+ const flushLogs = () => flushQueue(logQueue, q => { logQueue = q; }, "/api/logs", "log");
627
+ const flushMetrics = () => flushQueue(metricQueue, q => { metricQueue = q; }, "/api/metrics", "metric");
628
+
629
+ const sendMetric = async (name, value, unit = "") => {
630
+ metricQueue.push({
631
+ service: config.serviceName, name, value, unit,
632
+ timestamp: new Date().toISOString(),
633
+ version: config.version, environment: config.environment,
634
+ });
635
+ if (metricQueue.length >= BATCH_MAX_SIZE) await flushMetrics();
636
+ };
295
637
 
296
638
  // traceId/spanId are optional -- a log sent outside a traced request
297
639
  // (startup/shutdown messages) has neither, and the backend already
298
640
  // defaults them to "" (see toLogDoc in the backend's kafka consumer).
299
641
  const sendLog = async (level, message, traceId, spanId) => {
300
- try {
301
- await axios.post(`${config.backendUrl}/api/logs`, {
302
- service: config.serviceName,
303
- level,
304
- message,
305
- timestamp: new Date().toISOString(),
306
- version: config.version,
307
- environment: config.environment,
308
- ...(traceId ? { traceId } : {}),
309
- ...(spanId ? { spanId } : {}),
310
- }, { headers: authHeaders() });
311
- } catch (err) {
312
- if (config.debug) log(`log failed: ${describeError(err)}`);
313
- }
642
+ logQueue.push({
643
+ service: config.serviceName, level, message,
644
+ timestamp: new Date().toISOString(),
645
+ version: config.version, environment: config.environment,
646
+ ...(traceId ? { traceId } : {}),
647
+ ...(spanId ? { spanId } : {}),
648
+ });
649
+ if (logQueue.length >= BATCH_MAX_SIZE) await flushLogs();
314
650
  };
315
651
 
652
+ // Manual sendTrace() calls (the public API) are never sampled -- sampling
653
+ // only applies to the middleware's own per-request traces below, since a
654
+ // caller reaching for sendTrace() directly clearly wants that specific
655
+ // trace recorded, not probabilistically dropped.
316
656
  const sendTrace = async (trace) => {
317
- try {
318
- await axios.post(`${config.backendUrl}/api/traces`, {
319
- version: config.version,
320
- environment: config.environment,
321
- ...trace,
322
- timestamp: new Date().toISOString(),
323
- }, { headers: authHeaders() });
324
- } catch (err) {
325
- if (config.debug) log(`trace failed: ${describeError(err)}`);
326
- }
657
+ traceQueue.push({
658
+ version: config.version,
659
+ environment: config.environment,
660
+ ...trace,
661
+ timestamp: new Date().toISOString(),
662
+ });
663
+ if (traceQueue.length >= BATCH_MAX_SIZE) await flushTraces();
327
664
  };
328
665
 
329
666
  const ROLLUP_INTERVAL_MS = 10000; // 10 seconds
@@ -363,6 +700,13 @@ const startMetricsReporter = () => {
363
700
  const shutdown = async () => {
364
701
  log("shutting down gracefully...");
365
702
  await sendLog("INFO", `IntelliM agent stopped — ${config.serviceName}`);
703
+ // Queued items wait up to BATCH_FLUSH_INTERVAL_MS for the next timer
704
+ // tick -- without this, whatever was queued (including the shutdown
705
+ // log line just above) is simply lost the moment the process exits.
706
+ clearInterval(traceFlushTimer);
707
+ clearInterval(logFlushTimer);
708
+ clearInterval(metricFlushTimer);
709
+ await Promise.all([flushTraces(), flushLogs(), flushMetrics()]);
366
710
  process.exit(0);
367
711
  };
368
712
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "intellim-node-sdk",
3
- "version": "1.1.0",
3
+ "version": "1.4.0",
4
4
  "main": "index.js",
5
5
  "files": [
6
6
  "index.js",
@@ -29,6 +29,7 @@
29
29
  },
30
30
  "homepage": "https://github.com/Intelli-APM/apm/tree/main/agent/intellim-node-sdk#readme",
31
31
  "dependencies": {
32
- "axios": "^1.17.0"
32
+ "axios": "^1.17.0",
33
+ "require-in-the-middle": "^8.0.1"
33
34
  }
34
35
  }