chimericmesh 0.2.2__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.
- chimericmesh/__init__.py +3 -0
- chimericmesh/__main__.py +119 -0
- chimericmesh/agent/__init__.py +21 -0
- chimericmesh/agent/codesearch.py +131 -0
- chimericmesh/agent/digest.py +131 -0
- chimericmesh/agent/errors.py +38 -0
- chimericmesh/agent/feed.py +47 -0
- chimericmesh/agent/limits.py +98 -0
- chimericmesh/agent/ports.py +32 -0
- chimericmesh/agent/routes.py +92 -0
- chimericmesh/agent/service.py +116 -0
- chimericmesh/agent/snippet.py +135 -0
- chimericmesh/agent/verify.py +215 -0
- chimericmesh/agent/watch.py +156 -0
- chimericmesh/api.py +626 -0
- chimericmesh/approvals/__init__.py +25 -0
- chimericmesh/approvals/errors.py +72 -0
- chimericmesh/approvals/format.py +76 -0
- chimericmesh/approvals/irc.py +54 -0
- chimericmesh/approvals/ledger.py +149 -0
- chimericmesh/approvals/limits.py +87 -0
- chimericmesh/approvals/manager.py +935 -0
- chimericmesh/approvals/matching.py +107 -0
- chimericmesh/approvals/models.py +251 -0
- chimericmesh/approvals/ports.py +36 -0
- chimericmesh/approvals/routes.py +220 -0
- chimericmesh/approvals/rulebook.py +337 -0
- chimericmesh/approvals/schema.py +64 -0
- chimericmesh/approvals/scope.py +104 -0
- chimericmesh/approvals/validate.py +215 -0
- chimericmesh/catalog/demo_apps.json +41 -0
- chimericmesh/catalog/legacy_apps.json +612 -0
- chimericmesh/commands.py +223 -0
- chimericmesh/connectors/__init__.py +1 -0
- chimericmesh/connectors/config.py +55 -0
- chimericmesh/connectors/framing.py +132 -0
- chimericmesh/connectors/limiter.py +42 -0
- chimericmesh/connectors/manager.py +252 -0
- chimericmesh/connectors/offsets.py +157 -0
- chimericmesh/connectors/schema.py +31 -0
- chimericmesh/connectors/submit.py +26 -0
- chimericmesh/connectors/syslog_tcp.py +141 -0
- chimericmesh/connectors/tailer.py +236 -0
- chimericmesh/connectors/tailread.py +288 -0
- chimericmesh/demo/__init__.py +1 -0
- chimericmesh/demo/agent.py +32 -0
- chimericmesh/demo/apps/__init__.py +1 -0
- chimericmesh/demo/apps/__main__.py +83 -0
- chimericmesh/demo/apps/common.py +163 -0
- chimericmesh/demo/apps/mail_bridge.py +48 -0
- chimericmesh/demo/apps/orders_api.py +31 -0
- chimericmesh/demo/apps/spooler.py +28 -0
- chimericmesh/demo/config.py +38 -0
- chimericmesh/demo/engine.py +68 -0
- chimericmesh/demo/env.py +46 -0
- chimericmesh/demo/hub.py +172 -0
- chimericmesh/demo/launcher.py +165 -0
- chimericmesh/demo/ports.py +44 -0
- chimericmesh/demo/routes.py +81 -0
- chimericmesh/demo/samples.py +32 -0
- chimericmesh/demo/scenario.py +95 -0
- chimericmesh/demo/supervisor.py +267 -0
- chimericmesh/demo/watch.py +46 -0
- chimericmesh/diagnostics.py +253 -0
- chimericmesh/discovery/__init__.py +17 -0
- chimericmesh/discovery/accept.py +131 -0
- chimericmesh/discovery/catalog.py +313 -0
- chimericmesh/discovery/collect.py +131 -0
- chimericmesh/discovery/dismissals.py +46 -0
- chimericmesh/discovery/engine.py +41 -0
- chimericmesh/discovery/errors.py +34 -0
- chimericmesh/discovery/expand.py +151 -0
- chimericmesh/discovery/manager.py +220 -0
- chimericmesh/discovery/match.py +177 -0
- chimericmesh/discovery/models.py +174 -0
- chimericmesh/discovery/parse.py +166 -0
- chimericmesh/discovery/probe.py +69 -0
- chimericmesh/discovery/routes.py +129 -0
- chimericmesh/discovery/runner.py +147 -0
- chimericmesh/discovery/schema.py +25 -0
- chimericmesh/discovery/text.py +53 -0
- chimericmesh/events.py +74 -0
- chimericmesh/fsperms.py +72 -0
- chimericmesh/hub.py +757 -0
- chimericmesh/listeners.py +162 -0
- chimericmesh/mcp_server.py +199 -0
- chimericmesh/mute/__init__.py +10 -0
- chimericmesh/mute/models.py +14 -0
- chimericmesh/mute/mutelist.py +51 -0
- chimericmesh/mute/routes.py +49 -0
- chimericmesh/mute/schema.py +29 -0
- chimericmesh/mute/store.py +94 -0
- chimericmesh/notify.py +47 -0
- chimericmesh/parsers/__init__.py +12 -0
- chimericmesh/parsers/formats.py +23 -0
- chimericmesh/parsers/irc.py +91 -0
- chimericmesh/parsers/logctx.py +143 -0
- chimericmesh/parsers/ncsa.py +57 -0
- chimericmesh/parsers/plain.py +17 -0
- chimericmesh/parsers/syslog.py +82 -0
- chimericmesh/parsers/syslogtext.py +62 -0
- chimericmesh/parsers/telnet.py +56 -0
- chimericmesh/parsers/w3c.py +58 -0
- chimericmesh/parsers/xferlog.py +31 -0
- chimericmesh/replay.py +108 -0
- chimericmesh/replay_irc.py +202 -0
- chimericmesh/services/__init__.py +39 -0
- chimericmesh/services/access.py +224 -0
- chimericmesh/services/asgi.py +107 -0
- chimericmesh/services/deps.py +42 -0
- chimericmesh/services/errors.py +49 -0
- chimericmesh/services/limiter.py +130 -0
- chimericmesh/services/models.py +160 -0
- chimericmesh/services/paths.py +139 -0
- chimericmesh/services/registry.py +638 -0
- chimericmesh/services/routes.py +161 -0
- chimericmesh/services/schema.py +48 -0
- chimericmesh/services/status.py +239 -0
- chimericmesh/services/tagging.py +63 -0
- chimericmesh/services/token.py +129 -0
- chimericmesh/services/validate.py +184 -0
- chimericmesh/store/__init__.py +43 -0
- chimericmesh/store/audit.py +89 -0
- chimericmesh/store/config.py +88 -0
- chimericmesh/store/connection.py +98 -0
- chimericmesh/store/errors.py +65 -0
- chimericmesh/store/events.py +430 -0
- chimericmesh/store/incidents.py +292 -0
- chimericmesh/store/migrations.py +109 -0
- chimericmesh/store/models.py +49 -0
- chimericmesh/store/ports.py +61 -0
- chimericmesh/store/proposals.py +215 -0
- chimericmesh/store/schema.py +102 -0
- chimericmesh/store/store.py +173 -0
- chimericmesh/store/tx.py +143 -0
- chimericmesh/store/writer.py +315 -0
- chimericmesh/web/__init__.py +1 -0
- chimericmesh/web/feed.py +212 -0
- chimericmesh/web/index.html +3775 -0
- chimericmesh/web/sse.py +74 -0
- chimericmesh/web/stream.py +64 -0
- chimericmesh-0.2.2.dist-info/METADATA +537 -0
- chimericmesh-0.2.2.dist-info/RECORD +147 -0
- chimericmesh-0.2.2.dist-info/WHEEL +5 -0
- chimericmesh-0.2.2.dist-info/entry_points.txt +2 -0
- chimericmesh-0.2.2.dist-info/licenses/LICENSE +21 -0
- chimericmesh-0.2.2.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
"""The single writer thread. After ``Store.open`` every read and write runs here.
|
|
2
|
+
|
|
3
|
+
``WriterState`` holds everything the thread needs and no reference to the ``Store``, so a
|
|
4
|
+
``weakref.finalize`` on the store can stop the thread of an unreferenced store.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import asyncio
|
|
9
|
+
import concurrent.futures
|
|
10
|
+
import logging
|
|
11
|
+
import queue
|
|
12
|
+
import sqlite3
|
|
13
|
+
import threading
|
|
14
|
+
import time
|
|
15
|
+
from collections.abc import Callable
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
from .errors import (
|
|
20
|
+
StoreBusyError,
|
|
21
|
+
StoreClosedError,
|
|
22
|
+
StoreError,
|
|
23
|
+
StoreFullError,
|
|
24
|
+
StoreReentryError,
|
|
25
|
+
StoreWriteError,
|
|
26
|
+
)
|
|
27
|
+
from .tx import Tx
|
|
28
|
+
|
|
29
|
+
log = logging.getLogger("chimericmesh.store")
|
|
30
|
+
|
|
31
|
+
THREAD_NAME = "store-writer"
|
|
32
|
+
RETRY_DELAYS: tuple[float, ...] = (0.05, 0.2, 0.8) # three retries after the first try (T8)
|
|
33
|
+
|
|
34
|
+
_STOP = object()
|
|
35
|
+
_WAKE = object() # an event row is waiting; the hook decides when to flush
|
|
36
|
+
|
|
37
|
+
_BEGIN = "BEGIN IMMEDIATE"
|
|
38
|
+
_COMMIT = "COMMIT"
|
|
39
|
+
_ROLLBACK = "ROLLBACK"
|
|
40
|
+
_CHECKPOINT = "PRAGMA wal_checkpoint(TRUNCATE)"
|
|
41
|
+
_SET_CLEAN = (
|
|
42
|
+
"INSERT INTO counters (name, value) VALUES ('clean_shutdown', 1) "
|
|
43
|
+
"ON CONFLICT(name) DO UPDATE SET value = 1"
|
|
44
|
+
)
|
|
45
|
+
_RAISE_EVENT_ID = (
|
|
46
|
+
"INSERT INTO counters (name, value) VALUES ('event_id', ?) "
|
|
47
|
+
"ON CONFLICT(name) DO UPDATE SET value = max(value, excluded.value)"
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass
|
|
52
|
+
class Job:
|
|
53
|
+
fn: Callable[[Tx], Any]
|
|
54
|
+
write: bool
|
|
55
|
+
deliver: Callable[[Any, BaseException | None], None]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class WriterState:
|
|
59
|
+
def __init__(self, conn: sqlite3.Connection, path: str) -> None:
|
|
60
|
+
self.conn = conn
|
|
61
|
+
self.path = path
|
|
62
|
+
self.queue: queue.Queue[Any] = queue.Queue()
|
|
63
|
+
self.lock = threading.Lock()
|
|
64
|
+
self.thread: threading.Thread | None = None
|
|
65
|
+
self.stopping = False # no new jobs once set
|
|
66
|
+
self.abandon = False
|
|
67
|
+
self.clean = True
|
|
68
|
+
self.deadline: float | None = None
|
|
69
|
+
self.store_ok = True
|
|
70
|
+
self.last_event_id = 0
|
|
71
|
+
self.hook: Any = None # EventWriter: batching, trimming and drain on shutdown
|
|
72
|
+
self.finished = threading.Event()
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
# ---- delivery ------------------------------------------------------------------------------
|
|
76
|
+
|
|
77
|
+
def _set(fut: asyncio.Future, result: Any, exc: BaseException | None) -> None:
|
|
78
|
+
if fut.done(): # cancelled or already finished
|
|
79
|
+
return
|
|
80
|
+
try:
|
|
81
|
+
if exc is not None:
|
|
82
|
+
fut.set_exception(exc)
|
|
83
|
+
else:
|
|
84
|
+
fut.set_result(result)
|
|
85
|
+
except asyncio.InvalidStateError:
|
|
86
|
+
pass
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _deliver(loop: asyncio.AbstractEventLoop, future: asyncio.Future, result: Any,
|
|
90
|
+
exc: BaseException | None) -> None:
|
|
91
|
+
"""Hand a result to the loop thread. Never raises on the writer thread."""
|
|
92
|
+
try:
|
|
93
|
+
loop.call_soon_threadsafe(_set, future, result, exc)
|
|
94
|
+
except RuntimeError: # loop already closed
|
|
95
|
+
log.debug("result dropped: event loop is closed")
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def async_deliver(loop: asyncio.AbstractEventLoop, future: asyncio.Future):
|
|
99
|
+
return lambda result, exc: _deliver(loop, future, result, exc)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def sync_deliver(future: concurrent.futures.Future):
|
|
103
|
+
def deliver(result: Any, exc: BaseException | None) -> None:
|
|
104
|
+
if exc is not None:
|
|
105
|
+
future.set_exception(exc)
|
|
106
|
+
else:
|
|
107
|
+
future.set_result(result)
|
|
108
|
+
|
|
109
|
+
return deliver
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
# ---- running jobs --------------------------------------------------------------------------
|
|
113
|
+
|
|
114
|
+
def _classify(exc: sqlite3.Error) -> str | None:
|
|
115
|
+
"""'busy', 'full', 'io' (retryable), 'corrupt' (fatal), or None (not a store failure)."""
|
|
116
|
+
code = getattr(exc, "sqlite_errorcode", None)
|
|
117
|
+
primary = code & 0xFF if isinstance(code, int) else None
|
|
118
|
+
msg = str(exc).lower()
|
|
119
|
+
if primary in (11, 26) or "malformed" in msg or "not a database" in msg:
|
|
120
|
+
return "corrupt"
|
|
121
|
+
if primary in (5, 6) or "locked" in msg or "busy" in msg:
|
|
122
|
+
return "busy"
|
|
123
|
+
if primary == 13 or "disk is full" in msg or "database or disk is full" in msg:
|
|
124
|
+
return "full"
|
|
125
|
+
if primary == 10 or "disk i/o" in msg:
|
|
126
|
+
return "io"
|
|
127
|
+
return None
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
_ERRORS = {"busy": StoreBusyError, "full": StoreFullError, "io": StoreWriteError, "corrupt": StoreWriteError}
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _run_once(conn: sqlite3.Connection, job: Job) -> Any:
|
|
134
|
+
if job.write:
|
|
135
|
+
conn.execute(_BEGIN)
|
|
136
|
+
try:
|
|
137
|
+
result = job.fn(Tx(conn))
|
|
138
|
+
if job.write:
|
|
139
|
+
conn.execute(_COMMIT)
|
|
140
|
+
return result
|
|
141
|
+
except BaseException:
|
|
142
|
+
if conn.in_transaction:
|
|
143
|
+
try:
|
|
144
|
+
conn.execute(_ROLLBACK)
|
|
145
|
+
except sqlite3.Error:
|
|
146
|
+
pass
|
|
147
|
+
raise
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _set_ok(state: WriterState, ok: bool, why: str = "") -> None:
|
|
151
|
+
if state.store_ok != ok:
|
|
152
|
+
state.store_ok = ok
|
|
153
|
+
if ok:
|
|
154
|
+
log.warning("store: writes are succeeding again (%s)", state.path)
|
|
155
|
+
# the failure itself is logged where it happens
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _execute(state: WriterState, job: Job) -> None:
|
|
159
|
+
delays = RETRY_DELAYS
|
|
160
|
+
for attempt in range(len(delays) + 1):
|
|
161
|
+
try:
|
|
162
|
+
result = _run_once(state.conn, job)
|
|
163
|
+
except sqlite3.Error as exc:
|
|
164
|
+
kind = _classify(exc)
|
|
165
|
+
if kind is None:
|
|
166
|
+
job.deliver(None, exc)
|
|
167
|
+
return
|
|
168
|
+
if kind == "corrupt":
|
|
169
|
+
_set_ok(state, False)
|
|
170
|
+
log.critical("store: database error (%s) on %s", type(exc).__name__, state.path)
|
|
171
|
+
job.deliver(None, StoreWriteError(f"store write failed: {type(exc).__name__}"))
|
|
172
|
+
return
|
|
173
|
+
if attempt < len(delays):
|
|
174
|
+
log.warning("store: %s on %s, retry %d", kind, state.path, attempt + 1)
|
|
175
|
+
time.sleep(delays[attempt])
|
|
176
|
+
continue
|
|
177
|
+
_set_ok(state, False)
|
|
178
|
+
log.error("store: write failed after %d tries (%s, %s)", attempt + 1, kind, state.path)
|
|
179
|
+
job.deliver(None, _ERRORS[kind](f"store write failed: {kind}"))
|
|
180
|
+
return
|
|
181
|
+
except BaseException as exc: # caller's own error, not retried
|
|
182
|
+
job.deliver(None, exc)
|
|
183
|
+
return
|
|
184
|
+
if job.write:
|
|
185
|
+
_set_ok(state, True)
|
|
186
|
+
job.deliver(result, None)
|
|
187
|
+
return
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _final_work(state: WriterState) -> None:
|
|
191
|
+
"""Runs on the writer thread (or inline when none started) before the connection closes."""
|
|
192
|
+
conn = state.conn
|
|
193
|
+
try:
|
|
194
|
+
if not state.abandon:
|
|
195
|
+
if state.last_event_id:
|
|
196
|
+
conn.execute(_BEGIN)
|
|
197
|
+
conn.execute(_RAISE_EVENT_ID, (state.last_event_id,))
|
|
198
|
+
conn.execute(_COMMIT)
|
|
199
|
+
if state.clean:
|
|
200
|
+
conn.execute(_BEGIN)
|
|
201
|
+
conn.execute(_SET_CLEAN)
|
|
202
|
+
conn.execute(_COMMIT)
|
|
203
|
+
conn.execute(_CHECKPOINT)
|
|
204
|
+
except sqlite3.Error as exc:
|
|
205
|
+
log.error("store: shutdown work failed (%s): %s", state.path, type(exc).__name__)
|
|
206
|
+
if conn.in_transaction:
|
|
207
|
+
try:
|
|
208
|
+
conn.execute(_ROLLBACK)
|
|
209
|
+
except sqlite3.Error:
|
|
210
|
+
pass
|
|
211
|
+
finally:
|
|
212
|
+
try:
|
|
213
|
+
conn.close()
|
|
214
|
+
except sqlite3.Error:
|
|
215
|
+
pass
|
|
216
|
+
state.finished.set()
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _past_deadline(state: WriterState) -> bool:
|
|
220
|
+
return state.deadline is not None and time.monotonic() > state.deadline
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _service(state: WriterState, hook: Any) -> None:
|
|
224
|
+
try:
|
|
225
|
+
hook.service(state)
|
|
226
|
+
except Exception: # the writer thread must survive a bug in the hook
|
|
227
|
+
log.exception("store: event writer hook failed (%s)", state.path)
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _run(state: WriterState) -> None:
|
|
231
|
+
hook = state.hook
|
|
232
|
+
while True:
|
|
233
|
+
timeout = hook.next_wait() if hook is not None else None
|
|
234
|
+
try:
|
|
235
|
+
item = state.queue.get(timeout=timeout)
|
|
236
|
+
except queue.Empty:
|
|
237
|
+
item = None
|
|
238
|
+
if item is _STOP:
|
|
239
|
+
break
|
|
240
|
+
if item is _WAKE:
|
|
241
|
+
hook.on_wake()
|
|
242
|
+
elif item is not None:
|
|
243
|
+
if state.abandon or _past_deadline(state):
|
|
244
|
+
item.deliver(None, StoreClosedError("store is closing"))
|
|
245
|
+
else:
|
|
246
|
+
_execute(state, item)
|
|
247
|
+
if hook is not None and not state.abandon:
|
|
248
|
+
_service(state, hook)
|
|
249
|
+
_finish(state)
|
|
250
|
+
_final_work(state)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _finish(state: WriterState) -> None:
|
|
254
|
+
if state.hook is None:
|
|
255
|
+
return
|
|
256
|
+
try:
|
|
257
|
+
state.hook.finish(state)
|
|
258
|
+
except Exception:
|
|
259
|
+
log.exception("store: draining event rows failed (%s)", state.path)
|
|
260
|
+
|
|
261
|
+
# ---- control -------------------------------------------------------------------------------
|
|
262
|
+
|
|
263
|
+
def submit(state: WriterState, job: Job) -> None:
|
|
264
|
+
if state.thread is not None and threading.current_thread() is state.thread:
|
|
265
|
+
raise StoreReentryError("a store job was submitted from the writer thread")
|
|
266
|
+
with state.lock:
|
|
267
|
+
if state.stopping:
|
|
268
|
+
raise StoreClosedError("store is closed")
|
|
269
|
+
if state.thread is None:
|
|
270
|
+
state.thread = threading.Thread(target=_run, args=(state,), name=THREAD_NAME, daemon=True)
|
|
271
|
+
state.thread.start()
|
|
272
|
+
state.queue.put(job)
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def wake(state: WriterState) -> bool:
|
|
276
|
+
"""Tell the writer thread that event rows are waiting (starts it if needed). False when closed."""
|
|
277
|
+
with state.lock:
|
|
278
|
+
if state.stopping:
|
|
279
|
+
return False
|
|
280
|
+
if state.thread is None:
|
|
281
|
+
state.thread = threading.Thread(target=_run, args=(state,), name=THREAD_NAME, daemon=True)
|
|
282
|
+
state.thread.start()
|
|
283
|
+
state.queue.put(_WAKE)
|
|
284
|
+
return True
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def stop(state: WriterState, *, clean: bool, timeout: float, abandon: bool = False) -> bool:
|
|
288
|
+
"""Stop intake, drain until the deadline, finish on the writer thread. True when finished."""
|
|
289
|
+
with state.lock:
|
|
290
|
+
first = not state.stopping
|
|
291
|
+
if first:
|
|
292
|
+
state.stopping = True
|
|
293
|
+
state.clean = clean
|
|
294
|
+
state.abandon = abandon
|
|
295
|
+
state.deadline = time.monotonic() + max(timeout, 0.0)
|
|
296
|
+
if state.thread is None:
|
|
297
|
+
_finish(state)
|
|
298
|
+
_final_work(state) # nothing ever ran: finish inline on the caller's thread
|
|
299
|
+
else:
|
|
300
|
+
state.queue.put(_STOP)
|
|
301
|
+
thread = state.thread
|
|
302
|
+
if thread is None or thread is threading.current_thread():
|
|
303
|
+
return state.finished.is_set()
|
|
304
|
+
thread.join(max(timeout, 0.0) if first else 0.0)
|
|
305
|
+
if thread.is_alive():
|
|
306
|
+
if first:
|
|
307
|
+
log.error("store: writer did not finish within %.1fs; it will close the database when it unblocks",
|
|
308
|
+
timeout)
|
|
309
|
+
return False
|
|
310
|
+
return True
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def _stop_writer(state: WriterState) -> None:
|
|
314
|
+
"""weakref.finalize target: the store was dropped without close()."""
|
|
315
|
+
stop(state, clean=False, timeout=1.0)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Dashboard package: the static page and the per-service live log stream."""
|
chimericmesh/web/feed.py
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
"""Stream configuration, slot gate and frame generator (no web framework).
|
|
2
|
+
|
|
3
|
+
Stdlib and ``core`` only. Clocks and sleep are injected, so the generator runs against a fake feed and
|
|
4
|
+
a manual clock in tests, and against the hub (``StateView.events_after`` and ``recent``) in the app.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import asyncio
|
|
9
|
+
import json
|
|
10
|
+
import logging
|
|
11
|
+
from collections import deque
|
|
12
|
+
from collections.abc import AsyncIterator, Awaitable, Callable
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
from typing import Protocol
|
|
15
|
+
|
|
16
|
+
from chimericmesh.events import Event
|
|
17
|
+
|
|
18
|
+
from .sse import event_payload, frame_comment, frame_event, frame_named
|
|
19
|
+
|
|
20
|
+
log = logging.getLogger(__name__)
|
|
21
|
+
|
|
22
|
+
MAX_STREAMS = 20
|
|
23
|
+
RECENT_WINDOW = 500
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass(frozen=True, slots=True)
|
|
27
|
+
class StreamConfig:
|
|
28
|
+
poll_interval: float = 0.25
|
|
29
|
+
heartbeat: float = 15.0
|
|
30
|
+
queue_max: int = 1000 # R5.4
|
|
31
|
+
page: int = 500 # events_after limit per call
|
|
32
|
+
max_pages_per_cycle: int = 20
|
|
33
|
+
max_seconds: float = 3600.0 # the browser reconnects with Last-Event-ID
|
|
34
|
+
max_feed_failures: int = 5
|
|
35
|
+
# lease_grace and stall_after live in StreamGate only (L5)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class Lease:
|
|
39
|
+
"""One stream slot. ``release`` is idempotent; a reclaimed lease is already released."""
|
|
40
|
+
|
|
41
|
+
__slots__ = ("_gate", "created", "last_touch", "started", "released")
|
|
42
|
+
|
|
43
|
+
def __init__(self, gate: "StreamGate", now: float) -> None:
|
|
44
|
+
self._gate = gate
|
|
45
|
+
self.created = now
|
|
46
|
+
self.last_touch = now
|
|
47
|
+
self.started = False
|
|
48
|
+
self.released = False
|
|
49
|
+
|
|
50
|
+
def start(self, now: float) -> None:
|
|
51
|
+
if not self.released:
|
|
52
|
+
self.started = True
|
|
53
|
+
self.last_touch = now
|
|
54
|
+
|
|
55
|
+
def touch(self, now: float) -> None:
|
|
56
|
+
if not self.released:
|
|
57
|
+
self.last_touch = now
|
|
58
|
+
|
|
59
|
+
def release(self) -> None:
|
|
60
|
+
if self.released:
|
|
61
|
+
return
|
|
62
|
+
self.released = True
|
|
63
|
+
self._gate._leases.discard(self)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class StreamGate:
|
|
67
|
+
"""At most ``max_streams`` concurrent streams. Used from the event loop thread only, so no lock."""
|
|
68
|
+
|
|
69
|
+
def __init__(self, max_streams: int = MAX_STREAMS, *, lease_grace: float = 10.0,
|
|
70
|
+
stall_after: float = 10.0) -> None:
|
|
71
|
+
self.max_streams = max_streams
|
|
72
|
+
self.lease_grace = lease_grace
|
|
73
|
+
self.stall_after = stall_after
|
|
74
|
+
self._leases: set[Lease] = set()
|
|
75
|
+
|
|
76
|
+
@property
|
|
77
|
+
def active(self) -> int:
|
|
78
|
+
return len(self._leases)
|
|
79
|
+
|
|
80
|
+
def _reclaim(self, now: float) -> None:
|
|
81
|
+
for lease in list(self._leases):
|
|
82
|
+
if lease.started:
|
|
83
|
+
stale = now - lease.last_touch > self.stall_after
|
|
84
|
+
else:
|
|
85
|
+
stale = now - lease.created > self.lease_grace
|
|
86
|
+
if stale:
|
|
87
|
+
lease.release()
|
|
88
|
+
|
|
89
|
+
def acquire(self, now: float) -> Lease | None:
|
|
90
|
+
self._reclaim(now)
|
|
91
|
+
if len(self._leases) >= self.max_streams:
|
|
92
|
+
return None
|
|
93
|
+
lease = Lease(self, now)
|
|
94
|
+
self._leases.add(lease)
|
|
95
|
+
return lease
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class EventFeed(Protocol):
|
|
99
|
+
"""What the hub offers (store ``StateView``): events after a cursor, and the newest events."""
|
|
100
|
+
|
|
101
|
+
async def events_after(self, after_id: int, limit: int = 100, *, source: str | None = None,
|
|
102
|
+
service_id: str | None = None) -> list[Event]: ...
|
|
103
|
+
|
|
104
|
+
def recent(self, limit: int = 50, source: str | None = None) -> list[Event]: ...
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _mine(event: Event, service_id: str) -> bool:
|
|
108
|
+
return event.service_id is None if service_id == "unassigned" else event.service_id == service_id
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _closed(reason: str) -> str:
|
|
112
|
+
return frame_named("closed", json.dumps({"reason": reason}))
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
async def stream_frames(feed: EventFeed, service_id: str, *, after: int | None, tail: int = 0,
|
|
116
|
+
min_severity: int, config: StreamConfig, clock: Callable[[], float],
|
|
117
|
+
sleep: Callable[[float], Awaitable[None]],
|
|
118
|
+
service_exists: Callable[[str], bool],
|
|
119
|
+
lease: Lease | None = None) -> AsyncIterator[str]:
|
|
120
|
+
"""Yield SSE frames for one service until the age limit, a deleted service or a dead feed.
|
|
121
|
+
|
|
122
|
+
``min_severity`` keeps events with ``severity <= min_severity`` (0 is the most severe). The slot
|
|
123
|
+
lease is started at the first step and released in ``finally``, so a cancel frees it at once.
|
|
124
|
+
"""
|
|
125
|
+
started = clock()
|
|
126
|
+
try:
|
|
127
|
+
if lease is not None:
|
|
128
|
+
lease.start(started)
|
|
129
|
+
# Cursor (and backlog) from one snapshot taken before the first frame is sent, so an event that
|
|
130
|
+
# arrives while the client is still connecting is delivered (no gap) and never twice.
|
|
131
|
+
backlog: list[Event] = []
|
|
132
|
+
if after is not None:
|
|
133
|
+
cursor = after
|
|
134
|
+
else:
|
|
135
|
+
try:
|
|
136
|
+
window = feed.recent(RECENT_WINDOW if tail > 0 else 1)
|
|
137
|
+
except Exception:
|
|
138
|
+
log.warning("dashboard stream: feed.recent failed for %s", service_id)
|
|
139
|
+
yield frame_comment("open")
|
|
140
|
+
yield _closed("feed_error")
|
|
141
|
+
return
|
|
142
|
+
mine = [e for e in window if _mine(e, service_id)]
|
|
143
|
+
cursor = mine[0].id if mine else (window[0].id if window else 0)
|
|
144
|
+
if tail > 0:
|
|
145
|
+
backlog = [e for e in mine if e.severity <= min_severity][:tail]
|
|
146
|
+
backlog.reverse()
|
|
147
|
+
yield frame_comment("open")
|
|
148
|
+
for e in backlog:
|
|
149
|
+
yield frame_event(e.id, event_payload(e))
|
|
150
|
+
last_frame = clock()
|
|
151
|
+
failures = 0
|
|
152
|
+
last_warn: float | None = None
|
|
153
|
+
while True:
|
|
154
|
+
now = clock()
|
|
155
|
+
if lease is not None:
|
|
156
|
+
lease.touch(now)
|
|
157
|
+
if now - started >= config.max_seconds:
|
|
158
|
+
yield _closed("max_age")
|
|
159
|
+
return
|
|
160
|
+
if not service_exists(service_id):
|
|
161
|
+
yield _closed("service_deleted")
|
|
162
|
+
return
|
|
163
|
+
queue: deque[Event] = deque(maxlen=config.queue_max)
|
|
164
|
+
dropped = 0
|
|
165
|
+
failed = False
|
|
166
|
+
for _ in range(config.max_pages_per_cycle):
|
|
167
|
+
try:
|
|
168
|
+
page = await feed.events_after(cursor, config.page, service_id=service_id)
|
|
169
|
+
except asyncio.CancelledError:
|
|
170
|
+
raise
|
|
171
|
+
except Exception:
|
|
172
|
+
failed = True
|
|
173
|
+
break
|
|
174
|
+
failures = 0
|
|
175
|
+
for e in page:
|
|
176
|
+
cursor = max(cursor, e.id)
|
|
177
|
+
if e.severity <= min_severity:
|
|
178
|
+
if len(queue) == queue.maxlen:
|
|
179
|
+
dropped += 1
|
|
180
|
+
queue.append(e)
|
|
181
|
+
if len(page) < config.page:
|
|
182
|
+
break
|
|
183
|
+
await sleep(0)
|
|
184
|
+
yielded = False
|
|
185
|
+
if dropped:
|
|
186
|
+
yield frame_named("dropped", json.dumps({"count": dropped}))
|
|
187
|
+
yielded = True
|
|
188
|
+
for e in queue:
|
|
189
|
+
yield frame_event(e.id, event_payload(e))
|
|
190
|
+
yielded = True
|
|
191
|
+
if lease is not None:
|
|
192
|
+
lease.touch(clock())
|
|
193
|
+
if yielded:
|
|
194
|
+
last_frame = clock()
|
|
195
|
+
if failed:
|
|
196
|
+
failures += 1
|
|
197
|
+
t = clock()
|
|
198
|
+
if last_warn is None or t - last_warn >= 60.0:
|
|
199
|
+
last_warn = t
|
|
200
|
+
log.warning("dashboard stream: events_after failed (%d in a row)", failures)
|
|
201
|
+
if failures >= config.max_feed_failures:
|
|
202
|
+
yield _closed("feed_error")
|
|
203
|
+
return
|
|
204
|
+
await sleep(min(5.0, 0.5 * failures))
|
|
205
|
+
continue
|
|
206
|
+
if not yielded and clock() - last_frame >= config.heartbeat:
|
|
207
|
+
yield frame_comment("hb")
|
|
208
|
+
last_frame = clock()
|
|
209
|
+
await sleep(config.poll_interval)
|
|
210
|
+
finally:
|
|
211
|
+
if lease is not None:
|
|
212
|
+
lease.release()
|