mirror of
https://github.com/ThearchyHelios/AgentLab.git
synced 2026-11-26 10:33:17 +00:00
数据剖析改成逐表的后台任务:引擎改编排、剖析任务、接口、设置换新键
以前剖析是一次同步长请求,预算按整次算(max_queries 60、max_total_s 120),选 50 张表只做得完前两三张,其余整张记「查询次数用完」;不能停,关掉页面报告就没了,对业务库查了什么无从查。
- data/catalog_profile.py:检查逻辑和 _apply 并入规则原样保留,只换编排。公开的逐表入口 profile_table:先列全检查项(plan_checks,纯函数,范围的 profile_checks、建任务时列的检查项、执行用同一份;遮罩、多列、不在表结构里、指向视图的关系在这里就列成按规则跳过),第一条查询估行数(确知空表整张表跳过),逐项执行、进度回调,整张表结束写目录并和回调在同一次库操作里;停止时做完的项照常写、没做的记 cancelled 保留旧结论。_Runner 拆成整个任务一个的 SourceRunner(只读守卫、单条时限、任务级止损:连续 3 条失败、最近 10 条 7 条超时;最近 6 条 4 条超时提醒;每条查询留痕,SQL 经 normalize_sql 去掉字面量)和每张表一个的 TableBudget(用完只停这张表)。删掉同步的 profile_catalog、挑表前批量估行数(_skip_empty、PROFILE_DEFAULT_TABLES、PROFILE_PROBE_TABLES)和进程内 _RUNNING。设置换成 table_max_queries(1–200,缺省 40)、table_max_s(10–600,缺省 60),旧键 max_queries、max_total_s 启动时从库里删掉(migrate_settings,不折算:旧值按整次算,含义不同),保存时只摘掉不报错(without_legacy)。表助手的 run_query 和起草时核对有效记录条件改走单条查询入口 run_single_query,行为不变。
- data/catalog_profile_jobs.py:剖析任务的建(selected / needed / all 三种范围,排序同前:有待核实关系的在前、使用次数、表结构顺序;挑出 0 张 ProfileNothing)、排队(和同源起草按建立先后串行,waiting_for)、执行(每张表开始前重读数据源:停用或关掉剖析就停下;遮罩按最新设置)、停止、重试、启动标中断不续跑、保留最近 50 个结束的任务(某张表最近一次剖析所在的不删)、last_profile / profile_due 的查询、任务和逐表的接口形状。
- api/catalog.py:加 /profile-jobs(建、active、latest、{job_id}、tasks/{seq}、cancel、retry),登记在 /{table} 前面;删掉 POST /catalog/profile;清单每行加 last_profile、profile_due、profile_due_reason、profile_checks,顶层加 active_profile_job;单表加 last_profile;导入目录、同步起草遇到剖析任务 409 profile_busy。api/coded.py 加 profile_nothing、catalog_profile_finished;api/datasources.py 保存时摘掉旧键;main.py 启动时标中断加设置迁移,关停时停掉进行中的剖析。
- 测试:test_catalog_profile.py、test_catalog_profile_units.py、test_catalog_semantics.py 里打同步接口和旧设置键的改走任务和新键,检查逻辑的断言保留;同步接口的整次总量上限一条改成逐表次数、逐表时长两条。
This commit is contained in:
+178
-81
@@ -8,12 +8,17 @@
|
||||
- POST /catalog/{table}/patch 保存目录修改提案(乐观锁),记为人工确认
|
||||
- GET /catalog/{table}/impact 影响面:引用这张表的已发布、受管模板(data/catalog_impact.py)
|
||||
- POST /catalog/draft 同步起草(注释、外键、命名推断,可选模型)。界面改用下面的后台起草任务,这个留着;
|
||||
和后台任务双向互斥:同一个源有排队或进行中的后台任务(或正在同步起草)时 409
|
||||
catalog_draft_busy,同步起草期间建任务、重试、导入也是 409
|
||||
同一个源有排队或进行中的起草任务(或正在同步起草)时 409 catalog_draft_busy,有剖析任务时
|
||||
409 profile_busy;同步起草期间建起草任务、重试、导入也是 409,新建的剖析任务排在它后面
|
||||
- PUT /catalog/guidance 数据源级的起草要求(使用者补充的背景和要求,起草时交给模型)
|
||||
- POST /catalog/draft-jobs 建后台起草任务(202);GET /draft-jobs/active、/latest、/{job_id} 读任务;
|
||||
POST /draft-jobs/{job_id}/cancel 停止,/retry 只重试没写好的表(data/catalog_jobs.py)
|
||||
- POST /catalog/profile 同步剖析:对业务库发少量只读查询,核对关系、取码值候选(data/catalog_profile.py)
|
||||
POST /draft-jobs/{job_id}/cancel 停止,/retry 只重试没写好的表(data/catalog_jobs.py)。
|
||||
同源有剖析任务时照建,排在它后面(waiting_for)
|
||||
- POST /catalog/profile-jobs 建后台剖析任务(202):对业务库逐表发少量只读查询,核对关系、取码值候选、提议业务日期
|
||||
(data/catalog_profile_jobs.py,引擎在 data/catalog_profile.py);GET /profile-jobs/active、
|
||||
/latest、/{job_id} 读任务,/{job_id}/tasks/{seq} 读一张表的明细(检查项、发现、发过的查询);
|
||||
POST /profile-jobs/{job_id}/cancel 停止,/retry 只重试没做完的表。同源有起草任务时照建,
|
||||
排在它后面(waiting_for)
|
||||
- GET /catalog/review-queue 审阅队列:推断的项按使用次数、风险、来源排好;POST /catalog/review/batch 批量审阅,
|
||||
GET /catalog/review-progress 审阅进度,GET /catalog/{table}/usage 用过这张表的运行
|
||||
(data/catalog_review.py)
|
||||
@@ -23,8 +28,9 @@
|
||||
(data/catalog_assistant.py)
|
||||
|
||||
规则都在 data/catalog.py,这里只做取源、转换形状和把异常翻成状态码:版本不符 409,结构不合规、审阅路径
|
||||
不对 422,源或表不存在 404。所有写操作记录请求头 X-Actor 的署名(自报、未认证)。剖析没开启、正在剖析 409。
|
||||
起草任务的 409 带机读码(api/coded.py):同一个源已有排队或进行中的任务、起草模型用不了、要停止的任务已经结束。
|
||||
不对 422,源或表不存在 404。所有写操作记下署名(api/deps.actor_of:开了登录是认证过的用户名,否则请求头 X-Actor 的自报)。
|
||||
起草、剖析任务的 409 带机读码(api/coded.py):同一个源已有排队或进行中的同种任务、起草模型用不了、剖析没开启、按范围
|
||||
挑不出表、要停止的任务已经结束。
|
||||
|
||||
上传表格的源按当前快照的表结构回答(table_versions.resolve_source),和查询实际用的库是同一个版本。
|
||||
"""
|
||||
@@ -38,10 +44,10 @@ from pydantic import BaseModel, Field, ValidationError
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.api.coded import (
|
||||
CATALOG_DRAFT_BUSY, CATALOG_DRAFT_FINISHED, CATALOG_DRAFT_MODEL_UNAVAILABLE, PROFILE_BUSY, SCHEMA_MISSING,
|
||||
SNAPSHOT_TAMPERED, CodedHTTPException,
|
||||
CATALOG_DRAFT_BUSY, CATALOG_DRAFT_FINISHED, CATALOG_DRAFT_MODEL_UNAVAILABLE, CATALOG_PROFILE_FINISHED, PROFILE_BUSY,
|
||||
PROFILE_NOTHING, SCHEMA_MISSING, SNAPSHOT_TAMPERED, CodedHTTPException,
|
||||
)
|
||||
from app.api.runs import actor_of
|
||||
from app.api.deps import actor_of
|
||||
from app.data import catalog, catalog_impact, catalog_jobs, catalog_profile, catalog_profile_jobs, introspect
|
||||
from app.data import table_versions
|
||||
from app.data import catalog_assistant, catalog_review, catalog_transfer
|
||||
@@ -103,9 +109,11 @@ GUIDANCE_MISSING = "请求里要写起草要求(guidance 一项,一段文字
|
||||
GUIDANCE_NOT_TEXT = "起草要求要是一段文字(要清除起草要求请传空串)"
|
||||
|
||||
|
||||
class CatalogProfileIn(BaseModel):
|
||||
#: 要剖析的表;不给或为空时按使用次数取前 10 张目录里有待核实关系的表
|
||||
tables: list[str] | None = Field(default=None, max_length=200)
|
||||
class ProfileJobIn(BaseModel):
|
||||
#: 要剖析的表(范围 selected,按给的顺序去重);最多 500 张(超了 422,说明是中文)
|
||||
tables: list[str] | None = None
|
||||
#: 不指定表时的范围:needed 需要剖析的表(缺省)、all 全部表(都不含视图、没有可剖析的项的表)
|
||||
scope: Literal["needed", "all"] | None = None
|
||||
|
||||
|
||||
async def _resolved(session: AsyncSession, source_id: str) -> tuple[DataSource, Any]:
|
||||
@@ -135,7 +143,8 @@ def _item_value(notes: dict[str, Any], name: str) -> tuple[Any, str | None]:
|
||||
|
||||
|
||||
def _summary_row(name: str, meta: dict[str, Any] | None, entry: catalog.CatalogEntry | None,
|
||||
usage: int, last_draft: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
usage: int, last_draft: dict[str, Any] | None = None,
|
||||
profiling: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
notes = entry.notes if entry else {}
|
||||
label, label_status = _item_value(notes, "label")
|
||||
kind, _ = _item_value(notes, "kind")
|
||||
@@ -158,9 +167,20 @@ def _summary_row(name: str, meta: dict[str, Any] | None, entry: catalog.CatalogE
|
||||
# 这张表最近一次起草任务里的那一项:{status, job_id, finished_at, error, model_error, blank_columns},没起草过
|
||||
# 是 null
|
||||
"last_draft": last_draft,
|
||||
# 剖析:最近一次剖析(CatalogLastProfile,没剖析过是 null)、要不要剖析和为什么、按当前目录和表结构要做几项检查
|
||||
**(profiling or {"last_profile": None, "profile_due": False, "profile_due_reason": None, "profile_checks": 0}),
|
||||
}
|
||||
|
||||
|
||||
def _profiling(name: str, meta: dict[str, Any] | None, entry: catalog.CatalogEntry | None, *,
|
||||
tables: dict[str, Any], masked: set[str], last: dict[str, Any] | None) -> dict[str, Any]:
|
||||
notes = entry.notes if entry else {}
|
||||
checks = catalog_profile.profile_checks(name, meta, notes, tables=tables, masked=masked)
|
||||
reason = catalog_profile_jobs.due_reason(meta, notes, last, checks)
|
||||
return {"last_profile": catalog_profile_jobs.public_last(last), "profile_due": reason is not None,
|
||||
"profile_due_reason": reason, "profile_checks": checks}
|
||||
|
||||
|
||||
def _structure(meta: dict[str, Any]) -> dict[str, Any]:
|
||||
return {
|
||||
"qualified": meta.get("qualified"),
|
||||
@@ -189,6 +209,9 @@ async def _detail(session: AsyncSession, source: Any, table: str, entry: catalog
|
||||
"structure": _structure(meta) if meta is not None else None,
|
||||
"system_notes": catalog.system_notes_source(source),
|
||||
"usage": usage,
|
||||
# 这张表最近一次剖析(CatalogProfileTaskDetail:检查项、发现、跳过的项、日期范围、发过的查询);任务还在进行就是
|
||||
# 进行中的状态;没剖析过是 null
|
||||
"last_profile": await catalog_profile_jobs.last_detail(session, source.id, table),
|
||||
}
|
||||
|
||||
|
||||
@@ -224,11 +247,17 @@ async def list_catalog(source_id: str, session: AsyncSession = Depends(get_sessi
|
||||
entries = await catalog.read_catalog(session, source.id)
|
||||
usage = await catalog.table_usage(session, source)
|
||||
drafts = await catalog_jobs.last_drafts(session, source.id)
|
||||
lasts = await catalog_profile_jobs.last_profiles(session, source.id)
|
||||
masked = catalog_profile.masked_of(row.options)
|
||||
|
||||
def profiling(name: str, meta: dict[str, Any] | None) -> dict[str, Any]:
|
||||
return _profiling(name, meta, entries.get(name), tables=tables, masked=masked, last=lasts.get(name))
|
||||
|
||||
order = {name: i for i, name in enumerate(tables)}
|
||||
rows = [_summary_row(name, meta, entries.get(name), usage.get(name, 0), drafts.get(name))
|
||||
rows = [_summary_row(name, meta, entries.get(name), usage.get(name, 0), drafts.get(name), profiling(name, meta))
|
||||
for name, meta in tables.items()]
|
||||
rows.sort(key=lambda r: (-r["usage"], order[r["table_name"]]))
|
||||
rows += [_summary_row(name, None, entry, 0, drafts.get(name))
|
||||
rows += [_summary_row(name, None, entry, 0, drafts.get(name), profiling(name, None))
|
||||
for name, entry in sorted(entries.items()) if name not in tables]
|
||||
return {
|
||||
"tables": rows,
|
||||
@@ -239,8 +268,11 @@ async def list_catalog(source_id: str, session: AsyncSession = Depends(get_sessi
|
||||
"schema_total": max(_int(cache.get("total")), len(tables)),
|
||||
# 数据源级的起草要求(没有是 null)
|
||||
"guidance": catalog_jobs.guidance_of(row),
|
||||
# 排队或进行中的起草任务 {id, status, total, done},界面据此显示进度;没有是 null
|
||||
# 排队或进行中的起草任务 {id, status, total, done, waiting_for},界面据此显示进度;没有是 null
|
||||
"active_job": await catalog_jobs.job_brief(session, await catalog_jobs.active_job(session, source.id)),
|
||||
# 排队或进行中的剖析任务 {id, status, total, done, waiting_for};没有是 null
|
||||
"active_profile_job": await catalog_profile_jobs.job_brief(
|
||||
session, await catalog_profile_jobs.active_job(session, source.id)),
|
||||
}
|
||||
|
||||
|
||||
@@ -331,6 +363,136 @@ async def import_catalog(source_id: str, payload: CatalogImportIn, x_actor: str
|
||||
return report.as_dict()
|
||||
|
||||
|
||||
# ---- 后台剖析任务(同样登记在 GET /catalog/{table} 前面:active、latest 要先于 /profile-jobs/{job_id})
|
||||
|
||||
|
||||
async def _profile_source(session: AsyncSession, source_id: str) -> tuple[DataSource, Any]:
|
||||
"""建剖析任务、重试之前的几道门,409 都带机读码(界面按它分情况给下一步,不从原话里认):未开启 profile_disabled、
|
||||
数据源停用 datasource_inactive、快照登记被改动 snapshot_tampered、没有表结构 schema_missing。返回 (数据源记录,
|
||||
读表结构用的源)。"""
|
||||
row = await _source_row(session, source_id)
|
||||
try:
|
||||
catalog_profile.ensure_enabled(row)
|
||||
except catalog_profile.ProfileDisabled as e:
|
||||
raise CodedHTTPException(409, str(e), e.code) from e
|
||||
try:
|
||||
source = await table_versions.resolve_source(session, row)
|
||||
except SnapshotTampered as e: # 快照清单对不上(SnapshotManifestMismatch 同时是 SnapshotMissing)
|
||||
raise CodedHTTPException(409, str(e), SNAPSHOT_TAMPERED) from e
|
||||
except table_versions.SnapshotMissing as e:
|
||||
raise HTTPException(409, str(e)) from e
|
||||
cache = source.schema_cache or {}
|
||||
if not cache.get("tables"):
|
||||
raise CodedHTTPException(409, f"{introspect.why_empty(cache)},无法进行数据剖析。请先在数据源卡片上点「探查结构」",
|
||||
SCHEMA_MISSING)
|
||||
return row, source
|
||||
|
||||
|
||||
async def _start_profile(session: AsyncSession, row: DataSource, source: Any, *, tables: list[str] | None,
|
||||
scope: str, actor: str | None, retry_of: str | None = None) -> dict[str, Any]:
|
||||
try:
|
||||
job, tasks = await catalog_profile_jobs.create_job(
|
||||
session, row, source, tables=tables, scope=scope, settings=catalog_profile.ensure_enabled(row),
|
||||
actor=actor, retry_of=retry_of)
|
||||
except catalog_profile_jobs.ProfileBusy as e:
|
||||
raise CodedHTTPException(409, str(e), PROFILE_BUSY) from e
|
||||
except catalog_profile_jobs.ProfileNothing as e:
|
||||
raise CodedHTTPException(409, str(e), PROFILE_NOTHING) from e
|
||||
catalog_profile_jobs.manager.start(job.id)
|
||||
return {"job": catalog_profile_jobs.job_dict(job, tasks,
|
||||
waiting_for=await catalog_profile_jobs.waiting_for(session, job))}
|
||||
|
||||
|
||||
@router.post("/{source_id}/catalog/profile-jobs", status_code=202)
|
||||
async def create_profile_job(source_id: str, payload: ProfileJobIn, x_actor: str | None = Header(default=None),
|
||||
session: AsyncSession = Depends(get_session)) -> dict[str, Any]:
|
||||
"""建后台剖析任务,马上返回(202,任务是排队中)。tables 非空时范围是 selected(表结构里没有、视图、没有可剖析的项照样
|
||||
建进任务、状态 skipped),否则按 scope(缺省 needed)挑。同源有排队或进行中的剖析任务 409 profile_busy(说清进行到第几张;
|
||||
界面改去 GET /profile-jobs/active 显示那一个),按范围挑出 0 张表 409 profile_nothing;同源有起草任务时照建,排在它后面
|
||||
(waiting_for = "draft"),起草结束后自动开始。"""
|
||||
if payload.tables and len(payload.tables) > catalog_profile_jobs.MAX_TABLES:
|
||||
raise HTTPException(422, f"一次最多剖析 {catalog_profile_jobs.MAX_TABLES} 张表,当前 {len(payload.tables)} 张,"
|
||||
"请分几次剖析")
|
||||
row, source = await _profile_source(session, source_id)
|
||||
tables = [str(t) for t in payload.tables] if payload.tables else None
|
||||
scope = "selected" if tables else (payload.scope or "needed")
|
||||
return await _start_profile(session, row, source, tables=tables, scope=scope, actor=actor_of(x_actor))
|
||||
|
||||
|
||||
@router.get("/{source_id}/catalog/profile-jobs/active")
|
||||
async def active_profile_job(source_id: str, session: AsyncSession = Depends(get_session)) -> dict[str, Any]:
|
||||
"""排队或进行中的那个剖析任务,没有是 null。"""
|
||||
row = await _source_row(session, source_id)
|
||||
return {"job": await catalog_profile_jobs.job_out(session, await catalog_profile_jobs.active_job(session, row.id))}
|
||||
|
||||
|
||||
@router.get("/{source_id}/catalog/profile-jobs/latest")
|
||||
async def latest_profile_job(source_id: str, session: AsyncSession = Depends(get_session)) -> dict[str, Any]:
|
||||
"""最近建的一个剖析任务(任何状态),没有是 null。"""
|
||||
row = await _source_row(session, source_id)
|
||||
return {"job": await catalog_profile_jobs.job_out(session, await catalog_profile_jobs.latest_job(session, row.id))}
|
||||
|
||||
|
||||
async def _profile_job_or_404(session: AsyncSession, source_id: str, job_id: str) -> tuple[DataSource, Any]:
|
||||
row = await _source_row(session, source_id)
|
||||
job = await catalog_profile_jobs.load(session, row.id, job_id)
|
||||
if job is None:
|
||||
raise HTTPException(404, "剖析任务不存在,可能属于别的数据源,已随数据源删除,或者超过保留数被清理了")
|
||||
return row, job
|
||||
|
||||
|
||||
@router.get("/{source_id}/catalog/profile-jobs/{job_id}")
|
||||
async def get_profile_job(source_id: str, job_id: str,
|
||||
session: AsyncSession = Depends(get_session)) -> dict[str, Any]:
|
||||
_, job = await _profile_job_or_404(session, source_id, job_id)
|
||||
return {"job": await catalog_profile_jobs.job_out(session, job)}
|
||||
|
||||
|
||||
@router.get("/{source_id}/catalog/profile-jobs/{job_id}/tasks/{seq}")
|
||||
async def get_profile_task(source_id: str, job_id: str, seq: int,
|
||||
session: AsyncSession = Depends(get_session)) -> dict[str, Any]:
|
||||
"""剖析任务里的一张表(按剖析顺序的序号):检查项、发现、跳过的项、日期范围、发过的查询(字面量已换成「?」)。"""
|
||||
_, job = await _profile_job_or_404(session, source_id, job_id)
|
||||
task = await catalog_profile_jobs.load_task(session, job, seq)
|
||||
if task is None:
|
||||
raise HTTPException(404, "这次剖析里没有这一张表")
|
||||
return {"task": catalog_profile_jobs.task_detail(job, task)}
|
||||
|
||||
|
||||
@router.post("/{source_id}/catalog/profile-jobs/{job_id}/cancel")
|
||||
async def cancel_profile_job(source_id: str, job_id: str,
|
||||
session: AsyncSession = Depends(get_session)) -> dict[str, Any]:
|
||||
"""停止:排队的直接停止;进行中的不再等正在跑的那条查询(数据库按单条时限截止它),这张表做完的项照常写进目录、没做的
|
||||
保留旧结论,后面的表记停止。已经结束的 409 catalog_profile_finished。返回停止之后的任务。"""
|
||||
row, job = await _profile_job_or_404(session, source_id, job_id)
|
||||
owner = row.id
|
||||
try:
|
||||
await catalog_profile_jobs.cancel(session, job)
|
||||
except catalog_profile_jobs.ProfileFinished as e:
|
||||
raise CodedHTTPException(409, str(e), CATALOG_PROFILE_FINISHED) from e
|
||||
session.expire_all() # 后台在别的会话里收的尾:重新读
|
||||
return {"job": await catalog_profile_jobs.job_out(session, await catalog_profile_jobs.load(session, owner, job_id))}
|
||||
|
||||
|
||||
@router.post("/{source_id}/catalog/profile-jobs/{job_id}/retry", status_code=202)
|
||||
async def retry_profile_job(source_id: str, job_id: str, x_actor: str | None = Header(default=None),
|
||||
session: AsyncSession = Depends(get_session)) -> dict[str, Any]:
|
||||
"""重试:新任务,只含原任务里 failed、partial、cancelled 的表(按原来的顺序),范围 selected,设置取数据源当前的。
|
||||
同源有排队或进行中的剖析任务 409 profile_busy;没有可重试的表 422;开始不了的几种情况同建任务。"""
|
||||
_, old = await _profile_job_or_404(session, source_id, job_id)
|
||||
row, source = await _profile_source(session, source_id)
|
||||
try:
|
||||
await catalog_profile_jobs.ensure_free(session, row)
|
||||
except catalog_profile_jobs.ProfileBusy as e:
|
||||
raise CodedHTTPException(409, str(e), PROFILE_BUSY) from e
|
||||
try:
|
||||
tables = await catalog_profile_jobs.retry_tables(session, old)
|
||||
except catalog_profile_jobs.NothingToRetry as e:
|
||||
raise HTTPException(422, str(e)) from e
|
||||
return await _start_profile(session, row, source, tables=tables, scope="selected", actor=actor_of(x_actor),
|
||||
retry_of=old.id)
|
||||
|
||||
|
||||
@router.get("/{source_id}/catalog/{table}")
|
||||
async def get_catalog_table(source_id: str, table: str,
|
||||
session: AsyncSession = Depends(get_session)) -> dict[str, Any]:
|
||||
@@ -545,71 +707,6 @@ async def draft_catalog(source_id: str, payload: CatalogDraftIn,
|
||||
}
|
||||
|
||||
|
||||
def _profile_table_out(t: catalog_profile.TableProfile) -> dict[str, Any]:
|
||||
return {
|
||||
"table_name": t.table,
|
||||
"queries": t.queries,
|
||||
"row_estimate": t.row_estimate.to_dict() if t.row_estimate else None,
|
||||
"findings": t.findings,
|
||||
"skipped": [s.to_dict() for s in t.skipped],
|
||||
"date_ranges": t.date_ranges,
|
||||
"added": t.added,
|
||||
"updated": t.updated,
|
||||
"removed": t.removed,
|
||||
"version": t.version,
|
||||
"error": t.error,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/{source_id}/catalog/profile")
|
||||
async def profile_catalog_tables(source_id: str, payload: CatalogProfileIn,
|
||||
x_actor: str | None = Header(default=None),
|
||||
session: AsyncSession = Depends(get_session)) -> dict[str, Any]:
|
||||
"""同步剖析。返回每张表用了几条查询、写进目录的发现、跳过了什么及原因。
|
||||
|
||||
默认关闭:数据源设置里没开启数据剖析、数据源停用,409;同一个数据源已经在剖析,409。
|
||||
"""
|
||||
row, source = await _resolved(session, source_id)
|
||||
# 409 都带机读码(api/coded.py),界面按它分五种情况给下一步,不从原话里认
|
||||
try:
|
||||
catalog_profile.ensure_enabled(row)
|
||||
except catalog_profile.ProfileDisabled as e:
|
||||
raise CodedHTTPException(409, str(e), e.code) from e
|
||||
cache = source.schema_cache or {}
|
||||
if not cache.get("tables"):
|
||||
raise CodedHTTPException(409, f"{introspect.why_empty(cache)},无法进行数据剖析。请先在数据源卡片上点「探查结构」",
|
||||
SCHEMA_MISSING)
|
||||
actor = actor_of(x_actor)
|
||||
try:
|
||||
report = await catalog_profile.profile_catalog(session, row, source, tables=payload.tables or None,
|
||||
actor=actor)
|
||||
except catalog_profile.ProfileDisabled as e:
|
||||
raise CodedHTTPException(409, str(e), e.code) from e
|
||||
except catalog_profile.ProfileBusy as e:
|
||||
raise CodedHTTPException(409, str(e), PROFILE_BUSY) from e
|
||||
except SnapshotTampered as e:
|
||||
raise CodedHTTPException(409, str(e), SNAPSHOT_TAMPERED) from e
|
||||
rows = [_profile_table_out(t) for t in report.tables]
|
||||
note = None
|
||||
if not rows and report.empty_tables:
|
||||
note = (f"有待核对关联关系的 {len(report.empty_tables)} 张表都是空表,没有可以核实的数据。"
|
||||
"请在数据有了之后再剖析,或指定要剖析的表")
|
||||
elif not rows:
|
||||
note = "目录里还没有待核实的关联关系,请先起草数据目录,或指定要剖析的表"
|
||||
return {
|
||||
"profiled_at": report.profiled_at,
|
||||
"actor": actor,
|
||||
"settings": report.settings.to_dict(),
|
||||
"queries_used": report.queries_used,
|
||||
"stopped": report.stopped,
|
||||
"tables": rows,
|
||||
"total": {k: sum(r[k] for r in rows) for k in ("added", "updated", "removed")},
|
||||
# 不指定表时挑表途中确知是空表、跳过了的表(指定了表时总是空列表)
|
||||
"empty_tables": report.empty_tables,
|
||||
"note": note,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/{source_id}/catalog/{table}/review")
|
||||
async def review_catalog_item(source_id: str, table: str, payload: CatalogReviewIn,
|
||||
x_actor: str | None = Header(default=None),
|
||||
|
||||
@@ -11,14 +11,18 @@ from fastapi.responses import JSONResponse
|
||||
#: 限定的数据源一个都不在了(删了或停用了),见 copilot._sources
|
||||
DATASOURCE_SCOPE_EMPTY = "datasource_scope_empty"
|
||||
|
||||
#: 保存数据源时剖析设置不合规(422):field 是出错的那一项(max_queries……),说不清是哪一项时没有 field
|
||||
#: 保存数据源时剖析设置不合规(422):field 是出错的那一项(table_max_queries……),说不清是哪一项时没有 field
|
||||
PROFILE_SETTINGS_INVALID = "profile_settings_invalid"
|
||||
#: 剖析开始不了(409)的五种情况,见 api/catalog.profile_catalog_tables
|
||||
#: 剖析任务开始不了(409,api/catalog.create_profile_job):未开启、数据源停用、没有表结构、快照被改动、这个源已有排队或
|
||||
#: 进行中的剖析任务(导入目录、同步起草遇到剖析任务也是它)、按范围挑出 0 张表
|
||||
PROFILE_DISABLED = "profile_disabled"
|
||||
DATASOURCE_INACTIVE = "datasource_inactive"
|
||||
SCHEMA_MISSING = "schema_missing"
|
||||
PROFILE_BUSY = "profile_busy"
|
||||
SNAPSHOT_TAMPERED = "snapshot_tampered"
|
||||
PROFILE_NOTHING = "profile_nothing"
|
||||
#: 要停止的剖析任务已经结束了(409)
|
||||
CATALOG_PROFILE_FINISHED = "catalog_profile_finished"
|
||||
#: 数据目录的后台起草任务(api/catalog.py 的 /catalog/draft-jobs):同一个源已有排队或进行中的任务(409,界面改去
|
||||
#: GET /draft-jobs/active 显示那一个)、起草模型用不了(409,不建任务)、要停止的任务已经结束了(409)
|
||||
CATALOG_DRAFT_BUSY = "catalog_draft_busy"
|
||||
|
||||
@@ -23,7 +23,7 @@ from app.core.errors import AUTH, NETWORK, TIMEOUT, classify, explain, raw
|
||||
from app.core.config import settings
|
||||
from app.core.crypto import encrypt, mask
|
||||
from app.data import catalog as data_catalog
|
||||
from app.data.catalog_profile import profile_settings_rejection
|
||||
from app.data.catalog_profile import profile_settings_rejection, without_legacy
|
||||
from app.data import introspect as introspect_mod
|
||||
from app.data import table_versions
|
||||
from app.data.engine import (
|
||||
@@ -465,12 +465,13 @@ async def create_source(
|
||||
)).scalar_one_or_none()
|
||||
if exists:
|
||||
raise HTTPException(409, f"已存在名为「{payload.name}」的数据源,请换一个标识")
|
||||
_refuse_bad_options(payload.options)
|
||||
options = without_legacy(payload.options) or {}
|
||||
_refuse_bad_options(options)
|
||||
_refuse_reserved(payload.kind, payload.database)
|
||||
|
||||
row = DataSource(
|
||||
**payload.model_dump(exclude={"password", "options"}),
|
||||
options=_with_managed(payload.options, None),
|
||||
options=_with_managed(options, None),
|
||||
password=encrypt(payload.password),
|
||||
)
|
||||
_settle_oracle(row, None, None)
|
||||
@@ -519,6 +520,8 @@ async def update_source(
|
||||
# 升级前就指向上传目录的手工源:启动时已强制只读(table_versions.startup),不许再改回可写
|
||||
raise HTTPException(422, _UPLOAD_DIR_READONLY)
|
||||
if "options" in data:
|
||||
# 剖析设置里还带着以前按整次剖析算的预算(老页面提交的):只摘掉,不报错(catalog_profile.LEGACY_KEYS)
|
||||
data["options"] = without_legacy(data["options"])
|
||||
_refuse_bad_options(data["options"])
|
||||
data["options"] = _with_managed(data["options"] or {}, row.options)
|
||||
if "password" in data:
|
||||
|
||||
Reference in New Issue
Block a user