egzoscore 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. egzos/__init__.py +11 -0
  2. egzos/_ids.py +29 -0
  3. egzos/_signals.py +39 -0
  4. egzos/_term.py +33 -0
  5. egzos/_types.py +1023 -0
  6. egzos/api/__init__.py +150 -0
  7. egzos/api/app.py +1574 -0
  8. egzos/api/blobs.py +92 -0
  9. egzos/api/throttle.py +190 -0
  10. egzos/auth.py +176 -0
  11. egzos/authz/__init__.py +5 -0
  12. egzos/authz/presence.py +778 -0
  13. egzos/authz/values.py +32 -0
  14. egzos/backends/__init__.py +8 -0
  15. egzos/backends/base.py +91 -0
  16. egzos/backends/postgres.py +490 -0
  17. egzos/backends/sqlite.py +524 -0
  18. egzos/binding.py +309 -0
  19. egzos/cli/__init__.py +1092 -0
  20. egzos/cli/__main__.py +11 -0
  21. egzos/confirm.py +455 -0
  22. egzos/container.py +222 -0
  23. egzos/identity.py +1104 -0
  24. egzos/ledger.py +167 -0
  25. egzos/mcp/__init__.py +3 -0
  26. egzos/mcp/http.py +90 -0
  27. egzos/mcp/server.py +287 -0
  28. egzos/model.py +242 -0
  29. egzos/py.typed +0 -0
  30. egzos/resolver.py +115 -0
  31. egzos/store/__init__.py +10 -0
  32. egzos/store/autotitle.py +31 -0
  33. egzos/store/blobs.py +120 -0
  34. egzos/store/find.py +120 -0
  35. egzos/store/items.py +233 -0
  36. egzos/store/nodes.py +193 -0
  37. egzos/store/objects.py +143 -0
  38. egzos/store/uploads.py +369 -0
  39. egzos/trust.py +675 -0
  40. egzos/web/__init__.py +88 -0
  41. egzos/web/app.py +965 -0
  42. egzos/web/static/htmx.LICENSE +13 -0
  43. egzos/web/static/htmx.min.js +1 -0
  44. egzos/web/static/lifeboat.css +140 -0
  45. egzos/web/static/lifeboat.js +12 -0
  46. egzos/web/strings.py +133 -0
  47. egzos/web/templates/_manifest_row.html +3 -0
  48. egzos/web/templates/_shell.html +29 -0
  49. egzos/web/templates/_window.html +7 -0
  50. egzos/web/templates/base.html +24 -0
  51. egzos/web/templates/error.html +10 -0
  52. egzos/web/templates/home.html +39 -0
  53. egzos/web/templates/item.html +91 -0
  54. egzos/web/templates/notfound.html +6 -0
  55. egzos/web/templates/pending.html +107 -0
  56. egzos/web/tokens.css +294 -0
  57. egzoscore-0.2.0.dist-info/METADATA +135 -0
  58. egzoscore-0.2.0.dist-info/RECORD +62 -0
  59. egzoscore-0.2.0.dist-info/WHEEL +4 -0
  60. egzoscore-0.2.0.dist-info/entry_points.txt +2 -0
  61. egzoscore-0.2.0.dist-info/licenses/LICENSE +65 -0
  62. egzoscore-0.2.0.dist-info/licenses/NOTICE +6 -0
egzos/binding.py ADDED
@@ -0,0 +1,309 @@
1
+ # Copyright 2026 Ali Sasanian
2
+ # SPDX-License-Identifier: LicenseRef-PolyForm-Strict-1.0.0
3
+ """Which database a container keeps its state in, where it keeps its blobs, and its home's binding
4
+ to both (storage.md §3.7, §4).
5
+
6
+ `EGZOS_DATABASE_URL` names a postgres database, whose schema `egzos` holds the container's state;
7
+ unset, the state stays in the home's own `egzos.db`, as before. A home made on a named database
8
+ keeps `binding.json` beside its keys: the hash of the chain's first entry, and the `seq` and hash
9
+ of the newest entry it has seen, none of them secret. Every open checks the two before anything
10
+ serves, and stops with `HomeBindingError`. The connection string is the host's secret: it is read
11
+ from the environment where it is used and kept in no local, attribute, file or message, and a
12
+ driver's error, which can echo it, is never chained to the one raised.
13
+
14
+ The six `EGZOS_BLOBS_S3_*` variables name an object store beside a named database; none set, blobs
15
+ stay in the home's `blobs/`. The binding records the blob root, `"home"` or the store's endpoint,
16
+ bucket and prefix, and every open stops when the root named differs. The store's two keys are read
17
+ from the environment only where the store is built, and handed to OpenDAL.
18
+
19
+ The first entry's hash is no secret, and it binds because no other database can reproduce it: an
20
+ entry's hash covers its whole body, its `ts`, actor and details included (events.md §2-§3), not a
21
+ label, so an empty database, or another container's, never matches it. Narrowing what the first
22
+ entry carries would weaken the binding (a6 on #334)."""
23
+
24
+ from __future__ import annotations
25
+
26
+ import contextlib
27
+ import json
28
+ import os
29
+ import secrets
30
+ import sqlite3
31
+ from pathlib import Path
32
+ from typing import Any
33
+ from urllib.parse import urlsplit
34
+
35
+ from egzos.backends import SqliteBackend
36
+ from egzos.store.blobs import BlobStore
37
+
38
+ DATABASE_URL = "EGZOS_DATABASE_URL"
39
+ #: The object store's six variables (§3.7): the first four name it, the last two are its keys.
40
+ BLOBS_S3 = ("EGZOS_BLOBS_S3_ENDPOINT", "EGZOS_BLOBS_S3_REGION", "EGZOS_BLOBS_S3_BUCKET",
41
+ "EGZOS_BLOBS_S3_PREFIX", "EGZOS_BLOBS_S3_ACCESS_KEY_ID",
42
+ "EGZOS_BLOBS_S3_SECRET_ACCESS_KEY")
43
+ #: The blob root of a home whose blobs are its own `blobs/`; a binding that records none reads so.
44
+ HOME_BLOBS = "home"
45
+ #: The schema the operator applies the container's tables in (`backends.postgres.apply_schema`).
46
+ SCHEMA = "egzos"
47
+ BINDING_FILE = "binding.json"
48
+
49
+ _CASES = {
50
+ "unset": "this home is bound to a database, and EGZOS_DATABASE_URL is unset: it never falls "
51
+ "back to its own egzos.db",
52
+ "mismatch": "this home was made on another database than the one EGZOS_DATABASE_URL names "
53
+ "(its chain differs, or is empty)",
54
+ "unreachable": "the database EGZOS_DATABASE_URL names cannot be reached, or holds no egzos "
55
+ "schema this container may read: it never falls back to a local store",
56
+ "unbound": "the database EGZOS_DATABASE_URL names holds a chain, and this home holds no "
57
+ "binding to it, as a new or lost home would: its keys would be fresh",
58
+ "taken": "the database EGZOS_DATABASE_URL names already holds a chain: another home made its "
59
+ "container there",
60
+ "local": "this home's own egzos.db holds a chain, and EGZOS_DATABASE_URL is set: that chain, "
61
+ "its tokens and its counters would be left behind",
62
+ "restored": "the database EGZOS_DATABASE_URL names no longer holds the newest entry this home "
63
+ "has seen: it was restored to an earlier point without its home",
64
+ "driver": 'EGZOS_DATABASE_URL is set, and postgres support is not installed: pip install '
65
+ '"egzoscore[postgres]"',
66
+ "unreadable": "this home's binding.json, which binds it to the database EGZOS_DATABASE_URL "
67
+ "names, cannot be read",
68
+ "blobs-partial": "the EGZOS_BLOBS_S3_* variables name an object store all six or none, and "
69
+ "these are unset: ",
70
+ "blobs-alone": "the EGZOS_BLOBS_S3_* variables name an object store, and EGZOS_DATABASE_URL "
71
+ "is unset: an object store is named only beside a named database",
72
+ "blobs-userinfo": "EGZOS_BLOBS_S3_ENDPOINT holds userinfo: the object store's keys travel in "
73
+ "EGZOS_BLOBS_S3_ACCESS_KEY_ID and EGZOS_BLOBS_S3_SECRET_ACCESS_KEY only",
74
+ "blobs-moved": "the blob root the EGZOS_BLOBS_S3_* variables name (the home's blobs/ when they "
75
+ "are unset) differs from the one this home recorded: blobs never move to "
76
+ "another store, or back to the home, without the operator's rebind",
77
+ "blobs-driver": "the EGZOS_BLOBS_S3_* variables are set, and object store support is not "
78
+ 'installed: pip install "egzoscore[objects]"',
79
+ "blobs-endpoint": "EGZOS_BLOBS_S3_ENDPOINT is not an endpoint the object store can use: check "
80
+ "its scheme, host and port",
81
+ }
82
+
83
+
84
+ class HomeBindingError(RuntimeError):
85
+ """The container stops before anything serves (storage.md §3.7): its home and the database do
86
+ not belong together, or the database or the object store cannot be used. `case` names which;
87
+ the message names the variables, never a value."""
88
+
89
+ def __init__(self, case: str, unset: tuple[str, ...] = ()):
90
+ self.case = case
91
+ super().__init__(f"the container stops ({case}): {_CASES[case]}{', '.join(unset)}")
92
+
93
+
94
+ def _endpoint_fault(endpoint: str) -> str | None:
95
+ """The stop an endpoint calls for, or None. It fails closed: userinfo is found if either
96
+ reading of the authority holds an `@`, urllib's (a6 on #345) or the text after the first
97
+ `://` up to `/?#`, which also catches a scheme urllib does not recognise (a1r on #346); and an
98
+ endpoint urllib refuses, or reads with no host, stops as no endpoint. Never raises, so the
99
+ endpoint is in no frame a stop passes through."""
100
+ try:
101
+ parsed = urlsplit(endpoint if "://" in endpoint else "//" + endpoint)
102
+ host = parsed.hostname
103
+ except ValueError:
104
+ return "blobs-endpoint"
105
+ authority = endpoint.split("://", 1)[-1]
106
+ for end in "/?#":
107
+ authority = authority.split(end, 1)[0]
108
+ if "@" in parsed.netloc or "@" in authority:
109
+ return "blobs-userinfo"
110
+ return None if host else "blobs-endpoint"
111
+
112
+
113
+ def blob_root() -> str | dict[str, str]:
114
+ """The blob root the environment names (§3.7, §4): the home's `blobs/`, or the object store's
115
+ endpoint, bucket and prefix, none of them secret, spelled as OpenDAL roots them, so that one
116
+ root spelled twice is one root. Empty is unset, as for `EGZOS_DATABASE_URL`; a prefix of `/`
117
+ is the bucket's root. Stops when the six are set in part, beside no named database, or the
118
+ endpoint holds userinfo or is no endpoint, before any connection is made."""
119
+ unset = tuple(name for name in BLOBS_S3 if not os.environ.get(name))
120
+ if len(unset) == len(BLOBS_S3):
121
+ return HOME_BLOBS
122
+ if unset:
123
+ raise HomeBindingError("blobs-partial", unset)
124
+ if not os.environ.get(DATABASE_URL):
125
+ raise HomeBindingError("blobs-alone")
126
+ if (fault := _endpoint_fault(os.environ["EGZOS_BLOBS_S3_ENDPOINT"])) is not None:
127
+ raise HomeBindingError(fault)
128
+ return {"endpoint": os.environ["EGZOS_BLOBS_S3_ENDPOINT"].rstrip("/"),
129
+ "bucket": os.environ["EGZOS_BLOBS_S3_BUCKET"],
130
+ "prefix": os.environ["EGZOS_BLOBS_S3_PREFIX"].strip("/")}
131
+
132
+
133
+ def object_store(root: dict[str, str]) -> Any:
134
+ """An `ObjectBlobStore` at `root`, on an s3 operator as Supabase Storage needs one: the region
135
+ signs each request, addressing is path-style (OpenDAL's default), and nothing asks for
136
+ Content-MD5 or SSE, which it does not support. It does not honour If-None-Match either, so a
137
+ layer turns off the create-only write and `put` asks `exists` before it writes. The keys are
138
+ read from the environment here and handed to OpenDAL, kept in no attribute, file or message,
139
+ and OpenDAL reads no other credentials (no AWS config, no instance metadata). Building it does
140
+ no I/O. Stops when OpenDAL is not installed."""
141
+ try:
142
+ import opendal
143
+ from opendal.layers import CapabilityOverrideLayer
144
+ except ImportError:
145
+ opendal = None # type: ignore[assignment]
146
+ if opendal is None:
147
+ raise HomeBindingError("blobs-driver")
148
+ from egzos.store.objects import ObjectBlobStore
149
+
150
+ try:
151
+ op = opendal.Operator(
152
+ "s3", endpoint=root["endpoint"], bucket=root["bucket"], root=f"/{root['prefix']}",
153
+ region=os.environ["EGZOS_BLOBS_S3_REGION"],
154
+ access_key_id=os.environ["EGZOS_BLOBS_S3_ACCESS_KEY_ID"],
155
+ secret_access_key=os.environ["EGZOS_BLOBS_S3_SECRET_ACCESS_KEY"],
156
+ disable_config_load="true", disable_ec2_metadata="true")
157
+ except Exception: # noqa: BLE001 — OpenDAL's own text can carry the endpoint or a key
158
+ op = None
159
+ if op is None: # raised past the except block, so no OpenDAL error is chained (a1r on #345)
160
+ raise HomeBindingError("blobs-endpoint")
161
+ return ObjectBlobStore(op.layer(CapabilityOverrideLayer("write_with_if_not_exists=false")))
162
+
163
+
164
+ def _holds_chain(db: Path) -> bool:
165
+ """Whether the home's own `egzos.db` holds a chain, read without writing it. One that cannot
166
+ be read is taken to hold one: the container stops rather than leave a chain behind."""
167
+ if not db.exists():
168
+ return False
169
+ try:
170
+ con = sqlite3.connect(f"{db.resolve().as_uri()}?mode=ro", uri=True)
171
+ try:
172
+ table = con.execute("SELECT 1 FROM sqlite_master WHERE name = 'audit'").fetchone()
173
+ return bool(table) and con.execute("SELECT 1 FROM audit LIMIT 1").fetchone() is not None
174
+ finally:
175
+ con.close()
176
+ except sqlite3.Error:
177
+ return True
178
+
179
+
180
+ def _hash_at(backend: Any, seq: int) -> str | None:
181
+ """The hash of the entry at `seq`, read by its key: a binding is postgres's alone, and the
182
+ backend Protocol reads no single entry. The chain's first entry is `seq` 1."""
183
+ row = backend.db.execute("SELECT hash FROM audit WHERE seq = %s", (seq,)).fetchone()
184
+ return row[0] if row else None
185
+
186
+
187
+ class HomeBinding:
188
+ """A home's binding to the database its container keeps its state in, and to its blob root."""
189
+
190
+ def __init__(self, home: Path):
191
+ self.home = home
192
+ self.path = home / BINDING_FILE
193
+ self.local = home / "egzos.db"
194
+ # Empty is unset: an empty connection string would reach libpq's defaults, not a choice.
195
+ self.named = bool(os.environ.get(DATABASE_URL))
196
+ self.first: str | None = None # the first entry's hash, once the home is bound
197
+ self.blobs: str | dict[str, str] = HOME_BLOBS # the blob root named, as `open` read it
198
+ self._error: Any = () # the driver's error class, once it is imported
199
+
200
+ def open(self) -> tuple[Any, Any]:
201
+ """The container's backend and blob store, once every check passes. The object store's
202
+ own stops come first, and its store is built before any connection, since that does no
203
+ I/O; a home's `blobs/` is made only once the checks pass."""
204
+ self.blobs = blob_root()
205
+ objects = None if self.blobs == HOME_BLOBS else object_store(self.blobs)
206
+ backend = self._backend()
207
+ return backend, objects if objects is not None else BlobStore(self.home / "blobs")
208
+
209
+ def _backend(self) -> Any:
210
+ """The container's backend, once every check passes; the newest entry seen is rewritten."""
211
+ if not self.named:
212
+ if self.path.exists():
213
+ raise HomeBindingError("unset")
214
+ return SqliteBackend(self.local)
215
+ if _holds_chain(self.local):
216
+ raise HomeBindingError("local")
217
+ bound = self._read()
218
+ try:
219
+ import psycopg
220
+
221
+ from egzos.backends.postgres import PostgresBackend
222
+ except ImportError:
223
+ psycopg = None # type: ignore[assignment]
224
+ if psycopg is None:
225
+ raise HomeBindingError("driver")
226
+ self._error = psycopg.Error
227
+ backend, case = None, "unreachable"
228
+ try:
229
+ backend = PostgresBackend(os.environ[DATABASE_URL], SCHEMA)
230
+ case = self._check(backend, bound)
231
+ except psycopg.Error:
232
+ pass # its message can echo the connection string: raised below, unchained
233
+ finally:
234
+ if case and backend is not None:
235
+ backend.db.close()
236
+ if case:
237
+ raise HomeBindingError(case)
238
+ return backend
239
+
240
+ def _read(self) -> dict[str, Any] | None:
241
+ if not self.path.exists():
242
+ return None
243
+ try:
244
+ doc = json.loads(self.path.read_text())
245
+ if (isinstance(doc["first"], str) and type(doc["seen"]["seq"]) is int
246
+ and isinstance(doc["seen"]["hash"], str)):
247
+ return doc
248
+ except (OSError, ValueError, KeyError, TypeError):
249
+ pass
250
+ raise HomeBindingError("unreadable") # never read as absent: its keys would be fresh
251
+
252
+ def _check(self, backend: Any, bound: dict[str, Any] | None) -> str | None:
253
+ """Which stop applies, if any. None: a new home on an empty database, or a bound one."""
254
+ last = backend.audit_last()
255
+ if bound is None:
256
+ return "unbound" if last is not None else None
257
+ if last is None or _hash_at(backend, 1) != bound["first"]:
258
+ return "mismatch"
259
+ if bound.get("blobs", HOME_BLOBS) != self.blobs:
260
+ return "blobs-moved"
261
+ if _hash_at(backend, bound["seen"]["seq"]) != bound["seen"]["hash"]:
262
+ return "restored"
263
+ self._write(bound["first"], last)
264
+ return None
265
+
266
+ def making(self, backend: Any) -> bool:
267
+ """Inside the make's `atomic()` block (§3.6): whether it makes the container here. A home
268
+ with no binding whose block finds a chain already there stops: another home made it."""
269
+ if not self.named or self.path.exists():
270
+ return False
271
+ if backend.audit_last() is not None:
272
+ raise HomeBindingError("taken")
273
+ return True
274
+
275
+ def made(self, backend: Any) -> None:
276
+ """After the make's commit, its first entry and the newest seen. A crash before this
277
+ leaves a chain with no binding, which stops at the next open: unavailable, never unsafe."""
278
+ first, last = _hash_at(backend, 1), backend.audit_last()
279
+ if first is not None and last is not None:
280
+ self._write(first, last)
281
+
282
+ def record(self, backend: Any) -> None:
283
+ """At a clean close, the newest entry this home has seen. A database that can no longer be
284
+ read leaves the entry recorded before, which it still held."""
285
+ if self.first is None:
286
+ return
287
+ try:
288
+ last = backend.audit_last()
289
+ except self._error:
290
+ return
291
+ if last is not None:
292
+ self._write(self.first, last)
293
+
294
+ def _write(self, first: str, last: dict[str, Any]) -> None:
295
+ """Whole or not at all: written to a private file, then renamed over the binding."""
296
+ doc = json.dumps({"first": first, "seen": {"seq": last["seq"], "hash": last["hash"]},
297
+ "blobs": self.blobs})
298
+ tmp = self.path.with_name(f".{self.path.name}.{secrets.token_hex(8)}")
299
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
300
+ try:
301
+ with os.fdopen(fd, "w") as fh:
302
+ fh.write(doc)
303
+ fh.flush()
304
+ os.fsync(fh.fileno())
305
+ os.replace(tmp, self.path)
306
+ finally:
307
+ with contextlib.suppress(FileNotFoundError):
308
+ os.unlink(tmp)
309
+ self.first = first