intellim-node-sdk 1.0.1 → 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 +713 -346
  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
@@ -1,346 +1,713 @@
1
- "use strict";
2
-
3
- // ============================================
4
- // intellim-node-sdk (CLEANED — Batch 1)
5
- // Auto-instrumentation SDK for Node.js / Express apps.
6
- //
7
- // Usage (one line):
8
- // const intellim = require("intellim-node-sdk");
9
- // const { middleware } = intellim.init({ serviceName: "my-app" });
10
- // app.use(middleware);
11
- //
12
- // Captures automatically, per request:
13
- // - route, method, status, duration -> trace
14
- // - response_time -> metric
15
- // - errors (4xx/5xx) + slow (>1s) -> logs
16
- // And every 10s, app-level rollups:
17
- // - app_memory_mb, app_avg_response_time,
18
- // app_total_requests, app_error_rate
19
- //
20
- // FIXES IN THIS VERSION:
21
- // - Removed the noisy ">>> REQUEST IN" debug line.
22
- // - Removed the old http.request monkey-patch that caused
23
- // a feedback loop (the 12k junk "outgoing_request_duration").
24
- // - Consistent metric names.
25
- // ============================================
26
-
27
- const axios = require("axios");
28
- const http = require("http");
29
- const https = require("https");
30
- const { AsyncLocalStorage } = require("async_hooks");
31
-
32
- let config = {};
33
- let requestCount = 0;
34
- let errorCount = 0;
35
- let totalDuration = 0;
36
-
37
- 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
- // Holds { traceId, spanId } for whichever request is currently being
43
- // handled, scoped correctly per-request even under concurrent async work —
44
- // this is what lets an outgoing axios call made deep inside a route handler
45
- // find "which request am I part of" without threading it through every
46
- // function call by hand. Previously every span picked a brand-new random
47
- // traceId with no relation to any incoming request, so a single logical
48
- // request crossing multiple instrumented services produced N unrelated
49
- // traces instead of one correlated trace — this is the fix for that.
50
- const traceContext = new AsyncLocalStorage();
51
-
52
- const TRACE_ID_HEADER = "x-intellim-trace-id";
53
- const SPAN_ID_HEADER = "x-intellim-span-id";
54
-
55
- // Propagates the current request's trace context onto any outgoing HTTP
56
- // call the instrumented app makes (e.g. calling another instrumented
57
- // service) — this is what actually makes tracing "distributed" rather than
58
- // each service recording its own disconnected spans.
59
- //
60
- // This patches Node's core http/https modules directly instead of axios's
61
- // interceptors. That's a deliberate choice, not a style preference: axios
62
- // is a separate npm package, and this SDK's own copy of it (in its own
63
- // node_modules) is a DIFFERENT module instance than whatever copy the
64
- // instrumented app has in ITS OWN node_modules — patching "the" axios
65
- // instance from inside this SDK never touches the app's own axios calls at
66
- // all, since each has its own private interceptor registry. http/https are
67
- // true Node built-ins, though — there's only ever one copy of them in a
68
- // given process, shared by every package (including axios's own Node
69
- // adapter, which is built on top of http.request), so patching them here
70
- // reliably reaches every outgoing call regardless of which HTTP client
71
- // library the app uses. Deliberately ONLY adds headers, nothing more — a
72
- // past version of this SDK auto-recorded a trace/metric for every outgoing
73
- // call and that created a feedback loop of junk data (see the "REMOVED"
74
- // note in this file's header comment); this carries no such risk since it
75
- // never sends anything itself, it only annotates requests already being made.
76
- let _patched = false;
77
- function patchOutgoingRequests() {
78
- if (_patched) return;
79
- _patched = true;
80
-
81
- const addTraceHeaders = (headers) => {
82
- const ctx = traceContext.getStore();
83
- if (!ctx) return headers;
84
- return { ...(headers || {}), [TRACE_ID_HEADER]: ctx.traceId, [SPAN_ID_HEADER]: ctx.spanId };
85
- };
86
-
87
- for (const mod of [http, https]) {
88
- const originalRequest = mod.request.bind(mod);
89
- mod.request = (...args) => {
90
- if (args[0] && typeof args[0] === "object" && !(args[0] instanceof URL)) {
91
- // request(options[, callback])
92
- args[0] = { ...args[0], headers: addTraceHeaders(args[0].headers) };
93
- } else if (typeof args[1] === "object" && args[1] !== null) {
94
- // request(url, options[, callback])
95
- args[1] = { ...args[1], headers: addTraceHeaders(args[1].headers) };
96
- } else {
97
- // request(url[, callback]) — no options object to merge into, insert one
98
- args.splice(1, 0, { headers: addTraceHeaders() });
99
- }
100
- return originalRequest(...args);
101
- };
102
- // http.get/https.get do NOT call the module's (possibly patched)
103
- // `.request` internally — Node's real implementation closes over its
104
- // own original `request` function at module-definition time, so
105
- // patching `.request` alone silently never affects `.get()`. Has to be
106
- // redefined explicitly, calling the NEW `mod.request` directly.
107
- mod.get = (...args) => {
108
- const req = mod.request(...args);
109
- req.end();
110
- return req;
111
- };
112
- }
113
- }
114
-
115
- // Best-effort human-readable reason for a failed network call. Axios errors
116
- // normally have a real .message ("Request failed with status code 401",
117
- // "connect ECONNREFUSED ..."), but Node's dual-stack "happy eyeballs"
118
- // connection attempt (used for a bare hostname like "localhost", which
119
- // resolves to both ::1 and 127.0.0.1) can produce an AggregateError whose
120
- // own top-level .message is blank by design — the real per-address reasons
121
- // live in .errors (or .cause.errors) instead. Without this, a debug log
122
- // silently prints "failed: " with nothing after it, which is exactly what
123
- // happened when a backendUrl was left pointing at localhost with nothing
124
- // listening there.
125
- const describeError = (err) => {
126
- if (err.message) return err.message;
127
- if (err.code) return err.code;
128
- const sub = err.errors || (err.cause && err.cause.errors);
129
- if (sub && sub.length) return sub.map(e => e.message || e.code).join(", ");
130
- return "unknown error";
131
- };
132
-
133
- // One-time reachability check right at startup — separate from the ongoing
134
- // per-call debug logs below, which stay silent unless debug:true. A wrong
135
- // or unreachable backendUrl otherwise fails completely silently in a real
136
- // deployment (debug is off by default), so a client could have zero data
137
- // arriving for weeks with no indication anything is wrong. This is always
138
- // printed, regardless of the debug flag, specifically so a misconfigured
139
- // backendUrl is never invisible.
140
- const checkBackendReachable = async () => {
141
- try {
142
- await axios.get(config.backendUrl, { timeout: 5000, validateStatus: () => true });
143
- } catch (err) {
144
- log(`WARNING: could not reach backend at ${config.backendUrl} (${describeError(err)}) — no data will be sent until this is fixed. Check the backendUrl passed to init().`);
145
- }
146
- };
147
-
148
- // Announces "the process I'm running in (this PID) calls itself
149
- // `serviceName` in its own trace data" — lets the backend link this SDK's
150
- // traced name to whatever name Service Discovery's process scanner
151
- // independently gave the same underlying process (e.g. "index" for
152
- // `node index.js`), purely by matching PID. Sent once at startup and then
153
- // repeated periodically, since Discovery's own scan (every 30s on its
154
- // side) might not have found this PID yet at the exact moment the SDK
155
- // boots — retrying avoids depending on any particular startup order.
156
- const ANNOUNCE_INTERVAL_MS = 60000;
157
- const announceIdentity = async () => {
158
- try {
159
- await axios.post(`${config.backendUrl}/api/discovery/identify`, {
160
- pid: process.pid,
161
- tracedServiceName: config.serviceName,
162
- }, { headers: authHeaders() });
163
- } catch (err) {
164
- if (config.debug) log(`identity announce failed: ${describeError(err)}`);
165
- }
166
- };
167
-
168
- const init = (userConfig = {}) => {
169
- config = {
170
- serviceName: userConfig.serviceName || "unknown-service",
171
- backendUrl: userConfig.backendUrl || "http://localhost:3001",
172
- apiKey: userConfig.apiKey || process.env.INTELLIM_API_KEY || "",
173
- debug: userConfig.debug || false,
174
- };
175
-
176
- if (!config.apiKey && config.debug) {
177
- log("WARNING: no apiKey provided — /api/metrics, /api/logs, /api/traces all require one and will return 401");
178
- }
179
-
180
- log(`initializing for service: ${config.serviceName}`);
181
- checkBackendReachable();
182
-
183
- patchOutgoingRequests();
184
-
185
- startMetricsReporter();
186
-
187
- announceIdentity();
188
- setInterval(announceIdentity, ANNOUNCE_INTERVAL_MS);
189
-
190
- // small delay so the backend is reachable before first log
191
- setTimeout(() => {
192
- sendLog("INFO", `IntelliM agent started — monitoring ${config.serviceName}`);
193
- }, 2000);
194
-
195
- process.on("SIGTERM", shutdown);
196
- process.on("SIGINT", shutdown);
197
-
198
- log("ready! Monitoring all HTTP requests automatically.");
199
- return { middleware, sendLog, sendMetric, sendTrace };
200
- };
201
-
202
- // Express middleware — captures every request
203
- const middleware = (req, res, next) => {
204
- const start = Date.now();
205
- requestCount++;
206
-
207
- // A trace ID arriving on the incoming request means an upstream
208
- // instrumented service is already mid-trace and this request is just the
209
- // next hop — continue that same trace instead of starting a new one. No
210
- // header means this request is the root of a brand-new trace.
211
- const incomingTraceId = req.headers[TRACE_ID_HEADER];
212
- const incomingSpanId = req.headers[SPAN_ID_HEADER];
213
- const traceId = incomingTraceId || genId();
214
- const spanId = genId();
215
-
216
- res.on("finish", async () => {
217
- const duration = Date.now() - start;
218
- totalDuration += duration;
219
- if (res.statusCode >= 400) errorCount++;
220
-
221
- if (config.debug) {
222
- log(`${req.method} ${req.path} → ${res.statusCode} (${duration}ms)`);
223
- }
224
-
225
- await sendTrace({
226
- service: config.serviceName,
227
- traceId,
228
- spanId,
229
- parentSpanId: incomingSpanId || "",
230
- route: req.path,
231
- method: req.method,
232
- duration,
233
- status: res.statusCode,
234
- type: "trace",
235
- });
236
-
237
- await sendMetric("response_time", duration, "ms");
238
-
239
- if (res.statusCode >= 500) {
240
- await sendLog("ERROR", `${req.method} ${req.path} returned ${res.statusCode} in ${duration}ms`);
241
- } else if (res.statusCode === 401 || res.statusCode === 403) {
242
- await sendLog("WARN", `Auth failed: ${req.method} ${req.path} returned ${res.statusCode} in ${duration}ms`);
243
- } else if (res.statusCode === 429) {
244
- await sendLog("WARN", `Rate limited: ${req.method} ${req.path} returned 429 in ${duration}ms`);
245
- } else if (res.statusCode >= 400) {
246
- await sendLog("WARN", `${req.method} ${req.path} returned ${res.statusCode} in ${duration}ms`);
247
- }
248
- // Two-tier slow-request logging — a 1.2s request and an 8s request are
249
- // very different severities of problem, so don't bucket them the same.
250
- if (duration > 3000) {
251
- await sendLog("ERROR", `Very slow request: ${req.method} ${req.path} took ${duration}ms`);
252
- } else if (duration > 1000) {
253
- await sendLog("WARN", `Slow request: ${req.method} ${req.path} took ${duration}ms`);
254
- }
255
- });
256
-
257
- // Everything downstream (the actual route handler, and any axios calls
258
- // it makes to other services) runs inside this context so the outgoing
259
- // interceptor below can find the current traceId/spanId.
260
- traceContext.run({ traceId, spanId }, () => next());
261
- };
262
-
263
- // All ingestion endpoints (/api/metrics, /api/logs, /api/traces) require an
264
- // API key — this was missing entirely before, so every call from this SDK
265
- // silently 401'd once those routes started requiring authentication.
266
- const authHeaders = () => (config.apiKey ? { "x-api-key": config.apiKey } : {});
267
-
268
- const sendMetric = async (name, value, unit = "") => {
269
- try {
270
- await axios.post(`${config.backendUrl}/api/metrics`, {
271
- service: config.serviceName,
272
- name,
273
- value,
274
- unit,
275
- timestamp: new Date().toISOString(),
276
- }, { headers: authHeaders() });
277
- } catch (err) {
278
- if (config.debug) log(`metric ${name} failed: ${describeError(err)}`);
279
- }
280
- };
281
-
282
- const sendLog = async (level, message) => {
283
- try {
284
- await axios.post(`${config.backendUrl}/api/logs`, {
285
- service: config.serviceName,
286
- level,
287
- message,
288
- timestamp: new Date().toISOString(),
289
- }, { headers: authHeaders() });
290
- } catch (err) {
291
- if (config.debug) log(`log failed: ${describeError(err)}`);
292
- }
293
- };
294
-
295
- const sendTrace = async (trace) => {
296
- try {
297
- await axios.post(`${config.backendUrl}/api/traces`, {
298
- ...trace,
299
- timestamp: new Date().toISOString(),
300
- }, { headers: authHeaders() });
301
- } catch (err) {
302
- if (config.debug) log(`trace failed: ${describeError(err)}`);
303
- }
304
- };
305
-
306
- const ROLLUP_INTERVAL_MS = 10000; // 10 seconds
307
-
308
- const startMetricsReporter = () => {
309
- setInterval(async () => {
310
- const memMB = process.memoryUsage().heapUsed / 1024 / 1024;
311
-
312
- // Snapshot current-interval counts, then RESET immediately so the
313
- // next cycle measures only the next 10 seconds — not lifetime totals.
314
- // This is the same fix applied to app_error_rate earlier: a counter
315
- // that never resets produces a useless ever-growing number rather than
316
- // a meaningful "what happened recently" rate.
317
- const intervalRequests = requestCount;
318
- const intervalDuration = totalDuration;
319
- const intervalErrors = errorCount;
320
- requestCount = 0;
321
- totalDuration = 0;
322
- errorCount = 0;
323
-
324
- const avg = intervalRequests > 0 ? intervalDuration / intervalRequests : 0;
325
- const errRate = intervalRequests > 0 ? (intervalErrors / intervalRequests) * 100 : 0;
326
- const reqPerSec = intervalRequests / (ROLLUP_INTERVAL_MS / 1000); // per-second rate
327
-
328
- await sendMetric("app_memory_mb", parseFloat(memMB.toFixed(2)), "MB");
329
- await sendMetric("app_avg_response_time", parseFloat(avg.toFixed(2)), "ms");
330
- await sendMetric("http_request_count", intervalRequests, "count");
331
- await sendMetric("http_requests_per_second",parseFloat(reqPerSec.toFixed(2)),"req/s");
332
- await sendMetric("app_error_rate", parseFloat(errRate.toFixed(2)), "%");
333
-
334
- if (config.debug) {
335
- log(`rollup: mem=${memMB.toFixed(1)}MB avg=${avg.toFixed(0)}ms reqs=${intervalRequests} (${reqPerSec.toFixed(1)}/s) errors=${intervalErrors}`);
336
- }
337
- }, ROLLUP_INTERVAL_MS);
338
- };
339
-
340
- const shutdown = async () => {
341
- log("shutting down gracefully...");
342
- await sendLog("INFO", `IntelliM agent stopped — ${config.serviceName}`);
343
- process.exit(0);
344
- };
345
-
346
- module.exports = { init, middleware, sendLog, sendMetric, sendTrace };
1
+ "use strict";
2
+
3
+ // ============================================
4
+ // intellim-node-sdk (CLEANED — Batch 1)
5
+ // Auto-instrumentation SDK for Node.js / Express apps.
6
+ //
7
+ // Usage (one line):
8
+ // const intellim = require("intellim-node-sdk");
9
+ // const { middleware } = intellim.init({ serviceName: "my-app" });
10
+ // app.use(middleware);
11
+ //
12
+ // Captures automatically, per request:
13
+ // - route, method, status, duration -> trace
14
+ // - response_time -> metric
15
+ // - errors (4xx/5xx) + slow (>1s) -> logs
16
+ // And every 10s, app-level rollups:
17
+ // - app_memory_mb, app_avg_response_time,
18
+ // app_total_requests, app_error_rate
19
+ //
20
+ // FIXES IN THIS VERSION:
21
+ // - Removed the noisy ">>> REQUEST IN" debug line.
22
+ // - Removed the old http.request monkey-patch that caused
23
+ // a feedback loop (the 12k junk "outgoing_request_duration").
24
+ // - Consistent metric names.
25
+ // ============================================
26
+
27
+ const axios = require("axios");
28
+ const http = require("http");
29
+ const https = require("https");
30
+ const crypto = require("crypto");
31
+ const util = require("util");
32
+ const { AsyncLocalStorage } = require("async_hooks");
33
+ const Hook = require("require-in-the-middle");
34
+
35
+ let config = {};
36
+ let requestCount = 0;
37
+ let errorCount = 0;
38
+ let totalDuration = 0;
39
+
40
+ const log = (msg) => console.log(`[IntelliM] ${msg}`);
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");
49
+
50
+ // Holds { traceId, spanId } for whichever request is currently being
51
+ // handled, scoped correctly per-request even under concurrent async work —
52
+ // this is what lets an outgoing axios call made deep inside a route handler
53
+ // find "which request am I part of" without threading it through every
54
+ // function call by hand. Previously every span picked a brand-new random
55
+ // traceId with no relation to any incoming request, so a single logical
56
+ // request crossing multiple instrumented services produced N unrelated
57
+ // traces instead of one correlated trace — this is the fix for that.
58
+ const traceContext = new AsyncLocalStorage();
59
+
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";
90
+
91
+ // Propagates the current request's trace context onto any outgoing HTTP
92
+ // call the instrumented app makes (e.g. calling another instrumented
93
+ // service) — this is what actually makes tracing "distributed" rather than
94
+ // each service recording its own disconnected spans.
95
+ //
96
+ // This patches Node's core http/https modules directly instead of axios's
97
+ // interceptors. That's a deliberate choice, not a style preference: axios
98
+ // is a separate npm package, and this SDK's own copy of it (in its own
99
+ // node_modules) is a DIFFERENT module instance than whatever copy the
100
+ // instrumented app has in ITS OWN node_modules — patching "the" axios
101
+ // instance from inside this SDK never touches the app's own axios calls at
102
+ // all, since each has its own private interceptor registry. http/https are
103
+ // true Node built-ins, though — there's only ever one copy of them in a
104
+ // given process, shared by every package (including axios's own Node
105
+ // adapter, which is built on top of http.request), so patching them here
106
+ // reliably reaches every outgoing call regardless of which HTTP client
107
+ // library the app uses. Deliberately ONLY adds headers, nothing more — a
108
+ // past version of this SDK auto-recorded a trace/metric for every outgoing
109
+ // call and that created a feedback loop of junk data (see the "REMOVED"
110
+ // note in this file's header comment); this carries no such risk since it
111
+ // never sends anything itself, it only annotates requests already being made.
112
+ let _patched = false;
113
+ function patchOutgoingRequests() {
114
+ if (_patched) return;
115
+ _patched = true;
116
+
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) => {
140
+ const ctx = traceContext.getStore();
141
+ if (!ctx) return headers;
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
+ };
163
+ };
164
+
165
+ for (const mod of [http, https]) {
166
+ const originalRequest = mod.request.bind(mod);
167
+ mod.request = (...args) => {
168
+ if (args[0] && typeof args[0] === "object" && !(args[0] instanceof URL)) {
169
+ // request(options[, callback])
170
+ args[0] = { ...args[0], headers: addTraceHeaders(args[0].headers, safeHost(args[0])) };
171
+ } else if (typeof args[1] === "object" && args[1] !== null) {
172
+ // request(url, options[, callback])
173
+ args[1] = { ...args[1], headers: addTraceHeaders(args[1].headers, safeHost(args[0])) };
174
+ } else {
175
+ // request(url[, callback]) — no options object to merge into, insert one
176
+ args.splice(1, 0, { headers: addTraceHeaders(undefined, safeHost(args[0])) });
177
+ }
178
+ return originalRequest(...args);
179
+ };
180
+ // http.get/https.get do NOT call the module's (possibly patched)
181
+ // `.request` internally — Node's real implementation closes over its
182
+ // own original `request` function at module-definition time, so
183
+ // patching `.request` alone silently never affects `.get()`. Has to be
184
+ // redefined explicitly, calling the NEW `mod.request` directly.
185
+ mod.get = (...args) => {
186
+ const req = mod.request(...args);
187
+ req.end();
188
+ return req;
189
+ };
190
+ }
191
+ }
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
+
379
+ // Best-effort human-readable reason for a failed network call. Axios errors
380
+ // normally have a real .message ("Request failed with status code 401",
381
+ // "connect ECONNREFUSED ..."), but Node's dual-stack "happy eyeballs"
382
+ // connection attempt (used for a bare hostname like "localhost", which
383
+ // resolves to both ::1 and 127.0.0.1) can produce an AggregateError whose
384
+ // own top-level .message is blank by design — the real per-address reasons
385
+ // live in .errors (or .cause.errors) instead. Without this, a debug log
386
+ // silently prints "failed: " with nothing after it, which is exactly what
387
+ // happened when a backendUrl was left pointing at localhost with nothing
388
+ // listening there.
389
+ const describeError = (err) => {
390
+ if (err.message) return err.message;
391
+ if (err.code) return err.code;
392
+ const sub = err.errors || (err.cause && err.cause.errors);
393
+ if (sub && sub.length) return sub.map(e => e.message || e.code).join(", ");
394
+ return "unknown error";
395
+ };
396
+
397
+ // One-time reachability check right at startup — separate from the ongoing
398
+ // per-call debug logs below, which stay silent unless debug:true. A wrong
399
+ // or unreachable backendUrl otherwise fails completely silently in a real
400
+ // deployment (debug is off by default), so a client could have zero data
401
+ // arriving for weeks with no indication anything is wrong. This is always
402
+ // printed, regardless of the debug flag, specifically so a misconfigured
403
+ // backendUrl is never invisible.
404
+ const checkBackendReachable = async () => {
405
+ try {
406
+ await axios.get(config.backendUrl, { timeout: 5000, validateStatus: () => true });
407
+ } catch (err) {
408
+ log(`WARNING: could not reach backend at ${config.backendUrl} (${describeError(err)}) — no data will be sent until this is fixed. Check the backendUrl passed to init().`);
409
+ }
410
+ };
411
+
412
+ // Announces "the process I'm running in (this PID) calls itself
413
+ // `serviceName` in its own trace data" — lets the backend link this SDK's
414
+ // traced name to whatever name Service Discovery's process scanner
415
+ // independently gave the same underlying process (e.g. "index" for
416
+ // `node index.js`), purely by matching PID. Sent once at startup and then
417
+ // repeated periodically, since Discovery's own scan (every 30s on its
418
+ // side) might not have found this PID yet at the exact moment the SDK
419
+ // boots — retrying avoids depending on any particular startup order.
420
+ const ANNOUNCE_INTERVAL_MS = 60000;
421
+ // This SDK's own package version, not the instrumented app's version --
422
+ // shown on the Services card as a "what's actually running" signal
423
+ // (approximates "last deployed" too, paired with process uptime, since a
424
+ // real deploy-tracking pipeline is a separate, bigger feature).
425
+ const SDK_VERSION = require("./package.json").version;
426
+ const announceIdentity = async () => {
427
+ try {
428
+ await axios.post(`${config.backendUrl}/api/discovery/identify`, {
429
+ pid: process.pid,
430
+ tracedServiceName: config.serviceName,
431
+ sdkVersion: SDK_VERSION,
432
+ }, { headers: authHeaders() });
433
+ } catch (err) {
434
+ if (config.debug) log(`identity announce failed: ${describeError(err)}`);
435
+ }
436
+ };
437
+
438
+ const init = (userConfig = {}) => {
439
+ config = {
440
+ serviceName: userConfig.serviceName || "unknown-service",
441
+ backendUrl: userConfig.backendUrl || "http://localhost:3001",
442
+ apiKey: userConfig.apiKey || process.env.INTELLIM_API_KEY || "",
443
+ debug: userConfig.debug || false,
444
+ // Neither is required -- an app that doesn't set them just sends "" for
445
+ // both, same as every existing integration before this. Read from
446
+ // common env var names as a fallback so a CI/CD pipeline that already
447
+ // sets APP_VERSION/NODE_ENV doesn't need a code change to pick this up.
448
+ version: userConfig.version || process.env.APP_VERSION || "",
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,
474
+ };
475
+
476
+ if (!config.apiKey && config.debug) {
477
+ log("WARNING: no apiKey provided — /api/metrics, /api/logs, /api/traces all require one and will return 401");
478
+ }
479
+
480
+ log(`initializing for service: ${config.serviceName}`);
481
+ checkBackendReachable();
482
+
483
+ patchOutgoingRequests();
484
+ if (config.instrumentDb) patchPgQueries();
485
+ if (config.captureConsole) patchConsole();
486
+
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);
491
+
492
+ announceIdentity();
493
+ setInterval(announceIdentity, ANNOUNCE_INTERVAL_MS);
494
+
495
+ // small delay so the backend is reachable before first log
496
+ setTimeout(() => {
497
+ sendLog("INFO", `IntelliM agent started — monitoring ${config.serviceName}`);
498
+ }, 2000);
499
+
500
+ process.on("SIGTERM", shutdown);
501
+ process.on("SIGINT", shutdown);
502
+
503
+ log("ready! Monitoring all HTTP requests automatically.");
504
+ return { middleware, sendLog, sendMetric, sendTrace };
505
+ };
506
+
507
+ // Express middleware — captures every request
508
+ const middleware = (req, res, next) => {
509
+ const start = Date.now();
510
+ requestCount++;
511
+
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 = [];
531
+
532
+ res.on("finish", async () => {
533
+ const duration = Date.now() - start;
534
+ totalDuration += duration;
535
+ if (res.statusCode >= 400) errorCount++;
536
+
537
+ if (config.debug) {
538
+ log(`${req.method} ${req.path} → ${res.statusCode} (${duration}ms)`);
539
+ }
540
+
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
+ }
563
+
564
+ await sendMetric("response_time", duration, "ms");
565
+
566
+ if (res.statusCode >= 500) {
567
+ await sendLog("ERROR", `${req.method} ${req.path} returned ${res.statusCode} in ${duration}ms`, traceId, spanId);
568
+ } else if (res.statusCode === 401 || res.statusCode === 403) {
569
+ await sendLog("WARN", `Auth failed: ${req.method} ${req.path} returned ${res.statusCode} in ${duration}ms`, traceId, spanId);
570
+ } else if (res.statusCode === 429) {
571
+ await sendLog("WARN", `Rate limited: ${req.method} ${req.path} returned 429 in ${duration}ms`, traceId, spanId);
572
+ } else if (res.statusCode >= 400) {
573
+ await sendLog("WARN", `${req.method} ${req.path} returned ${res.statusCode} in ${duration}ms`, traceId, spanId);
574
+ }
575
+ // Two-tier slow-request logging — a 1.2s request and an 8s request are
576
+ // very different severities of problem, so don't bucket them the same.
577
+ if (duration > 3000) {
578
+ await sendLog("ERROR", `Very slow request: ${req.method} ${req.path} took ${duration}ms`, traceId, spanId);
579
+ } else if (duration > 1000) {
580
+ await sendLog("WARN", `Slow request: ${req.method} ${req.path} took ${duration}ms`, traceId, spanId);
581
+ }
582
+ });
583
+
584
+ // Everything downstream (the actual route handler, and any axios calls
585
+ // it makes to other services) runs inside this context so the outgoing
586
+ // interceptor below can find the current traceId/spanId.
587
+ traceContext.run({ traceId, spanId, calledHosts }, () => next());
588
+ };
589
+
590
+ // All ingestion endpoints (/api/metrics, /api/logs, /api/traces) require an
591
+ // API key — this was missing entirely before, so every call from this SDK
592
+ // silently 401'd once those routes started requiring authentication.
593
+ const authHeaders = () => (config.apiKey ? { "x-api-key": config.apiKey } : {});
594
+
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([]);
619
+ try {
620
+ await axios.post(`${config.backendUrl}${endpoint}`, { items: batch }, { headers: authHeaders() });
621
+ } catch (err) {
622
+ if (config.debug) log(`${label} batch (${batch.length}) failed: ${describeError(err)}`);
623
+ }
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
+ };
637
+
638
+ // traceId/spanId are optional -- a log sent outside a traced request
639
+ // (startup/shutdown messages) has neither, and the backend already
640
+ // defaults them to "" (see toLogDoc in the backend's kafka consumer).
641
+ const sendLog = async (level, message, traceId, spanId) => {
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();
650
+ };
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.
656
+ const sendTrace = async (trace) => {
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();
664
+ };
665
+
666
+ const ROLLUP_INTERVAL_MS = 10000; // 10 seconds
667
+
668
+ const startMetricsReporter = () => {
669
+ setInterval(async () => {
670
+ const memMB = process.memoryUsage().heapUsed / 1024 / 1024;
671
+
672
+ // Snapshot current-interval counts, then RESET immediately so the
673
+ // next cycle measures only the next 10 seconds — not lifetime totals.
674
+ // This is the same fix applied to app_error_rate earlier: a counter
675
+ // that never resets produces a useless ever-growing number rather than
676
+ // a meaningful "what happened recently" rate.
677
+ const intervalRequests = requestCount;
678
+ const intervalDuration = totalDuration;
679
+ const intervalErrors = errorCount;
680
+ requestCount = 0;
681
+ totalDuration = 0;
682
+ errorCount = 0;
683
+
684
+ const avg = intervalRequests > 0 ? intervalDuration / intervalRequests : 0;
685
+ const errRate = intervalRequests > 0 ? (intervalErrors / intervalRequests) * 100 : 0;
686
+ const reqPerSec = intervalRequests / (ROLLUP_INTERVAL_MS / 1000); // per-second rate
687
+
688
+ await sendMetric("app_memory_mb", parseFloat(memMB.toFixed(2)), "MB");
689
+ await sendMetric("app_avg_response_time", parseFloat(avg.toFixed(2)), "ms");
690
+ await sendMetric("http_request_count", intervalRequests, "count");
691
+ await sendMetric("http_requests_per_second",parseFloat(reqPerSec.toFixed(2)),"req/s");
692
+ await sendMetric("app_error_rate", parseFloat(errRate.toFixed(2)), "%");
693
+
694
+ if (config.debug) {
695
+ log(`rollup: mem=${memMB.toFixed(1)}MB avg=${avg.toFixed(0)}ms reqs=${intervalRequests} (${reqPerSec.toFixed(1)}/s) errors=${intervalErrors}`);
696
+ }
697
+ }, ROLLUP_INTERVAL_MS);
698
+ };
699
+
700
+ const shutdown = async () => {
701
+ log("shutting down gracefully...");
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()]);
710
+ process.exit(0);
711
+ };
712
+
713
+ module.exports = { init, middleware, sendLog, sendMetric, sendTrace };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "intellim-node-sdk",
3
- "version": "1.0.1",
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
  }