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/__init__.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""Gloss: a catalog-agnostic semantic layer built on Apache Ossie.
|
|
2
|
+
|
|
3
|
+
import glosslayer
|
|
4
|
+
from glosslayer import Table, Column, Human, Int, String
|
|
5
|
+
|
|
6
|
+
g = glosslayer.open("sqlite:///gloss.db")
|
|
7
|
+
t = Table("shop.returns", primary_key=[Column("return_id", Int(32))])
|
|
8
|
+
t.add_columns(Column("reason", String(255)))
|
|
9
|
+
g.add(t, source=Human("alice"))
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from . import checks, dtypes, plugins, schema
|
|
13
|
+
from .actors import AI, Actor, ActorDirectory, Agent, Human, Import, Inferred, System
|
|
14
|
+
from .dtypes import Boolean, Date, DateTime, Decimal, DType, Float, Int, Opaque, String, Time, UInt
|
|
15
|
+
from .ids import Kind, SubjectId, subject
|
|
16
|
+
from .ledger import Gloss, ModelState, Proposal, ProposeResult, ReadRecord, RekeyResult, open
|
|
17
|
+
from .model import (
|
|
18
|
+
Assertion,
|
|
19
|
+
AttributeSpec,
|
|
20
|
+
Confidentiality,
|
|
21
|
+
Event,
|
|
22
|
+
EventType,
|
|
23
|
+
InvalidTransition,
|
|
24
|
+
Status,
|
|
25
|
+
register_attribute,
|
|
26
|
+
)
|
|
27
|
+
from .modeling import AddResult, Column, Metric, Relationship, SemanticType, Table
|
|
28
|
+
from .policy import Context, Decision, DefaultPolicy, PermissionDenied, Policy, RolePolicy, Scope
|
|
29
|
+
from .seams import AssetSchema, Catalog, Coverage, Sink, Source
|
|
30
|
+
from .semantic import TypeSuggester
|
|
31
|
+
from .store import ConcurrentWrite, Query, SQLStore, Store
|
|
32
|
+
|
|
33
|
+
__version__ = "0.1.0"
|
|
34
|
+
|
|
35
|
+
__all__ = [
|
|
36
|
+
"AI",
|
|
37
|
+
"Actor",
|
|
38
|
+
"ActorDirectory",
|
|
39
|
+
"AddResult",
|
|
40
|
+
"Agent",
|
|
41
|
+
"Assertion",
|
|
42
|
+
"AssetSchema",
|
|
43
|
+
"AttributeSpec",
|
|
44
|
+
"Boolean",
|
|
45
|
+
"Catalog",
|
|
46
|
+
"Column",
|
|
47
|
+
"ConcurrentWrite",
|
|
48
|
+
"Confidentiality",
|
|
49
|
+
"Context",
|
|
50
|
+
"Coverage",
|
|
51
|
+
"DType",
|
|
52
|
+
"Date",
|
|
53
|
+
"DateTime",
|
|
54
|
+
"Decimal",
|
|
55
|
+
"Decision",
|
|
56
|
+
"DefaultPolicy",
|
|
57
|
+
"Event",
|
|
58
|
+
"EventType",
|
|
59
|
+
"Float",
|
|
60
|
+
"Gloss",
|
|
61
|
+
"Human",
|
|
62
|
+
"Import",
|
|
63
|
+
"Inferred",
|
|
64
|
+
"Int",
|
|
65
|
+
"InvalidTransition",
|
|
66
|
+
"Kind",
|
|
67
|
+
"Metric",
|
|
68
|
+
"ModelState",
|
|
69
|
+
"Opaque",
|
|
70
|
+
"PermissionDenied",
|
|
71
|
+
"Policy",
|
|
72
|
+
"Proposal",
|
|
73
|
+
"ProposeResult",
|
|
74
|
+
"Query",
|
|
75
|
+
"ReadRecord",
|
|
76
|
+
"RekeyResult",
|
|
77
|
+
"Relationship",
|
|
78
|
+
"RolePolicy",
|
|
79
|
+
"SQLStore",
|
|
80
|
+
"Scope",
|
|
81
|
+
"SemanticType",
|
|
82
|
+
"Sink",
|
|
83
|
+
"Source",
|
|
84
|
+
"Status",
|
|
85
|
+
"Store",
|
|
86
|
+
"String",
|
|
87
|
+
"SubjectId",
|
|
88
|
+
"System",
|
|
89
|
+
"Table",
|
|
90
|
+
"Time",
|
|
91
|
+
"TypeSuggester",
|
|
92
|
+
"UInt",
|
|
93
|
+
"checks",
|
|
94
|
+
"dtypes",
|
|
95
|
+
"open",
|
|
96
|
+
"plugins",
|
|
97
|
+
"register_attribute",
|
|
98
|
+
"schema",
|
|
99
|
+
"subject",
|
|
100
|
+
]
|
glosslayer/actors.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
"""Typed actors: who stated or did something.
|
|
2
|
+
|
|
3
|
+
from glosslayer import Human, AI
|
|
4
|
+
|
|
5
|
+
g.add(table, source=Human("edward"))
|
|
6
|
+
g.accept(assertion_id, actor=Human("alice"))
|
|
7
|
+
g.propose(..., source=AI("claude"))
|
|
8
|
+
|
|
9
|
+
Actors are ``str`` subclasses (``Human("edward") == "human:edward"``), so they work
|
|
10
|
+
everywhere a plain actor string does: storage, policies, the REST API, logs.
|
|
11
|
+
|
|
12
|
+
The part after the kind is an *identifier*, not a display name. Actors are written
|
|
13
|
+
into the event log, which is never edited, so a host with accounts should pass an id
|
|
14
|
+
that never changes and means the same on every machine (``Human("7f3a9c…")``), and
|
|
15
|
+
resolve it to a name when showing it: see :class:`ActorDirectory`. A person who has
|
|
16
|
+
left then resolves to nobody, and the log names no one.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
from typing import ClassVar, Protocol, runtime_checkable
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class Actor(str):
|
|
25
|
+
"""Base of the typed actors: the string is ``"<kind>:<name>"`` and ``name`` is the id after the colon."""
|
|
26
|
+
|
|
27
|
+
kind: ClassVar[str] = ""
|
|
28
|
+
name: str
|
|
29
|
+
|
|
30
|
+
def __new__(cls, name: str) -> Actor:
|
|
31
|
+
if cls is Actor:
|
|
32
|
+
raise TypeError("Use a concrete actor (Human, AI, Import, ...) or Actor.parse('kind:name')")
|
|
33
|
+
if not isinstance(name, str) or not name.strip():
|
|
34
|
+
raise ValueError(f"{cls.__name__} needs a non-empty name")
|
|
35
|
+
prefix = f"{cls.kind}:"
|
|
36
|
+
if name.startswith(prefix): # Human("human:edward") is fine too
|
|
37
|
+
name = name[len(prefix) :]
|
|
38
|
+
obj = super().__new__(cls, prefix + name)
|
|
39
|
+
obj.name = name
|
|
40
|
+
return obj
|
|
41
|
+
|
|
42
|
+
def __getnewargs__(self) -> tuple[str]: # keeps copy/pickle from double-prefixing
|
|
43
|
+
return (self.name,)
|
|
44
|
+
|
|
45
|
+
def __repr__(self) -> str:
|
|
46
|
+
return f"{type(self).__name__}({self.name!r})"
|
|
47
|
+
|
|
48
|
+
@staticmethod
|
|
49
|
+
def parse(value: str) -> Actor:
|
|
50
|
+
"""``"human:edward"`` → ``Human("edward")``. Unknown kinds become :class:`Other`.
|
|
51
|
+
|
|
52
|
+
A string without a ``kind:`` prefix is refused: guessing that it is a person would hand
|
|
53
|
+
an unknown caller a person's rights.
|
|
54
|
+
"""
|
|
55
|
+
if isinstance(value, Actor):
|
|
56
|
+
return value
|
|
57
|
+
kind, name = split_actor(value)
|
|
58
|
+
cls = _KINDS.get(kind)
|
|
59
|
+
return cls(name) if cls else Other(value)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def split_actor(value: str) -> tuple[str, str]:
|
|
63
|
+
"""``"human:alice"`` → ``("human", "alice")``; raises ``ValueError`` for any other shape."""
|
|
64
|
+
if not isinstance(value, str):
|
|
65
|
+
raise ValueError(f"An actor is a string like 'human:alice', not {type(value).__name__}")
|
|
66
|
+
kind, sep, name = value.partition(":")
|
|
67
|
+
if not sep or not kind or not name.strip():
|
|
68
|
+
raise ValueError(f"Invalid actor {value!r}: expected '<kind>:<id>', e.g. 'human:alice' or 'ai:claude'")
|
|
69
|
+
return kind, name
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def actor_kind(value: str) -> str | None:
|
|
73
|
+
"""The kind of a well-formed actor string, or None when it has no ``kind:`` prefix."""
|
|
74
|
+
try:
|
|
75
|
+
return split_actor(value)[0]
|
|
76
|
+
except ValueError:
|
|
77
|
+
return None
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class Human(Actor):
|
|
81
|
+
"""A person. The default policy lets humans review and accept."""
|
|
82
|
+
|
|
83
|
+
kind = "human"
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class AI(Actor):
|
|
87
|
+
"""An AI model or agent. It can propose, but the default policy never lets it accept."""
|
|
88
|
+
|
|
89
|
+
kind = "ai"
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
Agent = AI
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class Import(Actor):
|
|
96
|
+
"""A file or tool the facts were imported from, e.g. ``Import("ossie")``, ``Import("dbt")``."""
|
|
97
|
+
|
|
98
|
+
kind = "import"
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class Catalog(Actor):
|
|
102
|
+
"""A catalog plugin acting during sync, e.g. ``Catalog("flowfile")``."""
|
|
103
|
+
|
|
104
|
+
kind = "catalog"
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class Inferred(Actor):
|
|
108
|
+
"""A rule that derived the fact, e.g. ``Inferred("flowfile-lineage")``."""
|
|
109
|
+
|
|
110
|
+
kind = "inferred"
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class System(Actor):
|
|
114
|
+
"""Gloss itself or an automation acting on its own authority."""
|
|
115
|
+
|
|
116
|
+
kind = "system"
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
class Other(Actor):
|
|
120
|
+
"""An actor string whose kind Gloss doesn't know; kept verbatim."""
|
|
121
|
+
|
|
122
|
+
kind = ""
|
|
123
|
+
|
|
124
|
+
def __new__(cls, value: str) -> Other:
|
|
125
|
+
obj = str.__new__(cls, value)
|
|
126
|
+
obj.name = value
|
|
127
|
+
return obj
|
|
128
|
+
|
|
129
|
+
def __getnewargs__(self) -> tuple[str]:
|
|
130
|
+
return (str(self),)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
_KINDS: dict[str, type[Actor]] = {
|
|
134
|
+
c.kind: c for c in (Human, AI, Import, Catalog, Inferred, System)
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
KNOWN_KINDS = frozenset(_KINDS)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
@runtime_checkable
|
|
141
|
+
class ActorDirectory(Protocol):
|
|
142
|
+
"""How a host turns actor ids into something to show. Gloss never stores the answer."""
|
|
143
|
+
|
|
144
|
+
def display_name(self, actor: str) -> str | None:
|
|
145
|
+
"""The name to show for ``actor``, or None when the host no longer knows them."""
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
class IdentityDirectory:
|
|
149
|
+
"""The default: the id is the name (fine for scripts, the CLI and single-user ledgers)."""
|
|
150
|
+
|
|
151
|
+
def display_name(self, actor: str) -> str | None:
|
|
152
|
+
return split_actor(actor)[1] if actor_kind(actor) else actor
|
glosslayer/ai.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"""AI-facing views of the model, with confidentiality enforced.
|
|
2
|
+
|
|
3
|
+
Everything AI tools read goes through here. Subjects whose confidentiality is
|
|
4
|
+
above the reader's level are shown by name only (so the AI knows they exist and
|
|
5
|
+
can say so) with descriptions, expressions and examples removed. Confidentiality
|
|
6
|
+
set on a dataset applies to all its fields unless a field states its own level.
|
|
7
|
+
|
|
8
|
+
Pass an actor-bound view (``g.as_actor(AI("claude"))``, or a person's view with
|
|
9
|
+
``via="ai:claude"``) and the policy's scope for that actor applies: which paths it
|
|
10
|
+
may read and up to which level. Pass an unbound ledger and the policy's default AI
|
|
11
|
+
level applies to everything in it. Each call reports what it handed out to the
|
|
12
|
+
ledger's read hook (``Gloss.on_read``).
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from typing import TYPE_CHECKING, Any
|
|
18
|
+
|
|
19
|
+
from .model import Confidentiality, Status, attribute, detail_attributes
|
|
20
|
+
|
|
21
|
+
if TYPE_CHECKING:
|
|
22
|
+
from .ledger import Entry, Gloss
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def ai_limit(gloss: Gloss) -> Confidentiality:
|
|
26
|
+
"""The confidentiality ceiling for what this handle may show an AI."""
|
|
27
|
+
if gloss.actor is not None:
|
|
28
|
+
return gloss.scope.max_confidentiality
|
|
29
|
+
return gloss.policy.scope("ai:anonymous", None).max_confidentiality
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _view(name: str, entry: Entry, extra: tuple[str, ...] = ()) -> dict[str, Any]:
|
|
33
|
+
out: dict[str, Any] = {"name": name}
|
|
34
|
+
if "datatype" in entry.attrs:
|
|
35
|
+
out["datatype"] = entry.attrs["datatype"]
|
|
36
|
+
if entry.redacted:
|
|
37
|
+
out["confidentiality"] = entry.redacted
|
|
38
|
+
out["redacted"] = True
|
|
39
|
+
return out
|
|
40
|
+
shown = detail_attributes() | set(extra)
|
|
41
|
+
for attr, value in entry.attrs.items():
|
|
42
|
+
if attr in shown and attr != "datatype":
|
|
43
|
+
out[attr] = value
|
|
44
|
+
level = entry.attrs.get("confidentiality")
|
|
45
|
+
if level and level != Confidentiality.INTERNAL.value:
|
|
46
|
+
out["confidentiality"] = level
|
|
47
|
+
return out
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def model_context(
|
|
51
|
+
gloss: Gloss,
|
|
52
|
+
*,
|
|
53
|
+
datasets: list[str] | None = None,
|
|
54
|
+
include_pending: bool = False,
|
|
55
|
+
) -> dict[str, Any]:
|
|
56
|
+
"""Accepted model as compact JSON for an LLM prompt or an MCP tool result."""
|
|
57
|
+
limit = ai_limit(gloss)
|
|
58
|
+
statuses = [Status.ACCEPTED] + ([Status.PROPOSED, Status.REVIEWED] if include_pending else [])
|
|
59
|
+
state = gloss.snapshot(statuses, datasets=datasets)
|
|
60
|
+
state.redact(limit)
|
|
61
|
+
wanted = set(datasets) if datasets else None
|
|
62
|
+
metric_extra = tuple(n for n in ("time_column", "dimensions", "format") if attribute(n))
|
|
63
|
+
|
|
64
|
+
out: dict[str, Any] = {"visibility_limit": limit.value, "datasets": [], "relationships": [], "metrics": []}
|
|
65
|
+
if state.model.attrs.get("description"):
|
|
66
|
+
out["model"] = {"description": state.model.attrs["description"]}
|
|
67
|
+
shown: list[str] = []
|
|
68
|
+
for key, d in sorted(state.datasets.items()):
|
|
69
|
+
if wanted is not None and key not in wanted:
|
|
70
|
+
continue
|
|
71
|
+
dv = _view(key, d, extra=("primary_key",))
|
|
72
|
+
shown.append(f"dataset:{key}")
|
|
73
|
+
if not d.redacted:
|
|
74
|
+
dv["fields"] = [_view(fn, f) for fn, f in d.fields.items()]
|
|
75
|
+
dv["metrics"] = [_view(mn, m, metric_extra) for mn, m in d.metrics.items()]
|
|
76
|
+
shown += [f"field:{key}/{fn}" for fn, f in d.fields.items() if not f.redacted]
|
|
77
|
+
out["datasets"].append(dv)
|
|
78
|
+
for ref, r in sorted(state.relationships.items()):
|
|
79
|
+
a = r.attrs
|
|
80
|
+
if wanted is not None and not ({a.get("from"), a.get("to")} & wanted):
|
|
81
|
+
continue
|
|
82
|
+
if r.redacted:
|
|
83
|
+
continue
|
|
84
|
+
out["relationships"].append({k: a[k] for k in ("from", "to", "from_columns", "to_columns") if k in a}
|
|
85
|
+
| {"name": ref})
|
|
86
|
+
shown.append(f"relationship:{ref}")
|
|
87
|
+
if wanted is None:
|
|
88
|
+
for ref, m in sorted(state.metrics.items()):
|
|
89
|
+
out["metrics"].append(_view(ref, m, metric_extra))
|
|
90
|
+
shown.append(f"metric:{ref}")
|
|
91
|
+
gloss.report_read("model_context", shown)
|
|
92
|
+
return out
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def subject_level(gloss: Gloss, subject: str) -> Confidentiality:
|
|
96
|
+
"""Effective confidentiality of a subject (own accepted level, else its type's or dataset's, else internal)."""
|
|
97
|
+
from .ids import SubjectId
|
|
98
|
+
from .visibility import levels
|
|
99
|
+
|
|
100
|
+
s = str(SubjectId.parse(subject))
|
|
101
|
+
return levels(gloss.store, [s])[s]
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def review_status(gloss: Gloss, subject: str) -> list[dict[str, Any]]:
|
|
105
|
+
"""Facts about one subject and their status, with values hidden above the reader's level."""
|
|
106
|
+
from .ids import SubjectId
|
|
107
|
+
|
|
108
|
+
sid = SubjectId.parse(subject)
|
|
109
|
+
visible = subject_level(gloss, str(sid)) <= ai_limit(gloss)
|
|
110
|
+
detail = detail_attributes()
|
|
111
|
+
out = []
|
|
112
|
+
for a in gloss.find(subject=str(sid)):
|
|
113
|
+
d: dict[str, Any] = {"attribute": a.attribute, "status": a.status.value, "source": a.source}
|
|
114
|
+
if not a.redacted and (visible or a.attribute not in detail):
|
|
115
|
+
d["value"] = a.value
|
|
116
|
+
out.append(d)
|
|
117
|
+
if out:
|
|
118
|
+
gloss.report_read("review_status", [str(sid)])
|
|
119
|
+
return out
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def search(gloss: Gloss, text: str, *, limit: int = 20, kinds: list[str] | None = None) -> list[dict[str, Any]]:
|
|
123
|
+
"""Indexed search over accepted knowledge, with the AI visibility limit applied (see Gloss.search)."""
|
|
124
|
+
hits = gloss.search(text, limit=limit, kinds=kinds, for_ai=True)
|
|
125
|
+
gloss.report_read("search", [h["subject"] for h in hits if not h.get("redacted")])
|
|
126
|
+
return hits
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Built-in catalogs: ``FileCatalog`` reads assets from a YAML file."""
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""Built-in catalog backed by a YAML file. Useful on its own, for tests, and as a reference plugin.
|
|
2
|
+
|
|
3
|
+
name: demo
|
|
4
|
+
assets:
|
|
5
|
+
sales.orders:
|
|
6
|
+
source: warehouse.sales.orders
|
|
7
|
+
description: One row per order
|
|
8
|
+
primary_key: [order_id]
|
|
9
|
+
columns:
|
|
10
|
+
- {name: order_id, dtype: Int64}
|
|
11
|
+
- {name: amount, dtype: "Decimal(18,2)"}
|
|
12
|
+
- {name: created_at, dtype: "Datetime(time_unit='us', time_zone='UTC')"}
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
import yaml
|
|
21
|
+
|
|
22
|
+
from ..seams import AssetSchema, Column, asset_fingerprint
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class FileCatalog:
|
|
26
|
+
"""A catalog read from one YAML file in the format above; ``name`` defaults to the file's ``name:``."""
|
|
27
|
+
|
|
28
|
+
def __init__(self, path: str | Path, name: str | None = None):
|
|
29
|
+
self.path = Path(path)
|
|
30
|
+
self._data = self._load()
|
|
31
|
+
self.name = name or self._data.get("name") or f"file:{self.path.stem}"
|
|
32
|
+
|
|
33
|
+
@classmethod
|
|
34
|
+
def from_spec(cls, arg: str, **kwargs: Any) -> FileCatalog:
|
|
35
|
+
"""``arg`` is the YAML file's path."""
|
|
36
|
+
return cls(arg, **kwargs)
|
|
37
|
+
|
|
38
|
+
def _load(self) -> dict[str, Any]:
|
|
39
|
+
data = yaml.safe_load(self.path.read_text()) or {}
|
|
40
|
+
if not isinstance(data.get("assets", {}), dict):
|
|
41
|
+
raise ValueError(f"{self.path}: 'assets' must be a mapping of dataset key -> definition")
|
|
42
|
+
return data
|
|
43
|
+
|
|
44
|
+
def reload(self) -> None:
|
|
45
|
+
"""Read the file again; the catalog keeps what it loaded until then."""
|
|
46
|
+
self._data = self._load()
|
|
47
|
+
|
|
48
|
+
def list_assets(self) -> list[str]:
|
|
49
|
+
"""The dataset keys under ``assets``, in file order."""
|
|
50
|
+
return list((self._data.get("assets") or {}).keys())
|
|
51
|
+
|
|
52
|
+
def describe(self, key: str) -> AssetSchema:
|
|
53
|
+
"""The asset as loaded; an ``id`` in its entry becomes the ``uid`` a sync uses to spot renames."""
|
|
54
|
+
spec = (self._data.get("assets") or {})[key] or {}
|
|
55
|
+
cols = [
|
|
56
|
+
Column(
|
|
57
|
+
name=c["name"],
|
|
58
|
+
dtype=str(c.get("dtype", "")),
|
|
59
|
+
nullable=c.get("nullable"),
|
|
60
|
+
description=c.get("description"),
|
|
61
|
+
)
|
|
62
|
+
for c in spec.get("columns", [])
|
|
63
|
+
]
|
|
64
|
+
return AssetSchema(
|
|
65
|
+
key=key,
|
|
66
|
+
columns=cols,
|
|
67
|
+
description=spec.get("description"),
|
|
68
|
+
source=spec.get("source"),
|
|
69
|
+
primary_key=spec.get("primary_key"),
|
|
70
|
+
uid=str(spec["id"]) if spec.get("id") is not None else None,
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
def fingerprint(self, key: str) -> str:
|
|
74
|
+
"""``asset_fingerprint`` of the described asset: columns, descriptions, primary key and source."""
|
|
75
|
+
return asset_fingerprint(self.describe(key))
|
|
76
|
+
|
|
77
|
+
def write_back(self, key: str, facts: dict[str, Any]) -> None:
|
|
78
|
+
"""Write accepted descriptions back into the YAML file."""
|
|
79
|
+
assets = self._data.setdefault("assets", {})
|
|
80
|
+
spec = assets.setdefault(key, {})
|
|
81
|
+
if "description" in facts:
|
|
82
|
+
spec["description"] = facts["description"]
|
|
83
|
+
for col in spec.get("columns", []):
|
|
84
|
+
f = (facts.get("fields") or {}).get(col["name"])
|
|
85
|
+
if f and "description" in f:
|
|
86
|
+
col["description"] = f["description"]
|
|
87
|
+
self.path.write_text(yaml.safe_dump(self._data, sort_keys=False, allow_unicode=True))
|