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.
Files changed (83) hide show
  1. intentdataflow-0.3.10.dist-info/METADATA +191 -0
  2. intentdataflow-0.3.10.dist-info/RECORD +83 -0
  3. intentdataflow-0.3.10.dist-info/WHEEL +5 -0
  4. intentdataflow-0.3.10.dist-info/entry_points.txt +2 -0
  5. intentdataflow-0.3.10.dist-info/licenses/LICENSE +202 -0
  6. intentdataflow-0.3.10.dist-info/licenses/NOTICE +4 -0
  7. intentdataflow-0.3.10.dist-info/top_level.txt +1 -0
  8. intentflow/__init__.py +2 -0
  9. intentflow/auth.py +30 -0
  10. intentflow/business_rules.py +77 -0
  11. intentflow/catalogs.py +100 -0
  12. intentflow/change_review.py +331 -0
  13. intentflow/checks/__init__.py +92 -0
  14. intentflow/checks/airflow3.py +174 -0
  15. intentflow/checks/business.py +27 -0
  16. intentflow/checks/catalog.py +43 -0
  17. intentflow/checks/cluster.py +81 -0
  18. intentflow/checks/contracts.py +79 -0
  19. intentflow/checks/cost.py +35 -0
  20. intentflow/checks/dbt_quality.py +90 -0
  21. intentflow/checks/dbt_run.py +83 -0
  22. intentflow/checks/deep.py +180 -0
  23. intentflow/checks/dq.py +53 -0
  24. intentflow/checks/elementary.py +50 -0
  25. intentflow/checks/external.py +91 -0
  26. intentflow/checks/lakehouse.py +46 -0
  27. intentflow/checks/lint.py +81 -0
  28. intentflow/checks/orchestration.py +148 -0
  29. intentflow/checks/probes.py +66 -0
  30. intentflow/checks/runtime_history.py +94 -0
  31. intentflow/checks/schema_drift.py +92 -0
  32. intentflow/checks/sql_quality.py +274 -0
  33. intentflow/checks/streaming.py +62 -0
  34. intentflow/cli.py +914 -0
  35. intentflow/contracts.py +107 -0
  36. intentflow/datadiff.py +172 -0
  37. intentflow/dbt_loader.py +194 -0
  38. intentflow/dbt_results.py +55 -0
  39. intentflow/dq_results.py +108 -0
  40. intentflow/extensions.py +51 -0
  41. intentflow/external.py +381 -0
  42. intentflow/http_utils.py +89 -0
  43. intentflow/i18n.py +76 -0
  44. intentflow/incidents.py +83 -0
  45. intentflow/integrations.py +139 -0
  46. intentflow/lakehouse.py +62 -0
  47. intentflow/lineage.py +336 -0
  48. intentflow/lineage_api.py +244 -0
  49. intentflow/lineage_oracle.py +374 -0
  50. intentflow/locale/pt.json +1300 -0
  51. intentflow/model.py +43 -0
  52. intentflow/monitoring.py +197 -0
  53. intentflow/notify.py +154 -0
  54. intentflow/ol_emit.py +93 -0
  55. intentflow/openlineage.py +168 -0
  56. intentflow/orchestrators/__init__.py +53 -0
  57. intentflow/orchestrators/airflow.py +69 -0
  58. intentflow/orchestrators/aws.py +93 -0
  59. intentflow/orchestrators/dagster.py +48 -0
  60. intentflow/orchestrators/dbtcloud.py +68 -0
  61. intentflow/orchestrators/extra.py +135 -0
  62. intentflow/orchestrators/ingestion.py +112 -0
  63. intentflow/orchestrators/kestra.py +27 -0
  64. intentflow/orchestrators/more.py +135 -0
  65. intentflow/orchestrators/prefect.py +53 -0
  66. intentflow/orchestrators/spark.py +118 -0
  67. intentflow/otel.py +53 -0
  68. intentflow/overview.py +123 -0
  69. intentflow/preflight.py +363 -0
  70. intentflow/promexport.py +39 -0
  71. intentflow/pyflow.py +554 -0
  72. intentflow/risks.py +178 -0
  73. intentflow/runner.py +264 -0
  74. intentflow/secrets_box.py +84 -0
  75. intentflow/sqlmesh_loader.py +134 -0
  76. intentflow/store.py +1006 -0
  77. intentflow/streaming.py +115 -0
  78. intentflow/totp.py +38 -0
  79. intentflow/warehouses/__init__.py +190 -0
  80. intentflow/warehouses/cloud.py +160 -0
  81. intentflow/warehouses/more.py +342 -0
  82. intentflow/web.html +878 -0
  83. intentflow/web.py +726 -0
intentflow/risks.py ADDED
@@ -0,0 +1,178 @@
1
+ """What can break in the whole process, stated plainly: visibility gaps, fragile points and failures of the process itself.
2
+
3
+ Each item says **what** it is, **what breaks** (consequence) and **how to fix it**. It only reads the project, the lineage and the store.
4
+ Areas and severities are stable English keys (`visibility`, `fragility`, `external_jobs`, `process`; `high`, `medium`, `low`);
5
+ the text is translated.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import time
10
+ from pathlib import Path
11
+
12
+ from . import external as ext
13
+ from .i18n import N_, tr
14
+
15
+ SEV = {"high": 0, "medium": 1, "low": 2}
16
+ AREAS = {"visibility": N_("Visibility"), "fragility": N_("Fragility"), "external_jobs": N_("External jobs"), "process": N_("Process")}
17
+
18
+
19
+ def _item(area, sev, what, breaks, fix, count=None, examples=None):
20
+ return {"area": area, "severity": sev, "what": what, "breaks": breaks, "fix": fix, "count": count, "examples": (examples or [])[:8]}
21
+
22
+
23
+ def _down_models(proj, res, uid, col, limit=5000):
24
+ """Models reached downstream of a column (direct + indirect), without exposures."""
25
+ seen, stack, models = {(uid, col)}, [(uid, col)], set()
26
+ while stack and len(seen) < limit:
27
+ u, c = stack.pop()
28
+ for e in res.downstream_of(u, c):
29
+ if (e.dst, e.dst_col) not in seen:
30
+ seen.add((e.dst, e.dst_col))
31
+ models.add(e.dst)
32
+ stack.append((e.dst, e.dst_col))
33
+ for d, _via in res.indirect_of(u, c):
34
+ if d not in models:
35
+ models.add(d)
36
+ for dc in proj.nodes[d].columns:
37
+ if (d, dc) not in seen:
38
+ seen.add((d, dc))
39
+ stack.append((d, dc))
40
+ return models
41
+
42
+
43
+ def build(proj, res, store=None, base=None, declared: str | None = None, reads=None, top: int = 10) -> dict:
44
+ items: list[dict] = []
45
+ models = {u: n for u, n in proj.nodes.items() if n.resource_type in ("model", "snapshot") and proj.in_root_package(u)}
46
+ name = lambda u: proj.nodes[u].name
47
+ pol = store.policies() if store is not None else {}
48
+
49
+ # 1. visibility: where IntentFlow does not see, the impact disappears
50
+ nocat = [name(u) for u in models if not proj.actual_columns(u)]
51
+ if nocat:
52
+ items.append(_item("visibility", "high", tr("{n} model(s) without a catalog (catalog.json)", n=len(nocat)),
53
+ tr("column lineage and removed columns are not detected in these models"),
54
+ tr("run `dbt docs generate` after the build and point `--target` at that `target/`"), len(nocat), nocat))
55
+ unres: dict[str, int] = {}
56
+ for u, _c, _why in res.unresolved:
57
+ if u in proj.nodes:
58
+ unres[name(u)] = unres.get(name(u), 0) + 1
59
+ if unres:
60
+ items.append(_item("visibility", "medium", tr("{n} column(s) with unresolved lineage in {models} model(s)", n=sum(unres.values()), models=len(unres)),
61
+ tr("changing the source of these columns alerts no one (falls back to a whole-model dependency)"),
62
+ tr("avoid `select *` without a schema, declare the columns, or run `dbt docs generate`"),
63
+ sum(unres.values()), [f"{m} ({n})" for m, n in sorted(unres.items(), key=lambda x: -x[1])]))
64
+ opaque = sorted({name(d) for _s, _c, d, via in res.indirect if via == "opaque" and d in proj.nodes})
65
+ if opaque:
66
+ items.append(_item("visibility", "medium", tr("{n} model(s) with only an opaque dependency", n=len(opaque)),
67
+ tr("the impact is on the whole model, not the column: too many or too few alarms"),
68
+ tr("SQL with `select *`, macros or table functions; make the columns explicit"), len(opaque), opaque))
69
+
70
+ # 2. fragile points: columns with the largest blast radius and little protection
71
+ ext_reads = reads or []
72
+ cand = []
73
+ for u in models:
74
+ for c in proj.nodes[u].columns:
75
+ n = len(res.downstream_of(u, c)) + len(res.indirect_of(u, c.lower()))
76
+ if n:
77
+ cand.append((n, u, c))
78
+ cand.sort(reverse=True)
79
+ frag = []
80
+ for _n, u, c in cand[:200]: # ponytail: only the 200 highest-degree columns; widen if projects have flatter graphs
81
+ down = _down_models(proj, res, u, c)
82
+ jobs = {r.job for uid, col, r in ext.resolve(proj, ext_reads) if uid == u and col in (c.lower(), "*")}
83
+ n = proj.nodes[u]
84
+ tested = any((t.get("column") or "").lower() == c.lower() for t in n.tests)
85
+ frag.append({"model": n.name, "column": c, "downstream_models": len(down), "external_jobs": len(jobs), "owner": n.meta.get("owner"),
86
+ "tested": tested, "contract": n.contract_enforced})
87
+ frag.sort(key=lambda x: -(x["downstream_models"] + 2 * x["external_jobs"]))
88
+ weak = [f for f in frag if f["downstream_models"] + f["external_jobs"] >= 3 and not (f["tested"] and f["contract"])][:top]
89
+ if weak:
90
+ items.append(_item("fragility", "high", tr("{n} wide-reaching column(s) without a test or contract", n=len(weak)),
91
+ tr("a change in them breaks several consumers and nothing stops it in the PR"),
92
+ tr("add a test on the column and `contract: {enforced: true}` on the model (`DBT005`/`SCH001` start to block)"),
93
+ len(weak), [tr("{column} → {models} model(s), {jobs} external job(s)", column=f"{w['model']}.{w['column']}",
94
+ models=w["downstream_models"], jobs=w["external_jobs"]) + ("" if w["owner"] else ", " + tr("no owner"))
95
+ for w in weak]))
96
+ noowner = [name(u) for u in models if not proj.nodes[u].meta.get("owner") and _down_models(proj, res, u, next(iter(proj.nodes[u].columns), ""))]
97
+ if noowner:
98
+ items.append(_item("fragility", "medium", tr("{n} model(s) with consumers and no owner", n=len(noowner)),
99
+ tr("no one is told when they break"), tr("set `meta.owner` (`DBT003` suggests one)"), len(noowner), noowner))
100
+
101
+ # 3. external jobs (Spark/Python/notebooks)
102
+ if ext_reads:
103
+ um = ext.unmatched(proj, ext_reads)
104
+ amb = {d: v for d, v in um.items() if v["reason"] == "ambiguous"}
105
+ gone = {d: v for d, v in um.items() if v["reason"] == "missing"}
106
+ if amb:
107
+ items.append(_item("external_jobs", "high", tr("{n} dataset(s) read by external jobs are ambiguous", n=len(amb)),
108
+ tr("changes to the right model do not reach the job: the impact silently disappears"),
109
+ "`intentflow lineage --alias DATASET=MODEL`", len(amb), [f"{d} ← {', '.join(v['jobs'])}" for d, v in amb.items()]))
110
+ if gone:
111
+ items.append(_item("external_jobs", "low", tr("{n} dataset(s) read by external jobs without a matching model", n=len(gone)),
112
+ tr("normal for S3/external sources; if it should be a model, the impact does not reach the job"),
113
+ tr("`intentflow lineage --unmatched` (suggests the model) and `--alias`"), len(gone),
114
+ [f"{d} ← {', '.join(v['jobs'])}" for d, v in gone.items()]))
115
+ cov = ext.coverage(ext_reads)
116
+ if cov:
117
+ items.append(_item("external_jobs", "medium", tr("{n} job(s) with conservative propagation (no known output column)", n=len(cov)),
118
+ tr("any change in one input alerts every reader of the output (too many alarms)"),
119
+ tr("declare `feeds`, use `sql_file`/`py_file` or emit `columnLineage`"), len(cov), [c["job"] for c in cov]))
120
+ noown = sorted({r.job for r in ext_reads if not r.owner})
121
+ if noown:
122
+ items.append(_item("external_jobs", "medium", tr("{n} external job(s) without an owner", n=len(noown)),
123
+ tr("the `OL001` alert has no recipient"), tr("add `owner` in `intentflow.lineage.json`"), len(noown), noown))
124
+ unnamed = sorted({r.job for r in ext_reads if r.job.rsplit(".", 1)[-1].lower() in ("pyspark_shell", "spark-shell")})
125
+ if unnamed:
126
+ items.append(_item("external_jobs", "low", tr("{n} Spark job(s) with the default name", n=len(unnamed)),
127
+ tr("different jobs show up as one"), tr("set `appName(...)`"), len(unnamed), unnamed))
128
+
129
+ # 4. the process itself: what makes IntentFlow stop protecting
130
+ if store is not None:
131
+ if not store.get_setting("dbt.base_target") and base is None:
132
+ items.append(_item("process", "high", tr("no `--base`/`dbt.base_target`"),
133
+ tr("the PR gate does not compare against `main`: removed columns and type changes get through"),
134
+ tr("build the `main` `target/` in CI and pass `--base`")))
135
+ if declared and not Path(declared).is_file() and not store.ol_jobs():
136
+ items.append(_item("process", "medium", tr("no source of external jobs (no `intentflow.lineage.json` and no OpenLineage events)"),
137
+ tr("Spark/Python/notebooks that read the project do not show up in the impact"),
138
+ tr("point OpenLineage at `intentflow openlineage serve` or create the declaration file")))
139
+ old = [j["job"] for j in store.ol_jobs() if j["last_event"] and time.time() - j["last_event"] > 14 * 86400]
140
+ if old:
141
+ items.append(_item("process", "medium", tr("{n} OpenLineage job(s) without an event for more than 14 days", n=len(old)),
142
+ tr("the impact uses old reads: new or removed jobs are not reflected"), tr("check the emitter or remove the job"), len(old), old))
143
+ runs = store.runs(200)
144
+ failed = sorted({r["pipeline"] for r in runs if r["state"] == "failed"})
145
+ if failed:
146
+ items.append(_item("process", "medium", tr("{n} pipeline(s) with a recent failed run", n=len(failed)),
147
+ tr("stale data downstream; IntentFlow sees it but does not fix it"), tr("see `intentflow runs`"), len(failed), failed))
148
+ off = list(pol.get("disabled_checks", []) or [])
149
+ if off:
150
+ items.append(_item("process", "medium", tr("{n} check(s) turned off by policy", n=len(off)),
151
+ tr("these problems are no longer reported"), tr("review `disabled_checks`"), len(off), off))
152
+ if not store.recent_samples(time.time() - 7 * 86400):
153
+ items.append(_item("process", "low", tr("no monitoring samples in the last 7 days"),
154
+ tr("volume/freshness anomalies are not detected (`intentflow monitor`)"), tr("schedule `intentflow monitor`")))
155
+ items.sort(key=lambda i: (SEV[i["severity"]], -(i["count"] or 0)))
156
+ return {"items": items, "weak_columns": frag[:top], "models": len(models), "columns": res.columns_total,
157
+ "summary": {s: sum(1 for i in items if i["severity"] == s) for s in SEV}}
158
+
159
+
160
+ def to_markdown(r: dict) -> str:
161
+ icon = {"high": "🔴", "medium": "🟠", "low": "⚪"}
162
+ s = r["summary"]
163
+ L = ["### " + tr("What can break"), "",
164
+ tr("{models} model(s), {columns} column(s). High: **{high}** · medium: **{medium}** · low: **{low}**",
165
+ models=r["models"], columns=r["columns"], high=s["high"], medium=s["medium"], low=s["low"]), ""]
166
+ area = None
167
+ for i in r["items"]:
168
+ if i["area"] != area:
169
+ area = i["area"]
170
+ L += [f"#### {tr(AREAS[area])}", ""]
171
+ L.append(f"- {icon[i['severity']]} **{i['what']}**")
172
+ L.append(" - " + tr("breaks: {what}", what=i["breaks"]))
173
+ L.append(" - " + tr("fix: {what}", what=i["fix"]))
174
+ for e in i["examples"]:
175
+ L.append(f" - `{e}`")
176
+ if not r["items"]:
177
+ L.append(tr("Nothing found in the visibility, fragility and process checks."))
178
+ return "\n".join(L)
intentflow/runner.py ADDED
@@ -0,0 +1,264 @@
1
+ """Runs a full check: used by the CLI, the UI and the scheduler. Reads sources and policies from the store."""
2
+ from __future__ import annotations
3
+
4
+ import time
5
+ from pathlib import Path
6
+
7
+ from . import dbt_loader, dbt_results, lineage as lin
8
+ from .checks import Context, run_checks
9
+ from .orchestrators import Run
10
+ from .store import Store
11
+ from .i18n import tr
12
+
13
+ SOURCE_KEYS = {
14
+ "target": "dbt.target", "root": "dbt.root", "base": "dbt.base_target", "base_root": "dbt.base_root",
15
+ "airflow_dags": "airflow.dags", "kestra_flows": "kestra.flows", "duckdb": "warehouse.duckdb",
16
+ "postgres_env": "warehouse.postgres_env",
17
+ }
18
+
19
+
20
+ def resolve_options(store: Store, overrides: dict) -> dict:
21
+ """flags > saved settings."""
22
+ return {k: (overrides.get(k) if overrides.get(k) is not None else store.get_setting(sk)) for k, sk in SOURCE_KEYS.items()}
23
+
24
+
25
+ def sync_dbt_cloud(store: Store) -> str:
26
+ """Download the configured job's artifacts into a folder next to the store and return it (used as `dbt.target`)."""
27
+ from .orchestrators.dbtcloud import DbtCloudClient
28
+ job = str(store.get_setting("dbt_cloud.job_id"))
29
+ base = Path(store.get_setting("dbt_cloud.dir") or (Path(store.path).parent / ".intentflow_dbt_cloud" if store.backend == "sqlite" else Path.cwd() / ".intentflow_dbt_cloud"))
30
+ c = DbtCloudClient(store.get_setting("dbt_cloud.host"), store.get_setting("dbt_cloud.account_id"))
31
+ r = c.pull_artifacts(job, base / f"job-{job}", store.get_setting("dbt_cloud.run_id"))
32
+ return r["dir"]
33
+
34
+
35
+ class _TrackedWarehouse:
36
+ """Remember unavailable queries even when a probe handles the exception."""
37
+ def __init__(self, warehouse, ctx):
38
+ self.warehouse, self.ctx = warehouse, ctx
39
+
40
+ def __getattr__(self, name):
41
+ value = getattr(self.warehouse, name)
42
+ if not callable(value):
43
+ return value
44
+ def call(*args, **kwargs):
45
+ try:
46
+ return value(*args, **kwargs)
47
+ except Exception:
48
+ if self.ctx.active_check:
49
+ self.ctx.failed_checks.add(self.ctx.active_check)
50
+ raise
51
+ return call
52
+
53
+
54
+ def run_check(store: Store, overrides: dict | None = None, only: list[str] | None = None, stages: set[str] | None = None,
55
+ required_checks: set[str] | None = None) -> dict:
56
+ o = resolve_options(store, overrides or {})
57
+ if not o["target"] and store.get_setting("dbt_cloud.job_id") and store.get_setting("dbt_cloud.account_id"):
58
+ o["target"] = sync_dbt_cloud(store)
59
+ if not o["target"]:
60
+ raise ValueError(tr("dbt target directory not configured (`intentflow config set dbt.target <dir>` or in the UI)"))
61
+ project = dbt_loader.load(o["target"], o["root"] or Path(o["target"]).parent)
62
+ lineage = lin.build(project, cache=store)
63
+ store.flush()
64
+ base = base_l = None
65
+ if o["base"]:
66
+ base = dbt_loader.load(o["base"], o["base_root"] or Path(o["base"]).parent)
67
+ base_l = lin.build(base, cache=store)
68
+ store.flush()
69
+ from . import warehouses
70
+ wh = warehouses.connect(lambda k: o["duckdb"] if k == "warehouse.duckdb" and o["duckdb"] else
71
+ o["postgres_env"] if k == "warehouse.postgres_env" and o["postgres_env"] else store.get_setting(k))
72
+ dres = dbt_results.load(o["target"])
73
+ if dres:
74
+ dbt_results.record(store, dres) # timings enter the history once per invocation
75
+ store.set_setting("state.dbt_run", dbt_results.summary(dres, project))
76
+ from . import business_rules
77
+ business_rules.record(store, project, dres)
78
+ from . import contracts, dq_results, external
79
+ declared = store.get_setting("lineage.declared") or str(Path(o["root"] or Path(o["target"]).parent) / external.DECLARED_FILE)
80
+ ctx = Context(project=project, external=external.load(store, declared, project), lineage=lineage, base_project=base, base_lineage=base_l, policies=store.policies(), dbt_results=dres,
81
+ airflow_dags_dir=o["airflow_dags"], kestra_flows_dir=o["kestra_flows"], store=store, warehouse=wh,
82
+ dq_results=dq_results.load_all(store.get_setting("dq.results")),
83
+ contracts=contracts.load_all(store.get_setting("contracts.dir")),
84
+ samples=store.recent_samples(time.time() - 24 * 3600))
85
+ if required_checks is not None:
86
+ ctx.required_checks = required_checks
87
+ ctx.record_probe_history = False
88
+ if wh is not None:
89
+ ctx.warehouse = _TrackedWarehouse(wh, ctx)
90
+ ctx.runs = [Run(r["system"], r["pipeline"], r["run_id"], r["state"], r["start"], r["end"], r["duration"], r["url"]) for r in store.runs(1000)]
91
+ try:
92
+ findings = run_checks(ctx, only, stages=stages)
93
+ finally:
94
+ if wh is not None:
95
+ wh.close()
96
+ for f in findings: # owner and file help routing and CI annotations
97
+ for n in f.nodes:
98
+ node = project.nodes.get(n)
99
+ if node:
100
+ f.evidence.setdefault("owner", node.meta.get("owner") or node.meta.get("team"))
101
+ f.evidence.setdefault("file", node.path)
102
+ break
103
+ if f.evidence.get("owner") is None:
104
+ f.evidence.pop("owner", None)
105
+ if not store.get_setting("scan.include_packages"):
106
+ # findings whose nodes all belong to installed packages (dbt_utils, project-evaluator...) are not actionable by the team
107
+ findings = [f for f in findings if not f.nodes or any(n not in project.nodes or project.in_root_package(n) for n in f.nodes)]
108
+ res = store.sync_findings(findings, ctx.completed_checks)
109
+ store.set_setting("state.last_check", {"ts": time.time(), "findings": len(findings), **res, "lineage": lineage.precision_report})
110
+ store.audit("system", "check", {"findings": len(findings), **res})
111
+ return {"findings": findings, "lineage": lineage.precision_report, "store": res, "project": project,
112
+ "completed_checks": sorted(ctx.completed_checks), "failed_checks": sorted(ctx.failed_checks)}
113
+
114
+
115
+ def collect_runs(store: Store, airflow: str | None = None, airflow_api: str | None = None, kestra: str | None = None,
116
+ prefect: str | None = None, dagster: str | None = None,
117
+ airbyte: str | None = None, fivetran: str | None = None,
118
+ spark: str | None = None, databricks: str | None = None,
119
+ argo: str | None = None, mage: str | None = None, dbt_cloud: bool | None = None) -> dict:
120
+ """Collect runs from the configured orchestrators. URLs come from the argument or from the saved settings."""
121
+ from .orchestrators.airflow import AirflowClient
122
+ from .orchestrators.kestra import KestraClient
123
+ airflow = airflow or store.get_setting("airflow.url")
124
+ kestra = kestra or store.get_setting("kestra.url")
125
+ api = airflow_api or store.get_setting("airflow.api", "v1")
126
+ n, errors = 0, []
127
+ from .orchestrators.dagster import DagsterClient
128
+ from .orchestrators.prefect import PrefectClient
129
+ prefect = prefect or store.get_setting("prefect.url")
130
+ dagster = dagster or store.get_setting("dagster.url")
131
+ from .orchestrators.ingestion import AirbyteClient, FivetranClient
132
+ airbyte = airbyte or store.get_setting("airbyte.url")
133
+ fivetran = fivetran or store.get_setting("fivetran.url") # "https://api.fivetran.com" (or a proxy)
134
+ from .orchestrators.spark import DatabricksJobsClient, SparkClient
135
+ spark = spark or store.get_setting("spark.url")
136
+ databricks = databricks or store.get_setting("databricks.jobs_host") # ex.: adb-123.azuredatabricks.net (token: DATABRICKS_TOKEN)
137
+ from .orchestrators.more import ArgoClient, MageClient
138
+ argo = argo or store.get_setting("argo.url")
139
+ mage = mage or store.get_setting("mage.url")
140
+ from .orchestrators import extra
141
+ extras = []
142
+ for key, build in (("kafka_connect.url", lambda u: extra.KafkaConnectClient(u)), ("flink.url", lambda u: extra.FlinkClient(u)),
143
+ ("luigi.url", lambda u: extra.LuigiClient(u)), ("mlflow.url", lambda u: extra.MLflowClient(u)),
144
+ ("rundeck.url", lambda u: extra.RundeckClient(u, store.get_setting("rundeck.project") or "default"))):
145
+ u = store.get_setting(key)
146
+ if u:
147
+ extras.append((key.split(".")[0], build(u)))
148
+ if store.get_setting("aws.region") or store.get_setting("aws.endpoint_url"):
149
+ from .orchestrators import aws
150
+ rg, ep = store.get_setting("aws.region"), store.get_setting("aws.endpoint_url")
151
+ for flag, cls in (("aws.glue", aws.GlueClient), ("aws.stepfunctions", aws.StepFunctionsClient), ("aws.athena", aws.AthenaClient)):
152
+ if store.get_setting(flag):
153
+ try:
154
+ extras.append((flag.split(".")[1], cls(rg, ep)))
155
+ except RuntimeError as e: # boto3 ausente
156
+ extras.append((flag.split(".")[1], type("_Err", (), {"runs": lambda self, e=e: (_ for _ in ()).throw(e)})()))
157
+ if store.get_setting("azure.data_factory"):
158
+ from .orchestrators.more import AzureDataFactoryClient
159
+ extras.append(("adf", AzureDataFactoryClient(store.get_setting("azure.data_factory"))))
160
+ dbtc = None
161
+ if dbt_cloud is not False and store.get_setting("dbt_cloud.account_id"):
162
+ from .orchestrators.dbtcloud import DbtCloudClient
163
+ dbtc = DbtCloudClient(store.get_setting("dbt_cloud.host"), store.get_setting("dbt_cloud.account_id"))
164
+ clients = ([("airflow", AirflowClient(airflow, api))] if airflow else []) + ([("kestra", KestraClient(kestra))] if kestra else []) \
165
+ + ([("prefect", PrefectClient(prefect))] if prefect else []) + ([("dagster", DagsterClient(dagster))] if dagster else []) \
166
+ + ([("airbyte", AirbyteClient(airbyte))] if airbyte else []) + ([("fivetran", FivetranClient(fivetran))] if fivetran else []) \
167
+ + ([("spark", SparkClient(spark))] if spark else []) + ([("databricks", DatabricksJobsClient(databricks))] if databricks else []) \
168
+ + ([("dbt_cloud", dbtc)] if dbtc else []) + extras + ([("argo", ArgoClient(argo, store.get_setting("argo.namespace")))] if argo else []) + ([("mage", MageClient(mage))] if mage else [])
169
+ for name, c in clients:
170
+ try:
171
+ rs = c.runs()
172
+ store.upsert_runs(rs)
173
+ n += len(rs)
174
+ except Exception as e: # one bad orchestrator (bad JSON, socket error, schema change) must not stop the others
175
+ errors.append(f"{name}: {type(e).__name__}: {str(e)[:300]}")
176
+ if not clients:
177
+ errors.append(tr("no orchestrator configured") + " (airflow.url / kestra.url / prefect.url / dagster.url / airbyte.url / fivetran.url / spark.url / databricks.jobs_host / argo.url / mage.url / dbt_cloud.account_id / kafka_connect.url / flink.url / luigi.url / mlflow.url / rundeck.url / aws.*)")
178
+ return {"runs": n, "errors": errors}
179
+
180
+
181
+ def collect_samples(store: Store, host: bool = True, docker: bool = True) -> int:
182
+ from . import monitoring
183
+ from .orchestrators.airflow import AirflowClient
184
+ s = []
185
+ if host:
186
+ s += monitoring.host_memory()
187
+ if docker:
188
+ s += monitoring.docker_containers()
189
+ spark_url = store.get_setting("spark.url")
190
+ if spark_url:
191
+ from .orchestrators.spark import SparkClient
192
+ try:
193
+ s += SparkClient(spark_url).samples()
194
+ except RuntimeError:
195
+ pass
196
+ try:
197
+ from . import warehouses
198
+ wh = warehouses.connect(store.get_setting)
199
+ if wh is not None:
200
+ try:
201
+ s += monitoring.warehouse_spill(wh)
202
+ s += monitoring.warehouse_memory_failures(wh)
203
+ finally:
204
+ wh.close()
205
+ except Exception: # missing driver / no credential: does not take the collection down
206
+ pass
207
+ if store.get_setting("kubernetes.enabled"):
208
+ s += monitoring.kubernetes_pods(context=store.get_setting("kubernetes.context"), namespace=store.get_setting("kubernetes.namespace"))
209
+ if store.get_setting("prometheus.url"):
210
+ try:
211
+ qs = store.get_setting("prometheus.queries")
212
+ if isinstance(qs, str):
213
+ import json as _json
214
+ qs = _json.loads(qs)
215
+ s += monitoring.prometheus_samples(store.get_setting("prometheus.url"), qs or None)
216
+ except (RuntimeError, ValueError):
217
+ pass
218
+ for flags, mod in ((("catalog.glue", "catalog.unity"), "catalogs"), (("kafka.bootstrap", "kafka.schema_registry"), "streaming")):
219
+ if any(store.get_setting(f) for f in flags):
220
+ try:
221
+ __import__(f"intentflow.{mod}", fromlist=["collect"]).collect(store)
222
+ except Exception as e: # an unreachable catalog/registry must not drop the other samples
223
+ store.audit("system", "collect_failed", {"what": mod, "error": f"{type(e).__name__}: {str(e)[:300]}"})
224
+ url = store.get_setting("airflow.url")
225
+ if url:
226
+ try:
227
+ s += monitoring.airflow_pools(AirflowClient(url, store.get_setting("airflow.api", "v1")))
228
+ except RuntimeError:
229
+ pass
230
+ store.add_samples(s)
231
+ return len(s)
232
+
233
+
234
+ def watch(store: Store, interval_s: float = 300, iterations: int | None = None, sleep=time.sleep) -> int:
235
+ """Simple scheduler: collect runs/memory, run the checks and notify; repeat every `interval_s`."""
236
+ n = 0
237
+ while iterations is None or n < iterations:
238
+ t0 = time.time()
239
+ try:
240
+ for step in (collect_runs, collect_samples): # collection failures must not skip checks/notifications
241
+ try:
242
+ step(store)
243
+ except Exception as e:
244
+ store.audit("system", "watch_error", {"step": step.__name__, "error": str(e)[:300]})
245
+ if store.get_setting("dbt.target"):
246
+ res = run_check(store)
247
+ from . import incidents, notify
248
+ notify.send(store, incidents.group(store.findings("open"), res["project"]))
249
+ except Exception as e: # a bad cycle does not take the scheduler down
250
+ try:
251
+ store.audit("system", "watch_error", {"error": str(e)[:300]})
252
+ except Exception: # the connection itself died (database restart/failover): reopen it for the next cycle
253
+ try:
254
+ store.close()
255
+ except Exception:
256
+ pass
257
+ try:
258
+ store = Store(store.spec)
259
+ except Exception:
260
+ pass # database still down: try again next cycle
261
+ n += 1
262
+ if iterations is None or n < iterations:
263
+ sleep(max(0.0, interval_s - (time.time() - t0)))
264
+ return n
@@ -0,0 +1,84 @@
1
+ """Encryption at rest of secrets kept in the store (TOTP secret, SSO id_token and refresh_token).
2
+
3
+ AES-128-CBC + HMAC-SHA256 (Fernet, `cryptography` library). Format: `enc:v1:<token>`; values without the prefix are read as they are
4
+ (old stores keep working; `intentflow secrets migrate` encrypts what already exists).
5
+
6
+ Key, in order: `INTENTFLOW_SECRET_KEY` (any long text; turned into a key by SHA-256) → file `<store>.key` (0600, created on the
7
+ first write; only for a SQLite file). Rotation: set the new key in INTENTFLOW_SECRET_KEY, the previous one(s) in
8
+ INTENTFLOW_SECRET_KEY_OLD (comma-separated), run `intentflow secrets rotate`, then drop the old variable. Persisting new secrets is refused without encryption.
9
+ The `:memory:` store may keep plain text in memory; legacy values stay readable for migration.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import base64
14
+ import hashlib
15
+ import os
16
+ import stat
17
+ from pathlib import Path
18
+ from .i18n import tr
19
+
20
+ PREFIX = "enc:v1:"
21
+
22
+
23
+ def _fernet(key_bytes: bytes):
24
+ from cryptography.fernet import Fernet
25
+ return Fernet(base64.urlsafe_b64encode(hashlib.sha256(key_bytes).digest()))
26
+
27
+
28
+ class Box:
29
+ def __init__(self, store_path: str | None, backend: str = "sqlite"):
30
+ self._f = None
31
+ self._persistent = backend != "sqlite" or bool(store_path and store_path != ":memory:")
32
+ self.source = "none"
33
+ env = os.environ.get("INTENTFLOW_SECRET_KEY")
34
+ try:
35
+ if env:
36
+ self._f, self.source = _fernet(env.encode()), "env"
37
+ elif backend == "sqlite" and store_path and store_path != ":memory:":
38
+ kp = Path(str(store_path) + ".key")
39
+ if not kp.exists():
40
+ fd = os.open(kp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, stat.S_IRUSR | stat.S_IWUSR)
41
+ with os.fdopen(fd, "wb") as f:
42
+ f.write(base64.urlsafe_b64encode(os.urandom(32)))
43
+ self._f, self.source = _fernet(kp.read_bytes().strip()), "file"
44
+ olds = [k for k in os.environ.get("INTENTFLOW_SECRET_KEY_OLD", "").split(",") if k.strip()]
45
+ if self._f is not None and olds:
46
+ from cryptography.fernet import MultiFernet # encrypts with the first, decrypts with any
47
+ self._f = MultiFernet([self._f] + [_fernet(k.strip().encode()) for k in olds])
48
+ except ImportError: # legacy reads still possible; enc() refuses to persist new secrets
49
+ self._f, self.source = None, "unavailable"
50
+
51
+ @property
52
+ def enabled(self) -> bool:
53
+ return self._f is not None
54
+
55
+ def enc(self, v: str | None) -> str | None:
56
+ if v is None or v == "" or str(v).startswith(PREFIX):
57
+ return v
58
+ if self._f is None:
59
+ if self._persistent:
60
+ raise RuntimeError(tr("encryption unavailable: install intentdataflow[secrets] and set INTENTFLOW_SECRET_KEY for PostgreSQL"))
61
+ return v
62
+ return PREFIX + self._f.encrypt(str(v).encode()).decode()
63
+
64
+ def dec(self, v: str | None) -> str | None:
65
+ if v is None or not str(v).startswith(PREFIX):
66
+ return v
67
+ if self._f is None:
68
+ raise RuntimeError(tr("encrypted value and no key available (set INTENTFLOW_SECRET_KEY)"))
69
+ from cryptography.fernet import InvalidToken
70
+ try:
71
+ return self._f.decrypt(str(v)[len(PREFIX):].encode()).decode()
72
+ except InvalidToken:
73
+ raise RuntimeError(tr("could not decrypt: INTENTFLOW_SECRET_KEY differs from the one used to write")) from None
74
+
75
+ def rotate(self, v: str | None) -> str | None:
76
+ """Re-encrypt under the current key (plain text gets encrypted too)."""
77
+ if v is None or v == "":
78
+ return v
79
+ if not str(v).startswith(PREFIX):
80
+ return self.enc(v)
81
+ return PREFIX + self._f.encrypt(self.dec(v).encode()).decode()
82
+
83
+ def status(self) -> dict:
84
+ return {"encrypted_at_rest": self.enabled, "key_source": self.source}