intellim-node-sdk 1.0.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 (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +62 -0
  3. package/index.js +312 -0
  4. package/package.json +34 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 IntelliM
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,62 @@
1
+ # intellim-node-sdk
2
+
3
+ One-line auto-instrumentation for Node.js / Express applications, reporting
4
+ to a [IntelliM](https://github.com/Intelli-APM/apm) backend.
5
+
6
+ ## Install
7
+
8
+ ```bash
9
+ npm install intellim-node-sdk
10
+ ```
11
+
12
+ ## Usage
13
+
14
+ ```js
15
+ const intellim = require("intellim-node-sdk");
16
+
17
+ const { middleware } = intellim.init({
18
+ serviceName: "my-app",
19
+ backendUrl: "https://your-intellim-backend.example.com",
20
+ apiKey: "your-api-key", // or set INTELLIM_API_KEY in the environment
21
+ });
22
+
23
+ app.use(middleware);
24
+ ```
25
+
26
+ That's it — every request handled after this point is automatically traced.
27
+
28
+ ## What gets captured automatically
29
+
30
+ - **Per request:** route, method, status, duration → sent as a trace
31
+ - **Per request:** response time → sent as a metric
32
+ - **Errors and slow requests** (4xx/5xx, or over 1s) → sent as log lines
33
+ - **Every 10 seconds:** app-level rollups — memory usage, average response
34
+ time, request throughput, error rate
35
+
36
+ ## Distributed tracing across services
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.
43
+
44
+ This works by patching Node's core `http`/`https` modules (not by patching
45
+ whatever HTTP client library your app happens to use) — the two SDK
46
+ instances a service and the app it calls each have their own separate copy
47
+ of a package like axios, but there is only ever one `http` module in a
48
+ given Node process, so that's what reliably carries the trace context
49
+ across the boundary regardless of which library made the actual call.
50
+
51
+ ## Configuration
52
+
53
+ | Option | Required | Default | Notes |
54
+ |---------------|----------|-----------------------------|---------------------------------------------|
55
+ | `serviceName` | No | `"unknown-service"` | Shows up as this service's name everywhere |
56
+ | `backendUrl` | No | `http://localhost:3001` | Your IntelliM backend's URL |
57
+ | `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
+ | `debug` | No | `false` | Logs `[NexusRUM]`-style debug lines to the console |
59
+
60
+ ## License
61
+
62
+ MIT
package/index.js ADDED
@@ -0,0 +1,312 @@
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
+ // Announces "the process I'm running in (this PID) calls itself
116
+ // `serviceName` in its own trace data" — lets the backend link this SDK's
117
+ // traced name to whatever name Service Discovery's process scanner
118
+ // independently gave the same underlying process (e.g. "index" for
119
+ // `node index.js`), purely by matching PID. Sent once at startup and then
120
+ // repeated periodically, since Discovery's own scan (every 30s on its
121
+ // side) might not have found this PID yet at the exact moment the SDK
122
+ // boots — retrying avoids depending on any particular startup order.
123
+ const ANNOUNCE_INTERVAL_MS = 60000;
124
+ const announceIdentity = async () => {
125
+ try {
126
+ await axios.post(`${config.backendUrl}/api/discovery/identify`, {
127
+ pid: process.pid,
128
+ tracedServiceName: config.serviceName,
129
+ }, { headers: authHeaders() });
130
+ } catch (err) {
131
+ if (config.debug) log(`identity announce failed: ${err.message}`);
132
+ }
133
+ };
134
+
135
+ const init = (userConfig = {}) => {
136
+ config = {
137
+ serviceName: userConfig.serviceName || "unknown-service",
138
+ backendUrl: userConfig.backendUrl || "http://localhost:3001",
139
+ apiKey: userConfig.apiKey || process.env.INTELLIM_API_KEY || "",
140
+ debug: userConfig.debug || false,
141
+ };
142
+
143
+ if (!config.apiKey && config.debug) {
144
+ log("WARNING: no apiKey provided — /api/metrics, /api/logs, /api/traces all require one and will return 401");
145
+ }
146
+
147
+ log(`initializing for service: ${config.serviceName}`);
148
+
149
+ patchOutgoingRequests();
150
+
151
+ startMetricsReporter();
152
+
153
+ announceIdentity();
154
+ setInterval(announceIdentity, ANNOUNCE_INTERVAL_MS);
155
+
156
+ // small delay so the backend is reachable before first log
157
+ setTimeout(() => {
158
+ sendLog("INFO", `IntelliM agent started — monitoring ${config.serviceName}`);
159
+ }, 2000);
160
+
161
+ process.on("SIGTERM", shutdown);
162
+ process.on("SIGINT", shutdown);
163
+
164
+ log("ready! Monitoring all HTTP requests automatically.");
165
+ return { middleware, sendLog, sendMetric, sendTrace };
166
+ };
167
+
168
+ // Express middleware — captures every request
169
+ const middleware = (req, res, next) => {
170
+ const start = Date.now();
171
+ requestCount++;
172
+
173
+ // A trace ID arriving on the incoming request means an upstream
174
+ // instrumented service is already mid-trace and this request is just the
175
+ // next hop — continue that same trace instead of starting a new one. No
176
+ // header means this request is the root of a brand-new trace.
177
+ const incomingTraceId = req.headers[TRACE_ID_HEADER];
178
+ const incomingSpanId = req.headers[SPAN_ID_HEADER];
179
+ const traceId = incomingTraceId || genId();
180
+ const spanId = genId();
181
+
182
+ res.on("finish", async () => {
183
+ const duration = Date.now() - start;
184
+ totalDuration += duration;
185
+ if (res.statusCode >= 400) errorCount++;
186
+
187
+ if (config.debug) {
188
+ log(`${req.method} ${req.path} → ${res.statusCode} (${duration}ms)`);
189
+ }
190
+
191
+ await sendTrace({
192
+ service: config.serviceName,
193
+ traceId,
194
+ spanId,
195
+ parentSpanId: incomingSpanId || "",
196
+ route: req.path,
197
+ method: req.method,
198
+ duration,
199
+ status: res.statusCode,
200
+ type: "trace",
201
+ });
202
+
203
+ await sendMetric("response_time", duration, "ms");
204
+
205
+ if (res.statusCode >= 500) {
206
+ await sendLog("ERROR", `${req.method} ${req.path} returned ${res.statusCode} in ${duration}ms`);
207
+ } else if (res.statusCode === 401 || res.statusCode === 403) {
208
+ await sendLog("WARN", `Auth failed: ${req.method} ${req.path} returned ${res.statusCode} in ${duration}ms`);
209
+ } else if (res.statusCode === 429) {
210
+ await sendLog("WARN", `Rate limited: ${req.method} ${req.path} returned 429 in ${duration}ms`);
211
+ } else if (res.statusCode >= 400) {
212
+ await sendLog("WARN", `${req.method} ${req.path} returned ${res.statusCode} in ${duration}ms`);
213
+ }
214
+ // Two-tier slow-request logging — a 1.2s request and an 8s request are
215
+ // very different severities of problem, so don't bucket them the same.
216
+ if (duration > 3000) {
217
+ await sendLog("ERROR", `Very slow request: ${req.method} ${req.path} took ${duration}ms`);
218
+ } else if (duration > 1000) {
219
+ await sendLog("WARN", `Slow request: ${req.method} ${req.path} took ${duration}ms`);
220
+ }
221
+ });
222
+
223
+ // Everything downstream (the actual route handler, and any axios calls
224
+ // it makes to other services) runs inside this context so the outgoing
225
+ // interceptor below can find the current traceId/spanId.
226
+ traceContext.run({ traceId, spanId }, () => next());
227
+ };
228
+
229
+ // All ingestion endpoints (/api/metrics, /api/logs, /api/traces) require an
230
+ // API key — this was missing entirely before, so every call from this SDK
231
+ // silently 401'd once those routes started requiring authentication.
232
+ const authHeaders = () => (config.apiKey ? { "x-api-key": config.apiKey } : {});
233
+
234
+ const sendMetric = async (name, value, unit = "") => {
235
+ try {
236
+ await axios.post(`${config.backendUrl}/api/metrics`, {
237
+ service: config.serviceName,
238
+ name,
239
+ value,
240
+ unit,
241
+ timestamp: new Date().toISOString(),
242
+ }, { headers: authHeaders() });
243
+ } catch (err) {
244
+ if (config.debug) log(`metric ${name} failed: ${err.message}`);
245
+ }
246
+ };
247
+
248
+ const sendLog = async (level, message) => {
249
+ try {
250
+ await axios.post(`${config.backendUrl}/api/logs`, {
251
+ service: config.serviceName,
252
+ level,
253
+ message,
254
+ timestamp: new Date().toISOString(),
255
+ }, { headers: authHeaders() });
256
+ } catch (err) {
257
+ if (config.debug) log(`log failed: ${err.message}`);
258
+ }
259
+ };
260
+
261
+ const sendTrace = async (trace) => {
262
+ try {
263
+ await axios.post(`${config.backendUrl}/api/traces`, {
264
+ ...trace,
265
+ timestamp: new Date().toISOString(),
266
+ }, { headers: authHeaders() });
267
+ } catch (err) {
268
+ if (config.debug) log(`trace failed: ${err.message}`);
269
+ }
270
+ };
271
+
272
+ const ROLLUP_INTERVAL_MS = 10000; // 10 seconds
273
+
274
+ const startMetricsReporter = () => {
275
+ setInterval(async () => {
276
+ const memMB = process.memoryUsage().heapUsed / 1024 / 1024;
277
+
278
+ // Snapshot current-interval counts, then RESET immediately so the
279
+ // next cycle measures only the next 10 seconds — not lifetime totals.
280
+ // This is the same fix applied to app_error_rate earlier: a counter
281
+ // that never resets produces a useless ever-growing number rather than
282
+ // a meaningful "what happened recently" rate.
283
+ const intervalRequests = requestCount;
284
+ const intervalDuration = totalDuration;
285
+ const intervalErrors = errorCount;
286
+ requestCount = 0;
287
+ totalDuration = 0;
288
+ errorCount = 0;
289
+
290
+ const avg = intervalRequests > 0 ? intervalDuration / intervalRequests : 0;
291
+ const errRate = intervalRequests > 0 ? (intervalErrors / intervalRequests) * 100 : 0;
292
+ const reqPerSec = intervalRequests / (ROLLUP_INTERVAL_MS / 1000); // per-second rate
293
+
294
+ await sendMetric("app_memory_mb", parseFloat(memMB.toFixed(2)), "MB");
295
+ await sendMetric("app_avg_response_time", parseFloat(avg.toFixed(2)), "ms");
296
+ await sendMetric("http_request_count", intervalRequests, "count");
297
+ await sendMetric("http_requests_per_second",parseFloat(reqPerSec.toFixed(2)),"req/s");
298
+ await sendMetric("app_error_rate", parseFloat(errRate.toFixed(2)), "%");
299
+
300
+ if (config.debug) {
301
+ log(`rollup: mem=${memMB.toFixed(1)}MB avg=${avg.toFixed(0)}ms reqs=${intervalRequests} (${reqPerSec.toFixed(1)}/s) errors=${intervalErrors}`);
302
+ }
303
+ }, ROLLUP_INTERVAL_MS);
304
+ };
305
+
306
+ const shutdown = async () => {
307
+ log("shutting down gracefully...");
308
+ await sendLog("INFO", `IntelliM agent stopped — ${config.serviceName}`);
309
+ process.exit(0);
310
+ };
311
+
312
+ module.exports = { init, middleware, sendLog, sendMetric, sendTrace };
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "intellim-node-sdk",
3
+ "version": "1.0.0",
4
+ "main": "index.js",
5
+ "files": [
6
+ "index.js",
7
+ "README.md",
8
+ "LICENSE"
9
+ ],
10
+ "scripts": {
11
+ "test": "echo \"Error: no test specified\" && exit 1"
12
+ },
13
+ "keywords": [
14
+ "apm",
15
+ "monitoring",
16
+ "observability",
17
+ "tracing",
18
+ "distributed-tracing",
19
+ "express",
20
+ "performance"
21
+ ],
22
+ "author": "IntelliM",
23
+ "license": "MIT",
24
+ "description": "One-line auto-instrumentation for Node.js/Express apps — traces, metrics, and error logs sent to an IntelliM backend, with distributed trace propagation across services.",
25
+ "repository": {
26
+ "type": "git",
27
+ "url": "git+https://github.com/Intelli-APM/apm.git",
28
+ "directory": "agent/intellim-node-sdk"
29
+ },
30
+ "homepage": "https://github.com/Intelli-APM/apm/tree/main/agent/intellim-node-sdk#readme",
31
+ "dependencies": {
32
+ "axios": "^1.17.0"
33
+ }
34
+ }