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,184 @@
|
|
|
1
|
+
"""Pure, total field validators. Nothing here reads the filesystem (``paths.py`` does)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import re
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
|
|
8
|
+
from .errors import ValidationFailed
|
|
9
|
+
from .models import CLEAR, LogSourceFields, LogSourcePatch, ServiceFields, ServicePatch
|
|
10
|
+
|
|
11
|
+
SLUG = re.compile(r"[a-z0-9][a-z0-9-]{0,39}") # used with fullmatch, never with "$"
|
|
12
|
+
RESERVED_IDS = frozenset({"unassigned"})
|
|
13
|
+
KNOWN_PROTOCOLS = ("syslog-udp", "syslog-tcp", "telnet", "irc", "file")
|
|
14
|
+
DEFAULT_FORMATS = frozenset({"syslog-text", "ncsa", "w3c", "xferlog", "plain"})
|
|
15
|
+
FORMAT_NAME = re.compile(r"[a-z0-9][a-z0-9-]{0,29}")
|
|
16
|
+
|
|
17
|
+
_UNWANTED = re.compile(r"[\x00-\x1f\x7f-\x9f\ud800-\udfff]")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True, slots=True)
|
|
21
|
+
class Limits:
|
|
22
|
+
name: int = 80
|
|
23
|
+
list_len: int = 20
|
|
24
|
+
entry: int = 100
|
|
25
|
+
services: int = 100
|
|
26
|
+
sources_per_service: int = 20
|
|
27
|
+
sources_total: int = 200
|
|
28
|
+
path: int = 1024
|
|
29
|
+
host: int = 100
|
|
30
|
+
format: int = 30
|
|
31
|
+
backfill_max: int = 1000
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
LIMITS = Limits()
|
|
35
|
+
|
|
36
|
+
_SERVICE_KEYS = ("id", "name", "hosts", "app_names", "protocols", "code_folder")
|
|
37
|
+
_SOURCE_KEYS_CREATE = ("path", "format", "enabled", "host", "backfill_lines")
|
|
38
|
+
_SOURCE_KEYS_PATCH = ("format", "enabled", "host", "backfill_lines")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def clean_text(value: str) -> str:
|
|
42
|
+
"""Remove control characters and lone surrogates, then strip."""
|
|
43
|
+
return _UNWANTED.sub("", value).strip()
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def validate_slug(value: object) -> str:
|
|
47
|
+
if not isinstance(value, str):
|
|
48
|
+
raise ValidationFailed("id", "must be text")
|
|
49
|
+
if SLUG.fullmatch(value) is None:
|
|
50
|
+
raise ValidationFailed("id", "must match [a-z0-9][a-z0-9-]{0,39}")
|
|
51
|
+
if value in RESERVED_IDS:
|
|
52
|
+
raise ValidationFailed("id", f"{value!r} is reserved")
|
|
53
|
+
return value
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _text(field: str, value: object, cap: int) -> str:
|
|
57
|
+
if not isinstance(value, str):
|
|
58
|
+
raise ValidationFailed(field, "must be text")
|
|
59
|
+
cleaned = clean_text(value)
|
|
60
|
+
if not cleaned:
|
|
61
|
+
raise ValidationFailed(field, "must not be empty")
|
|
62
|
+
if len(cleaned) > cap:
|
|
63
|
+
raise ValidationFailed(field, f"must be at most {cap} characters")
|
|
64
|
+
return cleaned
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _entries(field: str, value: object) -> tuple[str, ...]:
|
|
68
|
+
if not isinstance(value, (list, tuple)):
|
|
69
|
+
raise ValidationFailed(field, "must be a list of text")
|
|
70
|
+
seen: set[str] = set()
|
|
71
|
+
out: list[str] = []
|
|
72
|
+
for item in value:
|
|
73
|
+
text = _text(field, item, LIMITS.entry)
|
|
74
|
+
key = text.casefold()
|
|
75
|
+
if key not in seen:
|
|
76
|
+
seen.add(key)
|
|
77
|
+
out.append(text)
|
|
78
|
+
if len(out) > LIMITS.list_len:
|
|
79
|
+
raise ValidationFailed(field, f"must have at most {LIMITS.list_len} entries")
|
|
80
|
+
return tuple(out)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _protocols(value: object) -> tuple[str, ...]:
|
|
84
|
+
if not isinstance(value, (list, tuple)):
|
|
85
|
+
raise ValidationFailed("protocols", "must be a list of text")
|
|
86
|
+
out: list[str] = []
|
|
87
|
+
for item in value:
|
|
88
|
+
if not isinstance(item, str) or item not in KNOWN_PROTOCOLS:
|
|
89
|
+
raise ValidationFailed("protocols", f"must be one of {', '.join(KNOWN_PROTOCOLS)}")
|
|
90
|
+
if item not in out:
|
|
91
|
+
out.append(item)
|
|
92
|
+
return tuple(out)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _code_folder(value: object) -> str:
|
|
96
|
+
if not isinstance(value, str) or not value:
|
|
97
|
+
raise ValidationFailed("code_folder", "must be a non-empty path")
|
|
98
|
+
return value
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _reject_unknown(raw: Mapping[str, object], allowed: tuple[str, ...]) -> None:
|
|
102
|
+
for key in raw:
|
|
103
|
+
if key not in allowed:
|
|
104
|
+
raise ValidationFailed(str(key)[:40], "unknown or read-only field")
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def validate_service_fields(raw: Mapping[str, object], *, for_create: bool) -> ServiceFields | ServicePatch:
|
|
108
|
+
"""Create: ``id`` and ``name`` are required. Patch: absent means unchanged, null clears only ``code_folder``."""
|
|
109
|
+
if not isinstance(raw, Mapping):
|
|
110
|
+
raise ValidationFailed("body", "must be an object")
|
|
111
|
+
_reject_unknown(raw, _SERVICE_KEYS if for_create else _SERVICE_KEYS[1:])
|
|
112
|
+
if for_create:
|
|
113
|
+
if "id" not in raw:
|
|
114
|
+
raise ValidationFailed("id", "is required")
|
|
115
|
+
if "name" not in raw:
|
|
116
|
+
raise ValidationFailed("name", "is required")
|
|
117
|
+
values: dict[str, object] = {}
|
|
118
|
+
if "id" in raw:
|
|
119
|
+
values["id"] = validate_slug(raw["id"])
|
|
120
|
+
if "name" in raw:
|
|
121
|
+
values["name"] = _text("name", raw["name"], LIMITS.name)
|
|
122
|
+
for field in ("hosts", "app_names"):
|
|
123
|
+
if field in raw:
|
|
124
|
+
values[field] = _entries(field, raw[field])
|
|
125
|
+
if "protocols" in raw:
|
|
126
|
+
values["protocols"] = _protocols(raw["protocols"])
|
|
127
|
+
if "code_folder" in raw:
|
|
128
|
+
if raw["code_folder"] is None:
|
|
129
|
+
values["code_folder"] = None if for_create else CLEAR
|
|
130
|
+
else:
|
|
131
|
+
values["code_folder"] = _code_folder(raw["code_folder"])
|
|
132
|
+
if for_create:
|
|
133
|
+
return ServiceFields(**values) # type: ignore[arg-type]
|
|
134
|
+
return ServicePatch(**values) # type: ignore[arg-type]
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _backfill(value: object) -> int:
|
|
138
|
+
if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= LIMITS.backfill_max:
|
|
139
|
+
raise ValidationFailed("backfill_lines", f"must be an integer from 0 to {LIMITS.backfill_max}")
|
|
140
|
+
return value
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _format(value: object, known: frozenset[str]) -> str:
|
|
144
|
+
if not isinstance(value, str):
|
|
145
|
+
raise ValidationFailed("format", "must be text")
|
|
146
|
+
name = clean_text(value)
|
|
147
|
+
if len(name) > LIMITS.format or name not in known:
|
|
148
|
+
raise ValidationFailed("format", f"must be one of {', '.join(sorted(known))}")
|
|
149
|
+
return name
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def validate_log_source_fields(raw: Mapping[str, object], *, known_formats: frozenset[str] | None = None,
|
|
153
|
+
for_create: bool) -> LogSourceFields | LogSourcePatch:
|
|
154
|
+
"""Create: ``path`` and ``format`` are required. Patch: ``path`` cannot change."""
|
|
155
|
+
if not isinstance(raw, Mapping):
|
|
156
|
+
raise ValidationFailed("body", "must be an object")
|
|
157
|
+
known = DEFAULT_FORMATS if known_formats is None else known_formats
|
|
158
|
+
_reject_unknown(raw, _SOURCE_KEYS_CREATE if for_create else _SOURCE_KEYS_PATCH)
|
|
159
|
+
if for_create:
|
|
160
|
+
for field in ("path", "format"):
|
|
161
|
+
if field not in raw:
|
|
162
|
+
raise ValidationFailed(field, "is required")
|
|
163
|
+
values: dict[str, object] = {}
|
|
164
|
+
if "path" in raw:
|
|
165
|
+
path = raw["path"]
|
|
166
|
+
if not isinstance(path, str) or not path:
|
|
167
|
+
raise ValidationFailed("path", "must be a non-empty path")
|
|
168
|
+
values["path"] = path
|
|
169
|
+
if "format" in raw:
|
|
170
|
+
values["format"] = _format(raw["format"], known)
|
|
171
|
+
if "enabled" in raw:
|
|
172
|
+
if not isinstance(raw["enabled"], bool):
|
|
173
|
+
raise ValidationFailed("enabled", "must be true or false")
|
|
174
|
+
values["enabled"] = raw["enabled"]
|
|
175
|
+
if "host" in raw:
|
|
176
|
+
if raw["host"] is None:
|
|
177
|
+
values["host"] = None if for_create else CLEAR
|
|
178
|
+
else:
|
|
179
|
+
values["host"] = _text("host", raw["host"], LIMITS.host)
|
|
180
|
+
if "backfill_lines" in raw:
|
|
181
|
+
values["backfill_lines"] = _backfill(raw["backfill_lines"])
|
|
182
|
+
if for_create:
|
|
183
|
+
return LogSourceFields(**values) # type: ignore[arg-type]
|
|
184
|
+
return LogSourcePatch(**values) # type: ignore[arg-type]
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Local SQLite store for the hub (stdlib only)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from .errors import (
|
|
5
|
+
InvalidTransition,
|
|
6
|
+
MigrationError,
|
|
7
|
+
NotFound,
|
|
8
|
+
SchemaTooNewError,
|
|
9
|
+
StoreBusyError,
|
|
10
|
+
StoreClosedError,
|
|
11
|
+
StoreCorruptError,
|
|
12
|
+
StoreError,
|
|
13
|
+
StoreFullError,
|
|
14
|
+
StoreOpenError,
|
|
15
|
+
StoreReentryError,
|
|
16
|
+
StoreWriteError,
|
|
17
|
+
)
|
|
18
|
+
from .config import StoreConfig
|
|
19
|
+
from .migrations import Migration, MigrationRegistry
|
|
20
|
+
from .store import Store, StoreHealth
|
|
21
|
+
from .tx import SubscriberError, Tx
|
|
22
|
+
|
|
23
|
+
__all__ = [
|
|
24
|
+
"Store",
|
|
25
|
+
"StoreConfig",
|
|
26
|
+
"StoreHealth",
|
|
27
|
+
"SubscriberError",
|
|
28
|
+
"Tx",
|
|
29
|
+
"InvalidTransition",
|
|
30
|
+
"Migration",
|
|
31
|
+
"MigrationError",
|
|
32
|
+
"MigrationRegistry",
|
|
33
|
+
"NotFound",
|
|
34
|
+
"SchemaTooNewError",
|
|
35
|
+
"StoreBusyError",
|
|
36
|
+
"StoreClosedError",
|
|
37
|
+
"StoreCorruptError",
|
|
38
|
+
"StoreError",
|
|
39
|
+
"StoreFullError",
|
|
40
|
+
"StoreOpenError",
|
|
41
|
+
"StoreReentryError",
|
|
42
|
+
"StoreWriteError",
|
|
43
|
+
]
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"""Append-only audit log. No update or delete operation exists here or in SQL (triggers)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import re
|
|
5
|
+
import weakref
|
|
6
|
+
from typing import TYPE_CHECKING, Any
|
|
7
|
+
|
|
8
|
+
from .tx import Tx
|
|
9
|
+
|
|
10
|
+
if TYPE_CHECKING:
|
|
11
|
+
from .store import Store
|
|
12
|
+
|
|
13
|
+
MAX_SHORT = 100
|
|
14
|
+
MAX_DETAIL = 1000
|
|
15
|
+
DEFAULT_LIMIT = 100
|
|
16
|
+
MAX_LIMIT = 500
|
|
17
|
+
|
|
18
|
+
_CONTROL = re.compile(r"[\x00-\x1f\x7f-\x9f]")
|
|
19
|
+
_USERINFO = re.compile(r"([A-Za-z][A-Za-z0-9+.\-]*://)[^/\s@]+@")
|
|
20
|
+
|
|
21
|
+
_INSERT = (
|
|
22
|
+
"INSERT INTO audit_log (ts, actor, action, subject, detail, service_id, rule_id, proposal_id) "
|
|
23
|
+
"VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
|
|
24
|
+
)
|
|
25
|
+
_SELECT = (
|
|
26
|
+
"SELECT id, ts, actor, action, subject, detail, service_id, rule_id, proposal_id FROM audit_log "
|
|
27
|
+
"WHERE (:before IS NULL OR id < :before) AND (:svc IS NULL OR service_id = :svc) "
|
|
28
|
+
"AND (:rule IS NULL OR rule_id = :rule) AND (:prop IS NULL OR proposal_id = :prop) "
|
|
29
|
+
"ORDER BY id DESC LIMIT :limit"
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class AuditLog:
|
|
34
|
+
"""Writes and reads audit rows. Text is sanitised before it reaches SQL."""
|
|
35
|
+
|
|
36
|
+
def __init__(self, store: "Store") -> None:
|
|
37
|
+
self._store = weakref.ref(store)
|
|
38
|
+
self._secrets: list[str] = []
|
|
39
|
+
|
|
40
|
+
def _add_secret(self, secret: str) -> None:
|
|
41
|
+
if secret and secret not in self._secrets:
|
|
42
|
+
self._secrets.append(secret)
|
|
43
|
+
|
|
44
|
+
def _clean(self, text: object, limit: int) -> str:
|
|
45
|
+
out = str(text).encode("utf-8", "replace").decode("utf-8")
|
|
46
|
+
out = _CONTROL.sub("", out)
|
|
47
|
+
for secret in sorted(self._secrets, key=len, reverse=True):
|
|
48
|
+
out = out.replace(secret, "[redacted]")
|
|
49
|
+
out = _USERINFO.sub(r"\1***@", out)
|
|
50
|
+
return out[:limit]
|
|
51
|
+
|
|
52
|
+
def _ref(self, value: str | None) -> str | None:
|
|
53
|
+
return None if value is None else self._clean(value, MAX_SHORT)
|
|
54
|
+
|
|
55
|
+
def append_tx(self, tx: Tx, actor: str, action: str, subject: str, detail: str = "", *,
|
|
56
|
+
service_id: str | None = None, rule_id: str | None = None,
|
|
57
|
+
proposal_id: str | None = None) -> int:
|
|
58
|
+
store = self._store()
|
|
59
|
+
ts = store.now() if store is not None else 0.0
|
|
60
|
+
cur = tx.execute(_INSERT, (
|
|
61
|
+
ts,
|
|
62
|
+
self._clean(actor, MAX_SHORT), self._clean(action, MAX_SHORT),
|
|
63
|
+
self._clean(subject, MAX_SHORT), self._clean(detail, MAX_DETAIL),
|
|
64
|
+
self._ref(service_id), self._ref(rule_id), self._ref(proposal_id),
|
|
65
|
+
))
|
|
66
|
+
return int(cur.lastrowid)
|
|
67
|
+
|
|
68
|
+
async def append(self, actor: str, action: str, subject: str, detail: str = "", *,
|
|
69
|
+
service_id: str | None = None, rule_id: str | None = None,
|
|
70
|
+
proposal_id: str | None = None) -> int:
|
|
71
|
+
store = self._store()
|
|
72
|
+
if store is None:
|
|
73
|
+
raise RuntimeError("audit log used after its store was dropped")
|
|
74
|
+
return await store.transact(lambda tx: self.append_tx(
|
|
75
|
+
tx, actor, action, subject, detail,
|
|
76
|
+
service_id=service_id, rule_id=rule_id, proposal_id=proposal_id))
|
|
77
|
+
|
|
78
|
+
async def read(self, limit: int = DEFAULT_LIMIT, before: int | None = None, *,
|
|
79
|
+
service_id: str | None = None, rule_id: str | None = None,
|
|
80
|
+
proposal_id: str | None = None) -> list[dict[str, Any]]:
|
|
81
|
+
store = self._store()
|
|
82
|
+
if store is None:
|
|
83
|
+
raise RuntimeError("audit log used after its store was dropped")
|
|
84
|
+
params = {
|
|
85
|
+
"before": before, "svc": service_id, "rule": rule_id, "prop": proposal_id,
|
|
86
|
+
"limit": max(1, min(int(limit), MAX_LIMIT)),
|
|
87
|
+
}
|
|
88
|
+
rows = await store.read(lambda tx: [dict(r) for r in tx.all(_SELECT, params)]) # type: ignore[arg-type]
|
|
89
|
+
return rows
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""Store configuration: five documented environment variables plus timing knobs for tests."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import logging
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
from collections.abc import Mapping
|
|
8
|
+
from dataclasses import dataclass, replace
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
log = logging.getLogger("chimericmesh.store")
|
|
12
|
+
|
|
13
|
+
DB_FILENAME = "chimericmesh.db"
|
|
14
|
+
MEMORY = ":memory:"
|
|
15
|
+
|
|
16
|
+
DEFAULT_MAX_EVENTS = 100_000
|
|
17
|
+
DEFAULT_EVENT_TTL_DAYS = 7
|
|
18
|
+
DEFAULT_REOPEN_AFTER = 300
|
|
19
|
+
|
|
20
|
+
_DIGITS = re.compile(r"[0-9]{1,18}")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _env_int(environ: Mapping[str, str], name: str, default: int, low: int, high: int) -> int:
|
|
24
|
+
raw = environ.get(name)
|
|
25
|
+
if raw is None:
|
|
26
|
+
return default
|
|
27
|
+
if _DIGITS.fullmatch(raw) and low <= int(raw) <= high:
|
|
28
|
+
return int(raw)
|
|
29
|
+
log.warning("%s=%r is not an integer in %d..%d; using %d", name, raw[:40], low, high, default)
|
|
30
|
+
return default
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True)
|
|
34
|
+
class StoreConfig:
|
|
35
|
+
max_events: int = DEFAULT_MAX_EVENTS
|
|
36
|
+
event_ttl_days: int = DEFAULT_EVENT_TTL_DAYS
|
|
37
|
+
reopen_after: int = DEFAULT_REOPEN_AFTER
|
|
38
|
+
batch_rows: int = 500
|
|
39
|
+
batch_ms: int = 250
|
|
40
|
+
queue_limit: int = 20000
|
|
41
|
+
trim_interval: float = 60.0
|
|
42
|
+
flush_interval: float = 30.0
|
|
43
|
+
flush_tick: float = 5.0
|
|
44
|
+
persist_slots: int = 256
|
|
45
|
+
|
|
46
|
+
@classmethod
|
|
47
|
+
def from_env(cls, environ: Mapping[str, str] | None = None, **overrides: object) -> "StoreConfig":
|
|
48
|
+
env = os.environ if environ is None else environ
|
|
49
|
+
cfg = cls(
|
|
50
|
+
max_events=_env_int(env, "CHIMERICMESH_MAX_EVENTS", DEFAULT_MAX_EVENTS, 1, 10_000_000),
|
|
51
|
+
event_ttl_days=_env_int(env, "CHIMERICMESH_EVENT_TTL_DAYS", DEFAULT_EVENT_TTL_DAYS, 1, 3650),
|
|
52
|
+
reopen_after=_env_int(env, "CHIMERICMESH_REOPEN_AFTER_SECONDS", DEFAULT_REOPEN_AFTER, 0, 86400),
|
|
53
|
+
)
|
|
54
|
+
return replace(cfg, **overrides) if overrides else cfg # type: ignore[arg-type]
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
PROPOSAL_ID_NOTE = "Proposal ids are unique per database; deleting the database restarts them at p1."
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def describe_startup(path: str) -> str:
|
|
61
|
+
"""The one startup log line: where the data lives and what that means for proposal ids."""
|
|
62
|
+
if path == MEMORY:
|
|
63
|
+
return f"store: in-memory database, nothing is saved. {PROPOSAL_ID_NOTE}"
|
|
64
|
+
return f"store: database at {path}. {PROPOSAL_ID_NOTE}"
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def env_reopen_after(environ: Mapping[str, str] | None = None) -> int:
|
|
68
|
+
"""``CHIMERICMESH_REOPEN_AFTER_SECONDS`` (0 to 86400); a bad value warns and gives 300."""
|
|
69
|
+
env = os.environ if environ is None else environ
|
|
70
|
+
return _env_int(env, "CHIMERICMESH_REOPEN_AFTER_SECONDS", DEFAULT_REOPEN_AFTER, 0, 86400)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def resolve_home(environ: Mapping[str, str] | None = None) -> str:
|
|
74
|
+
"""Absolute per-user home directory. Never derived from the working directory by default."""
|
|
75
|
+
env = os.environ if environ is None else environ
|
|
76
|
+
raw = env.get("CHIMERICMESH_HOME") or "~/.chimericmesh"
|
|
77
|
+
return os.path.abspath(os.path.expanduser(raw))
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def resolve_db_path(environ: Mapping[str, str] | None = None) -> str:
|
|
81
|
+
"""Absolute database path, or ``:memory:``. Pure: touches no file."""
|
|
82
|
+
env = os.environ if environ is None else environ
|
|
83
|
+
raw = env.get("CHIMERICMESH_DB")
|
|
84
|
+
if raw == MEMORY:
|
|
85
|
+
return MEMORY
|
|
86
|
+
if raw:
|
|
87
|
+
return os.path.abspath(os.path.expanduser(raw))
|
|
88
|
+
return str(Path(resolve_home(env)) / DB_FILENAME)
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""Open the SQLite connection: byte-level header guard, owner-only creation, pragmas, second guard."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import logging
|
|
5
|
+
import os
|
|
6
|
+
import sqlite3
|
|
7
|
+
import struct
|
|
8
|
+
|
|
9
|
+
from chimericmesh import fsperms
|
|
10
|
+
|
|
11
|
+
from .config import MEMORY
|
|
12
|
+
from .errors import SchemaTooNewError, StoreCorruptError, StoreOpenError
|
|
13
|
+
from .migrations import MigrationRegistry
|
|
14
|
+
|
|
15
|
+
log = logging.getLogger("chimericmesh.store")
|
|
16
|
+
|
|
17
|
+
_MAGIC = b"SQLite format 3\x00"
|
|
18
|
+
_HEADER_SIZE = 100
|
|
19
|
+
_MIN_SQLITE = (3, 24)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _header_user_version(path: str) -> int | None:
|
|
23
|
+
"""Read the header bytes only (no SQLite connection, nothing is written).
|
|
24
|
+
|
|
25
|
+
Returns None for a missing or empty file (a new database), else ``user_version`` as stored in
|
|
26
|
+
the main file. Raises StoreCorruptError when the file is not a SQLite database.
|
|
27
|
+
"""
|
|
28
|
+
try:
|
|
29
|
+
size = os.path.getsize(path)
|
|
30
|
+
except FileNotFoundError:
|
|
31
|
+
return None
|
|
32
|
+
if size == 0:
|
|
33
|
+
return None
|
|
34
|
+
with open(path, "rb") as fh:
|
|
35
|
+
head = fh.read(_HEADER_SIZE)
|
|
36
|
+
if len(head) < _HEADER_SIZE or head[:16] != _MAGIC:
|
|
37
|
+
raise StoreCorruptError(path)
|
|
38
|
+
return struct.unpack(">i", head[60:64])[0]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _create_owner_only(path: str) -> None:
|
|
42
|
+
parent = os.path.dirname(path)
|
|
43
|
+
if parent and not os.path.isdir(parent):
|
|
44
|
+
os.makedirs(parent, exist_ok=True)
|
|
45
|
+
fsperms.secure_dir(parent)
|
|
46
|
+
try:
|
|
47
|
+
fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
|
|
48
|
+
except FileExistsError:
|
|
49
|
+
return
|
|
50
|
+
os.close(fd)
|
|
51
|
+
fsperms.secure_file(path)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def open_connection(path: str, registry: MigrationRegistry) -> sqlite3.Connection:
|
|
55
|
+
"""Open ``path`` (absolute path or ``:memory:``) and return a ready connection.
|
|
56
|
+
|
|
57
|
+
Writes nothing before the guards pass: the byte guard first, then the pragmas and a
|
|
58
|
+
``PRAGMA user_version`` check (a crash can leave the new value only in the ``-wal`` file).
|
|
59
|
+
"""
|
|
60
|
+
if sqlite3.sqlite_version_info < _MIN_SQLITE:
|
|
61
|
+
raise StoreOpenError(
|
|
62
|
+
f"SQLite {'.'.join(map(str, sqlite3.sqlite_version_info))} is too old; "
|
|
63
|
+
"3.24 or newer is required"
|
|
64
|
+
)
|
|
65
|
+
memory = path == MEMORY
|
|
66
|
+
known = registry.highest()
|
|
67
|
+
if not memory:
|
|
68
|
+
found = _header_user_version(path)
|
|
69
|
+
if found is not None and found > known:
|
|
70
|
+
raise SchemaTooNewError(path, found, known)
|
|
71
|
+
try:
|
|
72
|
+
_create_owner_only(path)
|
|
73
|
+
except OSError as exc:
|
|
74
|
+
raise StoreOpenError(f"cannot create {path}: {type(exc).__name__}") from exc
|
|
75
|
+
try:
|
|
76
|
+
conn = sqlite3.connect(path, isolation_level=None, check_same_thread=False)
|
|
77
|
+
except sqlite3.Error as exc:
|
|
78
|
+
raise StoreOpenError(f"cannot open {path}: {type(exc).__name__}") from exc
|
|
79
|
+
try:
|
|
80
|
+
conn.execute("PRAGMA busy_timeout=5000")
|
|
81
|
+
mode = conn.execute("PRAGMA journal_mode=WAL").fetchone()[0]
|
|
82
|
+
if not memory and str(mode).lower() != "wal":
|
|
83
|
+
raise StoreOpenError(f"{path}: SQLite did not enable WAL mode (got {mode!r})")
|
|
84
|
+
conn.execute("PRAGMA synchronous=NORMAL")
|
|
85
|
+
conn.execute("PRAGMA foreign_keys=ON")
|
|
86
|
+
conn.execute("PRAGMA wal_autocheckpoint=1000")
|
|
87
|
+
current = conn.execute("PRAGMA user_version").fetchone()[0]
|
|
88
|
+
if current > known:
|
|
89
|
+
raise SchemaTooNewError(path, current, known)
|
|
90
|
+
if not memory:
|
|
91
|
+
fsperms.secure_sidecars(path)
|
|
92
|
+
except sqlite3.DatabaseError as exc:
|
|
93
|
+
conn.close()
|
|
94
|
+
raise StoreCorruptError(path, type(exc).__name__) from exc
|
|
95
|
+
except BaseException:
|
|
96
|
+
conn.close()
|
|
97
|
+
raise
|
|
98
|
+
return conn
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""Store error types. All of them derive from StoreError so callers can catch one class."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class StoreError(Exception):
|
|
6
|
+
"""Base class for every error raised by the store."""
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class StoreOpenError(StoreError):
|
|
10
|
+
"""The database could not be opened (environment, SQLite version, WAL unavailable)."""
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class StoreCorruptError(StoreOpenError):
|
|
14
|
+
"""The file exists but is not a valid SQLite database. The file is left untouched."""
|
|
15
|
+
|
|
16
|
+
def __init__(self, path: str, detail: str = "") -> None:
|
|
17
|
+
self.path = path
|
|
18
|
+
super().__init__(f"{path} is not a valid SQLite database" + (f": {detail}" if detail else ""))
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class SchemaTooNewError(StoreOpenError):
|
|
22
|
+
"""The database was written by a newer build (user_version above the highest known)."""
|
|
23
|
+
|
|
24
|
+
def __init__(self, path: str, found: int, known: int) -> None:
|
|
25
|
+
self.path = path
|
|
26
|
+
self.found = found
|
|
27
|
+
self.known = known
|
|
28
|
+
super().__init__(f"{path} has schema version {found}, this build knows up to {known}")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class MigrationError(StoreError):
|
|
32
|
+
"""A migration is invalid or failed; the failing migration was rolled back."""
|
|
33
|
+
|
|
34
|
+
def __init__(self, name: str, cause: BaseException | str | None = None) -> None:
|
|
35
|
+
self.name = name
|
|
36
|
+
self.cause = cause
|
|
37
|
+
super().__init__(f"migration {name}: {cause}" if cause else f"migration {name}")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class StoreWriteError(StoreError):
|
|
41
|
+
"""A write failed after the retries were used up."""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class StoreBusyError(StoreWriteError):
|
|
45
|
+
"""The database stayed busy or locked."""
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class StoreFullError(StoreWriteError):
|
|
49
|
+
"""The disk is full."""
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class StoreClosedError(StoreError):
|
|
53
|
+
"""The store was used after close."""
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class StoreReentryError(StoreError):
|
|
57
|
+
"""A job was submitted from the writer thread (it would wait for itself)."""
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class InvalidTransition(StoreError):
|
|
61
|
+
"""A proposal status change that the transition table does not allow."""
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class NotFound(StoreError):
|
|
65
|
+
"""The requested row does not exist."""
|