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,126 @@
|
|
|
1
|
+
"""Expiring credential caching with one refresh per key and explicit invalidation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import functools
|
|
6
|
+
import inspect
|
|
7
|
+
from collections.abc import Callable, Coroutine
|
|
8
|
+
from typing import Any, Concatenate, ParamSpec, Protocol, TypeVar, cast, overload
|
|
9
|
+
|
|
10
|
+
from python_wrap import _core, _fork
|
|
11
|
+
from python_wrap._runtime import seconds
|
|
12
|
+
from python_wrap.caching import CacheInfo, memoize
|
|
13
|
+
from python_wrap.concurrency import singleflight
|
|
14
|
+
|
|
15
|
+
__all__ = ["Expiring", "expiring"]
|
|
16
|
+
P = ParamSpec("P")
|
|
17
|
+
P2 = ParamSpec("P2")
|
|
18
|
+
R = TypeVar("R")
|
|
19
|
+
R_co = TypeVar("R_co", covariant=True)
|
|
20
|
+
T = TypeVar("T")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class Expiring(Protocol[P, R_co]):
|
|
24
|
+
"""A credential-returning callable with invalidate and cache_info controls."""
|
|
25
|
+
|
|
26
|
+
def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R_co: ...
|
|
27
|
+
|
|
28
|
+
def invalidate(self) -> None:
|
|
29
|
+
"""Invalidate cached values; later calls cannot join an older refresh."""
|
|
30
|
+
|
|
31
|
+
def cache_info(self) -> CacheInfo:
|
|
32
|
+
"""Return statistics for the credential cache."""
|
|
33
|
+
|
|
34
|
+
@overload
|
|
35
|
+
def __get__(
|
|
36
|
+
self: Expiring[Concatenate[T, P2], R_co],
|
|
37
|
+
instance: T,
|
|
38
|
+
owner: type[T] | None = None,
|
|
39
|
+
) -> Expiring[P2, R_co]: ...
|
|
40
|
+
|
|
41
|
+
@overload
|
|
42
|
+
def __get__(self, instance: None, owner: type[Any] | None = None) -> Expiring[P, R_co]: ...
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class _ExpiringDecorator(Protocol):
|
|
46
|
+
@overload
|
|
47
|
+
def __call__(
|
|
48
|
+
self, func: Callable[P, Coroutine[Any, Any, tuple[R, float]]]
|
|
49
|
+
) -> Expiring[P, Coroutine[Any, Any, R]]: ...
|
|
50
|
+
|
|
51
|
+
@overload
|
|
52
|
+
def __call__(self, func: Callable[P, tuple[R, float]]) -> Expiring[P, R]: ...
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def expiring(*, refresh_margin: float = 60) -> _ExpiringDecorator:
|
|
56
|
+
"""Cache a loader returning (value, expires_in_seconds), returning just its value.
|
|
57
|
+
|
|
58
|
+
Refreshes are coalesced across callers. Expiry is relative to successful loading,
|
|
59
|
+
reduced by refresh_margin. `.invalidate()` forces the next call to refresh, even
|
|
60
|
+
when a refresh that started before invalidation is still running. Old callers may
|
|
61
|
+
receive their old refresh's result, but it cannot populate the new cache generation.
|
|
62
|
+
For credentials whose lifetime is shorter than the margin no value is cached.
|
|
63
|
+
Sync and async loaders are supported; failures are not cached. Arguments follow
|
|
64
|
+
memoize's hashability rules, including `self` for methods.
|
|
65
|
+
"""
|
|
66
|
+
margin = seconds(refresh_margin, positive=False)
|
|
67
|
+
|
|
68
|
+
def decorate(func: Callable[..., Any]) -> Any:
|
|
69
|
+
generation = 0
|
|
70
|
+
lock = _fork.ForkSafeLock()
|
|
71
|
+
signature = inspect.signature(func)
|
|
72
|
+
|
|
73
|
+
def normalize(
|
|
74
|
+
args: tuple[Any, ...], kw: dict[str, Any]
|
|
75
|
+
) -> tuple[tuple[Any, ...], dict[str, Any]]:
|
|
76
|
+
bound = signature.bind(*args, **kw)
|
|
77
|
+
bound.apply_defaults()
|
|
78
|
+
return bound.args, bound.kwargs
|
|
79
|
+
|
|
80
|
+
def ttl(result: Any) -> float:
|
|
81
|
+
if not isinstance(result, tuple) or len(result) != 2:
|
|
82
|
+
raise TypeError("expiring loaders must return (value, expires_in_seconds)")
|
|
83
|
+
return max(0, seconds(result[1], positive=False) - margin)
|
|
84
|
+
|
|
85
|
+
if _core.is_async(func):
|
|
86
|
+
# The generation is part of the in-flight key, so invalidate is a barrier.
|
|
87
|
+
async def load(version: int, /, *args: Any, **kw: Any) -> Any:
|
|
88
|
+
return await func(*args, **kw)
|
|
89
|
+
|
|
90
|
+
cached: Any = memoize(ttl=ttl)(singleflight(load))
|
|
91
|
+
|
|
92
|
+
@functools.wraps(func)
|
|
93
|
+
async def aw(*args: Any, **kw: Any) -> Any:
|
|
94
|
+
with lock:
|
|
95
|
+
version = generation
|
|
96
|
+
args, kw = normalize(args, kw)
|
|
97
|
+
return (await cached(version, *args, **kw))[0]
|
|
98
|
+
|
|
99
|
+
wrapper: Any = aw
|
|
100
|
+
else:
|
|
101
|
+
|
|
102
|
+
def load_sync(version: int, /, *args: Any, **kw: Any) -> Any:
|
|
103
|
+
return func(*args, **kw)
|
|
104
|
+
|
|
105
|
+
cached = memoize(ttl=ttl)(singleflight(load_sync))
|
|
106
|
+
|
|
107
|
+
@functools.wraps(func)
|
|
108
|
+
def sw(*args: Any, **kw: Any) -> Any:
|
|
109
|
+
with lock:
|
|
110
|
+
version = generation
|
|
111
|
+
args, kw = normalize(args, kw)
|
|
112
|
+
return cached(version, *args, **kw)[0]
|
|
113
|
+
|
|
114
|
+
wrapper = sw
|
|
115
|
+
|
|
116
|
+
def invalidate() -> None:
|
|
117
|
+
nonlocal generation
|
|
118
|
+
with lock:
|
|
119
|
+
generation += 1
|
|
120
|
+
cached.cache_clear()
|
|
121
|
+
|
|
122
|
+
wrapper.__dict__["invalidate"] = invalidate
|
|
123
|
+
wrapper.__dict__["cache_info"] = cached.cache_info
|
|
124
|
+
return wrapper
|
|
125
|
+
|
|
126
|
+
return cast(_ExpiringDecorator, decorate)
|
python_wrap/dashboard.py
ADDED
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
"""A small live dashboard of resilience state for local development and staging.
|
|
2
|
+
|
|
3
|
+
`Dashboard` listens to the event stream, keeps a bounded ring buffer of recent events and
|
|
4
|
+
per-function counters, combines them with a `HealthRegistry` report, and serves a single
|
|
5
|
+
self-contained HTML page that refreshes itself from a JSON endpoint.
|
|
6
|
+
|
|
7
|
+
The dashboard has no authentication. Bind it to localhost, or mount it behind your own
|
|
8
|
+
access control. Never expose it publicly: function names, breaker names and event timing
|
|
9
|
+
are operational details. Exception messages are never recorded, only exception type names.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import json
|
|
15
|
+
import threading
|
|
16
|
+
from collections import deque
|
|
17
|
+
from collections.abc import Callable, Mapping
|
|
18
|
+
from socketserver import ThreadingMixIn
|
|
19
|
+
from typing import Any
|
|
20
|
+
from wsgiref.simple_server import WSGIRequestHandler, WSGIServer, make_server
|
|
21
|
+
|
|
22
|
+
from python_wrap import _core, _fork
|
|
23
|
+
from python_wrap.events import Event, subscribe
|
|
24
|
+
from python_wrap.exporters import PrometheusExporter
|
|
25
|
+
from python_wrap.health import HealthRegistry, health
|
|
26
|
+
|
|
27
|
+
__all__ = ["Dashboard"]
|
|
28
|
+
|
|
29
|
+
_RATE_WINDOW = 60.0
|
|
30
|
+
_MAX_FUNCTIONS = 500
|
|
31
|
+
_COUNTER_KEYS = {
|
|
32
|
+
"retry.attempt_failed": "retries",
|
|
33
|
+
"retry.gave_up": "gave_up",
|
|
34
|
+
"timeout.expired": "timeouts",
|
|
35
|
+
"circuit.rejected": "rejections",
|
|
36
|
+
"rate_limit.rejected": "rejections",
|
|
37
|
+
"bulkhead.rejected": "rejections",
|
|
38
|
+
"cache.hit": "cache_hits",
|
|
39
|
+
"cache.miss": "cache_misses",
|
|
40
|
+
}
|
|
41
|
+
_RATE_KINDS = {
|
|
42
|
+
"retry.attempt_failed": "retries",
|
|
43
|
+
"retry.gave_up": "gave_up",
|
|
44
|
+
"circuit.rejected": "rejections",
|
|
45
|
+
"rate_limit.rejected": "rejections",
|
|
46
|
+
"bulkhead.rejected": "rejections",
|
|
47
|
+
"timeout.expired": "timeouts",
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _safe_field(value: Any) -> Any:
|
|
52
|
+
"""Reduce a field to something JSON-safe and free of messages."""
|
|
53
|
+
if isinstance(value, BaseException):
|
|
54
|
+
return type(value).__name__
|
|
55
|
+
enum_value = getattr(value, "value", None)
|
|
56
|
+
if isinstance(enum_value, str):
|
|
57
|
+
return enum_value
|
|
58
|
+
if value is None or isinstance(value, (bool, int, float)):
|
|
59
|
+
return value
|
|
60
|
+
if isinstance(value, str):
|
|
61
|
+
return value[:100]
|
|
62
|
+
return type(value).__name__
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class Dashboard:
|
|
66
|
+
"""Collect recent events and health state and present them as JSON or HTML.
|
|
67
|
+
|
|
68
|
+
Args:
|
|
69
|
+
registry: `HealthRegistry` whose report is shown (breakers, bulkheads, checks).
|
|
70
|
+
exporter: Optional `PrometheusExporter`; its metrics are included in the snapshot.
|
|
71
|
+
recent: How many recent events to keep.
|
|
72
|
+
|
|
73
|
+
Raises:
|
|
74
|
+
ValueError: If ``recent`` is below 1.
|
|
75
|
+
|
|
76
|
+
Example:
|
|
77
|
+
>>> from python_wrap import _core
|
|
78
|
+
>>> with Dashboard(recent=10) as dash:
|
|
79
|
+
... _core.emit("cache.hit", "load")
|
|
80
|
+
... dash.snapshot()["functions"].get("load", {}).get("cache_hits")
|
|
81
|
+
1
|
|
82
|
+
"""
|
|
83
|
+
|
|
84
|
+
def __init__(
|
|
85
|
+
self,
|
|
86
|
+
*,
|
|
87
|
+
registry: HealthRegistry | None = health,
|
|
88
|
+
exporter: PrometheusExporter | None = None,
|
|
89
|
+
recent: int = 200,
|
|
90
|
+
) -> None:
|
|
91
|
+
if recent < 1:
|
|
92
|
+
raise ValueError("recent must be at least 1")
|
|
93
|
+
self.registry = registry
|
|
94
|
+
self.exporter = exporter
|
|
95
|
+
self._lock = _fork.ForkSafeLock()
|
|
96
|
+
self._events: deque[dict[str, Any]] = deque(maxlen=recent)
|
|
97
|
+
self._functions: dict[str, dict[str, int]] = {}
|
|
98
|
+
self._breakers: dict[str, str] = {}
|
|
99
|
+
self._recent_rates: deque[tuple[float, str]] = deque(maxlen=10_000)
|
|
100
|
+
self._started = _core.wall_time()
|
|
101
|
+
self._unsubscribe: Callable[[], None] | None = None
|
|
102
|
+
|
|
103
|
+
# ------------------------------------------------------------------ lifecycle
|
|
104
|
+
|
|
105
|
+
def install(self) -> Dashboard:
|
|
106
|
+
"""Subscribe to the event stream. Returns this dashboard."""
|
|
107
|
+
with self._lock:
|
|
108
|
+
if self._unsubscribe is None:
|
|
109
|
+
self._unsubscribe = subscribe(self._on_event)
|
|
110
|
+
return self
|
|
111
|
+
|
|
112
|
+
def close(self) -> None:
|
|
113
|
+
"""Unsubscribe. Collected data stays available."""
|
|
114
|
+
with self._lock:
|
|
115
|
+
unsubscribe, self._unsubscribe = self._unsubscribe, None
|
|
116
|
+
if unsubscribe is not None:
|
|
117
|
+
unsubscribe()
|
|
118
|
+
|
|
119
|
+
def __enter__(self) -> Dashboard:
|
|
120
|
+
return self.install()
|
|
121
|
+
|
|
122
|
+
def __exit__(self, *exc: object) -> None:
|
|
123
|
+
self.close()
|
|
124
|
+
|
|
125
|
+
# ------------------------------------------------------------------ collection
|
|
126
|
+
|
|
127
|
+
def _on_event(self, event: Event) -> None:
|
|
128
|
+
fields = {k: _safe_field(v) for k, v in event.fields.items()}
|
|
129
|
+
record = {
|
|
130
|
+
"time": _core.wall_time(),
|
|
131
|
+
"event": event.name,
|
|
132
|
+
"function": event.function,
|
|
133
|
+
"fields": fields,
|
|
134
|
+
}
|
|
135
|
+
now = _core.monotonic()
|
|
136
|
+
with self._lock:
|
|
137
|
+
self._events.append(record)
|
|
138
|
+
name = event.function
|
|
139
|
+
if name not in self._functions and len(self._functions) >= _MAX_FUNCTIONS:
|
|
140
|
+
name = "_other"
|
|
141
|
+
counters = self._functions.setdefault(
|
|
142
|
+
name,
|
|
143
|
+
{
|
|
144
|
+
"events": 0,
|
|
145
|
+
"retries": 0,
|
|
146
|
+
"gave_up": 0,
|
|
147
|
+
"timeouts": 0,
|
|
148
|
+
"rejections": 0,
|
|
149
|
+
"cache_hits": 0,
|
|
150
|
+
"cache_misses": 0,
|
|
151
|
+
},
|
|
152
|
+
)
|
|
153
|
+
counters["events"] += 1
|
|
154
|
+
key = _COUNTER_KEYS.get(event.name)
|
|
155
|
+
if key is not None:
|
|
156
|
+
counters[key] += 1
|
|
157
|
+
kind = _RATE_KINDS.get(event.name)
|
|
158
|
+
if kind is not None:
|
|
159
|
+
self._recent_rates.append((now, kind))
|
|
160
|
+
if event.name == "circuit.state_changed":
|
|
161
|
+
self._breakers[event.function] = str(fields.get("new"))
|
|
162
|
+
|
|
163
|
+
# ------------------------------------------------------------------ output
|
|
164
|
+
|
|
165
|
+
def snapshot(self) -> dict[str, Any]:
|
|
166
|
+
"""Return the current state as JSON-serialisable data.
|
|
167
|
+
|
|
168
|
+
Keys: ``time``, ``uptime_seconds``, ``health`` (registry report), ``breakers``
|
|
169
|
+
(name to last observed state), ``functions`` (per-function counters), ``rates``
|
|
170
|
+
(counts over the last 60 seconds), ``events`` (newest last) and, when an exporter
|
|
171
|
+
was given, ``metrics``.
|
|
172
|
+
"""
|
|
173
|
+
report = self.registry.report() if self.registry is not None else {}
|
|
174
|
+
now = _core.monotonic()
|
|
175
|
+
with self._lock:
|
|
176
|
+
events = list(self._events)
|
|
177
|
+
functions = {name: dict(c) for name, c in self._functions.items()}
|
|
178
|
+
breakers = dict(self._breakers)
|
|
179
|
+
rates = {"window_seconds": _RATE_WINDOW, **dict.fromkeys(set(_RATE_KINDS.values()), 0)}
|
|
180
|
+
for stamp, kind in self._recent_rates:
|
|
181
|
+
if now - stamp <= _RATE_WINDOW:
|
|
182
|
+
rates[kind] += 1
|
|
183
|
+
for name, info in report.items():
|
|
184
|
+
state = info.get("state")
|
|
185
|
+
if isinstance(state, str):
|
|
186
|
+
breakers[name] = state
|
|
187
|
+
data: dict[str, Any] = {
|
|
188
|
+
"time": _core.wall_time(),
|
|
189
|
+
"uptime_seconds": round(_core.wall_time() - self._started, 3),
|
|
190
|
+
"health": report,
|
|
191
|
+
"breakers": breakers,
|
|
192
|
+
"functions": functions,
|
|
193
|
+
"rates": rates,
|
|
194
|
+
"events": events,
|
|
195
|
+
}
|
|
196
|
+
if self.exporter is not None:
|
|
197
|
+
data["metrics"] = self.exporter.snapshot()
|
|
198
|
+
return json.loads(json.dumps(data, default=_safe_field)) # type: ignore[no-any-return]
|
|
199
|
+
|
|
200
|
+
def render_html(self) -> str:
|
|
201
|
+
"""Return the dashboard as one self-contained HTML page (no external assets)."""
|
|
202
|
+
return _HTML
|
|
203
|
+
|
|
204
|
+
# ------------------------------------------------------------------ serving
|
|
205
|
+
|
|
206
|
+
def _respond(self, method: str, path: str) -> tuple[str, str, bytes]:
|
|
207
|
+
if method not in ("GET", "HEAD"):
|
|
208
|
+
return "405 Method Not Allowed", "text/plain; charset=utf-8", b"method not allowed\n"
|
|
209
|
+
if path.endswith("/snapshot.json"):
|
|
210
|
+
body = json.dumps(self.snapshot()).encode("utf-8")
|
|
211
|
+
return "200 OK", "application/json", body
|
|
212
|
+
if path in ("", "/") or path.endswith("/"):
|
|
213
|
+
return "200 OK", "text/html; charset=utf-8", self.render_html().encode("utf-8")
|
|
214
|
+
return "404 Not Found", "text/plain; charset=utf-8", b"not found\n"
|
|
215
|
+
|
|
216
|
+
def wsgi_app(
|
|
217
|
+
self, environ: Mapping[str, Any], start_response: Callable[..., Any]
|
|
218
|
+
) -> list[bytes]:
|
|
219
|
+
"""WSGI application serving ``/`` (HTML) and ``/snapshot.json``."""
|
|
220
|
+
method = str(environ.get("REQUEST_METHOD", "GET")).upper()
|
|
221
|
+
status, ctype, body = self._respond(method, str(environ.get("PATH_INFO", "")))
|
|
222
|
+
start_response(
|
|
223
|
+
status,
|
|
224
|
+
[
|
|
225
|
+
("Content-Type", ctype),
|
|
226
|
+
("Content-Length", str(len(body))),
|
|
227
|
+
("Cache-Control", "no-store"),
|
|
228
|
+
],
|
|
229
|
+
)
|
|
230
|
+
return [] if method == "HEAD" else [body]
|
|
231
|
+
|
|
232
|
+
async def asgi_app(
|
|
233
|
+
self, scope: Mapping[str, Any], receive: Callable[..., Any], send: Callable[..., Any]
|
|
234
|
+
) -> None:
|
|
235
|
+
"""ASGI application serving ``/`` (HTML) and ``/snapshot.json``."""
|
|
236
|
+
if scope.get("type") == "lifespan":
|
|
237
|
+
while True:
|
|
238
|
+
message = await receive()
|
|
239
|
+
if message["type"] == "lifespan.startup":
|
|
240
|
+
await send({"type": "lifespan.startup.complete"})
|
|
241
|
+
else:
|
|
242
|
+
await send({"type": "lifespan.shutdown.complete"})
|
|
243
|
+
return
|
|
244
|
+
if scope.get("type") != "http":
|
|
245
|
+
return
|
|
246
|
+
method = str(scope.get("method", "GET")).upper()
|
|
247
|
+
status, ctype, body = self._respond(method, str(scope.get("path", "")))
|
|
248
|
+
headers = [
|
|
249
|
+
(b"content-type", ctype.encode("ascii")),
|
|
250
|
+
(b"content-length", str(len(body)).encode("ascii")),
|
|
251
|
+
(b"cache-control", b"no-store"),
|
|
252
|
+
]
|
|
253
|
+
await send({"type": "http.response.start", "status": int(status[:3]), "headers": headers})
|
|
254
|
+
await send({"type": "http.response.body", "body": b"" if method == "HEAD" else body})
|
|
255
|
+
|
|
256
|
+
def serve(self, host: str = "127.0.0.1", port: int = 0) -> tuple[WSGIServer, threading.Thread]:
|
|
257
|
+
"""Serve the dashboard from a daemon thread, for local development.
|
|
258
|
+
|
|
259
|
+
Installs the event listener if needed. Call ``server.shutdown()`` to stop it; that
|
|
260
|
+
also closes the socket and removes the listener this call installed. There is no
|
|
261
|
+
authentication: keep the default localhost binding.
|
|
262
|
+
|
|
263
|
+
Args:
|
|
264
|
+
host: Interface to bind. Defaults to localhost only.
|
|
265
|
+
port: Port to bind; ``0`` picks a free one (see ``server.server_address``).
|
|
266
|
+
|
|
267
|
+
Returns:
|
|
268
|
+
The server and its running thread.
|
|
269
|
+
"""
|
|
270
|
+
was_installed = self._unsubscribe is not None
|
|
271
|
+
self.install()
|
|
272
|
+
dashboard = self
|
|
273
|
+
|
|
274
|
+
class _Server(ThreadingMixIn, WSGIServer):
|
|
275
|
+
daemon_threads = True
|
|
276
|
+
|
|
277
|
+
def shutdown(self) -> None:
|
|
278
|
+
super().shutdown()
|
|
279
|
+
self.server_close()
|
|
280
|
+
if not was_installed:
|
|
281
|
+
dashboard.close()
|
|
282
|
+
|
|
283
|
+
class _Quiet(WSGIRequestHandler):
|
|
284
|
+
def log_message(self, format: str, *args: Any) -> None:
|
|
285
|
+
return
|
|
286
|
+
|
|
287
|
+
server = make_server(host, port, self.wsgi_app, server_class=_Server, handler_class=_Quiet)
|
|
288
|
+
thread = threading.Thread(
|
|
289
|
+
target=server.serve_forever, name="python-wrap-dashboard", daemon=True
|
|
290
|
+
)
|
|
291
|
+
thread.start()
|
|
292
|
+
return server, thread
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
_HTML = """<!doctype html>
|
|
296
|
+
<html lang="en">
|
|
297
|
+
<head>
|
|
298
|
+
<meta charset="utf-8">
|
|
299
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
300
|
+
<title>python-wrap dashboard</title>
|
|
301
|
+
<style>
|
|
302
|
+
:root { color-scheme: light dark; --bg:#fff; --fg:#1b1f23; --mut:#6a737d; --line:#d0d7de;
|
|
303
|
+
--ok:#1a7f37; --warn:#9a6700; --bad:#cf222e; }
|
|
304
|
+
@media (prefers-color-scheme: dark) { :root { --bg:#0d1117; --fg:#e6edf3; --mut:#8b949e;
|
|
305
|
+
--line:#30363d; --ok:#3fb950; --warn:#d29922; --bad:#f85149; } }
|
|
306
|
+
body { margin:0; padding:16px; font:14px/1.4 system-ui, sans-serif; background:var(--bg); color:var(--fg); }
|
|
307
|
+
h1 { font-size:18px; margin:0 0 4px; } h2 { font-size:14px; margin:20px 0 6px; }
|
|
308
|
+
.mut { color:var(--mut); } table { border-collapse:collapse; width:100%; }
|
|
309
|
+
th, td { text-align:left; padding:4px 8px; border-bottom:1px solid var(--line); font-variant-numeric:tabular-nums; }
|
|
310
|
+
.pill { padding:1px 8px; border-radius:10px; border:1px solid currentColor; }
|
|
311
|
+
.closed, .up { color:var(--ok); } .half_open { color:var(--warn); } .open, .down { color:var(--bad); }
|
|
312
|
+
.bar { display:inline-block; height:8px; background:var(--warn); vertical-align:middle; }
|
|
313
|
+
.cards { display:flex; flex-wrap:wrap; gap:12px; } .card { border:1px solid var(--line); border-radius:6px; padding:8px 12px; min-width:110px; }
|
|
314
|
+
.card b { display:block; font-size:20px; }
|
|
315
|
+
</style>
|
|
316
|
+
</head>
|
|
317
|
+
<body>
|
|
318
|
+
<h1>python-wrap dashboard</h1>
|
|
319
|
+
<div class="mut" id="status">loading...</div>
|
|
320
|
+
<h2>Last 60 seconds</h2><div class="cards" id="rates"></div>
|
|
321
|
+
<h2>Circuit breakers</h2><table id="breakers"></table>
|
|
322
|
+
<h2>Bulkheads</h2><table id="bulkheads"></table>
|
|
323
|
+
<h2>Health</h2><table id="health"></table>
|
|
324
|
+
<h2>Functions</h2><table id="functions"></table>
|
|
325
|
+
<h2>Recent events</h2><table id="events"></table>
|
|
326
|
+
<script>
|
|
327
|
+
var ENDPOINT = "snapshot.json";
|
|
328
|
+
function el(tag, text, cls) { var e = document.createElement(tag); if (text !== undefined) e.textContent = String(text); if (cls) e.className = cls; return e; }
|
|
329
|
+
function fill(id, head, rows) {
|
|
330
|
+
var t = document.getElementById(id); t.textContent = "";
|
|
331
|
+
var tr = el("tr"); head.forEach(function (h) { tr.appendChild(el("th", h)); }); t.appendChild(tr);
|
|
332
|
+
if (!rows.length) { var e = el("tr"); var c = el("td", "none", "mut"); c.colSpan = head.length; e.appendChild(c); t.appendChild(e); }
|
|
333
|
+
rows.forEach(function (r) { var row = el("tr"); r.forEach(function (c) { var td = el("td");
|
|
334
|
+
if (c && c.node) td.appendChild(c.node); else td.textContent = String(c); row.appendChild(td); }); t.appendChild(row); });
|
|
335
|
+
}
|
|
336
|
+
function render(s) {
|
|
337
|
+
document.getElementById("status").textContent = "updated " + new Date(s.time * 1000).toLocaleTimeString() + ", up " + Math.round(s.uptime_seconds) + "s";
|
|
338
|
+
var r = document.getElementById("rates"); r.textContent = "";
|
|
339
|
+
["retries", "gave_up", "rejections", "timeouts"].forEach(function (k) { var c = el("div", "", "card"); c.appendChild(el("b", s.rates[k] || 0)); c.appendChild(el("span", k.replace("_", " "), "mut")); r.appendChild(c); });
|
|
340
|
+
fill("breakers", ["breaker", "state"], Object.keys(s.breakers).sort().map(function (n) { return [n, { node: el("span", s.breakers[n], "pill " + s.breakers[n]) }]; }));
|
|
341
|
+
var bulk = [], hl = [];
|
|
342
|
+
Object.keys(s.health).sort().forEach(function (n) { var h = s.health[n];
|
|
343
|
+
hl.push([n, { node: el("span", h.healthy ? "up" : "down", "pill " + (h.healthy ? "up" : "down")) }, h.state || h.error || ""]);
|
|
344
|
+
if (typeof h.active === "number") { var w = Math.min(h.active * 10, 120); var cell = el("span"); var b = el("span", "", "bar"); b.style.width = w + "px"; cell.appendChild(b); cell.appendChild(el("span", " " + h.active + " active", "mut")); bulk.push([n, { node: cell }, h.waiting]); } });
|
|
345
|
+
fill("bulkheads", ["bulkhead", "active", "waiting"], bulk);
|
|
346
|
+
fill("health", ["component", "healthy", "detail"], hl);
|
|
347
|
+
fill("functions", ["function", "retries", "gave up", "timeouts", "rejections", "cache hits", "cache misses"], Object.keys(s.functions).sort().map(function (n) { var f = s.functions[n]; return [n, f.retries, f.gave_up, f.timeouts, f.rejections, f.cache_hits, f.cache_misses]; }));
|
|
348
|
+
fill("events", ["time", "event", "function", "fields"], s.events.slice(-50).reverse().map(function (e) { return [new Date(e.time * 1000).toLocaleTimeString(), e.event, e.function, JSON.stringify(e.fields)]; }));
|
|
349
|
+
}
|
|
350
|
+
function tick() {
|
|
351
|
+
fetch(ENDPOINT, { cache: "no-store" }).then(function (x) { return x.json(); }).then(render)
|
|
352
|
+
.catch(function () { document.getElementById("status").textContent = "disconnected"; });
|
|
353
|
+
}
|
|
354
|
+
tick(); setInterval(tick, 2000);
|
|
355
|
+
</script>
|
|
356
|
+
</body>
|
|
357
|
+
</html>
|
|
358
|
+
""" # noqa: E501
|