intentdataflow 0.3.10__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.
- intentdataflow-0.3.10.dist-info/METADATA +191 -0
- intentdataflow-0.3.10.dist-info/RECORD +83 -0
- intentdataflow-0.3.10.dist-info/WHEEL +5 -0
- intentdataflow-0.3.10.dist-info/entry_points.txt +2 -0
- intentdataflow-0.3.10.dist-info/licenses/LICENSE +202 -0
- intentdataflow-0.3.10.dist-info/licenses/NOTICE +4 -0
- intentdataflow-0.3.10.dist-info/top_level.txt +1 -0
- intentflow/__init__.py +2 -0
- intentflow/auth.py +30 -0
- intentflow/business_rules.py +77 -0
- intentflow/catalogs.py +100 -0
- intentflow/change_review.py +331 -0
- intentflow/checks/__init__.py +92 -0
- intentflow/checks/airflow3.py +174 -0
- intentflow/checks/business.py +27 -0
- intentflow/checks/catalog.py +43 -0
- intentflow/checks/cluster.py +81 -0
- intentflow/checks/contracts.py +79 -0
- intentflow/checks/cost.py +35 -0
- intentflow/checks/dbt_quality.py +90 -0
- intentflow/checks/dbt_run.py +83 -0
- intentflow/checks/deep.py +180 -0
- intentflow/checks/dq.py +53 -0
- intentflow/checks/elementary.py +50 -0
- intentflow/checks/external.py +91 -0
- intentflow/checks/lakehouse.py +46 -0
- intentflow/checks/lint.py +81 -0
- intentflow/checks/orchestration.py +148 -0
- intentflow/checks/probes.py +66 -0
- intentflow/checks/runtime_history.py +94 -0
- intentflow/checks/schema_drift.py +92 -0
- intentflow/checks/sql_quality.py +274 -0
- intentflow/checks/streaming.py +62 -0
- intentflow/cli.py +914 -0
- intentflow/contracts.py +107 -0
- intentflow/datadiff.py +172 -0
- intentflow/dbt_loader.py +194 -0
- intentflow/dbt_results.py +55 -0
- intentflow/dq_results.py +108 -0
- intentflow/extensions.py +51 -0
- intentflow/external.py +381 -0
- intentflow/http_utils.py +89 -0
- intentflow/i18n.py +76 -0
- intentflow/incidents.py +83 -0
- intentflow/integrations.py +139 -0
- intentflow/lakehouse.py +62 -0
- intentflow/lineage.py +336 -0
- intentflow/lineage_api.py +244 -0
- intentflow/lineage_oracle.py +374 -0
- intentflow/locale/pt.json +1300 -0
- intentflow/model.py +43 -0
- intentflow/monitoring.py +197 -0
- intentflow/notify.py +154 -0
- intentflow/ol_emit.py +93 -0
- intentflow/openlineage.py +168 -0
- intentflow/orchestrators/__init__.py +53 -0
- intentflow/orchestrators/airflow.py +69 -0
- intentflow/orchestrators/aws.py +93 -0
- intentflow/orchestrators/dagster.py +48 -0
- intentflow/orchestrators/dbtcloud.py +68 -0
- intentflow/orchestrators/extra.py +135 -0
- intentflow/orchestrators/ingestion.py +112 -0
- intentflow/orchestrators/kestra.py +27 -0
- intentflow/orchestrators/more.py +135 -0
- intentflow/orchestrators/prefect.py +53 -0
- intentflow/orchestrators/spark.py +118 -0
- intentflow/otel.py +53 -0
- intentflow/overview.py +123 -0
- intentflow/preflight.py +363 -0
- intentflow/promexport.py +39 -0
- intentflow/pyflow.py +554 -0
- intentflow/risks.py +178 -0
- intentflow/runner.py +264 -0
- intentflow/secrets_box.py +84 -0
- intentflow/sqlmesh_loader.py +134 -0
- intentflow/store.py +1006 -0
- intentflow/streaming.py +115 -0
- intentflow/totp.py +38 -0
- intentflow/warehouses/__init__.py +190 -0
- intentflow/warehouses/cloud.py +160 -0
- intentflow/warehouses/more.py +342 -0
- intentflow/web.html +878 -0
- intentflow/web.py +726 -0
intentflow/extensions.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""Extension point: packages register a module under the `intentflow.extensions` entry-point group.
|
|
2
|
+
|
|
3
|
+
A module may define any of these hooks (all optional):
|
|
4
|
+
FEATURES: set[str] shown to the UI in /api/me
|
|
5
|
+
register_cli(sub) add argparse subcommands
|
|
6
|
+
web_get(h, prim, path, q) -> bool handle a GET before core routing (True = handled)
|
|
7
|
+
web_post(h, prim, parts, body, query) -> bool handle a POST before core routing
|
|
8
|
+
refresh_session(h, prim, sid, user) -> bool keep an SSO session alive (False ends it)
|
|
9
|
+
logout_url(h, prim, info) -> str | None provider logout URL for an SSO session
|
|
10
|
+
me(h, prim, who) -> dict extra fields for /api/me
|
|
11
|
+
notify_deliver(sink, subject, body, meta) -> bool deliver to a sink type the core does not know
|
|
12
|
+
integration_cards(store, card) -> None add cards to the Integrations page
|
|
13
|
+
"""
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import sys
|
|
17
|
+
from functools import cache
|
|
18
|
+
from importlib.metadata import entry_points
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@cache
|
|
22
|
+
def loaded() -> tuple:
|
|
23
|
+
out = []
|
|
24
|
+
for ep in entry_points(group="intentflow.extensions"):
|
|
25
|
+
try:
|
|
26
|
+
out.append(ep.load())
|
|
27
|
+
except Exception as e: # a broken extension must not take the core down
|
|
28
|
+
print(f"warning: extension {ep.name} failed to load: {e}", file=sys.stderr)
|
|
29
|
+
return tuple(out)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def features() -> list[str]:
|
|
33
|
+
return sorted({f for m in loaded() for f in getattr(m, "FEATURES", ())})
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def first(hook: str, *a, **k):
|
|
37
|
+
"""Result of the first extension that implements `hook` and returns something other than None."""
|
|
38
|
+
for m in loaded():
|
|
39
|
+
fn = getattr(m, hook, None)
|
|
40
|
+
if fn is not None:
|
|
41
|
+
r = fn(*a, **k)
|
|
42
|
+
if r is not None:
|
|
43
|
+
return r
|
|
44
|
+
return None
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def each(hook: str, *a, **k) -> None:
|
|
48
|
+
for m in loaded():
|
|
49
|
+
fn = getattr(m, hook, None)
|
|
50
|
+
if fn is not None:
|
|
51
|
+
fn(*a, **k)
|
intentflow/external.py
ADDED
|
@@ -0,0 +1,381 @@
|
|
|
1
|
+
"""Consumers outside the project SQL (Spark, Python, notebooks, BI tools): reads of columns/datasets.
|
|
2
|
+
|
|
3
|
+
Two sources, same shape: OpenLineage events already ingested (`ol_jobs`/`ol_edges`) and an optional hand-written
|
|
4
|
+
`intentflow.lineage.json` for jobs that do not emit OpenLineage:
|
|
5
|
+
|
|
6
|
+
{"jobs": [{"name": "ltv_spark", "owner": "team-ds",
|
|
7
|
+
"reads": [{"dataset": "customers", "columns": ["email", "id"]}, {"dataset": "orders"}],
|
|
8
|
+
"writes": ["warehouse.ltv"]}]}
|
|
9
|
+
|
|
10
|
+
Missing `columns` = the whole dataset (any removed/changed column affects it).
|
|
11
|
+
`aliases` (optional, at the top of the file) links an external name to a model when suffix matching fails or is ambiguous:
|
|
12
|
+
`{"aliases": {"file:/lake/raw/customers": "stg_customers"}, "jobs": [...]}` (also applies to datasets coming from OpenLineage).
|
|
13
|
+
A SQL job (Spark SQL, notebook with `spark.sql`) can carry the text instead of `reads`:
|
|
14
|
+
`{"name": "ltv", "sql_file": "jobs/ltv.sql", "dialect": "spark", "writes": ["wh.ltv"]}` (or `"sql": "select ..."`; path relative to the
|
|
15
|
+
declaration file). Column lineage (reads and `feeds`) is computed by the same engine as the project, without declaring it by hand.
|
|
16
|
+
`params` replaces `${v}`, `$v`, `{v}`, `{{ v }}`; `{{ ref('m') }}`/`{{ source('s','t') }}` become the name; without a value the placeholder becomes
|
|
17
|
+
`__param_v__` (a table name still matches by suffix). Scripts with several statements (`INSERT ... SELECT`, `CREATE TABLE AS`) are accepted.
|
|
18
|
+
Python job (`"py_file"`): static analysis of the code (PySpark/pandas, see `pyflow`). It is heuristic (the code is never run); what it does not
|
|
19
|
+
understand stays conservative.
|
|
20
|
+
Datasets written by one job and read by another form a chain: the change propagates through the outputs. With `feeds` (per read) or
|
|
21
|
+
OpenLineage `columnLineage` the propagation is per column; without them it is conservative (any column of what the job writes):
|
|
22
|
+
`{"dataset": "customers", "columns": ["email"], "feeds": [{"dataset": "wh.ltv", "columns": ["score"]}]}`.
|
|
23
|
+
"""
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import json
|
|
27
|
+
import re
|
|
28
|
+
from dataclasses import dataclass
|
|
29
|
+
from pathlib import Path
|
|
30
|
+
|
|
31
|
+
from .i18n import N_, tr
|
|
32
|
+
|
|
33
|
+
DECLARED_FILE = "intentflow.lineage.json"
|
|
34
|
+
REASONS = {"ok": N_("ok"), "ambiguous": N_("ambiguous"), "missing": N_("missing")}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass(frozen=True)
|
|
38
|
+
class ExtRead:
|
|
39
|
+
job: str
|
|
40
|
+
dataset: str # name as the source wrote it (`ns:db.schema.table`, `table`, `schema.table`)
|
|
41
|
+
column: str # "*" = whole dataset
|
|
42
|
+
source: str # declared | openlineage
|
|
43
|
+
owner: str | None = None
|
|
44
|
+
writes: tuple = ()
|
|
45
|
+
feeds: tuple = () # ((dataset, column), ...) this read feeds; empty = unknown (propagates to everything the job writes)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _read_file(path) -> dict:
|
|
49
|
+
p = Path(path) if path else None
|
|
50
|
+
if p is None or not p.is_file():
|
|
51
|
+
return {}
|
|
52
|
+
try:
|
|
53
|
+
data = json.loads(p.read_text())
|
|
54
|
+
if not isinstance(data, dict) or not isinstance(data.get("jobs", []), list) or not isinstance(data.get("aliases", {}), dict):
|
|
55
|
+
raise TypeError('expected {"jobs": [...], "aliases": {...}}')
|
|
56
|
+
return data
|
|
57
|
+
except (ValueError, TypeError) as e:
|
|
58
|
+
raise ValueError(tr("{file}: invalid declared lineage file ({error})", file=p, error=f"{type(e).__name__}: {e}")) from None
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def load_aliases(path) -> dict[str, str]:
|
|
62
|
+
return {str(k): str(v) for k, v in _read_file(path).get("aliases", {}).items()}
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _safe_file(base: Path, ref: str, exts: tuple, name: str, what: str) -> str:
|
|
66
|
+
"""The declaration file may come from a PR: only read inside its directory, never an absolute path or `..`."""
|
|
67
|
+
root = base.resolve()
|
|
68
|
+
target = (root / str(ref)).resolve()
|
|
69
|
+
if not target.is_relative_to(root) or target.suffix.lower() not in exts or not target.is_file():
|
|
70
|
+
raise ValueError(tr("job '{job}': {what} must be a {exts} file inside {dir}/", job=name, what=what, exts="/".join(exts), dir=root.name))
|
|
71
|
+
if target.stat().st_size > 1_000_000:
|
|
72
|
+
raise ValueError(tr("job '{job}': {what} is over 1 MB", job=name, what=what))
|
|
73
|
+
return target.read_text()
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
# Bounded quantifiers and non-overlapping classes: linear time in the text size (the SQL may come from a PR)
|
|
77
|
+
_PARAM = re.compile(r"\$\{([^{}$]{1,200})\}|\{\{([^{}]{1,200})\}\}|(?<![\w$])\$([A-Za-z_]\w{0,100})|\{([A-Za-z_]\w{0,100})\}")
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _strip_blocks(text: str, opener: str, closer: str) -> str:
|
|
81
|
+
out, i = [], 0
|
|
82
|
+
while True:
|
|
83
|
+
j = text.find(opener, i)
|
|
84
|
+
k = text.find(closer, j + len(opener)) if j >= 0 else -1
|
|
85
|
+
if j < 0 or k < 0:
|
|
86
|
+
out.append(text[i:])
|
|
87
|
+
return "".join(out)
|
|
88
|
+
out.append(text[i:j])
|
|
89
|
+
i = k + len(closer)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def render_sql(text: str, params: dict | None = None) -> tuple[str, list[str]]:
|
|
93
|
+
"""Resolve macros/variables of parameterized SQL: `${v}`, `$v`, `{v}`, `{{ v }}`, `{{ ref('m') }}`, `{{ source('s','t') }}`; Jinja tags are dropped.
|
|
94
|
+
|
|
95
|
+
An unknown value becomes the identifier `__param_v__` (valid as a table, column or literal) and is returned in `unresolved`.
|
|
96
|
+
"""
|
|
97
|
+
params = {str(k): v for k, v in (params or {}).items()}
|
|
98
|
+
unresolved: set[str] = set()
|
|
99
|
+
if len(text) > 1_000_000:
|
|
100
|
+
raise ValueError(tr("SQL over 1 MB"))
|
|
101
|
+
text = _strip_blocks(_strip_blocks(text, "{%", "%}"), "{#", "#}")
|
|
102
|
+
|
|
103
|
+
def repl(m):
|
|
104
|
+
key = next(g for g in m.groups() if g).strip()
|
|
105
|
+
r = re.fullmatch(r"ref\(\s*['\"]([\w.]+)['\"]\s*\)", key)
|
|
106
|
+
if r:
|
|
107
|
+
return r.group(1)
|
|
108
|
+
r = re.fullmatch(r"source\(\s*['\"]([\w.]+)['\"]\s*,\s*['\"]([\w.]+)['\"]\s*\)", key)
|
|
109
|
+
if r:
|
|
110
|
+
return f"{r.group(1)}.{r.group(2)}"
|
|
111
|
+
if key in params:
|
|
112
|
+
return str(params[key])
|
|
113
|
+
unresolved.add(key)
|
|
114
|
+
return "__param_" + re.sub(r"\W", "_", key) + "__"
|
|
115
|
+
return _PARAM.sub(repl, text), sorted(unresolved)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _dataset_name(t) -> str:
|
|
119
|
+
return ".".join(x for x in (t.catalog, t.db, t.name) if x)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def sql_reads(name: str, owner, writes: tuple, text: str, dialect: str, project) -> list[ExtRead]:
|
|
123
|
+
"""Reads (column by column) and `feeds` of a SQL script with one or more statements (SELECT, INSERT ... SELECT, CREATE TABLE AS)."""
|
|
124
|
+
import sqlglot
|
|
125
|
+
from sqlglot import exp
|
|
126
|
+
from sqlglot.lineage import lineage as sg_lineage
|
|
127
|
+
from sqlglot.optimizer.qualify import qualify
|
|
128
|
+
try:
|
|
129
|
+
stmts = [t for t in sqlglot.parse(text, read=dialect) if t is not None]
|
|
130
|
+
except sqlglot.errors.SqlglotError:
|
|
131
|
+
raise ValueError(tr("job '{job}': invalid SQL for the '{dialect}' dialect", job=name, dialect=dialect)) from None # never echo the content
|
|
132
|
+
schema = project.sqlglot_schema() if project is not None else {}
|
|
133
|
+
out: list[ExtRead] = []
|
|
134
|
+
seen: set = set()
|
|
135
|
+
for st in stmts:
|
|
136
|
+
target = None
|
|
137
|
+
if isinstance(st, (exp.Create, exp.Insert)) and isinstance(st.this, (exp.Table, exp.Schema)):
|
|
138
|
+
tt = st.this if isinstance(st.this, exp.Table) else st.this.this
|
|
139
|
+
target = _dataset_name(tt) if isinstance(tt, exp.Table) else None
|
|
140
|
+
sel = st if isinstance(st, exp.Select) else st.find(exp.Select)
|
|
141
|
+
if sel is None:
|
|
142
|
+
continue
|
|
143
|
+
dsts = writes or ((target,) if target else ())
|
|
144
|
+
dst = dsts[0] if dsts else ""
|
|
145
|
+
ctes = {c.alias_or_name.lower() for c in sel.find_all(exp.CTE)}
|
|
146
|
+
try:
|
|
147
|
+
q = qualify(sel.copy(), schema=schema, dialect=dialect, validate_qualify_columns=False, identify=False)
|
|
148
|
+
except Exception:
|
|
149
|
+
q = sel.copy()
|
|
150
|
+
got = False
|
|
151
|
+
for col in q.named_selects:
|
|
152
|
+
try:
|
|
153
|
+
root = sg_lineage(col, q, schema=schema, dialect=dialect, trim_selects=False)
|
|
154
|
+
except Exception:
|
|
155
|
+
continue
|
|
156
|
+
stack = [root]
|
|
157
|
+
while stack:
|
|
158
|
+
n = stack.pop()
|
|
159
|
+
stack.extend(n.downstream)
|
|
160
|
+
if n.downstream or not isinstance(n.expression, exp.Table):
|
|
161
|
+
continue
|
|
162
|
+
ds = _dataset_name(n.expression)
|
|
163
|
+
src_col = n.name.split(".")[-1].strip('"`[]').lower()
|
|
164
|
+
if ds.lower() in ctes or (ds, src_col, col, dst) in seen:
|
|
165
|
+
continue
|
|
166
|
+
seen.add((ds, src_col, col, dst))
|
|
167
|
+
got = True
|
|
168
|
+
out.append(ExtRead(name, ds, src_col, "declared", owner, dsts, ((dst, col.lower()),) if dst else ()))
|
|
169
|
+
# columns used only in JOIN/WHERE/GROUP BY/window: not in the SELECT, but changing them changes the whole result
|
|
170
|
+
tabs = {}
|
|
171
|
+
for t in q.find_all(exp.Table):
|
|
172
|
+
tabs[(t.alias_or_name or "").lower()] = _dataset_name(t)
|
|
173
|
+
only = next(iter(tabs.values())) if len(tabs) == 1 else None
|
|
174
|
+
scopes = [q.args.get(k) for k in ("where", "group", "having", "order", "qualify")] + list(q.args.get("joins") or []) \
|
|
175
|
+
+ list(q.find_all(exp.Window))
|
|
176
|
+
cols = [c for sc in scopes if sc is not None for c in sc.find_all(exp.Column)]
|
|
177
|
+
for c in cols: # only filter/join/grouping/ordering/window; the projection is already direct lineage
|
|
178
|
+
ds = tabs.get((c.table or "").lower()) if c.table else only
|
|
179
|
+
if not ds or ds.lower() in ctes:
|
|
180
|
+
continue
|
|
181
|
+
col = c.name.lower()
|
|
182
|
+
if (ds, col, "*", dst) in seen:
|
|
183
|
+
continue
|
|
184
|
+
seen.add((ds, col, "*", dst))
|
|
185
|
+
got = True
|
|
186
|
+
out.append(ExtRead(name, ds, col, "declared", owner, dsts, ((dst, "*"),) if dst else ()))
|
|
187
|
+
if not got: # column lineage not resolved (e.g. `select *` without a schema): conservative read of each table
|
|
188
|
+
for t in sel.find_all(exp.Table):
|
|
189
|
+
ds = _dataset_name(t)
|
|
190
|
+
if ds.lower() not in ctes and (ds, "*", "*", dst) not in seen:
|
|
191
|
+
seen.add((ds, "*", "*", dst))
|
|
192
|
+
out.append(ExtRead(name, ds, "*", "declared", owner, dsts))
|
|
193
|
+
return out
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _sql_reads(job: dict, base: Path, project) -> list[ExtRead]:
|
|
197
|
+
name = str(job["name"])
|
|
198
|
+
text = str(job["sql"]) if job.get("sql") else _safe_file(base, job["sql_file"], (".sql", ".hql", ".txt"), name, "sql_file")
|
|
199
|
+
text, _ = render_sql(text, job.get("params"))
|
|
200
|
+
return sql_reads(name, job.get("owner"), tuple(str(w) for w in job.get("writes", [])), text, job.get("dialect") or "spark", project)
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _py_reads(job: dict, base: Path, project) -> list[ExtRead]:
|
|
204
|
+
from . import pyflow
|
|
205
|
+
name = str(job["name"])
|
|
206
|
+
src = _safe_file(base, job["py_file"], (".py",), name, "py_file")
|
|
207
|
+
return pyflow.reads(name, job.get("owner"), src, tuple(str(w) for w in job.get("writes", [])), job.get("dialect") or "spark",
|
|
208
|
+
project, job.get("params"), base=base)
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def load_declared(path, project=None) -> list[ExtRead]:
|
|
212
|
+
p = Path(path)
|
|
213
|
+
if not p.is_file():
|
|
214
|
+
return []
|
|
215
|
+
try:
|
|
216
|
+
data = _read_file(p)
|
|
217
|
+
jobs = data.get("jobs", [])
|
|
218
|
+
out = []
|
|
219
|
+
for j in jobs:
|
|
220
|
+
writes = tuple(str(w) for w in j.get("writes", []))
|
|
221
|
+
if "sql" in j or "sql_file" in j:
|
|
222
|
+
out += _sql_reads(j, p.parent, project)
|
|
223
|
+
continue
|
|
224
|
+
if "py_file" in j:
|
|
225
|
+
out += _py_reads(j, p.parent, project)
|
|
226
|
+
continue
|
|
227
|
+
for r in j["reads"]:
|
|
228
|
+
cols = [c.lower() for c in r.get("columns") or []] or ["*"]
|
|
229
|
+
feeds = tuple((str(f["dataset"]), (c2 or "*").lower()) for f in r.get("feeds", []) for c2 in (f.get("columns") or [None]))
|
|
230
|
+
out += [ExtRead(str(j["name"]), str(r["dataset"]), c, "declared", j.get("owner"), writes, feeds) for c in cols]
|
|
231
|
+
return out
|
|
232
|
+
except ValueError:
|
|
233
|
+
raise
|
|
234
|
+
except (KeyError, TypeError, AttributeError, OSError) as e:
|
|
235
|
+
raise ValueError(tr("{file}: invalid declared lineage file ({error})", file=p.name, error=type(e).__name__)) from None
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def load_openlineage(store) -> list[ExtRead]:
|
|
239
|
+
jobs = {j["job"]: j for j in store.ol_jobs()}
|
|
240
|
+
out, with_cols, feeds = [], set(), {}
|
|
241
|
+
for e in store.ol_edges():
|
|
242
|
+
feeds.setdefault((e["job"], e["src_ds"], str(e["src_col"]).lower()), []).append((e["dst_ds"], str(e["dst_col"]).lower()))
|
|
243
|
+
for (job, ds, col), f in feeds.items():
|
|
244
|
+
out.append(ExtRead(job, ds, col, "openlineage", None, tuple(jobs.get(job, {}).get("outputs", [])), tuple(f)))
|
|
245
|
+
with_cols.add((job, ds))
|
|
246
|
+
for name, j in jobs.items(): # input without a column edge: read of the whole dataset
|
|
247
|
+
out += [ExtRead(name, ds, "*", "openlineage", None, tuple(j["outputs"])) for ds in j["inputs"] if (name, ds) not in with_cols]
|
|
248
|
+
return out
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def load(store=None, declared=None, project=None) -> list[ExtRead]:
|
|
252
|
+
from dataclasses import replace
|
|
253
|
+
al = load_aliases(declared) if declared else {}
|
|
254
|
+
reads = (load_declared(declared, project) if declared else []) + (load_openlineage(store) if store is not None else [])
|
|
255
|
+
ref = lambda d: al.get(d, d)
|
|
256
|
+
return [replace(r, dataset=ref(r.dataset), writes=tuple(ref(w) for w in r.writes), feeds=tuple((ref(d), c) for d, c in r.feeds))
|
|
257
|
+
for r in reads] if al else reads
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
_EXT = (".parquet", ".csv", ".json", ".orc", ".avro", ".delta", ".tsv", ".txt")
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def _candidates(ref: str) -> list[list[str]]:
|
|
264
|
+
"""Lists of name parts, from the most specific to the least: `db.schema.tab`, or the last 3/2/1 segments of a path."""
|
|
265
|
+
name = ref.rsplit(":", 1)[-1]
|
|
266
|
+
clean = lambda x: x.strip('"`[]').lower()
|
|
267
|
+
if "/" in name: # file dataset (Spark/Parquet): the last path segments are schema/table
|
|
268
|
+
segs = [clean(x) for x in name.split("/") if x.strip()]
|
|
269
|
+
if segs and segs[-1].endswith(_EXT):
|
|
270
|
+
segs[-1] = segs[-1].rsplit(".", 1)[0]
|
|
271
|
+
return [segs[-k:] for k in (3, 2, 1) if len(segs) >= k]
|
|
272
|
+
parts = [clean(p) for p in name.split(".") if p.strip()]
|
|
273
|
+
firm = [p for p in parts if not re.fullmatch(r"__param_\w+__", p)] # an unresolved variable (`${db}.table`) names nothing
|
|
274
|
+
return [x for x in (parts, firm) if x] if firm != parts else ([parts] if parts else [])
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def match(project, ref: str) -> tuple[str | None, str]:
|
|
278
|
+
"""(uid, reason): `ok`, `missing` (no node) or `ambiguous` (the most specific matching suffix points to more than one node)."""
|
|
279
|
+
cached = getattr(project, "_ext_rels", None)
|
|
280
|
+
if cached is None or cached[0] != len(project.nodes): # match() runs inside readers() loops: build once per project
|
|
281
|
+
cached = (len(project.nodes), {uid: [p.strip('"`[]').lower() for p in n.relation.split(".")] if n.relation else []
|
|
282
|
+
for uid, n in project.nodes.items()})
|
|
283
|
+
project._ext_rels = cached
|
|
284
|
+
rels = cached[1]
|
|
285
|
+
for parts in _candidates(ref):
|
|
286
|
+
hits = {uid for uid, n in project.nodes.items()
|
|
287
|
+
if (rels[uid] and len(parts) <= len(rels[uid]) and rels[uid][-len(parts):] == parts)
|
|
288
|
+
or (len(parts) == 1 and n.name.lower() == parts[0])}
|
|
289
|
+
if len(hits) == 1:
|
|
290
|
+
return next(iter(hits)), "ok"
|
|
291
|
+
if hits:
|
|
292
|
+
return None, "ambiguous"
|
|
293
|
+
return None, "missing"
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def match_dataset(project, ref: str) -> str | None:
|
|
297
|
+
return match(project, ref)[0]
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def unmatched(project, reads: list[ExtRead]) -> dict[str, dict]:
|
|
301
|
+
"""{dataset: {"reason", "jobs"}} of the read datasets that did not match. `ambiguous` is the dangerous one: the impact silently disappears."""
|
|
302
|
+
out: dict[str, dict] = {}
|
|
303
|
+
for r in reads:
|
|
304
|
+
uid, why = match(project, r.dataset)
|
|
305
|
+
if not uid:
|
|
306
|
+
out.setdefault(r.dataset, {"reason": why, "jobs": set()})["jobs"].add(r.job)
|
|
307
|
+
return {k: {"reason": v["reason"], "jobs": sorted(v["jobs"])} for k, v in out.items()}
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def resolve(project, reads: list[ExtRead]) -> list[tuple[str, str, ExtRead]]:
|
|
311
|
+
"""[(uid, column, read)] of the reads that match a project node (the others are unknown to it)."""
|
|
312
|
+
cache: dict[str, str | None] = {}
|
|
313
|
+
out = []
|
|
314
|
+
for r in reads:
|
|
315
|
+
if r.dataset not in cache:
|
|
316
|
+
cache[r.dataset] = match_dataset(project, r.dataset)
|
|
317
|
+
if cache[r.dataset]:
|
|
318
|
+
out.append((cache[r.dataset], r.column, r))
|
|
319
|
+
return out
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def _same(project, a: str, b: str) -> bool:
|
|
323
|
+
"""Same dataset: identical name (ignoring trailing slash and case) or both match the same project node."""
|
|
324
|
+
if a.rstrip("/").lower() == b.rstrip("/").lower():
|
|
325
|
+
return True
|
|
326
|
+
ua, ub = match_dataset(project, a), match_dataset(project, b)
|
|
327
|
+
return ua is not None and ua == ub
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def readers(project, reads: list[ExtRead], touched: set[tuple[str, str]], models: set[str]) -> dict[str, dict]:
|
|
331
|
+
"""Affected external jobs: they read a column in `touched`, the whole dataset of a model in `models`, or an output of an affected job.
|
|
332
|
+
|
|
333
|
+
{job: {"reads": [ExtRead], "via": previous job | None, "depth": 1..}}; propagation through outputs without feeds is conservative (whole dataset).
|
|
334
|
+
"""
|
|
335
|
+
hit: dict[str, dict] = {}
|
|
336
|
+
for uid, col, r in resolve(project, reads):
|
|
337
|
+
if (uid, col) in touched or (col == "*" and uid in models):
|
|
338
|
+
hit.setdefault(r.job, {"reads": [], "via": None, "depth": 1})["reads"].append(r)
|
|
339
|
+
frontier = list(hit)
|
|
340
|
+
while frontier:
|
|
341
|
+
nxt = []
|
|
342
|
+
for j in frontier:
|
|
343
|
+
outs = {f for r in hit[j]["reads"] for f in (r.feeds or tuple((w, "*") for w in r.writes))}
|
|
344
|
+
if not outs:
|
|
345
|
+
continue
|
|
346
|
+
for r in reads:
|
|
347
|
+
if r.job in hit or r.job == j:
|
|
348
|
+
continue
|
|
349
|
+
if any(_same(project, r.dataset, d) and "*" in (r.column, c) or (_same(project, r.dataset, d) and r.column == c) for d, c in outs):
|
|
350
|
+
hit.setdefault(r.job, {"reads": [], "via": j, "depth": hit[j]["depth"] + 1})["reads"].append(r)
|
|
351
|
+
if r.job not in nxt:
|
|
352
|
+
nxt.append(r.job)
|
|
353
|
+
frontier = nxt
|
|
354
|
+
return hit
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
def suggest(project, ref: str, n: int = 3) -> list[str]:
|
|
358
|
+
"""Model names similar to the dataset (to write the alias)."""
|
|
359
|
+
import difflib
|
|
360
|
+
last = _candidates(ref)[-1:] or [[ref]]
|
|
361
|
+
want = last[0][-1] if last and last[0] else ref
|
|
362
|
+
names = {x.name for x in project.nodes.values()}
|
|
363
|
+
return difflib.get_close_matches(want.lower(), [x.lower() for x in names], n=n, cutoff=0.6)
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
def coverage(reads: list[ExtRead]) -> list[dict]:
|
|
367
|
+
"""Jobs with reads without `feeds`: propagation through their outputs is conservative (any written column)."""
|
|
368
|
+
by: dict[str, set] = {}
|
|
369
|
+
for r in reads:
|
|
370
|
+
if r.writes and not r.feeds:
|
|
371
|
+
by.setdefault(r.job, set()).add(f"{r.dataset}.{r.column}")
|
|
372
|
+
return [{"job": j, "reads_without_feeds": sorted(v)} for j, v in sorted(by.items())]
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def add_alias(path, dataset: str, model: str) -> None:
|
|
376
|
+
"""Write `aliases[dataset] = model` into intentflow.lineage.json (creates the file; keeps the rest)."""
|
|
377
|
+
p = Path(path)
|
|
378
|
+
data = _read_file(p) if p.is_file() else {}
|
|
379
|
+
data.setdefault("jobs", [])
|
|
380
|
+
data.setdefault("aliases", {})[dataset] = model
|
|
381
|
+
p.write_text(json.dumps(data, ensure_ascii=False, indent=1) + "\n")
|
intentflow/http_utils.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"""Bounded request framing shared by the local HTTP endpoints."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
from .i18n import tr
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def tls_context(cert: str, key: str):
|
|
7
|
+
"""Server TLS (>= 1.2). Unreadable files end the process with an explanation instead of a traceback."""
|
|
8
|
+
import ssl
|
|
9
|
+
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
|
10
|
+
ctx.minimum_version = ssl.TLSVersion.TLSv1_2
|
|
11
|
+
try:
|
|
12
|
+
ctx.load_cert_chain(cert, key)
|
|
13
|
+
except (OSError, ssl.SSLError) as e: # e.g. key mode 600 owned by another uid inside a container
|
|
14
|
+
raise SystemExit(tr("refused: cannot load the TLS certificate/key ({err}); the files must be readable by the user running the UI",
|
|
15
|
+
err=e)) from None
|
|
16
|
+
return ctx
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def urlopen(req, timeout: float):
|
|
20
|
+
"""urllib urlopen with retries on transient failures (connection errors, 429, 5xx); read-only calls only.
|
|
21
|
+
INTENTFLOW_HTTP_RETRIES (default 2) extra attempts, exponential backoff from 0.5s."""
|
|
22
|
+
import os
|
|
23
|
+
import time
|
|
24
|
+
import urllib.error
|
|
25
|
+
import urllib.request
|
|
26
|
+
try:
|
|
27
|
+
retries = max(0, int(os.environ.get("INTENTFLOW_HTTP_RETRIES", "2")))
|
|
28
|
+
except ValueError:
|
|
29
|
+
retries = 2
|
|
30
|
+
for n in range(retries + 1):
|
|
31
|
+
try:
|
|
32
|
+
return urllib.request.urlopen(req, timeout=timeout)
|
|
33
|
+
except urllib.error.HTTPError as e:
|
|
34
|
+
if n == retries or not (e.code == 429 or e.code >= 500):
|
|
35
|
+
raise
|
|
36
|
+
except (urllib.error.URLError, TimeoutError, ConnectionError):
|
|
37
|
+
if n == retries:
|
|
38
|
+
raise
|
|
39
|
+
time.sleep(0.5 * 2 ** n)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def access_log(handler, code) -> None:
|
|
43
|
+
"""One line per request on stderr when INTENTFLOW_ACCESS_LOG is `json` or `text` (default: off).
|
|
44
|
+
The query string is dropped: it may carry tokens."""
|
|
45
|
+
import os
|
|
46
|
+
import sys
|
|
47
|
+
import time
|
|
48
|
+
mode = os.environ.get("INTENTFLOW_ACCESS_LOG", "").lower()
|
|
49
|
+
if mode not in ("json", "text"):
|
|
50
|
+
return
|
|
51
|
+
rec = {"ts": round(time.time(), 3), "client": handler.client_address[0], "method": handler.command,
|
|
52
|
+
"path": (handler.path or "").split("?")[0], "status": int(code) if isinstance(code, int) else code}
|
|
53
|
+
if mode == "json":
|
|
54
|
+
import json
|
|
55
|
+
line = json.dumps(rec)
|
|
56
|
+
else:
|
|
57
|
+
line = f'{rec["client"]} {rec["method"]} {rec["path"]} {rec["status"]}'
|
|
58
|
+
print(line, file=sys.stderr, flush=True)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class RequestError(ValueError):
|
|
62
|
+
def __init__(self, status: int, message: str):
|
|
63
|
+
super().__init__(message)
|
|
64
|
+
self.status = status
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def read_body(handler, limit: int = 1024 * 1024) -> bytes:
|
|
68
|
+
"""Reject ambiguous framing before allocating/reading a client-controlled body.
|
|
69
|
+
A handler that already read the request (`handler.prefetched_body`) is served from that."""
|
|
70
|
+
if getattr(handler, "prefetched_body", None) is not None:
|
|
71
|
+
return handler.prefetched_body
|
|
72
|
+
if handler.headers.get("Transfer-Encoding") is not None:
|
|
73
|
+
raise RequestError(400, tr("Transfer-Encoding not supported"))
|
|
74
|
+
lengths = handler.headers.get_all("Content-Length", [])
|
|
75
|
+
if len(lengths) > 1:
|
|
76
|
+
raise RequestError(400, tr("duplicated Content-Length"))
|
|
77
|
+
raw = lengths[0] if lengths else "0"
|
|
78
|
+
if not raw.isascii() or not raw.isdecimal() or len(raw) > 10:
|
|
79
|
+
raise RequestError(400, tr("invalid Content-Length"))
|
|
80
|
+
size = int(raw)
|
|
81
|
+
if size > limit:
|
|
82
|
+
raise RequestError(413, tr("request body exceeds the limit"))
|
|
83
|
+
try:
|
|
84
|
+
body = handler.rfile.read(size)
|
|
85
|
+
except TimeoutError:
|
|
86
|
+
raise RequestError(408, tr("timed out reading the request")) from None
|
|
87
|
+
if len(body) != size:
|
|
88
|
+
raise RequestError(400, tr("incomplete request body"))
|
|
89
|
+
return body
|
intentflow/i18n.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""Translations. Source strings are English; `locale/<lang>.json` maps each English string to its translation.
|
|
2
|
+
|
|
3
|
+
Language, in order: the current request (UI sends `X-IntentFlow-Lang`), `INTENTFLOW_LANG`, then the locale variables
|
|
4
|
+
(`LC_ALL`, `LC_MESSAGES`, `LANG`). Anything starting with `pt` selects Portuguese; everything else is English.
|
|
5
|
+
Findings are stored already rendered, in the language of the process that ran the check.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import contextvars
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
from functools import cache
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
LANGS = ("en", "pt")
|
|
16
|
+
_request_lang: contextvars.ContextVar[str | None] = contextvars.ContextVar("intentflow_lang", default=None)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def normalize(value: str | None) -> str:
|
|
20
|
+
return "pt" if (value or "").strip().lower().startswith("pt") else "en"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def lang() -> str:
|
|
24
|
+
req = _request_lang.get()
|
|
25
|
+
if req:
|
|
26
|
+
return req
|
|
27
|
+
for var in ("INTENTFLOW_LANG", "LC_ALL", "LC_MESSAGES", "LANG"):
|
|
28
|
+
if os.environ.get(var):
|
|
29
|
+
return normalize(os.environ[var])
|
|
30
|
+
return "en"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def set_request_lang(value: str | None) -> None:
|
|
34
|
+
_request_lang.set(normalize(value) if value else None)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@cache
|
|
38
|
+
def catalog(code: str) -> dict[str, str]:
|
|
39
|
+
"""Core catalog plus `locale/<code>.json` next to each extension module."""
|
|
40
|
+
from . import extensions
|
|
41
|
+
out: dict[str, str] = {}
|
|
42
|
+
for base in [Path(__file__).parent] + [Path(m.__file__).parent for m in extensions.loaded()]:
|
|
43
|
+
p = base / "locale" / f"{code}.json"
|
|
44
|
+
if p.exists():
|
|
45
|
+
out.update(json.loads(p.read_text(encoding="utf-8")))
|
|
46
|
+
return out
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class Msg(str):
|
|
50
|
+
"""Translated text that remembers its English rendering, so finding ids do not depend on the language."""
|
|
51
|
+
en: str
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def tr(msg: str, /, **kw) -> Msg:
|
|
55
|
+
"""Translate `msg` and fill `{placeholders}` from `kw`."""
|
|
56
|
+
en = msg.format(**kw) if kw else msg
|
|
57
|
+
code = lang()
|
|
58
|
+
if code == "en":
|
|
59
|
+
out = Msg(en)
|
|
60
|
+
else:
|
|
61
|
+
s = catalog(code).get(msg, msg)
|
|
62
|
+
out = Msg(s.format(**kw) if kw else s)
|
|
63
|
+
out.en = en
|
|
64
|
+
return out
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def N_(msg: str) -> str:
|
|
68
|
+
"""Mark a constant for translation without translating it yet (translate where it is used: `tr(CONST)`)."""
|
|
69
|
+
return msg
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def cat(*parts: str) -> Msg:
|
|
73
|
+
"""Concatenate translated pieces keeping the English rendering."""
|
|
74
|
+
out = Msg("".join(parts))
|
|
75
|
+
out.en = "".join(getattr(p, "en", p) for p in parts)
|
|
76
|
+
return out
|