amiril 0.0.0.dev0__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.
Files changed (64) hide show
  1. amiril/__init__.py +51 -0
  2. amiril/_adapters.py +399 -0
  3. amiril/_engine/__init__.py +1 -0
  4. amiril/_engine/engine.py +113 -0
  5. amiril/_engine/expr.py +653 -0
  6. amiril/_engine/numbers.py +111 -0
  7. amiril/_engine/regex.py +262 -0
  8. amiril/_engine/rules.py +192 -0
  9. amiril/_engine/sentence.py +251 -0
  10. amiril/_engine/timeparse.py +72 -0
  11. amiril/_engine/validate.py +863 -0
  12. amiril/_engine/values.py +273 -0
  13. amiril/_kernel/__init__.py +1 -0
  14. amiril/_kernel/bundle.py +245 -0
  15. amiril/_kernel/coerce.py +103 -0
  16. amiril/_kernel/events.py +87 -0
  17. amiril/_kernel/guard.py +1196 -0
  18. amiril/_kernel/ids.py +66 -0
  19. amiril/_kernel/messages.py +30 -0
  20. amiril/_kernel/normalise.py +165 -0
  21. amiril/_kernel/records.py +131 -0
  22. amiril/_kernel/store.py +661 -0
  23. amiril/_runtime.py +617 -0
  24. amiril/adk.py +577 -0
  25. amiril/control/__init__.py +25 -0
  26. amiril/control/_delivery.py +567 -0
  27. amiril/control/_disk.py +418 -0
  28. amiril/control/_holds.py +252 -0
  29. amiril/control/_jsonschema.py +265 -0
  30. amiril/control/_pathc.py +85 -0
  31. amiril/control/_records.py +293 -0
  32. amiril/control/_redact.py +79 -0
  33. amiril/control/_transport.py +184 -0
  34. amiril/control/_wire.py +73 -0
  35. amiril/control/client.py +1313 -0
  36. amiril/control/config.py +204 -0
  37. amiril/control/schemas/bundle.response.schema.json +22 -0
  38. amiril/control/schemas/common.schema.json +593 -0
  39. amiril/control/schemas/decisions.request.schema.json +558 -0
  40. amiril/control/schemas/decisions.response.schema.json +23 -0
  41. amiril/control/schemas/error.response.schema.json +54 -0
  42. amiril/control/schemas/heartbeat.request.schema.json +305 -0
  43. amiril/control/schemas/heartbeat.response.schema.json +34 -0
  44. amiril/control/schemas/hold-create.request.schema.json +138 -0
  45. amiril/control/schemas/hold.response.schema.json +226 -0
  46. amiril/control/schemas/installation-register.request.schema.json +492 -0
  47. amiril/control/schemas/installation-register.response.schema.json +85 -0
  48. amiril/core.py +89 -0
  49. amiril/docs/README.md +14 -0
  50. amiril/docs/durability/langgraph.md +292 -0
  51. amiril/docs/frameworks/adk.md +141 -0
  52. amiril/docs/frameworks/langgraph.md +154 -0
  53. amiril/docs/frameworks/no-framework.md +238 -0
  54. amiril/docs/frameworks/write-an-adapter.md +203 -0
  55. amiril/durable.py +342 -0
  56. amiril/langgraph.py +746 -0
  57. amiril/plain.py +454 -0
  58. amiril/py.typed +0 -0
  59. amiril/seams.py +357 -0
  60. amiril/testing.py +21 -0
  61. amiril-0.0.0.dev0.dist-info/METADATA +114 -0
  62. amiril-0.0.0.dev0.dist-info/RECORD +64 -0
  63. amiril-0.0.0.dev0.dist-info/WHEEL +4 -0
  64. amiril-0.0.0.dev0.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,567 @@
1
+ """Decision delivery (spec/protocol.md 8.4 to 8.6, 2.5, 2.6): a bounded
2
+ in-memory queue that drops the oldest record when full, immutable batches
3
+ with an idempotency key, the retry classes and attempt accounting, and the
4
+ disk spool for batches that exhaust their attempts or are unsent at exit.
5
+ One background thread sends one batch at a time; nothing here blocks the
6
+ thread that queues a record."""
7
+
8
+ from __future__ import annotations
9
+
10
+ import logging
11
+ import random
12
+ import threading
13
+ import time
14
+ from collections import deque
15
+ from dataclasses import dataclass
16
+ from typing import Any, Protocol
17
+
18
+ from ._disk import Spool, SpooledBatch
19
+ from ._transport import NetworkError, Response, Transport
20
+ from ._wire import PROTOCOL, backoff, dumps, encode_body, new_uuid, retry_after_wait, ts_ms
21
+
22
+ log = logging.getLogger("amiril")
23
+
24
+ MAX_ATTEMPTS = 8 # 2.5
25
+ MAX_UNCOMPRESSED = 4 * 1024 * 1024 # 8.1
26
+
27
+
28
+ class Channel(Protocol):
29
+ """What delivery needs from the client."""
30
+
31
+ transport: Transport | None
32
+ process_id: str
33
+
34
+ @property
35
+ def installation_id(self) -> str | None: ...
36
+ @property
37
+ def max_records(self) -> int: ...
38
+ @property
39
+ def max_body_bytes(self) -> int: ...
40
+ @property
41
+ def refused(self) -> bool: ...
42
+ @property
43
+ def discarding(self) -> bool: ...
44
+
45
+ def on_ack(self) -> None: ...
46
+ def on_refused(self, status: int) -> None: ...
47
+ def reregister_once(self) -> bool: ...
48
+ def count_drop(self, reason: str, n: int) -> None: ...
49
+ def log_once(self, key: str, message: str) -> None: ...
50
+
51
+
52
+ @dataclass
53
+ class Batch:
54
+ """An immutable batch: its key, `sent_at`, `process_id` and records never
55
+ change (2.6). `installation_id` is fixed only for a batch read back from
56
+ another process's spool; this process's batches carry the current id,
57
+ which the server's body equality ignores (4.5). A spooled batch keeps the
58
+ `protocol` it was written with, which may be an earlier release's (8.4)."""
59
+
60
+ key: str
61
+ process_id: str
62
+ sent_at: str
63
+ records: list[dict]
64
+ installation_id: str | None = None
65
+ protocol: str = PROTOCOL
66
+ foreign: bool = False
67
+ attempts: int = 0
68
+ not_found: int = 0
69
+ due: float = 0.0
70
+ not_before: float = 0.0 # a server-requested wait (Retry-After): nothing moves `due` earlier than this
71
+ evicted: bool = False
72
+ evicted_in_flight: bool = False # counted as queue_full only if that request is not acknowledged
73
+ acked: bool = False
74
+ spooled: SpooledBatch | None = None
75
+
76
+ def body(self, current_installation: str | None) -> dict:
77
+ return {
78
+ "protocol": self.protocol,
79
+ "idempotency_key": self.key,
80
+ # A batch spooled before registration has none; the server's body hash ignores the field (2.6).
81
+ "installation_id": (self.installation_id if self.foreign and self.installation_id
82
+ else current_installation),
83
+ "process_id": self.process_id,
84
+ "sent_at": self.sent_at,
85
+ "records": self.records,
86
+ }
87
+
88
+ def spool_entry(self, current_installation: str | None) -> dict:
89
+ return self.body(current_installation)
90
+
91
+
92
+ class Delivery:
93
+ def __init__(self, channel: Channel, spool: Spool, capacity: int, *, flush_age: float, backoff_base: float,
94
+ backoff_cap: float, request_timeout: float, rng: random.Random,
95
+ clock: Any = time.monotonic, wall: Any = time.time) -> None:
96
+ self.ch = channel
97
+ self.spool = spool
98
+ self.capacity = max(1, capacity)
99
+ self.flush_age = flush_age
100
+ self.backoff_base = backoff_base
101
+ self.backoff_cap = backoff_cap
102
+ self.request_timeout = request_timeout
103
+ self.rng = rng
104
+ self.clock = clock
105
+ self.wall = wall
106
+ self._cond = threading.Condition()
107
+ self._loose: deque[tuple[dict, float]] = deque()
108
+ self._batches: deque[Batch] = deque()
109
+ self._inflight: Batch | None = None
110
+ self._sending: Batch | None = None
111
+ self._depth = 0
112
+ self._draining = True # 8.4: drain at start too
113
+ self._take_spool = True # alternate spooled and live batches
114
+ self._to_spool: list[Batch] = [] # evicted while refused: written to the spool by the delivery thread
115
+ self._flush_deadline: float | None = None
116
+ self._stop = False
117
+ self._rescan = False
118
+ self._want_spool = False
119
+ self._thread: threading.Thread | None = None
120
+
121
+ # -------------------------------------------------------- queueing (any thread)
122
+
123
+ def depth(self) -> int:
124
+ with self._cond:
125
+ return self._depth
126
+
127
+ def push(self, record: dict) -> None:
128
+ with self._cond:
129
+ if self.ch.discarding:
130
+ return
131
+ while self._depth >= self.capacity:
132
+ self._evict_oldest()
133
+ self._loose.append((record, self.clock()))
134
+ self._depth += 1
135
+ if len(self._loose) >= self.ch.max_records or len(self._loose) == 1:
136
+ self._cond.notify_all()
137
+
138
+ def _evict_oldest(self) -> None:
139
+ """8.4: a full queue drops the oldest record. A record inside a built
140
+ batch cannot leave it (the batch is immutable), so the batch goes whole.
141
+ While the key is refused (4.7) the oldest batch spills to the spool."""
142
+ if self.ch.refused and self.spool.dir is not None:
143
+ victim = self._take_oldest_batch()
144
+ if victim is not None:
145
+ # Spooled by the delivery thread: no disk I/O on the caller's thread or under this lock (6).
146
+ self._to_spool.append(victim)
147
+ self._cond.notify_all()
148
+ return
149
+ if self._inflight is not None and not self._inflight.evicted and self._inflight.spooled is None:
150
+ inf = self._inflight
151
+ inf.evicted = True
152
+ self._depth -= len(inf.records)
153
+ if inf is self._sending:
154
+ # Its request may still be acknowledged: the drop is counted when the request settles,
155
+ # so a heartbeat never reports a drop that a later acknowledgement would take back.
156
+ inf.evicted_in_flight = True
157
+ else:
158
+ self.ch.count_drop("queue_full", len(inf.records))
159
+ self._inflight = None
160
+ return
161
+ if self._batches:
162
+ b = self._batches.popleft()
163
+ self._depth -= len(b.records)
164
+ self.ch.count_drop("queue_full", len(b.records))
165
+ return
166
+ if self._loose:
167
+ self._loose.popleft()
168
+ self._depth -= 1
169
+ self.ch.count_drop("queue_full", 1)
170
+
171
+ def _take_oldest_batch(self) -> Batch | None:
172
+ if self._inflight is not None and self._inflight is not self._sending and not self._inflight.evicted \
173
+ and self._inflight.spooled is None:
174
+ b, self._inflight = self._inflight, None
175
+ elif self._batches:
176
+ b = self._batches.popleft()
177
+ elif self._loose:
178
+ b = self._build_locked()
179
+ else:
180
+ return None
181
+ self._depth -= len(b.records)
182
+ return b
183
+
184
+ def _build_locked(self) -> Batch:
185
+ records: list[dict] = []
186
+ size = 1024
187
+ limit = self.ch.max_records
188
+ while self._loose and len(records) < limit:
189
+ rec, _ = self._loose[0]
190
+ n = len(dumps(rec)) + 1
191
+ if records and size + n > MAX_UNCOMPRESSED:
192
+ break
193
+ self._loose.popleft()
194
+ records.append(rec)
195
+ size += n
196
+ return Batch(new_uuid(), self.ch.process_id, ts_ms(self.wall()), records)
197
+
198
+ # -------------------------------------------------------- the thread
199
+
200
+ def start(self) -> None:
201
+ self._thread = threading.Thread(target=self._run, name="amiril-delivery", daemon=True)
202
+ self._thread.start()
203
+
204
+ def wake(self, draining: bool = False) -> None:
205
+ with self._cond:
206
+ if draining and not self._draining:
207
+ self._draining = True
208
+ self._rescan = True
209
+ self._cond.notify_all()
210
+
211
+ def _ready_locked(self, now: float) -> float | None:
212
+ """Seconds until there is something to send (0 when now), None for nothing."""
213
+ if self.ch.discarding:
214
+ self._clear_locked()
215
+ return None
216
+ if self._to_spool:
217
+ return 0.0
218
+ if self.ch.refused or self.ch.transport is None:
219
+ return None
220
+ if self._inflight is not None:
221
+ return max(0.0, self._inflight.due - now)
222
+ if self._batches:
223
+ return 0.0
224
+ if self._loose:
225
+ if self._flush_deadline is not None or len(self._loose) >= self.ch.max_records:
226
+ return 0.0
227
+ return max(0.0, self._loose[0][1] + self.flush_age - now)
228
+ if self._draining and self.spool.dir is not None:
229
+ return 0.0
230
+ return None
231
+
232
+ def _clear_locked(self) -> None:
233
+ self._loose.clear()
234
+ self._batches.clear()
235
+ self._inflight = None
236
+ self._depth = 0
237
+
238
+ def _run(self) -> None:
239
+ self.spool.open() # the disk is touched by this thread, never by the agent's (6)
240
+ while True:
241
+ with self._cond:
242
+ while not self._stop:
243
+ wait = self._ready_locked(self.clock())
244
+ if wait == 0.0:
245
+ break
246
+ self._cond.wait(timeout=wait if wait is not None else 1.0)
247
+ if self._stop:
248
+ return
249
+ spill, self._to_spool = self._to_spool, []
250
+ rescan, self._rescan = self._rescan, False
251
+ batch = self._next_locked()
252
+ if batch is not None:
253
+ self._sending = batch
254
+ for b in spill:
255
+ if not self.spool.append(b.spool_entry(self.ch.installation_id)):
256
+ self.ch.count_drop("queue_full", len(b.records))
257
+ if rescan:
258
+ self.spool.rescan()
259
+ if batch is None:
260
+ batch = self._take_from_spool()
261
+ if batch is None:
262
+ continue
263
+ try:
264
+ self._send(batch)
265
+ except Exception as exc: # noqa: BLE001 - delivery must never die
266
+ log.debug("amiril: delivery error %s", exc)
267
+ with self._cond:
268
+ if self._inflight is batch:
269
+ batch.due = self.clock() + 1.0
270
+ finally:
271
+ with self._cond:
272
+ self._sending = None
273
+ if batch.evicted_in_flight and not batch.acked:
274
+ self.ch.count_drop("queue_full", len(batch.records))
275
+ batch.evicted_in_flight = False
276
+ self._cond.notify_all()
277
+
278
+ def _take_from_spool(self) -> Batch | None:
279
+ """Read the next spooled batch outside the lock; None ends this drain."""
280
+ if not self._want_spool:
281
+ return None
282
+ sb = self.spool.next()
283
+ with self._cond:
284
+ self._want_spool = False
285
+ if sb is None:
286
+ self._draining = False
287
+ return None
288
+ batch = self._from_spool(sb)
289
+ self._inflight = self._sending = batch
290
+ return batch
291
+
292
+ def _next_locked(self) -> Batch | None:
293
+ """The live batch to send now, or None. When a spooled batch is due
294
+ instead, sets `_want_spool` and returns None: the caller reads it
295
+ from disk after releasing the lock."""
296
+ self._want_spool = False
297
+ if self._inflight is not None:
298
+ return self._inflight
299
+ live_ready = bool(self._batches) or bool(self._loose and (
300
+ self._flush_deadline is not None or len(self._loose) >= self.ch.max_records
301
+ or self._loose[0][1] + self.flush_age <= self.clock()))
302
+ if self._draining and self.spool.dir is not None and (self._take_spool or not live_ready):
303
+ self._take_spool = False
304
+ self._want_spool = True
305
+ return None
306
+ self._take_spool = True
307
+ if self._batches:
308
+ self._inflight = self._batches.popleft()
309
+ elif live_ready:
310
+ self._inflight = self._build_locked()
311
+ return self._inflight
312
+
313
+ def _from_spool(self, sb: SpooledBatch) -> Batch:
314
+ e = sb.entry
315
+ foreign = e.get("process_id") != self.ch.process_id
316
+ return Batch(e["idempotency_key"], e.get("process_id") or self.ch.process_id, e.get("sent_at") or "",
317
+ list(e["records"]), installation_id=e.get("installation_id"),
318
+ protocol=p if isinstance(p := e.get("protocol"), str) and p else PROTOCOL,
319
+ foreign=foreign, spooled=sb)
320
+
321
+ # -------------------------------------------------------- sending one batch
322
+
323
+ def _timeout(self) -> float:
324
+ with self._cond:
325
+ deadline = self._flush_deadline
326
+ if deadline is None:
327
+ return self.request_timeout
328
+ return max(0.05, min(self.request_timeout, deadline - self.clock()))
329
+
330
+ def _send(self, batch: Batch) -> None:
331
+ body = batch.body(self.ch.installation_id)
332
+ raw = dumps(body)
333
+ wire, _ = encode_body(raw)
334
+ if batch.spooled is None and (len(wire) > self.ch.max_body_bytes or len(raw) > MAX_UNCOMPRESSED):
335
+ self._split(batch, local=True)
336
+ return
337
+ transport = self.ch.transport
338
+ if transport is None:
339
+ return
340
+ try:
341
+ resp = transport.request("POST", "/v1/decisions", raw=raw, timeout=self._timeout())
342
+ except NetworkError as exc:
343
+ self.ch.log_once("decisions-network", f"amiril: decision delivery failed ({exc}); retrying")
344
+ self._retry(batch, consume=True)
345
+ return
346
+ self._handle(batch, resp)
347
+
348
+ def _handle(self, batch: Batch, resp: Response) -> None:
349
+ status = resp.status
350
+ if 200 <= status < 300:
351
+ batch.acked = True
352
+ self._settle(batch)
353
+ self.ch.on_ack()
354
+ return
355
+ if batch.evicted:
356
+ self._settle(batch) # the queue already gave it up and counted it
357
+ return
358
+ if status == 400:
359
+ details = ((resp.body or {}).get("error") or {}).get("details") or {}
360
+ ids = details.get("record_ids") if isinstance(details, dict) else None
361
+ self.ch.log_once(f"decisions-400:{resp.error_text}",
362
+ f"amiril: the control plane rejected decision records ({resp.error_text})")
363
+ bad = set(ids) if isinstance(ids, list) and ids else None
364
+ keep = [r for r in batch.records if bad is not None and r.get("id") not in bad]
365
+ self._settle(batch)
366
+ self.ch.count_drop("rejected", len(batch.records) - len(keep))
367
+ if keep:
368
+ self._requeue([Batch(new_uuid(), batch.process_id, batch.sent_at, keep,
369
+ installation_id=batch.installation_id, protocol=batch.protocol,
370
+ foreign=batch.foreign)])
371
+ return
372
+ if status in (401, 403):
373
+ self.ch.on_refused(status)
374
+ if batch.spooled is not None:
375
+ self._settle(batch, keep_spooled=True)
376
+ return
377
+ if status == 404:
378
+ if batch.not_found >= 1:
379
+ self._drop(batch, "rejected")
380
+ return
381
+ batch.not_found += 1
382
+ if batch.evicted:
383
+ self._settle(batch)
384
+ elif self.ch.reregister_once():
385
+ batch.foreign = False # resend under the id just received (4.5)
386
+ batch.due = self.clock()
387
+ else:
388
+ self._retry(batch, consume=True)
389
+ return
390
+ if status == 409:
391
+ self.ch.log_once("decisions-409", "amiril: idempotency key reused with a different body; batch dropped")
392
+ self._drop(batch, "rejected")
393
+ return
394
+ if status == 413:
395
+ self._split(batch, local=False)
396
+ return
397
+ ra = resp.retry_after
398
+ if status in (429, 503) and ra is not None:
399
+ self._wait(batch, retry_after_wait(ra, self.rng))
400
+ return
401
+ if status >= 500 or status == 429:
402
+ self._retry(batch, consume=True)
403
+ return
404
+ self.ch.log_once(f"decisions-{status}:{resp.error_text}",
405
+ f"amiril: decision batch refused with {status} ({resp.error_text}); dropped")
406
+ self._drop(batch, "rejected")
407
+
408
+ # -------------------------------------------------------- outcomes
409
+
410
+ def _settle(self, batch: Batch, keep_spooled: bool = False) -> None:
411
+ """The batch leaves the queue (acknowledged, dropped or replaced)."""
412
+ with self._cond:
413
+ if self._inflight is batch:
414
+ self._inflight = None
415
+ if not batch.evicted and batch.spooled is None:
416
+ self._depth -= len(batch.records)
417
+ if batch.spooled is not None:
418
+ if keep_spooled:
419
+ self.spool.release(batch.spooled)
420
+ else:
421
+ self.spool.remove(batch.spooled)
422
+
423
+ def _drop(self, batch: Batch, reason: str) -> None:
424
+ self._settle(batch)
425
+ if not batch.evicted:
426
+ self.ch.count_drop(reason, len(batch.records))
427
+
428
+ def _requeue(self, batches: list[Batch]) -> None:
429
+ with self._cond:
430
+ for b in reversed(batches):
431
+ self._batches.appendleft(b)
432
+ self._depth += len(b.records)
433
+ self._cond.notify_all()
434
+
435
+ def _split(self, batch: Batch, local: bool) -> None:
436
+ """2.5 / 8.5: halves with new keys; a single record is `too_large`."""
437
+ if len(batch.records) == 1:
438
+ self._drop(batch, "too_large")
439
+ return
440
+ mid = len(batch.records) // 2
441
+ halves = [Batch(new_uuid(), batch.process_id, batch.sent_at, part,
442
+ installation_id=batch.installation_id, protocol=batch.protocol, foreign=batch.foreign)
443
+ for part in (batch.records[:mid], batch.records[mid:])]
444
+ self._settle(batch)
445
+ self._requeue(halves)
446
+
447
+ def _wait(self, batch: Batch, seconds: float) -> None:
448
+ """Retry-After: wait without consuming an attempt."""
449
+ if batch.spooled is not None:
450
+ self._park_spooled(batch)
451
+ return
452
+ with self._cond:
453
+ batch.due = batch.not_before = self.clock() + seconds
454
+ if batch.evicted and self._inflight is batch:
455
+ self._inflight = None
456
+
457
+ def _retry(self, batch: Batch, consume: bool) -> None:
458
+ if batch.spooled is not None:
459
+ self._park_spooled(batch)
460
+ return
461
+ if consume:
462
+ batch.attempts += 1
463
+ if batch.attempts >= MAX_ATTEMPTS:
464
+ self._exhausted(batch, "expired")
465
+ return
466
+ with self._cond:
467
+ if batch.evicted:
468
+ if self._inflight is batch:
469
+ self._inflight = None
470
+ return
471
+ batch.due = self.clock() + backoff(batch.attempts, self.backoff_base, self.backoff_cap, self.rng)
472
+ if self._flush_deadline is not None and batch.due > self._flush_deadline:
473
+ batch.due = max(self._flush_deadline, batch.not_before) # a batch still waiting at the deadline is spooled
474
+
475
+ def _park_spooled(self, batch: Batch) -> None:
476
+ """A spooled batch that fails again stays in its file; draining stops
477
+ until the next acknowledged request (8.4)."""
478
+ self._settle(batch, keep_spooled=True)
479
+ with self._cond:
480
+ self._draining = False
481
+
482
+ def _exhausted(self, batch: Batch, reason: str) -> None:
483
+ """2.5: after 8 attempts, to the spool where one exists, else dropped."""
484
+ self._settle(batch)
485
+ if batch.evicted:
486
+ return
487
+ if self.spool.append(batch.spool_entry(self.ch.installation_id)):
488
+ return
489
+ self.ch.count_drop(reason, len(batch.records))
490
+
491
+ # -------------------------------------------------------- flush and shutdown
492
+
493
+ def flush(self, timeout_s: float, final: bool = False) -> bool:
494
+ """Send everything queued now; True when the queue emptied in time.
495
+ `final` (shutdown) stops the thread at the deadline: no request starts
496
+ after it, and one in flight was started with a timeout ending there."""
497
+ deadline = self.clock() + timeout_s
498
+ with self._cond:
499
+ self._flush_deadline = deadline
500
+ for b in ([self._inflight] if self._inflight is not None else []):
501
+ b.due = max(min(b.due, self.clock()), b.not_before) # never earlier than Retry-After allows
502
+ self._cond.notify_all()
503
+ try:
504
+ while self._depth > 0 or self._inflight is not None:
505
+ remaining = deadline - self.clock()
506
+ if remaining <= 0 or self.ch.refused or self.ch.transport is None:
507
+ break
508
+ self._cond.wait(timeout=min(remaining, 0.05))
509
+ return self._depth == 0 and self._inflight is None
510
+ finally:
511
+ if final:
512
+ self._stop = True # before the deadline is cleared, so no unbounded request starts
513
+ self._cond.notify_all()
514
+ else:
515
+ self._flush_deadline = None
516
+
517
+ def stop(self, timeout_s: float = 1.0) -> None:
518
+ with self._cond:
519
+ self._stop = True
520
+ self._cond.notify_all()
521
+ if self._thread is not None:
522
+ self._thread.join(timeout_s)
523
+
524
+ def reinit_after_fork(self, spool: Spool) -> None:
525
+ """In a forked child: new lock, empty queue (the parent sends its own
526
+ records), no thread; the next `start()` runs a fresh one."""
527
+ self._cond = threading.Condition()
528
+ self._loose = deque()
529
+ self._batches = deque()
530
+ self._inflight = self._sending = None
531
+ self._depth = 0
532
+ self._to_spool = []
533
+ self._draining, self._take_spool, self._rescan, self._want_spool = True, True, False, False
534
+ self._flush_deadline = None
535
+ self._stop = False
536
+ self._thread = None
537
+ self.spool = spool
538
+
539
+ def pending_spill(self) -> int:
540
+ with self._cond:
541
+ return sum(len(b.records) for b in self._to_spool)
542
+
543
+ def spill(self) -> int:
544
+ """Exit: every unsent record goes to the spool as whole batches, or is
545
+ counted as dropped (`shutdown`). Returns the records spooled."""
546
+ spooled = 0
547
+ with self._cond:
548
+ pending: list[Batch] = []
549
+ if self._inflight is not None and not self._inflight.evicted and self._inflight.spooled is None:
550
+ pending.append(self._inflight)
551
+ pending.extend(self._batches)
552
+ while self._loose:
553
+ pending.append(self._build_locked())
554
+ pending.extend(self._to_spool)
555
+ self._to_spool = []
556
+ self._inflight = None
557
+ self._batches.clear()
558
+ self._depth = 0
559
+ for b in pending:
560
+ if self.spool.append(b.spool_entry(self.ch.installation_id)):
561
+ spooled += len(b.records)
562
+ else:
563
+ self.ch.count_drop("shutdown", len(b.records))
564
+ return spooled
565
+
566
+
567
+ __all__ = ["Batch", "Channel", "Delivery", "MAX_ATTEMPTS"]