trafficwar 2.0.0__tar.gz
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.
- trafficwar-2.0.0/.gitignore +9 -0
- trafficwar-2.0.0/LICENSE +21 -0
- trafficwar-2.0.0/PKG-INFO +536 -0
- trafficwar-2.0.0/README.md +480 -0
- trafficwar-2.0.0/pyproject.toml +94 -0
- trafficwar-2.0.0/src/trafficwar/__init__.py +73 -0
- trafficwar-2.0.0/src/trafficwar/_async_client.py +444 -0
- trafficwar-2.0.0/src/trafficwar/_base.py +595 -0
- trafficwar-2.0.0/src/trafficwar/_client.py +436 -0
- trafficwar-2.0.0/src/trafficwar/_errors.py +108 -0
- trafficwar-2.0.0/src/trafficwar/_models.py +78 -0
- trafficwar-2.0.0/src/trafficwar/_uuidv7.py +75 -0
- trafficwar-2.0.0/src/trafficwar/_version.py +1 -0
- trafficwar-2.0.0/src/trafficwar/py.typed +1 -0
- trafficwar-2.0.0/tests/event_fixture.py +12 -0
- trafficwar-2.0.0/tests/test_async.py +616 -0
- trafficwar-2.0.0/tests/test_required_contract.py +135 -0
- trafficwar-2.0.0/tests/test_sync.py +726 -0
- trafficwar-2.0.0/tests/test_uuidv7.py +106 -0
- trafficwar-2.0.0/tests/test_validation.py +487 -0
trafficwar-2.0.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 TrafficWar
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,536 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: trafficwar
|
|
3
|
+
Version: 2.0.0
|
|
4
|
+
Summary: Official Python server SDK for TrafficWar event ingestion
|
|
5
|
+
Project-URL: Homepage, https://trafficwar.tech
|
|
6
|
+
Project-URL: Documentation, https://trafficwar.tech
|
|
7
|
+
Project-URL: Repository, https://github.com/moeelbadri/trafficwar-sdks
|
|
8
|
+
Project-URL: Issues, https://github.com/moeelbadri/trafficwar-sdks/issues
|
|
9
|
+
Author: TrafficWar
|
|
10
|
+
License: MIT License
|
|
11
|
+
|
|
12
|
+
Copyright (c) 2026 TrafficWar
|
|
13
|
+
|
|
14
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
15
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
16
|
+
in the Software without restriction, including without limitation the rights
|
|
17
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
18
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
19
|
+
furnished to do so, subject to the following conditions:
|
|
20
|
+
|
|
21
|
+
The above copyright notice and this permission notice shall be included in all
|
|
22
|
+
copies or substantial portions of the Software.
|
|
23
|
+
|
|
24
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
25
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
26
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
27
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
28
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
29
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
30
|
+
SOFTWARE.
|
|
31
|
+
License-File: LICENSE
|
|
32
|
+
Keywords: analytics,events,observability,trafficwar
|
|
33
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
34
|
+
Classifier: Intended Audience :: Developers
|
|
35
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
36
|
+
Classifier: Operating System :: OS Independent
|
|
37
|
+
Classifier: Programming Language :: Python :: 3
|
|
38
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
39
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
40
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
41
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
42
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
43
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
44
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
45
|
+
Classifier: Typing :: Typed
|
|
46
|
+
Requires-Python: >=3.9
|
|
47
|
+
Requires-Dist: httpx<1,>=0.28.1
|
|
48
|
+
Provides-Extra: dev
|
|
49
|
+
Requires-Dist: build>=1.2; extra == 'dev'
|
|
50
|
+
Requires-Dist: mypy<2,>=1.11; extra == 'dev'
|
|
51
|
+
Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
|
|
52
|
+
Requires-Dist: pytest>=8.3; extra == 'dev'
|
|
53
|
+
Requires-Dist: ruff>=0.9; extra == 'dev'
|
|
54
|
+
Requires-Dist: twine>=6; extra == 'dev'
|
|
55
|
+
Description-Content-Type: text/markdown
|
|
56
|
+
|
|
57
|
+
# TrafficWar Python SDK
|
|
58
|
+
|
|
59
|
+
Official, typed Python server SDK for durable event ingestion into
|
|
60
|
+
[TrafficWar](https://trafficwar.tech).
|
|
61
|
+
|
|
62
|
+
> **Breaking changes in 2.0.0:** capture uses automatic batching and requires
|
|
63
|
+
> complete event inputs. See [Event fields](#event-fields) and the lifecycle
|
|
64
|
+
> examples below before upgrading.
|
|
65
|
+
|
|
66
|
+
## Install
|
|
67
|
+
|
|
68
|
+
```bash
|
|
69
|
+
pip install trafficwar
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Python 3.9 or newer and HTTPX `>=0.28.1,<1` are supported.
|
|
73
|
+
|
|
74
|
+
## Synchronous client
|
|
75
|
+
|
|
76
|
+
The fixed durations and timestamp offsets in the examples below are illustrative.
|
|
77
|
+
In an integration, record each operation's actual start timestamp and measure its
|
|
78
|
+
elapsed duration with a monotonic clock; do not use capture time as the start of
|
|
79
|
+
an operation that has already finished or copy the sample durations.
|
|
80
|
+
|
|
81
|
+
```python
|
|
82
|
+
from datetime import datetime, timezone
|
|
83
|
+
|
|
84
|
+
from trafficwar import Event, TrafficWar
|
|
85
|
+
|
|
86
|
+
trafficwar = TrafficWar("tw_live_...")
|
|
87
|
+
try:
|
|
88
|
+
event: Event = {
|
|
89
|
+
"event": "http",
|
|
90
|
+
"timestamp": datetime.now(timezone.utc),
|
|
91
|
+
"http_method": "POST",
|
|
92
|
+
"label": "Checkout",
|
|
93
|
+
"path": "/v1/checkout",
|
|
94
|
+
"source": "backend-a",
|
|
95
|
+
"span_kind": "server",
|
|
96
|
+
"operation_type": "route.handler",
|
|
97
|
+
"status_code": 200,
|
|
98
|
+
"latency_ms": 184.2,
|
|
99
|
+
"distinct_id": "usr_7f3a91c2",
|
|
100
|
+
"properties": {
|
|
101
|
+
"device_id": "dev_0198e743-a2c4-7c21",
|
|
102
|
+
},
|
|
103
|
+
}
|
|
104
|
+
trafficwar.capture(event)
|
|
105
|
+
finally:
|
|
106
|
+
flushed = trafficwar.close()
|
|
107
|
+
|
|
108
|
+
print(flushed.accepted, len(flushed.batches))
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
Synchronous `capture` accepts one mapping or a non-empty iterable of mappings.
|
|
112
|
+
It validates, snapshots, and enqueues the input, then returns `None` without
|
|
113
|
+
waiting for the network. Reuse one thread-safe client across calls. It is also
|
|
114
|
+
a context manager; leaving the context calls `close()`.
|
|
115
|
+
|
|
116
|
+
## Asynchronous client
|
|
117
|
+
|
|
118
|
+
The array form may send related spans or independent events. For a trace, emit
|
|
119
|
+
dependency spans first and the edge span last, and set `timestamp` on every span; see
|
|
120
|
+
[Traces and tiers](#traces-and-tiers).
|
|
121
|
+
|
|
122
|
+
```python
|
|
123
|
+
import uuid
|
|
124
|
+
from datetime import datetime, timedelta, timezone
|
|
125
|
+
|
|
126
|
+
from trafficwar import AsyncTrafficWar
|
|
127
|
+
|
|
128
|
+
trafficwar = AsyncTrafficWar("tw_live_...")
|
|
129
|
+
started_at = datetime.now(timezone.utc)
|
|
130
|
+
trace_id = str(uuid.uuid4())
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def at(offset_ms: float) -> datetime:
|
|
134
|
+
return started_at + timedelta(milliseconds=offset_ms)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
common = {
|
|
138
|
+
"label": "Pricing",
|
|
139
|
+
"path": "/pricing",
|
|
140
|
+
"distinct_id": "usr_7f3a91c2",
|
|
141
|
+
"trace_id": trace_id,
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
try:
|
|
145
|
+
await trafficwar.capture(
|
|
146
|
+
[
|
|
147
|
+
{
|
|
148
|
+
**common,
|
|
149
|
+
"event": "database",
|
|
150
|
+
"source": "db-replica-1",
|
|
151
|
+
"operation_type": "postgres.select",
|
|
152
|
+
"span_kind": "client",
|
|
153
|
+
"timestamp": at(12),
|
|
154
|
+
"latency_ms": 6.1,
|
|
155
|
+
},
|
|
156
|
+
{
|
|
157
|
+
**common,
|
|
158
|
+
"event": "redis",
|
|
159
|
+
"source": "redis-1",
|
|
160
|
+
"operation_type": "redis.get",
|
|
161
|
+
"span_kind": "client",
|
|
162
|
+
"timestamp": at(20),
|
|
163
|
+
"latency_ms": 1.4,
|
|
164
|
+
},
|
|
165
|
+
{
|
|
166
|
+
**common,
|
|
167
|
+
"event": "s3",
|
|
168
|
+
"source": "assets.ovh-s3",
|
|
169
|
+
"operation_type": "s3.get_object",
|
|
170
|
+
"span_kind": "client",
|
|
171
|
+
"timestamp": at(25),
|
|
172
|
+
"latency_ms": 22.0,
|
|
173
|
+
},
|
|
174
|
+
{
|
|
175
|
+
**common,
|
|
176
|
+
"event": "external",
|
|
177
|
+
"source": "search-provider",
|
|
178
|
+
"operation_type": "search.query",
|
|
179
|
+
"span_kind": "client",
|
|
180
|
+
"timestamp": at(48),
|
|
181
|
+
"latency_ms": 12.0,
|
|
182
|
+
},
|
|
183
|
+
{
|
|
184
|
+
**common,
|
|
185
|
+
"event": "http",
|
|
186
|
+
"http_method": "GET",
|
|
187
|
+
"status_code": 200,
|
|
188
|
+
"source": "backend-a",
|
|
189
|
+
"operation_type": "route.handler",
|
|
190
|
+
"span_kind": "server",
|
|
191
|
+
"timestamp": at(5),
|
|
192
|
+
"latency_ms": 68.0,
|
|
193
|
+
},
|
|
194
|
+
{
|
|
195
|
+
**common,
|
|
196
|
+
"event": "http",
|
|
197
|
+
"http_method": "GET",
|
|
198
|
+
"status_code": 200,
|
|
199
|
+
"source": "https://app.example.com",
|
|
200
|
+
"operation_type": "http.request",
|
|
201
|
+
"span_kind": "client",
|
|
202
|
+
"timestamp": at(0),
|
|
203
|
+
"latency_ms": 82.4,
|
|
204
|
+
},
|
|
205
|
+
]
|
|
206
|
+
)
|
|
207
|
+
finally:
|
|
208
|
+
flushed = await trafficwar.aclose()
|
|
209
|
+
|
|
210
|
+
print(flushed.accepted, len(flushed.batches))
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
Async `await capture(...)` accepts the same single-event or non-empty iterable
|
|
214
|
+
input and waits only for validation and enqueueing. It does not wait for an
|
|
215
|
+
HTTP request or return an `IngestResult`. `AsyncTrafficWar` can also be used as
|
|
216
|
+
an async context manager.
|
|
217
|
+
|
|
218
|
+
## Automatic batching
|
|
219
|
+
|
|
220
|
+
The first queued event starts a one-second timer. A client flushes when that
|
|
221
|
+
timer expires or as soon as 10,000 events are pending. TrafficWar's fixed
|
|
222
|
+
server batch maximum is 10,000, so a larger queued iterable is split across
|
|
223
|
+
requests.
|
|
224
|
+
|
|
225
|
+
Every request is a bare JSON array sent to `/v1/server/batch`, including a
|
|
226
|
+
single-event capture. The queue holds at most 100,000 unacknowledged events by
|
|
227
|
+
default. Configure the timing and bound with `flush_interval` and
|
|
228
|
+
`max_queue_size`:
|
|
229
|
+
|
|
230
|
+
```python
|
|
231
|
+
client = TrafficWar(
|
|
232
|
+
"tw_live_...",
|
|
233
|
+
flush_interval=1.0,
|
|
234
|
+
max_queue_size=100_000,
|
|
235
|
+
)
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
If enqueueing would exceed the configured queue limit, `capture` raises
|
|
239
|
+
`ValidationError` and enqueues none of that call. Iterables are eagerly
|
|
240
|
+
consumed so callers can safely reuse or mutate their original objects after
|
|
241
|
+
`capture` returns.
|
|
242
|
+
|
|
243
|
+
## Event fields
|
|
244
|
+
|
|
245
|
+
`Event` is a `TypedDict` requiring all seven fields: `event`, `label`,
|
|
246
|
+
`source`, `operation_type`, `span_kind`, `timestamp`, and `latency_ms`.
|
|
247
|
+
The four identity strings must be nonblank. `span_kind` must be `server`,
|
|
248
|
+
`client`, `producer`, `consumer`, or `internal`. `latency_ms` must be finite
|
|
249
|
+
and non-negative (zero is valid). `timestamp` must be an explicit RFC3339
|
|
250
|
+
string, epoch milliseconds, or timezone-aware `datetime`; datetimes normalize
|
|
251
|
+
to UTC RFC3339. The SDK never supplies capture time for a missing timestamp.
|
|
252
|
+
|
|
253
|
+
Additional optional fields:
|
|
254
|
+
|
|
255
|
+
- `event_id`
|
|
256
|
+
- `properties` (JSON)
|
|
257
|
+
- `user_agent`, `ip`, `country`, `city`
|
|
258
|
+
- `trace_id`, `distinct_id`, `path`
|
|
259
|
+
- `http_method` (trimmed and normalized to uppercase; must be a
|
|
260
|
+
1–64-character RFC HTTP token)
|
|
261
|
+
- `error`, `exception`, `error_code`
|
|
262
|
+
- `status_code` (0–65535)
|
|
263
|
+
|
|
264
|
+
`event="http"` requires `http_method`. HTTP events and `external` events
|
|
265
|
+
with `http_method` require either a valid `status_code` or a nonblank `error`
|
|
266
|
+
or `error_code` for a network failure with no response. `exception` alone is
|
|
267
|
+
not an outcome. Category checks ignore case and surrounding whitespace but
|
|
268
|
+
do not rewrite `event`. Supplied status codes retain the 0–65535 range.
|
|
269
|
+
|
|
270
|
+
`trace_id` is optional at runtime: a batch alone does not imply a trace.
|
|
271
|
+
Related spans must share a nonblank real trace ID. Independent events may
|
|
272
|
+
omit it; the SDK never generates fake correlation IDs.
|
|
273
|
+
|
|
274
|
+
The SDK generates a process-monotonic RFC 9562 UUIDv7 `event_id` for each event
|
|
275
|
+
that omits one. A caller may override it with any valid UUID.
|
|
276
|
+
|
|
277
|
+
Canonical `event` categories are `http`, `database`, `redis`, `s3`, and
|
|
278
|
+
`external`. Use `external` for an outbound HTTP service that belongs on the
|
|
279
|
+
infrastructure tier. Use `source` for the emitting host or dependency
|
|
280
|
+
(`backend-a`, `db-primary`, `redis-1`, `ovh-s3`, `google-routes`), `label` for
|
|
281
|
+
the human route name (`Checkout`), `path` for the route URL
|
|
282
|
+
(`/v1/checkout`), and `operation_type` for the concrete work
|
|
283
|
+
(`route.handler`, `postgres.select`, `redis.get`, `s3.get_object`,
|
|
284
|
+
`google.routes.compute`). Spans of one request share `trace_id`. `span_kind`
|
|
285
|
+
does not replace `source`, and it is not decorative: `event`, `source`, and
|
|
286
|
+
`span_kind` are the three fields that place a span on a tier.
|
|
287
|
+
|
|
288
|
+
## Traces and tiers
|
|
289
|
+
|
|
290
|
+
Spans of one request share `trace_id` and `label`. There is no `span_id` or
|
|
291
|
+
`parent_span_id` on the wire, so TrafficWar places each span on a tier from its
|
|
292
|
+
own fields, in this order:
|
|
293
|
+
|
|
294
|
+
1. `event` is `database`, `redis`, `s3`, or `external` —
|
|
295
|
+
**infrastructure**.
|
|
296
|
+
2. `event` is `http` and `source` is an absolute `http(s)://` URL, or starts
|
|
297
|
+
with `web`, `browser`, `client`, `edge`, or `frontend` followed by a
|
|
298
|
+
separator or nothing (`web`, `web-eu`, `frontend.eu`, but not `webhooks`)
|
|
299
|
+
— **edge**.
|
|
300
|
+
3. `event` is `http` and `source` contains `api`, `backend`, or `server` as a
|
|
301
|
+
token delimited by `-`, `_`, or `.` — **backend**.
|
|
302
|
+
4. `event` is `http` and `span_kind` is `server` — **backend**; `client` —
|
|
303
|
+
**edge**.
|
|
304
|
+
5. Anything else — **edge**.
|
|
305
|
+
|
|
306
|
+
`source` is compared case-insensitively and is tested before `span_kind`, so a
|
|
307
|
+
`source` such as `api.example.com` or `backend-a` pins a span to the backend
|
|
308
|
+
tier regardless of its `span_kind`. Sending your own API hostname as the
|
|
309
|
+
`source` of a browser-facing span is the most common way to get a span on the
|
|
310
|
+
wrong tier. `operation_type` never affects tier placement; it names the
|
|
311
|
+
concrete activity. Only `server` and `client` select an HTTP tier:
|
|
312
|
+
`producer`, `consumer`, and `internal` fall through to rule 5, so an `http`
|
|
313
|
+
span with one of those kinds lands on the edge tier.
|
|
314
|
+
|
|
315
|
+
On the edge and backend tiers the station is named by `label`, and `source`
|
|
316
|
+
becomes an instance dot inside that station. Infrastructure stations are named
|
|
317
|
+
from `event` and `source`, so `db-replica-1`, `redis-1`, `assets.ovh-s3`, and
|
|
318
|
+
`search-provider` each get their own station.
|
|
319
|
+
|
|
320
|
+
Keep inclusive durations nested: the sum of the dependency spans must not
|
|
321
|
+
exceed the server span, which must not exceed the client span. Set `timestamp`
|
|
322
|
+
on every span of a trace. A server normally captures all of its spans after the
|
|
323
|
+
request has finished, and using capture time for each timestamp would collapse
|
|
324
|
+
them onto one instant, leaving the waterfall with no chronological axis. A
|
|
325
|
+
single-span request needs no correlation ID or additional spans, but still
|
|
326
|
+
requires all seven fields: `event`, `label`, `source`, `operation_type`,
|
|
327
|
+
`span_kind`, an explicit start `timestamp`, and measured `latency_ms`. An `http`
|
|
328
|
+
server span also requires `http_method` and either `status_code` or a nonblank
|
|
329
|
+
`error`/`error_code` when a network failure produced no response.
|
|
330
|
+
|
|
331
|
+
A server cannot measure a browser's round trip. If you emit the edge span from
|
|
332
|
+
your backend, make it the widest interval you actually measured — the full
|
|
333
|
+
server-side hop including routing and middleware — and let the server span
|
|
334
|
+
cover only the handler. Do not invent a client round trip, and do not drop
|
|
335
|
+
`latency_ms` to sidestep the problem: missing durations are rejected. If you
|
|
336
|
+
have nothing wider than the handler to report, send the server span alone.
|
|
337
|
+
|
|
338
|
+
Two cautions. `source` is part of the metric aggregation grain, so when you
|
|
339
|
+
derive it from `Origin` or `Referer`, match those caller-controlled values
|
|
340
|
+
against an allowlist of hostnames you expect and collapse the rest to a single
|
|
341
|
+
value such as `web-other`.
|
|
342
|
+
|
|
343
|
+
For an outbound third-party HTTP call, send `event="external"` with
|
|
344
|
+
`span_kind="client"`. Keep the provider in `source` and the API action in
|
|
345
|
+
`operation_type`; this creates a source-keyed infrastructure station. The
|
|
346
|
+
incoming caller remains an `http` client span. If a request has no trusted
|
|
347
|
+
`Origin` or `Referer`, use a stable value such as `web-direct`; never substitute
|
|
348
|
+
your own API `Host` header.
|
|
349
|
+
|
|
350
|
+
## Actor identity and application errors
|
|
351
|
+
|
|
352
|
+
Use a stable pseudonymous `distinct_id` derived by your backend so one actor
|
|
353
|
+
keeps the same identity across devices. Prefer an opaque internal ID or a
|
|
354
|
+
backend-only HMAC; do not send a raw email address. Keep a separate
|
|
355
|
+
installation identifier such as `device_id` in `properties` when device-level
|
|
356
|
+
investigation matters.
|
|
357
|
+
|
|
358
|
+
Send application failures with first-class outcome fields and keep the full
|
|
359
|
+
stack trace in `properties`:
|
|
360
|
+
|
|
361
|
+
```python
|
|
362
|
+
import traceback
|
|
363
|
+
from datetime import datetime, timezone
|
|
364
|
+
from time import perf_counter
|
|
365
|
+
|
|
366
|
+
started_at = datetime.now(timezone.utc)
|
|
367
|
+
started = perf_counter()
|
|
368
|
+
try:
|
|
369
|
+
submit_order()
|
|
370
|
+
except Exception as exc:
|
|
371
|
+
client.capture(
|
|
372
|
+
{
|
|
373
|
+
"event": "http",
|
|
374
|
+
"source": "backend-a",
|
|
375
|
+
"operation_type": "route.handler",
|
|
376
|
+
"span_kind": "server",
|
|
377
|
+
"timestamp": started_at,
|
|
378
|
+
"latency_ms": (perf_counter() - started) * 1000,
|
|
379
|
+
"label": "/checkout",
|
|
380
|
+
"http_method": "POST",
|
|
381
|
+
"status_code": 500,
|
|
382
|
+
"error": str(exc),
|
|
383
|
+
"error_code": type(exc).__name__,
|
|
384
|
+
"distinct_id": "usr_7f3a91c2",
|
|
385
|
+
"properties": {
|
|
386
|
+
"exception_type": type(exc).__name__,
|
|
387
|
+
"stack_trace": "".join(
|
|
388
|
+
traceback.format_exception(type(exc), exc, exc.__traceback__)
|
|
389
|
+
),
|
|
390
|
+
"cause": str(exc.__cause__) if exc.__cause__ else "",
|
|
391
|
+
},
|
|
392
|
+
}
|
|
393
|
+
)
|
|
394
|
+
```
|
|
395
|
+
|
|
396
|
+
`properties` is opaque and does not set `is_error`. Always send `error`,
|
|
397
|
+
`error_code`, or a `status_code` of 400 or greater with diagnostic properties.
|
|
398
|
+
|
|
399
|
+
For S3, a provider alias such as `ovh-s3`, `aws-s3`, or `minio` creates one
|
|
400
|
+
provider station. Prefix it as `<bucket>.<provider>` only when the map should
|
|
401
|
+
separate buckets: `assets.ovh-s3` and `archive.ovh-s3` become distinct
|
|
402
|
+
stations, while `operation_type` values such as `s3.get_object` and
|
|
403
|
+
`s3.put_object` remain operation dots. The final dot is the reserved
|
|
404
|
+
bucket/provider separator, so provider aliases must not contain dots.
|
|
405
|
+
|
|
406
|
+
Caller-owned mappings are never modified. JSON is serialized once in compact,
|
|
407
|
+
deterministic UTF-8 form. Automatic gzip starts at 1 KiB; configure
|
|
408
|
+
`compression="gzip"` or `compression="none"` to force either mode:
|
|
409
|
+
|
|
410
|
+
```python
|
|
411
|
+
client = TrafficWar(
|
|
412
|
+
"tw_live_...",
|
|
413
|
+
timeout=30,
|
|
414
|
+
max_retries=3,
|
|
415
|
+
compression="auto",
|
|
416
|
+
compression_threshold=1024,
|
|
417
|
+
flush_interval=1.0,
|
|
418
|
+
max_queue_size=100_000,
|
|
419
|
+
on_error=lambda error: print(f"automatic TrafficWar flush failed: {error}"),
|
|
420
|
+
)
|
|
421
|
+
```
|
|
422
|
+
|
|
423
|
+
The decoded JSON limit is 8 MiB and the transmitted-body limit is 2 MiB.
|
|
424
|
+
|
|
425
|
+
## Shutdown
|
|
426
|
+
|
|
427
|
+
Always call synchronous `close()` or await async `aclose()` during graceful
|
|
428
|
+
application shutdown:
|
|
429
|
+
|
|
430
|
+
```python
|
|
431
|
+
result = client.close()
|
|
432
|
+
print(result.accepted, len(result.batches))
|
|
433
|
+
```
|
|
434
|
+
|
|
435
|
+
Close stops automatic work and sends every queued event. It returns an
|
|
436
|
+
aggregate `FlushResult`: `accepted` is the number of events drained, and
|
|
437
|
+
`batches` contains one `IngestResult` per HTTP request. The synchronous worker
|
|
438
|
+
is a daemon thread, and the async client owns a background task; exiting
|
|
439
|
+
without closing can lose pending events or leak task/resource warnings.
|
|
440
|
+
|
|
441
|
+
`capture_batch(events)` remains as a deprecated compatibility alias. New code
|
|
442
|
+
passes the non-empty iterable directly to `capture(events)`.
|
|
443
|
+
|
|
444
|
+
## Retries and errors
|
|
445
|
+
|
|
446
|
+
The SDK prepares each HTTP batch once. Its compact JSON bytes, optional gzip
|
|
447
|
+
bytes, generated event IDs, and internal idempotency key stay stable across
|
|
448
|
+
bounded retries. Idempotency is an internal delivery detail rather than part of
|
|
449
|
+
the `capture` API.
|
|
450
|
+
|
|
451
|
+
The SDK retries transport and timeout failures plus HTTP 408, 425, 500, 502,
|
|
452
|
+
503, and 504 responses with exponential jitter and `Retry-After` support. The
|
|
453
|
+
default is three retries after the initial attempt. A retryable response asking
|
|
454
|
+
for more than 60 seconds is surfaced immediately as `ServerError`. HTTP 409 and
|
|
455
|
+
quota HTTP 429 responses are never retried.
|
|
456
|
+
|
|
457
|
+
An automatic delivery failure invokes optional `on_error`. The callback is
|
|
458
|
+
observational: the failed prepared batch remains queued. A later automatic
|
|
459
|
+
attempt, `close`, or `aclose` retries that same batch, and close surfaces an
|
|
460
|
+
error if delivery still fails.
|
|
461
|
+
|
|
462
|
+
## Errors
|
|
463
|
+
|
|
464
|
+
All SDK exceptions derive from `TrafficWarError`:
|
|
465
|
+
|
|
466
|
+
- `ValidationError` and `SerializationError`
|
|
467
|
+
- `TransportError`
|
|
468
|
+
- `APIError`, `AuthenticationError`, `ConflictError`, and `ServerError`
|
|
469
|
+
- `RateLimitError`
|
|
470
|
+
- `ResponseError` for malformed success or error responses
|
|
471
|
+
|
|
472
|
+
API errors retain the response body's `status`, HTTP `status_code`, parsed
|
|
473
|
+
`details`, `retry_after`, `ingest_id`, and `idempotency_key`. `RateLimitError`
|
|
474
|
+
also exposes `period`, `used`, `limit`, `remaining_events`, `batch_events`, and
|
|
475
|
+
`retry_after_secs`.
|
|
476
|
+
|
|
477
|
+
```python
|
|
478
|
+
from datetime import datetime, timezone
|
|
479
|
+
|
|
480
|
+
from trafficwar import RateLimitError
|
|
481
|
+
|
|
482
|
+
client.capture(
|
|
483
|
+
{
|
|
484
|
+
"event": "job.failed",
|
|
485
|
+
"label": "Nightly job",
|
|
486
|
+
"source": "worker-a",
|
|
487
|
+
"operation_type": "job.run",
|
|
488
|
+
"span_kind": "internal",
|
|
489
|
+
"timestamp": datetime.now(timezone.utc),
|
|
490
|
+
"latency_ms": 12.5,
|
|
491
|
+
"status_code": 500,
|
|
492
|
+
}
|
|
493
|
+
)
|
|
494
|
+
|
|
495
|
+
try:
|
|
496
|
+
client.close()
|
|
497
|
+
except RateLimitError as exc:
|
|
498
|
+
print(exc.period, exc.remaining_events, exc.retry_after)
|
|
499
|
+
```
|
|
500
|
+
|
|
501
|
+
## Custom HTTPX clients
|
|
502
|
+
|
|
503
|
+
Inject a configured HTTPX client for custom transports, proxies, certificates,
|
|
504
|
+
or instrumentation. TrafficWar does not close caller-owned clients.
|
|
505
|
+
|
|
506
|
+
```python
|
|
507
|
+
import httpx
|
|
508
|
+
from datetime import datetime, timezone
|
|
509
|
+
from trafficwar import TrafficWar
|
|
510
|
+
|
|
511
|
+
http = httpx.Client(http2=True)
|
|
512
|
+
trafficwar = TrafficWar("tw_live_...", http_client=http)
|
|
513
|
+
try:
|
|
514
|
+
trafficwar.capture(
|
|
515
|
+
{
|
|
516
|
+
"event": "job_finished",
|
|
517
|
+
"label": "Nightly job",
|
|
518
|
+
"source": "worker-a",
|
|
519
|
+
"operation_type": "job.run",
|
|
520
|
+
"span_kind": "internal",
|
|
521
|
+
"timestamp": datetime.now(timezone.utc),
|
|
522
|
+
"latency_ms": 12.5,
|
|
523
|
+
}
|
|
524
|
+
)
|
|
525
|
+
finally:
|
|
526
|
+
trafficwar.close() # flushes the event and leaves `http` open
|
|
527
|
+
http.close()
|
|
528
|
+
```
|
|
529
|
+
|
|
530
|
+
The SDK sends a standalone request containing only its own body and headers.
|
|
531
|
+
Defaults from an injected client's headers, cookies, query parameters, and
|
|
532
|
+
authentication are never merged into TrafficWar requests.
|
|
533
|
+
|
|
534
|
+
## License
|
|
535
|
+
|
|
536
|
+
MIT
|