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
@@ -0,0 +1,135 @@
1
+ """Argo Workflows and Mage through REST, normalized into `Run`. Verification: local HTTP servers with the documented format
2
+ (no Kubernetes cluster or Mage runs here).
3
+
4
+ Argo : `GET /api/v1/workflows/{ns}` (Bearer ARGO_TOKEN; `ARGO_NAMESPACE` or argo.namespace; default `argo`)
5
+ Mage : `GET /api/pipeline_runs` (optional MAGE_API_KEY, sent as `api_key`)
6
+ """
7
+ from __future__ import annotations
8
+
9
+ from ..i18n import tr
10
+ from ..http_utils import urlopen as _urlopen
11
+
12
+ import os
13
+ import urllib.parse
14
+
15
+ from . import Run, http_json, ts
16
+ from .extra import _post_json
17
+ from datetime import UTC
18
+
19
+ ARGO_PHASE = {"Succeeded": "success", "Failed": "failed", "Error": "failed", "Running": "running", "Pending": "queued"}
20
+ MAGE_STATUS = {"completed": "success", "failed": "failed", "cancelled": "failed", "running": "running", "initial": "queued"}
21
+
22
+
23
+ class ArgoClient:
24
+ def __init__(self, base_url: str, namespace: str | None = None, fetch=http_json):
25
+ self.base, self.ns, self.fetch = base_url.rstrip("/"), namespace or os.environ.get("ARGO_NAMESPACE", "argo"), fetch
26
+
27
+ def _h(self) -> dict:
28
+ t = os.environ.get("ARGO_TOKEN")
29
+ return {"Authorization": f"Bearer {t}" if not t.startswith("Bearer ") else t} if t else {}
30
+
31
+ def runs(self, limit: int = 100) -> list[Run]:
32
+ data = self.fetch(f"{self.base}/api/v1/workflows/{urllib.parse.quote(self.ns)}?listOptions.limit={limit}", self._h()) or {}
33
+ out = []
34
+ for w in data.get("items") or []:
35
+ md, st = w.get("metadata", {}), w.get("status", {})
36
+ labels = md.get("labels") or {}
37
+ name = labels.get("workflows.argoproj.io/workflow-template") or labels.get("workflows.argoproj.io/cron-workflow") \
38
+ or (md.get("generateName") or md.get("name", "?")).rstrip("-")
39
+ s, e = ts(st.get("startedAt")), ts(st.get("finishedAt"))
40
+ state = ARGO_PHASE.get(st.get("phase", ""), "other")
41
+ out.append(Run("argo", name, md.get("name", ""), state, s, e if state in ("success", "failed") else None,
42
+ (e - s) if s and e and state in ("success", "failed") else None, f"{self.base}/workflows/{self.ns}/{md.get('name', '')}"))
43
+ return out
44
+
45
+
46
+ class MageClient:
47
+ """Mage OSS requires `api_key` + a session token. Credentials (from the environment): MAGE_TOKEN, or MAGE_USER/MAGE_PASSWORD (login at
48
+ `/api/sessions`); MAGE_API_KEY overrides Mage's default development key (a public value from its docs)."""
49
+ DEFAULT_KEY = "zkWlN0PkIKSN0C11CfUHUj84OT5XOJ6tDZ6bDRO2"
50
+
51
+ def __init__(self, base_url: str, fetch=http_json, login=None):
52
+ self.base, self.fetch, self._login, self._tok = base_url.rstrip("/"), fetch, login, None
53
+
54
+ def _key(self) -> str:
55
+ return os.environ.get("MAGE_API_KEY") or self.DEFAULT_KEY
56
+
57
+ def _token(self) -> str | None:
58
+ t = os.environ.get("MAGE_TOKEN")
59
+ if t:
60
+ return t
61
+ user, pw = os.environ.get("MAGE_USER"), os.environ.get("MAGE_PASSWORD")
62
+ if not (user and pw):
63
+ return None
64
+ if self._tok is None:
65
+ self._tok = (self._login or self._session)(user, pw)
66
+ return self._tok
67
+
68
+ def _session(self, user: str, pw: str) -> str:
69
+ import base64
70
+ import json
71
+ import urllib.error
72
+ import urllib.request
73
+ body = json.dumps({"session": {"email": user, "password": pw}, "api_key": self._key()}).encode()
74
+ req = urllib.request.Request(f"{self.base}/api/sessions", data=body, method="POST", headers={"Content-Type": "application/json"})
75
+ try:
76
+ with _urlopen(req, timeout=15) as r:
77
+ jwt = json.loads(r.read().decode())["session"]["token"]
78
+ seg = jwt.split(".")[1]
79
+ return json.loads(base64.urlsafe_b64decode(seg + "=" * (-len(seg) % 4)))["token"] # internal session token
80
+ except Exception as e:
81
+ raise RuntimeError(tr("Mage login failed at {url}: {error}", url=f"{self.base}/api/sessions", error=getattr(e, "code", type(e).__name__))) from None
82
+
83
+ def runs(self, limit: int = 100) -> list[Run]:
84
+ tok = self._token()
85
+ data = self.fetch(f"{self.base}/api/pipeline_runs?_limit={limit}&api_key={urllib.parse.quote(self._key())}",
86
+ {"Authorization": f"Bearer {tok}"} if tok else {}) or {}
87
+ if isinstance(data.get("error"), dict):
88
+ raise RuntimeError(tr("Mage refused the query: {error} (set MAGE_USER/MAGE_PASSWORD or MAGE_TOKEN)", error=data["error"].get("message", "")[:120]))
89
+ out = []
90
+ for r in data.get("pipeline_runs") or []:
91
+ s = ts(r.get("started_at") or r.get("execution_date"))
92
+ state = MAGE_STATUS.get(str(r.get("status", "")).lower(), "other")
93
+ e = ts(r.get("completed_at") or (r.get("updated_at") if state in ("success", "failed") else None)) # failed runs have no completed_at
94
+ # `updated_at` comes truncated to seconds: the end may fall before the fractional start
95
+ out.append(Run("mage", r.get("pipeline_uuid", "?"), str(r.get("id")), state, s, e if state in ("success", "failed") else None,
96
+ max(0.0, e - s) if s and e and state in ("success", "failed") else None, f"{self.base}/pipelines/{r.get('pipeline_uuid', '')}/runs"))
97
+ return out
98
+
99
+
100
+ class AzureDataFactoryClient:
101
+ """Azure Data Factory: `POST .../factories/{f}/queryPipelineRuns` (last 24 h). Token: AZURE_TOKEN
102
+ (`az account get-access-token --resource https://management.azure.com --query accessToken -o tsv`).
103
+ Permission: the *Reader* role (or `Microsoft.DataFactory/factories/pipelineruns/read`) on the factory."""
104
+ STATE = {"Succeeded": "success", "Failed": "failed", "Cancelled": "failed", "Canceling": "failed", "InProgress": "running", "Queued": "queued"}
105
+
106
+ def __init__(self, resource: str, base: str = "https://management.azure.com", post=_post_json):
107
+ """`resource`: `subscriptionId/resourceGroup/factoryName`."""
108
+ sub, rg, fac = resource.strip("/").split("/")[-3:]
109
+ self.url = (f"{base.rstrip('/')}/subscriptions/{sub}/resourceGroups/{rg}/providers/Microsoft.DataFactory/factories/{fac}"
110
+ f"/queryPipelineRuns?api-version=2018-06-01")
111
+ self.post = post
112
+ self.portal = "https://adf.azure.com/en/monitoring/pipelineruns/"
113
+
114
+ def runs(self, hours: int = 24) -> list[Run]:
115
+ from datetime import datetime, timedelta
116
+ now = datetime.now(UTC)
117
+ tok = os.environ.get("AZURE_TOKEN")
118
+ if not tok:
119
+ raise RuntimeError(tr("AZURE_TOKEN is not set"))
120
+ out, cont = [], None
121
+ for _ in range(10):
122
+ body = {"lastUpdatedAfter": (now - timedelta(hours=hours)).isoformat(), "lastUpdatedBefore": now.isoformat(),
123
+ **({"continuationToken": cont} if cont else {})}
124
+ d = self.post(self.url, body, {"Authorization": f"Bearer {tok}"}) or {}
125
+ for r in d.get("value", []):
126
+ state = self.STATE.get(r.get("status", ""), "other")
127
+ s, e = ts(r.get("runStart")), ts(r.get("runEnd"))
128
+ done = state in ("success", "failed")
129
+ dur = (r.get("durationInMs") / 1000) if r.get("durationInMs") is not None else ((e - s) if s and e else None)
130
+ out.append(Run("adf", r.get("pipelineName", "?"), r.get("runId", ""), state, s, e if done else None, dur if done else None,
131
+ self.portal + str(r.get("runId", ""))))
132
+ cont = d.get("continuationToken")
133
+ if not cont:
134
+ break
135
+ return out
@@ -0,0 +1,53 @@
1
+ """Prefect (2.x/3.x) via REST: `POST /api/flow_runs/filter` e `POST /api/flows/filter`. Token opcional: PREFECT_API_KEY."""
2
+ from __future__ import annotations
3
+
4
+ from ..i18n import tr
5
+ from ..http_utils import urlopen as _urlopen
6
+
7
+ import json
8
+ import os
9
+ import urllib.error
10
+ import urllib.request
11
+
12
+ from . import Run, ts
13
+
14
+ STATE = {"COMPLETED": "success", "FAILED": "failed", "CRASHED": "failed", "CANCELLED": "failed", "CANCELLING": "failed",
15
+ "RUNNING": "running", "PENDING": "queued", "SCHEDULED": "queued", "PAUSED": "running"}
16
+
17
+
18
+ def _post(url: str, body: dict, headers: dict, timeout: float = 15.0):
19
+ req = urllib.request.Request(url, data=json.dumps(body).encode(), method="POST", headers={"Content-Type": "application/json", **headers})
20
+ try:
21
+ with _urlopen(req, timeout=timeout) as r:
22
+ return json.loads(r.read().decode() or "null")
23
+ except urllib.error.HTTPError as e:
24
+ raise RuntimeError(tr("HTTP {code} at {url}", code=e.code, url=url)) from None
25
+ except urllib.error.URLError as e:
26
+ raise RuntimeError(tr("no connection to {url}: {reason}", url=url, reason=e.reason)) from None
27
+
28
+
29
+ class PrefectClient:
30
+ def __init__(self, base_url: str, post=_post):
31
+ # aceita http://host:4200 ou http://host:4200/api
32
+ self.base = base_url.rstrip("/").removesuffix("/api")
33
+ self.post = post
34
+
35
+ def _h(self) -> dict:
36
+ k = os.environ.get("PREFECT_API_KEY")
37
+ return {"Authorization": f"Bearer {k}"} if k else {}
38
+
39
+ def runs(self, limit: int = 100) -> list[Run]:
40
+ rs = self.post(f"{self.base}/api/flow_runs/filter", {"limit": limit, "sort": "START_TIME_DESC"}, self._h())
41
+ ids = sorted({r["flow_id"] for r in rs if r.get("flow_id")})
42
+ names = {}
43
+ if ids:
44
+ fl = self.post(f"{self.base}/api/flows/filter", {"flows": {"id": {"any_": ids}}, "limit": len(ids)}, self._h())
45
+ names = {f["id"]: f["name"] for f in fl}
46
+ out = []
47
+ for r in rs:
48
+ st = (r.get("state") or {}).get("type", "")
49
+ s, e = ts(r.get("start_time")), ts(r.get("end_time"))
50
+ dur = r.get("total_run_time") or ((e - s) if s and e else None)
51
+ out.append(Run("prefect", names.get(r.get("flow_id"), r.get("name", "?")), r["id"], STATE.get(st, "other"), s, e, dur,
52
+ f"{self.base}/runs/flow-run/{r['id']}"))
53
+ return out
@@ -0,0 +1,118 @@
1
+ """Spark (UI/History Server REST `/api/v1`) and Databricks Jobs (`/api/2.1/jobs/runs/list`).
2
+
3
+ Spark: applications become `Run`s; executors and stages become memory/spill samples (for the existing cluster checks).
4
+ Databricks Jobs: Bearer DATABRICKS_TOKEN. Verification: a real Spark 3.5 in a container; Databricks only with a local HTTP server.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import os
9
+ import time
10
+
11
+ from . import Run, http_json, ts
12
+
13
+ DB_RESULT = {"SUCCESS": "success", "FAILED": "failed", "TIMEDOUT": "failed", "CANCELED": "failed", "MAXIMUM_CONCURRENT_RUNS_REACHED": "failed",
14
+ "UPSTREAM_FAILED": "failed", "EXCLUDED": "other", "SUCCESS_WITH_FAILURES": "failed"}
15
+ OOM_HINTS = ("outofmemory", "out of memory", "exceeding memory limits", "killed by yarn", "oomkilled", "exit code 137")
16
+
17
+
18
+ _SIZE = {"k": 1024, "m": 1024**2, "g": 1024**3, "t": 1024**4}
19
+
20
+
21
+ def _size(v: str | None) -> float | None:
22
+ """'1g' / '512m' / '2048' (MiB in Spark when there is no unit) → bytes."""
23
+ import re
24
+ m = re.fullmatch(r"\s*(\d+(?:\.\d+)?)\s*([kKmMgGtT])?[bB]?\s*", str(v or ""))
25
+ if not m:
26
+ return None
27
+ return float(m.group(1)) * (_SIZE[m.group(2).lower()] if m.group(2) else 1024**2)
28
+
29
+
30
+ class SparkClient:
31
+ def __init__(self, base_url: str, fetch=http_json):
32
+ self.base, self.fetch = base_url.rstrip("/"), fetch
33
+
34
+ def _get(self, path: str):
35
+ return self.fetch(f"{self.base}/api/v1{path}", {})
36
+
37
+ def apps(self) -> list[dict]:
38
+ return self._get("/applications") or []
39
+
40
+ def runs(self) -> list[Run]:
41
+ out = []
42
+ for a in self.apps():
43
+ for att in a.get("attempts", [{}]):
44
+ s = (att.get("startTimeEpoch") or 0) / 1000 or ts(att.get("startTime"))
45
+ e = (att.get("endTimeEpoch") or 0) / 1000 or ts(att.get("endTime"))
46
+ done = bool(att.get("completed"))
47
+ state = "running"
48
+ if done:
49
+ try:
50
+ jobs = self._get(f"/applications/{a['id']}/jobs")
51
+ except RuntimeError:
52
+ jobs = []
53
+ state = "failed" if any(str(j.get("status")).upper() == "FAILED" for j in jobs) else "success"
54
+ rid = a["id"] + (f"/{att['attemptId']}" if att.get("attemptId") else "")
55
+ out.append(Run("spark", a.get("name", a["id"]), rid, state, s or None, (e or None) if done else None,
56
+ (e - s) if done and s and e else None, f"{self.base}/history/{a['id']}"))
57
+ return out
58
+
59
+ def samples(self, now: float | None = None):
60
+ from ..monitoring import Sample
61
+ now = now or time.time()
62
+ out = []
63
+ for a in self.apps():
64
+ name = a.get("name", a["id"])
65
+ try:
66
+ props = {k: v for k, v in (self._get(f"/applications/{a['id']}/environment").get("sparkProperties") or [])}
67
+ except (RuntimeError, AttributeError, ValueError):
68
+ props = {}
69
+ for ex in self._get(f"/applications/{a['id']}/allexecutors"):
70
+ eid = ex.get("id", "?")
71
+ maxm = float(ex.get("maxMemory") or 0)
72
+ heap = float((ex.get("peakMemoryMetrics") or {}).get("JVMHeapMemory") or 0)
73
+ limit = _size(props.get("spark.driver.memory" if eid == "driver" else "spark.executor.memory"))
74
+ if heap and limit: # heap real do JVM (pico) contra o limite configurado
75
+ out.append(Sample(now, "spark", f"{name}:{eid}", "memory_bytes", heap, limit))
76
+ else: # storage memory only (not the heap): better than nothing
77
+ out.append(Sample(now, "spark", f"{name}:{eid}", "memory_bytes", float(ex.get("memoryUsed") or 0), maxm or None))
78
+ reason = str(ex.get("removeReason") or "").lower()
79
+ if reason and any(h in reason for h in OOM_HINTS):
80
+ out.append(Sample(now, "spark", f"{name}:{eid}", "oom_killed", 1.0))
81
+ spilled = 0.0
82
+ for st in self._get(f"/applications/{a['id']}/stages"):
83
+ spilled += float(st.get("memoryBytesSpilled") or 0) + float(st.get("diskBytesSpilled") or 0)
84
+ if spilled:
85
+ out.append(Sample(now, "spark", name, "spilled_bytes", spilled))
86
+ return out
87
+
88
+
89
+ class DatabricksJobsClient:
90
+ def __init__(self, host: str | None = None, fetch=http_json):
91
+ self.host = (host or os.environ.get("DATABRICKS_HOST", "")).rstrip("/")
92
+ if self.host and "://" not in self.host:
93
+ self.host = "https://" + self.host
94
+ self.fetch = fetch
95
+
96
+ def _h(self) -> dict:
97
+ t = os.environ.get("DATABRICKS_TOKEN")
98
+ return {"Authorization": f"Bearer {t}"} if t else {}
99
+
100
+ def runs(self, limit: int = 100) -> list[Run]:
101
+ out = []
102
+ for r in self.fetch(f"{self.host}/api/2.1/jobs/runs/list?limit={min(limit, 25)}&expand_tasks=false", self._h()).get("runs", []):
103
+ st = r.get("state") or {}
104
+ life = st.get("life_cycle_state", "")
105
+ if life in ("TERMINATED", "SKIPPED"):
106
+ state = DB_RESULT.get(st.get("result_state", ""), "other") if life == "TERMINATED" else "other"
107
+ elif life == "INTERNAL_ERROR":
108
+ state = "failed"
109
+ elif life in ("PENDING", "QUEUED", "BLOCKED", "WAITING_FOR_RETRY"):
110
+ state = "queued"
111
+ else:
112
+ state = "running"
113
+ s = (r.get("start_time") or 0) / 1000 or None
114
+ e = (r.get("end_time") or 0) / 1000 or None
115
+ dur = (r.get("run_duration") or 0) / 1000 or ((e - s) if s and e else None)
116
+ out.append(Run("databricks", r.get("run_name") or str(r.get("job_id")), str(r.get("run_id")), state, s,
117
+ e if state in ("success", "failed") else None, dur if state in ("success", "failed") else None, r.get("run_page_url", "")))
118
+ return out
intentflow/otel.py ADDED
@@ -0,0 +1,53 @@
1
+ """Exports IntentFlow metrics over OTLP/HTTP (JSON) to an OpenTelemetry Collector: `POST {endpoint}/v1/metrics`.
2
+ Same series as the Prometheus `/metrics`. Env: OTEL_EXPORTER_OTLP_ENDPOINT (default), OTEL_EXPORTER_OTLP_HEADERS (`k=v,k2=v2`).
3
+ """
4
+ from __future__ import annotations
5
+
6
+ import json
7
+ import os
8
+ import time
9
+ import urllib.request
10
+ from .i18n import tr
11
+
12
+
13
+ def _attrs(d: dict) -> list[dict]:
14
+ return [{"key": k, "value": {"stringValue": str(v)}} for k, v in d.items()]
15
+
16
+
17
+ def build_payload(store, now: float | None = None, service: str = "intentflow") -> dict:
18
+ t = str(int((now or time.time()) * 1e9))
19
+ metrics = []
20
+
21
+ def gauge(name: str, desc: str, points: list[tuple[dict, float]]):
22
+ metrics.append({"name": name, "description": desc, "gauge": {"dataPoints": [
23
+ {"attributes": _attrs(a), "timeUnixNano": t, "asDouble": float(v)} for a, v in points]}})
24
+ sev: dict[str, int] = {}
25
+ chk: dict[str, int] = {}
26
+ for f in store.findings("open"):
27
+ sev[f["severity"]] = sev.get(f["severity"], 0) + 1
28
+ c = f.get("check_id") or f.get("check") or "?"
29
+ chk[c] = chk.get(c, 0) + 1
30
+ gauge("intentflow.findings.open", "Open findings by severity", [({"severity": s}, n) for s, n in sorted(sev.items())] or [({"severity": "none"}, 0)])
31
+ gauge("intentflow.findings.open.by_check", "Open findings by check", [({"check": c}, n) for c, n in sorted(chk.items())])
32
+ runs: dict[tuple, int] = {}
33
+ for r in store.runs(1000):
34
+ runs[(r["system"], r["state"])] = runs.get((r["system"], r["state"]), 0) + 1
35
+ gauge("intentflow.runs", "Recent runs by system and state", [({"system": s, "state": st}, n) for (s, st), n in sorted(runs.items())])
36
+ last = store.get_setting("state.last_check") or {}
37
+ gauge("intentflow.check.last_findings", "Findings of the last check", [({}, float(last.get("findings", 0)))])
38
+ return {"resourceMetrics": [{"resource": {"attributes": _attrs({"service.name": service})},
39
+ "scopeMetrics": [{"scope": {"name": "intentflow"}, "metrics": metrics}]}]}
40
+
41
+
42
+ def push(store, endpoint: str | None = None, timeout: float = 10.0) -> int:
43
+ ep = (endpoint or os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT") or "").rstrip("/")
44
+ if not ep:
45
+ raise RuntimeError(tr("pass --endpoint or set OTEL_EXPORTER_OTLP_ENDPOINT"))
46
+ hdr = {"Content-Type": "application/json"}
47
+ for kv in (os.environ.get("OTEL_EXPORTER_OTLP_HEADERS") or "").split(","):
48
+ if "=" in kv:
49
+ k, v = kv.split("=", 1)
50
+ hdr[k.strip()] = v.strip()
51
+ req = urllib.request.Request(f"{ep}/v1/metrics", data=json.dumps(build_payload(store)).encode(), method="POST", headers=hdr)
52
+ with urllib.request.urlopen(req, timeout=timeout) as r:
53
+ return r.status
intentflow/overview.py ADDED
@@ -0,0 +1,123 @@
1
+ """Single view: what is running, what failed, what is being fixed and what was prevented."""
2
+ from __future__ import annotations
3
+
4
+
5
+ import time
6
+ from collections import Counter, defaultdict, OrderedDict
7
+ import threading
8
+
9
+ from . import incidents as inc_mod
10
+ from .checks import REGISTRY, load_all
11
+ from .store import Store
12
+
13
+
14
+ def build(store: Store, window_h: int = 24) -> dict:
15
+ now = time.time()
16
+ load_all()
17
+ disabled = set(store.get_setting("policy.disabled_checks", []) or [])
18
+ findings = store.findings("open")
19
+ sev = Counter(f["severity"] for f in findings)
20
+ runs = store.runs(500)
21
+ by = defaultdict(list)
22
+ for r in runs:
23
+ by[(r["system"], r["pipeline"])].append(r)
24
+ pipelines = []
25
+ for (sys_, pipe), rs in by.items():
26
+ rs.sort(key=lambda r: r["start"] or 0, reverse=True)
27
+ pipelines.append({"system": sys_, "pipeline": pipe, "last_state": rs[0]["state"], "runs": len(rs),
28
+ "failed": sum(r["state"] == "failed" for r in rs), "last_start": rs[0]["start"], "url": rs[0]["url"],
29
+ "last_duration": rs[0]["duration"]})
30
+ pipelines.sort(key=lambda p: (p["last_state"] != "failed", p["last_state"] != "running", p["pipeline"]))
31
+ latest: dict = {}
32
+ for s in store.recent_samples(now - window_h * 3600):
33
+ latest[(s.source, s.scope, s.metric)] = s
34
+ cluster = [{"source": s.source, "scope": s.scope, "metric": s.metric, "value": s.value, "limit": s.limit,
35
+ "ratio": (s.value / s.limit) if s.limit else None} for s in latest.values()]
36
+ cluster.sort(key=lambda c: -(c["ratio"] or 0))
37
+ proj = None
38
+ target = store.get_setting("dbt.target")
39
+ if target:
40
+ try:
41
+ from . import lineage_api # mtime-cached load: the overview is polled every few seconds
42
+ proj = lineage_api.load(target, store.get_setting("dbt.root"), cache=store)[0]
43
+ except Exception:
44
+ proj = None
45
+ incidents = [{"id": i.id, "title": i.title, "severity": i.severity, "findings": len(i.findings), "finding_ids": [f["id"] for f in i.findings], "impacted": len(i.impacted),
46
+ "owners": i.owners} for i in inc_mod.group(findings, proj)]
47
+ props = store.proposals()
48
+ return {
49
+ "generated_at": now,
50
+ "summary": {"open_findings": len(findings), "by_severity": dict(sev),
51
+ "running": sum(p["last_state"] == "running" for p in pipelines),
52
+ "failing": sum(p["last_state"] == "failed" for p in pipelines),
53
+ "fixes_pending": sum(p["status"] in ("pending", "approved", "invalid") for p in props),
54
+ "fixes_applied": sum(p["status"] == "applied" for p in props)},
55
+ "check_stats": [dict(c, suggest_disable=bool(c["fp_rate"] is not None and c["fp_rate"] >= 0.5 and (c["false_positive"] + c["resolved"]) >= 5))
56
+ for c in store.check_stats()],
57
+ "openlineage": store.ol_jobs()[:50],
58
+ "dbt_run": store.get_setting("state.dbt_run"),
59
+ "checks": [{"id": c.id, "title": c.title, "stage": c.stage, "cost": c.cost, "enabled": c.id not in disabled}
60
+ for c in sorted(REGISTRY.values(), key=lambda c: c.id)],
61
+ "incidents": incidents[:50], "findings": findings[:200], "pipelines": pipelines, "cluster": cluster[:50],
62
+ "proposals": [{k: v for k, v in p.items() if k not in _HIDDEN_PROPOSAL_KEYS} | {"changes": [{"file": c["file"], "diff": c["diff"]} for c in p["changes"]]}
63
+ for p in props[:50]],
64
+ "audit": store.audit_log(limit=30),
65
+ }
66
+
67
+
68
+ # raw backups hold whole original files (outside a viewer's write scope too); the diff is what the UI needs
69
+ _HIDDEN_PROPOSAL_KEYS = {"backup", "backup_bytes", "project_root", "validation_request"}
70
+
71
+ _CACHE: OrderedDict = OrderedDict()
72
+ _CACHE_GUARD = threading.Lock()
73
+ _CACHE_LOCKS: dict[str, list] = {} # lock + active/waiting references; the entry is removed when idle
74
+ _CACHE_LIMIT = 128
75
+
76
+
77
+ def _signature(store: Store):
78
+ import os
79
+ key = store.path
80
+ if store.backend == "sqlite" and os.path.exists(key):
81
+ files = (key, key + "-wal")
82
+ return tuple((os.stat(f).st_mtime_ns, os.stat(f).st_size) if os.path.exists(f) else (0, 0) for f in files)
83
+ c = store.con
84
+ return (tuple(c.execute("select count(*), coalesce(max(last_seen), 0) from findings").fetchone()),
85
+ tuple(c.execute("select count(*), coalesce(max(ts), 0) from audit").fetchone()),
86
+ tuple(c.execute("select count(*), coalesce(max(updated), 0) from proposals").fetchone()),
87
+ tuple(c.execute("select count(*), coalesce(max(\"end\"), 0) from runs").fetchone()),
88
+ tuple(c.execute("select count(*), coalesce(max(ts), 0) from samples").fetchone()),
89
+ tuple(c.execute("select count(*), coalesce(max(updated), 0) from settings").fetchone()))
90
+
91
+
92
+ def build_cached(store: Store, ttl: float = 2.0) -> dict:
93
+ """Short cache with one build per store: keeps dozens of requests from rebuilding the view at the same time."""
94
+ key = str(store.path)
95
+ with _CACHE_GUARD:
96
+ slot = _CACHE_LOCKS.get(key)
97
+ if slot is None:
98
+ slot = [threading.Lock(), 0]
99
+ _CACHE_LOCKS[key] = slot
100
+ slot[1] += 1
101
+ lock = slot[0]
102
+ try:
103
+ with lock:
104
+ signature = _signature(store)
105
+ now = time.time()
106
+ with _CACHE_GUARD:
107
+ hit = _CACHE.get(key)
108
+ if hit and hit[0] == signature and now - hit[1] < ttl:
109
+ _CACHE.move_to_end(key)
110
+ return hit[2]
111
+ out = build(store)
112
+ signature = _signature(store) # persiste a assinatura mais recente se houve escrita concorrente
113
+ with _CACHE_GUARD:
114
+ _CACHE[key] = (signature, time.time(), out)
115
+ _CACHE.move_to_end(key)
116
+ while len(_CACHE) > _CACHE_LIMIT:
117
+ _CACHE.popitem(last=False)
118
+ return out
119
+ finally:
120
+ with _CACHE_GUARD:
121
+ slot[1] -= 1
122
+ if slot[1] == 0 and _CACHE_LOCKS.get(key) is slot:
123
+ del _CACHE_LOCKS[key]