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,292 @@
|
|
|
1
|
+
"""Incident rows: snapshot, upsert, load. The lifecycle (persist, reopen) is added below."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import asyncio
|
|
5
|
+
import json
|
|
6
|
+
import logging
|
|
7
|
+
import time
|
|
8
|
+
from collections.abc import Callable
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from typing import TYPE_CHECKING
|
|
11
|
+
|
|
12
|
+
from chimericmesh.diagnostics import Incident, IncidentTracker, classify
|
|
13
|
+
|
|
14
|
+
from .ports import Announce, AuditSink
|
|
15
|
+
from .tx import Tx
|
|
16
|
+
|
|
17
|
+
if TYPE_CHECKING:
|
|
18
|
+
from .store import Store
|
|
19
|
+
|
|
20
|
+
log = logging.getLogger("chimericmesh.store")
|
|
21
|
+
|
|
22
|
+
MAX_SAMPLE = 4096
|
|
23
|
+
MAX_HOST = 255
|
|
24
|
+
|
|
25
|
+
_COLUMNS = (
|
|
26
|
+
"SELECT id, host, service_id, category, signature, severity, count, first_seen, last_seen, sample, "
|
|
27
|
+
"sources, resolved, resolved_at, opening, opened, announced_count FROM incidents"
|
|
28
|
+
)
|
|
29
|
+
_UPSERT = (
|
|
30
|
+
"INSERT INTO incidents (id, host, service_id, category, signature, severity, count, first_seen, "
|
|
31
|
+
"last_seen, sample, sources, resolved, resolved_at, opening, opened, announced_count) "
|
|
32
|
+
"VALUES (:id, :host, :service_id, :category, :signature, :severity, :count, :first_seen, :last_seen, "
|
|
33
|
+
":sample, :sources, :resolved, :resolved_at, :opening, :opened, :announced_count) "
|
|
34
|
+
"ON CONFLICT(id) DO UPDATE SET host = excluded.host, service_id = excluded.service_id, "
|
|
35
|
+
"category = excluded.category, signature = excluded.signature, severity = excluded.severity, "
|
|
36
|
+
"count = excluded.count, first_seen = excluded.first_seen, last_seen = excluded.last_seen, "
|
|
37
|
+
"sample = excluded.sample, sources = excluded.sources, resolved = excluded.resolved, "
|
|
38
|
+
"resolved_at = excluded.resolved_at, opening = excluded.opening, opened = excluded.opened, "
|
|
39
|
+
"announced_count = excluded.announced_count"
|
|
40
|
+
)
|
|
41
|
+
_LOAD_NEWEST = _COLUMNS + " ORDER BY last_seen DESC, id LIMIT :limit"
|
|
42
|
+
_GET = _COLUMNS + " WHERE id = ?"
|
|
43
|
+
_IDS_BEYOND = "SELECT id FROM incidents ORDER BY last_seen DESC, id LIMIT -1 OFFSET ?"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _text(value: str, limit: int) -> str:
|
|
47
|
+
"""Cut to ``limit`` and replace lone surrogates, which sqlite3 cannot bind."""
|
|
48
|
+
return value.encode("utf-8", "replace").decode("utf-8")[:limit]
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass(frozen=True, slots=True)
|
|
52
|
+
class IncidentRow:
|
|
53
|
+
"""Immutable snapshot of an incident, built on the loop thread before a write is submitted."""
|
|
54
|
+
|
|
55
|
+
id: str
|
|
56
|
+
host: str
|
|
57
|
+
service_id: str | None
|
|
58
|
+
category: str
|
|
59
|
+
signature: str
|
|
60
|
+
severity: int
|
|
61
|
+
count: int
|
|
62
|
+
first_seen: float
|
|
63
|
+
last_seen: float
|
|
64
|
+
sample: str
|
|
65
|
+
sources: tuple[str, ...]
|
|
66
|
+
resolved: bool
|
|
67
|
+
resolved_at: float | None
|
|
68
|
+
opening: int
|
|
69
|
+
opened: bool
|
|
70
|
+
announced_count: int | None
|
|
71
|
+
|
|
72
|
+
@classmethod
|
|
73
|
+
def from_incident(cls, inc: Incident, announced_count: int | None) -> "IncidentRow":
|
|
74
|
+
return cls(
|
|
75
|
+
id=inc.id, host=_text(inc.host, MAX_HOST), service_id=inc.service_id, category=inc.category,
|
|
76
|
+
signature=_text(inc.signature, 200), severity=inc.severity, count=inc.count,
|
|
77
|
+
first_seen=inc.first_seen, last_seen=inc.last_seen, sample=_text(inc.sample, MAX_SAMPLE),
|
|
78
|
+
sources=tuple(inc.sources), resolved=bool(inc.resolved), resolved_at=inc.resolved_at,
|
|
79
|
+
opening=inc.opening, opened=bool(inc.opened), announced_count=announced_count,
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
def params(self) -> dict[str, object]:
|
|
83
|
+
return {
|
|
84
|
+
"id": self.id, "host": self.host, "service_id": self.service_id, "category": self.category,
|
|
85
|
+
"signature": self.signature, "severity": self.severity, "count": self.count,
|
|
86
|
+
"first_seen": self.first_seen, "last_seen": self.last_seen, "sample": self.sample,
|
|
87
|
+
"sources": json.dumps([_text(s, 64) for s in self.sources]), "resolved": int(self.resolved),
|
|
88
|
+
"resolved_at": self.resolved_at, "opening": self.opening, "opened": int(self.opened),
|
|
89
|
+
"announced_count": self.announced_count,
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _decode(row: object) -> IncidentRow:
|
|
94
|
+
r = dict(row) # type: ignore[call-overload]
|
|
95
|
+
try:
|
|
96
|
+
sources = tuple(str(s) for s in json.loads(r["sources"]))
|
|
97
|
+
except (TypeError, ValueError):
|
|
98
|
+
sources = ()
|
|
99
|
+
return IncidentRow(
|
|
100
|
+
id=r["id"], host=r["host"], service_id=r["service_id"], category=r["category"],
|
|
101
|
+
signature=r["signature"], severity=r["severity"], count=r["count"], first_seen=r["first_seen"],
|
|
102
|
+
last_seen=r["last_seen"], sample=r["sample"], sources=sources, resolved=bool(r["resolved"]),
|
|
103
|
+
resolved_at=r["resolved_at"], opening=r["opening"], opened=bool(r["opened"]),
|
|
104
|
+
announced_count=r["announced_count"],
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def row_to_incident(row: IncidentRow) -> Incident:
|
|
109
|
+
"""Rebuild an ``Incident``. Hypothesis and remediation are recomputed from the stored sample."""
|
|
110
|
+
_category, hypothesis, steps = classify(row.sample)
|
|
111
|
+
return Incident(
|
|
112
|
+
id=row.id, host=row.host, category=row.category, signature=row.signature, severity=row.severity,
|
|
113
|
+
count=row.count, first_seen=row.first_seen, last_seen=row.last_seen, sources=list(row.sources),
|
|
114
|
+
sample=row.sample, hypothesis=hypothesis, remediation=list(steps), resolved=row.resolved,
|
|
115
|
+
service_id=row.service_id, opening=row.opening, resolved_at=row.resolved_at, opened=row.opened,
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def upsert_incident(tx: Tx, row: IncidentRow) -> None:
|
|
120
|
+
tx.execute(_UPSERT, row.params()) # type: ignore[arg-type]
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def load_incidents(tx: Tx, limit: int) -> list[IncidentRow]:
|
|
124
|
+
"""The ``limit`` most recently seen incidents, newest first."""
|
|
125
|
+
return [_decode(r) for r in tx.all(_LOAD_NEWEST, {"limit": max(0, int(limit))})] # type: ignore[arg-type]
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def stored_ids_beyond(tx: Tx, offset: int) -> list[str]:
|
|
129
|
+
"""Ids of incidents older than the newest ``offset`` (stored but not loaded at start)."""
|
|
130
|
+
return [r[0] for r in tx.all(_IDS_BEYOND, (max(0, int(offset)),))]
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def get_incident_row(tx: Tx, incident_id: str) -> IncidentRow | None:
|
|
134
|
+
row = tx.one(_GET, (incident_id,))
|
|
135
|
+
return None if row is None else _decode(row)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
# ---- lifecycle -----------------------------------------------------------------------------
|
|
139
|
+
|
|
140
|
+
class IncidentLifecycle:
|
|
141
|
+
"""Persists incidents behind the hub's in-memory state and owns the reopen rule.
|
|
142
|
+
|
|
143
|
+
Works with ``store=None`` (a bare hub): persistence is then a no-op. The caller builds every
|
|
144
|
+
write from an immutable ``IncidentRow`` on the loop thread, so the writer thread never reads a
|
|
145
|
+
live ``Incident``.
|
|
146
|
+
"""
|
|
147
|
+
|
|
148
|
+
def __init__(self, tracker: IncidentTracker, *, store: "Store | None", announce: Announce,
|
|
149
|
+
now: Callable[[], float], reopen_after: float,
|
|
150
|
+
audit_getter: Callable[[], AuditSink | None] = lambda: None,
|
|
151
|
+
announced_getter: Callable[[str], int | None] = lambda _id: None,
|
|
152
|
+
persist_slots: int = 256, flush_interval: float = 30.0) -> None:
|
|
153
|
+
self.tracker = tracker
|
|
154
|
+
self.store = store
|
|
155
|
+
self._announce = announce
|
|
156
|
+
self._now = now
|
|
157
|
+
self.reopen_after = reopen_after
|
|
158
|
+
self._audit_getter = audit_getter
|
|
159
|
+
self._announced_getter = announced_getter
|
|
160
|
+
self._slots = asyncio.Semaphore(persist_slots)
|
|
161
|
+
self.flush_interval = flush_interval
|
|
162
|
+
self._dirty: dict[str, Incident] = {}
|
|
163
|
+
self._gen: dict[str, int] = {}
|
|
164
|
+
self._written: dict[str, float] = {}
|
|
165
|
+
self._last_warn = -1e9
|
|
166
|
+
|
|
167
|
+
# -- bookkeeping --
|
|
168
|
+
|
|
169
|
+
def mark_dirty(self, inc: Incident) -> None:
|
|
170
|
+
if self.store is None:
|
|
171
|
+
return # nothing is written, so nothing is kept alive
|
|
172
|
+
self._dirty[inc.id] = inc
|
|
173
|
+
self._gen[inc.id] = self._gen.get(inc.id, 0) + 1
|
|
174
|
+
|
|
175
|
+
def _snapshot(self, inc: Incident) -> IncidentRow:
|
|
176
|
+
return IncidentRow.from_incident(inc, self._announced_getter(inc.id))
|
|
177
|
+
|
|
178
|
+
def _warn(self, message: str, *args: object) -> None:
|
|
179
|
+
"""One warning per minute, so a stalled store cannot flood the log."""
|
|
180
|
+
t = time.monotonic()
|
|
181
|
+
if t - self._last_warn >= 60:
|
|
182
|
+
self._last_warn = t
|
|
183
|
+
log.warning(message, *args)
|
|
184
|
+
|
|
185
|
+
def _store_ok(self) -> bool:
|
|
186
|
+
return self.store is not None and self.store.health().store_ok
|
|
187
|
+
|
|
188
|
+
# -- persistence --
|
|
189
|
+
|
|
190
|
+
async def persist(self, inc: Incident) -> None:
|
|
191
|
+
"""Write ``inc`` now. Never raises. Under backpressure or a failing store the incident stays dirty."""
|
|
192
|
+
if self.store is None:
|
|
193
|
+
return
|
|
194
|
+
if self._slots.locked() or not self._store_ok():
|
|
195
|
+
self.mark_dirty(inc)
|
|
196
|
+
self._warn("store stalled: incident %s stays dirty", inc.id)
|
|
197
|
+
return
|
|
198
|
+
gen = self._gen.get(inc.id, 0)
|
|
199
|
+
row = self._snapshot(inc)
|
|
200
|
+
async with self._slots:
|
|
201
|
+
try:
|
|
202
|
+
await self.store.transact(lambda tx: upsert_incident(tx, row))
|
|
203
|
+
except asyncio.CancelledError:
|
|
204
|
+
self.mark_dirty(inc)
|
|
205
|
+
raise
|
|
206
|
+
except Exception:
|
|
207
|
+
log.exception("incident %s not persisted; it will be retried", inc.id)
|
|
208
|
+
self.mark_dirty(inc)
|
|
209
|
+
return
|
|
210
|
+
self._written[inc.id] = self._now()
|
|
211
|
+
if self._gen.get(inc.id, 0) == gen:
|
|
212
|
+
self._dirty.pop(inc.id, None)
|
|
213
|
+
|
|
214
|
+
async def maybe_flush(self, inc: Incident) -> None:
|
|
215
|
+
"""Mark dirty and write when the last write is at least ``flush_interval`` old."""
|
|
216
|
+
self.mark_dirty(inc)
|
|
217
|
+
if self._is_due(inc.id):
|
|
218
|
+
await self.persist(inc)
|
|
219
|
+
|
|
220
|
+
def _is_due(self, incident_id: str) -> bool:
|
|
221
|
+
return self._now() - self._written.get(incident_id, -1e18) >= self.flush_interval
|
|
222
|
+
|
|
223
|
+
def flush_due(self) -> list[IncidentRow]:
|
|
224
|
+
"""Snapshots of dirty incidents whose last write is at least ``flush_interval`` old."""
|
|
225
|
+
return [self._snapshot(i) for i in self._dirty.values() if self._is_due(i.id)]
|
|
226
|
+
|
|
227
|
+
async def flush_dirty(self) -> None:
|
|
228
|
+
for inc in [i for i in list(self._dirty.values()) if self._is_due(i.id)]:
|
|
229
|
+
await self.persist(inc)
|
|
230
|
+
|
|
231
|
+
# -- reopen --
|
|
232
|
+
|
|
233
|
+
def reopen_due(self, inc: Incident) -> bool:
|
|
234
|
+
"""True for a resolved incident whose reopen window has passed (hub clock, not event time)."""
|
|
235
|
+
return (inc.resolved and inc.resolved_at is not None
|
|
236
|
+
and self._now() - inc.resolved_at >= self.reopen_after)
|
|
237
|
+
|
|
238
|
+
async def reopen(self, inc: Incident) -> None:
|
|
239
|
+
"""Persist and announce a new opening. ``inc`` was already reset by ``tracker.reopen``.
|
|
240
|
+
|
|
241
|
+
The incident row and the ``incident_reopened`` audit row share one transaction when the audit
|
|
242
|
+
sink is this store's log. The announcement goes out after the commit, once, and never waits
|
|
243
|
+
on a failing store.
|
|
244
|
+
"""
|
|
245
|
+
row = IncidentRow.from_incident(inc, 1) # marker 1: one announcement per opening
|
|
246
|
+
sink = self._audit_getter()
|
|
247
|
+
detail = f"incident={inc.id} opening={inc.opening} service={inc.service_id or 'unassigned'}"
|
|
248
|
+
refs = {"service_id": inc.service_id}
|
|
249
|
+
in_tx = (self.store is not None and sink is not None
|
|
250
|
+
and sink is getattr(self.store, "audit", None))
|
|
251
|
+
gen = self._gen.get(inc.id, 0)
|
|
252
|
+
committed = False
|
|
253
|
+
if self.store is not None and not self._slots.locked() and self._store_ok():
|
|
254
|
+
async with self._slots:
|
|
255
|
+
try:
|
|
256
|
+
def write(tx: Tx) -> None:
|
|
257
|
+
upsert_incident(tx, row)
|
|
258
|
+
if in_tx:
|
|
259
|
+
sink.append_tx(tx, "hub", "incident_reopened", inc.id, detail, **refs) # type: ignore[union-attr]
|
|
260
|
+
await self.store.transact(write)
|
|
261
|
+
committed = True
|
|
262
|
+
except asyncio.CancelledError:
|
|
263
|
+
self.mark_dirty(inc)
|
|
264
|
+
raise
|
|
265
|
+
except Exception:
|
|
266
|
+
log.exception("reopen of %s not persisted; it will be retried", inc.id)
|
|
267
|
+
elif self.store is not None:
|
|
268
|
+
self._warn("store stalled: reopen of %s stays dirty", inc.id)
|
|
269
|
+
if self.store is not None:
|
|
270
|
+
if committed:
|
|
271
|
+
self._written[inc.id] = self._now()
|
|
272
|
+
if self._gen.get(inc.id, 0) == gen:
|
|
273
|
+
self._dirty.pop(inc.id, None)
|
|
274
|
+
else:
|
|
275
|
+
self.mark_dirty(inc)
|
|
276
|
+
if sink is not None and not in_tx:
|
|
277
|
+
try:
|
|
278
|
+
await sink.append("hub", "incident_reopened", inc.id, detail, **refs)
|
|
279
|
+
except Exception:
|
|
280
|
+
log.exception("audit row for reopen of %s lost", inc.id)
|
|
281
|
+
try:
|
|
282
|
+
await self._announce(f"REOPENED {inc.id}: {inc.category} on {inc.host}")
|
|
283
|
+
except Exception:
|
|
284
|
+
log.exception("announcement for reopen of %s failed", inc.id)
|
|
285
|
+
|
|
286
|
+
async def flush_all(self, deadline: float | None = None) -> None:
|
|
287
|
+
"""Shutdown: write every dirty incident; stop submitting at ``deadline`` (``time.monotonic``)."""
|
|
288
|
+
for inc in list(self._dirty.values()):
|
|
289
|
+
if deadline is not None and time.monotonic() >= deadline:
|
|
290
|
+
log.error("shutdown deadline passed with %d dirty incident(s) unwritten", len(self._dirty))
|
|
291
|
+
return
|
|
292
|
+
await self.persist(inc)
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""Migration registry. Modules register their migrations; the runner applies them at open."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import sqlite3
|
|
5
|
+
import time
|
|
6
|
+
from collections.abc import Callable
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
|
|
9
|
+
from .errors import MigrationError
|
|
10
|
+
|
|
11
|
+
MODULE_BLOCKS: dict[str, tuple[int, int]] = {
|
|
12
|
+
"store": (1, 99),
|
|
13
|
+
"services": (100, 199),
|
|
14
|
+
"connectors": (200, 299),
|
|
15
|
+
"discovery": (300, 399),
|
|
16
|
+
"approvals": (400, 499),
|
|
17
|
+
"agent": (500, 599),
|
|
18
|
+
"dashboard": (600, 699),
|
|
19
|
+
"mute": (700, 799),
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
Apply = tuple[str, ...] | Callable[[sqlite3.Connection], None]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class Migration:
|
|
27
|
+
module: str
|
|
28
|
+
version: int
|
|
29
|
+
name: str
|
|
30
|
+
apply: Apply
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class MigrationRegistry:
|
|
34
|
+
def __init__(self) -> None:
|
|
35
|
+
self._by_version: dict[int, Migration] = {}
|
|
36
|
+
self._names: set[str] = set()
|
|
37
|
+
|
|
38
|
+
def register(self, module: str, version: int, name: str, apply: Apply) -> None:
|
|
39
|
+
block = MODULE_BLOCKS.get(module)
|
|
40
|
+
if block is None:
|
|
41
|
+
raise MigrationError(name, f"unknown module {module!r}")
|
|
42
|
+
low, high = block
|
|
43
|
+
if not low <= version <= high:
|
|
44
|
+
raise MigrationError(name, f"version {version} is outside the {module} block {low}-{high}")
|
|
45
|
+
if version in self._by_version:
|
|
46
|
+
raise MigrationError(name, f"duplicate version {version}")
|
|
47
|
+
if name in self._names:
|
|
48
|
+
raise MigrationError(name, "duplicate name")
|
|
49
|
+
self._by_version[version] = Migration(module, version, name, apply)
|
|
50
|
+
self._names.add(name)
|
|
51
|
+
|
|
52
|
+
def migrations(self) -> list[Migration]:
|
|
53
|
+
return [self._by_version[v] for v in sorted(self._by_version)]
|
|
54
|
+
|
|
55
|
+
def highest(self) -> int:
|
|
56
|
+
return max(self._by_version, default=0)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _set_user_version(conn: sqlite3.Connection, n: int) -> None:
|
|
60
|
+
"""The only dynamic SQL in the store: PRAGMA user_version cannot take a parameter."""
|
|
61
|
+
if isinstance(n, bool) or not isinstance(n, int):
|
|
62
|
+
raise TypeError("user_version must be an int")
|
|
63
|
+
conn.execute(f"PRAGMA user_version = {int(n)}")
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
_BOOTSTRAP = (
|
|
67
|
+
"CREATE TABLE IF NOT EXISTS migrations (version INTEGER PRIMARY KEY, module TEXT NOT NULL, "
|
|
68
|
+
"name TEXT NOT NULL UNIQUE, applied_at REAL NOT NULL)"
|
|
69
|
+
)
|
|
70
|
+
_INSERT_MIGRATION = "INSERT INTO migrations (version, module, name, applied_at) VALUES (?, ?, ?, ?)"
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _run(conn: sqlite3.Connection, m: Migration, now: Callable[[], float]) -> None:
|
|
74
|
+
conn.execute("BEGIN IMMEDIATE")
|
|
75
|
+
try:
|
|
76
|
+
if callable(m.apply):
|
|
77
|
+
m.apply(conn)
|
|
78
|
+
if not conn.in_transaction:
|
|
79
|
+
raise MigrationError(
|
|
80
|
+
m.name,
|
|
81
|
+
"the migration committed or rolled back by itself; DDL it already committed "
|
|
82
|
+
"cannot be undone",
|
|
83
|
+
)
|
|
84
|
+
else:
|
|
85
|
+
for statement in m.apply:
|
|
86
|
+
conn.execute(statement)
|
|
87
|
+
conn.execute(_INSERT_MIGRATION, (m.version, m.module, m.name, now()))
|
|
88
|
+
current = conn.execute("PRAGMA user_version").fetchone()[0]
|
|
89
|
+
_set_user_version(conn, max(current, m.version))
|
|
90
|
+
conn.execute("COMMIT")
|
|
91
|
+
except MigrationError:
|
|
92
|
+
if conn.in_transaction:
|
|
93
|
+
conn.execute("ROLLBACK")
|
|
94
|
+
raise
|
|
95
|
+
except Exception as exc:
|
|
96
|
+
if conn.in_transaction:
|
|
97
|
+
conn.execute("ROLLBACK")
|
|
98
|
+
raise MigrationError(m.name, exc) from exc
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def apply_migrations(
|
|
102
|
+
conn: sqlite3.Connection, registry: MigrationRegistry, *, now: Callable[[], float] = time.time
|
|
103
|
+
) -> None:
|
|
104
|
+
"""Apply every registered migration not yet recorded, in ascending version order."""
|
|
105
|
+
conn.execute(_BOOTSTRAP)
|
|
106
|
+
done = {row[0] for row in conn.execute("SELECT version FROM migrations")}
|
|
107
|
+
for m in registry.migrations():
|
|
108
|
+
if m.version not in done:
|
|
109
|
+
_run(conn, m, now)
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Proposal model shared by the in-memory hub and the store."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import time
|
|
5
|
+
from dataclasses import asdict, dataclass, field
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
BASELINE_KEYS = ("id", "incident_id", "action", "details", "status", "created", "decided_by",
|
|
9
|
+
"decided_at", "result_note")
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass
|
|
13
|
+
class Proposal:
|
|
14
|
+
"""A remediation an agent wants to perform, awaiting a human decision.
|
|
15
|
+
|
|
16
|
+
SAFETY: ChimericMesh never executes ``action`` on any host. It only records the
|
|
17
|
+
human decision and announces it on IRC. The agent (Kiro via MCP) does the real work
|
|
18
|
+
under its own tool permissions, and only after the proposal is approved.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
id: str
|
|
22
|
+
incident_id: str
|
|
23
|
+
action: str
|
|
24
|
+
details: str = ""
|
|
25
|
+
status: str = "pending" # pending -> approved|denied ; approved -> done
|
|
26
|
+
created: float = field(default_factory=time.time)
|
|
27
|
+
decided_by: str = ""
|
|
28
|
+
decided_at: float | None = None
|
|
29
|
+
result_note: str = ""
|
|
30
|
+
# Extended fields (nullable, so rows written by older versions still load).
|
|
31
|
+
decision_origin: str | None = None
|
|
32
|
+
service_id: str | None = None
|
|
33
|
+
incident_opening: int | None = None
|
|
34
|
+
approved_by_rule: str | None = None
|
|
35
|
+
kind: str | None = None
|
|
36
|
+
files: list[str] | None = None
|
|
37
|
+
estimated_lines: int | None = None
|
|
38
|
+
verification: str | None = None
|
|
39
|
+
files_changed: list[str] | None = None
|
|
40
|
+
lines_changed: int | None = None
|
|
41
|
+
verification_result: str | None = None
|
|
42
|
+
|
|
43
|
+
def to_dict(self) -> dict[str, Any]:
|
|
44
|
+
"""The nine baseline keys, unchanged."""
|
|
45
|
+
full = asdict(self)
|
|
46
|
+
return {k: full[k] for k in BASELINE_KEYS}
|
|
47
|
+
|
|
48
|
+
def to_full_dict(self) -> dict[str, Any]:
|
|
49
|
+
return asdict(self)
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Protocols that let other modules use the store without importing the hub."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from collections.abc import Awaitable, Callable, Mapping
|
|
5
|
+
from typing import Literal, Protocol, runtime_checkable
|
|
6
|
+
|
|
7
|
+
from chimericmesh.diagnostics import Incident
|
|
8
|
+
from chimericmesh.events import Event
|
|
9
|
+
|
|
10
|
+
from .models import Proposal
|
|
11
|
+
|
|
12
|
+
Announce = Callable[[str], Awaitable[None]]
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class AuditSink(Protocol):
|
|
16
|
+
async def append(self, actor: str, action: str, subject: str, detail: str = "", *,
|
|
17
|
+
service_id: str | None = None, rule_id: str | None = None,
|
|
18
|
+
proposal_id: str | None = None) -> object: ...
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@runtime_checkable
|
|
22
|
+
class ProposalClient(Protocol):
|
|
23
|
+
"""What the agent loop gets: create and complete only."""
|
|
24
|
+
|
|
25
|
+
async def create_proposal(self, incident_id: str, action: str, details: str = "", *,
|
|
26
|
+
extra: Mapping[str, object] | None = None) -> Proposal | None: ...
|
|
27
|
+
|
|
28
|
+
async def complete(self, pid: str, note: str = "", *,
|
|
29
|
+
extra: Mapping[str, object] | None = None) -> Proposal | None: ...
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@runtime_checkable
|
|
33
|
+
class ProposalWriter(ProposalClient, Protocol):
|
|
34
|
+
"""Write seam for proposals. ``Hub`` implements it in both modes."""
|
|
35
|
+
|
|
36
|
+
async def decide(self, pid: str, approve: bool, by: str) -> Proposal | None: ...
|
|
37
|
+
|
|
38
|
+
async def hub_transition(self, pid: str, new_status: str, *, decided_by: str,
|
|
39
|
+
approved_by_rule: str | None = None, result_note: str | None = None,
|
|
40
|
+
extra: Mapping[str, object] | None = None) -> Proposal | None: ...
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class StateView(Protocol):
|
|
44
|
+
"""Read-only view of hub state. ``Hub`` implements it in both modes."""
|
|
45
|
+
|
|
46
|
+
def now(self) -> float: ...
|
|
47
|
+
|
|
48
|
+
def get_incident(self, incident_id: str) -> Incident | None: ...
|
|
49
|
+
|
|
50
|
+
def incidents(self, *, status: Literal["open", "resolved"] | None = None,
|
|
51
|
+
service_id: str | None = None, limit: int | None = None) -> list[Incident]: ...
|
|
52
|
+
|
|
53
|
+
def get_proposal(self, pid: str) -> Proposal | None: ...
|
|
54
|
+
|
|
55
|
+
def list_proposals(self, status: str | None = None, *, service_id: str | None = None,
|
|
56
|
+
limit: int | None = None) -> list[Proposal]: ...
|
|
57
|
+
|
|
58
|
+
def recent(self, limit: int = 50, source: str | None = None) -> list[Event]: ...
|
|
59
|
+
|
|
60
|
+
async def events_after(self, after_id: int, limit: int = 100, *, source: str | None = None,
|
|
61
|
+
service_id: str | None = None) -> list[Event]: ...
|