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/ids.py ADDED
@@ -0,0 +1,203 @@
1
+ """Stable, catalog-independent identifiers for the things semantic facts are about.
2
+
3
+ Every fact attaches to a *subject*. Subjects are plain strings so they can be
4
+ stored, logged and passed to AI tools without ceremony:
5
+
6
+ model: the semantic model as a whole
7
+ model:sales the model published from the ``sales`` namespace
8
+ dataset:sales.orders a dataset (table, view, query)
9
+ field:sales.orders/amount a field of a dataset
10
+ metric:sales.orders/avg_price a metric that belongs to one dataset
11
+ metric:sales::total_revenue a metric owned by the ``sales`` namespace
12
+ relationship:sales::orders_customers a relationship owned by the ``sales`` namespace
13
+ type:crm::email_address a semantic type owned by the ``crm`` namespace
14
+ type:email_address the same kinds without a namespace are ledger-wide
15
+
16
+ Dataset keys are free-form dotted paths; ``/`` separates a dataset key from a
17
+ member name and ``::`` separates a namespace from a name. A *namespace* is a
18
+ dotted path in the same space as dataset keys (``main.sales`` owns
19
+ ``main.sales.orders``), so one prefix rule covers access, stewardship and moves
20
+ for every kind of subject.
21
+
22
+ Subject strings are written into the event log, which is never edited. When a
23
+ table is renamed or moved the catalog of record reports it and Gloss appends
24
+ re-key events (see ``Gloss.rekey``); the strings themselves stay name-based so
25
+ two machines that know the same table agree on its subject.
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ from dataclasses import dataclass, replace
31
+ from enum import Enum
32
+
33
+ NS_SEP = "::"
34
+
35
+
36
+ class Kind(str, Enum):
37
+ """What a subject is: the part of a subject string before the first colon."""
38
+ MODEL = "model"
39
+ DATASET = "dataset"
40
+ FIELD = "field"
41
+ RELATIONSHIP = "relationship"
42
+ METRIC = "metric"
43
+ TYPE = "type"
44
+
45
+
46
+ def _check_part(what: str, value: str, original: str) -> None:
47
+ if not value or "/" in value or NS_SEP in value:
48
+ raise ValueError(f"Invalid {what} {value!r} in subject {original!r}: it cannot be empty or contain '/' or '::'")
49
+
50
+
51
+ @dataclass(frozen=True)
52
+ class SubjectId:
53
+ """A parsed subject. ``str()`` gives the canonical string that is stored and logged."""
54
+ kind: Kind
55
+ dataset: str | None = None # dataset key, for datasets, fields and dataset metrics
56
+ name: str | None = None # member name (field, relationship, metric, type)
57
+ namespace: str | None = None # owning namespace, for models, relationships, metrics and types
58
+
59
+ # -- construction -------------------------------------------------------
60
+ @classmethod
61
+ def parse(cls, value: str | SubjectId) -> SubjectId:
62
+ """Parse a subject string (a ``SubjectId`` passes through); ``ValueError`` when it is malformed."""
63
+ if isinstance(value, SubjectId):
64
+ return value
65
+ if not isinstance(value, str) or ":" not in value:
66
+ raise ValueError(f"Invalid subject {value!r}: expected '<kind>:<path>'")
67
+ kind_s, path = value.split(":", 1)
68
+ try:
69
+ kind = Kind(kind_s)
70
+ except ValueError:
71
+ raise ValueError(f"Unknown subject kind {kind_s!r} in {value!r}") from None
72
+
73
+ if kind is Kind.MODEL:
74
+ if not path:
75
+ return cls(kind)
76
+ _check_part("namespace", path, value)
77
+ return cls(kind, namespace=path)
78
+ if not path:
79
+ raise ValueError(f"Subject {value!r} has an empty path")
80
+ if kind is Kind.DATASET:
81
+ if NS_SEP in path:
82
+ raise ValueError(f"Dataset subject {value!r} cannot contain '::'")
83
+ return cls(kind, dataset=path)
84
+ if kind is Kind.FIELD or (kind is Kind.METRIC and "/" in path):
85
+ ds, sep, name = path.rpartition("/")
86
+ if not sep or not ds or not name or NS_SEP in path:
87
+ raise ValueError(f"{kind.value} subject {value!r} must look like '{kind.value}:<dataset>/<name>'")
88
+ return cls(kind, dataset=ds, name=name)
89
+ if "/" in path:
90
+ raise ValueError(f"{kind.value} subject {value!r} cannot contain '/'")
91
+ ns, sep, name = path.rpartition(NS_SEP)
92
+ if sep:
93
+ _check_part("namespace", ns, value)
94
+ _check_part("name", name, value)
95
+ return cls(kind, name=name, namespace=ns)
96
+ return cls(kind, name=path)
97
+
98
+ @classmethod
99
+ def model(cls, namespace: str | None = None) -> SubjectId:
100
+ """The model subject: ledger-wide, or the one published from ``namespace``."""
101
+ return cls(Kind.MODEL, namespace=namespace or None)
102
+
103
+ @classmethod
104
+ def for_dataset(cls, key: str) -> SubjectId:
105
+ """The subject of the dataset with key ``key``."""
106
+ return cls(Kind.DATASET, dataset=key)
107
+
108
+ @classmethod
109
+ def for_field(cls, dataset: str, name: str) -> SubjectId:
110
+ """The subject of column ``name`` of ``dataset``."""
111
+ return cls(Kind.FIELD, dataset=dataset, name=name)
112
+
113
+ @classmethod
114
+ def for_relationship(cls, name: str, namespace: str | None = None) -> SubjectId:
115
+ """A relationship subject; ``name`` may carry its namespace (``"sales::orders_customers"``)."""
116
+ return cls._named(Kind.RELATIONSHIP, name, namespace)
117
+
118
+ @classmethod
119
+ def for_type(cls, name: str, namespace: str | None = None) -> SubjectId:
120
+ """A semantic type subject; ``name`` may carry its namespace (``"crm::email_address"``)."""
121
+ return cls._named(Kind.TYPE, name, namespace)
122
+
123
+ @classmethod
124
+ def for_metric(cls, name: str, dataset: str | None = None, *, namespace: str | None = None) -> SubjectId:
125
+ """A metric of ``dataset`` or ``namespace`` (not both), else ledger-wide; ``name`` may hold one."""
126
+ if dataset and namespace:
127
+ raise ValueError("A metric belongs to a dataset or to a namespace, not both")
128
+ if dataset:
129
+ return cls(Kind.METRIC, dataset=dataset, name=name)
130
+ return cls._named(Kind.METRIC, name, namespace)
131
+
132
+ @classmethod
133
+ def _named(cls, kind: Kind, name: str, namespace: str | None) -> SubjectId:
134
+ """``name`` may itself be a reference like ``"crm::email_address"``."""
135
+ if namespace is None and NS_SEP in name:
136
+ namespace, _, name = name.rpartition(NS_SEP)
137
+ return cls.parse(f"{kind.value}:{namespace}{NS_SEP}{name}" if namespace else f"{kind.value}:{name}")
138
+
139
+ # -- rendering ------------------------------------------------------------
140
+ def __str__(self) -> str:
141
+ k = self.kind.value
142
+ if self.kind is Kind.MODEL:
143
+ return f"{k}:{self.namespace or ''}"
144
+ if self.kind is Kind.DATASET:
145
+ return f"{k}:{self.dataset}"
146
+ if self.dataset:
147
+ return f"{k}:{self.dataset}/{self.name}"
148
+ return f"{k}:{self.ref}"
149
+
150
+ @property
151
+ def ref(self) -> str:
152
+ """How other facts refer to this subject: ``crm::email_address``, or the bare name."""
153
+ if self.dataset and self.name:
154
+ return f"{self.dataset}/{self.name}"
155
+ if self.namespace and self.name:
156
+ return f"{self.namespace}{NS_SEP}{self.name}"
157
+ return self.name or self.dataset or self.namespace or ""
158
+
159
+ @property
160
+ def owning_dataset(self) -> str | None:
161
+ """The dataset this subject belongs to, used for progress roll-ups and drift."""
162
+ return self.dataset
163
+
164
+ @property
165
+ def scope_path(self) -> str | None:
166
+ """The dotted path that access rules and moves apply to: the dataset key or the namespace.
167
+
168
+ ``None`` for ledger-wide subjects (``model:``, ``type:email_address``).
169
+ """
170
+ return self.dataset or self.namespace
171
+
172
+ def moved(self, old: str, new: str) -> SubjectId | None:
173
+ """This subject after the path ``old`` became ``new``, or None when it is not under ``old``."""
174
+ path = self.scope_path
175
+ if path is None or not path_covers(old, path):
176
+ return None
177
+ target = replace_prefix(path, old, new)
178
+ return replace(self, dataset=target) if self.dataset else replace(self, namespace=target)
179
+
180
+
181
+ def subject(value: str | SubjectId) -> SubjectId:
182
+ """Shorthand for :meth:`SubjectId.parse`."""
183
+ return SubjectId.parse(value)
184
+
185
+
186
+ def path_covers(prefix: str, path: str | None) -> bool:
187
+ """Whether ``path`` is ``prefix`` or lies under it, compared per dotted segment.
188
+
189
+ ``"finance"`` and ``"finance."`` both cover ``finance`` and ``finance.invoices`` and neither
190
+ covers ``financial.x``. The empty prefix covers everything, including ledger-wide subjects.
191
+ """
192
+ p = prefix.rstrip(".")
193
+ if not p:
194
+ return True
195
+ if path is None:
196
+ return False
197
+ return path == p or path.startswith(p + ".")
198
+
199
+
200
+ def replace_prefix(path: str, old: str, new: str) -> str:
201
+ """``path`` with its leading ``old`` segments replaced by ``new``."""
202
+ o, n = old.rstrip("."), new.rstrip(".")
203
+ return n + path[len(o):] if o else path