glosslayer 0.1.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.
- glosslayer/__init__.py +100 -0
- glosslayer/actors.py +152 -0
- glosslayer/ai.py +126 -0
- glosslayer/catalogs/__init__.py +1 -0
- glosslayer/catalogs/file.py +87 -0
- glosslayer/checks.py +512 -0
- glosslayer/cli.py +560 -0
- glosslayer/client.py +417 -0
- glosslayer/dtypes.py +237 -0
- glosslayer/ids.py +203 -0
- glosslayer/ledger.py +1654 -0
- glosslayer/mcp_server.py +108 -0
- glosslayer/model.py +589 -0
- glosslayer/modeling.py +602 -0
- glosslayer/ossie/__init__.py +13 -0
- glosslayer/ossie/exporter.py +322 -0
- glosslayer/ossie/importer.py +179 -0
- glosslayer/ossie/ossie-schema.json +398 -0
- glosslayer/plugins.py +108 -0
- glosslayer/policy.py +375 -0
- glosslayer/references.py +52 -0
- glosslayer/schema.py +162 -0
- glosslayer/seams.py +147 -0
- glosslayer/search_index.py +218 -0
- glosslayer/semantic.py +75 -0
- glosslayer/server.py +690 -0
- glosslayer/sinks.py +56 -0
- glosslayer/store/__init__.py +8 -0
- glosslayer/store/base.py +50 -0
- glosslayer/store/sql.py +918 -0
- glosslayer/sync.py +381 -0
- glosslayer/types.py +34 -0
- glosslayer/visibility.py +85 -0
- glosslayer/viz.py +110 -0
- glosslayer-0.1.0.dist-info/METADATA +1101 -0
- glosslayer-0.1.0.dist-info/RECORD +40 -0
- glosslayer-0.1.0.dist-info/WHEEL +4 -0
- glosslayer-0.1.0.dist-info/entry_points.txt +13 -0
- glosslayer-0.1.0.dist-info/licenses/LICENSE +201 -0
- glosslayer-0.1.0.dist-info/licenses/NOTICE +12 -0
glosslayer/client.py
ADDED
|
@@ -0,0 +1,417 @@
|
|
|
1
|
+
"""A client for a Gloss ledger served over REST, and a way to use two ledgers as one.
|
|
2
|
+
|
|
3
|
+
remote = glosslayer.client.Client("https://hub.example/semantic", headers={"Authorization": "Bearer …"})
|
|
4
|
+
remote.search("revenue")
|
|
5
|
+
remote.propose("field:main.sales.orders/amount", "description", "Order value incl. VAT")
|
|
6
|
+
|
|
7
|
+
``Client`` mirrors the reading and proposing half of :class:`glosslayer.Gloss` against the routes of
|
|
8
|
+
:mod:`glosslayer.server`. Who you are is decided by the server from your credentials, so no call takes
|
|
9
|
+
an actor.
|
|
10
|
+
|
|
11
|
+
``Federation`` presents several ledgers as one, each owning a path prefix: an application's own
|
|
12
|
+
ledger for local tables next to an organisation's ledger for shared ones.
|
|
13
|
+
|
|
14
|
+
both = Federation({"main.": remote}, default=local.as_actor(Human("me")))
|
|
15
|
+
both.pending() # from both
|
|
16
|
+
both.current("dataset:main.sales.orders") # from the remote, by its key
|
|
17
|
+
|
|
18
|
+
Only the standard library is needed. Pass ``send`` to use another HTTP stack (or a test client).
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import json
|
|
24
|
+
import urllib.error
|
|
25
|
+
import urllib.parse
|
|
26
|
+
import urllib.request
|
|
27
|
+
from collections.abc import Callable, Iterable, Mapping, Sequence
|
|
28
|
+
from typing import Any
|
|
29
|
+
|
|
30
|
+
from .ids import SubjectId, path_covers
|
|
31
|
+
from .ledger import Proposal, ProposeResult
|
|
32
|
+
from .model import OPEN_STATUSES, Assertion, Event, InvalidTransition
|
|
33
|
+
from .policy import PermissionDenied
|
|
34
|
+
|
|
35
|
+
Send = Callable[[str, str, Mapping[str, Any] | None, Any], tuple[int, Any]]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class RemoteError(RuntimeError):
|
|
39
|
+
"""An error answer from the server that has no local exception; carries its ``status`` and ``detail``."""
|
|
40
|
+
|
|
41
|
+
def __init__(self, status: int, detail: Any):
|
|
42
|
+
super().__init__(f"Gloss server answered {status}: {detail}")
|
|
43
|
+
self.status, self.detail = status, detail
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _urllib_send(base: str, headers: Mapping[str, str], timeout: float) -> Send:
|
|
47
|
+
def send(method: str, path: str, params: Mapping[str, Any] | None, body: Any) -> tuple[int, Any]:
|
|
48
|
+
url = base + path
|
|
49
|
+
if params:
|
|
50
|
+
url += "?" + urllib.parse.urlencode(params, doseq=True)
|
|
51
|
+
data = json.dumps(body).encode() if body is not None else None
|
|
52
|
+
req = urllib.request.Request(url, data=data, method=method) # noqa: S310 (the caller names the server)
|
|
53
|
+
req.add_header("Accept", "application/json")
|
|
54
|
+
if data is not None:
|
|
55
|
+
req.add_header("Content-Type", "application/json")
|
|
56
|
+
for k, v in headers.items():
|
|
57
|
+
req.add_header(k, v)
|
|
58
|
+
try:
|
|
59
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp: # noqa: S310
|
|
60
|
+
raw, status = resp.read(), resp.status
|
|
61
|
+
except urllib.error.HTTPError as exc:
|
|
62
|
+
raw, status = exc.read(), exc.code
|
|
63
|
+
text = raw.decode() if raw else ""
|
|
64
|
+
try:
|
|
65
|
+
return status, json.loads(text) if text else None
|
|
66
|
+
except json.JSONDecodeError:
|
|
67
|
+
return status, text
|
|
68
|
+
|
|
69
|
+
return send
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _clean(params: Mapping[str, Any]) -> dict[str, Any]:
|
|
73
|
+
out = {}
|
|
74
|
+
for k, v in params.items():
|
|
75
|
+
if v is None:
|
|
76
|
+
continue
|
|
77
|
+
if isinstance(v, (list, tuple, set, frozenset)):
|
|
78
|
+
v = [getattr(x, "value", x) for x in v]
|
|
79
|
+
out[k] = getattr(v, "value", v)
|
|
80
|
+
return out
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class Client:
|
|
84
|
+
"""A ledger served by :mod:`glosslayer.server`, used like an actor-bound ``Gloss`` view.
|
|
85
|
+
|
|
86
|
+
Error answers come back as the local exceptions: 403 as ``PermissionDenied``, 404 as ``KeyError``,
|
|
87
|
+
422 as ``InvalidTransition`` or ``ValueError``, anything else (409 included) as ``RemoteError``.
|
|
88
|
+
"""
|
|
89
|
+
|
|
90
|
+
def __init__(self, base_url: str = "", *, headers: Mapping[str, str] | None = None,
|
|
91
|
+
send: Send | None = None, timeout: float = 30.0):
|
|
92
|
+
self.base_url = base_url.rstrip("/")
|
|
93
|
+
self._send = send or _urllib_send(self.base_url, dict(headers or {}), timeout)
|
|
94
|
+
|
|
95
|
+
def _call(self, method: str, path: str, params: Mapping[str, Any] | None = None, body: Any = None) -> Any:
|
|
96
|
+
status, data = self._send(method, path, _clean(params or {}) or None, body)
|
|
97
|
+
if status < 400:
|
|
98
|
+
return data
|
|
99
|
+
detail = data.get("detail") if isinstance(data, dict) else data
|
|
100
|
+
if status == 403:
|
|
101
|
+
raise PermissionDenied(detail)
|
|
102
|
+
if status == 404:
|
|
103
|
+
raise KeyError(detail)
|
|
104
|
+
if status == 422 and isinstance(detail, str):
|
|
105
|
+
raise InvalidTransition(detail) if detail.startswith("Cannot ") else ValueError(detail)
|
|
106
|
+
raise RemoteError(status, detail)
|
|
107
|
+
|
|
108
|
+
@staticmethod
|
|
109
|
+
def _subject(subject: str | SubjectId) -> str:
|
|
110
|
+
return urllib.parse.quote(str(SubjectId.parse(subject)), safe="/:")
|
|
111
|
+
|
|
112
|
+
# -- reads ------------------------------------------------------------------
|
|
113
|
+
def find(self, **criteria: Any) -> list[Assertion]:
|
|
114
|
+
"""One page of assertions matching ``criteria`` (``GET /assertions``; 200 unless ``limit`` says)."""
|
|
115
|
+
params = dict(criteria)
|
|
116
|
+
if "statuses" in params:
|
|
117
|
+
params["status"] = params.pop("statuses")
|
|
118
|
+
return [Assertion.from_dict(a) for a in self._call("GET", "/assertions", params)["items"]]
|
|
119
|
+
|
|
120
|
+
def count(self, **criteria: Any) -> int:
|
|
121
|
+
"""How many assertions match ``criteria``: the ``total`` of ``GET /assertions``."""
|
|
122
|
+
params = {**criteria, "limit": 1}
|
|
123
|
+
if "statuses" in params:
|
|
124
|
+
params["status"] = params.pop("statuses")
|
|
125
|
+
return self._call("GET", "/assertions", params)["total"]
|
|
126
|
+
|
|
127
|
+
def pending(self, **criteria: Any) -> list[Assertion]:
|
|
128
|
+
"""Open assertions (proposed, reviewed, stale) matching ``criteria``; one page, like ``find``."""
|
|
129
|
+
criteria.setdefault("statuses", list(OPEN_STATUSES))
|
|
130
|
+
return self.find(**criteria)
|
|
131
|
+
|
|
132
|
+
def get(self, assertion_id: str) -> Assertion:
|
|
133
|
+
"""One assertion by id or unambiguous id prefix (``GET /assertions/{id}``)."""
|
|
134
|
+
return Assertion.from_dict(self._call("GET", f"/assertions/{assertion_id}"))
|
|
135
|
+
|
|
136
|
+
def current(self, subject: str | SubjectId) -> dict[str, Any]:
|
|
137
|
+
"""Accepted value per attribute for one subject (``GET /subjects/{subject}``)."""
|
|
138
|
+
return self._call("GET", f"/subjects/{self._subject(subject)}")["current"]
|
|
139
|
+
|
|
140
|
+
def version(self, subject: str | SubjectId) -> int | None:
|
|
141
|
+
"""Version of the subject's accepted definition, see ``Gloss.version`` (``GET /subjects/{s}``)."""
|
|
142
|
+
return self._call("GET", f"/subjects/{self._subject(subject)}")["version"]
|
|
143
|
+
|
|
144
|
+
def history(self, subject: str | SubjectId) -> list[Event]:
|
|
145
|
+
"""Every event of the facts now at ``subject`` (``GET /subjects/{subject}/history``)."""
|
|
146
|
+
return [Event.from_dict(e) for e in self._call("GET", f"/subjects/{self._subject(subject)}/history")]
|
|
147
|
+
|
|
148
|
+
def log(self, after_seq: int = 0, limit: int | None = None, *, correlation: str | None = None) -> list[Event]:
|
|
149
|
+
"""Events after ``after_seq`` in ``seq`` order (``GET /log``; 500 unless ``limit`` is given)."""
|
|
150
|
+
params = {"after_seq": after_seq, "limit": limit, "correlation": correlation}
|
|
151
|
+
return [Event.from_dict(e) for e in self._call("GET", "/log", params)]
|
|
152
|
+
|
|
153
|
+
def progress(self, dataset_prefix: str | None = None) -> dict[str, dict[str, int]]:
|
|
154
|
+
"""Review progress per dataset or namespace: ``{path: {status: count}}`` (``GET /progress``)."""
|
|
155
|
+
return self._call("GET", "/progress", {"dataset_prefix": dataset_prefix})
|
|
156
|
+
|
|
157
|
+
def search(self, text: str, *, kinds: Sequence[str] | None = None, dataset_prefix: str | None = None,
|
|
158
|
+
limit: int = 20, for_ai: bool | None = None) -> list[dict[str, Any]]:
|
|
159
|
+
"""Ranked search as the caller (``GET /search``).
|
|
160
|
+
|
|
161
|
+
``for_ai`` asks ``GET /ai/search`` instead, which ignores ``kinds`` and ``dataset_prefix``.
|
|
162
|
+
"""
|
|
163
|
+
path = "/ai/search" if for_ai else "/search"
|
|
164
|
+
params = {"q": text, "limit": limit} if for_ai else {
|
|
165
|
+
"q": text, "kind": kinds, "dataset_prefix": dataset_prefix, "limit": limit}
|
|
166
|
+
return [{k: v for k, v in hit.items() if v not in (None, False)} for hit in self._call("GET", path, params)]
|
|
167
|
+
|
|
168
|
+
def tables(self, prefix: str | None = None, *, include_pending: bool = False) -> list[dict[str, Any]]:
|
|
169
|
+
"""Tables as plain dicts (the server's ``TableOut``)."""
|
|
170
|
+
return self._call("GET", "/tables", {"prefix": prefix, "include_pending": include_pending})
|
|
171
|
+
|
|
172
|
+
def table(self, key: str, *, include_pending: bool = False) -> dict[str, Any]:
|
|
173
|
+
"""One table as a plain dict, the server's ``TableOut`` (``GET /tables/{key}``)."""
|
|
174
|
+
return self._call("GET", f"/tables/{urllib.parse.quote(key)}", {"include_pending": include_pending})
|
|
175
|
+
|
|
176
|
+
def relationships(self, table: str | None = None, *, include_pending: bool = False) -> list[dict[str, Any]]:
|
|
177
|
+
"""Relationships as dicts, optionally only those touching ``table`` (``GET /relationships``)."""
|
|
178
|
+
return self._call("GET", "/relationships", {"table": table, "include_pending": include_pending})
|
|
179
|
+
|
|
180
|
+
def metrics(self, table: str | None = None, *, include_pending: bool = False) -> list[dict[str, Any]]:
|
|
181
|
+
"""Metrics as dicts; with ``table`` only that table's (``GET /metrics``)."""
|
|
182
|
+
return self._call("GET", "/metrics", {"table": table, "include_pending": include_pending})
|
|
183
|
+
|
|
184
|
+
def semantic_types(self, *, include_pending: bool = False) -> list[dict[str, Any]]:
|
|
185
|
+
"""Semantic types as dicts, each with a ``used_by`` count (``GET /types``)."""
|
|
186
|
+
return self._call("GET", "/types", {"include_pending": include_pending})
|
|
187
|
+
|
|
188
|
+
def model_context(self, datasets: list[str] | None = None) -> dict[str, Any]:
|
|
189
|
+
"""The accepted model as compact JSON for an AI, within its visibility limit (``GET /ai/context``)."""
|
|
190
|
+
return self._call("GET", "/ai/context", {"dataset": datasets})
|
|
191
|
+
|
|
192
|
+
def to_yaml(self, *, name: str | None = None, include_pending: bool = False,
|
|
193
|
+
namespace: str | None = None) -> str:
|
|
194
|
+
"""The model as Ossie YAML text (``GET /export/ossie``)."""
|
|
195
|
+
return self._call("GET", "/export/ossie",
|
|
196
|
+
{"name": name, "include_pending": include_pending, "namespace": namespace})
|
|
197
|
+
|
|
198
|
+
# -- writes -----------------------------------------------------------------
|
|
199
|
+
def propose(self, subject: str | SubjectId, attribute: str, value: Any, *, source: str | None = None,
|
|
200
|
+
confidence: float | None = None, evidence: Sequence[dict[str, Any]] | None = None,
|
|
201
|
+
comment: str | None = None, accept: bool = False, group: str | None = None) -> Assertion:
|
|
202
|
+
"""Propose one fact (``POST /assertions``); ``accept=True`` asks to accept it at once."""
|
|
203
|
+
body = {"subject": str(subject), "attribute": attribute, "value": value, "source": source,
|
|
204
|
+
"confidence": confidence, "evidence": list(evidence or []), "comment": comment,
|
|
205
|
+
"accept": accept, "group": group}
|
|
206
|
+
return Assertion.from_dict(self._call("POST", "/assertions", body=body)["assertion"])
|
|
207
|
+
|
|
208
|
+
def propose_many(self, proposals: Iterable[Proposal], *, source: str | None = None, accept: bool = False,
|
|
209
|
+
comment: str | None = None) -> list[ProposeResult]:
|
|
210
|
+
"""Propose many facts in one request (``POST /proposals``), de-duplicated by the server."""
|
|
211
|
+
body = {
|
|
212
|
+
"proposals": [
|
|
213
|
+
{"subject": p.subject, "attribute": p.attribute, "value": p.value, "confidence": p.confidence,
|
|
214
|
+
"evidence": p.evidence, "comment": p.comment, "group": p.group}
|
|
215
|
+
for p in proposals
|
|
216
|
+
],
|
|
217
|
+
"source": source, "accept": accept, "comment": comment,
|
|
218
|
+
}
|
|
219
|
+
return [ProposeResult(Assertion.from_dict(r["assertion"]), r["outcome"], r["accepted"])
|
|
220
|
+
for r in self._call("POST", "/proposals", body=body)]
|
|
221
|
+
|
|
222
|
+
def _act(self, action: str, assertion_id: str, comment: str | None) -> Assertion:
|
|
223
|
+
return Assertion.from_dict(
|
|
224
|
+
self._call("POST", f"/assertions/{assertion_id}/{action}", body={"comment": comment})
|
|
225
|
+
)
|
|
226
|
+
|
|
227
|
+
def review(self, assertion_id: str, *, comment: str | None = None) -> Assertion:
|
|
228
|
+
"""Mark an assertion reviewed (``POST /assertions/{id}/review``)."""
|
|
229
|
+
return self._act("review", assertion_id, comment)
|
|
230
|
+
|
|
231
|
+
def accept(self, assertion_id: str, *, comment: str | None = None) -> Assertion:
|
|
232
|
+
"""Accept an assertion (``POST /assertions/{id}/accept``)."""
|
|
233
|
+
return self._act("accept", assertion_id, comment)
|
|
234
|
+
|
|
235
|
+
def reject(self, assertion_id: str, *, comment: str | None = None) -> Assertion:
|
|
236
|
+
"""Reject an assertion (``POST /assertions/{id}/reject``)."""
|
|
237
|
+
return self._act("reject", assertion_id, comment)
|
|
238
|
+
|
|
239
|
+
def retract(self, assertion_id: str, *, comment: str | None = None) -> Assertion:
|
|
240
|
+
"""Withdraw an assertion, accepted or not (``POST /assertions/{id}/retract``)."""
|
|
241
|
+
return self._act("retract", assertion_id, comment)
|
|
242
|
+
|
|
243
|
+
def reopen(self, assertion_id: str, *, comment: str | None = None) -> Assertion:
|
|
244
|
+
"""Send a rejected or reviewed assertion back to proposed (``POST /assertions/{id}/reopen``)."""
|
|
245
|
+
return self._act("reopen", assertion_id, comment)
|
|
246
|
+
|
|
247
|
+
def restore(self, assertion_id: str, *, comment: str | None = None) -> Assertion:
|
|
248
|
+
"""Put a superseded value back as the accepted one (``POST /assertions/{id}/restore``)."""
|
|
249
|
+
return self._act("restore", assertion_id, comment)
|
|
250
|
+
|
|
251
|
+
def transition_many(self, action: str, assertion_ids: Iterable[str], *, comment: str | None = None
|
|
252
|
+
) -> tuple[list[Assertion], list[tuple[str, str]]]:
|
|
253
|
+
"""Apply one action to many assertions (``POST /bulk/{action}``): ``(changed, [(id, error)])``."""
|
|
254
|
+
res = self._call("POST", f"/bulk/{action}", body={"ids": list(assertion_ids), "comment": comment})
|
|
255
|
+
return [Assertion.from_dict(a) for a in res["changed"]], [(e["id"], e["error"]) for e in res["errors"]]
|
|
256
|
+
|
|
257
|
+
def accept_group(self, group: str, *, comment: str | None = None) -> list[Assertion]:
|
|
258
|
+
"""Accept every open fact of one proposal group, all or nothing (``POST /groups/{group}/accept``)."""
|
|
259
|
+
return [Assertion.from_dict(a) for a in self._call("POST", f"/groups/{group}/accept",
|
|
260
|
+
body={"comment": comment})]
|
|
261
|
+
|
|
262
|
+
def reject_group(self, group: str, *, comment: str | None = None) -> list[Assertion]:
|
|
263
|
+
"""Reject every open fact of one proposal group, all or nothing (``POST /groups/{group}/reject``)."""
|
|
264
|
+
return [Assertion.from_dict(a) for a in self._call("POST", f"/groups/{group}/reject",
|
|
265
|
+
body={"comment": comment})]
|
|
266
|
+
|
|
267
|
+
def record_check_results(self, results: Iterable[Any], *, run_id: str | None = None) -> str:
|
|
268
|
+
"""Log a run of check results and return its run id (``POST /checks/results``)."""
|
|
269
|
+
body = {"results": [r.to_dict() for r in results], "run_id": run_id}
|
|
270
|
+
return self._call("POST", "/checks/results", body=body)["run_id"]
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
class Federation:
|
|
274
|
+
"""Several ledgers as one, each owning the subjects under its path prefix.
|
|
275
|
+
|
|
276
|
+
``ledgers`` maps a path prefix to a ledger: a ``Client`` or an actor-bound ``Gloss`` view.
|
|
277
|
+
``default`` takes everything no prefix covers, including ledger-wide subjects. Reads about
|
|
278
|
+
one subject go to its owner; listings ask every ledger and combine the answers; a write goes
|
|
279
|
+
to the owner of its subject. Assertion ids are looked for in each ledger in turn.
|
|
280
|
+
"""
|
|
281
|
+
|
|
282
|
+
def __init__(self, ledgers: Mapping[str, Any], *, default: Any = None):
|
|
283
|
+
self.ledgers = dict(sorted(ledgers.items(), key=lambda kv: -len(kv[0])))
|
|
284
|
+
self.default = default
|
|
285
|
+
|
|
286
|
+
def _all(self) -> list[Any]:
|
|
287
|
+
seen = list(dict.fromkeys(self.ledgers.values()))
|
|
288
|
+
return seen + ([self.default] if self.default is not None and self.default not in seen else [])
|
|
289
|
+
|
|
290
|
+
def owner(self, subject: str | SubjectId) -> Any:
|
|
291
|
+
"""The ledger whose longest prefix covers the subject's path, else ``default`` (or ``KeyError``)."""
|
|
292
|
+
path = SubjectId.parse(subject).scope_path
|
|
293
|
+
for prefix, ledger in self.ledgers.items():
|
|
294
|
+
if path is not None and path_covers(prefix, path):
|
|
295
|
+
return ledger
|
|
296
|
+
if self.default is None:
|
|
297
|
+
raise KeyError(f"No ledger owns {subject}")
|
|
298
|
+
return self.default
|
|
299
|
+
|
|
300
|
+
def _owner_of_key(self, key: str) -> Any:
|
|
301
|
+
return self.owner(SubjectId.for_dataset(key))
|
|
302
|
+
|
|
303
|
+
def _holding(self, assertion_id: str) -> Any:
|
|
304
|
+
for ledger in self._all():
|
|
305
|
+
try:
|
|
306
|
+
ledger.get(assertion_id)
|
|
307
|
+
return ledger
|
|
308
|
+
except KeyError:
|
|
309
|
+
continue
|
|
310
|
+
raise KeyError(f"No assertion {assertion_id!r}")
|
|
311
|
+
|
|
312
|
+
def _targets(self, criteria: Mapping[str, Any]) -> list[Any]:
|
|
313
|
+
if criteria.get("subject"):
|
|
314
|
+
return [self.owner(criteria["subject"])]
|
|
315
|
+
if criteria.get("dataset"):
|
|
316
|
+
return [self._owner_of_key(criteria["dataset"])]
|
|
317
|
+
return self._all()
|
|
318
|
+
|
|
319
|
+
# -- reads ------------------------------------------------------------------
|
|
320
|
+
def find(self, **criteria: Any) -> list[Assertion]:
|
|
321
|
+
"""Matching assertions from the owning ledger, or from all of them, sorted by subject."""
|
|
322
|
+
rows = [a for ledger in self._targets(criteria) for a in ledger.find(**criteria)]
|
|
323
|
+
return sorted(rows, key=lambda a: (a.subject, a.attribute, a.created_at))
|
|
324
|
+
|
|
325
|
+
def pending(self, **criteria: Any) -> list[Assertion]:
|
|
326
|
+
"""Open assertions (proposed, reviewed, stale) from the ledgers ``find`` would ask."""
|
|
327
|
+
criteria.setdefault("statuses", list(OPEN_STATUSES))
|
|
328
|
+
return self.find(**criteria)
|
|
329
|
+
|
|
330
|
+
def count(self, **criteria: Any) -> int:
|
|
331
|
+
"""The sum of ``count`` over the ledgers ``find`` would ask."""
|
|
332
|
+
return sum(ledger.count(**criteria) for ledger in self._targets(criteria))
|
|
333
|
+
|
|
334
|
+
def get(self, assertion_id: str) -> Assertion:
|
|
335
|
+
"""One assertion, from the first ledger that holds its id."""
|
|
336
|
+
return self._holding(assertion_id).get(assertion_id)
|
|
337
|
+
|
|
338
|
+
def current(self, subject: str | SubjectId) -> dict[str, Any]:
|
|
339
|
+
"""Accepted value per attribute for one subject, from its owner."""
|
|
340
|
+
return self.owner(subject).current(subject)
|
|
341
|
+
|
|
342
|
+
def version(self, subject: str | SubjectId) -> int | None:
|
|
343
|
+
"""Version of the subject's accepted definition, from its owner."""
|
|
344
|
+
return self.owner(subject).version(subject)
|
|
345
|
+
|
|
346
|
+
def history(self, subject: str | SubjectId) -> list[Event]:
|
|
347
|
+
"""Every event of the facts now at ``subject``, from its owner."""
|
|
348
|
+
return self.owner(subject).history(subject)
|
|
349
|
+
|
|
350
|
+
def progress(self, dataset_prefix: str | None = None) -> dict[str, dict[str, int]]:
|
|
351
|
+
"""Review progress from every ledger, merged and sorted by path."""
|
|
352
|
+
out: dict[str, dict[str, int]] = {}
|
|
353
|
+
for ledger in self._all():
|
|
354
|
+
out.update(ledger.progress(dataset_prefix))
|
|
355
|
+
return dict(sorted(out.items()))
|
|
356
|
+
|
|
357
|
+
def search(self, text: str, *, limit: int = 20, **options: Any) -> list[dict[str, Any]]:
|
|
358
|
+
"""Hits from every ledger, interleaved so each ledger's best come first."""
|
|
359
|
+
lists = [ledger.search(text, limit=limit, **options) for ledger in self._all()]
|
|
360
|
+
out: list[dict[str, Any]] = []
|
|
361
|
+
for i in range(max((len(x) for x in lists), default=0)):
|
|
362
|
+
out += [x[i] for x in lists if i < len(x)]
|
|
363
|
+
return out[:limit]
|
|
364
|
+
|
|
365
|
+
def table(self, key: str, **options: Any) -> Any:
|
|
366
|
+
"""One table, from the ledger that owns its key."""
|
|
367
|
+
return self._owner_of_key(key).table(key, **options)
|
|
368
|
+
|
|
369
|
+
def tables(self, prefix: str | None = None, **options: Any) -> list[Any]:
|
|
370
|
+
"""Tables from every ledger, one ledger after another."""
|
|
371
|
+
return [t for ledger in self._all() for t in ledger.tables(prefix, **options)]
|
|
372
|
+
|
|
373
|
+
# -- writes -----------------------------------------------------------------
|
|
374
|
+
def propose(self, subject: str | SubjectId, attribute: str, value: Any, **options: Any) -> Assertion:
|
|
375
|
+
"""Propose a fact to the ledger that owns its subject."""
|
|
376
|
+
return self.owner(subject).propose(subject, attribute, value, **options)
|
|
377
|
+
|
|
378
|
+
def propose_many(self, proposals: Iterable[Proposal], **options: Any) -> list[ProposeResult]:
|
|
379
|
+
"""Each proposal goes to the owner of its subject; results come back in the order given."""
|
|
380
|
+
items = list(proposals)
|
|
381
|
+
by_owner: dict[int, tuple[Any, list[int]]] = {}
|
|
382
|
+
for i, p in enumerate(items):
|
|
383
|
+
owner = self.owner(p.subject)
|
|
384
|
+
by_owner.setdefault(id(owner), (owner, []))[1].append(i)
|
|
385
|
+
out: list[ProposeResult | None] = [None] * len(items)
|
|
386
|
+
for owner, positions in by_owner.values():
|
|
387
|
+
for pos, res in zip(positions, owner.propose_many([items[i] for i in positions], **options),
|
|
388
|
+
strict=True):
|
|
389
|
+
out[pos] = res
|
|
390
|
+
return [r for r in out if r is not None]
|
|
391
|
+
|
|
392
|
+
def _act(self, action: str, assertion_id: str, **options: Any) -> Assertion:
|
|
393
|
+
return getattr(self._holding(assertion_id), action)(assertion_id, **options)
|
|
394
|
+
|
|
395
|
+
def review(self, assertion_id: str, **options: Any) -> Assertion:
|
|
396
|
+
"""Mark an assertion reviewed, in the ledger holding it."""
|
|
397
|
+
return self._act("review", assertion_id, **options)
|
|
398
|
+
|
|
399
|
+
def accept(self, assertion_id: str, **options: Any) -> Assertion:
|
|
400
|
+
"""Accept an assertion, in the ledger holding it."""
|
|
401
|
+
return self._act("accept", assertion_id, **options)
|
|
402
|
+
|
|
403
|
+
def reject(self, assertion_id: str, **options: Any) -> Assertion:
|
|
404
|
+
"""Reject an assertion, in the ledger holding it."""
|
|
405
|
+
return self._act("reject", assertion_id, **options)
|
|
406
|
+
|
|
407
|
+
def retract(self, assertion_id: str, **options: Any) -> Assertion:
|
|
408
|
+
"""Withdraw an assertion, in the ledger holding it."""
|
|
409
|
+
return self._act("retract", assertion_id, **options)
|
|
410
|
+
|
|
411
|
+
def reopen(self, assertion_id: str, **options: Any) -> Assertion:
|
|
412
|
+
"""Send an assertion back to proposed, in the ledger holding it."""
|
|
413
|
+
return self._act("reopen", assertion_id, **options)
|
|
414
|
+
|
|
415
|
+
def restore(self, assertion_id: str, **options: Any) -> Assertion:
|
|
416
|
+
"""Put a superseded value back as the accepted one, in the ledger holding it."""
|
|
417
|
+
return self._act("restore", assertion_id, **options)
|
glosslayer/dtypes.py
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
"""Precise column types.
|
|
2
|
+
|
|
3
|
+
from glosslayer import Column, Int, Decimal, String, DateTime
|
|
4
|
+
|
|
5
|
+
Column("return_id", Int(32))
|
|
6
|
+
Column("refund", Decimal(18, 2))
|
|
7
|
+
Column("reason", String(255))
|
|
8
|
+
Column("returned_at", DateTime(tz="UTC"))
|
|
9
|
+
|
|
10
|
+
Ossie's datatypes are logical (``Integer``, ``Decimal``, ``String`` …) and carry no
|
|
11
|
+
width or precision. A Gloss type maps to the Ossie datatype *and* keeps the precise
|
|
12
|
+
physical type as its own fact (``physical_type``, e.g. ``"Int32"``, ``"Decimal(18,2)"``),
|
|
13
|
+
which exports under ``nonportable_extensions`` and survives a round trip.
|
|
14
|
+
|
|
15
|
+
Bare classes work too: ``Column("id", Int)`` means "an integer, width unspecified".
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import re
|
|
21
|
+
from dataclasses import dataclass
|
|
22
|
+
from typing import ClassVar
|
|
23
|
+
|
|
24
|
+
from .types import to_ossie_datatype
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(frozen=True)
|
|
28
|
+
class DType:
|
|
29
|
+
"""Base of the precise column types: ``ossie`` is the Ossie datatype, ``physical`` the precise one."""
|
|
30
|
+
|
|
31
|
+
ossie_name: ClassVar[str] = "Opaque"
|
|
32
|
+
|
|
33
|
+
@property
|
|
34
|
+
def ossie(self) -> str:
|
|
35
|
+
"""The Ossie logical datatype."""
|
|
36
|
+
return self.ossie_name
|
|
37
|
+
|
|
38
|
+
@property
|
|
39
|
+
def physical(self) -> str | None:
|
|
40
|
+
"""Precise type string, or None when nothing beyond the Ossie type is known."""
|
|
41
|
+
return None
|
|
42
|
+
|
|
43
|
+
def __str__(self) -> str:
|
|
44
|
+
return self.physical or self.ossie
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass(frozen=True)
|
|
48
|
+
class Int(DType):
|
|
49
|
+
"""An integer, signed unless ``unsigned``; ``bits`` is 8, 16, 32, 64 or 128, or None for any width."""
|
|
50
|
+
|
|
51
|
+
bits: int | None = None
|
|
52
|
+
unsigned: bool = False
|
|
53
|
+
ossie_name: ClassVar[str] = "Integer"
|
|
54
|
+
|
|
55
|
+
def __post_init__(self) -> None:
|
|
56
|
+
if self.bits is not None and self.bits not in (8, 16, 32, 64, 128):
|
|
57
|
+
raise ValueError(f"Int bits must be 8, 16, 32, 64 or 128, not {self.bits}")
|
|
58
|
+
|
|
59
|
+
def __repr__(self) -> str:
|
|
60
|
+
name = "UInt" if self.unsigned else "Int"
|
|
61
|
+
return f"{name}({self.bits})" if self.bits else f"{name}()"
|
|
62
|
+
|
|
63
|
+
@property
|
|
64
|
+
def physical(self) -> str | None:
|
|
65
|
+
if self.bits is None:
|
|
66
|
+
return "UInt" if self.unsigned else None
|
|
67
|
+
return f"{'UInt' if self.unsigned else 'Int'}{self.bits}"
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@dataclass(frozen=True, repr=False)
|
|
71
|
+
class UInt(Int):
|
|
72
|
+
"""An unsigned integer; ``UInt()`` without a width still records that it is unsigned."""
|
|
73
|
+
|
|
74
|
+
unsigned: bool = True
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
@dataclass(frozen=True)
|
|
78
|
+
class Float(DType):
|
|
79
|
+
"""A floating-point number of 16, 32 or 64 ``bits``, or None for any width."""
|
|
80
|
+
|
|
81
|
+
bits: int | None = None
|
|
82
|
+
ossie_name: ClassVar[str] = "Float"
|
|
83
|
+
|
|
84
|
+
def __post_init__(self) -> None:
|
|
85
|
+
if self.bits is not None and self.bits not in (16, 32, 64):
|
|
86
|
+
raise ValueError(f"Float bits must be 16, 32 or 64, not {self.bits}")
|
|
87
|
+
|
|
88
|
+
def __repr__(self) -> str:
|
|
89
|
+
return f"Float({self.bits})" if self.bits else "Float()"
|
|
90
|
+
|
|
91
|
+
@property
|
|
92
|
+
def physical(self) -> str | None:
|
|
93
|
+
return f"Float{self.bits}" if self.bits else None
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
@dataclass(frozen=True)
|
|
97
|
+
class Decimal(DType):
|
|
98
|
+
"""A fixed-point number: ``precision`` of 1 to 76 digits, and a ``scale`` that needs a precision."""
|
|
99
|
+
|
|
100
|
+
precision: int | None = None
|
|
101
|
+
scale: int | None = None
|
|
102
|
+
ossie_name: ClassVar[str] = "Decimal"
|
|
103
|
+
|
|
104
|
+
def __post_init__(self) -> None:
|
|
105
|
+
if self.scale is not None and self.precision is None:
|
|
106
|
+
raise ValueError("Decimal scale needs a precision: Decimal(18, 2)")
|
|
107
|
+
if self.precision is not None and not 1 <= self.precision <= 76:
|
|
108
|
+
raise ValueError("Decimal precision must be between 1 and 76")
|
|
109
|
+
if self.scale is not None and not 0 <= self.scale <= self.precision: # type: ignore[operator]
|
|
110
|
+
raise ValueError("Decimal scale must be between 0 and the precision")
|
|
111
|
+
|
|
112
|
+
def __repr__(self) -> str:
|
|
113
|
+
args = [str(a) for a in (self.precision, self.scale) if a is not None]
|
|
114
|
+
return f"Decimal({', '.join(args)})"
|
|
115
|
+
|
|
116
|
+
@property
|
|
117
|
+
def physical(self) -> str | None:
|
|
118
|
+
if self.precision is None:
|
|
119
|
+
return None
|
|
120
|
+
return f"Decimal({self.precision},{self.scale})" if self.scale is not None else f"Decimal({self.precision})"
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
@dataclass(frozen=True)
|
|
124
|
+
class String(DType):
|
|
125
|
+
"""Text, with an optional maximum ``length``."""
|
|
126
|
+
|
|
127
|
+
length: int | None = None
|
|
128
|
+
ossie_name: ClassVar[str] = "String"
|
|
129
|
+
|
|
130
|
+
def __post_init__(self) -> None:
|
|
131
|
+
if self.length is not None and self.length < 1:
|
|
132
|
+
raise ValueError("String length must be positive")
|
|
133
|
+
|
|
134
|
+
def __repr__(self) -> str:
|
|
135
|
+
return f"String({self.length})" if self.length else "String()"
|
|
136
|
+
|
|
137
|
+
@property
|
|
138
|
+
def physical(self) -> str | None:
|
|
139
|
+
return f"String({self.length})" if self.length else None
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
@dataclass(frozen=True)
|
|
143
|
+
class Boolean(DType):
|
|
144
|
+
"""A true/false value."""
|
|
145
|
+
|
|
146
|
+
ossie_name: ClassVar[str] = "Boolean"
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
@dataclass(frozen=True)
|
|
150
|
+
class Date(DType):
|
|
151
|
+
"""A calendar date without a time."""
|
|
152
|
+
|
|
153
|
+
ossie_name: ClassVar[str] = "Date"
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
@dataclass(frozen=True)
|
|
157
|
+
class Time(DType):
|
|
158
|
+
"""A time of day without a date."""
|
|
159
|
+
|
|
160
|
+
ossie_name: ClassVar[str] = "Time"
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
_UNITS = ("s", "ms", "us", "ns")
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
@dataclass(frozen=True)
|
|
167
|
+
class DateTime(DType):
|
|
168
|
+
"""``DateTime()`` has no time zone; ``DateTime(tz="UTC")`` maps to Ossie ``DateTimeTz``."""
|
|
169
|
+
|
|
170
|
+
tz: str | bool | None = None # a zone name, or True for "has a zone, unspecified"
|
|
171
|
+
unit: str | None = None
|
|
172
|
+
|
|
173
|
+
def __post_init__(self) -> None:
|
|
174
|
+
if self.unit is not None and self.unit not in _UNITS:
|
|
175
|
+
raise ValueError(f"DateTime unit must be one of {_UNITS}")
|
|
176
|
+
|
|
177
|
+
def __repr__(self) -> str:
|
|
178
|
+
args = [f"tz={self.tz!r}" if self.tz is not None else "", f"unit={self.unit!r}" if self.unit else ""]
|
|
179
|
+
return f"DateTime({', '.join(a for a in args if a)})"
|
|
180
|
+
|
|
181
|
+
@property
|
|
182
|
+
def ossie(self) -> str:
|
|
183
|
+
return "DateTimeTz" if self.tz else "DateTime"
|
|
184
|
+
|
|
185
|
+
@property
|
|
186
|
+
def physical(self) -> str | None:
|
|
187
|
+
args = [a for a in (self.unit, f"tz={self.tz}" if isinstance(self.tz, str) else None) if a]
|
|
188
|
+
return f"DateTime({', '.join(args)})" if args else None
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
@dataclass(frozen=True)
|
|
192
|
+
class Opaque(DType):
|
|
193
|
+
"""A type outside Ossie's vocabulary, kept by name: ``Opaque("geometry")``."""
|
|
194
|
+
|
|
195
|
+
name: str = "Opaque"
|
|
196
|
+
|
|
197
|
+
@property
|
|
198
|
+
def physical(self) -> str | None:
|
|
199
|
+
return None if self.name == "Opaque" else self.name
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
ALL: tuple[type[DType], ...] = (Int, UInt, Float, Decimal, String, Boolean, Date, Time, DateTime, Opaque)
|
|
203
|
+
|
|
204
|
+
_PARSE = [
|
|
205
|
+
(re.compile(r"^(U?)Int(\d+)$"), lambda m: (UInt if m[1] else Int)(int(m[2]))),
|
|
206
|
+
(re.compile(r"^UInt$"), lambda m: UInt()),
|
|
207
|
+
(re.compile(r"^Float(\d+)$"), lambda m: Float(int(m[1]))),
|
|
208
|
+
(re.compile(r"^Decimal\((\d+)(?:,\s*(\d+))?\)$"), lambda m: Decimal(int(m[1]), int(m[2]) if m[2] else None)),
|
|
209
|
+
(re.compile(r"^String\((\d+)\)$"), lambda m: String(int(m[1]))),
|
|
210
|
+
(
|
|
211
|
+
re.compile(r"^DateTime\((?:(s|ms|us|ns))?(?:,\s*)?(?:tz=([^)]+))?\)$"),
|
|
212
|
+
lambda m: DateTime(tz=m[2], unit=m[1]),
|
|
213
|
+
),
|
|
214
|
+
]
|
|
215
|
+
|
|
216
|
+
_LOGICAL = {"Integer": Int, "Float": Float, "Decimal": Decimal, "String": String, "Boolean": Boolean,
|
|
217
|
+
"Date": Date, "Time": Time, "DateTime": DateTime, "Opaque": Opaque}
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def parse(physical: str | None, logical: str | None = None) -> DType | None:
|
|
221
|
+
"""Rebuild a DType from a stored physical type (Gloss format) and/or Ossie datatype."""
|
|
222
|
+
if physical:
|
|
223
|
+
for rx, make in _PARSE:
|
|
224
|
+
m = rx.match(physical)
|
|
225
|
+
if m:
|
|
226
|
+
return make(m)
|
|
227
|
+
mapped = to_ossie_datatype(physical)
|
|
228
|
+
if mapped and mapped != "Opaque" and (logical is None or mapped == logical):
|
|
229
|
+
return _from_logical(mapped)
|
|
230
|
+
return Opaque(physical)
|
|
231
|
+
return _from_logical(logical) if logical else None
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _from_logical(logical: str) -> DType:
|
|
235
|
+
if logical == "DateTimeTz":
|
|
236
|
+
return DateTime(tz=True)
|
|
237
|
+
return _LOGICAL[logical]()
|