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/store/items.py ADDED
@@ -0,0 +1,233 @@
1
+ # Copyright 2026 Ali Sasanian
2
+ # SPDX-License-Identifier: LicenseRef-PolyForm-Strict-1.0.0
3
+ """
4
+ The store: add, get, inbox. Every write lands UNVERIFIED (CLAUDE.md invariant 5; v0.3 §5) and is
5
+ auto-titled at write time. `add` with no scope → the inbox (v0.3 §4). `add ./file` → artifact:
6
+ metadata item + content-addressed blob. Pure capture (R11): every unaddressed add opens an
7
+ auto-created, auto-titled thread inside the inbox.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import mimetypes
13
+ from collections.abc import Callable
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ from egzos._ids import ulid
18
+ from egzos._types import CONTAINER_CONFIG_DEFAULTS, ContainerConfig, UploadRecord
19
+ from egzos.backends.base import Backend
20
+ from egzos.ledger import Ledger
21
+ from egzos.model import KINDS, ContextItem, Node, Token, now_iso
22
+ from egzos.store.autotitle import DegradedTitler, Titler
23
+ from egzos.store.blobs import BlobStore
24
+ from egzos.store.nodes import NodeService
25
+
26
+
27
+ class StoreError(Exception):
28
+ pass
29
+
30
+
31
+ class Store:
32
+ def __init__(
33
+ self,
34
+ backend: Backend,
35
+ ledger: Ledger,
36
+ nodes: NodeService,
37
+ blobs: BlobStore,
38
+ titler: Titler | None = None,
39
+ config: ContainerConfig | None = None,
40
+ ):
41
+ self.backend = backend
42
+ self.ledger = ledger
43
+ self.nodes = nodes
44
+ self.blobs = blobs
45
+ self.titler = titler or DegradedTitler()
46
+ # F5/F30 (#271): the container's `blobs_inline_max_bytes`, never a second constant.
47
+ # `config` may omit the key (absence tested by absence, per `_types.py`'s own loading
48
+ # rule) — `CONTAINER_CONFIG_DEFAULTS` is the fallback either way.
49
+ default_limit = CONTAINER_CONFIG_DEFAULTS["blobs_inline_max_bytes"]
50
+ self.inline_blob_limit = (
51
+ default_limit if config is None else config.get("blobs_inline_max_bytes", default_limit)
52
+ )
53
+ # coverage predicate, wired by the container once the trust engine exists
54
+ self.covers: Callable[[Token, Node], bool] | None = None
55
+ # the serving predicate search uses (`find.shown`), wired by the container likewise
56
+ self.shown: Callable[[Token, ContextItem, Node], bool] | None = None
57
+
58
+ # -- add ------------------------------------------------------------------------------
59
+ def add(
60
+ self,
61
+ *,
62
+ body: str | None = None,
63
+ file: Path | None = None,
64
+ upload: UploadRecord | None = None,
65
+ promote: bool = False,
66
+ kind: str | None = None,
67
+ scope: Node | None = None,
68
+ key: str | None = None,
69
+ tags: list[str] | None = None,
70
+ token: Token,
71
+ actor: str,
72
+ principal: str,
73
+ ) -> ContextItem:
74
+ if not token.has("remember"):
75
+ raise StoreError("token lacks `remember`")
76
+ if body is None and file is None and upload is None:
77
+ raise StoreError("nothing to add")
78
+ kind = kind or ("artifact" if file or upload else "memory")
79
+ if kind not in KINDS:
80
+ raise StoreError(f"unknown kind {kind!r}")
81
+
82
+ # Pure capture (R11): no scope → a fresh auto-titled thread inside the inbox.
83
+ opened_thread: Node | None = None
84
+ if scope is None:
85
+ inbox = self.nodes.inbox()
86
+ assert inbox is not None
87
+ opened_thread = Node(id=ulid(), type="thread", name="", parent=inbox.id)
88
+ scope = opened_thread
89
+
90
+ # remember is same-scope only (v0.3 §5): the token must cover where the write lands.
91
+ anchor = scope if opened_thread is None else self.nodes.inbox()
92
+ if self.covers is not None and anchor is not None and not self.covers(token, anchor):
93
+ raise StoreError("scope not found") # silence-not-errors
94
+
95
+ content: dict[str, Any] = {}
96
+ if file is not None:
97
+ data = Path(file).read_bytes()
98
+ sha = self.blobs.put(data)
99
+ mime = mimetypes.guess_type(str(file))[0] or "application/octet-stream"
100
+ content.update(sha256=sha, mime=mime, size=len(data), filename=Path(file).name)
101
+ if len(data) <= self.inline_blob_limit and mime.startswith("text/"):
102
+ content["inline"] = data.decode("utf-8", errors="replace")
103
+ self.ledger.append(
104
+ "blob.put",
105
+ actor=actor,
106
+ principal=principal,
107
+ subject=sha,
108
+ scope=scope.id,
109
+ size=len(data),
110
+ mime=mime,
111
+ )
112
+ title_body = content.get("inline")
113
+ elif upload is not None:
114
+ # rest.md §4.4 item 3: the bytes are staged already. A person's are promoted now; an
115
+ # agent's stay staged, unaddressable, until a person promotes the item (§4).
116
+ sha = upload["sha256"]
117
+ content.update(sha256=sha, mime=upload["mime"], size=upload["size"],
118
+ filename=upload["name"])
119
+ if promote and self.blobs.promote(sha):
120
+ self.ledger.append("blob.put", actor=actor, principal=principal, subject=sha,
121
+ scope=scope.id, size=upload["size"], mime=upload["mime"])
122
+ if upload["size"] <= self.inline_blob_limit and upload["mime"].startswith("text/"):
123
+ data = self.blobs.get(sha) or b""
124
+ content["inline"] = data.decode("utf-8", errors="replace")
125
+ elif promote and not self.blobs.exists(sha):
126
+ # storage.md §3.6: promoted nowhere and stored nowhere, so nothing was staged.
127
+ raise StoreError("nothing staged")
128
+ title_body = content.get("inline")
129
+ else:
130
+ content["body"] = body
131
+ title_body = body
132
+ content["auto_title"] = self.titler.title(
133
+ body=title_body, filename=content.get("filename"), mime=content.get("mime")
134
+ )
135
+ content["title_engine"] = self.titler.name
136
+
137
+ ts = now_iso()
138
+ item = ContextItem(
139
+ id=ulid(),
140
+ kind=kind,
141
+ scope=scope.id,
142
+ key=key,
143
+ content=content,
144
+ tags=tags or [],
145
+ provenance={
146
+ "actor": actor,
147
+ "principal": principal,
148
+ "client": token.client,
149
+ "derived_from": None,
150
+ "imported_from": None,
151
+ "approved_by": None,
152
+ },
153
+ trust={"status": "unverified"},
154
+ lifecycle={"created_at": ts, "updated_at": ts, "version": 1},
155
+ visibility={"ring": scope.type},
156
+ )
157
+ # One block: the thread, the item and their entries land together, or none of them, so a
158
+ # busy lock refuses before anything is written (storage.md §3.6; GHSA-2478-6jv5-83ff).
159
+ with self.backend.atomic():
160
+ if opened_thread is not None:
161
+ # A name is one path segment: a "/" in writer-supplied text would split it.
162
+ opened_thread.name = content["auto_title"][:40].replace("/", "-")
163
+ self.backend.put_node(opened_thread)
164
+ self.ledger.append(
165
+ "node.create",
166
+ actor=actor,
167
+ principal=principal,
168
+ subject=opened_thread.id,
169
+ scope=opened_thread.parent,
170
+ type="thread",
171
+ auto=True,
172
+ )
173
+ self.backend.put(item)
174
+ self.ledger.append(
175
+ "item.add",
176
+ actor=actor,
177
+ principal=principal,
178
+ subject=item.id,
179
+ scope=scope.id,
180
+ kind=kind,
181
+ status="unverified",
182
+ auto_title=content["auto_title"],
183
+ )
184
+ return item
185
+
186
+ # -- read -----------------------------------------------------------------------------
187
+ def get(self, item_id: str) -> ContextItem | None:
188
+ return self.backend.get(item_id)
189
+
190
+ def inbox_items(self) -> list[tuple[Node, ContextItem]]:
191
+ """Everything captured but not yet wrapped: items in the inbox's auto-threads."""
192
+ inbox = self.nodes.inbox()
193
+ if not inbox:
194
+ return []
195
+ out: list[tuple[Node, ContextItem]] = []
196
+ for thread in self.backend.list_nodes(parent=inbox.id):
197
+ for item in self.backend.query([thread.id]):
198
+ out.append((thread, item))
199
+ for item in self.backend.query([inbox.id]):
200
+ out.append((inbox, item))
201
+ return out
202
+
203
+ def blob_pull(
204
+ self, item: ContextItem, *, token: Token, actor: str, principal: str
205
+ ) -> bytes | None:
206
+ """Artifact download IS fetch (v0.3 §5): the same capability, coverage AND serving check
207
+ as a fetch, one silent None when any fails; the pull is its own audit event. Serving here
208
+ is search's own predicate, so bytes never leave by a path the item itself would not: a
209
+ quarantined or tombstoned item never, an unpromoted rule only to the curator (#135)."""
210
+ if not token.has("fetch"):
211
+ return None
212
+ node = self.backend.get_node(item.scope)
213
+ if node is None or self.covers is None or not self.covers(token, node):
214
+ return None
215
+ if item.status == "quarantined" or item.lifecycle.get("tombstoned"):
216
+ return None
217
+ if self.shown is None or not self.shown(token, item, node):
218
+ return None
219
+ sha = item.content.get("sha256")
220
+ if not sha:
221
+ return None
222
+ data = self.blobs.get(sha)
223
+ if data is not None:
224
+ self.ledger.append(
225
+ "blob.pull",
226
+ actor=actor,
227
+ principal=principal,
228
+ subject=item.id,
229
+ scope=item.scope,
230
+ sha256=sha,
231
+ size=len(data),
232
+ )
233
+ return data
egzos/store/nodes.py ADDED
@@ -0,0 +1,193 @@
1
+ # Copyright 2026 Ali Sasanian
2
+ # SPDX-License-Identifier: LicenseRef-PolyForm-Strict-1.0.0
3
+ """
4
+ Node model: ULIDs, parent pointers, computed paths, ring ranks, the inbox, the chain.
5
+
6
+ Hierarchy is wrapping added inside-out (v0.4 §2). Two roots exist from init: the personal tree
7
+ `user:self` (rooted at identity) and `global`. The inbox is the incoming bucket under the personal
8
+ root, audience zero. Resolution walks the ancestors that exist — bare thread → personal root →
9
+ global (v0.4 §2) — with the personal root slotted between org and global by default (R11).
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from collections.abc import Callable
15
+
16
+ from egzos._ids import ulid
17
+ from egzos.backends.base import Backend
18
+ from egzos.ledger import Ledger
19
+ from egzos.model import BASELINE_CREATE, CONTAINER_TYPES, RING_RANK, ROOT_TYPES, Node, Token
20
+
21
+
22
+ class StructureError(Exception):
23
+ pass
24
+
25
+
26
+ class AmbiguousRef(LookupError):
27
+ """A path tail that names more than one node the caller can see. `paths` lists only those
28
+ nodes, so the answer tells the caller nothing it could not already see."""
29
+
30
+ def __init__(self, paths: list[str]):
31
+ self.paths = paths
32
+ super().__init__("matches more than one scope: " + ", ".join(paths))
33
+
34
+
35
+ class NodeService:
36
+ def __init__(self, backend: Backend, ledger: Ledger):
37
+ self.backend = backend
38
+ self.ledger = ledger
39
+ # Trust's coverage check, wired by the container. Unwired, every token-scoped lookup
40
+ # fails closed: a node nobody can prove coverage of is a node nobody sees.
41
+ self.covers: Callable[[Token, Node], bool] | None = None
42
+
43
+ def visible(self, token: Token | None, node: Node) -> bool:
44
+ """Whether `token` may see `node`; `None` is the container itself (no principal)."""
45
+ if token is None:
46
+ return True
47
+ return self.covers is not None and self.covers(token, node)
48
+
49
+ # -- roots ---------------------------------------------------------------------------
50
+ def ensure_roots(self, *, actor: str, principal: str) -> dict[str, Node]:
51
+ roots: dict[str, Node] = {}
52
+ g = self.backend.find_root("global")
53
+ if not g:
54
+ g = Node(id=ulid(), type="global", name="global", parent=None)
55
+ self.backend.put_node(g)
56
+ self.ledger.append(
57
+ "node.create", actor=actor, principal=principal, subject=g.id, type="global"
58
+ )
59
+ u = self.backend.find_root("user")
60
+ if not u:
61
+ u = Node(id=ulid(), type="user", name="self", parent=None)
62
+ self.backend.put_node(u)
63
+ self.ledger.append(
64
+ "node.create", actor=actor, principal=principal, subject=u.id, type="user"
65
+ )
66
+ inbox = self.inbox(u)
67
+ if not inbox:
68
+ inbox = Node(id=ulid(), type="inbox", name="inbox", parent=u.id)
69
+ self.backend.put_node(inbox)
70
+ self.ledger.append(
71
+ "node.create", actor=actor, principal=principal, subject=inbox.id, type="inbox"
72
+ )
73
+ roots.update(global_=g, user=u, inbox=inbox)
74
+ return roots
75
+
76
+ def global_root(self) -> Node:
77
+ return self.backend.find_root("global") # type: ignore[return-value]
78
+
79
+ def user_root(self) -> Node:
80
+ return self.backend.find_root("user") # type: ignore[return-value]
81
+
82
+ def inbox(self, user_root: Node | None = None) -> Node | None:
83
+ u = user_root or self.user_root()
84
+ found = self.backend.list_nodes(parent=u.id, type="inbox")
85
+ return found[0] if found else None
86
+
87
+ # -- structure -----------------------------------------------------------------------
88
+ def create(
89
+ self, type: str, name: str, parent: Node, *, token: Token, actor: str, principal: str
90
+ ) -> Node:
91
+ if not self.visible(token, parent):
92
+ raise StructureError("scope not found") # the same answer as a parent that is absent
93
+ if type not in CONTAINER_TYPES or type in ("inbox", "global"):
94
+ raise StructureError(f"cannot create a container of type {type!r}")
95
+ if type == "uxo":
96
+ raise StructureError("uxo is undefined and is not instantiated until defined (R11)")
97
+ # Structure-creation is a permission (v0.3 §2): threads/projects baseline, the rest admin.
98
+ if type not in BASELINE_CREATE and not token.has("admin"):
99
+ raise StructureError(f"creating a {type} needs admin at the parent scope")
100
+ node = Node(id=ulid(), type=type, name=name, parent=parent.id)
101
+ with self.backend.atomic(): # the node and its entry, together (GHSA-2478-6jv5-83ff)
102
+ self.backend.put_node(node)
103
+ self.ledger.append(
104
+ "node.create",
105
+ actor=actor,
106
+ principal=principal,
107
+ subject=node.id,
108
+ scope=parent.id,
109
+ type=type,
110
+ name=name,
111
+ )
112
+ return node
113
+
114
+ def reparent(self, node: Node, new_parent: Node) -> None:
115
+ """Moving is a metadata update — zero bytes move (v0.4 §16)."""
116
+ node.parent = new_parent.id
117
+ self.backend.put_node(node)
118
+
119
+ # -- addressing ----------------------------------------------------------------------
120
+ def ancestors(self, node: Node) -> list[Node]:
121
+ """node itself first, then each parent up to a root."""
122
+ out = [node]
123
+ seen = {node.id}
124
+ cur = node
125
+ while cur.parent and cur.parent not in seen:
126
+ parent = self.backend.get_node(cur.parent)
127
+ if not parent:
128
+ break
129
+ out.append(parent)
130
+ seen.add(parent.id)
131
+ cur = parent
132
+ return out
133
+
134
+ def path(self, node: Node) -> str:
135
+ parts = []
136
+ for n in reversed(self.ancestors(node)):
137
+ parts.append(
138
+ n.type if n.type in ROOT_TYPES and n.type == "global" else f"{n.type}:{n.name}"
139
+ )
140
+ return "/".join(parts)
141
+
142
+ def ring_rank(self, node: Node) -> int | None:
143
+ return RING_RANK.get(node.type)
144
+
145
+ def chain(self, scope: Node, *, include_global: bool = True) -> list[Node]:
146
+ """The resolution chain, innermost first. Personal root rides along in every chain;
147
+ exo is a branch beside the org tree and never inherits inward (v0.4 §2), so an exo
148
+ ancestor ends the tree walk there before the personal root and global are appended."""
149
+ chain: list[Node] = []
150
+ for n in self.ancestors(scope):
151
+ chain.append(n)
152
+ if n.type == "exo":
153
+ break
154
+ user = self.user_root()
155
+ if user and all(n.id != user.id for n in chain):
156
+ chain.append(user)
157
+ if include_global:
158
+ g = self.global_root()
159
+ if g and all(n.id != g.id for n in chain):
160
+ chain.append(g)
161
+ return chain
162
+
163
+ def resolve_ref(self, ref: str, token: Token | None = None) -> Node | None:
164
+ """Accept a node id or a path like `project:health` / `user:self/project:health`. With a
165
+ token, only nodes it covers exist: an uncovered node answers exactly like an absent one,
166
+ and never makes a reference ambiguous. A tail that matches several visible nodes raises
167
+ AmbiguousRef instead of picking one."""
168
+ node = self.backend.get_node(ref)
169
+ if node:
170
+ return node if self.visible(token, node) else None
171
+ parts = ref.strip("/").split("/")
172
+ candidates = [
173
+ n
174
+ for n in self.backend.list_nodes()
175
+ if _matches_tail(self, n, parts) and self.visible(token, n)
176
+ ]
177
+ if len(candidates) == 1:
178
+ return candidates[0]
179
+ if len(candidates) > 1:
180
+ # Nothing is picked (the Chief's revision of freeze answer 1, 2026-10-03): any rule
181
+ # that picks — recency of creation or of activity — can be steered by whoever writes
182
+ # into one of the candidates. The caller names one: a longer path, or the id.
183
+ raise AmbiguousRef(sorted(self.path(n) for n in candidates))
184
+ return None
185
+
186
+
187
+ def _matches_tail(svc: NodeService, node: Node, parts: list[str]) -> bool:
188
+ anc = list(reversed(svc.ancestors(node)))
189
+ labels = [n.type if n.type == "global" else f"{n.type}:{n.name}" for n in anc]
190
+ if len(parts) > len(labels):
191
+ return False
192
+ tail = labels[-len(parts) :]
193
+ return all(p == lbl or p == lbl.split(":", 1)[-1] for p, lbl in zip(parts, tail, strict=True))
egzos/store/objects.py ADDED
@@ -0,0 +1,143 @@
1
+ # Copyright 2026 Ali Sasanian
2
+ # SPDX-License-Identifier: LicenseRef-PolyForm-Strict-1.0.0
3
+ """
4
+ Blob store on an object store, through OpenDAL (v0.7 §S): the directory store's surface and
5
+ refusals (storage.md §4) over a synchronous `opendal.Operator`, whose root is the blob root, with
6
+ `sha256/<hash>` and `staging/<hash>` under it. Using it needs `pip install "egzoscore[objects]"`;
7
+ importing this module does not.
8
+
9
+ What each method relies on is read from `capability()`, never assumed:
10
+ - `promote` copies where the service can (an S3-style store: one server-side copy, whole or not
11
+ at all), else reads and writes (memory, a test fake, cannot), and never renames, so a block that
12
+ rolls back keeps the staged copy. Its delete, as `discard`'s, waits for the act's COMMIT
13
+ (`defer`, §3.6); a crash before it leaves a staged copy a retried `promote` or the next open's
14
+ sweep removes (§4).
15
+ - A blob is written as whole bytes in one `write`, never through `open(..., "wb")`, whose exit
16
+ commits what was written so far. On a directory, an `fs_operator` writes to a temporary name on
17
+ the root's own filesystem and renames it into place, so no blob is ever seen part-written.
18
+ - `put` dedups by a create-only write where the service reports one, else asks `exists` first;
19
+ an operator layered with `CapabilityOverrideLayer("write_with_if_not_exists=false")` takes the
20
+ second way. `discard` asks `exists` first: `delete` is silent on a missing key.
21
+ - `get` re-hashes what it read, so a store can lose bytes but never substitute them; `promote`
22
+ does not yet (§4, a1p), as that would read every staged object before moving it.
23
+
24
+ Like the directory store it issues nothing: a URL is `grant_url`'s rendering of Trust's grant.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import contextlib
30
+ from collections.abc import Callable
31
+ from pathlib import Path
32
+ from typing import TYPE_CHECKING, Any
33
+
34
+ from egzos.store.blobs import GRANT_QUERY, BlobStore, _check, _is_digest, grant_url
35
+
36
+ if TYPE_CHECKING:
37
+ import opendal
38
+
39
+ __all__ = ["GRANT_QUERY", "ObjectBlobStore", "fs_operator", "grant_url"]
40
+
41
+
42
+ def _opendal() -> Any:
43
+ """OpenDAL, or an ImportError that names the extra installing it."""
44
+ try:
45
+ import opendal
46
+ except ImportError as e:
47
+ raise ImportError('an object store needs OpenDAL: pip install "egzoscore[objects]"') from e
48
+ return opendal
49
+
50
+
51
+ def fs_operator(root: Path) -> opendal.Operator:
52
+ """A directory as an object store. Each write goes to a temporary name in `<root>/.tmp`, so on
53
+ the root's own filesystem, and is renamed into place: without it a write lands in place, and a
54
+ failed one leaves a truncated blob. A failed write may leave its temporary file behind."""
55
+ root = Path(root).absolute()
56
+ return _opendal().Operator("fs", root=str(root), atomic_write_dir=str(root / ".tmp"))
57
+
58
+
59
+ class ObjectBlobStore:
60
+ """`BlobStore` (storage.md §4) on an opendal `Operator`, whose root is the blob root."""
61
+
62
+ digest = staticmethod(BlobStore.digest) # one definition of a content address
63
+
64
+ def __init__(self, op: opendal.Operator):
65
+ opendal = _opendal()
66
+ if not isinstance(op, opendal.Operator): # an AsyncOperator answers with coroutines
67
+ raise TypeError("ObjectBlobStore takes a synchronous opendal.Operator")
68
+ self.op = op
69
+ self._missing = opendal.exceptions.NotFound
70
+ self._taken = opendal.exceptions.ConditionNotMatch
71
+ can = op.capability()
72
+ self.create_only = bool(can.write_with_if_not_exists)
73
+ self.promotes_by = "copy+delete" if can.copy else "read+write+delete"
74
+ self.defer: Callable[[str], object] = self._unstage # as the directory store's
75
+
76
+ def put(self, data: bytes) -> str:
77
+ sha = self.digest(data)
78
+ key = f"sha256/{sha}"
79
+ if self.create_only:
80
+ with contextlib.suppress(self._taken): # already there: dedup by construction
81
+ self.op.write(key, data, if_not_exists=True)
82
+ elif not self.op.exists(key):
83
+ self.op.write(key, data)
84
+ return sha
85
+
86
+ def stage(self, data: bytes) -> str:
87
+ sha = self.digest(data)
88
+ self.op.write(f"staging/{sha}", data) # never deduped against promoted bytes [0.3 · 41]
89
+ return sha
90
+
91
+ def promote(self, sha: str) -> bool:
92
+ """The directory store's `promote` ([0.3 · 43]), decided by the staged bytes alone: any
93
+ promoted copy is replaced, and `False` means nothing was staged at that address."""
94
+ _check(sha)
95
+ src, dst = f"staging/{sha}", f"sha256/{sha}"
96
+ if self.promotes_by == "read+write+delete":
97
+ try:
98
+ data = self.op.read(src)
99
+ except self._missing:
100
+ return False
101
+ self.op.write(dst, data)
102
+ elif not self.op.exists(src):
103
+ return False
104
+ else:
105
+ self.op.copy(src, dst)
106
+ self.defer(sha) # after the COMMIT, a re-check, then the delete
107
+ return True
108
+
109
+ def get(self, sha: str) -> bytes | None:
110
+ if not _is_digest(sha):
111
+ return None # never a key built from a value that is not a digest
112
+ try:
113
+ data = self.op.read(f"sha256/{sha}")
114
+ except self._missing:
115
+ return None
116
+ return data if self.digest(data) == sha else None # lost, never substituted (§4)
117
+
118
+ def exists(self, sha: str) -> bool:
119
+ return _is_digest(sha) and self.op.exists(f"sha256/{sha}")
120
+
121
+ def discard(self, sha: str) -> bool:
122
+ """Delete STAGED bytes, never promoted ones ([0.3 · 44]); True if there were any. The
123
+ delete waits for the act's COMMIT (`defer`)."""
124
+ _check(sha)
125
+ if not self.op.exists(f"staging/{sha}"):
126
+ return False
127
+ self.defer(sha)
128
+ return True
129
+
130
+ def _unstage(self, sha: str) -> bool:
131
+ """Delete the bytes staged at `sha` now, True if there were any: what `defer` runs."""
132
+ _check(sha)
133
+ key = f"staging/{sha}"
134
+ if not self.op.exists(key):
135
+ return False
136
+ self.op.delete(key)
137
+ return True
138
+
139
+ def _staged_names(self) -> list[str]:
140
+ """Every address staged here, for the open-time sweep alone (storage.md §4): the store's
141
+ own listing, no `BlobStore` method and no reader's."""
142
+ names = (entry.path.rpartition("/")[2] for entry in self.op.list("staging/"))
143
+ return sorted(name for name in names if _is_digest(name))