@trafficwar/node 4.0.0 → 5.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/AGENTS.md CHANGED
@@ -21,16 +21,15 @@ application. Installing the package alone does not capture requests.
21
21
  or flush the shared client on every request. Do not exit before shutdown finishes.
22
22
  - Omit `event_id` to use the generated UUIDv7. Do not reuse IDs across
23
23
  distinct events. Spans share `trace_id`, not `event_id`.
24
+ - Supply `event`, `label`, `source`, `operation_type`, `span_kind`, `timestamp`, and `latency_ms` on every event. Identity strings must be non-blank; latency must be finite and nonnegative. Record the actual start before work and measure duration with a monotonic clock; there is no timestamp default. Do not fill missing measurements with capture time or zero to pass validation.
25
+ - HTTP events require `http_method`. HTTP events and `external` events carrying `http_method` require the actual `status_code`, or a non-blank `error`/`error_code` when no response exists. Include the method on outbound HTTP calls; do not omit it to bypass outcome validation.
24
26
 
25
27
  ## Automatic observed pairs
26
28
 
27
29
  - Accepted captures automatically discover exact event/label pairs. Captured
28
30
  values are never rewritten or pinned to a code location. A shared wrapper
29
31
  can send different categories and labels on every call, as can batch slots.
30
- - Only an entire call that passes event validation, duplicate-ID checks and
31
- queue capacity teaches pairs. Missing labels and strings unsuitable for the
32
- catalog do not block otherwise valid event delivery. Event validation is
33
- unchanged: supplied non-string labels are still invalid event fields.
32
+ - Only an entire call that passes event validation, duplicate-ID checks and queue capacity teaches pairs. Missing, blank, and non-string labels fail validation. Non-blank strings exceeding catalog limits still deliver events but do not register pairs.
34
33
  - Register only non-blank event/label strings, at most 128 Unicode code points
35
34
  each, with no control characters. Preserve case and whitespace exactly;
36
35
  identity is the pair, not a concatenation of its values or their cross product.
@@ -109,10 +108,9 @@ trafficwar.capture({
109
108
 
110
109
  ## Traces and errors
111
110
 
112
- - Spans for one request share `trace_id` and `label`. Measure durations with
111
+ - Spans for one request must share a non-blank `trace_id` and the same `label`; propagate one request-level ID, never generate an independent ID for each span. Standalone events may omit `trace_id`; a batch alone does not imply a trace. Measure durations with
113
112
  a monotonic clock; `timestamp` is the actual span start as a `Date`, RFC3339
114
- string, or integer epoch milliseconds. If captured after completion,
115
- default capture-time timestamps do not describe the span's start.
113
+ string, or integer epoch milliseconds, not capture time after completion.
116
114
  - Keep inclusive durations nested. Emit dependency spans first, then the
117
115
  server span, then an edge span if one was actually measured. Do not invent
118
116
  browser latency or emit a synthetic edge span solely to populate the map.
package/README.md CHANGED
@@ -28,6 +28,8 @@ const trafficwar = new TrafficWar({
28
28
  },
29
29
  });
30
30
 
31
+ // Example measured request start and duration; use your handler's real measurements.
32
+ const requestStartedAt = new Date(Date.now() - 184);
31
33
  trafficwar.capture({
32
34
  event: "http",
33
35
  http_method: "POST",
@@ -37,6 +39,7 @@ trafficwar.capture({
37
39
  span_kind: "server",
38
40
  operation_type: "route.handler",
39
41
  status_code: 200,
42
+ timestamp: requestStartedAt,
40
43
  latency_ms: 184.2,
41
44
  distinct_id: "usr_7f3a91c2",
42
45
  properties: {
@@ -58,11 +61,11 @@ are never rewritten, including calls through shared wrappers. Registration is
58
61
  memory-only, sends unsent deltas and has no startup inventory, source scanning
59
62
  or persistence. See [Automatic observed event/label registration](#automatic-observed-eventlabel-registration).
60
63
 
61
- `Date` timestamps are serialized as RFC3339 without changing the caller's
62
- object. String timestamps must be RFC3339; numeric timestamps are integer epoch
63
- milliseconds. If `timestamp` is omitted, the SDK sets it to the current time at
64
- capture, which is right for a standalone event and wrong for a trace captured
65
- after the request has already finished.
64
+ Every event requires `event`, `label`, `source`, `operation_type`, `span_kind`, `timestamp`, and `latency_ms`. The four identity strings must be non-blank; values are preserved, not trimmed or rewritten. Latency must be finite and ≥ 0. Missing fields reject the whole capture call before enqueue or catalog discovery.
65
+
66
+ `timestamp` is the actual span start, with no capture-time default. `Date` values are serialized as RFC3339 without changing the caller's object; strings must be RFC3339 and numbers must be integer epoch milliseconds.
67
+
68
+ HTTP events require `http_method`. HTTP events, and `external` events carrying `http_method`, require `status_code` or a non-blank `error`/`error_code` for failures without a response. Send the real response status when available; never fabricate one for a network failure. HTTP category checks ignore case and surrounding whitespace. Related spans must share a non-blank `trace_id`; it remains optional at runtime because a batch can contain independent events.
66
69
 
67
70
  ## Automatic batching
68
71
 
@@ -101,15 +104,22 @@ const trafficwar = new TrafficWar({
101
104
  ### Automatic observed event/label registration
102
105
 
103
106
  ```ts
107
+ import { TrafficWar, type TrafficWarEvent } from "@trafficwar/node";
108
+
104
109
  const trafficwar = new TrafficWar({
105
110
  apiKey: process.env.TRAFFICWAR_API_KEY!,
106
111
  });
107
112
 
108
- function captureWork(event: string, label: string, latency_ms: number) {
109
- trafficwar.capture({ event, label, latency_ms });
113
+ function captureWork(input: TrafficWarEvent) {
114
+ trafficwar.capture(input);
110
115
  }
111
- captureWork("database", "Checkout", 12);
112
- captureWork("redis", "Different label", 29);
116
+ // Illustrative timings; supply actual measured span starts and durations.
117
+ captureWork({ event: "database", label: "Checkout", source: "db-primary",
118
+ operation_type: "postgres.select", span_kind: "client",
119
+ timestamp: new Date(Date.now() - 12), latency_ms: 12 });
120
+ captureWork({ event: "redis", label: "Different label", source: "redis-1",
121
+ operation_type: "redis.get", span_kind: "client",
122
+ timestamp: new Date(Date.now() - 29), latency_ms: 29 });
113
123
  // Emits database / Checkout and redis / Different label, unchanged.
114
124
  ```
115
125
 
@@ -126,10 +136,10 @@ captureWork("redis", "Different label", 29);
126
136
  station metadata. The backend adds/deduplicates instead of replacing the
127
137
  service list, so replicas do not need complete-list coordination.
128
138
  - Registration requires non-blank strings of at most 128 Unicode code points
129
- without controls. Case and whitespace are preserved exactly. Missing labels,
130
- empty/blank labels, overly long strings and control-containing strings are
131
- skipped for catalog purposes but do not block otherwise valid events. Event
132
- validation remains unchanged (a supplied non-string label is not valid).
139
+ without controls. Case and whitespace are preserved exactly. Overly long
140
+ strings and control-containing strings are skipped for catalog purposes but
141
+ do not block otherwise valid events. Missing, blank, or non-string labels
142
+ fail event validation before discovery.
133
143
  - There is no source scanning, explicit catalog, strict/static switch,
134
144
  capture-location pinning, filesystem access, JSON persistence, API polling,
135
145
  startup registration or first-value rewriting. Remove obsolete `catalog`,
@@ -171,7 +181,7 @@ the human route name (`Checkout`), `path` for the route URL
171
181
  normalized to uppercase and must be a 1–64-character RFC HTTP token. Spans
172
182
  of one request share `trace_id`. `span_kind` is one of `server`, `client`,
173
183
  `producer`, `consumer`, or `internal`, lowercase; any other value is
174
- discarded. It does not replace `source`, and it is not decorative: `event`,
184
+ rejected. It does not replace `source`, and it is not decorative: `event`,
175
185
  `source`, and `span_kind` are the three fields that place a span on a tier.
176
186
 
177
187
  ## Traces and tiers
@@ -210,10 +220,7 @@ from `event` and `source`, so `db-primary`, `redis-1`, `receipts.ovh-s3`, and
210
220
 
211
221
  Emit dependency spans first and the edge span last, and keep inclusive
212
222
  durations nested: the sum of the dependency spans must not exceed the server
213
- span, which must not exceed the client span. Set `timestamp` on every span of a
214
- trace. A server normally captures all of its spans after the request has
215
- finished, and the default capture-time timestamp would collapse them onto one
216
- instant, leaving the waterfall with no chronological axis.
223
+ span, which must not exceed the client span. Set `timestamp` to each span's actual start, not the time at which the completed trace is captured, so the waterfall retains its chronological axis.
217
224
 
218
225
  ```ts
219
226
  const trace_id = crypto.randomUUID();
@@ -251,8 +258,7 @@ That trace renders as one journey: an edge station for `Checkout` with
251
258
  `https://app.example.com` as its caller, a backend station for `Checkout`
252
259
  served by `backend-a`, and four infrastructure stations beneath it.
253
260
 
254
- A single-span request needs none of this. One `http` span with
255
- `span_kind: "server"` is a complete, valid event.
261
+ A single-span request can send one complete `http` server event with all required fields; it does not need synthetic dependency or edge spans.
256
262
 
257
263
  ### Edge spans emitted by a server
258
264
 
@@ -260,8 +266,7 @@ A server cannot measure a browser's round trip. If you emit the edge span from
260
266
  your backend, make it the widest interval you actually measured — the full
261
267
  server-side hop including routing and middleware — and let the server span
262
268
  cover only the handler. Do not invent a client round trip, and do not drop
263
- `latency_ms` to sidestep the problem: an absent value is stored as `0` and
264
- enters the latency histogram. If you have nothing wider than the handler to
269
+ `latency_ms` to sidestep the problem: missing latency is rejected. If you have nothing wider than the handler to
265
270
  report, send the server span alone. A trace does not require an edge span.
266
271
 
267
272
  ### Two cautions
@@ -282,6 +287,9 @@ trafficwar.capture({
282
287
  label: "Route planner",
283
288
  span_kind: "client",
284
289
  operation_type: "google.routes.compute",
290
+ timestamp: new Date(Date.now() - 13),
291
+ http_method: "POST",
292
+ status_code: 200,
285
293
  latency_ms: 13,
286
294
  });
287
295
  ```
@@ -302,6 +310,8 @@ Send application failures with first-class outcome fields and keep the full
302
310
  stack trace in `properties`:
303
311
 
304
312
  ```ts
313
+ const requestStartedAt = new Date();
314
+ const started = performance.now();
305
315
  try {
306
316
  await submitOrder();
307
317
  } catch (caught) {
@@ -313,6 +323,9 @@ try {
313
323
  path: "/v1/checkout",
314
324
  source: "backend-a",
315
325
  span_kind: "server",
326
+ operation_type: "route.handler",
327
+ timestamp: requestStartedAt,
328
+ latency_ms: performance.now() - started,
316
329
  http_method: "POST",
317
330
  status_code: 500,
318
331
  error: error.message,
@@ -415,7 +428,9 @@ import {
415
428
  TrafficWarValidationError,
416
429
  } from "@trafficwar/node";
417
430
 
418
- trafficwar.capture({ event: "http", label: "Checkout", status_code: 500 });
431
+ trafficwar.capture({ event: "http", label: "Checkout", source: "backend-a",
432
+ span_kind: "server", operation_type: "route.handler", http_method: "POST",
433
+ timestamp: new Date(Date.now() - 184), latency_ms: 184, status_code: 500 });
419
434
 
420
435
  try {
421
436
  await trafficwar.close();
package/dist/index.cjs CHANGED
@@ -301,12 +301,14 @@ function normalizeEvent(input, path, idempotencyKey) {
301
301
  normalized[key] = value;
302
302
  }
303
303
  }
304
- if (typeof normalized.event !== "string" || normalized.event.trim().length === 0) {
305
- throw validationError(
306
- `${path}.event must be a non-empty string`,
307
- `${path}.event`,
308
- idempotencyKey
309
- );
304
+ for (const field of ["event", "label", "source", "operation_type"]) {
305
+ if (typeof normalized[field] !== "string" || normalized[field].trim().length === 0) {
306
+ throw validationError(
307
+ `${path}.${field} must be a non-empty string`,
308
+ `${path}.${field}`,
309
+ idempotencyKey
310
+ );
311
+ }
310
312
  }
311
313
  for (const field of FORBIDDEN_IDENTITY_FIELDS) {
312
314
  if (Object.hasOwn(normalized, field)) {
@@ -326,18 +328,14 @@ function normalizeEvent(input, path, idempotencyKey) {
326
328
  );
327
329
  }
328
330
  }
329
- if (Object.hasOwn(normalized, "timestamp")) {
330
- normalized.timestamp = normalizeTimestamp(
331
- normalized.timestamp,
332
- `${path}.timestamp`,
333
- idempotencyKey
334
- );
335
- } else {
336
- normalized.timestamp = (/* @__PURE__ */ new Date()).toISOString();
337
- }
338
- if (Object.hasOwn(normalized, "latency_ms") && (typeof normalized.latency_ms !== "number" || !Number.isFinite(normalized.latency_ms))) {
331
+ normalized.timestamp = normalizeTimestamp(
332
+ normalized.timestamp,
333
+ `${path}.timestamp`,
334
+ idempotencyKey
335
+ );
336
+ if (typeof normalized.latency_ms !== "number" || !Number.isFinite(normalized.latency_ms) || normalized.latency_ms < 0) {
339
337
  throw validationError(
340
- `${path}.latency_ms must be a finite number`,
338
+ `${path}.latency_ms must be a finite nonnegative number`,
341
339
  `${path}.latency_ms`,
342
340
  idempotencyKey
343
341
  );
@@ -349,7 +347,8 @@ function normalizeEvent(input, path, idempotencyKey) {
349
347
  idempotencyKey
350
348
  );
351
349
  }
352
- if (httpMethodProvided) {
350
+ const category = normalized.event.trim().toLowerCase();
351
+ if (httpMethodProvided || category === "http") {
353
352
  normalized.http_method = normalizeHttpMethod(
354
353
  normalized.http_method,
355
354
  `${path}.http_method`,
@@ -365,13 +364,20 @@ function normalizeEvent(input, path, idempotencyKey) {
365
364
  );
366
365
  }
367
366
  }
368
- if (Object.hasOwn(normalized, "span_kind") && (typeof normalized.span_kind !== "string" || !SPAN_KINDS.has(normalized.span_kind))) {
367
+ if (typeof normalized.span_kind !== "string" || !SPAN_KINDS.has(normalized.span_kind)) {
369
368
  throw validationError(
370
369
  `${path}.span_kind must be server, client, producer, consumer, or internal`,
371
370
  `${path}.span_kind`,
372
371
  idempotencyKey
373
372
  );
374
373
  }
374
+ if ((category === "http" || category === "external" && httpMethodProvided) && !Object.hasOwn(normalized, "status_code") && !(typeof normalized.error === "string" && normalized.error.trim()) && !(typeof normalized.error_code === "string" && normalized.error_code.trim())) {
375
+ throw validationError(
376
+ `${path}.status_code is required for HTTP responses; use error or error_code for a failure without a response`,
377
+ `${path}.status_code`,
378
+ idempotencyKey
379
+ );
380
+ }
375
381
  try {
376
382
  return snapshotJsonValue(
377
383
  normalized,
@@ -590,7 +596,7 @@ function uuidv7() {
590
596
 
591
597
  // package.json
592
598
  var package_default = {
593
- version: "4.0.0"};
599
+ version: "5.0.0"};
594
600
 
595
601
  // src/client.ts
596
602
  var TRAFFICWAR_DEFAULT_BASE_URL = "https://ingest.trafficwar.tech";