@tracelumo/node 0.5.0 → 0.6.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.
package/README.md CHANGED
@@ -55,6 +55,7 @@ NODE_OPTIONS="--require @tracelumo/node/register" npm run dev
55
55
  | `TRACELUMO_LOGS` | `true` | Set to `false` to stop sending console output as logs and errors. |
56
56
  | `TRACELUMO_METRICS` | `true` | Set to `false` to stop sending system metrics. |
57
57
  | `TRACELUMO_METRICS_INTERVAL` | `15` | Seconds between metric samples (5 to 300). |
58
+ | `TRACELUMO_HEARTBEAT_INTERVAL` | `1` | Seconds between heartbeats (1 to 60); `0` turns them off. |
58
59
  | `TRACELUMO_ENABLED` | `true` | Set to `false` to turn the SDK off. |
59
60
 
60
61
  Logs are batched (up to 100 per request, sent every second) and capped at 8 KiB per line. Node.js process warnings are sent as `warn`, not `error`.
@@ -68,6 +69,12 @@ built-ins inside your app: no agent or extra process. The first sample is taken
68
69
  sent right away, so serverless functions (Vercel, AWS Lambda), which pause between requests, report while they run. The
69
70
  timers never keep your process alive.
70
71
 
72
+ **Heartbeat:** every second the SDK also sends a tiny heartbeat with the current CPU, memory and event loop use. The
73
+ Infrastructure page shows each instance online and current within a second. Heartbeats reuse one connection, never
74
+ overlap, update the instance in place (they add no rows to the database), and stop if the server doesn't support them.
75
+ On serverless platforms each heartbeat is a function call to TraceLumo; raise `TRACELUMO_HEARTBEAT_INTERVAL` (for
76
+ example to `5`) if that matters for your plan.
77
+
71
78
  **Containers (Docker, Kubernetes, ECS, Fargate):** inside a container, Node.js reports the host's CPUs and memory, so
72
79
  the SDK also reads the container's own cgroup (v2, or v1 on older nodes). It reports:
73
80
  - CPU against the container's limit, and CPU throttling.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tracelumo/node",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "Connect Node.js apps to TraceLumo: automatic traces, logs, errors and system metrics",
5
5
  "type": "commonjs",
6
6
  "main": "./src/index.cjs",
package/src/config.cjs CHANGED
@@ -65,10 +65,13 @@ function configuration(options = {}, cwd = process.cwd(), environment = process.
65
65
  // Seconds between metric samples: 15 by default, 5 to 300.
66
66
  const requested = Number(options.metricsInterval ?? setting('TRACELUMO_METRICS_INTERVAL') ?? 15);
67
67
  const metricsInterval = Number.isFinite(requested) ? Math.min(300, Math.max(5, Math.round(requested))) : 15;
68
+ // Seconds between heartbeats: 1 by default, up to 60; 0 turns them off (metrics samples still go out).
69
+ const beat = Number(options.heartbeatInterval ?? setting('TRACELUMO_HEARTBEAT_INTERVAL') ?? 1);
70
+ const heartbeatInterval = Number.isFinite(beat) ? (beat <= 0 ? 0 : Math.min(60, Math.max(1, Math.round(beat)))) : 1;
68
71
  const base = url.replace(/\/v1\/traces$/, '');
69
72
  return {
70
73
  url, logsUrl: `${base}/v1/ingest/logs`, errorsUrl: `${base}/v1/ingest/errors`, metricsUrl: `${base}/v1/ingest/metrics`,
71
- token, service, logs, metrics, metricsInterval,
74
+ heartbeatUrl: `${base}/v1/ingest/heartbeat`, token, service, logs, metrics, metricsInterval, heartbeatInterval,
72
75
  };
73
76
  }
74
77
 
package/src/index.d.cts CHANGED
@@ -9,6 +9,8 @@ export interface TracingOptions {
9
9
  metrics?: boolean;
10
10
  /** Seconds between metric samples, 5 to 300. Defaults to 15 (TRACELUMO_METRICS_INTERVAL). */
11
11
  metricsInterval?: number;
12
+ /** Seconds between heartbeats (current CPU and memory, online status), 1 to 60; 0 turns them off. Defaults to 1 (TRACELUMO_HEARTBEAT_INTERVAL). */
13
+ heartbeatInterval?: number;
12
14
  }
13
15
 
14
16
  export function start(options?: TracingOptions): void;
package/src/metrics.cjs CHANGED
@@ -6,6 +6,8 @@ const os = require('node:os');
6
6
  const { monitorEventLoopDelay, performance, PerformanceObserver } = require('node:perf_hooks');
7
7
  const { containerValues, createCgroup, ecsDetails, platform } = require('./container.cjs');
8
8
  const { createQueue } = require('./logs.cjs');
9
+ const http = require('node:http');
10
+ const https = require('node:https');
9
11
 
10
12
  /**
11
13
  * System and runtime metrics, collected inside the application with Node.js built-ins only — no agent, no extra
@@ -169,11 +171,83 @@ function createSampler({ service, cwd = process.cwd(), cgroup } = {}) {
169
171
  return values;
170
172
  }
171
173
 
172
- return { info, sample, stop: () => { delay.disable(); gc?.disconnect(); } };
174
+ // The heartbeat's quick reading: CPU, memory and event loop use since the previous beat. It keeps its own
175
+ // baseline, so it doesn't disturb the full samples.
176
+ let lastBeat = { at: performance.now(), cpu: process.cpuUsage(), elu: performance.eventLoopUtilization(), group: lastGroup };
177
+ function beat() {
178
+ const now = { at: performance.now(), cpu: process.cpuUsage(), elu: performance.eventLoopUtilization(), group: group?.read() ?? null };
179
+ const elapsedMs = Math.max(1, now.at - lastBeat.at);
180
+ const cpu = ((now.cpu.user - lastBeat.cpu.user + now.cpu.system - lastBeat.cpu.system) / 1000 / elapsedMs / (info.cpus || 1)) * 100;
181
+ const memory = process.memoryUsage();
182
+ const values = {
183
+ process_cpu: round(Math.min(100, Math.max(0, cpu))),
184
+ rss: memory.rss,
185
+ heap_used: memory.heapUsed,
186
+ event_loop_utilization: round(performance.eventLoopUtilization(now.elu, lastBeat.elu).utilization * 100),
187
+ uptime: Math.round(process.uptime()),
188
+ };
189
+ if (group) {
190
+ const container = containerValues(lastBeat.group, now.group, elapsedMs, info.cpus);
191
+ for (const key of ['container_cpu', 'container_cpu_cores', 'container_memory', 'container_memory_pct']) {
192
+ if (container[key] !== undefined) values[key] = container[key];
193
+ }
194
+ }
195
+ lastBeat = now;
196
+ return values;
197
+ }
198
+
199
+ return { info, sample, beat, stop: () => { delay.disable(); gc?.disconnect(); } };
173
200
  }
174
201
 
175
202
  /** Samples every `interval` seconds and sends the samples to TraceLumo in batches. */
176
- function startMetrics({ metricsUrl, token, service, metricsInterval }, options) {
203
+ /**
204
+ * A heartbeat every `seconds`: a tiny request with the instance's current CPU and memory, so the dashboard shows
205
+ * it online and current within a second. One kept-alive connection, never more than one request at a time, no
206
+ * retries (the next beat replaces a lost one). It stops for good if the server doesn't know heartbeats (an older
207
+ * TraceLumo) or rejects the token.
208
+ */
209
+ function startHeartbeat({ heartbeatUrl, token }, { instance, sampler, seconds, suppress }) {
210
+ const target = new URL(heartbeatUrl);
211
+ const transport = target.protocol === 'https:' ? https : http;
212
+ const agent = new transport.Agent({ keepAlive: true, maxSockets: 1 });
213
+ let busy = false;
214
+ let stopped = false;
215
+ const send = () => {
216
+ if (busy || stopped) return;
217
+ let body;
218
+ try {
219
+ body = JSON.stringify({
220
+ instance, timestamp: new Date().toISOString(), every: seconds,
221
+ service: sampler.info.service, hostname: sampler.info.hostname, values: sampler.beat(),
222
+ });
223
+ } catch {
224
+ return;
225
+ }
226
+ busy = true;
227
+ suppress(() => {
228
+ const request = transport.request(target, {
229
+ method: 'POST', agent, timeout: 4000,
230
+ headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body), Authorization: `Bearer ${token}` },
231
+ }, (response) => {
232
+ if (response.statusCode === 404 || response.statusCode === 401 || response.statusCode === 403) stopped = true;
233
+ response.resume();
234
+ response.on('end', () => { busy = false; });
235
+ response.on('error', () => { busy = false; });
236
+ });
237
+ request.on('timeout', () => request.destroy());
238
+ request.on('error', () => { busy = false; });
239
+ request.end(body);
240
+ });
241
+ };
242
+ const timer = setInterval(send, seconds * 1000);
243
+ timer.unref();
244
+ return () => {
245
+ clearInterval(timer);
246
+ agent.destroy();
247
+ };
248
+ }
249
+
250
+ function startMetrics({ metricsUrl, heartbeatUrl, token, service, metricsInterval, heartbeatInterval = 0 }, options) {
177
251
  const sampler = createSampler({ service });
178
252
  const instance = randomUUID();
179
253
  // On ECS, the task metadata endpoint adds the cluster, task, launch type (EC2 or Fargate) and zone.
@@ -192,9 +266,13 @@ function startMetrics({ metricsUrl, token, service, metricsInterval }, options)
192
266
  first.unref();
193
267
  const timer = setInterval(record, metricsInterval * 1000);
194
268
  timer.unref();
269
+ const stopHeartbeat = heartbeatInterval > 0 && heartbeatUrl
270
+ ? startHeartbeat({ heartbeatUrl, token }, { instance, sampler, seconds: heartbeatInterval, suppress: options.suppress })
271
+ : () => {};
195
272
  return {
196
273
  flush: queue.flush,
197
274
  async close() {
275
+ stopHeartbeat();
198
276
  clearTimeout(first);
199
277
  clearInterval(timer);
200
278
  record();
@@ -204,4 +282,4 @@ function startMetrics({ metricsUrl, token, service, metricsInterval }, options)
204
282
  };
205
283
  }
206
284
 
207
- module.exports = { createSampler, startMetrics, hostInfo, runtime, defined };
285
+ module.exports = { createSampler, startMetrics, startHeartbeat, hostInfo, runtime, defined };