@trafficwar/node 1.0.0 → 2.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/README.md +97 -46
- package/dist/index.cjs +413 -130
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +26 -12
- package/dist/index.d.ts +26 -12
- package/dist/index.js +412 -131
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var crypto = require('crypto');
|
|
4
3
|
var zlib = require('zlib');
|
|
5
4
|
var buffer = require('buffer');
|
|
5
|
+
var crypto = require('crypto');
|
|
6
6
|
|
|
7
7
|
// src/client.ts
|
|
8
8
|
|
|
@@ -110,9 +110,9 @@ function validationError(message, path, idempotencyKey, cause) {
|
|
|
110
110
|
cause
|
|
111
111
|
});
|
|
112
112
|
}
|
|
113
|
-
function
|
|
113
|
+
function snapshotJsonValue(value, path, ancestors, idempotencyKey) {
|
|
114
114
|
if (value === null || typeof value === "string" || typeof value === "boolean") {
|
|
115
|
-
return;
|
|
115
|
+
return value;
|
|
116
116
|
}
|
|
117
117
|
if (typeof value === "number") {
|
|
118
118
|
if (!Number.isFinite(value)) {
|
|
@@ -122,7 +122,7 @@ function assertJsonValue(value, path, ancestors, idempotencyKey) {
|
|
|
122
122
|
idempotencyKey
|
|
123
123
|
);
|
|
124
124
|
}
|
|
125
|
-
return;
|
|
125
|
+
return value;
|
|
126
126
|
}
|
|
127
127
|
if (typeof value !== "object") {
|
|
128
128
|
throw validationError(
|
|
@@ -158,6 +158,7 @@ function assertJsonValue(value, path, ancestors, idempotencyKey) {
|
|
|
158
158
|
ancestors.add(value);
|
|
159
159
|
try {
|
|
160
160
|
if (Array.isArray(value)) {
|
|
161
|
+
const snapshot2 = [];
|
|
161
162
|
for (let index = 0; index < value.length; index += 1) {
|
|
162
163
|
if (!(index in value)) {
|
|
163
164
|
throw validationError(
|
|
@@ -166,18 +167,27 @@ function assertJsonValue(value, path, ancestors, idempotencyKey) {
|
|
|
166
167
|
idempotencyKey
|
|
167
168
|
);
|
|
168
169
|
}
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
170
|
+
snapshot2.push(
|
|
171
|
+
snapshotJsonValue(
|
|
172
|
+
value[index],
|
|
173
|
+
`${path}[${index}]`,
|
|
174
|
+
ancestors,
|
|
175
|
+
idempotencyKey
|
|
176
|
+
)
|
|
174
177
|
);
|
|
175
178
|
}
|
|
176
|
-
return;
|
|
179
|
+
return snapshot2;
|
|
177
180
|
}
|
|
181
|
+
const snapshot = /* @__PURE__ */ Object.create(null);
|
|
178
182
|
for (const [key, child] of Object.entries(value)) {
|
|
179
|
-
|
|
183
|
+
snapshot[key] = snapshotJsonValue(
|
|
184
|
+
child,
|
|
185
|
+
`${path}.${key}`,
|
|
186
|
+
ancestors,
|
|
187
|
+
idempotencyKey
|
|
188
|
+
);
|
|
180
189
|
}
|
|
190
|
+
return snapshot;
|
|
181
191
|
} finally {
|
|
182
192
|
ancestors.delete(value);
|
|
183
193
|
}
|
|
@@ -331,7 +341,12 @@ function normalizeEvent(input, path, idempotencyKey) {
|
|
|
331
341
|
);
|
|
332
342
|
}
|
|
333
343
|
try {
|
|
334
|
-
|
|
344
|
+
return snapshotJsonValue(
|
|
345
|
+
normalized,
|
|
346
|
+
path,
|
|
347
|
+
/* @__PURE__ */ new WeakSet(),
|
|
348
|
+
idempotencyKey
|
|
349
|
+
);
|
|
335
350
|
} catch (error) {
|
|
336
351
|
if (error instanceof TrafficWarValidationError) {
|
|
337
352
|
throw error;
|
|
@@ -343,33 +358,6 @@ function normalizeEvent(input, path, idempotencyKey) {
|
|
|
343
358
|
error
|
|
344
359
|
);
|
|
345
360
|
}
|
|
346
|
-
return normalized;
|
|
347
|
-
}
|
|
348
|
-
function assertUniqueEventIds(events, idempotencyKey) {
|
|
349
|
-
const seen = /* @__PURE__ */ new Set();
|
|
350
|
-
for (let index = 0; index < events.length; index += 1) {
|
|
351
|
-
const eventId = events[index]?.event_id;
|
|
352
|
-
if (typeof eventId !== "string") {
|
|
353
|
-
continue;
|
|
354
|
-
}
|
|
355
|
-
if (seen.has(eventId)) {
|
|
356
|
-
throw validationError(
|
|
357
|
-
`events[${index}].event_id duplicates another event_id in this batch`,
|
|
358
|
-
`events[${index}].event_id`,
|
|
359
|
-
idempotencyKey
|
|
360
|
-
);
|
|
361
|
-
}
|
|
362
|
-
seen.add(eventId);
|
|
363
|
-
}
|
|
364
|
-
}
|
|
365
|
-
function validateIdempotencyKey(value) {
|
|
366
|
-
if (typeof value !== "string" || value.length === 0 || value.length > 256 || !/^[\x21-\x7e]+$/.test(value)) {
|
|
367
|
-
throw new TrafficWarValidationError(
|
|
368
|
-
"idempotencyKey must contain 1-256 visible ASCII characters",
|
|
369
|
-
{ path: "options.idempotencyKey" }
|
|
370
|
-
);
|
|
371
|
-
}
|
|
372
|
-
return value;
|
|
373
361
|
}
|
|
374
362
|
function serializeJson(payload, idempotencyKey) {
|
|
375
363
|
let serialized;
|
|
@@ -389,15 +377,85 @@ function serializeJson(payload, idempotencyKey) {
|
|
|
389
377
|
}
|
|
390
378
|
return buffer.Buffer.from(serialized, "utf8");
|
|
391
379
|
}
|
|
380
|
+
var RANDOM_BITS = 74n;
|
|
381
|
+
var RANDOM_MASK = (1n << RANDOM_BITS) - 1n;
|
|
382
|
+
var MAX_TIMESTAMP = (1n << 48n) - 1n;
|
|
383
|
+
var STATE_KEY = /* @__PURE__ */ Symbol.for("@trafficwar/node.uuidv7-state");
|
|
384
|
+
var processState = globalThis;
|
|
385
|
+
var existingState = processState[STATE_KEY];
|
|
386
|
+
var state = existingState ?? {
|
|
387
|
+
lastTimestamp: -1n,
|
|
388
|
+
lastRandom: 0n
|
|
389
|
+
};
|
|
390
|
+
processState[STATE_KEY] = state;
|
|
391
|
+
function random74() {
|
|
392
|
+
const bytes = crypto.randomBytes(10);
|
|
393
|
+
let value = 0n;
|
|
394
|
+
for (const byte of bytes) {
|
|
395
|
+
value = value << 8n | BigInt(byte);
|
|
396
|
+
}
|
|
397
|
+
return value & RANDOM_MASK;
|
|
398
|
+
}
|
|
399
|
+
function nextFields() {
|
|
400
|
+
const now = BigInt(Date.now());
|
|
401
|
+
if (now < 0n || now > MAX_TIMESTAMP) {
|
|
402
|
+
throw new RangeError("Current time cannot be represented as UUIDv7");
|
|
403
|
+
}
|
|
404
|
+
if (now > state.lastTimestamp) {
|
|
405
|
+
state.lastTimestamp = now;
|
|
406
|
+
state.lastRandom = random74();
|
|
407
|
+
} else if (state.lastRandom < RANDOM_MASK) {
|
|
408
|
+
state.lastRandom += 1n;
|
|
409
|
+
} else {
|
|
410
|
+
if (state.lastTimestamp >= MAX_TIMESTAMP) {
|
|
411
|
+
throw new RangeError("UUIDv7 timestamp space exhausted");
|
|
412
|
+
}
|
|
413
|
+
state.lastTimestamp += 1n;
|
|
414
|
+
state.lastRandom = random74();
|
|
415
|
+
}
|
|
416
|
+
return {
|
|
417
|
+
timestamp: state.lastTimestamp,
|
|
418
|
+
random: state.lastRandom
|
|
419
|
+
};
|
|
420
|
+
}
|
|
421
|
+
function hex(bytes) {
|
|
422
|
+
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join(
|
|
423
|
+
""
|
|
424
|
+
);
|
|
425
|
+
}
|
|
426
|
+
function uuidv7() {
|
|
427
|
+
const { timestamp, random } = nextFields();
|
|
428
|
+
const bytes = new Uint8Array(16);
|
|
429
|
+
let timestampBits = timestamp;
|
|
430
|
+
for (let index = 5; index >= 0; index -= 1) {
|
|
431
|
+
bytes[index] = Number(timestampBits & 0xffn);
|
|
432
|
+
timestampBits >>= 8n;
|
|
433
|
+
}
|
|
434
|
+
bytes[6] = 112 | Number(random >> 70n & 0x0fn);
|
|
435
|
+
bytes[7] = Number(random >> 62n & 0xffn);
|
|
436
|
+
bytes[8] = 128 | Number(random >> 56n & 0x3fn);
|
|
437
|
+
let remaining = random & (1n << 56n) - 1n;
|
|
438
|
+
for (let index = 15; index >= 9; index -= 1) {
|
|
439
|
+
bytes[index] = Number(remaining & 0xffn);
|
|
440
|
+
remaining >>= 8n;
|
|
441
|
+
}
|
|
442
|
+
const value = hex(bytes);
|
|
443
|
+
return `${value.slice(0, 8)}-${value.slice(8, 12)}-${value.slice(
|
|
444
|
+
12,
|
|
445
|
+
16
|
|
446
|
+
)}-${value.slice(16, 20)}-${value.slice(20)}`;
|
|
447
|
+
}
|
|
392
448
|
|
|
393
449
|
// package.json
|
|
394
450
|
var package_default = {
|
|
395
|
-
version: "
|
|
451
|
+
version: "2.0.0"};
|
|
396
452
|
|
|
397
453
|
// src/client.ts
|
|
398
454
|
var TRAFFICWAR_DEFAULT_BASE_URL = "https://ingest.trafficwar.tech";
|
|
399
455
|
var TRAFFICWAR_DEFAULT_TIMEOUT_MS = 3e4;
|
|
400
456
|
var TRAFFICWAR_DEFAULT_MAX_RETRIES = 3;
|
|
457
|
+
var TRAFFICWAR_DEFAULT_FLUSH_INTERVAL_MS = 1e3;
|
|
458
|
+
var TRAFFICWAR_DEFAULT_MAX_QUEUE_SIZE = 1e5;
|
|
401
459
|
var TRAFFICWAR_MAX_BATCH_SIZE = 1e4;
|
|
402
460
|
var TRAFFICWAR_MAX_COMPRESSED_BODY_BYTES = 2 * 1024 * 1024;
|
|
403
461
|
var TRAFFICWAR_MAX_DECODED_BODY_BYTES = 8 * 1024 * 1024;
|
|
@@ -416,6 +474,13 @@ var AttemptTransportFailure = class {
|
|
|
416
474
|
this.timedOut = timedOut;
|
|
417
475
|
}
|
|
418
476
|
};
|
|
477
|
+
var PreparedRequestTooLarge = class extends Error {
|
|
478
|
+
limit;
|
|
479
|
+
constructor(limit) {
|
|
480
|
+
super(limit);
|
|
481
|
+
this.limit = limit;
|
|
482
|
+
}
|
|
483
|
+
};
|
|
419
484
|
function asRecord(value) {
|
|
420
485
|
if (value === null || typeof value !== "object" || Array.isArray(value)) {
|
|
421
486
|
return void 0;
|
|
@@ -482,26 +547,6 @@ function validateCompression(value) {
|
|
|
482
547
|
}
|
|
483
548
|
return actual;
|
|
484
549
|
}
|
|
485
|
-
function isAbortSignal(value) {
|
|
486
|
-
return value !== null && typeof value === "object" && typeof value.aborted === "boolean" && typeof value.addEventListener === "function" && typeof value.removeEventListener === "function";
|
|
487
|
-
}
|
|
488
|
-
function requestIdentity(options) {
|
|
489
|
-
if (options !== void 0 && (options === null || typeof options !== "object" || Array.isArray(options))) {
|
|
490
|
-
throw new TrafficWarValidationError(
|
|
491
|
-
"request options must be an object",
|
|
492
|
-
{ path: "options" }
|
|
493
|
-
);
|
|
494
|
-
}
|
|
495
|
-
const idempotencyKey = options?.idempotencyKey === void 0 ? crypto.randomUUID() : validateIdempotencyKey(options.idempotencyKey);
|
|
496
|
-
const signal = options?.signal;
|
|
497
|
-
if (signal !== void 0 && !isAbortSignal(signal)) {
|
|
498
|
-
throw new TrafficWarValidationError(
|
|
499
|
-
"signal must be an AbortSignal",
|
|
500
|
-
{ path: "options.signal", idempotencyKey }
|
|
501
|
-
);
|
|
502
|
-
}
|
|
503
|
-
return { idempotencyKey, signal };
|
|
504
|
-
}
|
|
505
550
|
function parseBody(text) {
|
|
506
551
|
if (text.length === 0) {
|
|
507
552
|
return { text, value: void 0, isJson: false };
|
|
@@ -637,10 +682,7 @@ function gzipBody(decoded) {
|
|
|
637
682
|
async function prepareRequest(payload, idempotencyKey, compression, compressionThresholdBytes) {
|
|
638
683
|
const decoded = serializeJson(payload, idempotencyKey);
|
|
639
684
|
if (decoded.byteLength > TRAFFICWAR_MAX_DECODED_BODY_BYTES) {
|
|
640
|
-
throw new
|
|
641
|
-
`Decoded request body exceeds ${TRAFFICWAR_MAX_DECODED_BODY_BYTES} bytes`,
|
|
642
|
-
{ path: "body", idempotencyKey }
|
|
643
|
-
);
|
|
685
|
+
throw new PreparedRequestTooLarge("decoded");
|
|
644
686
|
}
|
|
645
687
|
const useGzip = compression === "gzip" || compression === "auto" && decoded.byteLength >= compressionThresholdBytes;
|
|
646
688
|
let body;
|
|
@@ -654,10 +696,7 @@ async function prepareRequest(payload, idempotencyKey, compression, compressionT
|
|
|
654
696
|
});
|
|
655
697
|
}
|
|
656
698
|
if (body.byteLength > TRAFFICWAR_MAX_COMPRESSED_BODY_BYTES) {
|
|
657
|
-
throw new
|
|
658
|
-
`Request body exceeds the ${TRAFFICWAR_MAX_COMPRESSED_BODY_BYTES}-byte wire limit`,
|
|
659
|
-
{ path: "body", idempotencyKey }
|
|
660
|
-
);
|
|
699
|
+
throw new PreparedRequestTooLarge("wire");
|
|
661
700
|
}
|
|
662
701
|
return {
|
|
663
702
|
body,
|
|
@@ -737,8 +776,22 @@ var TrafficWar = class {
|
|
|
737
776
|
maxRetries;
|
|
738
777
|
compression;
|
|
739
778
|
compressionThresholdBytes;
|
|
779
|
+
flushIntervalMs;
|
|
780
|
+
maxQueueSize;
|
|
740
781
|
#apiKey;
|
|
741
782
|
#fetch;
|
|
783
|
+
#onError;
|
|
784
|
+
#queue = [];
|
|
785
|
+
#pendingEventIds = /* @__PURE__ */ new Set();
|
|
786
|
+
#pendingCount = 0;
|
|
787
|
+
#preparedBatch;
|
|
788
|
+
#timer;
|
|
789
|
+
#drainPromise;
|
|
790
|
+
#backgroundPromise;
|
|
791
|
+
#backgroundScheduled = false;
|
|
792
|
+
#closePromise;
|
|
793
|
+
#closing = false;
|
|
794
|
+
#closed = false;
|
|
742
795
|
constructor(options) {
|
|
743
796
|
if (options === null || typeof options !== "object" || Array.isArray(options)) {
|
|
744
797
|
throw new TrafficWarValidationError(
|
|
@@ -770,95 +823,323 @@ var TrafficWar = class {
|
|
|
770
823
|
0,
|
|
771
824
|
TRAFFICWAR_MAX_DECODED_BODY_BYTES
|
|
772
825
|
);
|
|
826
|
+
this.flushIntervalMs = validateIntegerOption(
|
|
827
|
+
"flushIntervalMs",
|
|
828
|
+
options.flushIntervalMs,
|
|
829
|
+
TRAFFICWAR_DEFAULT_FLUSH_INTERVAL_MS,
|
|
830
|
+
1,
|
|
831
|
+
MAX_TIMER_MS
|
|
832
|
+
);
|
|
833
|
+
this.maxQueueSize = validateIntegerOption(
|
|
834
|
+
"maxQueueSize",
|
|
835
|
+
options.maxQueueSize,
|
|
836
|
+
TRAFFICWAR_DEFAULT_MAX_QUEUE_SIZE,
|
|
837
|
+
1,
|
|
838
|
+
Number.MAX_SAFE_INTEGER
|
|
839
|
+
);
|
|
773
840
|
if (options.fetch !== void 0 && typeof options.fetch !== "function") {
|
|
774
841
|
throw new TrafficWarValidationError(
|
|
775
842
|
"fetch must be a function",
|
|
776
843
|
{ path: "options.fetch" }
|
|
777
844
|
);
|
|
778
845
|
}
|
|
846
|
+
if (options.onError !== void 0 && typeof options.onError !== "function") {
|
|
847
|
+
throw new TrafficWarValidationError(
|
|
848
|
+
"onError must be a function",
|
|
849
|
+
{ path: "options.onError" }
|
|
850
|
+
);
|
|
851
|
+
}
|
|
779
852
|
this.#fetch = options.fetch ?? ((input, init) => {
|
|
780
853
|
return globalThis.fetch(input, init);
|
|
781
854
|
});
|
|
855
|
+
this.#onError = options.onError;
|
|
782
856
|
}
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
const identity = requestIdentity(options);
|
|
799
|
-
if (!Array.isArray(events) || events.length === 0) {
|
|
857
|
+
capture(eventOrEvents) {
|
|
858
|
+
if (this.#closed) {
|
|
859
|
+
throw new TrafficWarValidationError(
|
|
860
|
+
"TrafficWar client is closed",
|
|
861
|
+
{ path: "client" }
|
|
862
|
+
);
|
|
863
|
+
}
|
|
864
|
+
if (this.#closing) {
|
|
865
|
+
throw new TrafficWarValidationError(
|
|
866
|
+
"TrafficWar client is closing",
|
|
867
|
+
{ path: "client" }
|
|
868
|
+
);
|
|
869
|
+
}
|
|
870
|
+
const isBatch = Array.isArray(eventOrEvents);
|
|
871
|
+
if (isBatch && eventOrEvents.length === 0) {
|
|
800
872
|
throw new TrafficWarValidationError(
|
|
801
873
|
"events must be a non-empty array",
|
|
802
|
-
{ path: "events"
|
|
874
|
+
{ path: "events" }
|
|
803
875
|
);
|
|
804
876
|
}
|
|
805
|
-
|
|
877
|
+
const events = isBatch ? eventOrEvents : [eventOrEvents];
|
|
878
|
+
if (isBatch) {
|
|
879
|
+
for (let index = 0; index < events.length; index += 1) {
|
|
880
|
+
if (!(index in events)) {
|
|
881
|
+
const path = `events[${index}]`;
|
|
882
|
+
throw new TrafficWarValidationError(
|
|
883
|
+
`${path} is missing; sparse event arrays are not supported`,
|
|
884
|
+
{ path }
|
|
885
|
+
);
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
if (events.length > this.maxQueueSize - this.#pendingCount) {
|
|
806
890
|
throw new TrafficWarValidationError(
|
|
807
|
-
`
|
|
808
|
-
{ path: "
|
|
891
|
+
`TrafficWar queue cannot exceed ${this.maxQueueSize} events`,
|
|
892
|
+
{ path: "queue" }
|
|
809
893
|
);
|
|
810
894
|
}
|
|
811
|
-
const normalized =
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
895
|
+
const normalized = [];
|
|
896
|
+
for (let index = 0; index < events.length; index += 1) {
|
|
897
|
+
const path = isBatch ? `events[${index}]` : "event";
|
|
898
|
+
normalized.push(normalizeEvent(events[index], path));
|
|
899
|
+
}
|
|
900
|
+
for (const event of normalized) {
|
|
901
|
+
if (!Object.hasOwn(event, "event_id")) {
|
|
902
|
+
event.event_id = uuidv7();
|
|
903
|
+
}
|
|
904
|
+
}
|
|
905
|
+
const incomingEventIds = /* @__PURE__ */ new Set();
|
|
906
|
+
for (let index = 0; index < normalized.length; index += 1) {
|
|
907
|
+
const eventId = normalized[index].event_id;
|
|
908
|
+
if (incomingEventIds.has(eventId) || this.#pendingEventIds.has(eventId)) {
|
|
909
|
+
const path = isBatch ? `events[${index}].event_id` : "event.event_id";
|
|
910
|
+
throw new TrafficWarValidationError(
|
|
911
|
+
`${path} duplicates an unacknowledged event_id`,
|
|
912
|
+
{ path }
|
|
913
|
+
);
|
|
914
|
+
}
|
|
915
|
+
incomingEventIds.add(eventId);
|
|
916
|
+
}
|
|
917
|
+
for (const event of normalized) {
|
|
918
|
+
this.#queue.push(event);
|
|
919
|
+
this.#pendingEventIds.add(event.event_id);
|
|
920
|
+
}
|
|
921
|
+
this.#pendingCount += normalized.length;
|
|
922
|
+
if (this.#pendingCount >= TRAFFICWAR_MAX_BATCH_SIZE) {
|
|
923
|
+
this.#clearTimer();
|
|
924
|
+
this.#startBackgroundDrain();
|
|
925
|
+
} else {
|
|
926
|
+
this.#ensureTimer();
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
/**
|
|
930
|
+
* @deprecated Pass the array directly to capture().
|
|
931
|
+
*/
|
|
932
|
+
captureBatch(events) {
|
|
933
|
+
if (!Array.isArray(events) || events.length === 0) {
|
|
934
|
+
throw new TrafficWarValidationError(
|
|
935
|
+
"events must be a non-empty array",
|
|
936
|
+
{ path: "events" }
|
|
937
|
+
);
|
|
938
|
+
}
|
|
939
|
+
this.capture(events);
|
|
940
|
+
}
|
|
941
|
+
flush() {
|
|
942
|
+
if (this.#closePromise) {
|
|
943
|
+
return this.#closePromise;
|
|
944
|
+
}
|
|
945
|
+
this.#clearTimer();
|
|
946
|
+
return this.#startDrain();
|
|
947
|
+
}
|
|
948
|
+
close() {
|
|
949
|
+
if (this.#closed) {
|
|
950
|
+
return Promise.resolve({ accepted: 0, batches: [] });
|
|
951
|
+
}
|
|
952
|
+
if (this.#closePromise) {
|
|
953
|
+
return this.#closePromise;
|
|
954
|
+
}
|
|
955
|
+
this.#clearTimer();
|
|
956
|
+
this.#closing = true;
|
|
957
|
+
let closing;
|
|
958
|
+
closing = Promise.resolve().then(async () => {
|
|
959
|
+
const batches = [];
|
|
960
|
+
let accepted = 0;
|
|
961
|
+
try {
|
|
962
|
+
do {
|
|
963
|
+
const result = await this.#startDrain();
|
|
964
|
+
accepted += result.accepted;
|
|
965
|
+
for (const batch of result.batches) {
|
|
966
|
+
batches.push(batch);
|
|
967
|
+
}
|
|
968
|
+
} while (this.#pendingCount > 0);
|
|
969
|
+
this.#clearTimer();
|
|
970
|
+
this.#closed = true;
|
|
971
|
+
return { accepted, batches };
|
|
972
|
+
} finally {
|
|
973
|
+
if (this.#closePromise === closing) {
|
|
974
|
+
this.#closePromise = void 0;
|
|
975
|
+
}
|
|
976
|
+
this.#closing = false;
|
|
977
|
+
if (!this.#closed && this.#pendingCount > 0) {
|
|
978
|
+
this.#ensureTimer();
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
});
|
|
982
|
+
this.#closePromise = closing;
|
|
983
|
+
return closing;
|
|
984
|
+
}
|
|
985
|
+
#ensureTimer() {
|
|
986
|
+
if (this.#closed || this.#closing || this.#pendingCount === 0 || this.#timer !== void 0) {
|
|
987
|
+
return;
|
|
988
|
+
}
|
|
989
|
+
const timer = setTimeout(() => {
|
|
990
|
+
if (this.#timer === timer) {
|
|
991
|
+
this.#timer = void 0;
|
|
992
|
+
}
|
|
993
|
+
this.#startBackgroundDrain();
|
|
994
|
+
}, this.flushIntervalMs);
|
|
995
|
+
timer.unref();
|
|
996
|
+
this.#timer = timer;
|
|
825
997
|
}
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
998
|
+
#clearTimer() {
|
|
999
|
+
if (this.#timer !== void 0) {
|
|
1000
|
+
clearTimeout(this.#timer);
|
|
1001
|
+
this.#timer = void 0;
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
#startBackgroundDrain() {
|
|
1005
|
+
if (this.#backgroundScheduled) {
|
|
1006
|
+
return;
|
|
1007
|
+
}
|
|
1008
|
+
this.#backgroundScheduled = true;
|
|
1009
|
+
queueMicrotask(() => {
|
|
1010
|
+
this.#backgroundScheduled = false;
|
|
1011
|
+
if (!this.#closed && this.#pendingCount > 0) {
|
|
1012
|
+
this.#observeBackgroundDrain(this.#startDrain());
|
|
1013
|
+
}
|
|
1014
|
+
});
|
|
1015
|
+
}
|
|
1016
|
+
#observeBackgroundDrain(drain) {
|
|
1017
|
+
if (this.#backgroundPromise === drain) {
|
|
1018
|
+
return;
|
|
1019
|
+
}
|
|
1020
|
+
this.#backgroundPromise = drain;
|
|
1021
|
+
void drain.then(
|
|
1022
|
+
() => {
|
|
1023
|
+
if (this.#backgroundPromise === drain) {
|
|
1024
|
+
this.#backgroundPromise = void 0;
|
|
1025
|
+
}
|
|
1026
|
+
},
|
|
1027
|
+
(error) => {
|
|
1028
|
+
if (this.#backgroundPromise === drain) {
|
|
1029
|
+
this.#backgroundPromise = void 0;
|
|
1030
|
+
}
|
|
1031
|
+
if (this.#onError) {
|
|
1032
|
+
try {
|
|
1033
|
+
const handled = this.#onError(error);
|
|
1034
|
+
void Promise.resolve(handled).catch(() => void 0);
|
|
1035
|
+
} catch {
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
832
1039
|
);
|
|
1040
|
+
}
|
|
1041
|
+
#startDrain() {
|
|
1042
|
+
if (this.#drainPromise) {
|
|
1043
|
+
return this.#drainPromise;
|
|
1044
|
+
}
|
|
1045
|
+
let drain;
|
|
1046
|
+
drain = (async () => {
|
|
1047
|
+
try {
|
|
1048
|
+
return await this.#drain();
|
|
1049
|
+
} finally {
|
|
1050
|
+
if (this.#drainPromise === drain) {
|
|
1051
|
+
this.#drainPromise = void 0;
|
|
1052
|
+
}
|
|
1053
|
+
if (this.#pendingCount === 0) {
|
|
1054
|
+
this.#clearTimer();
|
|
1055
|
+
} else if (!this.#closed) {
|
|
1056
|
+
this.#ensureTimer();
|
|
1057
|
+
}
|
|
1058
|
+
}
|
|
1059
|
+
})();
|
|
1060
|
+
this.#drainPromise = drain;
|
|
1061
|
+
return drain;
|
|
1062
|
+
}
|
|
1063
|
+
async #drain() {
|
|
1064
|
+
const batches = [];
|
|
1065
|
+
let accepted = 0;
|
|
1066
|
+
while (this.#pendingCount > 0) {
|
|
1067
|
+
const batch = this.#preparedBatch ?? await this.#prepareNextBatch();
|
|
1068
|
+
this.#preparedBatch = batch;
|
|
1069
|
+
const result = await this.#send(batch);
|
|
1070
|
+
for (const event of batch.events) {
|
|
1071
|
+
this.#pendingEventIds.delete(event.event_id);
|
|
1072
|
+
}
|
|
1073
|
+
this.#preparedBatch = void 0;
|
|
1074
|
+
this.#pendingCount -= batch.events.length;
|
|
1075
|
+
accepted += result.accepted;
|
|
1076
|
+
batches.push(result);
|
|
1077
|
+
}
|
|
1078
|
+
return { accepted, batches };
|
|
1079
|
+
}
|
|
1080
|
+
async #prepareNextBatch() {
|
|
1081
|
+
let count = Math.min(this.#queue.length, TRAFFICWAR_MAX_BATCH_SIZE);
|
|
1082
|
+
if (count === 0) {
|
|
1083
|
+
throw new Error("TrafficWar queue state is inconsistent");
|
|
1084
|
+
}
|
|
1085
|
+
while (true) {
|
|
1086
|
+
const events = this.#queue.slice(0, count);
|
|
1087
|
+
const idempotencyKey = uuidv7();
|
|
1088
|
+
try {
|
|
1089
|
+
const prepared = await prepareRequest(
|
|
1090
|
+
events,
|
|
1091
|
+
idempotencyKey,
|
|
1092
|
+
this.compression,
|
|
1093
|
+
this.compressionThresholdBytes
|
|
1094
|
+
);
|
|
1095
|
+
this.#queue.splice(0, count);
|
|
1096
|
+
return { ...prepared, events, idempotencyKey };
|
|
1097
|
+
} catch (error) {
|
|
1098
|
+
if (!(error instanceof PreparedRequestTooLarge)) {
|
|
1099
|
+
throw error;
|
|
1100
|
+
}
|
|
1101
|
+
if (count > 1) {
|
|
1102
|
+
count = Math.max(1, Math.floor(count / 2));
|
|
1103
|
+
continue;
|
|
1104
|
+
}
|
|
1105
|
+
const message = error.limit === "decoded" ? `Decoded request body exceeds ${TRAFFICWAR_MAX_DECODED_BODY_BYTES} bytes` : `Request body exceeds the ${TRAFFICWAR_MAX_COMPRESSED_BODY_BYTES}-byte wire limit`;
|
|
1106
|
+
throw new TrafficWarValidationError(message, {
|
|
1107
|
+
path: "body",
|
|
1108
|
+
idempotencyKey
|
|
1109
|
+
});
|
|
1110
|
+
}
|
|
1111
|
+
}
|
|
1112
|
+
}
|
|
1113
|
+
async #send(batch, signal) {
|
|
833
1114
|
const headers = {
|
|
834
1115
|
accept: "application/json",
|
|
835
1116
|
authorization: `Bearer ${this.#apiKey}`,
|
|
836
1117
|
"content-type": "application/json",
|
|
837
|
-
"idempotency-key":
|
|
1118
|
+
"idempotency-key": batch.idempotencyKey,
|
|
838
1119
|
"user-agent": `@trafficwar/node/${SDK_VERSION}`,
|
|
839
1120
|
"x-trafficwar-sdk": `node/${SDK_VERSION}`
|
|
840
1121
|
};
|
|
841
|
-
if (
|
|
842
|
-
headers["content-encoding"] =
|
|
1122
|
+
if (batch.contentEncoding) {
|
|
1123
|
+
headers["content-encoding"] = batch.contentEncoding;
|
|
843
1124
|
}
|
|
844
|
-
const url = `${this.baseUrl}
|
|
1125
|
+
const url = `${this.baseUrl}/v1/server/batch`;
|
|
845
1126
|
const init = {
|
|
846
1127
|
method: "POST",
|
|
847
1128
|
headers,
|
|
848
|
-
body:
|
|
1129
|
+
body: batch.body,
|
|
849
1130
|
redirect: "error"
|
|
850
1131
|
};
|
|
851
1132
|
let sawTimeout = false;
|
|
852
1133
|
for (let attempt = 0; attempt <= this.maxRetries; attempt += 1) {
|
|
853
|
-
if (
|
|
1134
|
+
if (signal?.aborted) {
|
|
854
1135
|
throw new TrafficWarConnectionError(
|
|
855
1136
|
"TrafficWar request was aborted",
|
|
856
1137
|
{
|
|
857
1138
|
attempts: attempt,
|
|
858
1139
|
aborted: true,
|
|
859
1140
|
timedOut: sawTimeout,
|
|
860
|
-
idempotencyKey:
|
|
861
|
-
cause:
|
|
1141
|
+
idempotencyKey: batch.idempotencyKey,
|
|
1142
|
+
cause: signal.reason
|
|
862
1143
|
}
|
|
863
1144
|
);
|
|
864
1145
|
}
|
|
@@ -868,21 +1149,21 @@ var TrafficWar = class {
|
|
|
868
1149
|
this.#fetch,
|
|
869
1150
|
url,
|
|
870
1151
|
init,
|
|
871
|
-
|
|
1152
|
+
signal,
|
|
872
1153
|
this.timeoutMs
|
|
873
1154
|
);
|
|
874
1155
|
} catch (error) {
|
|
875
1156
|
const failure = error instanceof AttemptTransportFailure ? error : new AttemptTransportFailure(error, false);
|
|
876
1157
|
sawTimeout ||= failure.timedOut;
|
|
877
|
-
if (
|
|
1158
|
+
if (signal?.aborted) {
|
|
878
1159
|
throw new TrafficWarConnectionError(
|
|
879
1160
|
"TrafficWar request was aborted",
|
|
880
1161
|
{
|
|
881
1162
|
attempts: attempt + 1,
|
|
882
1163
|
aborted: true,
|
|
883
1164
|
timedOut: sawTimeout,
|
|
884
|
-
idempotencyKey:
|
|
885
|
-
cause:
|
|
1165
|
+
idempotencyKey: batch.idempotencyKey,
|
|
1166
|
+
cause: signal.reason ?? failure.cause
|
|
886
1167
|
}
|
|
887
1168
|
);
|
|
888
1169
|
}
|
|
@@ -892,13 +1173,13 @@ var TrafficWar = class {
|
|
|
892
1173
|
{
|
|
893
1174
|
attempts: attempt + 1,
|
|
894
1175
|
timedOut: sawTimeout,
|
|
895
|
-
idempotencyKey:
|
|
1176
|
+
idempotencyKey: batch.idempotencyKey,
|
|
896
1177
|
cause: failure.cause
|
|
897
1178
|
}
|
|
898
1179
|
);
|
|
899
1180
|
}
|
|
900
1181
|
try {
|
|
901
|
-
await sleep(retryDelayMs(attempt, void 0),
|
|
1182
|
+
await sleep(retryDelayMs(attempt, void 0), signal);
|
|
902
1183
|
} catch (cause) {
|
|
903
1184
|
throw new TrafficWarConnectionError(
|
|
904
1185
|
"TrafficWar request was aborted",
|
|
@@ -906,7 +1187,7 @@ var TrafficWar = class {
|
|
|
906
1187
|
attempts: attempt + 1,
|
|
907
1188
|
aborted: true,
|
|
908
1189
|
timedOut: sawTimeout,
|
|
909
|
-
idempotencyKey:
|
|
1190
|
+
idempotencyKey: batch.idempotencyKey,
|
|
910
1191
|
cause
|
|
911
1192
|
}
|
|
912
1193
|
);
|
|
@@ -918,15 +1199,15 @@ var TrafficWar = class {
|
|
|
918
1199
|
return parseSuccess(
|
|
919
1200
|
result.response,
|
|
920
1201
|
parsed,
|
|
921
|
-
|
|
922
|
-
|
|
1202
|
+
batch.events.length,
|
|
1203
|
+
batch.idempotencyKey
|
|
923
1204
|
);
|
|
924
1205
|
}
|
|
925
1206
|
if (RETRYABLE_STATUSES.has(result.response.status) && attempt < this.maxRetries) {
|
|
926
1207
|
const retryAfter = retryAfterSeconds(result.response, parsed);
|
|
927
1208
|
if (retryAfter === void 0 || retryAfter <= MAX_RETRY_AFTER_SECONDS) {
|
|
928
1209
|
try {
|
|
929
|
-
await sleep(retryDelayMs(attempt, retryAfter),
|
|
1210
|
+
await sleep(retryDelayMs(attempt, retryAfter), signal);
|
|
930
1211
|
} catch (cause) {
|
|
931
1212
|
throw new TrafficWarConnectionError(
|
|
932
1213
|
"TrafficWar request was aborted",
|
|
@@ -934,7 +1215,7 @@ var TrafficWar = class {
|
|
|
934
1215
|
attempts: attempt + 1,
|
|
935
1216
|
aborted: true,
|
|
936
1217
|
timedOut: sawTimeout,
|
|
937
|
-
idempotencyKey:
|
|
1218
|
+
idempotencyKey: batch.idempotencyKey,
|
|
938
1219
|
cause
|
|
939
1220
|
}
|
|
940
1221
|
);
|
|
@@ -945,18 +1226,20 @@ var TrafficWar = class {
|
|
|
945
1226
|
throw buildApiError(
|
|
946
1227
|
result.response,
|
|
947
1228
|
parsed,
|
|
948
|
-
|
|
1229
|
+
batch.idempotencyKey
|
|
949
1230
|
);
|
|
950
1231
|
}
|
|
951
1232
|
throw new TrafficWarConnectionError("Unable to reach TrafficWar", {
|
|
952
1233
|
attempts: this.maxRetries + 1,
|
|
953
1234
|
timedOut: sawTimeout,
|
|
954
|
-
idempotencyKey:
|
|
1235
|
+
idempotencyKey: batch.idempotencyKey
|
|
955
1236
|
});
|
|
956
1237
|
}
|
|
957
1238
|
};
|
|
958
1239
|
|
|
959
1240
|
exports.TRAFFICWAR_DEFAULT_BASE_URL = TRAFFICWAR_DEFAULT_BASE_URL;
|
|
1241
|
+
exports.TRAFFICWAR_DEFAULT_FLUSH_INTERVAL_MS = TRAFFICWAR_DEFAULT_FLUSH_INTERVAL_MS;
|
|
1242
|
+
exports.TRAFFICWAR_DEFAULT_MAX_QUEUE_SIZE = TRAFFICWAR_DEFAULT_MAX_QUEUE_SIZE;
|
|
960
1243
|
exports.TRAFFICWAR_DEFAULT_MAX_RETRIES = TRAFFICWAR_DEFAULT_MAX_RETRIES;
|
|
961
1244
|
exports.TRAFFICWAR_DEFAULT_TIMEOUT_MS = TRAFFICWAR_DEFAULT_TIMEOUT_MS;
|
|
962
1245
|
exports.TRAFFICWAR_MAX_BATCH_SIZE = TRAFFICWAR_MAX_BATCH_SIZE;
|