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.
- package/LICENSE +7 -0
- package/README.md +203 -2
- package/bin/tracenest.js +252 -0
- package/package.json +45 -3
- package/src/analysis/slowOperations.js +69 -0
- package/src/analysis/statistics.js +151 -0
- package/src/core/context.js +77 -0
- package/src/core/event.js +131 -0
- package/src/core/eventStore.js +151 -0
- package/src/core/operation.js +199 -0
- package/src/core/tracer.js +382 -0
- package/src/index.js +70 -0
- package/src/integrations/express.js +136 -0
- package/src/reporters/consoleReporter.js +167 -0
- package/src/reporters/jsonReporter.js +49 -0
- package/src/utils/formatting.js +66 -0
- package/src/utils/identifiers.js +30 -0
- package/src/utils/time.js +61 -0
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Calculates detailed performance and execution statistics from operations and events.
|
|
5
|
+
* Clearly distinguishes total wall-clock elapsed time from cumulative operation durations.
|
|
6
|
+
*
|
|
7
|
+
* @param {Array<import('../core/operation').Operation>} operations
|
|
8
|
+
* @param {Array<import('../core/event').TraceEvent>} [events=[]]
|
|
9
|
+
* @returns {object}
|
|
10
|
+
*/
|
|
11
|
+
function calculateStatistics(operations = [], events = []) {
|
|
12
|
+
const totalOperations = operations.length;
|
|
13
|
+
let successfulOperations = 0;
|
|
14
|
+
let failedOperations = 0;
|
|
15
|
+
let runningOperations = 0;
|
|
16
|
+
|
|
17
|
+
const statusCounts = {
|
|
18
|
+
SUCCESS: 0,
|
|
19
|
+
ERROR: 0,
|
|
20
|
+
RUNNING: 0
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
const nameCounts = {};
|
|
24
|
+
const completedDurations = [];
|
|
25
|
+
|
|
26
|
+
let minDuration = null;
|
|
27
|
+
let maxDuration = null;
|
|
28
|
+
let sumDuration = 0;
|
|
29
|
+
|
|
30
|
+
let earliestStartTime = null;
|
|
31
|
+
let latestEndTime = null;
|
|
32
|
+
|
|
33
|
+
for (const op of operations) {
|
|
34
|
+
// Status counts
|
|
35
|
+
if (op.status === 'SUCCESS') {
|
|
36
|
+
successfulOperations++;
|
|
37
|
+
statusCounts.SUCCESS++;
|
|
38
|
+
} else if (op.status === 'ERROR') {
|
|
39
|
+
failedOperations++;
|
|
40
|
+
statusCounts.ERROR++;
|
|
41
|
+
} else {
|
|
42
|
+
runningOperations++;
|
|
43
|
+
statusCounts.RUNNING++;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// Name counts
|
|
47
|
+
nameCounts[op.name] = (nameCounts[op.name] || 0) + 1;
|
|
48
|
+
|
|
49
|
+
// Timing bounds for wall-clock calculation
|
|
50
|
+
if (typeof op.startTime === 'number') {
|
|
51
|
+
if (earliestStartTime === null || op.startTime < earliestStartTime) {
|
|
52
|
+
earliestStartTime = op.startTime;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
if (typeof op.endTime === 'number') {
|
|
56
|
+
if (latestEndTime === null || op.endTime > latestEndTime) {
|
|
57
|
+
latestEndTime = op.endTime;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// Individual completed operation durations
|
|
62
|
+
if (typeof op.durationMs === 'number' && !Number.isNaN(op.durationMs)) {
|
|
63
|
+
completedDurations.push(op.durationMs);
|
|
64
|
+
sumDuration += op.durationMs;
|
|
65
|
+
|
|
66
|
+
if (minDuration === null || op.durationMs < minDuration) {
|
|
67
|
+
minDuration = op.durationMs;
|
|
68
|
+
}
|
|
69
|
+
if (maxDuration === null || op.durationMs > maxDuration) {
|
|
70
|
+
maxDuration = op.durationMs;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// 1. Wall-clock elapsed time (from the very first operation start to the latest completion)
|
|
76
|
+
let wallClockTimeMs = 0;
|
|
77
|
+
if (earliestStartTime !== null && latestEndTime !== null) {
|
|
78
|
+
wallClockTimeMs = Math.max(0, latestEndTime - earliestStartTime);
|
|
79
|
+
} else if (completedDurations.length > 0) {
|
|
80
|
+
wallClockTimeMs = sumDuration;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// 2. Cumulative sum of all individual operation durations (can exceed wall-clock time due to concurrency/nesting)
|
|
84
|
+
const sumOperationDurationMs = Math.round(sumDuration * 1000) / 1000;
|
|
85
|
+
|
|
86
|
+
// 3. Average duration of completed operations
|
|
87
|
+
const completedCount = completedDurations.length;
|
|
88
|
+
const averageDurationMs = completedCount > 0 ? Math.round((sumDuration / completedCount) * 1000) / 1000 : 0;
|
|
89
|
+
|
|
90
|
+
// 4. Quantiles / Percentiles using linear interpolation
|
|
91
|
+
completedDurations.sort((a, b) => a - b);
|
|
92
|
+
const p50 = getPercentile(completedDurations, 50);
|
|
93
|
+
const p90 = getPercentile(completedDurations, 90);
|
|
94
|
+
const p95 = getPercentile(completedDurations, 95);
|
|
95
|
+
const p99 = getPercentile(completedDurations, 99);
|
|
96
|
+
|
|
97
|
+
const successRate = totalOperations > 0
|
|
98
|
+
? Math.round((successfulOperations / totalOperations) * 10000) / 100
|
|
99
|
+
: 100;
|
|
100
|
+
|
|
101
|
+
return {
|
|
102
|
+
totalOperations,
|
|
103
|
+
successfulOperations,
|
|
104
|
+
failedOperations,
|
|
105
|
+
runningOperations,
|
|
106
|
+
successRate,
|
|
107
|
+
totalEvents: events.length,
|
|
108
|
+
// totalExecutionTimeMs preserved for backwards compatibility; alias of wallClockTimeMs
|
|
109
|
+
totalExecutionTimeMs: wallClockTimeMs,
|
|
110
|
+
wallClockTimeMs,
|
|
111
|
+
sumOperationDurationMs,
|
|
112
|
+
averageDurationMs,
|
|
113
|
+
minDurationMs: minDuration !== null ? minDuration : 0,
|
|
114
|
+
maxDurationMs: maxDuration !== null ? maxDuration : 0,
|
|
115
|
+
percentiles: {
|
|
116
|
+
p50,
|
|
117
|
+
p90,
|
|
118
|
+
p95,
|
|
119
|
+
p99
|
|
120
|
+
},
|
|
121
|
+
statusCounts,
|
|
122
|
+
nameCounts
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Calculates the p-th percentile from a sorted array of numbers using linear interpolation.
|
|
128
|
+
* @param {number[]} sortedNumbers
|
|
129
|
+
* @param {number} p (0 - 100)
|
|
130
|
+
* @returns {number}
|
|
131
|
+
*/
|
|
132
|
+
function getPercentile(sortedNumbers, p) {
|
|
133
|
+
if (!Array.isArray(sortedNumbers) || sortedNumbers.length === 0) return 0;
|
|
134
|
+
if (sortedNumbers.length === 1) return sortedNumbers[0];
|
|
135
|
+
|
|
136
|
+
const rank = (p / 100) * (sortedNumbers.length - 1);
|
|
137
|
+
const lowerIndex = Math.floor(rank);
|
|
138
|
+
const fraction = rank - lowerIndex;
|
|
139
|
+
|
|
140
|
+
if (lowerIndex >= sortedNumbers.length - 1) {
|
|
141
|
+
return sortedNumbers[sortedNumbers.length - 1];
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const interpolated = sortedNumbers[lowerIndex] + fraction * (sortedNumbers[lowerIndex + 1] - sortedNumbers[lowerIndex]);
|
|
145
|
+
return Math.round(interpolated * 1000) / 1000;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
module.exports = {
|
|
149
|
+
calculateStatistics,
|
|
150
|
+
getPercentile
|
|
151
|
+
};
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { AsyncLocalStorage } = require('node:async_hooks');
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Manages async execution context for TraceNest using AsyncLocalStorage.
|
|
7
|
+
*/
|
|
8
|
+
class ContextManager {
|
|
9
|
+
constructor() {
|
|
10
|
+
this._storage = new AsyncLocalStorage();
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Runs a function within the specified trace context.
|
|
15
|
+
* @param {object} context
|
|
16
|
+
* @param {Function} fn
|
|
17
|
+
* @returns {any}
|
|
18
|
+
*/
|
|
19
|
+
run(context, fn) {
|
|
20
|
+
return this._storage.run(context, fn);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Returns current active context or undefined if outside context.
|
|
25
|
+
* @returns {object|undefined}
|
|
26
|
+
*/
|
|
27
|
+
get() {
|
|
28
|
+
return this._storage.getStore();
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Returns currently active Operation instance if any.
|
|
33
|
+
* @returns {import('./operation').Operation|null}
|
|
34
|
+
*/
|
|
35
|
+
getActiveOperation() {
|
|
36
|
+
const store = this.get();
|
|
37
|
+
return (store && store.operation) || null;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Returns current trace ID or null.
|
|
42
|
+
* @returns {string|null}
|
|
43
|
+
*/
|
|
44
|
+
getActiveTraceId() {
|
|
45
|
+
const store = this.get();
|
|
46
|
+
return (store && store.traceId) || null;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Returns current nesting depth level.
|
|
51
|
+
* @returns {number}
|
|
52
|
+
*/
|
|
53
|
+
getActiveDepth() {
|
|
54
|
+
const store = this.get();
|
|
55
|
+
return store ? store.depth : 0;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Creates a child context object for a new operation.
|
|
60
|
+
* @param {import('./operation').Operation} operation
|
|
61
|
+
* @param {object} [customFields]
|
|
62
|
+
* @returns {object}
|
|
63
|
+
*/
|
|
64
|
+
createChildContext(operation, customFields = {}) {
|
|
65
|
+
return {
|
|
66
|
+
traceId: operation.traceId,
|
|
67
|
+
operationId: operation.id,
|
|
68
|
+
operation,
|
|
69
|
+
depth: operation.depth + 1,
|
|
70
|
+
...customFields
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
module.exports = {
|
|
76
|
+
ContextManager
|
|
77
|
+
};
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { createEventId } = require('../utils/identifiers');
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Valid event types supported by TraceNest.
|
|
7
|
+
*/
|
|
8
|
+
const EventTypes = Object.freeze({
|
|
9
|
+
START: 'START',
|
|
10
|
+
TRACK: 'TRACK',
|
|
11
|
+
CALL: 'CALL',
|
|
12
|
+
SUCCESS: 'SUCCESS',
|
|
13
|
+
ERROR: 'ERROR',
|
|
14
|
+
WARNING: 'WARNING',
|
|
15
|
+
END: 'END'
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Safely serializes an Error instance or thrown value into a clean JSON-friendly object.
|
|
20
|
+
* Handles Error instances, primitives, null, undefined, and custom error-like objects.
|
|
21
|
+
*
|
|
22
|
+
* @param {unknown} err
|
|
23
|
+
* @param {boolean} [includeStack=true]
|
|
24
|
+
* @returns {object}
|
|
25
|
+
*/
|
|
26
|
+
function serializeError(err, includeStack = true) {
|
|
27
|
+
if (err === null) {
|
|
28
|
+
return { name: 'Error', message: 'Thrown error: null', stack: null };
|
|
29
|
+
}
|
|
30
|
+
if (err === undefined) {
|
|
31
|
+
return { name: 'Error', message: 'Thrown error: undefined', stack: null };
|
|
32
|
+
}
|
|
33
|
+
if (typeof err === 'string') {
|
|
34
|
+
return { name: 'Error', message: err, stack: null };
|
|
35
|
+
}
|
|
36
|
+
if (typeof err === 'number' || typeof err === 'boolean' || typeof err === 'symbol' || typeof err === 'bigint') {
|
|
37
|
+
return { name: 'Error', message: String(err), stack: null };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const result = {
|
|
41
|
+
name: err.name || 'Error',
|
|
42
|
+
message: err.message !== undefined ? String(err.message) : String(err),
|
|
43
|
+
code: err.code || undefined
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
if (includeStack && typeof err.stack === 'string') {
|
|
47
|
+
result.stack = err.stack;
|
|
48
|
+
} else {
|
|
49
|
+
result.stack = null;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// Preserve any custom error properties (e.g. status, details, errno)
|
|
53
|
+
for (const key of Object.keys(err)) {
|
|
54
|
+
if (!['name', 'message', 'stack', 'code'].includes(key)) {
|
|
55
|
+
try {
|
|
56
|
+
result[key] = err[key];
|
|
57
|
+
} catch (_) {
|
|
58
|
+
// Skip un-serializable properties
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
return result;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Represents an individual trace event.
|
|
68
|
+
*/
|
|
69
|
+
class TraceEvent {
|
|
70
|
+
/**
|
|
71
|
+
* @param {object} params
|
|
72
|
+
* @param {string} [params.id]
|
|
73
|
+
* @param {string} params.traceId
|
|
74
|
+
* @param {string|null} [params.operationId]
|
|
75
|
+
* @param {string|null} [params.parentOperationId]
|
|
76
|
+
* @param {string} params.type
|
|
77
|
+
* @param {string} params.name
|
|
78
|
+
* @param {number} [params.timestamp]
|
|
79
|
+
* @param {number|null} [params.durationMs]
|
|
80
|
+
* @param {number} [params.depth]
|
|
81
|
+
* @param {object} [params.metadata]
|
|
82
|
+
* @param {object|Error|null} [params.error]
|
|
83
|
+
*/
|
|
84
|
+
constructor({
|
|
85
|
+
id = createEventId(),
|
|
86
|
+
traceId,
|
|
87
|
+
operationId = null,
|
|
88
|
+
parentOperationId = null,
|
|
89
|
+
type,
|
|
90
|
+
name,
|
|
91
|
+
timestamp = Date.now(),
|
|
92
|
+
durationMs = null,
|
|
93
|
+
depth = 0,
|
|
94
|
+
metadata = undefined,
|
|
95
|
+
error = null
|
|
96
|
+
}) {
|
|
97
|
+
this.id = id;
|
|
98
|
+
this.traceId = traceId;
|
|
99
|
+
this.operationId = operationId;
|
|
100
|
+
this.parentOperationId = parentOperationId;
|
|
101
|
+
this.type = type;
|
|
102
|
+
this.name = String(name || 'unnamed_event');
|
|
103
|
+
this.timestamp = timestamp;
|
|
104
|
+
this.durationMs = durationMs !== null ? Number(durationMs) : null;
|
|
105
|
+
this.depth = Math.max(0, depth);
|
|
106
|
+
this.metadata = metadata && typeof metadata === 'object' ? { ...metadata } : undefined;
|
|
107
|
+
this.error = error ? (typeof error === 'object' && error.name && error.message ? error : serializeError(error)) : null;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
toJSON() {
|
|
111
|
+
return {
|
|
112
|
+
id: this.id,
|
|
113
|
+
traceId: this.traceId,
|
|
114
|
+
operationId: this.operationId,
|
|
115
|
+
parentOperationId: this.parentOperationId,
|
|
116
|
+
type: this.type,
|
|
117
|
+
name: this.name,
|
|
118
|
+
timestamp: this.timestamp,
|
|
119
|
+
durationMs: this.durationMs,
|
|
120
|
+
depth: this.depth,
|
|
121
|
+
...(this.metadata ? { metadata: this.metadata } : {}),
|
|
122
|
+
...(this.error ? { error: this.error } : {})
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
module.exports = {
|
|
128
|
+
EventTypes,
|
|
129
|
+
TraceEvent,
|
|
130
|
+
serializeError
|
|
131
|
+
};
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* In-memory bounded store for trace events and operations.
|
|
5
|
+
* Implements bounded storage to avoid unbounded memory growth.
|
|
6
|
+
*/
|
|
7
|
+
class EventStore {
|
|
8
|
+
/**
|
|
9
|
+
* @param {object} [options]
|
|
10
|
+
* @param {number} [options.maxEvents=10000] Maximum number of events to retain
|
|
11
|
+
* @param {number} [options.maxOperations=10000] Maximum number of operations to retain
|
|
12
|
+
*/
|
|
13
|
+
constructor(options = {}) {
|
|
14
|
+
this.maxEvents = options.maxEvents && options.maxEvents > 0 ? options.maxEvents : 10000;
|
|
15
|
+
this.maxOperations = options.maxOperations && options.maxOperations > 0 ? options.maxOperations : this.maxEvents;
|
|
16
|
+
this._events = [];
|
|
17
|
+
this._operations = new Map();
|
|
18
|
+
this.totalEventsRecorded = 0;
|
|
19
|
+
this.droppedEventsCount = 0;
|
|
20
|
+
this.totalOperationsRecorded = 0;
|
|
21
|
+
this.droppedOperationsCount = 0;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Update configuration.
|
|
26
|
+
* @param {object} options
|
|
27
|
+
*/
|
|
28
|
+
configure(options = {}) {
|
|
29
|
+
if (typeof options.maxEvents === 'number' && options.maxEvents > 0) {
|
|
30
|
+
this.maxEvents = options.maxEvents;
|
|
31
|
+
this._pruneEvents();
|
|
32
|
+
}
|
|
33
|
+
if (typeof options.maxOperations === 'number' && options.maxOperations > 0) {
|
|
34
|
+
this.maxOperations = options.maxOperations;
|
|
35
|
+
this._pruneOperations();
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Adds an event to the store. Drops oldest events if limit is exceeded.
|
|
41
|
+
* @param {import('./event').TraceEvent} event
|
|
42
|
+
*/
|
|
43
|
+
addEvent(event) {
|
|
44
|
+
if (!event) return;
|
|
45
|
+
this.totalEventsRecorded++;
|
|
46
|
+
|
|
47
|
+
if (this._events.length >= this.maxEvents) {
|
|
48
|
+
// Drop oldest 10% or at least 1 to prevent continuous small allocations
|
|
49
|
+
const dropCount = Math.max(1, Math.floor(this.maxEvents * 0.1));
|
|
50
|
+
this._events.splice(0, dropCount);
|
|
51
|
+
this.droppedEventsCount += dropCount;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
this._events.push(event);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Adds or updates an operation in the store.
|
|
59
|
+
* If operation capacity is exceeded, prunes oldest operations.
|
|
60
|
+
* @param {import('./operation').Operation} operation
|
|
61
|
+
*/
|
|
62
|
+
addOperation(operation) {
|
|
63
|
+
if (!operation || !operation.id) return;
|
|
64
|
+
|
|
65
|
+
if (!this._operations.has(operation.id)) {
|
|
66
|
+
this.totalOperationsRecorded++;
|
|
67
|
+
if (this._operations.size >= this.maxOperations) {
|
|
68
|
+
this._pruneOperations();
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
this._operations.set(operation.id, operation);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Retrieves an operation by ID.
|
|
77
|
+
* @param {string} id
|
|
78
|
+
* @returns {import('./operation').Operation|undefined}
|
|
79
|
+
*/
|
|
80
|
+
getOperation(id) {
|
|
81
|
+
return this._operations.get(id);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Returns a copy of all stored events in insertion order.
|
|
86
|
+
* @returns {import('./event').TraceEvent[]}
|
|
87
|
+
*/
|
|
88
|
+
getEvents() {
|
|
89
|
+
return [...this._events];
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Returns an array of all recorded operations.
|
|
94
|
+
* @returns {import('./operation').Operation[]}
|
|
95
|
+
*/
|
|
96
|
+
getOperations() {
|
|
97
|
+
return Array.from(this._operations.values());
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Clears all stored events and operations.
|
|
102
|
+
*/
|
|
103
|
+
clear() {
|
|
104
|
+
this._events = [];
|
|
105
|
+
this._operations.clear();
|
|
106
|
+
this.totalEventsRecorded = 0;
|
|
107
|
+
this.droppedEventsCount = 0;
|
|
108
|
+
this.totalOperationsRecorded = 0;
|
|
109
|
+
this.droppedOperationsCount = 0;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Returns current count of stored events and operations.
|
|
114
|
+
* @returns {{ eventsCount: number, operationsCount: number, totalEventsRecorded: number, droppedEventsCount: number, totalOperationsRecorded: number, droppedOperationsCount: number }}
|
|
115
|
+
*/
|
|
116
|
+
size() {
|
|
117
|
+
return {
|
|
118
|
+
eventsCount: this._events.length,
|
|
119
|
+
operationsCount: this._operations.size,
|
|
120
|
+
totalEventsRecorded: this.totalEventsRecorded,
|
|
121
|
+
droppedEventsCount: this.droppedEventsCount,
|
|
122
|
+
totalOperationsRecorded: this.totalOperationsRecorded,
|
|
123
|
+
droppedOperationsCount: this.droppedOperationsCount
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
_pruneEvents() {
|
|
128
|
+
if (this._events.length > this.maxEvents) {
|
|
129
|
+
const excess = this._events.length - this.maxEvents;
|
|
130
|
+
this._events.splice(0, excess);
|
|
131
|
+
this.droppedEventsCount += excess;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
_pruneOperations() {
|
|
136
|
+
if (this._operations.size >= this.maxOperations) {
|
|
137
|
+
const dropCount = Math.max(1, Math.floor(this.maxOperations * 0.1));
|
|
138
|
+
let count = 0;
|
|
139
|
+
for (const key of this._operations.keys()) {
|
|
140
|
+
this._operations.delete(key);
|
|
141
|
+
count++;
|
|
142
|
+
if (count >= dropCount) break;
|
|
143
|
+
}
|
|
144
|
+
this.droppedOperationsCount += count;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
module.exports = {
|
|
150
|
+
EventStore
|
|
151
|
+
};
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { createOperationId } = require('../utils/identifiers');
|
|
4
|
+
const { getHrTime, calcElapsedMs } = require('../utils/time');
|
|
5
|
+
const { serializeError, EventTypes, TraceEvent } = require('./event');
|
|
6
|
+
|
|
7
|
+
const OperationStatus = Object.freeze({
|
|
8
|
+
RUNNING: 'RUNNING',
|
|
9
|
+
SUCCESS: 'SUCCESS',
|
|
10
|
+
ERROR: 'ERROR'
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Represents a timed, potentially nested execution operation.
|
|
15
|
+
*/
|
|
16
|
+
class Operation {
|
|
17
|
+
/**
|
|
18
|
+
* @param {object} params
|
|
19
|
+
* @param {string} [params.id]
|
|
20
|
+
* @param {string} params.traceId
|
|
21
|
+
* @param {string|null} [params.parentId]
|
|
22
|
+
* @param {string} params.name
|
|
23
|
+
* @param {number} [params.depth]
|
|
24
|
+
* @param {object} [params.metadata]
|
|
25
|
+
* @param {object} [params.store] EventStore reference
|
|
26
|
+
* @param {object} [params.tracer] Tracer instance reference
|
|
27
|
+
*/
|
|
28
|
+
constructor({
|
|
29
|
+
id = createOperationId(),
|
|
30
|
+
traceId,
|
|
31
|
+
parentId = null,
|
|
32
|
+
name,
|
|
33
|
+
depth = 0,
|
|
34
|
+
metadata = {},
|
|
35
|
+
store = null,
|
|
36
|
+
tracer = null
|
|
37
|
+
}) {
|
|
38
|
+
this.id = id;
|
|
39
|
+
this.traceId = traceId;
|
|
40
|
+
this.parentId = parentId;
|
|
41
|
+
this.name = String(name || 'unnamed_operation');
|
|
42
|
+
this.depth = Math.max(0, depth);
|
|
43
|
+
this.metadata = { ...metadata };
|
|
44
|
+
this._store = store;
|
|
45
|
+
this._tracer = tracer;
|
|
46
|
+
|
|
47
|
+
this.startTime = Date.now();
|
|
48
|
+
this._startHrTime = getHrTime();
|
|
49
|
+
this.endTime = null;
|
|
50
|
+
this.durationMs = null;
|
|
51
|
+
this.status = OperationStatus.RUNNING;
|
|
52
|
+
this.error = null;
|
|
53
|
+
this.children = [];
|
|
54
|
+
this._ended = false;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Attach a child operation ID to this operation.
|
|
59
|
+
* @param {string} childId
|
|
60
|
+
*/
|
|
61
|
+
addChild(childId) {
|
|
62
|
+
if (childId && !this.children.includes(childId)) {
|
|
63
|
+
this.children.push(childId);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Annotate this operation with custom metadata.
|
|
69
|
+
* @param {string|object} keyOrObj
|
|
70
|
+
* @param {any} [value]
|
|
71
|
+
* @returns {Operation} this
|
|
72
|
+
*/
|
|
73
|
+
annotate(keyOrObj, value) {
|
|
74
|
+
if (typeof keyOrObj === 'string') {
|
|
75
|
+
this.metadata[keyOrObj] = value;
|
|
76
|
+
} else if (keyOrObj && typeof keyOrObj === 'object') {
|
|
77
|
+
Object.assign(this.metadata, keyOrObj);
|
|
78
|
+
}
|
|
79
|
+
return this;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Records a point-in-time tracking event nested inside this operation.
|
|
84
|
+
* @param {string} name
|
|
85
|
+
* @param {object} [metadata]
|
|
86
|
+
*/
|
|
87
|
+
track(name, metadata) {
|
|
88
|
+
if (!this._store) return;
|
|
89
|
+
const evt = new TraceEvent({
|
|
90
|
+
traceId: this.traceId,
|
|
91
|
+
operationId: this.id,
|
|
92
|
+
parentOperationId: this.parentId,
|
|
93
|
+
type: EventTypes.TRACK,
|
|
94
|
+
name,
|
|
95
|
+
depth: this.depth + 1,
|
|
96
|
+
metadata
|
|
97
|
+
});
|
|
98
|
+
this._store.addEvent(evt);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Ends the operation. Idempotent: repeated calls are safely ignored.
|
|
103
|
+
* @param {unknown} [err] Optional error if operation failed
|
|
104
|
+
* @returns {Operation} this
|
|
105
|
+
*/
|
|
106
|
+
end(err = null) {
|
|
107
|
+
if (this._ended) {
|
|
108
|
+
return this;
|
|
109
|
+
}
|
|
110
|
+
this._ended = true;
|
|
111
|
+
this.endTime = Date.now();
|
|
112
|
+
this.durationMs = calcElapsedMs(this._startHrTime);
|
|
113
|
+
|
|
114
|
+
const hasError = arguments.length > 0 && err !== null && err !== undefined;
|
|
115
|
+
|
|
116
|
+
if (hasError) {
|
|
117
|
+
this.status = OperationStatus.ERROR;
|
|
118
|
+
this.error = serializeError(err);
|
|
119
|
+
} else if (this.status !== OperationStatus.ERROR) {
|
|
120
|
+
this.status = OperationStatus.SUCCESS;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
if (this._store) {
|
|
124
|
+
const eventType = this.status === OperationStatus.ERROR ? EventTypes.ERROR : EventTypes.SUCCESS;
|
|
125
|
+
const endEvent = new TraceEvent({
|
|
126
|
+
traceId: this.traceId,
|
|
127
|
+
operationId: this.id,
|
|
128
|
+
parentOperationId: this.parentId,
|
|
129
|
+
type: eventType,
|
|
130
|
+
name: this.name,
|
|
131
|
+
timestamp: this.endTime,
|
|
132
|
+
durationMs: this.durationMs,
|
|
133
|
+
depth: this.depth,
|
|
134
|
+
metadata: Object.keys(this.metadata).length > 0 ? this.metadata : undefined,
|
|
135
|
+
error: this.error
|
|
136
|
+
});
|
|
137
|
+
this._store.addEvent(endEvent);
|
|
138
|
+
this._store.addOperation(this);
|
|
139
|
+
|
|
140
|
+
// Check for slow operation threshold
|
|
141
|
+
if (this._tracer && this._tracer.options && this._tracer.options.autoWarnSlowOperations) {
|
|
142
|
+
const threshold = this._tracer.options.slowOperationThresholdMs || 100;
|
|
143
|
+
if (this.durationMs >= threshold) {
|
|
144
|
+
const warnEvent = new TraceEvent({
|
|
145
|
+
traceId: this.traceId,
|
|
146
|
+
operationId: this.id,
|
|
147
|
+
parentOperationId: this.parentId,
|
|
148
|
+
type: EventTypes.WARNING,
|
|
149
|
+
name: `Slow operation detected: ${this.name} (${this.durationMs}ms >= ${threshold}ms)`,
|
|
150
|
+
timestamp: this.endTime,
|
|
151
|
+
durationMs: this.durationMs,
|
|
152
|
+
depth: this.depth,
|
|
153
|
+
metadata: { thresholdMs: threshold, actualMs: this.durationMs }
|
|
154
|
+
});
|
|
155
|
+
this._store.addEvent(warnEvent);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
return this;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Marks the operation as failed with an error and ends it.
|
|
165
|
+
* Works for any thrown value including primitives, null, or undefined.
|
|
166
|
+
* @param {unknown} err
|
|
167
|
+
* @returns {Operation} this
|
|
168
|
+
*/
|
|
169
|
+
fail(err) {
|
|
170
|
+
if (this._ended) {
|
|
171
|
+
return this;
|
|
172
|
+
}
|
|
173
|
+
this.status = OperationStatus.ERROR;
|
|
174
|
+
this.error = serializeError(err);
|
|
175
|
+
return this.end(err);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
toJSON() {
|
|
179
|
+
return {
|
|
180
|
+
id: this.id,
|
|
181
|
+
traceId: this.traceId,
|
|
182
|
+
parentId: this.parentId,
|
|
183
|
+
name: this.name,
|
|
184
|
+
depth: this.depth,
|
|
185
|
+
startTime: this.startTime,
|
|
186
|
+
endTime: this.endTime,
|
|
187
|
+
durationMs: this.durationMs,
|
|
188
|
+
status: this.status,
|
|
189
|
+
children: [...this.children],
|
|
190
|
+
...(this.error ? { error: this.error } : {}),
|
|
191
|
+
...(Object.keys(this.metadata).length > 0 ? { metadata: this.metadata } : {})
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
module.exports = {
|
|
197
|
+
Operation,
|
|
198
|
+
OperationStatus
|
|
199
|
+
};
|