python-wrap 0.2.1__py3-none-any.whl → 0.4.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.
- python_wrap/__init__.py +348 -1
- python_wrap/__main__.py +57 -0
- python_wrap/_backend.py +133 -0
- python_wrap/_buckets.py +162 -0
- python_wrap/_core.py +12 -3
- python_wrap/_data/agent_guide.md +103 -0
- python_wrap/_data/recipes.json +703 -0
- python_wrap/_fork.py +113 -0
- python_wrap/_integration.py +29 -0
- python_wrap/_runtime.py +157 -0
- python_wrap/adapters/__init__.py +101 -0
- python_wrap/adapters/_frameworks.py +251 -0
- python_wrap/adapters/_sdk.py +1978 -0
- python_wrap/adapters/anthropic.py +139 -0
- python_wrap/adapters/langchain.py +288 -0
- python_wrap/adapters/openai.py +169 -0
- python_wrap/adapters/openai_agents.py +468 -0
- python_wrap/adapters/pydantic_ai.py +459 -0
- python_wrap/adaptive.py +605 -0
- python_wrap/agents.py +2503 -0
- python_wrap/alerts.py +293 -0
- python_wrap/async_cache.py +745 -0
- python_wrap/batching.py +17 -4
- python_wrap/buffering.py +952 -0
- python_wrap/bulkhead.py +58 -6
- python_wrap/caching.py +425 -56
- python_wrap/celery.py +528 -0
- python_wrap/chaos.py +519 -0
- python_wrap/circuit.py +454 -23
- python_wrap/compat.py +267 -0
- python_wrap/concurrency.py +82 -1746
- python_wrap/config.py +25 -4
- python_wrap/coordination.py +638 -0
- python_wrap/credentials.py +126 -0
- python_wrap/dashboard.py +358 -0
- python_wrap/debounce.py +538 -0
- python_wrap/django.py +100 -0
- python_wrap/doctor.py +599 -0
- python_wrap/events.py +145 -4
- python_wrap/exporters.py +663 -0
- python_wrap/fastapi.py +81 -0
- python_wrap/flask.py +61 -0
- python_wrap/genai.py +1101 -0
- python_wrap/health.py +187 -0
- python_wrap/http.py +940 -0
- python_wrap/idempotency.py +446 -0
- python_wrap/introspect.py +738 -0
- python_wrap/lifecycle.py +620 -0
- python_wrap/llm.py +2574 -0
- python_wrap/llm_cassette.py +948 -0
- python_wrap/llm_http_chaos.py +326 -0
- python_wrap/llm_shared.py +772 -0
- python_wrap/llm_testing.py +990 -0
- python_wrap/llm_validate.py +383 -0
- python_wrap/local_state.py +395 -0
- python_wrap/logs.py +82 -26
- python_wrap/mcp.py +490 -0
- python_wrap/mcp_guard.py +357 -0
- python_wrap/metrics.py +6 -3
- python_wrap/migrate.py +1452 -0
- python_wrap/observability.py +484 -0
- python_wrap/periodic.py +24 -2
- python_wrap/policies.py +396 -0
- python_wrap/policy.py +14 -0
- python_wrap/predicates.py +276 -0
- python_wrap/presets.py +378 -0
- python_wrap/processing.py +227 -0
- python_wrap/propagation.py +62 -0
- python_wrap/pytest_plugin.py +85 -0
- python_wrap/quotas.py +319 -0
- python_wrap/ratelimit.py +560 -0
- python_wrap/redaction.py +228 -0
- python_wrap/retry.py +448 -70
- python_wrap/shared.py +653 -0
- python_wrap/singleflight.py +255 -0
- python_wrap/slow.py +72 -0
- python_wrap/stores.py +168 -0
- python_wrap/switches.py +164 -0
- python_wrap/testing.py +34 -8
- python_wrap/timeouts.py +874 -0
- python_wrap/timing.py +239 -17
- python_wrap/validation.py +187 -12
- python_wrap/web.py +723 -0
- {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/METADATA +117 -7
- python_wrap-0.4.0.dist-info/RECORD +95 -0
- python_wrap-0.2.1.dist-info/RECORD +0 -29
- {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/WHEEL +0 -0
- {python_wrap-0.2.1.dist-info → python_wrap-0.4.0.dist-info}/licenses/LICENSE +0 -0
python_wrap/buffering.py
ADDED
|
@@ -0,0 +1,952 @@
|
|
|
1
|
+
"""Bounded, explicit-lifecycle background writers for batches of independent records.
|
|
2
|
+
|
|
3
|
+
Records live in memory by default. Pass ``journal=`` (`SQLiteJournal`, or
|
|
4
|
+
`RedisStreamJournal`) to make accepted records durable: each one is written to the
|
|
5
|
+
journal before ``submit`` returns, removed once its batch has been written, and replayed
|
|
6
|
+
into the writer the next time it starts. Delivery is then at least once.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import asyncio
|
|
12
|
+
import atexit
|
|
13
|
+
import contextlib
|
|
14
|
+
import contextvars
|
|
15
|
+
import functools
|
|
16
|
+
import json
|
|
17
|
+
import math
|
|
18
|
+
import os
|
|
19
|
+
import sqlite3
|
|
20
|
+
import threading
|
|
21
|
+
import time
|
|
22
|
+
from collections import deque
|
|
23
|
+
from collections.abc import Callable, Coroutine, Hashable, Iterator, Sequence
|
|
24
|
+
from dataclasses import dataclass
|
|
25
|
+
from typing import Any, Protocol, cast, overload, runtime_checkable
|
|
26
|
+
|
|
27
|
+
from python_wrap import _core, _fork
|
|
28
|
+
from python_wrap._runtime import seconds
|
|
29
|
+
|
|
30
|
+
__all__ = [
|
|
31
|
+
"AsyncBuffered",
|
|
32
|
+
"BufferJournal",
|
|
33
|
+
"BufferStats",
|
|
34
|
+
"Buffered",
|
|
35
|
+
"RedisStreamJournal",
|
|
36
|
+
"SQLiteJournal",
|
|
37
|
+
"buffered",
|
|
38
|
+
]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@runtime_checkable
|
|
42
|
+
class BufferJournal(Protocol):
|
|
43
|
+
"""Durable storage for records a buffered writer has accepted but not yet written.
|
|
44
|
+
|
|
45
|
+
* ``append(record)`` persists one record and returns its id. It must not return
|
|
46
|
+
before the record is durable.
|
|
47
|
+
* ``ack(ids)`` removes records whose batch was written (or that were dropped on
|
|
48
|
+
purpose by ``on_full="drop_oldest"``).
|
|
49
|
+
* ``pending()`` returns every remaining ``(id, record)``, oldest first; the writer
|
|
50
|
+
replays them when it starts.
|
|
51
|
+
|
|
52
|
+
One journal (one SQLite ``name``, one Redis stream) belongs to one live writer:
|
|
53
|
+
two processes replaying the same journal would both write its records.
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
def append(self, record: Any, /) -> Hashable: ...
|
|
57
|
+
|
|
58
|
+
def ack(self, ids: Sequence[Hashable], /) -> None: ...
|
|
59
|
+
|
|
60
|
+
def pending(self) -> list[tuple[Hashable, Any]]: ...
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _json_dumps(record: Any) -> bytes:
|
|
64
|
+
return json.dumps(record, separators=(",", ":")).encode("utf-8")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _json_loads(data: bytes) -> Any:
|
|
68
|
+
return json.loads(data)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
_JOURNAL_SCHEMA = (
|
|
72
|
+
"CREATE TABLE IF NOT EXISTS python_wrap_buffer ("
|
|
73
|
+
" id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, payload BLOB NOT NULL)",
|
|
74
|
+
"CREATE INDEX IF NOT EXISTS python_wrap_buffer_name ON python_wrap_buffer (name, id)",
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _chunks(items: Sequence[Any], size: int) -> Iterator[Sequence[Any]]:
|
|
79
|
+
for start in range(0, len(items), size):
|
|
80
|
+
yield items[start : start + size]
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class SQLiteJournal:
|
|
84
|
+
"""A `BufferJournal` in a local SQLite file (stdlib only).
|
|
85
|
+
|
|
86
|
+
Records are serialised with JSON by default, so they must be JSON-serialisable
|
|
87
|
+
(tuples come back as lists); pass ``dumps``/``loads`` (for example pickle, for a
|
|
88
|
+
file only you can write) for other types. Each ``append`` is its own committed
|
|
89
|
+
transaction, so a record ``submit`` accepted survives a crash of the process.
|
|
90
|
+
|
|
91
|
+
Args:
|
|
92
|
+
path: Database file (created on first use). In-memory databases are rejected:
|
|
93
|
+
they would not survive the restart the journal exists for.
|
|
94
|
+
name: Journal name inside the file; several writers can share one file with
|
|
95
|
+
different names.
|
|
96
|
+
dumps: Record serialiser returning bytes.
|
|
97
|
+
loads: Deserialiser matching ``dumps``.
|
|
98
|
+
busy_timeout: Seconds to wait for a lock held by another connection.
|
|
99
|
+
|
|
100
|
+
Raises:
|
|
101
|
+
ValueError: For an empty or in-memory path, an empty name or a bad timeout.
|
|
102
|
+
|
|
103
|
+
Example:
|
|
104
|
+
```python
|
|
105
|
+
import os
|
|
106
|
+
import tempfile
|
|
107
|
+
|
|
108
|
+
from python_wrap.buffering import SQLiteJournal, buffered
|
|
109
|
+
|
|
110
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
111
|
+
journal = SQLiteJournal(os.path.join(tmp, "outbox.db"))
|
|
112
|
+
written = []
|
|
113
|
+
|
|
114
|
+
@buffered(max_size=10, flush_interval=0.01, journal=journal)
|
|
115
|
+
def write(rows):
|
|
116
|
+
written.extend(rows)
|
|
117
|
+
|
|
118
|
+
assert write.submit({"id": 1})
|
|
119
|
+
assert write.close(timeout=2)
|
|
120
|
+
assert written == [{"id": 1}] and journal.pending() == []
|
|
121
|
+
journal.close()
|
|
122
|
+
```
|
|
123
|
+
"""
|
|
124
|
+
|
|
125
|
+
def __init__(
|
|
126
|
+
self,
|
|
127
|
+
path: str | os.PathLike[str],
|
|
128
|
+
*,
|
|
129
|
+
name: str = "default",
|
|
130
|
+
dumps: Callable[[Any], bytes] = _json_dumps,
|
|
131
|
+
loads: Callable[[bytes], Any] = _json_loads,
|
|
132
|
+
busy_timeout: float = 5.0,
|
|
133
|
+
) -> None:
|
|
134
|
+
text = os.fspath(path)
|
|
135
|
+
if not text or text == ":memory:" or text.startswith("file::memory:"):
|
|
136
|
+
raise ValueError("path must name a database file")
|
|
137
|
+
if not name:
|
|
138
|
+
raise ValueError("name must not be empty")
|
|
139
|
+
if not math.isfinite(busy_timeout) or busy_timeout < 0:
|
|
140
|
+
raise ValueError("busy_timeout must be finite and >= 0")
|
|
141
|
+
self.path, self.name, self.busy_timeout = text, name, float(busy_timeout)
|
|
142
|
+
self.dumps, self.loads = dumps, loads
|
|
143
|
+
self._lock = _fork.ForkSafeLock()
|
|
144
|
+
self._conn: sqlite3.Connection | None = None
|
|
145
|
+
self._abandoned: list[sqlite3.Connection] = []
|
|
146
|
+
self._pid = os.getpid()
|
|
147
|
+
_fork.register(self)
|
|
148
|
+
|
|
149
|
+
def _reset_after_fork(self) -> None:
|
|
150
|
+
# Never use or close a connection inherited across fork.
|
|
151
|
+
if self._conn is not None:
|
|
152
|
+
self._abandoned.append(self._conn)
|
|
153
|
+
self._conn = None
|
|
154
|
+
self._pid = os.getpid()
|
|
155
|
+
|
|
156
|
+
def _connection(self) -> sqlite3.Connection:
|
|
157
|
+
if self._pid != os.getpid():
|
|
158
|
+
self._reset_after_fork()
|
|
159
|
+
if self._conn is None:
|
|
160
|
+
conn = sqlite3.connect(
|
|
161
|
+
self.path, timeout=self.busy_timeout, isolation_level=None, check_same_thread=False
|
|
162
|
+
)
|
|
163
|
+
try:
|
|
164
|
+
conn.execute(f"PRAGMA busy_timeout={int(self.busy_timeout * 1000)}")
|
|
165
|
+
conn.execute("PRAGMA journal_mode=WAL")
|
|
166
|
+
conn.execute("PRAGMA synchronous=FULL")
|
|
167
|
+
for statement in _JOURNAL_SCHEMA:
|
|
168
|
+
conn.execute(statement)
|
|
169
|
+
except BaseException:
|
|
170
|
+
conn.close()
|
|
171
|
+
raise
|
|
172
|
+
self._conn = conn
|
|
173
|
+
return self._conn
|
|
174
|
+
|
|
175
|
+
def append(self, record: Any, /) -> int:
|
|
176
|
+
"""Persist one record and return its row id."""
|
|
177
|
+
payload = self.dumps(record)
|
|
178
|
+
with self._lock:
|
|
179
|
+
cursor = self._connection().execute(
|
|
180
|
+
"INSERT INTO python_wrap_buffer (name, payload) VALUES (?, ?)",
|
|
181
|
+
(self.name, payload),
|
|
182
|
+
)
|
|
183
|
+
return int(cursor.lastrowid or 0)
|
|
184
|
+
|
|
185
|
+
def ack(self, ids: Sequence[Hashable], /) -> None:
|
|
186
|
+
"""Delete written (or deliberately dropped) records."""
|
|
187
|
+
if not ids:
|
|
188
|
+
return
|
|
189
|
+
with self._lock:
|
|
190
|
+
conn = self._connection()
|
|
191
|
+
for chunk in _chunks(list(ids), 500):
|
|
192
|
+
# Only "?" placeholders are interpolated; values are bound parameters.
|
|
193
|
+
marks = ",".join("?" * len(chunk))
|
|
194
|
+
sql = "DELETE FROM python_wrap_buffer WHERE name = ? AND id IN (" + marks + ")"
|
|
195
|
+
conn.execute(sql, (self.name, *chunk)) # nosec B608
|
|
196
|
+
|
|
197
|
+
def pending(self) -> list[tuple[Hashable, Any]]:
|
|
198
|
+
"""Every unwritten record, oldest first. Undecodable rows are logged and skipped."""
|
|
199
|
+
with self._lock:
|
|
200
|
+
rows = (
|
|
201
|
+
self._connection()
|
|
202
|
+
.execute(
|
|
203
|
+
"SELECT id, payload FROM python_wrap_buffer WHERE name = ? ORDER BY id",
|
|
204
|
+
(self.name,),
|
|
205
|
+
)
|
|
206
|
+
.fetchall()
|
|
207
|
+
)
|
|
208
|
+
found: list[tuple[Hashable, Any]] = []
|
|
209
|
+
for row_id, payload in rows:
|
|
210
|
+
try:
|
|
211
|
+
found.append((int(row_id), self.loads(bytes(payload))))
|
|
212
|
+
except Exception:
|
|
213
|
+
_log_failure(_core.get_logger(None), "buffered: undecodable journal record")
|
|
214
|
+
return found
|
|
215
|
+
|
|
216
|
+
def close(self) -> None:
|
|
217
|
+
"""Close this process's connection; the file and its records stay."""
|
|
218
|
+
with self._lock:
|
|
219
|
+
if self._conn is not None and self._pid == os.getpid():
|
|
220
|
+
self._conn.close()
|
|
221
|
+
self._conn = None
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
class RedisStreamJournal:
|
|
225
|
+
"""A `BufferJournal` in a Redis stream (``XADD``/``XDEL``/``XRANGE``).
|
|
226
|
+
|
|
227
|
+
python-wrap never imports redis: pass a synchronous ``redis.Redis``-compatible
|
|
228
|
+
client. Durability is whatever the Redis server provides (configure AOF with
|
|
229
|
+
``appendfsync always`` or ``everysec`` if records must survive a Redis restart).
|
|
230
|
+
Journal calls are synchronous; with `AsyncBuffered` they run on the event loop, so
|
|
231
|
+
prefer `SQLiteJournal` (a local file) for async writers.
|
|
232
|
+
|
|
233
|
+
Args:
|
|
234
|
+
client: A synchronous Redis client.
|
|
235
|
+
stream: Stream key, unique to one writer.
|
|
236
|
+
dumps: Record serialiser returning bytes (JSON by default).
|
|
237
|
+
loads: Deserialiser matching ``dumps``.
|
|
238
|
+
|
|
239
|
+
Raises:
|
|
240
|
+
ValueError: If ``stream`` is empty.
|
|
241
|
+
"""
|
|
242
|
+
|
|
243
|
+
_FIELD = "r"
|
|
244
|
+
|
|
245
|
+
def __init__(
|
|
246
|
+
self,
|
|
247
|
+
client: Any,
|
|
248
|
+
stream: str,
|
|
249
|
+
*,
|
|
250
|
+
dumps: Callable[[Any], bytes] = _json_dumps,
|
|
251
|
+
loads: Callable[[bytes], Any] = _json_loads,
|
|
252
|
+
) -> None:
|
|
253
|
+
if not stream:
|
|
254
|
+
raise ValueError("stream must not be empty")
|
|
255
|
+
self.client, self.stream = client, stream
|
|
256
|
+
self.dumps, self.loads = dumps, loads
|
|
257
|
+
|
|
258
|
+
def append(self, record: Any, /) -> Hashable:
|
|
259
|
+
"""``XADD`` one record; return its stream id."""
|
|
260
|
+
found: Hashable = self.client.xadd(self.stream, {self._FIELD: self.dumps(record)})
|
|
261
|
+
return found
|
|
262
|
+
|
|
263
|
+
def ack(self, ids: Sequence[Hashable], /) -> None:
|
|
264
|
+
"""``XDEL`` written (or deliberately dropped) records."""
|
|
265
|
+
for chunk in _chunks(list(ids), 500):
|
|
266
|
+
self.client.xdel(self.stream, *chunk)
|
|
267
|
+
|
|
268
|
+
def pending(self) -> list[tuple[Hashable, Any]]:
|
|
269
|
+
"""Every record still in the stream, oldest first (read in pages of 500)."""
|
|
270
|
+
found: list[tuple[Hashable, Any]] = []
|
|
271
|
+
start: Any = "-"
|
|
272
|
+
while True:
|
|
273
|
+
page = self.client.xrange(self.stream, min=start, max="+", count=500)
|
|
274
|
+
for entry_id, fields in page:
|
|
275
|
+
payload = fields.get(self._FIELD, fields.get(self._FIELD.encode()))
|
|
276
|
+
try:
|
|
277
|
+
found.append((entry_id, self.loads(payload)))
|
|
278
|
+
except Exception:
|
|
279
|
+
_log_failure(_core.get_logger(None), "buffered: undecodable journal record")
|
|
280
|
+
if len(page) < 500:
|
|
281
|
+
return found
|
|
282
|
+
last = page[-1][0]
|
|
283
|
+
start = "(" + (last.decode() if isinstance(last, bytes) else str(last))
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
@dataclass(frozen=True)
|
|
287
|
+
class BufferStats:
|
|
288
|
+
"""Pending includes records currently being written; failures are counted separately."""
|
|
289
|
+
|
|
290
|
+
queued: int
|
|
291
|
+
written: int
|
|
292
|
+
dropped: int
|
|
293
|
+
failed_batches: int
|
|
294
|
+
failed_records: int
|
|
295
|
+
enabled: bool
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
class Buffered:
|
|
299
|
+
"""A synchronous batch callable with submit/flush/close/disable/stats controls.
|
|
300
|
+
|
|
301
|
+
A writer thread starts lazily on first submission. Queued records are discarded
|
|
302
|
+
after fork to avoid duplicate writes; each child may start its own writer.
|
|
303
|
+
Failed batches are counted and logged, not retried (use retry on the handler).
|
|
304
|
+
|
|
305
|
+
With ``journal=``, every accepted record is persisted before ``submit`` returns
|
|
306
|
+
and removed only after its batch was written. Records left in the journal (the
|
|
307
|
+
process died, a batch failed, the writer was disabled or closed with a backlog) are
|
|
308
|
+
replayed when the writer next starts: on the first ``submit`` or an explicit
|
|
309
|
+
`replay`. Delivery is at least once, so handlers should be idempotent.
|
|
310
|
+
"""
|
|
311
|
+
|
|
312
|
+
def __init__(
|
|
313
|
+
self,
|
|
314
|
+
func: Callable[[list[Any]], Any],
|
|
315
|
+
*,
|
|
316
|
+
max_size: int = 200,
|
|
317
|
+
flush_interval: float = 1,
|
|
318
|
+
max_queue: int = 10000,
|
|
319
|
+
on_full: str = "drop",
|
|
320
|
+
drain_on_exit: float = 3,
|
|
321
|
+
on_error: str = "continue",
|
|
322
|
+
logger: Any = None,
|
|
323
|
+
journal: BufferJournal | None = None,
|
|
324
|
+
) -> None:
|
|
325
|
+
_validate(max_size, max_queue, on_full, on_error)
|
|
326
|
+
_validate_journal(journal)
|
|
327
|
+
self.func, self.max_size, self.max_queue = func, max_size, max_queue
|
|
328
|
+
self.interval = seconds(flush_interval)
|
|
329
|
+
self.drain = seconds(drain_on_exit, positive=False)
|
|
330
|
+
self.on_full, self.on_error = on_full, on_error
|
|
331
|
+
self.log = _core.get_logger(logger)
|
|
332
|
+
self.journal = journal
|
|
333
|
+
self._replayed = journal is None
|
|
334
|
+
self._condition = threading.Condition()
|
|
335
|
+
self._bindings_lock = _fork.ForkSafeLock()
|
|
336
|
+
self._queue: deque[Any] = deque()
|
|
337
|
+
self._pending = self._written = self._dropped = self._failed = self._failed_records = 0
|
|
338
|
+
self._enabled = True
|
|
339
|
+
self._closing = False
|
|
340
|
+
self._flushing = 0
|
|
341
|
+
self._thread: threading.Thread | None = None
|
|
342
|
+
self._fork_dropped = 0
|
|
343
|
+
self._options = {
|
|
344
|
+
"max_size": max_size,
|
|
345
|
+
"flush_interval": flush_interval,
|
|
346
|
+
"max_queue": max_queue,
|
|
347
|
+
"on_full": on_full,
|
|
348
|
+
"drain_on_exit": drain_on_exit,
|
|
349
|
+
"on_error": on_error,
|
|
350
|
+
"logger": logger,
|
|
351
|
+
"journal": journal,
|
|
352
|
+
}
|
|
353
|
+
functools.update_wrapper(self, func, updated=())
|
|
354
|
+
_fork.register(self)
|
|
355
|
+
|
|
356
|
+
def _reset_after_fork(self) -> None:
|
|
357
|
+
# A child never replays a journal on its own: the parent (or a sibling) may be
|
|
358
|
+
# replaying the same records. Call replay() explicitly in the one process
|
|
359
|
+
# that owns the journal.
|
|
360
|
+
self._replayed = True
|
|
361
|
+
self._condition = threading.Condition()
|
|
362
|
+
self._fork_dropped = self._pending
|
|
363
|
+
self._queue.clear()
|
|
364
|
+
self._pending = 0
|
|
365
|
+
self._thread = None
|
|
366
|
+
self._flushing = 0
|
|
367
|
+
|
|
368
|
+
def __get__(self, instance: Any, owner: type[Any] | None = None) -> Buffered:
|
|
369
|
+
if instance is None:
|
|
370
|
+
return self
|
|
371
|
+
return cast(Buffered, _bound_writer(self, instance))
|
|
372
|
+
|
|
373
|
+
def __call__(self, batch: list[Any]) -> Any:
|
|
374
|
+
return self.func(batch)
|
|
375
|
+
|
|
376
|
+
def submit(self, item: Any, *, timeout: float | None = None) -> bool:
|
|
377
|
+
"""Queue an item, returning False when disabled, closed, full, or timed out.
|
|
378
|
+
|
|
379
|
+
With a journal the record is persisted before this returns True; an error from
|
|
380
|
+
the journal propagates and the record is not queued.
|
|
381
|
+
"""
|
|
382
|
+
end = None if timeout is None else time.monotonic() + seconds(timeout, positive=False)
|
|
383
|
+
with self._condition:
|
|
384
|
+
if self._fork_dropped:
|
|
385
|
+
_log_warning(
|
|
386
|
+
self.log,
|
|
387
|
+
"buffered: discarded %d inherited pending records after fork",
|
|
388
|
+
self._fork_dropped,
|
|
389
|
+
)
|
|
390
|
+
self._fork_dropped = 0
|
|
391
|
+
self._replay_locked()
|
|
392
|
+
while self._enabled and not self._closing and len(self._queue) >= self.max_queue:
|
|
393
|
+
if self.on_full == "drop":
|
|
394
|
+
self._dropped += 1
|
|
395
|
+
return False
|
|
396
|
+
if self.on_full == "drop_oldest":
|
|
397
|
+
self._forget([self._queue.popleft()])
|
|
398
|
+
self._pending -= 1
|
|
399
|
+
self._dropped += 1
|
|
400
|
+
break
|
|
401
|
+
left = None if end is None else end - time.monotonic()
|
|
402
|
+
if left is not None and left <= 0:
|
|
403
|
+
self._dropped += 1
|
|
404
|
+
return False
|
|
405
|
+
self._condition.wait(left)
|
|
406
|
+
if not self._enabled or self._closing:
|
|
407
|
+
self._dropped += 1
|
|
408
|
+
return False
|
|
409
|
+
record_id = None if self.journal is None else self.journal.append(item)
|
|
410
|
+
self._queue.append((record_id, item))
|
|
411
|
+
self._pending += 1
|
|
412
|
+
try:
|
|
413
|
+
self._start_locked()
|
|
414
|
+
except BaseException:
|
|
415
|
+
self._queue.pop()
|
|
416
|
+
self._pending -= 1
|
|
417
|
+
raise
|
|
418
|
+
self._condition.notify_all()
|
|
419
|
+
return True
|
|
420
|
+
|
|
421
|
+
def replay(self) -> int:
|
|
422
|
+
"""Load the journal's unwritten records into the queue and start the writer.
|
|
423
|
+
|
|
424
|
+
Runs automatically on the first ``submit``; call it at startup to drain a
|
|
425
|
+
backlog before anything new is submitted. Only the first call (automatic or
|
|
426
|
+
explicit) replays; later calls return 0, as do writers without a journal.
|
|
427
|
+
|
|
428
|
+
Returns:
|
|
429
|
+
The number of records replayed.
|
|
430
|
+
"""
|
|
431
|
+
with self._condition:
|
|
432
|
+
count = self._replay_locked()
|
|
433
|
+
if count:
|
|
434
|
+
self._start_locked()
|
|
435
|
+
self._condition.notify_all()
|
|
436
|
+
return count
|
|
437
|
+
|
|
438
|
+
def _replay_locked(self) -> int:
|
|
439
|
+
if self._replayed or self.journal is None:
|
|
440
|
+
return 0
|
|
441
|
+
records = self.journal.pending()
|
|
442
|
+
self._replayed = True
|
|
443
|
+
self._queue.extendleft(reversed(records))
|
|
444
|
+
self._pending += len(records)
|
|
445
|
+
if records:
|
|
446
|
+
_log_warning(self.log, "buffered: replaying %d journaled records", len(records))
|
|
447
|
+
return len(records)
|
|
448
|
+
|
|
449
|
+
def _start_locked(self) -> None:
|
|
450
|
+
if self._thread is not None:
|
|
451
|
+
return
|
|
452
|
+
ctx = contextvars.copy_context()
|
|
453
|
+
self._thread = threading.Thread(
|
|
454
|
+
target=ctx.run, args=(self._run,), daemon=True, name="python-wrap-buffered"
|
|
455
|
+
)
|
|
456
|
+
try:
|
|
457
|
+
self._thread.start()
|
|
458
|
+
except BaseException:
|
|
459
|
+
self._thread = None
|
|
460
|
+
raise
|
|
461
|
+
atexit.register(self.close, self.drain)
|
|
462
|
+
|
|
463
|
+
def _forget(self, entries: Sequence[tuple[Hashable | None, Any]]) -> None:
|
|
464
|
+
"""Remove written or deliberately dropped records from the journal."""
|
|
465
|
+
_ack(self.journal, entries, self.log)
|
|
466
|
+
|
|
467
|
+
def _run(self) -> None:
|
|
468
|
+
while True:
|
|
469
|
+
with self._condition:
|
|
470
|
+
while not self._queue and not self._closing:
|
|
471
|
+
self._condition.wait()
|
|
472
|
+
if not self._queue:
|
|
473
|
+
return
|
|
474
|
+
end = time.monotonic() + self.interval
|
|
475
|
+
while len(self._queue) < self.max_size and not self._closing and not self._flushing:
|
|
476
|
+
left = end - time.monotonic()
|
|
477
|
+
if left <= 0:
|
|
478
|
+
break
|
|
479
|
+
self._condition.wait(left)
|
|
480
|
+
batch = [self._queue.popleft() for _ in range(min(self.max_size, len(self._queue)))]
|
|
481
|
+
self._condition.notify_all()
|
|
482
|
+
failed = False
|
|
483
|
+
try:
|
|
484
|
+
self.func([item for _, item in batch])
|
|
485
|
+
self._forget(batch)
|
|
486
|
+
except BaseException as exc:
|
|
487
|
+
failed = True
|
|
488
|
+
_log_failure(self.log, "buffered: batch write failed")
|
|
489
|
+
if not isinstance(exc, Exception):
|
|
490
|
+
with self._condition:
|
|
491
|
+
self._closing = True
|
|
492
|
+
self._enabled = False
|
|
493
|
+
self._dropped += len(self._queue)
|
|
494
|
+
self._pending -= len(self._queue)
|
|
495
|
+
self._queue.clear()
|
|
496
|
+
finally:
|
|
497
|
+
with self._condition:
|
|
498
|
+
self._pending -= len(batch)
|
|
499
|
+
if failed:
|
|
500
|
+
self._failed += 1
|
|
501
|
+
self._failed_records += len(batch)
|
|
502
|
+
if self.on_error == "disable":
|
|
503
|
+
self._enabled = False
|
|
504
|
+
self._dropped += len(self._queue)
|
|
505
|
+
self._pending -= len(self._queue)
|
|
506
|
+
self._queue.clear()
|
|
507
|
+
else:
|
|
508
|
+
self._written += len(batch)
|
|
509
|
+
self._condition.notify_all()
|
|
510
|
+
|
|
511
|
+
def flush(self, timeout: float | None = 5) -> bool:
|
|
512
|
+
"""Wait for pending writes; return False on timeout. Does not stop the writer."""
|
|
513
|
+
if self._thread is threading.current_thread():
|
|
514
|
+
raise RuntimeError("a buffered handler cannot flush itself")
|
|
515
|
+
end = None if timeout is None else time.monotonic() + seconds(timeout, positive=False)
|
|
516
|
+
with self._condition:
|
|
517
|
+
self._flushing += 1
|
|
518
|
+
self._condition.notify_all()
|
|
519
|
+
try:
|
|
520
|
+
while self._pending:
|
|
521
|
+
left = None if end is None else end - time.monotonic()
|
|
522
|
+
if left is not None and left <= 0:
|
|
523
|
+
return False
|
|
524
|
+
self._condition.wait(left)
|
|
525
|
+
return True
|
|
526
|
+
finally:
|
|
527
|
+
self._flushing -= 1
|
|
528
|
+
|
|
529
|
+
def close(self, timeout: float | None = 5) -> bool:
|
|
530
|
+
"""Stop accepting, drain queued writes, then end the worker when it is idle."""
|
|
531
|
+
with self._condition:
|
|
532
|
+
self._closing = True
|
|
533
|
+
self._condition.notify_all()
|
|
534
|
+
end = None if timeout is None else time.monotonic() + seconds(timeout, positive=False)
|
|
535
|
+
done = self.flush(timeout)
|
|
536
|
+
if done and self._thread is not None:
|
|
537
|
+
left = None if end is None else max(0, end - time.monotonic())
|
|
538
|
+
self._thread.join(left)
|
|
539
|
+
done = not self._thread.is_alive()
|
|
540
|
+
if done:
|
|
541
|
+
atexit.unregister(self.close)
|
|
542
|
+
return done
|
|
543
|
+
|
|
544
|
+
def disable(self, reason: str = "disabled") -> None:
|
|
545
|
+
"""Stop accepting new records; already queued records still drain."""
|
|
546
|
+
with self._condition:
|
|
547
|
+
self._enabled = False
|
|
548
|
+
self._condition.notify_all()
|
|
549
|
+
_log_warning(self.log, "buffered disabled: %s", reason)
|
|
550
|
+
|
|
551
|
+
def stats(self) -> BufferStats:
|
|
552
|
+
with self._condition:
|
|
553
|
+
return BufferStats(
|
|
554
|
+
self._pending,
|
|
555
|
+
self._written,
|
|
556
|
+
self._dropped,
|
|
557
|
+
self._failed,
|
|
558
|
+
self._failed_records,
|
|
559
|
+
self._enabled and not self._closing,
|
|
560
|
+
)
|
|
561
|
+
|
|
562
|
+
def __enter__(self) -> Buffered:
|
|
563
|
+
return self
|
|
564
|
+
|
|
565
|
+
def __exit__(self, *exc: Any) -> None:
|
|
566
|
+
self.close(self.drain)
|
|
567
|
+
|
|
568
|
+
|
|
569
|
+
class _AsyncSignal:
|
|
570
|
+
"""Register waiters synchronously, before wait_for can schedule another task.
|
|
571
|
+
|
|
572
|
+
Python 3.10 wait_for wraps coroutine arguments in a task. Sharing/clearing an
|
|
573
|
+
Event between producers and flushers can lose its notification before that task
|
|
574
|
+
starts. State predicates plus eagerly registered futures avoid that race.
|
|
575
|
+
"""
|
|
576
|
+
|
|
577
|
+
def __init__(self) -> None:
|
|
578
|
+
self.waiters: set[asyncio.Future[None]] = set()
|
|
579
|
+
|
|
580
|
+
def wait(self) -> asyncio.Future[None]:
|
|
581
|
+
future: asyncio.Future[None] = asyncio.get_running_loop().create_future()
|
|
582
|
+
self.waiters.add(future)
|
|
583
|
+
future.add_done_callback(self.waiters.discard)
|
|
584
|
+
return future
|
|
585
|
+
|
|
586
|
+
def set(self) -> None:
|
|
587
|
+
for future in tuple(self.waiters):
|
|
588
|
+
if not future.done():
|
|
589
|
+
future.set_result(None)
|
|
590
|
+
self.waiters.clear()
|
|
591
|
+
|
|
592
|
+
def clear(self) -> None:
|
|
593
|
+
# Notifications have no sticky state: callers always recheck their predicate.
|
|
594
|
+
pass
|
|
595
|
+
|
|
596
|
+
|
|
597
|
+
class AsyncBuffered:
|
|
598
|
+
"""Event-loop-local async writer with awaitable submit/flush/close controls.
|
|
599
|
+
|
|
600
|
+
Use `async with writer` or explicitly await close before stopping its loop.
|
|
601
|
+
Cancellation of close/flush does not cancel the writer. If the writer itself is
|
|
602
|
+
cancelled, its active batch is counted as failed, queued records are dropped,
|
|
603
|
+
and subsequent submissions are refused. Handlers may have performed side effects
|
|
604
|
+
before cancellation, so failed batches are never retried automatically.
|
|
605
|
+
|
|
606
|
+
``journal=`` works as for `Buffered` (replayed on the first ``submit`` or an
|
|
607
|
+
explicit ``await replay()``). Journal calls are synchronous and run on the event
|
|
608
|
+
loop, so use a local `SQLiteJournal`.
|
|
609
|
+
"""
|
|
610
|
+
|
|
611
|
+
def __init__(
|
|
612
|
+
self,
|
|
613
|
+
func: Callable[[list[Any]], Any],
|
|
614
|
+
*,
|
|
615
|
+
max_size: int = 200,
|
|
616
|
+
flush_interval: float = 1,
|
|
617
|
+
max_queue: int = 10000,
|
|
618
|
+
on_full: str = "drop",
|
|
619
|
+
drain_on_exit: float = 3,
|
|
620
|
+
on_error: str = "continue",
|
|
621
|
+
logger: Any = None,
|
|
622
|
+
journal: BufferJournal | None = None,
|
|
623
|
+
) -> None:
|
|
624
|
+
_validate(max_size, max_queue, on_full, on_error)
|
|
625
|
+
_validate_journal(journal)
|
|
626
|
+
self.func, self.max_size, self.max_queue = func, max_size, max_queue
|
|
627
|
+
self.interval = seconds(flush_interval)
|
|
628
|
+
self.drain = seconds(drain_on_exit, positive=False)
|
|
629
|
+
self.on_full, self.on_error = on_full, on_error
|
|
630
|
+
self.log = _core.get_logger(logger)
|
|
631
|
+
self.journal = journal
|
|
632
|
+
self._replayed = journal is None
|
|
633
|
+
self._bindings_lock = _fork.ForkSafeLock()
|
|
634
|
+
self._queue: deque[Any] = deque()
|
|
635
|
+
self._changed = _AsyncSignal()
|
|
636
|
+
self._loop: asyncio.AbstractEventLoop | None = None
|
|
637
|
+
self._task: asyncio.Task[None] | None = None
|
|
638
|
+
self._written = self._dropped = self._failed = self._failed_records = 0
|
|
639
|
+
self._pending = self._flushers = 0
|
|
640
|
+
self._enabled, self._closing = True, False
|
|
641
|
+
self._options = {
|
|
642
|
+
"max_size": max_size,
|
|
643
|
+
"flush_interval": flush_interval,
|
|
644
|
+
"max_queue": max_queue,
|
|
645
|
+
"on_full": on_full,
|
|
646
|
+
"drain_on_exit": drain_on_exit,
|
|
647
|
+
"on_error": on_error,
|
|
648
|
+
"logger": logger,
|
|
649
|
+
"journal": journal,
|
|
650
|
+
}
|
|
651
|
+
functools.update_wrapper(self, func, updated=())
|
|
652
|
+
_fork.register(self)
|
|
653
|
+
|
|
654
|
+
def _reset_after_fork(self) -> None:
|
|
655
|
+
self._replayed = True # see Buffered._reset_after_fork
|
|
656
|
+
self._dropped += self._pending
|
|
657
|
+
self._queue.clear()
|
|
658
|
+
self._changed = _AsyncSignal()
|
|
659
|
+
self._loop = None
|
|
660
|
+
self._task = None
|
|
661
|
+
self._pending = self._flushers = 0
|
|
662
|
+
|
|
663
|
+
def __get__(self, instance: Any, owner: type[Any] | None = None) -> AsyncBuffered:
|
|
664
|
+
if instance is None:
|
|
665
|
+
return self
|
|
666
|
+
return cast(AsyncBuffered, _bound_writer(self, instance))
|
|
667
|
+
|
|
668
|
+
async def __call__(self, batch: list[Any]) -> Any:
|
|
669
|
+
return await self.func(batch)
|
|
670
|
+
|
|
671
|
+
def _check_loop(self) -> asyncio.AbstractEventLoop:
|
|
672
|
+
loop = asyncio.get_running_loop()
|
|
673
|
+
if self._loop is not None and loop is not self._loop:
|
|
674
|
+
raise RuntimeError("AsyncBuffered belongs to another event loop")
|
|
675
|
+
return loop
|
|
676
|
+
|
|
677
|
+
async def submit(self, item: Any, *, timeout: float | None = None) -> bool:
|
|
678
|
+
"""Queue one record; blocked calls recheck close/disable before acceptance."""
|
|
679
|
+
loop = self._check_loop()
|
|
680
|
+
end = None if timeout is None else loop.time() + seconds(timeout, positive=False)
|
|
681
|
+
self._replay_now()
|
|
682
|
+
while self._enabled and not self._closing and len(self._queue) >= self.max_queue:
|
|
683
|
+
if self.on_full == "drop":
|
|
684
|
+
self._dropped += 1
|
|
685
|
+
return False
|
|
686
|
+
if self.on_full == "drop_oldest":
|
|
687
|
+
_ack(self.journal, [self._queue.popleft()], self.log)
|
|
688
|
+
self._pending -= 1
|
|
689
|
+
self._dropped += 1
|
|
690
|
+
break
|
|
691
|
+
self._changed.clear()
|
|
692
|
+
left = None if end is None else end - loop.time()
|
|
693
|
+
if left is not None and left <= 0:
|
|
694
|
+
self._dropped += 1
|
|
695
|
+
return False
|
|
696
|
+
try:
|
|
697
|
+
await asyncio.wait_for(self._changed.wait(), left)
|
|
698
|
+
except asyncio.TimeoutError:
|
|
699
|
+
self._dropped += 1
|
|
700
|
+
return False
|
|
701
|
+
if not self._enabled or self._closing:
|
|
702
|
+
self._dropped += 1
|
|
703
|
+
return False
|
|
704
|
+
record_id = None if self.journal is None else self.journal.append(item)
|
|
705
|
+
self._queue.append((record_id, item))
|
|
706
|
+
self._pending += 1
|
|
707
|
+
try:
|
|
708
|
+
self._start(loop)
|
|
709
|
+
except BaseException:
|
|
710
|
+
self._queue.pop()
|
|
711
|
+
self._pending -= 1
|
|
712
|
+
raise
|
|
713
|
+
self._changed.set()
|
|
714
|
+
return True
|
|
715
|
+
|
|
716
|
+
async def replay(self) -> int:
|
|
717
|
+
"""`Buffered.replay` for async writers: load the journal and start the writer."""
|
|
718
|
+
loop = self._check_loop()
|
|
719
|
+
count = self._replay_now()
|
|
720
|
+
if count:
|
|
721
|
+
self._start(loop)
|
|
722
|
+
self._changed.set()
|
|
723
|
+
return count
|
|
724
|
+
|
|
725
|
+
def _replay_now(self) -> int:
|
|
726
|
+
if self._replayed or self.journal is None:
|
|
727
|
+
return 0
|
|
728
|
+
records = self.journal.pending()
|
|
729
|
+
self._replayed = True
|
|
730
|
+
self._queue.extendleft(reversed(records))
|
|
731
|
+
self._pending += len(records)
|
|
732
|
+
if records:
|
|
733
|
+
_log_warning(self.log, "buffered: replaying %d journaled records", len(records))
|
|
734
|
+
return len(records)
|
|
735
|
+
|
|
736
|
+
def _start(self, loop: asyncio.AbstractEventLoop) -> None:
|
|
737
|
+
if self._task is None:
|
|
738
|
+
self._loop = loop
|
|
739
|
+
self._task = loop.create_task(self._run())
|
|
740
|
+
|
|
741
|
+
async def _run(self) -> None:
|
|
742
|
+
active: list[Any] = []
|
|
743
|
+
try:
|
|
744
|
+
while True:
|
|
745
|
+
while not self._queue and not self._closing:
|
|
746
|
+
self._changed.clear()
|
|
747
|
+
await self._changed.wait()
|
|
748
|
+
if not self._queue:
|
|
749
|
+
return
|
|
750
|
+
end = asyncio.get_running_loop().time() + self.interval
|
|
751
|
+
while len(self._queue) < self.max_size and not self._closing and not self._flushers:
|
|
752
|
+
left = end - asyncio.get_running_loop().time()
|
|
753
|
+
if left <= 0:
|
|
754
|
+
break
|
|
755
|
+
self._changed.clear()
|
|
756
|
+
try:
|
|
757
|
+
await asyncio.wait_for(self._changed.wait(), left)
|
|
758
|
+
except asyncio.TimeoutError:
|
|
759
|
+
break
|
|
760
|
+
active = [
|
|
761
|
+
self._queue.popleft() for _ in range(min(self.max_size, len(self._queue)))
|
|
762
|
+
]
|
|
763
|
+
self._changed.set()
|
|
764
|
+
try:
|
|
765
|
+
await self.func([item for _, item in active])
|
|
766
|
+
_ack(self.journal, active, self.log)
|
|
767
|
+
except Exception:
|
|
768
|
+
self._failed += 1
|
|
769
|
+
self._failed_records += len(active)
|
|
770
|
+
_log_failure(self.log, "buffered: async batch write failed")
|
|
771
|
+
if self.on_error == "disable":
|
|
772
|
+
self._enabled = False
|
|
773
|
+
self._drop_queue()
|
|
774
|
+
else:
|
|
775
|
+
self._written += len(active)
|
|
776
|
+
self._pending -= len(active)
|
|
777
|
+
active = []
|
|
778
|
+
self._changed.set()
|
|
779
|
+
finally:
|
|
780
|
+
if active:
|
|
781
|
+
self._failed += 1
|
|
782
|
+
self._failed_records += len(active)
|
|
783
|
+
self._pending -= len(active)
|
|
784
|
+
self._enabled = False
|
|
785
|
+
self._closing = True
|
|
786
|
+
self._drop_queue()
|
|
787
|
+
self._changed.set()
|
|
788
|
+
|
|
789
|
+
def _drop_queue(self) -> None:
|
|
790
|
+
self._dropped += len(self._queue)
|
|
791
|
+
self._pending -= len(self._queue)
|
|
792
|
+
self._queue.clear()
|
|
793
|
+
|
|
794
|
+
async def flush(self, timeout: float | None = 5) -> bool:
|
|
795
|
+
"""Immediately dispatch queued batches and wait for writes, bounded by timeout."""
|
|
796
|
+
loop = self._check_loop()
|
|
797
|
+
if asyncio.current_task() is self._task:
|
|
798
|
+
raise RuntimeError("a buffered handler cannot flush itself")
|
|
799
|
+
end = None if timeout is None else loop.time() + seconds(timeout, positive=False)
|
|
800
|
+
self._flushers += 1
|
|
801
|
+
self._changed.set()
|
|
802
|
+
try:
|
|
803
|
+
while self._pending:
|
|
804
|
+
left = None if end is None else end - loop.time()
|
|
805
|
+
if left is not None and left <= 0:
|
|
806
|
+
return False
|
|
807
|
+
self._changed.clear()
|
|
808
|
+
try:
|
|
809
|
+
await asyncio.wait_for(self._changed.wait(), left)
|
|
810
|
+
except asyncio.TimeoutError:
|
|
811
|
+
return False
|
|
812
|
+
return True
|
|
813
|
+
finally:
|
|
814
|
+
self._flushers -= 1
|
|
815
|
+
|
|
816
|
+
async def close(self, timeout: float | None = 5) -> bool:
|
|
817
|
+
"""Refuse new submissions and drain; cancellation leaves the writer running."""
|
|
818
|
+
self._check_loop()
|
|
819
|
+
self._closing = True
|
|
820
|
+
self._changed.set()
|
|
821
|
+
done = await self.flush(timeout)
|
|
822
|
+
if done and self._task is not None and not self._task.cancelled():
|
|
823
|
+
await asyncio.shield(self._task)
|
|
824
|
+
return done
|
|
825
|
+
|
|
826
|
+
def disable(self, reason: str = "disabled") -> None:
|
|
827
|
+
self._enabled = False
|
|
828
|
+
self._changed.set()
|
|
829
|
+
_log_warning(self.log, "buffered disabled: %s", reason)
|
|
830
|
+
|
|
831
|
+
def stats(self) -> BufferStats:
|
|
832
|
+
return BufferStats(
|
|
833
|
+
self._pending,
|
|
834
|
+
self._written,
|
|
835
|
+
self._dropped,
|
|
836
|
+
self._failed,
|
|
837
|
+
self._failed_records,
|
|
838
|
+
self._enabled and not self._closing,
|
|
839
|
+
)
|
|
840
|
+
|
|
841
|
+
async def __aenter__(self) -> AsyncBuffered:
|
|
842
|
+
self._check_loop()
|
|
843
|
+
return self
|
|
844
|
+
|
|
845
|
+
async def __aexit__(self, *exc: Any) -> None:
|
|
846
|
+
await self.close(self.drain)
|
|
847
|
+
|
|
848
|
+
|
|
849
|
+
def _ack(
|
|
850
|
+
journal: BufferJournal | None, entries: Sequence[tuple[Hashable | None, Any]], log: Any
|
|
851
|
+
) -> None:
|
|
852
|
+
"""Acknowledge journaled entries; a failure only means they may be replayed again."""
|
|
853
|
+
if journal is None:
|
|
854
|
+
return
|
|
855
|
+
ids = [record_id for record_id, _ in entries if record_id is not None]
|
|
856
|
+
if not ids:
|
|
857
|
+
return
|
|
858
|
+
try:
|
|
859
|
+
journal.ack(ids)
|
|
860
|
+
except Exception:
|
|
861
|
+
_log_failure(log, "buffered: journal ack failed; records may be written again")
|
|
862
|
+
|
|
863
|
+
|
|
864
|
+
def _validate_journal(journal: Any) -> None:
|
|
865
|
+
if journal is not None and not isinstance(journal, BufferJournal):
|
|
866
|
+
raise TypeError("journal must implement BufferJournal: append, ack and pending")
|
|
867
|
+
|
|
868
|
+
|
|
869
|
+
def _bound_writer(writer: Any, instance: Any) -> Any:
|
|
870
|
+
"""Keep independent, lazily started buffers on each instance/class."""
|
|
871
|
+
if writer.journal is not None:
|
|
872
|
+
raise TypeError(
|
|
873
|
+
"buffered methods cannot use journal=: every instance would replay the same "
|
|
874
|
+
"records; use a module-level buffered function"
|
|
875
|
+
)
|
|
876
|
+
name = f"_python_wrap_buffer_{id(writer)}"
|
|
877
|
+
with writer._bindings_lock:
|
|
878
|
+
try:
|
|
879
|
+
stored = vars(instance).get(name)
|
|
880
|
+
except TypeError:
|
|
881
|
+
raise TypeError("buffered methods require instances with __dict__") from None
|
|
882
|
+
if stored is None:
|
|
883
|
+
stored = type(writer)(functools.partial(writer.func, instance), **writer._options)
|
|
884
|
+
setattr(instance, name, stored)
|
|
885
|
+
return stored
|
|
886
|
+
|
|
887
|
+
|
|
888
|
+
def _log_failure(logger: Any, message: str) -> None:
|
|
889
|
+
with contextlib.suppress(Exception):
|
|
890
|
+
logger.exception(message)
|
|
891
|
+
|
|
892
|
+
|
|
893
|
+
def _log_warning(logger: Any, message: str, *args: Any) -> None:
|
|
894
|
+
with contextlib.suppress(Exception):
|
|
895
|
+
logger.warning(message, *args)
|
|
896
|
+
|
|
897
|
+
|
|
898
|
+
def _validate(size: int, capacity: int, on_full: str, on_error: str) -> None:
|
|
899
|
+
if (
|
|
900
|
+
isinstance(size, bool)
|
|
901
|
+
or not isinstance(size, int)
|
|
902
|
+
or isinstance(capacity, bool)
|
|
903
|
+
or not isinstance(capacity, int)
|
|
904
|
+
or size < 1
|
|
905
|
+
or capacity < 1
|
|
906
|
+
):
|
|
907
|
+
raise ValueError("max_size and max_queue must be positive")
|
|
908
|
+
if on_full not in {"drop", "block", "drop_oldest"}:
|
|
909
|
+
raise ValueError("on_full must be drop, block or drop_oldest")
|
|
910
|
+
if on_error not in {"continue", "disable"}:
|
|
911
|
+
raise ValueError("on_error must be continue or disable")
|
|
912
|
+
|
|
913
|
+
|
|
914
|
+
class _BufferedDecorator(Protocol):
|
|
915
|
+
@overload
|
|
916
|
+
def __call__(self, func: Callable[..., Coroutine[Any, Any, Any]]) -> AsyncBuffered: ...
|
|
917
|
+
@overload
|
|
918
|
+
def __call__(self, func: Callable[..., Any]) -> Buffered: ...
|
|
919
|
+
|
|
920
|
+
|
|
921
|
+
def buffered(
|
|
922
|
+
*,
|
|
923
|
+
max_size: int = 200,
|
|
924
|
+
flush_interval: float = 1,
|
|
925
|
+
max_queue: int = 10000,
|
|
926
|
+
on_full: str = "drop",
|
|
927
|
+
drain_on_exit: float = 3,
|
|
928
|
+
on_error: str = "continue",
|
|
929
|
+
logger: Any = None,
|
|
930
|
+
journal: BufferJournal | None = None,
|
|
931
|
+
) -> _BufferedDecorator:
|
|
932
|
+
"""Decorate a batch handler with a lazy sync or async background buffer.
|
|
933
|
+
|
|
934
|
+
``journal`` (a `SQLiteJournal`, `RedisStreamJournal` or any `BufferJournal`) makes
|
|
935
|
+
accepted records durable with at-least-once replay after a restart; without it,
|
|
936
|
+
records live only in memory.
|
|
937
|
+
"""
|
|
938
|
+
options: dict[str, Any] = {
|
|
939
|
+
"max_size": max_size,
|
|
940
|
+
"flush_interval": flush_interval,
|
|
941
|
+
"max_queue": max_queue,
|
|
942
|
+
"on_full": on_full,
|
|
943
|
+
"drain_on_exit": drain_on_exit,
|
|
944
|
+
"on_error": on_error,
|
|
945
|
+
"logger": logger,
|
|
946
|
+
"journal": journal,
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
def decorate(func: Callable[..., Any]) -> Any:
|
|
950
|
+
return AsyncBuffered(func, **options) if _core.is_async(func) else Buffered(func, **options)
|
|
951
|
+
|
|
952
|
+
return cast(_BufferedDecorator, decorate)
|