intellim-node-sdk 1.0.1 → 1.1.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 (2) hide show
  1. package/index.js +369 -346
  2. package/package.json +1 -1
package/index.js CHANGED
@@ -1,346 +1,369 @@
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 { 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
+ // This SDK's own package version, not the instrumented app's version --
158
+ // shown on the Services card as a "what's actually running" signal
159
+ // (approximates "last deployed" too, paired with process uptime, since a
160
+ // real deploy-tracking pipeline is a separate, bigger feature).
161
+ const SDK_VERSION = require("./package.json").version;
162
+ const announceIdentity = async () => {
163
+ try {
164
+ await axios.post(`${config.backendUrl}/api/discovery/identify`, {
165
+ pid: process.pid,
166
+ tracedServiceName: config.serviceName,
167
+ sdkVersion: SDK_VERSION,
168
+ }, { headers: authHeaders() });
169
+ } catch (err) {
170
+ if (config.debug) log(`identity announce failed: ${describeError(err)}`);
171
+ }
172
+ };
173
+
174
+ const init = (userConfig = {}) => {
175
+ config = {
176
+ serviceName: userConfig.serviceName || "unknown-service",
177
+ backendUrl: userConfig.backendUrl || "http://localhost:3001",
178
+ apiKey: userConfig.apiKey || process.env.INTELLIM_API_KEY || "",
179
+ debug: userConfig.debug || false,
180
+ // Neither is required -- an app that doesn't set them just sends "" for
181
+ // both, same as every existing integration before this. Read from
182
+ // common env var names as a fallback so a CI/CD pipeline that already
183
+ // sets APP_VERSION/NODE_ENV doesn't need a code change to pick this up.
184
+ version: userConfig.version || process.env.APP_VERSION || "",
185
+ environment: userConfig.environment || process.env.NODE_ENV || "",
186
+ };
187
+
188
+ if (!config.apiKey && config.debug) {
189
+ log("WARNING: no apiKey provided — /api/metrics, /api/logs, /api/traces all require one and will return 401");
190
+ }
191
+
192
+ log(`initializing for service: ${config.serviceName}`);
193
+ checkBackendReachable();
194
+
195
+ patchOutgoingRequests();
196
+
197
+ startMetricsReporter();
198
+
199
+ announceIdentity();
200
+ setInterval(announceIdentity, ANNOUNCE_INTERVAL_MS);
201
+
202
+ // small delay so the backend is reachable before first log
203
+ setTimeout(() => {
204
+ sendLog("INFO", `IntelliM agent started — monitoring ${config.serviceName}`);
205
+ }, 2000);
206
+
207
+ process.on("SIGTERM", shutdown);
208
+ process.on("SIGINT", shutdown);
209
+
210
+ log("ready! Monitoring all HTTP requests automatically.");
211
+ return { middleware, sendLog, sendMetric, sendTrace };
212
+ };
213
+
214
+ // Express middleware — captures every request
215
+ const middleware = (req, res, next) => {
216
+ const start = Date.now();
217
+ requestCount++;
218
+
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();
227
+
228
+ res.on("finish", async () => {
229
+ const duration = Date.now() - start;
230
+ totalDuration += duration;
231
+ if (res.statusCode >= 400) errorCount++;
232
+
233
+ if (config.debug) {
234
+ log(`${req.method} ${req.path} → ${res.statusCode} (${duration}ms)`);
235
+ }
236
+
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
+ });
248
+
249
+ await sendMetric("response_time", duration, "ms");
250
+
251
+ if (res.statusCode >= 500) {
252
+ await sendLog("ERROR", `${req.method} ${req.path} returned ${res.statusCode} in ${duration}ms`, traceId, spanId);
253
+ } else if (res.statusCode === 401 || res.statusCode === 403) {
254
+ await sendLog("WARN", `Auth failed: ${req.method} ${req.path} returned ${res.statusCode} in ${duration}ms`, traceId, spanId);
255
+ } else if (res.statusCode === 429) {
256
+ await sendLog("WARN", `Rate limited: ${req.method} ${req.path} returned 429 in ${duration}ms`, traceId, spanId);
257
+ } else if (res.statusCode >= 400) {
258
+ await sendLog("WARN", `${req.method} ${req.path} returned ${res.statusCode} in ${duration}ms`, traceId, spanId);
259
+ }
260
+ // Two-tier slow-request logging — a 1.2s request and an 8s request are
261
+ // very different severities of problem, so don't bucket them the same.
262
+ if (duration > 3000) {
263
+ await sendLog("ERROR", `Very slow request: ${req.method} ${req.path} took ${duration}ms`, traceId, spanId);
264
+ } else if (duration > 1000) {
265
+ await sendLog("WARN", `Slow request: ${req.method} ${req.path} took ${duration}ms`, traceId, spanId);
266
+ }
267
+ });
268
+
269
+ // Everything downstream (the actual route handler, and any axios calls
270
+ // it makes to other services) runs inside this context so the outgoing
271
+ // interceptor below can find the current traceId/spanId.
272
+ traceContext.run({ traceId, spanId }, () => next());
273
+ };
274
+
275
+ // All ingestion endpoints (/api/metrics, /api/logs, /api/traces) require an
276
+ // API key — this was missing entirely before, so every call from this SDK
277
+ // silently 401'd once those routes started requiring authentication.
278
+ const authHeaders = () => (config.apiKey ? { "x-api-key": config.apiKey } : {});
279
+
280
+ const sendMetric = async (name, value, unit = "") => {
281
+ 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() });
291
+ } catch (err) {
292
+ if (config.debug) log(`metric ${name} failed: ${describeError(err)}`);
293
+ }
294
+ };
295
+
296
+ // traceId/spanId are optional -- a log sent outside a traced request
297
+ // (startup/shutdown messages) has neither, and the backend already
298
+ // defaults them to "" (see toLogDoc in the backend's kafka consumer).
299
+ 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
+ }
314
+ };
315
+
316
+ 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
+ }
327
+ };
328
+
329
+ const ROLLUP_INTERVAL_MS = 10000; // 10 seconds
330
+
331
+ const startMetricsReporter = () => {
332
+ setInterval(async () => {
333
+ const memMB = process.memoryUsage().heapUsed / 1024 / 1024;
334
+
335
+ // Snapshot current-interval counts, then RESET immediately so the
336
+ // next cycle measures only the next 10 seconds — not lifetime totals.
337
+ // This is the same fix applied to app_error_rate earlier: a counter
338
+ // that never resets produces a useless ever-growing number rather than
339
+ // a meaningful "what happened recently" rate.
340
+ const intervalRequests = requestCount;
341
+ const intervalDuration = totalDuration;
342
+ const intervalErrors = errorCount;
343
+ requestCount = 0;
344
+ totalDuration = 0;
345
+ errorCount = 0;
346
+
347
+ const avg = intervalRequests > 0 ? intervalDuration / intervalRequests : 0;
348
+ const errRate = intervalRequests > 0 ? (intervalErrors / intervalRequests) * 100 : 0;
349
+ const reqPerSec = intervalRequests / (ROLLUP_INTERVAL_MS / 1000); // per-second rate
350
+
351
+ await sendMetric("app_memory_mb", parseFloat(memMB.toFixed(2)), "MB");
352
+ await sendMetric("app_avg_response_time", parseFloat(avg.toFixed(2)), "ms");
353
+ await sendMetric("http_request_count", intervalRequests, "count");
354
+ await sendMetric("http_requests_per_second",parseFloat(reqPerSec.toFixed(2)),"req/s");
355
+ await sendMetric("app_error_rate", parseFloat(errRate.toFixed(2)), "%");
356
+
357
+ if (config.debug) {
358
+ log(`rollup: mem=${memMB.toFixed(1)}MB avg=${avg.toFixed(0)}ms reqs=${intervalRequests} (${reqPerSec.toFixed(1)}/s) errors=${intervalErrors}`);
359
+ }
360
+ }, ROLLUP_INTERVAL_MS);
361
+ };
362
+
363
+ const shutdown = async () => {
364
+ log("shutting down gracefully...");
365
+ await sendLog("INFO", `IntelliM agent stopped — ${config.serviceName}`);
366
+ process.exit(0);
367
+ };
368
+
369
+ 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.1.0",
4
4
  "main": "index.js",
5
5
  "files": [
6
6
  "index.js",