tracenest-node 0.0.0-stage → 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.
@@ -0,0 +1,382 @@
1
+ 'use strict';
2
+
3
+ const { ContextManager } = require('./context');
4
+ const { EventStore } = require('./eventStore');
5
+ const { Operation } = require('./operation');
6
+ const { TraceEvent, EventTypes } = require('./event');
7
+ const { createTraceId } = require('../utils/identifiers');
8
+ const { calculateStatistics } = require('../analysis/statistics');
9
+ const { detectSlowOperations, buildOperationTree } = require('../analysis/slowOperations');
10
+ const { ConsoleReporter } = require('../reporters/consoleReporter');
11
+ const { JsonReporter } = require('../reporters/jsonReporter');
12
+
13
+ class Tracer {
14
+ /**
15
+ * @param {object} [options]
16
+ */
17
+ constructor(options = {}) {
18
+ this.options = {
19
+ slowOperationThresholdMs: 100,
20
+ maxEvents: 10000,
21
+ maxOperations: 10000,
22
+ autoWarnSlowOperations: false,
23
+ name: 'default',
24
+ ...options
25
+ };
26
+
27
+ this.enabled = false;
28
+ this.traceId = null;
29
+ this.contextManager = new ContextManager();
30
+ this.store = new EventStore({
31
+ maxEvents: this.options.maxEvents,
32
+ maxOperations: this.options.maxOperations
33
+ });
34
+ this.consoleReporter = new ConsoleReporter();
35
+ this.jsonReporter = new JsonReporter();
36
+ this._sessionStarted = false;
37
+ }
38
+
39
+ /**
40
+ * Starts or enables tracing session.
41
+ * @param {object} [options]
42
+ * @returns {Tracer} this
43
+ */
44
+ start(options = {}) {
45
+ this.configure(options);
46
+ this.enabled = true;
47
+
48
+ if (!this.traceId) {
49
+ this.traceId = options.traceId || createTraceId();
50
+ }
51
+
52
+ if (!this._sessionStarted) {
53
+ this._sessionStarted = true;
54
+ const startEvent = new TraceEvent({
55
+ traceId: this.traceId,
56
+ type: EventTypes.START,
57
+ name: `Trace session started: ${this.options.name || 'default'}`,
58
+ timestamp: Date.now(),
59
+ depth: 0
60
+ });
61
+ this.store.addEvent(startEvent);
62
+ }
63
+
64
+ return this;
65
+ }
66
+
67
+ /**
68
+ * Disables tracing without resetting data.
69
+ * @returns {Tracer} this
70
+ */
71
+ stop() {
72
+ if (this.enabled && this.traceId) {
73
+ const endEvent = new TraceEvent({
74
+ traceId: this.traceId,
75
+ type: EventTypes.END,
76
+ name: `Trace session stopped: ${this.options.name || 'default'}`,
77
+ timestamp: Date.now(),
78
+ depth: 0
79
+ });
80
+ this.store.addEvent(endEvent);
81
+ }
82
+ this.enabled = false;
83
+ return this;
84
+ }
85
+
86
+ /**
87
+ * Resets all stored events, operations, and trace session state.
88
+ * @returns {Tracer} this
89
+ */
90
+ reset() {
91
+ this.enabled = false;
92
+ this.store.clear();
93
+ this.traceId = null;
94
+ this._sessionStarted = false;
95
+ return this;
96
+ }
97
+
98
+ /**
99
+ * Reconfigures tracer options.
100
+ * @param {object} options
101
+ * @returns {Tracer} this
102
+ */
103
+ configure(options = {}) {
104
+ if (typeof options !== 'object' || options === null) {
105
+ return this;
106
+ }
107
+
108
+ if (typeof options.slowOperationThresholdMs === 'number' && options.slowOperationThresholdMs >= 0) {
109
+ this.options.slowOperationThresholdMs = options.slowOperationThresholdMs;
110
+ }
111
+ if (typeof options.maxEvents === 'number' && options.maxEvents > 0) {
112
+ this.options.maxEvents = options.maxEvents;
113
+ this.store.configure({ maxEvents: options.maxEvents });
114
+ }
115
+ if (typeof options.maxOperations === 'number' && options.maxOperations > 0) {
116
+ this.options.maxOperations = options.maxOperations;
117
+ this.store.configure({ maxOperations: options.maxOperations });
118
+ }
119
+ if (typeof options.autoWarnSlowOperations === 'boolean') {
120
+ this.options.autoWarnSlowOperations = options.autoWarnSlowOperations;
121
+ }
122
+ if (typeof options.name === 'string') {
123
+ this.options.name = options.name;
124
+ }
125
+ if (typeof options.enabled === 'boolean') {
126
+ this.enabled = options.enabled;
127
+ }
128
+
129
+ return this;
130
+ }
131
+
132
+ /**
133
+ * Returns whether tracing is currently enabled.
134
+ * @returns {boolean}
135
+ */
136
+ isEnabled() {
137
+ return this.enabled;
138
+ }
139
+
140
+ /**
141
+ * Returns currently active operation from execution context.
142
+ * @returns {Operation|null}
143
+ */
144
+ getActiveOperation() {
145
+ return this.contextManager.getActiveOperation();
146
+ }
147
+
148
+ /**
149
+ * Records a point-in-time tracking event in the current execution context.
150
+ * @param {string} name Event description/name
151
+ * @param {object} [metadata] Custom event metadata
152
+ * @returns {TraceEvent|null}
153
+ */
154
+ track(name, metadata) {
155
+ if (!this.enabled) return null;
156
+
157
+ const activeOp = this.contextManager.getActiveOperation();
158
+ const traceId = (activeOp && activeOp.traceId) || this.traceId || createTraceId();
159
+ const depth = activeOp ? activeOp.depth + 1 : 0;
160
+
161
+ const event = new TraceEvent({
162
+ traceId,
163
+ operationId: activeOp ? activeOp.id : null,
164
+ parentOperationId: activeOp ? activeOp.id : null,
165
+ type: EventTypes.TRACK,
166
+ name: String(name || 'unnamed_event'),
167
+ depth,
168
+ metadata
169
+ });
170
+
171
+ this.store.addEvent(event);
172
+ return event;
173
+ }
174
+
175
+ /**
176
+ * Manually begins a new timed operation.
177
+ * @param {string} name Operation name
178
+ * @param {object} [metadata] Custom operation metadata
179
+ * @returns {Operation} The created operation
180
+ */
181
+ begin(name, metadata = {}) {
182
+ const activeOp = this.contextManager.getActiveOperation();
183
+ const traceId = (activeOp && activeOp.traceId) || this.traceId || createTraceId();
184
+ const parentId = activeOp ? activeOp.id : null;
185
+ const depth = activeOp ? activeOp.depth + 1 : 0;
186
+
187
+ const operation = new Operation({
188
+ traceId,
189
+ parentId,
190
+ name: String(name || 'unnamed_operation'),
191
+ depth,
192
+ metadata,
193
+ store: this.enabled ? this.store : null,
194
+ tracer: this
195
+ });
196
+
197
+ if (activeOp) {
198
+ activeOp.addChild(operation.id);
199
+ }
200
+
201
+ if (this.enabled) {
202
+ this.store.addOperation(operation);
203
+ const callEvent = new TraceEvent({
204
+ traceId,
205
+ operationId: operation.id,
206
+ parentOperationId: parentId,
207
+ type: EventTypes.CALL,
208
+ name: operation.name,
209
+ depth,
210
+ metadata: Object.keys(operation.metadata).length > 0 ? operation.metadata : undefined
211
+ });
212
+ this.store.addEvent(callEvent);
213
+ }
214
+
215
+ return operation;
216
+ }
217
+
218
+ /**
219
+ * Traces a synchronous or asynchronous function execution.
220
+ * Automatically tracks start, completion, duration, status, and nesting.
221
+ * Preserves return values and re-throws errors without swallowing.
222
+ *
223
+ * @param {string} name Name of the operation
224
+ * @param {Function} fn Function to execute
225
+ * @param {object} [metadata] Optional metadata
226
+ * @returns {Promise<any>|any}
227
+ */
228
+ trace(name, fn, metadata = {}) {
229
+ if (typeof fn !== 'function') {
230
+ throw new TypeError(`TraceNest.trace expects a function as second argument, got ${typeof fn}`);
231
+ }
232
+
233
+ if (!this.enabled) {
234
+ return fn();
235
+ }
236
+
237
+ const activeOp = this.contextManager.getActiveOperation();
238
+ const traceId = (activeOp && activeOp.traceId) || this.traceId || createTraceId();
239
+ const parentId = activeOp ? activeOp.id : null;
240
+ const depth = activeOp ? activeOp.depth + 1 : 0;
241
+
242
+ const operation = new Operation({
243
+ traceId,
244
+ parentId,
245
+ name: String(name || 'unnamed_operation'),
246
+ depth,
247
+ metadata,
248
+ store: this.store,
249
+ tracer: this
250
+ });
251
+
252
+ if (activeOp) {
253
+ activeOp.addChild(operation.id);
254
+ }
255
+
256
+ this.store.addOperation(operation);
257
+
258
+ // Record CALL event
259
+ const callEvent = new TraceEvent({
260
+ traceId,
261
+ operationId: operation.id,
262
+ parentOperationId: parentId,
263
+ type: EventTypes.CALL,
264
+ name: operation.name,
265
+ depth,
266
+ metadata: Object.keys(operation.metadata).length > 0 ? operation.metadata : undefined
267
+ });
268
+ this.store.addEvent(callEvent);
269
+
270
+ const childContext = this.contextManager.createChildContext(operation);
271
+
272
+ // Run inside async context
273
+ return this.contextManager.run(childContext, () => {
274
+ let result;
275
+ try {
276
+ result = fn();
277
+ } catch (err) {
278
+ operation.fail(err);
279
+ throw err;
280
+ }
281
+
282
+ // Check if result is a Promise / Thenable
283
+ if (result !== null && (typeof result === 'object' || typeof result === 'function') && typeof result.then === 'function') {
284
+ return Promise.resolve(result)
285
+ .then((val) => {
286
+ operation.end(null);
287
+ return val;
288
+ })
289
+ .catch((err) => {
290
+ operation.fail(err);
291
+ throw err;
292
+ });
293
+ }
294
+
295
+ // Synchronous success
296
+ operation.end(null);
297
+ return result;
298
+ });
299
+ }
300
+
301
+ /**
302
+ * Compiles and returns all report data as a structured object.
303
+ * @param {object} [options]
304
+ * @returns {object}
305
+ */
306
+ getReportData(options = {}) {
307
+ const operations = this.store.getOperations();
308
+ const events = this.store.getEvents();
309
+ const summary = calculateStatistics(operations, events);
310
+ const threshold = (options && options.slowOperationThresholdMs !== undefined)
311
+ ? options.slowOperationThresholdMs
312
+ : this.options.slowOperationThresholdMs;
313
+ const slowOperations = detectSlowOperations(operations, threshold);
314
+ const tree = buildOperationTree(operations);
315
+
316
+ // Collect errors
317
+ const errors = [];
318
+ for (const op of operations) {
319
+ if (op.status === 'ERROR' && op.error) {
320
+ errors.push({
321
+ operationId: op.id,
322
+ name: op.name,
323
+ error: op.error,
324
+ durationMs: op.durationMs,
325
+ timestamp: op.endTime || op.startTime
326
+ });
327
+ }
328
+ }
329
+
330
+ return {
331
+ tracenestVersion: require('../../package.json').version,
332
+ traceId: this.traceId,
333
+ name: this.options.name,
334
+ timestamp: new Date().toISOString(),
335
+ summary,
336
+ slowOperations,
337
+ tree,
338
+ operations: operations.map(op => typeof op.toJSON === 'function' ? op.toJSON() : op),
339
+ events: events.map(e => typeof e.toJSON === 'function' ? e.toJSON() : e),
340
+ errors,
341
+ storeStats: this.store.size()
342
+ };
343
+ }
344
+
345
+ /**
346
+ * Generates and prints the console execution report.
347
+ * @param {object} [options]
348
+ * @returns {string} Rendered text output
349
+ */
350
+ report(options = {}) {
351
+ const reportData = this.getReportData(options);
352
+ if (!options.silent) {
353
+ this.consoleReporter.print(reportData, options);
354
+ }
355
+ return this.consoleReporter.render(reportData, options);
356
+ }
357
+
358
+ /**
359
+ * Exports full trace data as a JSON file.
360
+ * @param {string} filePath Target file path
361
+ * @param {object} [options]
362
+ * @returns {string} Resolved file path
363
+ */
364
+ exportJSON(filePath, options = {}) {
365
+ const reportData = this.getReportData(options);
366
+ return this.jsonReporter.export(filePath, reportData, options);
367
+ }
368
+
369
+ /**
370
+ * Express middleware factory.
371
+ * @param {object} [options]
372
+ * @returns {Function} Express middleware (req, res, next)
373
+ */
374
+ expressMiddleware(options = {}) {
375
+ const { createExpressMiddleware } = require('../integrations/express');
376
+ return createExpressMiddleware(this, options);
377
+ }
378
+ }
379
+
380
+ module.exports = {
381
+ Tracer
382
+ };
package/src/index.js ADDED
@@ -0,0 +1,70 @@
1
+ 'use strict';
2
+
3
+ const { Tracer } = require('./core/tracer');
4
+ const { Operation, OperationStatus } = require('./core/operation');
5
+ const { TraceEvent, EventTypes } = require('./core/event');
6
+ const { ContextManager } = require('./core/context');
7
+ const { EventStore } = require('./core/eventStore');
8
+ const { calculateStatistics } = require('./analysis/statistics');
9
+ const { detectSlowOperations, buildOperationTree } = require('./analysis/slowOperations');
10
+ const { ConsoleReporter } = require('./reporters/consoleReporter');
11
+ const { JsonReporter } = require('./reporters/jsonReporter');
12
+ const { createExpressMiddleware, createExpressErrorMiddleware } = require('./integrations/express');
13
+
14
+ // Default global singleton tracer
15
+ const defaultTracer = new Tracer();
16
+
17
+ // Bind all methods to preserve `this` context when destructured
18
+ const TraceNest = {
19
+ // Main tracing methods
20
+ start: defaultTracer.start.bind(defaultTracer),
21
+ stop: defaultTracer.stop.bind(defaultTracer),
22
+ reset: defaultTracer.reset.bind(defaultTracer),
23
+ configure: defaultTracer.configure.bind(defaultTracer),
24
+ isEnabled: defaultTracer.isEnabled.bind(defaultTracer),
25
+ getActiveOperation: defaultTracer.getActiveOperation.bind(defaultTracer),
26
+ track: defaultTracer.track.bind(defaultTracer),
27
+ begin: defaultTracer.begin.bind(defaultTracer),
28
+ trace: defaultTracer.trace.bind(defaultTracer),
29
+ report: defaultTracer.report.bind(defaultTracer),
30
+ exportJSON: defaultTracer.exportJSON.bind(defaultTracer),
31
+ getReportData: defaultTracer.getReportData.bind(defaultTracer),
32
+ expressMiddleware: defaultTracer.expressMiddleware.bind(defaultTracer),
33
+ expressErrorMiddleware: () => createExpressErrorMiddleware(defaultTracer),
34
+
35
+ // Properties
36
+ get traceId() {
37
+ return defaultTracer.traceId;
38
+ },
39
+ get enabled() {
40
+ return defaultTracer.enabled;
41
+ },
42
+ get store() {
43
+ return defaultTracer.store;
44
+ },
45
+
46
+ // Export classes and helpers for advanced / customized use
47
+ Tracer,
48
+ Operation,
49
+ OperationStatus,
50
+ TraceEvent,
51
+ EventTypes,
52
+ ContextManager,
53
+ EventStore,
54
+ calculateStatistics,
55
+ detectSlowOperations,
56
+ buildOperationTree,
57
+ ConsoleReporter,
58
+ JsonReporter,
59
+ createExpressMiddleware,
60
+ createExpressErrorMiddleware,
61
+
62
+ /**
63
+ * Factory function to create a new isolated Tracer instance.
64
+ * @param {object} [options]
65
+ * @returns {Tracer}
66
+ */
67
+ createTracer: (options) => new Tracer(options)
68
+ };
69
+
70
+ module.exports = TraceNest;
@@ -0,0 +1,136 @@
1
+ 'use strict';
2
+
3
+ const { createRequestId } = require('../utils/identifiers');
4
+
5
+ /**
6
+ * Creates Express middleware for tracing HTTP requests and associating downstream operations.
7
+ *
8
+ * @param {import('../core/tracer').Tracer} tracer
9
+ * @param {object} [options]
10
+ * @param {string} [options.headerName='x-request-id']
11
+ * @param {boolean} [options.injectHeader=true] Whether to set response headers X-Trace-Id and X-Request-Id
12
+ * @param {Array<string|RegExp>} [options.ignorePaths=[]] Paths to exclude from tracing
13
+ * @returns {Function} Express middleware (req, res, next)
14
+ */
15
+ function createExpressMiddleware(tracer, options = {}) {
16
+ const headerName = (options.headerName || 'x-request-id').toLowerCase();
17
+ const injectHeader = options.injectHeader !== false;
18
+ const ignorePaths = options.ignorePaths || [];
19
+
20
+ return function tracenestMiddleware(req, res, next) {
21
+ if (!tracer.isEnabled()) {
22
+ return next();
23
+ }
24
+
25
+ // Check if path is in ignore list
26
+ const reqPath = req.path || req.url || '';
27
+ for (const pattern of ignorePaths) {
28
+ if (typeof pattern === 'string' && reqPath === pattern) {
29
+ return next();
30
+ }
31
+ if (pattern instanceof RegExp && pattern.test(reqPath)) {
32
+ return next();
33
+ }
34
+ }
35
+
36
+ // Extract or generate request ID
37
+ const requestId = (req.headers && req.headers[headerName]) || createRequestId();
38
+ req.requestId = requestId;
39
+ req.traceId = tracer.traceId;
40
+
41
+ if (injectHeader) {
42
+ if (typeof res.setHeader === 'function') {
43
+ if (tracer.traceId) res.setHeader('X-Trace-Id', tracer.traceId);
44
+ res.setHeader('X-Request-Id', requestId);
45
+ }
46
+ }
47
+
48
+ const method = req.method || 'GET';
49
+ const rawUrl = req.originalUrl || req.url || '/';
50
+ const opName = `HTTP ${method} ${req.path || rawUrl}`;
51
+
52
+ const metadata = {
53
+ httpMethod: method,
54
+ url: rawUrl,
55
+ path: req.path || reqPath,
56
+ requestId,
57
+ ip: req.ip || (req.socket && req.socket.remoteAddress),
58
+ userAgent: req.headers && req.headers['user-agent']
59
+ };
60
+
61
+ // Begin the HTTP operation
62
+ const operation = tracer.begin(opName, metadata);
63
+ let ended = false;
64
+
65
+ const cleanup = (error = null) => {
66
+ if (ended) return;
67
+ ended = true;
68
+
69
+ const statusCode = res.statusCode || 200;
70
+ operation.annotate('statusCode', statusCode);
71
+
72
+ // If route pattern is available (e.g. /users/:id), record it
73
+ if (req.route && req.route.path) {
74
+ operation.annotate('route', `${req.baseUrl || ''}${req.route.path}`);
75
+ }
76
+
77
+ if (error) {
78
+ operation.fail(error);
79
+ } else if (statusCode >= 400) {
80
+ const httpError = new Error(`HTTP ${statusCode} ${res.statusMessage || 'Request Error'}`);
81
+ httpError.statusCode = statusCode;
82
+ operation.fail(httpError);
83
+ } else {
84
+ operation.end();
85
+ }
86
+ };
87
+
88
+ // Listen on response finish
89
+ res.on('finish', () => {
90
+ cleanup(null);
91
+ });
92
+
93
+ // Listen on aborted connection
94
+ res.on('close', () => {
95
+ if (!res.writableEnded && !res.finished) {
96
+ cleanup(new Error('HTTP request connection closed before response completed'));
97
+ }
98
+ });
99
+
100
+ // Run downstream middleware & route handlers inside child context
101
+ const childContext = tracer.contextManager.createChildContext(operation, {
102
+ requestId,
103
+ isHttpRequest: true
104
+ });
105
+
106
+ return tracer.contextManager.run(childContext, () => {
107
+ return next();
108
+ });
109
+ };
110
+ }
111
+
112
+ /**
113
+ * Express error handling middleware to capture route errors.
114
+ * @param {import('../core/tracer').Tracer} tracer
115
+ * @returns {Function} (err, req, res, next)
116
+ */
117
+ function createExpressErrorMiddleware(tracer) {
118
+ return function tracenestErrorHandler(err, req, res, next) {
119
+ if (tracer.isEnabled()) {
120
+ const activeOp = tracer.contextManager.getActiveOperation();
121
+ if (activeOp) {
122
+ activeOp.annotate('hasError', true);
123
+ activeOp.track('Express error encountered', {
124
+ errorMessage: err.message,
125
+ errorName: err.name
126
+ });
127
+ }
128
+ }
129
+ return next(err);
130
+ };
131
+ }
132
+
133
+ module.exports = {
134
+ createExpressMiddleware,
135
+ createExpressErrorMiddleware
136
+ };