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
|
@@ -0,0 +1,395 @@
|
|
|
1
|
+
"""Share circuit breaker state between processes on one host, without Redis.
|
|
2
|
+
|
|
3
|
+
`SQLiteBreakerState` is a drop-in ``backend=`` for `CircuitBreaker` with the same
|
|
4
|
+
contract and semantics as `RedisBreakerState`, stored in a local SQLite file. Use it for
|
|
5
|
+
gunicorn or uvicorn workers and Celery prefork children on a single machine: one
|
|
6
|
+
worker's failures open the breaker for all of them.
|
|
7
|
+
|
|
8
|
+
Every operation is one ``BEGIN IMMEDIATE`` transaction (atomic across processes), the
|
|
9
|
+
database runs in WAL mode, and each thread of each process gets its own connection,
|
|
10
|
+
reopened after a fork. Time is the wall clock (`_core.wall_time`), the only clock the
|
|
11
|
+
processes share.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import contextlib
|
|
17
|
+
import math
|
|
18
|
+
import os
|
|
19
|
+
import sqlite3
|
|
20
|
+
import threading
|
|
21
|
+
import time
|
|
22
|
+
import uuid
|
|
23
|
+
from typing import Any
|
|
24
|
+
|
|
25
|
+
from python_wrap import _core, _fork
|
|
26
|
+
|
|
27
|
+
__all__ = ["SQLiteBreakerState"]
|
|
28
|
+
|
|
29
|
+
_SCHEMA = (
|
|
30
|
+
"""CREATE TABLE IF NOT EXISTS breakers (
|
|
31
|
+
name TEXT PRIMARY KEY,
|
|
32
|
+
state TEXT NOT NULL DEFAULT 'closed',
|
|
33
|
+
gen INTEGER NOT NULL DEFAULT 0,
|
|
34
|
+
opened INTEGER NOT NULL DEFAULT 0,
|
|
35
|
+
failures INTEGER NOT NULL DEFAULT 0,
|
|
36
|
+
trials INTEGER NOT NULL DEFAULT 0,
|
|
37
|
+
successes INTEGER NOT NULL DEFAULT 0,
|
|
38
|
+
trial_deadline INTEGER NOT NULL DEFAULT 0,
|
|
39
|
+
total_failures INTEGER NOT NULL DEFAULT 0,
|
|
40
|
+
total_successes INTEGER NOT NULL DEFAULT 0,
|
|
41
|
+
total_rejected INTEGER NOT NULL DEFAULT 0
|
|
42
|
+
)""",
|
|
43
|
+
"""CREATE TABLE IF NOT EXISTS breaker_failures (
|
|
44
|
+
name TEXT NOT NULL,
|
|
45
|
+
ts INTEGER NOT NULL,
|
|
46
|
+
id TEXT NOT NULL
|
|
47
|
+
)""",
|
|
48
|
+
"CREATE INDEX IF NOT EXISTS breaker_failures_name_ts ON breaker_failures (name, ts)",
|
|
49
|
+
"""CREATE TABLE IF NOT EXISTS breaker_slots (
|
|
50
|
+
name TEXT NOT NULL,
|
|
51
|
+
slot INTEGER NOT NULL,
|
|
52
|
+
calls INTEGER NOT NULL DEFAULT 0,
|
|
53
|
+
failures INTEGER NOT NULL DEFAULT 0,
|
|
54
|
+
slow INTEGER NOT NULL DEFAULT 0,
|
|
55
|
+
PRIMARY KEY (name, slot)
|
|
56
|
+
)""",
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
_COLUMNS = (
|
|
60
|
+
"state",
|
|
61
|
+
"gen",
|
|
62
|
+
"opened",
|
|
63
|
+
"failures",
|
|
64
|
+
"trials",
|
|
65
|
+
"successes",
|
|
66
|
+
"trial_deadline",
|
|
67
|
+
"total_failures",
|
|
68
|
+
"total_successes",
|
|
69
|
+
"total_rejected",
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class SQLiteBreakerState:
|
|
74
|
+
"""Breaker state in a local SQLite file, shared by every process that opens it.
|
|
75
|
+
|
|
76
|
+
Use the same path, and the same breaker name and settings, in every process. The
|
|
77
|
+
directory must exist and be writable by all of them. Backend errors (for example a
|
|
78
|
+
database that stays locked longer than ``busy_timeout``) propagate; they are never
|
|
79
|
+
read as a healthy dependency. Half-open reservations expire after
|
|
80
|
+
``max(1s, recovery_timeout)``, so a crashed probing worker cannot hold the trial
|
|
81
|
+
slot forever. Not suitable for network file systems.
|
|
82
|
+
|
|
83
|
+
Args:
|
|
84
|
+
path: Database file path (created on first use). ``":memory:"`` is rejected:
|
|
85
|
+
each connection would get a private database.
|
|
86
|
+
busy_timeout: Seconds to wait for another process's transaction.
|
|
87
|
+
|
|
88
|
+
Raises:
|
|
89
|
+
ValueError: For an empty or in-memory path, or a negative ``busy_timeout``.
|
|
90
|
+
|
|
91
|
+
Example:
|
|
92
|
+
```python
|
|
93
|
+
import os
|
|
94
|
+
import tempfile
|
|
95
|
+
|
|
96
|
+
from python_wrap import CircuitBreaker
|
|
97
|
+
from python_wrap.local_state import SQLiteBreakerState
|
|
98
|
+
|
|
99
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
100
|
+
state = SQLiteBreakerState(os.path.join(tmp, "breakers.db"))
|
|
101
|
+
breaker = CircuitBreaker(name="vendor-api", backend=state, failure_threshold=1)
|
|
102
|
+
breaker.force_open()
|
|
103
|
+
other = CircuitBreaker(name="vendor-api", backend=state, failure_threshold=1)
|
|
104
|
+
assert other.state.value == "open"
|
|
105
|
+
state.close()
|
|
106
|
+
```
|
|
107
|
+
"""
|
|
108
|
+
|
|
109
|
+
def __init__(self, path: str | os.PathLike[str], *, busy_timeout: float = 5.0) -> None:
|
|
110
|
+
text = os.fspath(path)
|
|
111
|
+
if not text or text == ":memory:" or text.startswith("file::memory:"):
|
|
112
|
+
raise ValueError("path must name a file shared between processes")
|
|
113
|
+
if not math.isfinite(busy_timeout) or busy_timeout < 0:
|
|
114
|
+
raise ValueError("busy_timeout must be finite and >= 0")
|
|
115
|
+
self.path, self.busy_timeout = text, float(busy_timeout)
|
|
116
|
+
self._local = threading.local()
|
|
117
|
+
self._lock = _fork.ForkSafeLock()
|
|
118
|
+
self._conns: list[sqlite3.Connection] = []
|
|
119
|
+
self._abandoned: list[sqlite3.Connection] = []
|
|
120
|
+
self._pid = os.getpid()
|
|
121
|
+
_fork.register(self)
|
|
122
|
+
|
|
123
|
+
def _reset_after_fork(self) -> None:
|
|
124
|
+
# Never use or close a connection inherited across fork; just park it.
|
|
125
|
+
self._abandoned.extend(self._conns)
|
|
126
|
+
self._conns = []
|
|
127
|
+
self._local = threading.local()
|
|
128
|
+
self._pid = os.getpid()
|
|
129
|
+
|
|
130
|
+
# -- connections -------------------------------------------------------------------
|
|
131
|
+
def _setup(self, conn: sqlite3.Connection) -> None:
|
|
132
|
+
"""Switch to WAL and create the schema.
|
|
133
|
+
|
|
134
|
+
Changing the journal mode takes a lock that SQLite does not always wait for with
|
|
135
|
+
the busy handler, so concurrent first connections (threads or processes) can see
|
|
136
|
+
"database is locked" immediately. Retry until ``busy_timeout`` has elapsed.
|
|
137
|
+
"""
|
|
138
|
+
deadline = time.monotonic() + self.busy_timeout
|
|
139
|
+
while True:
|
|
140
|
+
try:
|
|
141
|
+
conn.execute("PRAGMA journal_mode=WAL")
|
|
142
|
+
conn.execute("PRAGMA synchronous=NORMAL")
|
|
143
|
+
for statement in _SCHEMA:
|
|
144
|
+
conn.execute(statement)
|
|
145
|
+
return
|
|
146
|
+
except sqlite3.OperationalError as exc:
|
|
147
|
+
if "locked" not in str(exc) or time.monotonic() >= deadline:
|
|
148
|
+
raise
|
|
149
|
+
time.sleep(0.005)
|
|
150
|
+
|
|
151
|
+
def _connection(self) -> sqlite3.Connection:
|
|
152
|
+
if self._pid != os.getpid(): # fork without the at-fork hook (non-POSIX paths)
|
|
153
|
+
self._reset_after_fork()
|
|
154
|
+
conn: sqlite3.Connection | None = getattr(self._local, "conn", None)
|
|
155
|
+
if conn is not None:
|
|
156
|
+
return conn
|
|
157
|
+
conn = sqlite3.connect(
|
|
158
|
+
self.path,
|
|
159
|
+
timeout=self.busy_timeout,
|
|
160
|
+
isolation_level=None,
|
|
161
|
+
check_same_thread=False,
|
|
162
|
+
)
|
|
163
|
+
try:
|
|
164
|
+
conn.execute(f"PRAGMA busy_timeout={int(self.busy_timeout * 1000)}")
|
|
165
|
+
self._setup(conn)
|
|
166
|
+
except BaseException:
|
|
167
|
+
conn.close()
|
|
168
|
+
raise
|
|
169
|
+
self._local.conn = conn
|
|
170
|
+
with self._lock:
|
|
171
|
+
self._conns.append(conn)
|
|
172
|
+
return conn
|
|
173
|
+
|
|
174
|
+
def close(self) -> None:
|
|
175
|
+
"""Close every connection this process opened. The state stays in the file."""
|
|
176
|
+
with self._lock:
|
|
177
|
+
conns, self._conns = self._conns, []
|
|
178
|
+
self._local = threading.local()
|
|
179
|
+
for conn in conns:
|
|
180
|
+
with contextlib.suppress(sqlite3.Error):
|
|
181
|
+
conn.close()
|
|
182
|
+
|
|
183
|
+
# -- the contract ------------------------------------------------------------------
|
|
184
|
+
def operate(
|
|
185
|
+
self,
|
|
186
|
+
breaker: Any,
|
|
187
|
+
operation: str,
|
|
188
|
+
generation: int = 0,
|
|
189
|
+
trial: bool = False,
|
|
190
|
+
slow: bool = False,
|
|
191
|
+
) -> dict[str, Any]:
|
|
192
|
+
"""Apply one breaker operation atomically and return the resulting row.
|
|
193
|
+
|
|
194
|
+
Args:
|
|
195
|
+
breaker: A `CircuitBreaker` (its name and settings are read).
|
|
196
|
+
operation: ``state``, ``admit``, ``success``, ``failure``, ``neutral``,
|
|
197
|
+
``reset`` or ``force_open``.
|
|
198
|
+
generation: The generation the call was admitted under; outcomes from an
|
|
199
|
+
older generation are ignored.
|
|
200
|
+
trial: Whether the call was a half-open trial.
|
|
201
|
+
slow: Whether the call took longer than the breaker's ``slow_call_duration``.
|
|
202
|
+
|
|
203
|
+
Returns:
|
|
204
|
+
A dict with the same keys as `RedisBreakerState.operate`.
|
|
205
|
+
"""
|
|
206
|
+
conn = self._connection()
|
|
207
|
+
conn.execute("BEGIN IMMEDIATE")
|
|
208
|
+
try:
|
|
209
|
+
data = self._apply(conn, breaker, operation, generation, trial, slow)
|
|
210
|
+
except BaseException:
|
|
211
|
+
conn.execute("ROLLBACK")
|
|
212
|
+
raise
|
|
213
|
+
conn.execute("COMMIT")
|
|
214
|
+
return data
|
|
215
|
+
|
|
216
|
+
@staticmethod
|
|
217
|
+
def _slots(
|
|
218
|
+
conn: sqlite3.Connection,
|
|
219
|
+
name: str,
|
|
220
|
+
now: int,
|
|
221
|
+
window: int,
|
|
222
|
+
calls: int,
|
|
223
|
+
failed: int,
|
|
224
|
+
slow: int,
|
|
225
|
+
) -> tuple[int, int, int]:
|
|
226
|
+
"""Record an outcome in its time slot (ten per window) and sum the live slots."""
|
|
227
|
+
slot = now // max(1, window // 10)
|
|
228
|
+
conn.execute("DELETE FROM breaker_slots WHERE name=? AND slot<=?", (name, slot - 10))
|
|
229
|
+
if calls:
|
|
230
|
+
conn.execute(
|
|
231
|
+
"INSERT INTO breaker_slots (name, slot, calls, failures, slow) VALUES (?,?,?,?,?)"
|
|
232
|
+
" ON CONFLICT (name, slot) DO UPDATE SET calls=calls+excluded.calls,"
|
|
233
|
+
" failures=failures+excluded.failures, slow=slow+excluded.slow",
|
|
234
|
+
(name, slot, calls, failed, slow),
|
|
235
|
+
)
|
|
236
|
+
row = conn.execute(
|
|
237
|
+
"SELECT COALESCE(SUM(calls),0), COALESCE(SUM(failures),0), COALESCE(SUM(slow),0)"
|
|
238
|
+
" FROM breaker_slots WHERE name=?",
|
|
239
|
+
(name,),
|
|
240
|
+
).fetchone()
|
|
241
|
+
return int(row[0]), int(row[1]), int(row[2])
|
|
242
|
+
|
|
243
|
+
def _apply(
|
|
244
|
+
self,
|
|
245
|
+
conn: sqlite3.Connection,
|
|
246
|
+
breaker: Any,
|
|
247
|
+
op: str,
|
|
248
|
+
generation: int,
|
|
249
|
+
is_trial: bool,
|
|
250
|
+
is_slow: bool = False,
|
|
251
|
+
) -> dict[str, Any]:
|
|
252
|
+
name: str = breaker.name
|
|
253
|
+
frate = getattr(breaker, "failure_rate", None) or 0
|
|
254
|
+
srate = getattr(breaker, "slow_call_rate", None) or 0
|
|
255
|
+
minc, rated, slow = getattr(breaker, "minimum_calls", 1), bool(frate or srate), int(is_slow)
|
|
256
|
+
wc = wf = ws = 0
|
|
257
|
+
trip = False
|
|
258
|
+
|
|
259
|
+
def trips() -> bool:
|
|
260
|
+
return wc >= minc and bool((frate and wf >= frate * wc) or (srate and ws >= srate * wc))
|
|
261
|
+
|
|
262
|
+
now = int(_core.wall_time() * 1000)
|
|
263
|
+
threshold = breaker.failure_threshold
|
|
264
|
+
window = 0 if breaker.window is None else max(1, math.ceil(breaker.window * 1000))
|
|
265
|
+
reset = math.ceil(breaker.recovery_timeout * 1000)
|
|
266
|
+
halfmax, target = breaker.half_open_max_calls, breaker.success_threshold
|
|
267
|
+
|
|
268
|
+
conn.execute("INSERT OR IGNORE INTO breakers (name) VALUES (?)", (name,))
|
|
269
|
+
# _COLUMNS is a module constant; the only value is bound as a parameter.
|
|
270
|
+
query = f"SELECT {', '.join(_COLUMNS)} FROM breakers WHERE name=?" # nosec B608
|
|
271
|
+
row = conn.execute(query, (name,))
|
|
272
|
+
(
|
|
273
|
+
state,
|
|
274
|
+
gen,
|
|
275
|
+
opened,
|
|
276
|
+
failures,
|
|
277
|
+
trials,
|
|
278
|
+
successes,
|
|
279
|
+
deadline,
|
|
280
|
+
total_failures,
|
|
281
|
+
total_successes,
|
|
282
|
+
total_rejected,
|
|
283
|
+
) = row.fetchone()
|
|
284
|
+
old = state
|
|
285
|
+
admitted, trial, wait = 1, 0, 0
|
|
286
|
+
|
|
287
|
+
if op == "reset":
|
|
288
|
+
state, failures, trials, successes, opened = "closed", 0, 0, 0, 0
|
|
289
|
+
gen += 1
|
|
290
|
+
total_failures = total_successes = total_rejected = 0
|
|
291
|
+
conn.execute("DELETE FROM breaker_failures WHERE name=?", (name,))
|
|
292
|
+
conn.execute("DELETE FROM breaker_slots WHERE name=?", (name,))
|
|
293
|
+
elif op == "force_open":
|
|
294
|
+
state, opened, trials = "open", now, 0
|
|
295
|
+
gen += 1
|
|
296
|
+
else:
|
|
297
|
+
if state == "open" and now - opened >= reset:
|
|
298
|
+
state, trials, successes = "half_open", 0, 0
|
|
299
|
+
gen += 1
|
|
300
|
+
deadline = now + max(1000, reset)
|
|
301
|
+
if op == "admit":
|
|
302
|
+
if state == "half_open" and now >= deadline:
|
|
303
|
+
gen += 1
|
|
304
|
+
trials = successes = 0
|
|
305
|
+
deadline = now + max(1000, reset)
|
|
306
|
+
if state == "open" or (state == "half_open" and trials >= halfmax):
|
|
307
|
+
admitted = 0
|
|
308
|
+
wait = max(0, opened + reset - now)
|
|
309
|
+
total_rejected += 1
|
|
310
|
+
elif state == "half_open":
|
|
311
|
+
trial = 1
|
|
312
|
+
trials += 1
|
|
313
|
+
elif op in ("success", "failure", "neutral") and generation == gen:
|
|
314
|
+
if is_trial:
|
|
315
|
+
trials = max(0, trials - 1)
|
|
316
|
+
if op == "success":
|
|
317
|
+
total_successes += 1
|
|
318
|
+
if state == "half_open" and slow and srate:
|
|
319
|
+
trip = True
|
|
320
|
+
elif state == "half_open":
|
|
321
|
+
successes += 1
|
|
322
|
+
if successes >= target:
|
|
323
|
+
state, failures = "closed", 0
|
|
324
|
+
gen += 1
|
|
325
|
+
conn.execute("DELETE FROM breaker_failures WHERE name=?", (name,))
|
|
326
|
+
conn.execute("DELETE FROM breaker_slots WHERE name=?", (name,))
|
|
327
|
+
else:
|
|
328
|
+
if window == 0:
|
|
329
|
+
failures = 0
|
|
330
|
+
if rated and not is_trial:
|
|
331
|
+
wc, wf, ws = self._slots(conn, name, now, window, 1, 0, slow)
|
|
332
|
+
trip = trips()
|
|
333
|
+
elif op == "failure":
|
|
334
|
+
total_failures += 1
|
|
335
|
+
if rated and not is_trial and state != "half_open":
|
|
336
|
+
wc, wf, ws = self._slots(conn, name, now, window, 1, 1, slow)
|
|
337
|
+
trip = trips()
|
|
338
|
+
if frate:
|
|
339
|
+
failures = wf
|
|
340
|
+
elif window > 0:
|
|
341
|
+
conn.execute(
|
|
342
|
+
"DELETE FROM breaker_failures WHERE name=? AND ts<=?",
|
|
343
|
+
(name, now - window),
|
|
344
|
+
)
|
|
345
|
+
conn.execute(
|
|
346
|
+
"INSERT INTO breaker_failures (name, ts, id) VALUES (?, ?, ?)",
|
|
347
|
+
(name, now, uuid.uuid4().hex),
|
|
348
|
+
)
|
|
349
|
+
failures = conn.execute(
|
|
350
|
+
"SELECT COUNT(*) FROM breaker_failures WHERE name=?", (name,)
|
|
351
|
+
).fetchone()[0]
|
|
352
|
+
else:
|
|
353
|
+
failures += 1
|
|
354
|
+
if state == "half_open" or (not frate and failures >= threshold):
|
|
355
|
+
trip = True
|
|
356
|
+
if trip:
|
|
357
|
+
state, opened, trials, successes = "open", now, 0, 0
|
|
358
|
+
gen += 1
|
|
359
|
+
if rated and wc == 0:
|
|
360
|
+
wc, wf, ws = self._slots(conn, name, now, window, 0, 0, 0)
|
|
361
|
+
|
|
362
|
+
conn.execute(
|
|
363
|
+
"UPDATE breakers SET state=?, gen=?, opened=?, failures=?, trials=?, successes=?,"
|
|
364
|
+
" trial_deadline=?, total_failures=?, total_successes=?, total_rejected=?"
|
|
365
|
+
" WHERE name=?",
|
|
366
|
+
(
|
|
367
|
+
state,
|
|
368
|
+
gen,
|
|
369
|
+
opened,
|
|
370
|
+
failures,
|
|
371
|
+
trials,
|
|
372
|
+
successes,
|
|
373
|
+
deadline,
|
|
374
|
+
total_failures,
|
|
375
|
+
total_successes,
|
|
376
|
+
total_rejected,
|
|
377
|
+
name,
|
|
378
|
+
),
|
|
379
|
+
)
|
|
380
|
+
return {
|
|
381
|
+
"admitted": admitted,
|
|
382
|
+
"state": state,
|
|
383
|
+
"generation": gen,
|
|
384
|
+
"trial": trial,
|
|
385
|
+
"wait": wait,
|
|
386
|
+
"failures": failures,
|
|
387
|
+
"total_failures": total_failures,
|
|
388
|
+
"total_successes": total_successes,
|
|
389
|
+
"total_rejected": total_rejected,
|
|
390
|
+
"opened": opened,
|
|
391
|
+
"old": old,
|
|
392
|
+
"window_calls": wc,
|
|
393
|
+
"window_failures": wf,
|
|
394
|
+
"window_slow": ws,
|
|
395
|
+
}
|
python_wrap/logs.py
CHANGED
|
@@ -22,35 +22,26 @@ from typing import Any, TypeVar, cast, overload
|
|
|
22
22
|
|
|
23
23
|
from python_wrap import _core, config
|
|
24
24
|
from python_wrap._core import F, LoggerLike, P, R
|
|
25
|
+
from python_wrap.redaction import DEFAULT_REDACT
|
|
26
|
+
from python_wrap.redaction import is_sensitive as _is_sensitive
|
|
27
|
+
from python_wrap.redaction import redact as _deep_redact
|
|
25
28
|
|
|
26
29
|
__all__ = [
|
|
27
30
|
"DEFAULT_REDACT",
|
|
28
31
|
"AuditRecord",
|
|
32
|
+
"ContextFilter",
|
|
29
33
|
"audit",
|
|
34
|
+
"bind",
|
|
30
35
|
"current_log_context",
|
|
31
36
|
"log_args",
|
|
32
37
|
"log_context",
|
|
33
38
|
"log_return",
|
|
34
39
|
"trace",
|
|
40
|
+
"unbind",
|
|
35
41
|
]
|
|
36
42
|
|
|
37
43
|
S = TypeVar("S")
|
|
38
44
|
|
|
39
|
-
DEFAULT_REDACT: tuple[str, ...] = (
|
|
40
|
-
"password",
|
|
41
|
-
"passwd",
|
|
42
|
-
"secret",
|
|
43
|
-
"token",
|
|
44
|
-
"api_key",
|
|
45
|
-
"apikey",
|
|
46
|
-
"authorization",
|
|
47
|
-
"auth",
|
|
48
|
-
"credential",
|
|
49
|
-
"private_key",
|
|
50
|
-
"cookie",
|
|
51
|
-
"session",
|
|
52
|
-
)
|
|
53
|
-
|
|
54
45
|
_MASK = "***"
|
|
55
46
|
_PACKAGE_DIR = os.path.dirname(os.path.abspath(__file__))
|
|
56
47
|
|
|
@@ -115,12 +106,20 @@ def _instrument(
|
|
|
115
106
|
return cast("Callable[P, R]", wrapper)
|
|
116
107
|
|
|
117
108
|
|
|
118
|
-
def _redact_predicate(
|
|
119
|
-
|
|
120
|
-
|
|
109
|
+
def _redact_predicate(
|
|
110
|
+
redact: Iterable[str] | None, match: str = "segment"
|
|
111
|
+
) -> Callable[[str], bool]:
|
|
112
|
+
"""Build a "does this name look sensitive" test.
|
|
113
|
+
|
|
114
|
+
Whole-segment matching is the default so ``author`` and ``session_date`` are not
|
|
115
|
+
mistaken for secrets; ``match="substring"`` keeps the old, looser behaviour.
|
|
116
|
+
"""
|
|
117
|
+
if match not in ("segment", "substring"):
|
|
118
|
+
raise ValueError("redact_match must be segment or substring")
|
|
119
|
+
needles = tuple(n for n in (DEFAULT_REDACT if redact is None else redact) if n)
|
|
121
120
|
if not needles:
|
|
122
121
|
return lambda name: False
|
|
123
|
-
return lambda name:
|
|
122
|
+
return lambda name: _is_sensitive(name, needles, match=match)
|
|
124
123
|
|
|
125
124
|
|
|
126
125
|
def _short(value: object, max_length: int) -> str:
|
|
@@ -374,6 +373,8 @@ def log_args(
|
|
|
374
373
|
level: int = logging.DEBUG,
|
|
375
374
|
redact: Iterable[str] | None = None,
|
|
376
375
|
redact_extra: Iterable[str] = (),
|
|
376
|
+
redact_match: str = "segment",
|
|
377
|
+
deep: bool = False,
|
|
377
378
|
max_length: int = 200,
|
|
378
379
|
) -> Callable[[F], F]: ...
|
|
379
380
|
def log_args(
|
|
@@ -384,6 +385,8 @@ def log_args(
|
|
|
384
385
|
level: int = logging.DEBUG,
|
|
385
386
|
redact: Iterable[str] | None = None,
|
|
386
387
|
redact_extra: Iterable[str] = (),
|
|
388
|
+
redact_match: str = "segment",
|
|
389
|
+
deep: bool = False,
|
|
387
390
|
max_length: int = 200,
|
|
388
391
|
) -> Any:
|
|
389
392
|
"""Log each call's arguments, by parameter name, before running it.
|
|
@@ -395,12 +398,19 @@ def log_args(
|
|
|
395
398
|
func: The function, when used as a bare ``@log_args``.
|
|
396
399
|
logger: A ``logging.Logger``, a logger name, or ``None`` for the package logger.
|
|
397
400
|
level: Log level. Defaults to ``DEBUG`` (v0.1 logged at ``INFO``).
|
|
398
|
-
redact: Parameter-name fragments whose values are shown as ``'***'
|
|
399
|
-
|
|
400
|
-
`
|
|
401
|
-
|
|
401
|
+
redact: Parameter-name fragments whose values are shown as ``'***'``.
|
|
402
|
+
``None`` (default) uses `DEFAULT_REDACT` or the list set by
|
|
403
|
+
`python_wrap.config.configure`. A list given here **replaces** that; pass
|
|
404
|
+
``()`` to disable redaction.
|
|
402
405
|
redact_extra: Fragments to mask **in addition** to the list above (never
|
|
403
406
|
replaces it). Added to any `redact_extra` set via `configure`.
|
|
407
|
+
redact_match: ``"segment"`` (default) masks a name only when a whole word
|
|
408
|
+
segment matches, so ``author`` and ``session_date`` stay visible while
|
|
409
|
+
``auth_token`` and ``session_token`` are masked. Ambiguous bare ``auth``
|
|
410
|
+
and ``session`` are exact-only defaults; custom fragments match segments.
|
|
411
|
+
``"substring"`` restores the old looser matching.
|
|
412
|
+
deep: Also mask nested mappings/containers without modifying inputs. Depth
|
|
413
|
+
limits and cycles are masked entirely rather than exposing raw data.
|
|
404
414
|
max_length: Longest rendering of a single value before it is truncated.
|
|
405
415
|
|
|
406
416
|
Returns:
|
|
@@ -410,7 +420,8 @@ def log_args(
|
|
|
410
420
|
>>> @log_args(logger="app")
|
|
411
421
|
... def login(user, password): ...
|
|
412
422
|
"""
|
|
413
|
-
|
|
423
|
+
fragments = config.redaction(redact, DEFAULT_REDACT) + tuple(redact_extra)
|
|
424
|
+
secret = _redact_predicate(fragments, redact_match)
|
|
414
425
|
|
|
415
426
|
def decorate(f: Callable[P, R]) -> Callable[P, R]:
|
|
416
427
|
lg = _core.get_logger(logger)
|
|
@@ -420,6 +431,8 @@ def log_args(
|
|
|
420
431
|
def start(args: tuple[Any, ...], kwargs: dict[str, Any]) -> None:
|
|
421
432
|
if lg.isEnabledFor(level):
|
|
422
433
|
bound = binder(args, kwargs)
|
|
434
|
+
if deep:
|
|
435
|
+
bound = _deep_redact(bound, fragments=fragments, match=redact_match)
|
|
423
436
|
_log(lg, level, "Calling %s", _format_call(name, bound, max_length))
|
|
424
437
|
|
|
425
438
|
return _instrument(f, start, lambda state, ok, value: None)
|
|
@@ -527,6 +540,8 @@ def audit(
|
|
|
527
540
|
level: int = logging.INFO,
|
|
528
541
|
redact: Iterable[str] | None = None,
|
|
529
542
|
redact_extra: Iterable[str] = (),
|
|
543
|
+
redact_match: str = "segment",
|
|
544
|
+
deep: bool = False,
|
|
530
545
|
include_result: bool = False,
|
|
531
546
|
sink: Callable[[AuditRecord], None] | None = None,
|
|
532
547
|
) -> Callable[[F], F]: ...
|
|
@@ -538,6 +553,8 @@ def audit(
|
|
|
538
553
|
level: int = logging.INFO,
|
|
539
554
|
redact: Iterable[str] | None = None,
|
|
540
555
|
redact_extra: Iterable[str] = (),
|
|
556
|
+
redact_match: str = "segment",
|
|
557
|
+
deep: bool = False,
|
|
541
558
|
include_result: bool = False,
|
|
542
559
|
sink: Callable[[AuditRecord], None] | None = None,
|
|
543
560
|
) -> Any:
|
|
@@ -558,6 +575,8 @@ def audit(
|
|
|
558
575
|
disables redaction.
|
|
559
576
|
redact_extra: Fragments to mask in addition to the list above (never
|
|
560
577
|
replaces it). Added to any `redact_extra` set via `configure`.
|
|
578
|
+
redact_match: ``"segment"`` (default) or ``"substring"``; see `log_args`.
|
|
579
|
+
deep: Also mask nested argument mappings/containers, without mutating inputs.
|
|
561
580
|
include_result: Store the return value in ``record.result``.
|
|
562
581
|
sink: Callable receiving every record, e.g. to write to a database.
|
|
563
582
|
|
|
@@ -569,7 +588,8 @@ def audit(
|
|
|
569
588
|
>>> @audit(sink=records.append)
|
|
570
589
|
... def delete_user(user_id, token): ...
|
|
571
590
|
"""
|
|
572
|
-
|
|
591
|
+
fragments = config.redaction(redact, DEFAULT_REDACT) + tuple(redact_extra)
|
|
592
|
+
secret = _redact_predicate(fragments, redact_match)
|
|
573
593
|
|
|
574
594
|
def decorate(f: Callable[P, R]) -> Callable[P, R]:
|
|
575
595
|
lg = _core.get_logger(logger)
|
|
@@ -581,10 +601,13 @@ def audit(
|
|
|
581
601
|
) -> tuple[datetime, str, dict[str, Any], float, dict[str, Any]] | None:
|
|
582
602
|
if sink is None and not lg.isEnabledFor(level):
|
|
583
603
|
return None # nobody would see the record: skip building it
|
|
604
|
+
arguments = binder(args, kwargs)
|
|
605
|
+
if deep:
|
|
606
|
+
arguments = _deep_redact(arguments, fragments=fragments, match=redact_match)
|
|
584
607
|
return (
|
|
585
608
|
datetime.now(timezone.utc),
|
|
586
609
|
_caller_location(),
|
|
587
|
-
|
|
610
|
+
arguments,
|
|
588
611
|
_core.perf_counter(),
|
|
589
612
|
current_log_context(),
|
|
590
613
|
)
|
|
@@ -765,3 +788,36 @@ def trace(
|
|
|
765
788
|
return _instrument(f, start, finish)
|
|
766
789
|
|
|
767
790
|
return decorate if func is None else decorate(func)
|
|
791
|
+
|
|
792
|
+
|
|
793
|
+
def bind(**fields: Any) -> contextvars.Token[Mapping[str, Any]]:
|
|
794
|
+
"""Merge context fields and return a token for `unbind` in request/task hooks."""
|
|
795
|
+
return _log_fields.set(MappingProxyType({**_log_fields.get(), **fields}))
|
|
796
|
+
|
|
797
|
+
|
|
798
|
+
def unbind(token: contextvars.Token[Mapping[str, Any]]) -> None:
|
|
799
|
+
"""Restore a bind token in the same context where it was created."""
|
|
800
|
+
_log_fields.reset(token)
|
|
801
|
+
|
|
802
|
+
|
|
803
|
+
class ContextFilter(logging.Filter):
|
|
804
|
+
"""Inject log_context into arbitrary application records, attached to handlers.
|
|
805
|
+
|
|
806
|
+
Explicit `extra=` attributes win; reserved LogRecord fields are never overwritten.
|
|
807
|
+
Defaults ensure formatter fields such as `user` exist outside requests too.
|
|
808
|
+
"""
|
|
809
|
+
|
|
810
|
+
def __init__(self, defaults: Mapping[str, Any] | None = None, *, as_attrs: bool = True) -> None:
|
|
811
|
+
super().__init__()
|
|
812
|
+
self.defaults = dict(defaults or {})
|
|
813
|
+
self.as_attrs = as_attrs
|
|
814
|
+
|
|
815
|
+
def filter(self, record: logging.LogRecord) -> bool:
|
|
816
|
+
fields = {**self.defaults, **current_log_context()}
|
|
817
|
+
explicit = getattr(record, "context", {})
|
|
818
|
+
record.context = {**fields, **(explicit if isinstance(explicit, Mapping) else {})}
|
|
819
|
+
if self.as_attrs:
|
|
820
|
+
for key, value in fields.items():
|
|
821
|
+
if key not in ("message", "asctime") and not hasattr(record, key):
|
|
822
|
+
setattr(record, key, value)
|
|
823
|
+
return True
|