@csaimonitor/sdk 0.1.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/CHANGELOG.md +34 -0
- package/LICENSE +22 -0
- package/README.md +315 -0
- package/dist/async-client.d.ts +143 -0
- package/dist/async-client.d.ts.map +1 -0
- package/dist/async-client.js +356 -0
- package/dist/async-client.js.map +1 -0
- package/dist/batcher.d.ts +50 -0
- package/dist/batcher.d.ts.map +1 -0
- package/dist/batcher.js +203 -0
- package/dist/batcher.js.map +1 -0
- package/dist/client.d.ts +178 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +248 -0
- package/dist/client.js.map +1 -0
- package/dist/config.d.ts +72 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/config.js +115 -0
- package/dist/config.js.map +1 -0
- package/dist/decorators.d.ts +23 -0
- package/dist/decorators.d.ts.map +1 -0
- package/dist/decorators.js +203 -0
- package/dist/decorators.js.map +1 -0
- package/dist/exceptions.d.ts +57 -0
- package/dist/exceptions.d.ts.map +1 -0
- package/dist/exceptions.js +99 -0
- package/dist/exceptions.js.map +1 -0
- package/dist/index.d.ts +49 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +69 -0
- package/dist/index.js.map +1 -0
- package/dist/models.d.ts +59 -0
- package/dist/models.d.ts.map +1 -0
- package/dist/models.js +84 -0
- package/dist/models.js.map +1 -0
- package/dist/utils.d.ts +53 -0
- package/dist/utils.d.ts.map +1 -0
- package/dist/utils.js +176 -0
- package/dist/utils.js.map +1 -0
- package/package.json +52 -0
|
@@ -0,0 +1,356 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Asynchronous client for CSMonitor SDK.
|
|
4
|
+
*
|
|
5
|
+
* This module provides the AsyncCSMonitor class for async/await tracking.
|
|
6
|
+
*/
|
|
7
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
8
|
+
exports.AsyncCSMonitor = exports.AsyncTrackedEvent = void 0;
|
|
9
|
+
const config_1 = require("./config");
|
|
10
|
+
const models_1 = require("./models");
|
|
11
|
+
const decorators_1 = require("./decorators");
|
|
12
|
+
const utils_1 = require("./utils");
|
|
13
|
+
const exceptions_1 = require("./exceptions");
|
|
14
|
+
/**
|
|
15
|
+
* Async context manager for tracking events.
|
|
16
|
+
*/
|
|
17
|
+
class AsyncTrackedEvent {
|
|
18
|
+
constructor(monitor, eventType, inputData) {
|
|
19
|
+
this.metadata = {};
|
|
20
|
+
this.status = 'success';
|
|
21
|
+
this.monitor = monitor;
|
|
22
|
+
this.eventType = eventType;
|
|
23
|
+
this.inputData = inputData;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Set output data for the event.
|
|
27
|
+
*/
|
|
28
|
+
setOutput(outputData) {
|
|
29
|
+
this.outputData = (0, utils_1.safeSerialize)(outputData);
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Set metadata fields.
|
|
33
|
+
*/
|
|
34
|
+
setMetadata(metadata) {
|
|
35
|
+
this.metadata = { ...this.metadata, ...metadata };
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Set cost in USD.
|
|
39
|
+
*/
|
|
40
|
+
setCost(costUsd) {
|
|
41
|
+
this.costUsd = costUsd;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Set event status.
|
|
45
|
+
*/
|
|
46
|
+
setStatus(status) {
|
|
47
|
+
this.status = status;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Set error message and status.
|
|
51
|
+
*/
|
|
52
|
+
setError(errorMessage) {
|
|
53
|
+
this.status = 'failure';
|
|
54
|
+
this.errorMessage = errorMessage;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Enter async context manager.
|
|
58
|
+
*/
|
|
59
|
+
async start() {
|
|
60
|
+
this.startTime = Date.now();
|
|
61
|
+
this.startTimestamp = (0, utils_1.getIsoTimestamp)();
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Exit async context manager and log event.
|
|
65
|
+
*/
|
|
66
|
+
async finish(error) {
|
|
67
|
+
// Calculate latency
|
|
68
|
+
let latencyMs;
|
|
69
|
+
if (this.startTime) {
|
|
70
|
+
latencyMs = Date.now() - this.startTime;
|
|
71
|
+
}
|
|
72
|
+
// Handle exception
|
|
73
|
+
if (error) {
|
|
74
|
+
this.status = 'failure';
|
|
75
|
+
this.errorMessage = (0, utils_1.formatErrorMessage)(error);
|
|
76
|
+
}
|
|
77
|
+
// Apply redaction
|
|
78
|
+
let finalInputData = this.inputData;
|
|
79
|
+
let finalOutputData = this.outputData;
|
|
80
|
+
if (this.monitor.config.redactKeys.length > 0) {
|
|
81
|
+
if (finalInputData) {
|
|
82
|
+
finalInputData = (0, utils_1.redactSensitiveData)(finalInputData, this.monitor.config.redactKeys);
|
|
83
|
+
}
|
|
84
|
+
if (finalOutputData) {
|
|
85
|
+
finalOutputData = (0, utils_1.redactSensitiveData)(finalOutputData, this.monitor.config.redactKeys);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
// Create event
|
|
89
|
+
const event = models_1.Event.create(this.monitor.config.agentId, this.eventType, finalInputData, finalOutputData, Object.keys(this.metadata).length > 0 ? this.metadata : undefined, this.costUsd, latencyMs, this.status, this.errorMessage, this.startTimestamp);
|
|
90
|
+
// Log event
|
|
91
|
+
await this.monitor._addEventAsync(event);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
exports.AsyncTrackedEvent = AsyncTrackedEvent;
|
|
95
|
+
/**
|
|
96
|
+
* Asynchronous client for tracking agent events.
|
|
97
|
+
*
|
|
98
|
+
* This class provides async/await support for event tracking.
|
|
99
|
+
*
|
|
100
|
+
* @example
|
|
101
|
+
* ```typescript
|
|
102
|
+
* const monitor = new AsyncCSMonitor({
|
|
103
|
+
* apiKey: 'your_key',
|
|
104
|
+
* agentId: 'my_agent',
|
|
105
|
+
* apiUrl: 'http://localhost:3002/api/v1'
|
|
106
|
+
* });
|
|
107
|
+
*
|
|
108
|
+
* @monitor.track()
|
|
109
|
+
* async function myAsyncFunction(x: number): Promise<number> {
|
|
110
|
+
* await someAsyncOperation();
|
|
111
|
+
* return x * 2;
|
|
112
|
+
* }
|
|
113
|
+
*
|
|
114
|
+
* const result = await myAsyncFunction(5);
|
|
115
|
+
* await monitor.flush();
|
|
116
|
+
* await monitor.stop();
|
|
117
|
+
* ```
|
|
118
|
+
*/
|
|
119
|
+
class AsyncCSMonitor {
|
|
120
|
+
constructor(options) {
|
|
121
|
+
this.eventQueue = [];
|
|
122
|
+
this.started = false;
|
|
123
|
+
// Create config
|
|
124
|
+
this.config = new config_1.CSMonitorConfig(options);
|
|
125
|
+
this.logger = (0, utils_1.setupLogger)(this.config.debug);
|
|
126
|
+
this.onError = options.onError;
|
|
127
|
+
this.logger.info(`AsyncCSMonitor initialized for agent '${this.config.agentId}'`);
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Start the background flushing task.
|
|
131
|
+
*/
|
|
132
|
+
async start() {
|
|
133
|
+
if (this.started) {
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
this.started = true;
|
|
137
|
+
this.flushTimer = setInterval(() => {
|
|
138
|
+
this.flush().catch((error) => {
|
|
139
|
+
this.logger.error(`Error in background flush: ${error}`);
|
|
140
|
+
if (this.onError) {
|
|
141
|
+
this.onError(error);
|
|
142
|
+
}
|
|
143
|
+
});
|
|
144
|
+
}, this.config.flushInterval * 1000);
|
|
145
|
+
this.logger.debug('AsyncCSMonitor background task started');
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Stop the background task and flush remaining events.
|
|
149
|
+
*/
|
|
150
|
+
async stop() {
|
|
151
|
+
if (!this.started) {
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
this.logger.debug('Stopping AsyncCSMonitor background task');
|
|
155
|
+
if (this.flushTimer) {
|
|
156
|
+
clearInterval(this.flushTimer);
|
|
157
|
+
this.flushTimer = undefined;
|
|
158
|
+
}
|
|
159
|
+
this.started = false;
|
|
160
|
+
// Flush remaining events
|
|
161
|
+
await this.flush();
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Decorator to automatically track async function execution.
|
|
165
|
+
* @param options - Tracking options
|
|
166
|
+
* @returns Decorator function
|
|
167
|
+
*/
|
|
168
|
+
track(options) {
|
|
169
|
+
const decoratorFactory = (0, decorators_1.createTrackDecorator)(this);
|
|
170
|
+
return decoratorFactory(options);
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Create an async context manager for tracking an event.
|
|
174
|
+
* @param eventType - Type of event
|
|
175
|
+
* @param inputData - Initial input data
|
|
176
|
+
* @returns AsyncTrackedEvent context manager
|
|
177
|
+
*/
|
|
178
|
+
trackEvent(eventType, inputData) {
|
|
179
|
+
const event = new AsyncTrackedEvent(this, eventType, inputData);
|
|
180
|
+
event.start().catch((error) => {
|
|
181
|
+
this.logger.error(`Error starting tracked event: ${error}`);
|
|
182
|
+
});
|
|
183
|
+
return event;
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Manually log an event (async).
|
|
187
|
+
* @param options - Event data
|
|
188
|
+
*/
|
|
189
|
+
async logEvent(options) {
|
|
190
|
+
// Apply redaction
|
|
191
|
+
let finalInputData = options.inputData;
|
|
192
|
+
let finalOutputData = options.outputData;
|
|
193
|
+
if (this.config.redactKeys.length > 0) {
|
|
194
|
+
if (finalInputData) {
|
|
195
|
+
finalInputData = (0, utils_1.redactSensitiveData)(finalInputData, this.config.redactKeys);
|
|
196
|
+
}
|
|
197
|
+
if (finalOutputData) {
|
|
198
|
+
finalOutputData = (0, utils_1.redactSensitiveData)(finalOutputData, this.config.redactKeys);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
// Create event
|
|
202
|
+
const event = models_1.Event.create(this.config.agentId, options.eventType, finalInputData, finalOutputData, options.metadata, options.costUsd, options.latencyMs, options.status || 'success', options.errorMessage, options.timestamp);
|
|
203
|
+
// Add to queue
|
|
204
|
+
await this._addEventAsync(event);
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Add event to async queue (internal method).
|
|
208
|
+
*/
|
|
209
|
+
async _addEventAsync(event) {
|
|
210
|
+
if (!this.config.enabled) {
|
|
211
|
+
this.logger.debug('Tracking disabled, skipping event');
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
// Ensure monitor is started
|
|
215
|
+
if (!this.started) {
|
|
216
|
+
await this.start();
|
|
217
|
+
}
|
|
218
|
+
this.eventQueue.push(event);
|
|
219
|
+
this.logger.debug(`Event added to async queue: ${event.event_type}`);
|
|
220
|
+
// Check if we should flush immediately
|
|
221
|
+
if (this.eventQueue.length >= this.config.batchSize) {
|
|
222
|
+
this.logger.debug('Batch size reached, triggering immediate flush');
|
|
223
|
+
await this.flush();
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Flush all pending events immediately (async).
|
|
228
|
+
*/
|
|
229
|
+
async flush() {
|
|
230
|
+
if (this.eventQueue.length === 0) {
|
|
231
|
+
this.logger.debug('Async queue is empty, nothing to flush');
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
// Take all events from the queue
|
|
235
|
+
const events = this.eventQueue.splice(0, this.eventQueue.length);
|
|
236
|
+
if (events.length > 0) {
|
|
237
|
+
this.logger.debug(`Flushing ${events.length} events (async)`);
|
|
238
|
+
await this.sendBatch(events);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* Send a batch of events to the API with retry logic (async).
|
|
243
|
+
*/
|
|
244
|
+
async sendBatch(events) {
|
|
245
|
+
if (events.length === 0) {
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
// Convert events to API format
|
|
249
|
+
const payload = {
|
|
250
|
+
events: events.map((event) => event.toDict()),
|
|
251
|
+
};
|
|
252
|
+
// Retry with exponential backoff
|
|
253
|
+
let retryCount = 0;
|
|
254
|
+
const maxRetries = this.config.retryAttempts;
|
|
255
|
+
let backoffSeconds = 1;
|
|
256
|
+
while (retryCount <= maxRetries) {
|
|
257
|
+
try {
|
|
258
|
+
const controller = new AbortController();
|
|
259
|
+
const timeoutId = setTimeout(() => controller.abort(), this.config.timeout * 1000);
|
|
260
|
+
const response = await fetch(this.config.batchUrl, {
|
|
261
|
+
method: 'POST',
|
|
262
|
+
headers: this.config.headers,
|
|
263
|
+
body: JSON.stringify(payload),
|
|
264
|
+
signal: controller.signal,
|
|
265
|
+
});
|
|
266
|
+
clearTimeout(timeoutId);
|
|
267
|
+
if (response.status === 200 || response.status === 201) {
|
|
268
|
+
this.logger.info(`Successfully sent batch of ${events.length} events (async)`);
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
else if (response.status === 401 || response.status === 403) {
|
|
272
|
+
const text = await response.text();
|
|
273
|
+
const error = new exceptions_1.AuthenticationError(`Authentication failed: ${text}`, response.status);
|
|
274
|
+
this.logger.error(`Authentication error (async): ${error}`);
|
|
275
|
+
if (this.onError) {
|
|
276
|
+
this.onError(error);
|
|
277
|
+
}
|
|
278
|
+
return; // Don't retry auth errors
|
|
279
|
+
}
|
|
280
|
+
else {
|
|
281
|
+
const text = await response.text();
|
|
282
|
+
const error = new exceptions_1.APIError(`API request failed: ${text}`, response.status, text);
|
|
283
|
+
this.logger.warn(`API error (async, attempt ${retryCount + 1}/${maxRetries + 1}): ${error}`);
|
|
284
|
+
if (retryCount < maxRetries) {
|
|
285
|
+
retryCount++;
|
|
286
|
+
await this.sleep(backoffSeconds);
|
|
287
|
+
backoffSeconds *= 2;
|
|
288
|
+
}
|
|
289
|
+
else {
|
|
290
|
+
this.logger.error(`Failed to send batch (async) after ${maxRetries + 1} attempts`);
|
|
291
|
+
if (this.onError) {
|
|
292
|
+
this.onError(error);
|
|
293
|
+
}
|
|
294
|
+
return;
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
catch (error) {
|
|
299
|
+
if (error instanceof Error && error.name === 'AbortError') {
|
|
300
|
+
const networkError = new exceptions_1.NetworkError(`Request timeout: ${error.message}`);
|
|
301
|
+
this.logger.warn(`Timeout error (async, attempt ${retryCount + 1}/${maxRetries + 1}): ${networkError}`);
|
|
302
|
+
if (retryCount < maxRetries) {
|
|
303
|
+
retryCount++;
|
|
304
|
+
await this.sleep(backoffSeconds);
|
|
305
|
+
backoffSeconds *= 2;
|
|
306
|
+
}
|
|
307
|
+
else {
|
|
308
|
+
this.logger.error(`Failed to send batch (async) after ${maxRetries + 1} attempts (timeout)`);
|
|
309
|
+
if (this.onError) {
|
|
310
|
+
this.onError(networkError);
|
|
311
|
+
}
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
else if (error instanceof Error) {
|
|
316
|
+
const networkError = new exceptions_1.NetworkError(`Network error: ${error.message}`);
|
|
317
|
+
this.logger.warn(`Network error (async, attempt ${retryCount + 1}/${maxRetries + 1}): ${networkError}`);
|
|
318
|
+
if (retryCount < maxRetries) {
|
|
319
|
+
retryCount++;
|
|
320
|
+
await this.sleep(backoffSeconds);
|
|
321
|
+
backoffSeconds *= 2;
|
|
322
|
+
}
|
|
323
|
+
else {
|
|
324
|
+
this.logger.error(`Failed to send batch (async) after ${maxRetries + 1} attempts (network error)`);
|
|
325
|
+
if (this.onError) {
|
|
326
|
+
this.onError(networkError);
|
|
327
|
+
}
|
|
328
|
+
return;
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
else {
|
|
332
|
+
const apiError = new exceptions_1.APIError(`Unexpected error: ${String(error)}`);
|
|
333
|
+
this.logger.error(`Unexpected error sending batch (async): ${apiError}`);
|
|
334
|
+
if (this.onError) {
|
|
335
|
+
this.onError(apiError);
|
|
336
|
+
}
|
|
337
|
+
return; // Don't retry unexpected errors
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
/**
|
|
343
|
+
* Sleep for a given number of seconds.
|
|
344
|
+
*/
|
|
345
|
+
sleep(seconds) {
|
|
346
|
+
return new Promise((resolve) => setTimeout(resolve, seconds * 1000));
|
|
347
|
+
}
|
|
348
|
+
/**
|
|
349
|
+
* String representation.
|
|
350
|
+
*/
|
|
351
|
+
toString() {
|
|
352
|
+
return `AsyncCSMonitor(agentId='${this.config.agentId}', enabled=${this.config.enabled})`;
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
exports.AsyncCSMonitor = AsyncCSMonitor;
|
|
356
|
+
//# sourceMappingURL=async-client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"async-client.js","sourceRoot":"","sources":["../src/async-client.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;;AAEH,qCAAmE;AACnE,qCAAiC;AACjC,6CAAoD;AACpD,mCAMiB;AACjB,6CAA2E;AAE3E;;GAEG;AACH,MAAa,iBAAiB;IAY5B,YAAY,OAAuB,EAAE,SAAiB,EAAE,SAAmC;QAPnF,aAAQ,GAA4B,EAAE,CAAC;QAEvC,WAAM,GAAW,SAAS,CAAC;QAMjC,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;IAC7B,CAAC;IAED;;OAEG;IACH,SAAS,CAAC,UAAmB;QAC3B,IAAI,CAAC,UAAU,GAAG,IAAA,qBAAa,EAAC,UAAU,CAAC,CAAC;IAC9C,CAAC;IAED;;OAEG;IACH,WAAW,CAAC,QAAiC;QAC3C,IAAI,CAAC,QAAQ,GAAG,EAAE,GAAG,IAAI,CAAC,QAAQ,EAAE,GAAG,QAAQ,EAAE,CAAC;IACpD,CAAC;IAED;;OAEG;IACH,OAAO,CAAC,OAAe;QACrB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;IAED;;OAEG;IACH,SAAS,CAAC,MAAc;QACtB,IAAI,CAAC,MAAM,GA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CAAC,2CAA2C,QAAQ,EAAE,CAAC,CAAC;oBACzE,IAAI,IAAI,CAAC,OAAO,EAAE,CAAC;wBACjB,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;oBACzB,CAAC;oBACD,OAAO,CAAC,gCAAgC;gBAC1C,CAAC;YACH,CAAC;QACH,CAAC;IACH,CAAC;IAED;;OAEG;IACK,KAAK,CAAC,OAAe;QAC3B,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CAAC,CAAC,CAAC;IACvE,CAAC;IAED;;OAEG;IACH,QAAQ;QACN,OAAO,2BAA2B,IAAI,CAAC,MAAM,CAAC,OAAO,cAAc,IAAI,CAAC,MAAM,CAAC,OAAO,GAAG,CAAC;IAC5F,CAAC;CACF;AA/RD,wCA+RC"}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Event batching and background flushing for CSMonitor SDK.
|
|
3
|
+
*
|
|
4
|
+
* This module handles automatic batching of events and background flushing
|
|
5
|
+
* to the API using a background timer.
|
|
6
|
+
*/
|
|
7
|
+
import { Event } from './models';
|
|
8
|
+
import { CSMonitorConfig } from './config';
|
|
9
|
+
/**
|
|
10
|
+
* Thread-safe queue for batching and sending events.
|
|
11
|
+
* This class manages a background timer that automatically flushes events
|
|
12
|
+
* to the API when the batch size is reached or after a time interval.
|
|
13
|
+
*/
|
|
14
|
+
export declare class BatchQueue {
|
|
15
|
+
private readonly config;
|
|
16
|
+
private readonly onError?;
|
|
17
|
+
private readonly logger;
|
|
18
|
+
private readonly queue;
|
|
19
|
+
private flushTimer?;
|
|
20
|
+
private started;
|
|
21
|
+
constructor(config: CSMonitorConfig, onError?: (error: Error) => void);
|
|
22
|
+
/**
|
|
23
|
+
* Start the background flushing timer.
|
|
24
|
+
*/
|
|
25
|
+
start(): void;
|
|
26
|
+
/**
|
|
27
|
+
* Stop the background timer and flush remaining events.
|
|
28
|
+
*/
|
|
29
|
+
stop(): void;
|
|
30
|
+
/**
|
|
31
|
+
* Add an event to the queue.
|
|
32
|
+
* @param event - Event to add
|
|
33
|
+
*/
|
|
34
|
+
addEvent(event: Event): void;
|
|
35
|
+
/**
|
|
36
|
+
* Flush all pending events immediately (blocking).
|
|
37
|
+
*/
|
|
38
|
+
flush(): void;
|
|
39
|
+
/**
|
|
40
|
+
* Send a batch of events to the API with retry logic.
|
|
41
|
+
* @param events - List of events to send
|
|
42
|
+
*/
|
|
43
|
+
private sendBatch;
|
|
44
|
+
/**
|
|
45
|
+
* Sleep for a given number of seconds.
|
|
46
|
+
* @param seconds - Number of seconds to sleep
|
|
47
|
+
*/
|
|
48
|
+
private sleep;
|
|
49
|
+
}
|
|
50
|
+
//# sourceMappingURL=batcher.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"batcher.d.ts","sourceRoot":"","sources":["../src/batcher.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,KAAK,EAAE,MAAM,UAAU,CAAC;AACjC,OAAO,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AAI3C;;;;GAIG;AACH,qBAAa,UAAU;IACrB,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAkB;IACzC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAyB;IAClD,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAiC;IACxD,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAe;IACrC,OAAO,CAAC,UAAU,CAAC,CAAiB;IACpC,OAAO,CAAC,OAAO,CAAkB;gBAErB,MAAM,EAAE,eAAe,EAAE,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI;IAMrE;;OAEG;IACH,KAAK,IAAI,IAAI;IAab;;OAEG;IACH,IAAI,IAAI,IAAI;IAkBZ;;;OAGG;IACH,QAAQ,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI;IAgB5B;;OAEG;IACH,KAAK,IAAI,IAAI;IAoBb;;;OAGG;YACW,SAAS;IAsHvB;;;OAGG;IACH,OAAO,CAAC,KAAK;CAGd"}
|
package/dist/batcher.js
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Event batching and background flushing for CSMonitor SDK.
|
|
4
|
+
*
|
|
5
|
+
* This module handles automatic batching of events and background flushing
|
|
6
|
+
* to the API using a background timer.
|
|
7
|
+
*/
|
|
8
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
9
|
+
exports.BatchQueue = void 0;
|
|
10
|
+
const exceptions_1 = require("./exceptions");
|
|
11
|
+
const utils_1 = require("./utils");
|
|
12
|
+
/**
|
|
13
|
+
* Thread-safe queue for batching and sending events.
|
|
14
|
+
* This class manages a background timer that automatically flushes events
|
|
15
|
+
* to the API when the batch size is reached or after a time interval.
|
|
16
|
+
*/
|
|
17
|
+
class BatchQueue {
|
|
18
|
+
constructor(config, onError) {
|
|
19
|
+
this.queue = [];
|
|
20
|
+
this.started = false;
|
|
21
|
+
this.config = config;
|
|
22
|
+
this.onError = onError;
|
|
23
|
+
this.logger = (0, utils_1.setupLogger)(config.debug);
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Start the background flushing timer.
|
|
27
|
+
*/
|
|
28
|
+
start() {
|
|
29
|
+
if (this.started) {
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
this.started = true;
|
|
33
|
+
this.flushTimer = setInterval(() => {
|
|
34
|
+
this.flush();
|
|
35
|
+
}, this.config.flushInterval * 1000);
|
|
36
|
+
this.logger.debug('BatchQueue background timer started');
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Stop the background timer and flush remaining events.
|
|
40
|
+
*/
|
|
41
|
+
stop() {
|
|
42
|
+
if (!this.started) {
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
this.logger.debug('Stopping BatchQueue background timer');
|
|
46
|
+
if (this.flushTimer) {
|
|
47
|
+
clearInterval(this.flushTimer);
|
|
48
|
+
this.flushTimer = undefined;
|
|
49
|
+
}
|
|
50
|
+
this.started = false;
|
|
51
|
+
// Flush any remaining events
|
|
52
|
+
this.flush();
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Add an event to the queue.
|
|
56
|
+
* @param event - Event to add
|
|
57
|
+
*/
|
|
58
|
+
addEvent(event) {
|
|
59
|
+
if (!this.config.enabled) {
|
|
60
|
+
this.logger.debug('Tracking disabled, skipping event');
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
this.queue.push(event);
|
|
64
|
+
this.logger.debug(`Event added to queue: ${event.event_type}`);
|
|
65
|
+
// Check if we should flush immediately
|
|
66
|
+
if (this.queue.length >= this.config.batchSize) {
|
|
67
|
+
this.logger.debug('Batch size reached, triggering immediate flush');
|
|
68
|
+
this.flush();
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Flush all pending events immediately (blocking).
|
|
73
|
+
*/
|
|
74
|
+
flush() {
|
|
75
|
+
if (this.queue.length === 0) {
|
|
76
|
+
this.logger.debug('Queue is empty, nothing to flush');
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
// Take all events from the queue
|
|
80
|
+
const events = this.queue.splice(0, this.queue.length);
|
|
81
|
+
if (events.length > 0) {
|
|
82
|
+
this.logger.debug(`Flushing ${events.length} events`);
|
|
83
|
+
this.sendBatch(events).catch((error) => {
|
|
84
|
+
this.logger.error(`Error flushing events: ${error}`);
|
|
85
|
+
if (this.onError) {
|
|
86
|
+
this.onError(error);
|
|
87
|
+
}
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Send a batch of events to the API with retry logic.
|
|
93
|
+
* @param events - List of events to send
|
|
94
|
+
*/
|
|
95
|
+
async sendBatch(events) {
|
|
96
|
+
if (events.length === 0) {
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
// Convert events to API format
|
|
100
|
+
const payload = {
|
|
101
|
+
events: events.map((event) => event.toDict()),
|
|
102
|
+
};
|
|
103
|
+
// Retry with exponential backoff
|
|
104
|
+
let retryCount = 0;
|
|
105
|
+
const maxRetries = this.config.retryAttempts;
|
|
106
|
+
let backoffSeconds = 1;
|
|
107
|
+
while (retryCount <= maxRetries) {
|
|
108
|
+
try {
|
|
109
|
+
// Use native fetch (Node.js 18+) or fallback
|
|
110
|
+
const controller = new AbortController();
|
|
111
|
+
const timeoutId = setTimeout(() => controller.abort(), this.config.timeout * 1000);
|
|
112
|
+
const response = await fetch(this.config.batchUrl, {
|
|
113
|
+
method: 'POST',
|
|
114
|
+
headers: this.config.headers,
|
|
115
|
+
body: JSON.stringify(payload),
|
|
116
|
+
signal: controller.signal,
|
|
117
|
+
});
|
|
118
|
+
clearTimeout(timeoutId);
|
|
119
|
+
if (response.status === 200 || response.status === 201) {
|
|
120
|
+
this.logger.info(`Successfully sent batch of ${events.length} events`);
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
else if (response.status === 401 || response.status === 403) {
|
|
124
|
+
const text = await response.text();
|
|
125
|
+
const error = new exceptions_1.AuthenticationError(`Authentication failed: ${text}`, response.status);
|
|
126
|
+
this.logger.error(`Authentication error: ${error}`);
|
|
127
|
+
if (this.onError) {
|
|
128
|
+
this.onError(error);
|
|
129
|
+
}
|
|
130
|
+
return; // Don't retry auth errors
|
|
131
|
+
}
|
|
132
|
+
else {
|
|
133
|
+
const text = await response.text();
|
|
134
|
+
const error = new exceptions_1.APIError(`API request failed: ${text}`, response.status, text);
|
|
135
|
+
this.logger.warn(`API error (attempt ${retryCount + 1}/${maxRetries + 1}): ${error}`);
|
|
136
|
+
if (retryCount < maxRetries) {
|
|
137
|
+
retryCount++;
|
|
138
|
+
await this.sleep(backoffSeconds);
|
|
139
|
+
backoffSeconds *= 2; // Exponential backoff
|
|
140
|
+
}
|
|
141
|
+
else {
|
|
142
|
+
this.logger.error(`Failed to send batch after ${maxRetries + 1} attempts`);
|
|
143
|
+
if (this.onError) {
|
|
144
|
+
this.onError(error);
|
|
145
|
+
}
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
catch (error) {
|
|
151
|
+
if (error instanceof Error && error.name === 'AbortError') {
|
|
152
|
+
const networkError = new exceptions_1.NetworkError(`Request timeout: ${error.message}`);
|
|
153
|
+
this.logger.warn(`Timeout error (attempt ${retryCount + 1}/${maxRetries + 1}): ${networkError}`);
|
|
154
|
+
if (retryCount < maxRetries) {
|
|
155
|
+
retryCount++;
|
|
156
|
+
await this.sleep(backoffSeconds);
|
|
157
|
+
backoffSeconds *= 2;
|
|
158
|
+
}
|
|
159
|
+
else {
|
|
160
|
+
this.logger.error(`Failed to send batch after ${maxRetries + 1} attempts (timeout)`);
|
|
161
|
+
if (this.onError) {
|
|
162
|
+
this.onError(networkError);
|
|
163
|
+
}
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
else if (error instanceof Error) {
|
|
168
|
+
const networkError = new exceptions_1.NetworkError(`Network error: ${error.message}`);
|
|
169
|
+
this.logger.warn(`Network error (attempt ${retryCount + 1}/${maxRetries + 1}): ${networkError}`);
|
|
170
|
+
if (retryCount < maxRetries) {
|
|
171
|
+
retryCount++;
|
|
172
|
+
await this.sleep(backoffSeconds);
|
|
173
|
+
backoffSeconds *= 2;
|
|
174
|
+
}
|
|
175
|
+
else {
|
|
176
|
+
this.logger.error(`Failed to send batch after ${maxRetries + 1} attempts (network error)`);
|
|
177
|
+
if (this.onError) {
|
|
178
|
+
this.onError(networkError);
|
|
179
|
+
}
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
else {
|
|
184
|
+
const apiError = new exceptions_1.APIError(`Unexpected error: ${String(error)}`);
|
|
185
|
+
this.logger.error(`Unexpected error sending batch: ${apiError}`);
|
|
186
|
+
if (this.onError) {
|
|
187
|
+
this.onError(apiError);
|
|
188
|
+
}
|
|
189
|
+
return; // Don't retry unexpected errors
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* Sleep for a given number of seconds.
|
|
196
|
+
* @param seconds - Number of seconds to sleep
|
|
197
|
+
*/
|
|
198
|
+
sleep(seconds) {
|
|
199
|
+
return new Promise((resolve) => setTimeout(resolve, seconds * 1000));
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
exports.BatchQueue = BatchQueue;
|
|
203
|
+
//# sourceMappingURL=batcher.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"batcher.js","sourceRoot":"","sources":["../src/batcher.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;AAIH,6CAA2E;AAC3E,mCAAsC;AAEtC;;;;GAIG;AACH,MAAa,UAAU;IAQrB,YAAY,MAAuB,EAAE,OAAgC;QAJpD,UAAK,GAAY,EAAE,CAAC;QAE7B,YAAO,GAAY,KAAK,CAAC;QAG/B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,MAAM,GAAG,IAAA,mBAAW,EAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IAC1C,CAAC;IAED;;OAEG;IACH,KAAK;QACH,IAAI,IAAI,CAAC,OAAO,EAAE,CAAC;YACjB,OAAO;QACT,CAAC;QAED,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;QACpB,IAAI,CAAC,UAAU,GAAG,WAAW,CAAC,GAAG,EAAE;YACjC,IAAI,CAAC,KAAK,EAAE,CAAC;QACf,CAAC,EAAE,IAAI,CAAC,MAAM,CAAC,aAAa,GAAG,IAAI,CAAC,CAAC;QAErC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,qCAAqC,CAAC,CAAC;IAC3D,CAAC;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