trafficwar 2.0.0__py3-none-any.whl

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/__init__.py ADDED
@@ -0,0 +1,73 @@
1
+ """Official Python server SDK for TrafficWar."""
2
+
3
+ from ._async_client import AsyncTrafficWar
4
+ from ._base import (
5
+ DEFAULT_BASE_URL,
6
+ DEFAULT_COMPRESSION_THRESHOLD,
7
+ DEFAULT_FLUSH_INTERVAL,
8
+ DEFAULT_MAX_QUEUE_SIZE,
9
+ DEFAULT_MAX_RETRIES,
10
+ DEFAULT_TIMEOUT,
11
+ MAX_BATCH_EVENTS,
12
+ MAX_DECODED_BODY_BYTES,
13
+ MAX_ENCODED_BODY_BYTES,
14
+ )
15
+ from ._client import TrafficWar
16
+ from ._errors import (
17
+ APIError,
18
+ AuthenticationError,
19
+ ConflictError,
20
+ RateLimitError,
21
+ ResponseError,
22
+ SerializationError,
23
+ ServerError,
24
+ TrafficWarError,
25
+ TransportError,
26
+ ValidationError,
27
+ )
28
+ from ._models import (
29
+ ErrorHandler,
30
+ Event,
31
+ EventInput,
32
+ FlushResult,
33
+ IngestResult,
34
+ JSONPrimitive,
35
+ JSONValue,
36
+ SpanKind,
37
+ Timestamp,
38
+ )
39
+ from ._version import __version__
40
+
41
+ __all__ = [
42
+ "DEFAULT_BASE_URL",
43
+ "DEFAULT_COMPRESSION_THRESHOLD",
44
+ "DEFAULT_FLUSH_INTERVAL",
45
+ "DEFAULT_MAX_QUEUE_SIZE",
46
+ "DEFAULT_MAX_RETRIES",
47
+ "DEFAULT_TIMEOUT",
48
+ "MAX_BATCH_EVENTS",
49
+ "MAX_DECODED_BODY_BYTES",
50
+ "MAX_ENCODED_BODY_BYTES",
51
+ "APIError",
52
+ "AsyncTrafficWar",
53
+ "AuthenticationError",
54
+ "ConflictError",
55
+ "ErrorHandler",
56
+ "Event",
57
+ "EventInput",
58
+ "FlushResult",
59
+ "IngestResult",
60
+ "JSONPrimitive",
61
+ "JSONValue",
62
+ "RateLimitError",
63
+ "ResponseError",
64
+ "SerializationError",
65
+ "ServerError",
66
+ "SpanKind",
67
+ "Timestamp",
68
+ "TrafficWar",
69
+ "TrafficWarError",
70
+ "TransportError",
71
+ "ValidationError",
72
+ "__version__",
73
+ ]
@@ -0,0 +1,444 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import warnings
5
+ from collections import deque
6
+ from contextlib import suppress
7
+ from itertools import islice
8
+ from types import TracebackType
9
+ from typing import Any, Optional
10
+
11
+ import httpx
12
+
13
+ from ._base import (
14
+ DEFAULT_BASE_URL,
15
+ DEFAULT_COMPRESSION_THRESHOLD,
16
+ DEFAULT_FLUSH_INTERVAL,
17
+ DEFAULT_MAX_QUEUE_SIZE,
18
+ DEFAULT_MAX_RETRIES,
19
+ DEFAULT_TIMEOUT,
20
+ MAX_BATCH_EVENTS,
21
+ MAX_RETRY_AFTER_SECONDS,
22
+ RETRYABLE_STATUS_CODES,
23
+ BaseTrafficWar,
24
+ )
25
+ from ._errors import TransportError, ValidationError
26
+ from ._models import ErrorHandler, EventInput, FlushResult, IngestResult, PreparedRequest
27
+
28
+
29
+ def _empty_flush_result() -> FlushResult:
30
+ return FlushResult(accepted=0, batches=())
31
+
32
+
33
+ class AsyncTrafficWar(BaseTrafficWar):
34
+ """Async client with a lazily started automatic batching task."""
35
+
36
+ def __init__(
37
+ self,
38
+ api_key: str,
39
+ *,
40
+ base_url: str = DEFAULT_BASE_URL,
41
+ timeout: float = DEFAULT_TIMEOUT,
42
+ max_retries: int = DEFAULT_MAX_RETRIES,
43
+ compression: str = "auto",
44
+ compression_threshold: int = DEFAULT_COMPRESSION_THRESHOLD,
45
+ flush_interval: float = DEFAULT_FLUSH_INTERVAL,
46
+ max_queue_size: int = DEFAULT_MAX_QUEUE_SIZE,
47
+ on_error: Optional[ErrorHandler] = None,
48
+ http_client: Optional[httpx.AsyncClient] = None,
49
+ ) -> None:
50
+ super().__init__(
51
+ api_key,
52
+ base_url=base_url,
53
+ timeout=timeout,
54
+ max_retries=max_retries,
55
+ compression=compression,
56
+ compression_threshold=compression_threshold,
57
+ flush_interval=flush_interval,
58
+ max_queue_size=max_queue_size,
59
+ on_error=on_error,
60
+ )
61
+ if http_client is not None and not isinstance(http_client, httpx.AsyncClient):
62
+ raise ValidationError("http_client must be an httpx.AsyncClient")
63
+ if http_client is not None and http_client.is_closed:
64
+ raise ValidationError("http_client must not already be closed")
65
+ self._client = http_client if http_client is not None else httpx.AsyncClient()
66
+ self._owns_client = http_client is None
67
+
68
+ self._queue: deque[dict[str, Any]] = deque()
69
+ self._pending_event_ids: set[str] = set()
70
+ self._pending_count = 0
71
+ self._prepared: Optional[PreparedRequest] = None
72
+ self._deadline: Optional[float] = None
73
+ self._immediate = False
74
+ self._loop: Optional[asyncio.AbstractEventLoop] = None
75
+ self._lock: Optional[asyncio.Lock] = None
76
+ self._wake: Optional[asyncio.Event] = None
77
+ self._worker_task: Optional[asyncio.Task[None]] = None
78
+ self._drain_task: Optional[asyncio.Task[FlushResult]] = None
79
+ self._close_task: Optional[asyncio.Task[FlushResult]] = None
80
+ self._worker_stop = False
81
+ self._closing = False
82
+ self._closed = False
83
+
84
+ async def capture(self, event_or_events: EventInput) -> None:
85
+ """Validate, snapshot, and enqueue one event or a non-empty iterable."""
86
+
87
+ await self._enqueue(event_or_events, force_batch=False)
88
+
89
+ async def capture_batch(
90
+ self,
91
+ events: EventInput,
92
+ ) -> None:
93
+ """Deprecated compatibility alias for ``capture(events)``."""
94
+
95
+ warnings.warn(
96
+ "capture_batch() is deprecated; pass the iterable directly to capture()",
97
+ DeprecationWarning,
98
+ stacklevel=2,
99
+ )
100
+ await self._enqueue(events, force_batch=True)
101
+
102
+ async def _enqueue(self, event_or_events: EventInput, *, force_batch: bool) -> None:
103
+ if self._closed:
104
+ raise RuntimeError("AsyncTrafficWar client is closed")
105
+ _loop, lock, wake = self._ensure_runtime()
106
+ async with lock:
107
+ if self._closed:
108
+ raise RuntimeError("AsyncTrafficWar client is closed")
109
+ if self._closing:
110
+ raise RuntimeError("AsyncTrafficWar client is closing")
111
+
112
+ normalized = await asyncio.to_thread(
113
+ self._normalize_capture_input,
114
+ event_or_events,
115
+ force_batch=force_batch,
116
+ )
117
+ async with lock:
118
+ if self._closed:
119
+ raise RuntimeError("AsyncTrafficWar client is closed")
120
+ if self._closing:
121
+ raise RuntimeError("AsyncTrafficWar client is closing")
122
+ if len(normalized) > self.max_queue_size - self._pending_count:
123
+ raise ValidationError(
124
+ f"TrafficWar queue cannot exceed {self.max_queue_size} events"
125
+ )
126
+ for event in normalized:
127
+ event_id = event["event_id"]
128
+ if event_id in self._pending_event_ids:
129
+ raise ValidationError(
130
+ f"event_id {event_id!r} duplicates an unacknowledged event"
131
+ )
132
+
133
+ was_empty = self._pending_count == 0
134
+ self._queue.extend(normalized)
135
+ self._pending_event_ids.update(event["event_id"] for event in normalized)
136
+ self._pending_count += len(normalized)
137
+ if self._pending_count >= MAX_BATCH_EVENTS:
138
+ self._deadline = None
139
+ self._immediate = True
140
+ elif was_empty and self._drain_task is None:
141
+ self._deadline = self._runtime_loop().time() + self.flush_interval
142
+ wake.set()
143
+
144
+ def _ensure_runtime(
145
+ self,
146
+ ) -> tuple[asyncio.AbstractEventLoop, asyncio.Lock, asyncio.Event]:
147
+ loop = asyncio.get_running_loop()
148
+ if self._loop is None:
149
+ self._loop = loop
150
+ self._lock = asyncio.Lock()
151
+ self._wake = asyncio.Event()
152
+ self._worker_stop = False
153
+ self._worker_task = loop.create_task(self._worker_loop())
154
+ elif self._loop is not loop:
155
+ raise RuntimeError("AsyncTrafficWar cannot be used across event loops")
156
+ elif (
157
+ not self._closed
158
+ and not self._closing
159
+ and (self._worker_task is None or self._worker_task.done())
160
+ ):
161
+ self._worker_stop = False
162
+ self._worker_task = loop.create_task(self._worker_loop())
163
+
164
+ if self._lock is None or self._wake is None:
165
+ raise RuntimeError("AsyncTrafficWar runtime state is inconsistent")
166
+ return loop, self._lock, self._wake
167
+
168
+ def _runtime_loop(self) -> asyncio.AbstractEventLoop:
169
+ if self._loop is None:
170
+ raise RuntimeError("AsyncTrafficWar runtime has not started")
171
+ return self._loop
172
+
173
+ def _runtime_lock(self) -> asyncio.Lock:
174
+ if self._lock is None:
175
+ raise RuntimeError("AsyncTrafficWar runtime has not started")
176
+ return self._lock
177
+
178
+ def _runtime_wake(self) -> asyncio.Event:
179
+ if self._wake is None:
180
+ raise RuntimeError("AsyncTrafficWar runtime has not started")
181
+ return self._wake
182
+
183
+ async def flush(self) -> FlushResult:
184
+ """Drain all queued and in-flight events, surfacing delivery failures."""
185
+
186
+ if self._closed:
187
+ return _empty_flush_result()
188
+ _loop, lock, wake = self._ensure_runtime()
189
+ async with lock:
190
+ if self._closed:
191
+ return _empty_flush_result()
192
+ close_task = self._close_task if self._closing else None
193
+ if close_task is None:
194
+ self._deadline = None
195
+ self._immediate = False
196
+ drain_task = self._start_drain_locked()
197
+ wake.set()
198
+ else:
199
+ drain_task = None
200
+
201
+ if close_task is not None:
202
+ return await asyncio.shield(close_task)
203
+ if drain_task is None:
204
+ raise RuntimeError("AsyncTrafficWar drain state is inconsistent")
205
+ return await asyncio.shield(drain_task)
206
+
207
+ async def _worker_loop(self) -> None:
208
+ loop = self._runtime_loop()
209
+ lock = self._runtime_lock()
210
+ wake = self._runtime_wake()
211
+
212
+ while True:
213
+ task: Optional[asyncio.Task[FlushResult]] = None
214
+ observe = False
215
+ delay: Optional[float] = None
216
+ async with lock:
217
+ if self._worker_stop:
218
+ return
219
+ if self._pending_count == 0:
220
+ self._deadline = None
221
+ self._immediate = False
222
+ wake.clear()
223
+ elif self._drain_task is not None:
224
+ task = self._drain_task
225
+ wake.clear()
226
+ else:
227
+ now = loop.time()
228
+ if self._immediate or (self._deadline is not None and now >= self._deadline):
229
+ self._deadline = None
230
+ self._immediate = False
231
+ task = self._start_drain_locked()
232
+ observe = True
233
+ else:
234
+ if self._deadline is None:
235
+ self._deadline = now + self.flush_interval
236
+ delay = max(0.0, self._deadline - now)
237
+ wake.clear()
238
+
239
+ if task is not None:
240
+ try:
241
+ await asyncio.shield(task)
242
+ except Exception as error:
243
+ if observe:
244
+ self._report_background_error(error)
245
+ continue
246
+
247
+ if delay is None:
248
+ await wake.wait()
249
+ else:
250
+ with suppress(asyncio.TimeoutError):
251
+ await asyncio.wait_for(wake.wait(), timeout=delay)
252
+
253
+ def _start_drain_locked(self) -> asyncio.Task[FlushResult]:
254
+ if self._drain_task is not None:
255
+ return self._drain_task
256
+ task = self._runtime_loop().create_task(self._run_drain())
257
+ self._drain_task = task
258
+ return task
259
+
260
+ async def _run_drain(self) -> FlushResult:
261
+ accepted = 0
262
+ batches: list[IngestResult] = []
263
+ lock = self._runtime_lock()
264
+ wake = self._runtime_wake()
265
+ current = asyncio.current_task()
266
+ succeeded = False
267
+
268
+ try:
269
+ while True:
270
+ async with lock:
271
+ if self._pending_count == 0:
272
+ succeeded = True
273
+ return FlushResult(accepted=accepted, batches=tuple(batches))
274
+ prepared = self._prepared
275
+
276
+ if prepared is None:
277
+ prepared = await self._prepare_next_batch()
278
+
279
+ result = await self._send(prepared)
280
+ async with lock:
281
+ if self._prepared is not prepared:
282
+ raise RuntimeError("TrafficWar prepared batch state is inconsistent")
283
+ self._prepared = None
284
+ self._pending_count -= len(prepared.events)
285
+ for event in prepared.events:
286
+ self._pending_event_ids.remove(event["event_id"])
287
+ accepted += result.accepted
288
+ batches.append(result)
289
+ finally:
290
+ async with lock:
291
+ if self._drain_task is current:
292
+ self._drain_task = None
293
+ self._immediate = succeeded and self._pending_count >= MAX_BATCH_EVENTS
294
+ if self._pending_count == 0 or self._immediate:
295
+ self._deadline = None
296
+ elif not self._closed and not self._closing and not self._worker_stop:
297
+ self._deadline = self._runtime_loop().time() + self.flush_interval
298
+ wake.set()
299
+
300
+ async def _prepare_next_batch(self) -> PreparedRequest:
301
+ lock = self._runtime_lock()
302
+ async with lock:
303
+ if self._prepared is not None:
304
+ return self._prepared
305
+ queued = list(islice(self._queue, 0, MAX_BATCH_EVENTS))
306
+
307
+ prepared = await asyncio.to_thread(self._prepare_queued_batch, queued)
308
+ async with lock:
309
+ if self._prepared is not None:
310
+ return self._prepared
311
+ for expected in prepared.events:
312
+ actual = self._queue.popleft()
313
+ if actual is not expected:
314
+ raise RuntimeError("TrafficWar queue order is inconsistent")
315
+ self._prepared = prepared
316
+ return prepared
317
+
318
+ def _report_background_error(self, error: Exception) -> None:
319
+ if self._on_error is None:
320
+ return
321
+ with suppress(Exception):
322
+ self._on_error(error)
323
+
324
+ async def _send(self, prepared: PreparedRequest) -> IngestResult:
325
+ for attempt in range(self.max_retries + 1):
326
+ request = self._request(prepared)
327
+ try:
328
+ response = await self._client.send(
329
+ request,
330
+ auth=None,
331
+ follow_redirects=False,
332
+ )
333
+ except httpx.TransportError as exc:
334
+ if attempt < self.max_retries:
335
+ await asyncio.sleep(self._retry_delay(attempt, None))
336
+ continue
337
+ raise TransportError(
338
+ f"TrafficWar transport failed after {attempt + 1} attempt(s): {exc}",
339
+ details={"exception": type(exc).__name__},
340
+ idempotency_key=prepared.idempotency_key,
341
+ ) from exc
342
+
343
+ if response.status_code in RETRYABLE_STATUS_CODES and attempt < self.max_retries:
344
+ delay = self._retry_delay(attempt, response)
345
+ if delay <= MAX_RETRY_AFTER_SECONDS:
346
+ await response.aclose()
347
+ await asyncio.sleep(delay)
348
+ continue
349
+ try:
350
+ return self._result_or_error(response, prepared)
351
+ finally:
352
+ await response.aclose()
353
+
354
+ raise AssertionError("retry loop exited unexpectedly")
355
+
356
+ async def aclose(self) -> FlushResult:
357
+ """Stop automatic work, drain successfully, then close owned resources."""
358
+
359
+ if self._closed:
360
+ return _empty_flush_result()
361
+ loop, lock, wake = self._ensure_runtime()
362
+ async with lock:
363
+ if self._closed:
364
+ return _empty_flush_result()
365
+ if self._close_task is None:
366
+ self._closing = True
367
+ self._worker_stop = True
368
+ self._deadline = None
369
+ self._immediate = False
370
+ wake.set()
371
+ self._close_task = loop.create_task(self._close_impl())
372
+ close_task = self._close_task
373
+ return await asyncio.shield(close_task)
374
+
375
+ async def _close_impl(self) -> FlushResult:
376
+ loop = self._runtime_loop()
377
+ lock = self._runtime_lock()
378
+ wake = self._runtime_wake()
379
+ current = asyncio.current_task()
380
+ accepted = 0
381
+ batches: list[IngestResult] = []
382
+
383
+ async with lock:
384
+ active = self._drain_task
385
+ worker = self._worker_task
386
+
387
+ try:
388
+ if active is not None:
389
+ result = await asyncio.shield(active)
390
+ accepted += result.accepted
391
+ batches.extend(result.batches)
392
+ if worker is not None and worker is not current:
393
+ await worker
394
+
395
+ while True:
396
+ async with lock:
397
+ if self._pending_count == 0:
398
+ break
399
+ drain_task = self._start_drain_locked()
400
+ result = await asyncio.shield(drain_task)
401
+ accepted += result.accepted
402
+ batches.extend(result.batches)
403
+
404
+ if self._owns_client:
405
+ await self._client.aclose()
406
+ result = FlushResult(accepted=accepted, batches=tuple(batches))
407
+ except Exception:
408
+ if worker is not None and worker is not current and not worker.done():
409
+ await worker
410
+ async with lock:
411
+ self._closing = False
412
+ self._worker_stop = False
413
+ if self._pending_count > 0:
414
+ self._deadline = loop.time() + self.flush_interval
415
+ if self._worker_task is None or self._worker_task.done():
416
+ self._worker_task = loop.create_task(self._worker_loop())
417
+ if self._close_task is current:
418
+ self._close_task = None
419
+ wake.set()
420
+ raise
421
+
422
+ async with lock:
423
+ self._closed = True
424
+ self._closing = False
425
+ self._worker_task = None
426
+ if self._close_task is current:
427
+ self._close_task = None
428
+ wake.set()
429
+ return result
430
+
431
+ async def __aenter__(self) -> AsyncTrafficWar:
432
+ if self._closed:
433
+ raise RuntimeError("AsyncTrafficWar client is closed")
434
+ if self._closing:
435
+ raise RuntimeError("AsyncTrafficWar client is closing")
436
+ return self
437
+
438
+ async def __aexit__(
439
+ self,
440
+ exc_type: Optional[type[BaseException]],
441
+ exc_value: Optional[BaseException],
442
+ traceback: Optional[TracebackType],
443
+ ) -> None:
444
+ await self.aclose()