@trafficwar/node 1.0.0 → 2.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/README.md CHANGED
@@ -6,87 +6,157 @@ Official, dependency-free TrafficWar server SDK for Node.js 22 and newer.
6
6
 
7
7
  ```sh
8
8
  npm install @trafficwar/node
9
+ # or
10
+ pnpm add @trafficwar/node
11
+ # or
12
+ bun add @trafficwar/node
9
13
  ```
10
14
 
11
- ## Capture an event
15
+ ## Capture events
12
16
 
13
17
  ```ts
14
18
  import { TrafficWar } from "@trafficwar/node";
15
19
 
16
20
  const trafficwar = new TrafficWar({
17
21
  apiKey: process.env.TRAFFICWAR_API_KEY!,
22
+ onError(error) {
23
+ console.error("TrafficWar automatic flush failed", error);
24
+ },
18
25
  });
19
26
 
20
- const result = await trafficwar.capture({
27
+ trafficwar.capture({
21
28
  event: "checkout.completed",
22
- event_id: "018f47a2-7b17-7b9f-8a9c-5b1fdbda7b31",
23
29
  timestamp: new Date(),
24
30
  latency_ms: 184.2,
25
31
  status_code: 200,
26
- span_kind: "server",
27
- operation_type: "http",
32
+ source: "checkout-api",
28
33
  properties: {
29
34
  orderId: "ord_123",
30
35
  total: 49.95,
31
36
  },
32
37
  });
33
38
 
34
- console.log(result.ingestId, result.accepted, result.idempotencyKey);
39
+ trafficwar.capture([
40
+ { event: "job.started", source: "worker" },
41
+ { event: "job.finished", source: "worker", latency_ms: 42 },
42
+ ]);
35
43
  ```
36
44
 
45
+ `capture` accepts one event or a non-empty array. It validates, snapshots, and
46
+ enqueues the input synchronously, then returns `void`; it does not return an
47
+ `IngestResult` or wait for the network.
48
+
37
49
  `Date` timestamps are serialized as RFC3339 without changing the caller's
38
50
  object. String timestamps must be RFC3339; numeric timestamps are integer epoch
39
51
  milliseconds.
40
52
 
41
- The SDK does not generate `event_id`. You may provide a UUID, or omit it and
42
- let TrafficWar derive a stable ID from the request's idempotency receipt.
43
- `user_id`, `service`, and `service_id` must not be sent: TrafficWar derives
44
- identity from the API key.
53
+ ## Automatic batching
45
54
 
46
- ## Capture a batch
55
+ The first queued event starts a one-second timer. The client flushes when that
56
+ timer expires or as soon as 10,000 events are pending. TrafficWar's fixed
57
+ server batch maximum is 10,000, so a larger queued array is split across
58
+ requests.
59
+
60
+ Every request is a bare JSON array sent to `/v1/server/batch`, including a
61
+ single-event capture. The queue holds at most 100,000 unacknowledged events by
62
+ default. Configure the timing and queue bound with `flushIntervalMs` and
63
+ `maxQueueSize`:
47
64
 
48
65
  ```ts
49
- await trafficwar.captureBatch([
50
- { event: "job.started", trace_id: "trace-123" },
51
- { event: "job.finished", trace_id: "trace-123", latency_ms: 42 },
52
- ]);
66
+ const trafficwar = new TrafficWar({
67
+ apiKey: process.env.TRAFFICWAR_API_KEY!,
68
+ flushIntervalMs: 1_000,
69
+ maxQueueSize: 100_000,
70
+ });
71
+ ```
72
+
73
+ If enqueueing would exceed the configured queue limit, `capture` throws a
74
+ `TrafficWarValidationError` and enqueues none of that call.
75
+
76
+ Set `debug: true` to print queue, flush, request, retry, and acknowledgement
77
+ diagnostics with `console.debug`. Debug logging is off by default and never
78
+ includes API keys or queued event payloads.
79
+
80
+ ```ts
81
+ const trafficwar = new TrafficWar({
82
+ apiKey: process.env.TRAFFICWAR_API_KEY!,
83
+ debug: true,
84
+ });
53
85
  ```
54
86
 
55
- Batches must contain 1 to 10,000 events. The SDK sends the required bare JSON
56
- array to `/v1/server/batch`; a single capture sends one JSON object to
57
- `/v1/server/capture`.
87
+ The SDK generates a process-monotonic RFC 9562 UUIDv7 `event_id` for each event
88
+ that omits one. A caller may override it with any valid UUID. Caller-owned
89
+ objects are never modified.
58
90
 
59
- ## Request options
91
+ Use `source` for caller-selected origin or runtime metadata such as
92
+ `checkout-api`, `node-worker`, or `production`. `span_kind` is separate,
93
+ optional tracing semantics (`server`, `client`, `producer`, `consumer`, or
94
+ `internal`); it does not replace `source`.
60
95
 
61
- Every SDK call creates a fresh idempotency key. The exact JSON bytes, optional
62
- gzip bytes, and key are created once and reused across that call's retries.
63
- Supply your own key when retry coordination must survive a process boundary:
96
+ ## Flush results and shutdown
97
+
98
+ Call `flush` when an application needs an acknowledgement before continuing:
64
99
 
65
100
  ```ts
66
- const controller = new AbortController();
101
+ trafficwar.capture({ event: "deployment.finished", source: "release-worker" });
67
102
 
68
- await trafficwar.capture(
69
- { event: "invoice.created" },
70
- {
71
- idempotencyKey: "invoice-inv_123-v1",
72
- signal: controller.signal,
73
- },
74
- );
103
+ const result = await trafficwar.flush();
104
+ console.log(result.accepted);
105
+ for (const batch of result.batches) {
106
+ console.log(batch.ingestId, batch.accepted, batch.idempotencyKey);
107
+ }
75
108
  ```
76
109
 
77
- An idempotency key must contain 1-256 visible ASCII characters. A key is scoped
78
- to the service represented by the API key and is body- and route-sensitive.
79
- Reusing a key for a different request produces HTTP 409 and is never retried.
110
+ `flush` returns an aggregate `FlushResult`: `accepted` is the number of events
111
+ drained by that operation, and `batches` contains one `IngestResult` per HTTP
112
+ request.
113
+
114
+ Always await `close` during graceful application shutdown:
115
+
116
+ ```ts
117
+ const result = await trafficwar.close();
118
+ console.log(result.accepted, result.batches.length);
119
+ ```
120
+
121
+ `close` already stops automatic work and flushes every queued event; a separate
122
+ shutdown `flush` is unnecessary. The automatic timer is unref'ed and will not
123
+ keep Node running, so exiting without awaiting `close` can lose pending events.
124
+
125
+ `captureBatch(events)` remains as a deprecated compatibility alias. New code
126
+ passes the non-empty array directly to `capture(events)`.
127
+
128
+ ## Delivery, retries, and errors
129
+
130
+ The SDK prepares each HTTP batch once. Its compact JSON bytes, optional gzip
131
+ bytes, generated event IDs, and internal idempotency key stay stable across
132
+ bounded retries. Idempotency is an internal delivery detail rather than part of
133
+ the `capture` API.
134
+
135
+ Transport failures, per-attempt timeouts, and HTTP 408, 425, 500, 502, 503, and
136
+ 504 use exponential full jitter. `Retry-After` is honored as a minimum delay
137
+ up to 60 seconds; larger values are surfaced immediately as API errors. HTTP
138
+ 409 and 429 are never retried.
139
+
140
+ An automatic delivery failure invokes optional `onError`. The handler is
141
+ observational: the failed prepared batch remains queued. A later automatic
142
+ attempt, `flush`, or `close` retries that same batch, and explicit `flush` or
143
+ `close` surfaces an error if delivery still fails.
80
144
 
81
145
  ## Client options
82
146
 
83
147
  - `apiKey` (required): TrafficWar server API key.
84
148
  - `baseUrl`: ingest origin. Defaults to `https://ingest.trafficwar.tech`.
149
+ - `debug`: print safe batch lifecycle diagnostics with `console.debug`.
150
+ Defaults to `false`.
85
151
  - `timeoutMs`: timeout for each attempt. Defaults to 30,000 ms, safely above
86
152
  TrafficWar's 10-second durable acknowledgement window.
87
153
  - `maxRetries`: retries after the first attempt. Defaults to 3.
88
154
  - `compression`: `"auto"`, `"gzip"`, or `"none"`. Defaults to `"auto"`.
89
155
  - `compressionThresholdBytes`: gzip threshold in auto mode. Defaults to 1024.
156
+ - `flushIntervalMs`: delay from the first pending event to automatic flush.
157
+ Defaults to 1,000 ms.
158
+ - `maxQueueSize`: maximum unacknowledged events. Defaults to 100,000.
159
+ - `onError`: optional callback for automatic background delivery errors.
90
160
  - `fetch`: injected Fetch-compatible function, primarily for testing.
91
161
 
92
162
  The SDK sends `Content-Type: application/json`, `Authorization: Bearer ...`, a
@@ -95,13 +165,6 @@ server SDK User-Agent, and `x-trafficwar-sdk`. It never sends `Origin`.
95
165
  Decoded JSON is limited to 8 MiB. The identity or gzip wire body is limited to
96
166
  2 MiB. Auto mode gzip-compresses bodies at or above the configured threshold.
97
167
 
98
- ## Retries and errors
99
-
100
- Transport failures, per-attempt timeouts, and HTTP 408, 425, 500, 502, 503, and
101
- 504 use exponential full jitter. `Retry-After` is honored as a minimum delay
102
- up to 60 seconds; larger values are surfaced immediately as API errors so calls
103
- remain bounded. HTTP 409 and 429 are never retried.
104
-
105
168
  ```ts
106
169
  import {
107
170
  TrafficWarApiError,
@@ -111,8 +174,10 @@ import {
111
174
  TrafficWarValidationError,
112
175
  } from "@trafficwar/node";
113
176
 
177
+ trafficwar.capture({ event: "task.failed", status_code: 500 });
178
+
114
179
  try {
115
- await trafficwar.capture({ event: "task.failed", status_code: 500 });
180
+ await trafficwar.flush();
116
181
  } catch (error) {
117
182
  if (error instanceof TrafficWarRateLimitError) {
118
183
  console.error(error.period, error.remainingEvents, error.retryAfterSeconds);
@@ -129,11 +194,11 @@ try {
129
194
  }
130
195
  ```
131
196
 
132
- Request errors retain the idempotency key. HTTP and protocol errors also retain
133
- the status, parsed response details, `Retry-After` as `retryAfterSeconds`, and
134
- the ingest ID when supplied by TrafficWar. Rate-limit errors additionally map
135
- `period`, `used`, `limit`, `remainingEvents`, `batchEvents`, and
136
- `retryAfterSecs`.
197
+ Delivery errors retain the batch's internal idempotency key. HTTP and protocol
198
+ errors also retain the status, parsed response details, `Retry-After` as
199
+ `retryAfterSeconds`, and the ingest ID when supplied by TrafficWar. Rate-limit
200
+ errors additionally map `period`, `used`, `limit`, `remainingEvents`,
201
+ `batchEvents`, and `retryAfterSecs`.
137
202
 
138
203
  CommonJS is also supported:
139
204