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,430 @@
|
|
|
1
|
+
"""Event rows: bounded queue, batch writer, retention and queries.
|
|
2
|
+
|
|
3
|
+
``EventWriter.put`` runs on the loop thread and never blocks. The writer thread calls the hook
|
|
4
|
+
methods (``next_wait``, ``on_wake``, ``service``, ``finish``) from its loop in ``writer.py``.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import asyncio
|
|
9
|
+
import collections
|
|
10
|
+
import concurrent.futures
|
|
11
|
+
import logging
|
|
12
|
+
import threading
|
|
13
|
+
import time
|
|
14
|
+
from collections.abc import Callable
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
from chimericmesh.events import Event
|
|
18
|
+
|
|
19
|
+
from .config import StoreConfig
|
|
20
|
+
from .tx import Tx, counter_name_part
|
|
21
|
+
from .writer import (
|
|
22
|
+
Job,
|
|
23
|
+
WriterState,
|
|
24
|
+
_deliver,
|
|
25
|
+
_execute,
|
|
26
|
+
_past_deadline,
|
|
27
|
+
async_deliver,
|
|
28
|
+
submit,
|
|
29
|
+
sync_deliver,
|
|
30
|
+
wake,
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
log = logging.getLogger("chimericmesh.store")
|
|
34
|
+
|
|
35
|
+
MAX_TEXT = 4096
|
|
36
|
+
WARN_EVERY = 60.0 # seconds between "queue full" warnings
|
|
37
|
+
|
|
38
|
+
_INSERT = (
|
|
39
|
+
"INSERT OR IGNORE INTO events (id, ts, source, host, app, severity, message, raw, service_id, "
|
|
40
|
+
"log_source_id, ingested) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
|
|
41
|
+
)
|
|
42
|
+
_COUNT = "SELECT COUNT(*) FROM events"
|
|
43
|
+
_TTL_DELETE = (
|
|
44
|
+
"DELETE FROM events WHERE id IN (SELECT id FROM events WHERE ingested < ? ORDER BY id LIMIT ?)"
|
|
45
|
+
)
|
|
46
|
+
_CAP_DELETE = "DELETE FROM events WHERE id IN (SELECT id FROM events ORDER BY id LIMIT ?)"
|
|
47
|
+
|
|
48
|
+
UNASSIGNED = "unassigned"
|
|
49
|
+
_COLUMNS = (
|
|
50
|
+
"SELECT id, ts, source, host, app, severity, message, raw, service_id, log_source_id FROM events"
|
|
51
|
+
)
|
|
52
|
+
_AFTER = (
|
|
53
|
+
_COLUMNS + " WHERE id > :after AND (:before IS NULL OR id < :before) AND (:src IS NULL OR source = :src) "
|
|
54
|
+
"AND (:svc IS NULL OR service_id = :svc) ORDER BY id LIMIT :limit"
|
|
55
|
+
)
|
|
56
|
+
_AFTER_UNASSIGNED = (
|
|
57
|
+
_COLUMNS + " WHERE id > :after AND (:before IS NULL OR id < :before) AND (:src IS NULL OR source = :src) "
|
|
58
|
+
"AND service_id IS NULL ORDER BY id LIMIT :limit"
|
|
59
|
+
)
|
|
60
|
+
_NEWEST = _COLUMNS + " ORDER BY id DESC LIMIT ?"
|
|
61
|
+
_MAX_ID = "SELECT COALESCE(MAX(id), 0) FROM events"
|
|
62
|
+
|
|
63
|
+
def crash_margin(config: StoreConfig) -> int:
|
|
64
|
+
"""``2 * queue_limit + batch_rows`` (L2)."""
|
|
65
|
+
return 2 * config.queue_limit + config.batch_rows
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def event_id_high_water(tx: Tx) -> int:
|
|
69
|
+
"""The larger of the highest stored event id and the ``event_id`` counter."""
|
|
70
|
+
return max(int(tx.one(_MAX_ID)[0]), tx.counter_get("event_id"))
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
_COUNTERS = "SELECT name, value FROM counters WHERE name = 'events_total' OR name LIKE 'evsrc:%'"
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def read_counters(tx: Tx) -> tuple[int, dict[str, int]]:
|
|
77
|
+
"""Cumulative event totals: (all events, per source). Source names are the sanitised counter parts."""
|
|
78
|
+
total, by_source = 0, {}
|
|
79
|
+
for row in tx.all(_COUNTERS):
|
|
80
|
+
if row[0] == "events_total":
|
|
81
|
+
total = int(row[1])
|
|
82
|
+
else:
|
|
83
|
+
by_source[row[0][len("evsrc:"):]] = int(row[1])
|
|
84
|
+
return total, by_source
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
TRIM_CHUNK = 5000 # rows per delete; each chunk is its own transaction
|
|
88
|
+
TRIM_SLACK = 500 # a size-cap trim starts when approx_rows passes max_events + this
|
|
89
|
+
|
|
90
|
+
# Row tuple layout
|
|
91
|
+
_ID, _SOURCE = 0, 2
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _text(value: object) -> str:
|
|
95
|
+
"""Replace lone surrogates, which sqlite3 cannot bind."""
|
|
96
|
+
return str(value).encode("utf-8", "replace").decode("utf-8")
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _clip(value: object) -> str:
|
|
100
|
+
return _text(value)[:MAX_TEXT]
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _opt(value: object | None) -> str | None:
|
|
104
|
+
return None if value is None else _text(value)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _make_row(event: Event, ingested: float) -> tuple:
|
|
108
|
+
return (
|
|
109
|
+
event.id or None, # no id: SQLite assigns one
|
|
110
|
+
float(event.ts), _text(event.source), _text(event.host), _text(event.app), int(event.severity),
|
|
111
|
+
_clip(event.message), _clip(event.raw), _opt(event.service_id), _opt(event.log_source_id),
|
|
112
|
+
float(ingested),
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _insert_batch(tx: Tx, batch: list[tuple], deltas: dict[str, int], last_id: int) -> int:
|
|
117
|
+
"""Insert one batch, its counter deltas and the id high-water mark. Returns rows inserted."""
|
|
118
|
+
cur = tx.executemany(_INSERT, batch)
|
|
119
|
+
inserted = cur.rowcount
|
|
120
|
+
for name, delta in deltas.items():
|
|
121
|
+
tx.counter_add(name, delta)
|
|
122
|
+
if last_id:
|
|
123
|
+
tx.counter_raise("event_id", last_id)
|
|
124
|
+
return inserted
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _to_event(row: Any) -> Event:
|
|
128
|
+
return Event(source=row["source"], host=row["host"], app=row["app"], severity=row["severity"],
|
|
129
|
+
message=row["message"], raw=row["raw"], ts=row["ts"], id=row["id"],
|
|
130
|
+
service_id=row["service_id"], log_source_id=row["log_source_id"])
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _ttl_chunk(tx: Tx, cutoff: float, n: int) -> int:
|
|
134
|
+
"""Delete up to ``n`` of the lowest-id rows ingested before ``cutoff``. Returns rows deleted."""
|
|
135
|
+
return tx.execute(_TTL_DELETE, (cutoff, n)).rowcount
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _cap_chunk(tx: Tx, n: int) -> int:
|
|
139
|
+
"""Delete the ``n`` lowest-id rows. Returns rows deleted."""
|
|
140
|
+
return tx.execute(_CAP_DELETE, (n,)).rowcount
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
class EventWriter:
|
|
144
|
+
def __init__(self, state: WriterState, config: StoreConfig, now: Callable[[], float],
|
|
145
|
+
previous_shutdown_clean: bool) -> None:
|
|
146
|
+
self._state = state
|
|
147
|
+
self._cfg = config
|
|
148
|
+
self._now = now
|
|
149
|
+
self.previous_shutdown_clean = previous_shutdown_clean
|
|
150
|
+
self._lock = threading.Lock()
|
|
151
|
+
# (seq, monotonic time of put, row)
|
|
152
|
+
self._rows: collections.deque[tuple[int, float, tuple]] = collections.deque()
|
|
153
|
+
self._seq = 0 # sequence number of the newest accepted row
|
|
154
|
+
self._resolved = 0 # every row with a sequence number <= this is committed or dropped
|
|
155
|
+
self._orphans: dict[str, int] = {} # counter deltas of rows that never reach a batch
|
|
156
|
+
self._waiters: list[tuple[int, asyncio.AbstractEventLoop, asyncio.Future]] = []
|
|
157
|
+
self._wake_sent = False
|
|
158
|
+
self._closed = False
|
|
159
|
+
self._last_warn: float | None = None
|
|
160
|
+
self.dropped_events = 0
|
|
161
|
+
# retention (writer thread only)
|
|
162
|
+
self._approx: int | None = None # row count estimate; None until the first count
|
|
163
|
+
self._last_trim = time.monotonic()
|
|
164
|
+
self._trim: str | None = None # None, "ttl" or "cap" while a trim is running
|
|
165
|
+
self._trim_cutoff = 0.0
|
|
166
|
+
self._trim_remaining = 0
|
|
167
|
+
self._last_was_flush = False
|
|
168
|
+
|
|
169
|
+
# ---- loop thread ---------------------------------------------------------------------------
|
|
170
|
+
|
|
171
|
+
def put(self, event: Event) -> None:
|
|
172
|
+
"""Queue one row. Never blocks and never raises."""
|
|
173
|
+
try:
|
|
174
|
+
row = _make_row(event, self._now())
|
|
175
|
+
send_wake = False
|
|
176
|
+
with self._lock:
|
|
177
|
+
if self._closed or self._state.stopping:
|
|
178
|
+
self._note_drop(1, "after close")
|
|
179
|
+
return
|
|
180
|
+
if len(self._rows) >= self._cfg.queue_limit:
|
|
181
|
+
_, _, old = self._rows.popleft()
|
|
182
|
+
self._add_orphan(old)
|
|
183
|
+
self._note_drop(1, "queue full")
|
|
184
|
+
self._seq += 1
|
|
185
|
+
self._rows.append((self._seq, time.monotonic(), row))
|
|
186
|
+
if not self._wake_sent:
|
|
187
|
+
self._wake_sent = send_wake = True
|
|
188
|
+
if send_wake and not wake(self._state):
|
|
189
|
+
with self._lock:
|
|
190
|
+
self._wake_sent = False
|
|
191
|
+
except Exception: # put must never break ingest
|
|
192
|
+
log.exception("store: could not queue an event row")
|
|
193
|
+
self.dropped_events += 1
|
|
194
|
+
|
|
195
|
+
@property
|
|
196
|
+
def crash_margin(self) -> int:
|
|
197
|
+
"""Ids that may have been handed out but not stored when the previous run crashed (L2)."""
|
|
198
|
+
return crash_margin(self._cfg)
|
|
199
|
+
|
|
200
|
+
def queue_depth(self) -> int:
|
|
201
|
+
return len(self._rows)
|
|
202
|
+
|
|
203
|
+
async def barrier(self) -> None:
|
|
204
|
+
"""Return once every row queued so far is committed or dropped (forces a flush)."""
|
|
205
|
+
loop = asyncio.get_running_loop()
|
|
206
|
+
with self._lock:
|
|
207
|
+
target = self._seq
|
|
208
|
+
if self._closed or target <= self._resolved:
|
|
209
|
+
return
|
|
210
|
+
fut: asyncio.Future = loop.create_future()
|
|
211
|
+
self._waiters.append((target, loop, fut))
|
|
212
|
+
self._wake_sent = True
|
|
213
|
+
if not wake(self._state):
|
|
214
|
+
self._resolve(self._seq)
|
|
215
|
+
await fut
|
|
216
|
+
|
|
217
|
+
# ---- shared helpers ------------------------------------------------------------------------
|
|
218
|
+
|
|
219
|
+
def _note_drop(self, n: int, why: str) -> None:
|
|
220
|
+
"""Count dropped rows and warn at most once a minute. Caller may hold the lock."""
|
|
221
|
+
self.dropped_events += n
|
|
222
|
+
now = self._now()
|
|
223
|
+
if self._last_warn is None or now - self._last_warn >= WARN_EVERY:
|
|
224
|
+
self._last_warn = now
|
|
225
|
+
log.warning("store: event rows dropped (%s); %d dropped so far", why, self.dropped_events)
|
|
226
|
+
|
|
227
|
+
def _add_orphan(self, row: tuple) -> None:
|
|
228
|
+
for name in ("events_total", "evsrc:" + counter_name_part(row[_SOURCE])):
|
|
229
|
+
self._orphans[name] = self._orphans.get(name, 0) + 1
|
|
230
|
+
|
|
231
|
+
def _forced(self) -> bool:
|
|
232
|
+
return any(target > self._resolved for target, _, _ in self._waiters)
|
|
233
|
+
|
|
234
|
+
def _resolve(self, upto: int) -> None:
|
|
235
|
+
with self._lock:
|
|
236
|
+
self._resolved = max(self._resolved, upto)
|
|
237
|
+
ready = [w for w in self._waiters if w[0] <= self._resolved]
|
|
238
|
+
self._waiters = [w for w in self._waiters if w[0] > self._resolved]
|
|
239
|
+
for _, loop, fut in ready:
|
|
240
|
+
_deliver(loop, fut, None, None)
|
|
241
|
+
|
|
242
|
+
# ---- writer thread hooks -------------------------------------------------------------------
|
|
243
|
+
|
|
244
|
+
def on_wake(self) -> None:
|
|
245
|
+
with self._lock:
|
|
246
|
+
self._wake_sent = False
|
|
247
|
+
|
|
248
|
+
def next_wait(self) -> float | None:
|
|
249
|
+
"""Seconds the writer may sleep before it must look at the queue again (None = forever)."""
|
|
250
|
+
if self._trim is not None:
|
|
251
|
+
return 0.0
|
|
252
|
+
trim_due = max(0.0, self._last_trim + self._cfg.trim_interval - time.monotonic())
|
|
253
|
+
with self._lock:
|
|
254
|
+
if not self._rows:
|
|
255
|
+
return trim_due
|
|
256
|
+
if len(self._rows) >= self._cfg.batch_rows or self._forced():
|
|
257
|
+
return 0.0
|
|
258
|
+
due = self._rows[0][1] + self._cfg.batch_ms / 1000.0
|
|
259
|
+
return min(trim_due, max(0.0, due - time.monotonic()))
|
|
260
|
+
|
|
261
|
+
def _flush_due(self) -> bool:
|
|
262
|
+
with self._lock:
|
|
263
|
+
if not self._rows:
|
|
264
|
+
return False
|
|
265
|
+
if len(self._rows) >= self._cfg.batch_rows or self._forced():
|
|
266
|
+
return True
|
|
267
|
+
return time.monotonic() - self._rows[0][1] >= self._cfg.batch_ms / 1000.0
|
|
268
|
+
|
|
269
|
+
def service(self, state: WriterState) -> None:
|
|
270
|
+
"""One unit of work per call, so queued jobs run between batches and trim chunks."""
|
|
271
|
+
if self._trim is None and time.monotonic() - self._last_trim >= self._cfg.trim_interval:
|
|
272
|
+
self._start_trim()
|
|
273
|
+
if self._flush_due() and not (self._trim is not None and self._last_was_flush):
|
|
274
|
+
self._flush_one(state)
|
|
275
|
+
self._last_was_flush = True
|
|
276
|
+
if (self._trim is None and self._approx is not None
|
|
277
|
+
and self._approx > self._cfg.max_events + TRIM_SLACK):
|
|
278
|
+
self._start_trim()
|
|
279
|
+
return
|
|
280
|
+
self._last_was_flush = False
|
|
281
|
+
if self._trim is not None:
|
|
282
|
+
self._trim_step(state)
|
|
283
|
+
|
|
284
|
+
# ---- retention -----------------------------------------------------------------------------
|
|
285
|
+
|
|
286
|
+
def _job(self, state: WriterState, fn: Callable[[Tx], Any], write: bool) -> tuple[Any, BaseException | None]:
|
|
287
|
+
box: list[tuple[Any, BaseException | None]] = []
|
|
288
|
+
_execute(state, Job(fn, write, lambda result, exc: box.append((result, exc))))
|
|
289
|
+
return box[0]
|
|
290
|
+
|
|
291
|
+
def _start_trim(self) -> None:
|
|
292
|
+
self._trim = "ttl"
|
|
293
|
+
self._trim_cutoff = self._now() - self._cfg.event_ttl_days * 86400.0
|
|
294
|
+
self._last_trim = time.monotonic()
|
|
295
|
+
|
|
296
|
+
def _trim_step(self, state: WriterState) -> None:
|
|
297
|
+
"""Run one chunk of the TTL loop, then of the size-cap loop (stop rule in the design)."""
|
|
298
|
+
if self._trim == "ttl":
|
|
299
|
+
cutoff = self._trim_cutoff
|
|
300
|
+
|
|
301
|
+
def ttl(tx: Tx) -> tuple[int, int | None]:
|
|
302
|
+
n = _ttl_chunk(tx, cutoff, TRIM_CHUNK)
|
|
303
|
+
return n, (int(tx.one(_COUNT)[0]) if n < TRIM_CHUNK else None)
|
|
304
|
+
|
|
305
|
+
result, exc = self._job(state, ttl, True)
|
|
306
|
+
if exc is not None:
|
|
307
|
+
log.error("store: event trim failed (%s)", type(exc).__name__)
|
|
308
|
+
self._trim = None
|
|
309
|
+
return
|
|
310
|
+
n, total = result
|
|
311
|
+
if self._approx is not None:
|
|
312
|
+
self._approx = max(0, self._approx - n)
|
|
313
|
+
if n < TRIM_CHUNK:
|
|
314
|
+
self._approx = total
|
|
315
|
+
self._trim_remaining = total - self._cfg.max_events
|
|
316
|
+
self._trim = "cap" if self._trim_remaining > 0 else None
|
|
317
|
+
return
|
|
318
|
+
remaining = self._trim_remaining
|
|
319
|
+
result, exc = self._job(state, lambda tx: _cap_chunk(tx, min(TRIM_CHUNK, remaining)), True)
|
|
320
|
+
if exc is not None:
|
|
321
|
+
log.error("store: event trim failed (%s)", type(exc).__name__)
|
|
322
|
+
self._trim = None
|
|
323
|
+
return
|
|
324
|
+
if self._approx is not None:
|
|
325
|
+
self._approx = max(0, self._approx - result)
|
|
326
|
+
self._trim_remaining -= result
|
|
327
|
+
if result == 0 or self._trim_remaining <= 0:
|
|
328
|
+
self._trim = None
|
|
329
|
+
def _take_batch(self) -> tuple[list[tuple[int, float, tuple]], dict[str, int]]:
|
|
330
|
+
with self._lock:
|
|
331
|
+
n = min(len(self._rows), self._cfg.batch_rows)
|
|
332
|
+
taken = [self._rows.popleft() for _ in range(n)]
|
|
333
|
+
orphans, self._orphans = self._orphans, {}
|
|
334
|
+
return taken, orphans
|
|
335
|
+
|
|
336
|
+
def _flush_one(self, state: WriterState) -> None:
|
|
337
|
+
if self._approx is None:
|
|
338
|
+
total, exc = self._job(state, lambda tx: int(tx.one(_COUNT)[0]), False)
|
|
339
|
+
if exc is None:
|
|
340
|
+
self._approx = total
|
|
341
|
+
taken, orphans = self._take_batch()
|
|
342
|
+
if not taken:
|
|
343
|
+
return
|
|
344
|
+
batch = [row for _, _, row in taken]
|
|
345
|
+
deltas = dict(orphans)
|
|
346
|
+
deltas["events_total"] = deltas.get("events_total", 0) + len(batch)
|
|
347
|
+
for row in batch:
|
|
348
|
+
name = "evsrc:" + counter_name_part(row[_SOURCE])
|
|
349
|
+
deltas[name] = deltas.get(name, 0) + 1
|
|
350
|
+
last_id = max((row[_ID] or 0 for row in batch), default=0)
|
|
351
|
+
box: list[tuple[Any, BaseException | None]] = []
|
|
352
|
+
_execute(state, Job(lambda tx: _insert_batch(tx, batch, deltas, last_id), True,
|
|
353
|
+
lambda result, exc: box.append((result, exc))))
|
|
354
|
+
result, exc = box[0]
|
|
355
|
+
if exc is not None:
|
|
356
|
+
with self._lock:
|
|
357
|
+
self._note_drop(len(batch), "write failed")
|
|
358
|
+
for name, delta in deltas.items():
|
|
359
|
+
self._orphans[name] = self._orphans.get(name, 0) + delta
|
|
360
|
+
log.error("store: dropped a batch of %d event rows after the retries (%s)",
|
|
361
|
+
len(batch), type(exc).__name__)
|
|
362
|
+
else:
|
|
363
|
+
ignored = len(batch) - int(result)
|
|
364
|
+
if self._approx is not None:
|
|
365
|
+
self._approx += int(result)
|
|
366
|
+
if ignored > 0:
|
|
367
|
+
with self._lock:
|
|
368
|
+
self._note_drop(ignored, "duplicate event id")
|
|
369
|
+
log.error("store: %d event rows ignored (duplicate ids)", ignored)
|
|
370
|
+
self._resolve(taken[-1][0])
|
|
371
|
+
|
|
372
|
+
def finish(self, state: WriterState) -> None:
|
|
373
|
+
"""Shutdown: drain until the deadline (unless abandoned), then drop what is left."""
|
|
374
|
+
if not state.abandon:
|
|
375
|
+
while True:
|
|
376
|
+
with self._lock:
|
|
377
|
+
pending = bool(self._rows)
|
|
378
|
+
if not pending or _past_deadline(state):
|
|
379
|
+
break
|
|
380
|
+
self._flush_one(state)
|
|
381
|
+
with self._lock:
|
|
382
|
+
left = len(self._rows)
|
|
383
|
+
for _, _, row in self._rows:
|
|
384
|
+
self._add_orphan(row)
|
|
385
|
+
self._rows.clear()
|
|
386
|
+
self._closed = True
|
|
387
|
+
if left:
|
|
388
|
+
self._note_drop(left, "shutdown")
|
|
389
|
+
self._resolve(self._seq)
|
|
390
|
+
|
|
391
|
+
# ---- queries (run on the writer thread through the job queue) ------------------------------
|
|
392
|
+
|
|
393
|
+
async def _read(self, fn: Callable[[Tx], Any]) -> Any:
|
|
394
|
+
loop = asyncio.get_running_loop()
|
|
395
|
+
future: asyncio.Future = loop.create_future()
|
|
396
|
+
submit(self._state, Job(fn, False, async_deliver(loop, future)))
|
|
397
|
+
return await future
|
|
398
|
+
|
|
399
|
+
def _read_sync(self, fn: Callable[[Tx], Any]) -> Any:
|
|
400
|
+
future: concurrent.futures.Future = concurrent.futures.Future()
|
|
401
|
+
submit(self._state, Job(fn, False, sync_deliver(future)))
|
|
402
|
+
return future.result()
|
|
403
|
+
|
|
404
|
+
async def after(self, after_id: int, limit: int = 100, *, source: str | None = None,
|
|
405
|
+
service_id: str | None = None, before_id: int | None = None) -> list[Event]:
|
|
406
|
+
"""Events with an id above ``after_id``, oldest first, at most ``limit``."""
|
|
407
|
+
params = {"after": int(after_id), "before": before_id, "src": source, "svc": service_id,
|
|
408
|
+
"limit": max(0, int(limit))}
|
|
409
|
+
if service_id == UNASSIGNED:
|
|
410
|
+
return await self._read(lambda tx: [_to_event(r) for r in tx.all(_AFTER_UNASSIGNED, params)]) # type: ignore[arg-type]
|
|
411
|
+
return await self._read(lambda tx: [_to_event(r) for r in tx.all(_AFTER, params)]) # type: ignore[arg-type]
|
|
412
|
+
|
|
413
|
+
async def newest(self, limit: int) -> list[Event]:
|
|
414
|
+
"""The newest ``limit`` events, oldest first (startup refill of the ring)."""
|
|
415
|
+
n = max(0, int(limit))
|
|
416
|
+
rows = await self._read(lambda tx: tx.all(_NEWEST, (n,)))
|
|
417
|
+
return [_to_event(r) for r in reversed(rows)]
|
|
418
|
+
|
|
419
|
+
def newest_sync(self, limit: int) -> list[Event]:
|
|
420
|
+
"""Blocking form of ``newest`` for the hub's startup load."""
|
|
421
|
+
n = max(0, int(limit))
|
|
422
|
+
rows = self._read_sync(lambda tx: tx.all(_NEWEST, (n,)))
|
|
423
|
+
return [_to_event(r) for r in reversed(rows)]
|
|
424
|
+
|
|
425
|
+
def max_id_sync(self) -> int:
|
|
426
|
+
"""Startup seed for event ids: a pure read. Blocks the caller; runs on the writer thread.
|
|
427
|
+
|
|
428
|
+
After an unclean shutdown ``Store.open`` already raised the stored mark by ``crash_margin`` (B2).
|
|
429
|
+
"""
|
|
430
|
+
return self._read_sync(event_id_high_water)
|