intellim-node-sdk 1.0.0 → 1.0.1
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.
- package/index.js +346 -312
- package/package.json +1 -1
package/index.js
CHANGED
|
@@ -1,312 +1,346 @@
|
|
|
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
|
-
//
|
|
116
|
-
//
|
|
117
|
-
//
|
|
118
|
-
//
|
|
119
|
-
//
|
|
120
|
-
//
|
|
121
|
-
//
|
|
122
|
-
//
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
log(
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
};
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
};
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
}
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
await
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
}
|
|
303
|
-
}
|
|
304
|
-
};
|
|
305
|
-
|
|
306
|
-
const
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
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
|
+
// 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 };
|