@trafficwar/node 2.1.1 → 2.2.1

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
@@ -25,19 +25,51 @@ const trafficwar = new TrafficWar({
25
25
  });
26
26
 
27
27
  trafficwar.capture({
28
- event: "checkout.completed",
28
+ event: "http",
29
+ http_method: "GET",
30
+ label: "Checkout",
31
+ path: "/v1/checkout",
32
+ source: "backend-a",
33
+ operation_type: "route.handler",
29
34
  latency_ms: 184.2,
30
- status_code: 200,
31
- source: "checkout-api",
35
+ distinct_id: "usr_7f3a91c2",
36
+ trace_id: "tr_1",
32
37
  properties: {
33
- orderId: "ord_123",
34
- total: 49.95,
38
+ device_id: "dev_0198e743-a2c4-7c21",
35
39
  },
36
40
  });
37
41
 
38
42
  trafficwar.capture([
39
- { event: "job.started", source: "worker" },
40
- { event: "job.finished", source: "worker", latency_ms: 42 },
43
+ {
44
+ event: "database",
45
+ label: "Checkout",
46
+ path: "/v1/checkout",
47
+ source: "db-primary",
48
+ operation_type: "postgres.select",
49
+ latency_ms: 48.2,
50
+ distinct_id: "usr_7f3a91c2",
51
+ trace_id: "tr_1",
52
+ },
53
+ {
54
+ event: "redis",
55
+ label: "Checkout",
56
+ path: "/v1/checkout",
57
+ source: "redis-1",
58
+ operation_type: "redis.get",
59
+ latency_ms: 1.4,
60
+ distinct_id: "usr_7f3a91c2",
61
+ trace_id: "tr_1",
62
+ },
63
+ {
64
+ event: "s3",
65
+ label: "Checkout",
66
+ path: "/v1/checkout",
67
+ source: "receipts.ovh-s3",
68
+ operation_type: "s3.put_object",
69
+ latency_ms: 22.0,
70
+ distinct_id: "usr_7f3a91c2",
71
+ trace_id: "tr_1",
72
+ },
41
73
  ]);
42
74
  ```
43
75
 
@@ -88,28 +120,72 @@ The SDK generates a process-monotonic RFC 9562 UUIDv7 `event_id` for each event
88
120
  that omits one. A caller may override it with any valid UUID. Caller-owned
89
121
  objects are never modified.
90
122
 
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`.
123
+ Canonical `event` categories are `http`, `database`, `redis`, and `s3`. Use
124
+ `source` for the emitting host or dependency (`backend-a`, `db-primary`,
125
+ `redis-1`, `ovh-s3`, `https://app.example.com`), `label` for the human route
126
+ name (`Checkout`), `path` for the route URL (`/v1/checkout`), and
127
+ `operation_type` for the concrete work (`route.handler`, `postgres.select`,
128
+ `redis.get`, `s3.get_object`). For HTTP events, `http_method` is trimmed and
129
+ normalized to uppercase and must be a 1–64-character RFC HTTP token. Spans of
130
+ one request share `trace_id`. `span_kind` is separate, optional tracing
131
+ semantics (`server`, `client`, `producer`, `consumer`, or `internal`); it does
132
+ not replace `source`.
95
133
 
96
- ## Flush results and shutdown
134
+ ## Actor identity and application errors
97
135
 
98
- Call `flush` when an application needs an acknowledgement before continuing:
136
+ Use a stable pseudonymous `distinct_id` derived by your backend so one actor
137
+ keeps the same identity across devices. Prefer an opaque internal ID or a
138
+ backend-only HMAC; do not send a raw email address. Keep a separate
139
+ installation identifier such as `device_id` in `properties` when device-level
140
+ investigation matters.
99
141
 
100
- ```ts
101
- trafficwar.capture({ event: "deployment.finished", source: "release-worker" });
142
+ Send application failures with first-class outcome fields and keep the full
143
+ stack trace in `properties`:
102
144
 
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);
145
+ ```ts
146
+ try {
147
+ await submitOrder();
148
+ } catch (caught) {
149
+ const error = caught instanceof Error ? caught : new Error(String(caught));
150
+
151
+ trafficwar.capture({
152
+ event: "http",
153
+ label: "/checkout",
154
+ http_method: "POST",
155
+ status_code: 500,
156
+ error: error.message,
157
+ error_code: "CHECKOUT_FAILED",
158
+ distinct_id: "usr_7f3a91c2",
159
+ properties: {
160
+ exception_type: error.name,
161
+ stack_trace: error.stack ?? error.message,
162
+ cause: "connection deadline exceeded",
163
+ },
164
+ });
107
165
  }
108
166
  ```
109
167
 
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.
168
+ `properties` is opaque and does not set `is_error`. Always send `error`,
169
+ `error_code`, or a `status_code` of 400 or greater with diagnostic properties.
170
+
171
+ For S3, a provider alias such as `ovh-s3`, `aws-s3`, or `minio` creates one
172
+ provider station. Prefix it as `<bucket>.<provider>` only when the map should
173
+ separate buckets: `assets.ovh-s3` and `archive.ovh-s3` become distinct
174
+ stations, while `operation_type` values such as `s3.get_object` and
175
+ `s3.put_object` remain operation dots. The final dot is the reserved
176
+ bucket/provider separator, so provider aliases must not contain dots.
177
+
178
+ The package exports `EventCategory`, `OperationType`, `KnownS3Provider`, and
179
+ `S3Source` for typed wrappers. These types suggest the canonical values in
180
+ editors while still accepting custom event, operation, and provider aliases:
181
+
182
+ ```ts
183
+ import type { S3Source } from "@trafficwar/node";
184
+
185
+ const assets: S3Source = "assets.ovh-s3";
186
+ ```
187
+
188
+ ## Shutdown
113
189
 
114
190
  Always await `close` during graceful application shutdown:
115
191
 
@@ -118,9 +194,11 @@ const result = await trafficwar.close();
118
194
  console.log(result.accepted, result.batches.length);
119
195
  ```
120
196
 
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.
197
+ `close` stops automatic work and sends every queued event. It returns an
198
+ aggregate `FlushResult`: `accepted` is the number of events drained, and
199
+ `batches` contains one `IngestResult` per HTTP request. The automatic timer is
200
+ unref'ed and will not keep Node running, so exiting without awaiting `close`
201
+ can lose pending events.
124
202
 
125
203
  `captureBatch(events)` remains as a deprecated compatibility alias. New code
126
204
  passes the non-empty array directly to `capture(events)`.
@@ -139,8 +217,8 @@ up to 60 seconds; larger values are surfaced immediately as API errors. HTTP
139
217
 
140
218
  An automatic delivery failure invokes optional `onError`. The handler is
141
219
  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.
220
+ attempt or `close` retries that same batch, and `close` surfaces an error if
221
+ delivery still fails.
144
222
 
145
223
  ## Client options
146
224
 
@@ -177,7 +255,7 @@ import {
177
255
  trafficwar.capture({ event: "task.failed", status_code: 500 });
178
256
 
179
257
  try {
180
- await trafficwar.flush();
258
+ await trafficwar.close();
181
259
  } catch (error) {
182
260
  if (error instanceof TrafficWarRateLimitError) {
183
261
  console.error(error.period, error.remainingEvents, error.retryAfterSeconds);
package/dist/index.cjs CHANGED
@@ -80,6 +80,7 @@ var TrafficWarProtocolError = class extends TrafficWarError {
80
80
  };
81
81
  var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
82
82
  var RFC3339_PATTERN = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,9})?(?:Z|[+-](\d{2}):(\d{2}))$/i;
83
+ var HTTP_TOKEN_PATTERN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
83
84
  var STRING_FIELDS = [
84
85
  "user_agent",
85
86
  "label",
@@ -253,6 +254,24 @@ function normalizeTimestamp(timestamp, path, idempotencyKey) {
253
254
  }
254
255
  return timestamp;
255
256
  }
257
+ function normalizeHttpMethod(value, path, idempotencyKey) {
258
+ if (typeof value !== "string") {
259
+ throw validationError(
260
+ `${path} must be an RFC HTTP token from 1 to 64 characters`,
261
+ path,
262
+ idempotencyKey
263
+ );
264
+ }
265
+ const method = value.trim().toUpperCase();
266
+ if (method.length < 1 || method.length > 64 || !HTTP_TOKEN_PATTERN.test(method)) {
267
+ throw validationError(
268
+ `${path} must be an RFC HTTP token from 1 to 64 characters`,
269
+ path,
270
+ idempotencyKey
271
+ );
272
+ }
273
+ return method;
274
+ }
256
275
  function normalizeEvent(input, path, idempotencyKey) {
257
276
  if (input === null || typeof input !== "object" || Array.isArray(input)) {
258
277
  throw validationError(
@@ -273,7 +292,11 @@ function normalizeEvent(input, path, idempotencyKey) {
273
292
  );
274
293
  }
275
294
  const normalized = {};
295
+ let httpMethodProvided = false;
276
296
  for (const [key, value] of entries) {
297
+ if (key === "http_method") {
298
+ httpMethodProvided = true;
299
+ }
277
300
  if (value !== void 0) {
278
301
  normalized[key] = value;
279
302
  }
@@ -326,6 +349,13 @@ function normalizeEvent(input, path, idempotencyKey) {
326
349
  idempotencyKey
327
350
  );
328
351
  }
352
+ if (httpMethodProvided) {
353
+ normalized.http_method = normalizeHttpMethod(
354
+ normalized.http_method,
355
+ `${path}.http_method`,
356
+ idempotencyKey
357
+ );
358
+ }
329
359
  for (const field of STRING_FIELDS) {
330
360
  if (Object.hasOwn(normalized, field) && typeof normalized[field] !== "string") {
331
361
  throw validationError(
@@ -450,7 +480,7 @@ function uuidv7() {
450
480
 
451
481
  // package.json
452
482
  var package_default = {
453
- version: "2.1.1"};
483
+ version: "2.2.1"};
454
484
 
455
485
  // src/client.ts
456
486
  var TRAFFICWAR_DEFAULT_BASE_URL = "https://ingest.trafficwar.tech";