pipeline.py
17.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
"""数据管道:把对象骨架从业务库同步进来,并按关系物化出关系边。
业务数据永远实时查业务库 —— 这里只同步「骨架」:
- 主键、显示名:问句里点名具体对象时做链接、全局搜对象;
- 关系键列:按关系的 join 绑定物化成 `otlg_link_edge`,多跳遍历 / 影响分析只走这张表;
- 维度属性:遍历结果按数据范围过滤、按维度分组。
跨表多跳 JOIN 在业务库上实时做既慢、跨数据源还做不了;骨架表上 BFS 很便宜。
代价是有同步延迟,所以每个结果都带「数据截至」时间。
"""
from __future__ import annotations
import datetime as dt
import logging
import time
from typing import Any
from fastapi import HTTPException
from sqlalchemy import delete, func, insert, select
from ..core import db as core_db
from ..core import identity
from ..core.dbx import iso, jdump, jload, new_id, now, session
from ..governance import audit
from . import objects, service
from .models import InstanceCache, LinkEdge, Pipeline
from .sqlutil import ident
log = logging.getLogger(__name__)
SCHEDULES = ("manual", "hourly", "daily")
MAX_EDGES = 500_000
_BATCH = 2000 # 批量写入:远程元数据库上逐行 INSERT 太慢
def _ws() -> str:
return identity.current().workspace
def _type_id(ref: str) -> str:
try:
return objects.object_type(ref)["id"]
except HTTPException:
return ""
def _links_of(ot_id: str) -> list[tuple[dict, dict, str, str]]:
"""涉及这个对象类型的已发布关系:(关系, join 绑定, from 类型 id, to 类型 id)。"""
out = []
for lt in service.rt_by_kind("link_type"):
jb = service.rt_binding(lt, "join")
if not jb:
continue
spec = lt.get("spec") or {}
f, t = _type_id(spec.get("from_type") or ""), _type_id(spec.get("to_type") or "")
if f and t and ot_id in (f, t):
out.append((lt, jb["ref"], f, t))
return out
def _skeleton_columns(ot: dict, ref: dict) -> tuple[list[str], dict[str, str]]:
"""要同步的列:主键、显示列、所有关系键列、维度属性列。返回 (列, 维度列→属性名)。"""
cols = [ref["key_column"]]
if ref.get("label_column"):
cols.append(ref["label_column"])
for _, j, f, t in _links_of(ot["id"]):
if f == ot["id"]:
cols.append(j["from_column"])
if t == ot["id"]:
cols.append(j["to_column"])
prop_cols: dict[str, str] = {}
for p in (ot.get("spec") or {}).get("properties") or []:
if p.get("is_dimension") or p.get("is_key"):
col = (ref.get("columns") or {}).get(p["name"]) or (ref["key_column"] if p.get("is_key") else "")
if col:
prop_cols[col] = p["name"]
cols.append(col)
return list(dict.fromkeys(cols)), prop_cols
def _parent_labels(ot_id: str, ws: str) -> list[tuple[str, dict[str, str]]]:
"""这个对象通过外键指向的上级对象:[(外键列, {上级主键: 上级显示名})](上级要先同步过)。"""
out = []
with session() as s:
for _, j, f, t in _links_of(ot_id):
if f != ot_id or t == ot_id:
continue
labels = {r.obj_key: r.label for r in s.scalars(select(InstanceCache).where(
InstanceCache.workspace == ws, InstanceCache.concept_id == t)).all()}
out.append((j["from_column"], labels))
return out
def sync_type(type_ref: str, limit: int | None = None) -> dict:
"""同步一个对象类型的骨架,然后重建和它有关的关系边。"""
ot = objects.object_type(type_ref)
b = objects.table_binding(ot)
ref = b["ref"]
limit = int(limit or core_db.get_config("PIPELINE_ROW_LIMIT", "20000") or 20000)
cols, prop_cols = _skeleton_columns(ot, ref)
# 执行器对每条查询都有行数上限(SQL_ROW_LIMIT),按主键排序分页拉,直到拉满 limit 或拉完
from ..text2sql import executor
page = max(1, min(int(executor.limits()[0] or 1000), limit))
names: list[str] = []
rows: list[list[Any]] = []
while len(rows) < limit:
sql = (f"SELECT {', '.join(ident(c) for c in cols)} FROM {ident(ref['table'])} "
f"ORDER BY {ident(ref['key_column'])} LIMIT {page} OFFSET {len(rows)}")
names, chunk = objects._run(b["ds_id"], sql)
rows += chunk
if len(chunk) < page:
break
rows = rows[:limit]
ws = _ws()
at = now()
key_col, label_col = ref["key_column"], ref.get("label_column") or ref["key_column"]
parents = [] if ref.get("label_column") else _parent_labels(ot["id"], ws)
seen: set[str] = set()
batch: list[dict] = []
for row in rows:
raw = dict(zip(names, row))
k = raw.get(key_col)
if k is None or str(k) in seen:
continue
seen.add(str(k))
lab = raw.get(label_col)
if parents:
# 没有名称列的对象(如「仓库 × 商品」的库存行):用它指向的上级对象名称拼一个人看得懂的名字
lab = " · ".join(labels.get(str(raw.get(col)), str(raw.get(col)))
for col, labels in parents if raw.get(col) is not None) or lab
props = {prop_cols[c]: raw.get(c) for c in prop_cols if c in raw}
joins = {c: raw.get(c) for c in cols if c not in (key_col,)}
batch.append({"workspace": ws, "concept_id": ot["id"], "obj_key": str(k)[:255],
"label": str(lab if lab not in (None, "") else k)[:255],
"props_json": jdump({"p": props, "j": joins}), "synced_at": at})
with session() as s:
s.execute(delete(InstanceCache).where(InstanceCache.workspace == ws,
InstanceCache.concept_id == ot["id"]))
for i in range(0, len(batch), _BATCH):
s.execute(insert(InstanceCache), batch[i:i + _BATCH])
s.commit()
edges = sum(rebuild_edges(lt, j, f, t) for lt, j, f, t in _links_of(ot["id"]))
from . import linker
linker.invalidate()
return {"object_type": ot["name"], "rows": len(seen), "edges": edges,
"truncated": len(rows) >= limit, "synced_at": iso(at)}
def _cache_rows(ws: str, type_id: str) -> list[tuple[str, dict]]:
with session() as s:
return [(r.obj_key, jload(r.props_json, {}) or {}) for r in s.scalars(select(InstanceCache).where(
InstanceCache.workspace == ws, InstanceCache.concept_id == type_id)).all()]
def _val(v: Any) -> str | None:
if v is None or v == "":
return None
if isinstance(v, float) and v.is_integer():
v = int(v)
return str(v)
def rebuild_edges(lt: dict, join: dict, from_type: str, to_type: str) -> int:
"""按 join 绑定物化一条关系的所有边:from 表的 from_column = to 表的 to_column。"""
ws = _ws()
def col_value(key: str, props: dict, col: str) -> str | None:
j = props.get("j") or {}
return _val(j[col]) if col in j else key # 不在关系键里的就是主键列本身
to_index: dict[str, list[str]] = {}
for k, p in _cache_rows(ws, to_type):
v = col_value(k, p, join["to_column"])
if v is not None:
to_index.setdefault(v, []).append(k)
edges: list[dict] = []
if to_index:
for k, p in _cache_rows(ws, from_type):
v = col_value(k, p, join["from_column"])
if v is None:
continue
for tk in to_index.get(v, []):
if from_type == to_type and tk == k:
continue
edges.append({"workspace": ws, "link_id": lt["id"], "from_type": from_type, "from_key": k,
"to_type": to_type, "to_key": tk})
if len(edges) >= MAX_EDGES:
log.warning("关系「%s」的边超过 %d 条,已截断", lt["name"], MAX_EDGES)
edges = edges[:MAX_EDGES]
break
with session() as s:
s.execute(delete(LinkEdge).where(LinkEdge.workspace == ws, LinkEdge.link_id == lt["id"]))
for i in range(0, len(edges), _BATCH):
s.execute(insert(LinkEdge), edges[i:i + _BATCH])
s.commit()
return len(edges)
# ---------------- 管道的登记与运行 ----------------
def _dict(p: Pipeline, names: dict[str, str] | None = None) -> dict:
return {"id": p.id, "object_type_id": p.object_type_id,
"object_type": (names or {}).get(p.object_type_id, p.object_type_id),
"schedule": p.schedule, "row_limit": p.row_limit, "enabled": bool(p.enabled),
"status": p.status, "last_rows": p.last_rows, "last_edges": p.last_edges,
"last_error": p.last_error or "", "last_run_at": iso(p.last_run_at),
"last_duration_ms": p.last_duration_ms, "created_at": iso(p.created_at)}
def _type_names() -> dict[str, str]:
return {c["id"]: c["name"] for c in service.list_concepts(kind="object_type")}
def list_pipelines() -> list[dict]:
names = _type_names()
with session() as s:
rows = s.scalars(select(Pipeline).where(Pipeline.workspace == _ws())
.order_by(Pipeline.created_at)).all()
return [_dict(p, names) for p in rows]
def get(pid: str) -> Pipeline:
with session() as s:
p = s.get(Pipeline, pid)
if p is None or p.workspace != _ws():
raise HTTPException(404, "数据管道不存在")
s.expunge(p)
return p
def create(object_type: str, schedule: str = "manual", row_limit: int = 0) -> dict:
ot = objects.object_type(object_type)
objects.table_binding(ot)
if schedule not in SCHEDULES:
raise HTTPException(422, f"调度只能是 {'/'.join(SCHEDULES)}")
with session() as s:
dup = s.scalars(select(Pipeline).where(Pipeline.workspace == _ws(),
Pipeline.object_type_id == ot["id"])).first()
if dup:
raise HTTPException(409, f"「{ot['name']}」已经有数据管道了")
p = Pipeline(id=new_id("pl"), workspace=_ws(), object_type_id=ot["id"], schedule=schedule,
row_limit=int(row_limit or 0), created_by=identity.current().id)
s.add(p)
s.commit()
out = _dict(p, {ot["id"]: ot["name"]})
audit.record("pipeline.create", "pipeline", out["id"], f"新建数据管道「{ot['name']}」({schedule})")
return out
def update(pid: str, *, schedule: str | None = None, row_limit: int | None = None,
enabled: bool | None = None) -> dict:
get(pid)
with session() as s:
p = s.get(Pipeline, pid)
if schedule is not None:
if schedule not in SCHEDULES:
raise HTTPException(422, f"调度只能是 {'/'.join(SCHEDULES)}")
p.schedule = schedule
if row_limit is not None:
p.row_limit = max(0, int(row_limit))
if enabled is not None:
p.enabled = 1 if enabled else 0
s.commit()
return _dict(p, _type_names())
def delete_pipeline(pid: str) -> None:
p = get(pid)
with session() as s:
s.execute(delete(Pipeline).where(Pipeline.id == pid))
s.execute(delete(InstanceCache).where(InstanceCache.workspace == p.workspace,
InstanceCache.concept_id == p.object_type_id))
s.execute(delete(LinkEdge).where(LinkEdge.workspace == p.workspace,
(LinkEdge.from_type == p.object_type_id)
| (LinkEdge.to_type == p.object_type_id)))
s.commit()
audit.record("pipeline.delete", "pipeline", pid, "删除数据管道(骨架与关系边一并清除)")
def run(pid: str) -> dict:
p = get(pid)
started = time.time()
with session() as s:
row = s.get(Pipeline, pid)
row.status = "running"
s.commit()
try:
out = sync_type(p.object_type_id, p.row_limit or None)
status, err = "ok", ""
except HTTPException as e:
out, status, err = {}, "failed", str(e.detail)
except Exception as e: # noqa: BLE001
log.exception("数据管道 %s 运行失败", pid)
out, status, err = {}, "failed", str(e)[:500]
ms = int((time.time() - started) * 1000)
with session() as s:
row = s.get(Pipeline, pid)
row.status = status
row.last_error = err
row.last_run_at = now()
row.last_duration_ms = ms
if status == "ok":
row.last_rows = out["rows"]
row.last_edges = out["edges"]
s.commit()
res = _dict(row, _type_names())
audit.record("pipeline.run", "pipeline", pid,
f"数据管道同步「{res['object_type']}」:"
+ (f"{out['rows']} 个对象、{out['edges']} 条关系边,{ms} ms" if status == "ok" else f"失败:{err}"),
after=out or {"error": err})
return {**res, "result": out}
def ensure_all(schedule: str = "manual") -> dict:
"""给所有已映射、还没有管道的对象类型建管道。"""
have = {p["object_type_id"] for p in list_pipelines()}
created = []
for c in service.list_concepts(kind="object_type"):
if c["id"] in have or not c.get("mapped") or not service.rt_get(c["id"]):
continue
try:
created.append(create(c["id"], schedule)["id"])
except HTTPException:
continue
return {"created": created}
def run_all_events():
"""后台任务:逐条同步,yield 进度。每条都会重建相关的边,所以跑完一轮两端都在的边都齐了。"""
items = [p for p in list_pipelines() if p["enabled"]]
# 上级对象先同步(外键指向别人的少的排前面),下级拼显示名时才取得到上级的名称
ups = {p["object_type_id"]: sum(1 for _, _, f, t in _links_of(p["object_type_id"])
if f == p["object_type_id"] and t != f) for p in items}
items.sort(key=lambda p: ups.get(p["object_type_id"], 0))
ok = 0
for i, p in enumerate(items, 1):
r = run(p["id"])
ok += r["status"] == "ok"
yield {"stage": "pipeline", "progress": int(i / max(1, len(items)) * 100),
"message": f"{r['object_type']}:{'%d 个对象、%d 条边' % (r['last_rows'], r['last_edges']) if r['status'] == 'ok' else r['last_error']}"}
yield {"stage": "done", "progress": 100, "message": f"同步完成 {ok}/{len(items)}",
"result": {"ok": ok, "total": len(items)}}
def run_all() -> dict:
out = list(run_all_events())
return out[-1]["result"]
def status() -> dict:
ws = _ws()
with session() as s:
objs = s.scalar(select(func.count(InstanceCache.id)).where(InstanceCache.workspace == ws)) or 0
edges = s.scalar(select(func.count(LinkEdge.id)).where(LinkEdge.workspace == ws)) or 0
last = s.scalar(select(func.max(InstanceCache.synced_at)).where(InstanceCache.workspace == ws))
return {"objects": int(objs), "edges": int(edges), "synced_at": iso(last)}
def dataset(type_ref: str, q: str = "", limit: int = 50, offset: int = 0) -> dict:
"""本体数据集:浏览某个对象类型已同步的骨架。"""
ot = objects.object_type(type_ref)
ws = _ws()
with session() as s:
stmt = select(InstanceCache).where(InstanceCache.workspace == ws,
InstanceCache.concept_id == ot["id"])
if q:
stmt = stmt.where(InstanceCache.label.like(f"%{q}%") | (InstanceCache.obj_key == q))
total = s.scalar(select(func.count()).select_from(stmt.subquery())) or 0
rows = s.scalars(stmt.order_by(InstanceCache.id).offset(offset).limit(min(limit, 500))).all()
items = [{"key": r.obj_key, "label": r.label, "properties": (jload(r.props_json, {}) or {}).get("p") or {},
"synced_at": iso(r.synced_at)} for r in rows]
return {"object_type": {"id": ot["id"], "name": ot["name"]}, "total": int(total), "items": items}
def reap_stale() -> int:
"""进程重启后,上次没跑完的管道 / 业务建模还标着 running:改成失败,免得界面永远转圈、定时永远跳过。"""
from sqlalchemy import update
from .models import ModelRun
with session() as s:
n = s.execute(update(Pipeline).where(Pipeline.status == "running").values(
status="failed", last_error="服务重启,同步中断")).rowcount or 0
n += s.execute(update(ModelRun).where(ModelRun.status == "running").values(
status="failed", error="服务重启,建模中断,可以重新运行")).rowcount or 0
s.commit()
return n
# ---------------- 定时 ----------------
def _due(p: Pipeline, at: dt.datetime) -> bool:
if not p.enabled or p.schedule == "manual" or p.status == "running":
return False
if p.last_run_at is None:
return True
gap = dt.timedelta(hours=1) if p.schedule == "hourly" else dt.timedelta(days=1)
return at - p.last_run_at >= gap
def tick(at: dt.datetime | None = None) -> list[str]:
at = at or dt.datetime.now()
with session() as s:
items = [(p.id, p.workspace) for p in s.scalars(select(Pipeline)).all() if _due(p, at)]
fired = []
for pid, ws in items:
tok = identity.set_current(identity.Actor(id="system", name="系统 · 数据管道", kind="system",
roles=["admin"], workspace=ws))
try:
run(pid)
fired.append(pid)
except Exception: # noqa: BLE001
log.exception("定时数据管道失败 %s", pid)
finally:
identity.reset(tok)
return fired