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