409 lines
19 KiB
Python
409 lines
19 KiB
Python
"""外部数据源接口 -- 注册表维护、连通性测试、运行时取数。
|
||
|
||
分成两层的理由和设计字典一样:**改配置要权限,调一次只要登录**(那个人能不能调这个源,
|
||
由源上的 `min_permission` 决定,判据在 `service/fetch.run` 里)。前端永远只跟这一层说话,
|
||
业务系统的地址与密钥不出现在浏览器里。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import re
|
||
|
||
from fastapi import APIRouter, Depends, Query
|
||
from sqlalchemy import select
|
||
from sqlalchemy.orm import Session
|
||
|
||
from .. import models, schemas
|
||
from ..db import get_db
|
||
from ..deps import CurrentUser, current_user, require_permission
|
||
from ..envelope import bad_request, not_found, ok
|
||
from ..service import fetch, presets, processdata
|
||
from ..service.fetch import MAX_RETRIES
|
||
|
||
router = APIRouter(tags=["data-source"])
|
||
|
||
CODE_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
|
||
METHODS = ("GET", "POST", "PUT", "PATCH", "DELETE")
|
||
|
||
#: 可以直接往列上赋的请求字段(请求体是驼峰,Pydantic 已经翻成下划线属性)
|
||
COLUMNS = (
|
||
"name", "system", "kind", "enabled", "provider", "mock_payload",
|
||
"method", "url", "headers", "body_template", "param_meta",
|
||
"auth_type", "auth_username", "items_path", "pick", "map_value", "map_label", "map_extra",
|
||
"src_process", "src_match",
|
||
"timeout_seconds", "retries", "cache_seconds", "rate_limit_qpm", "cooldown_seconds",
|
||
"min_permission", "description",
|
||
"direction", "success_path", "success_value", "message_path", "ref_path", "shadow",
|
||
)
|
||
#: 数值型配置的范围:越界的值与其放过去炸,不如保存的时候就挡住
|
||
LIMITS = {
|
||
"timeout_seconds": (1, 120),
|
||
"retries": (0, MAX_RETRIES),
|
||
"cache_seconds": (0, 86400),
|
||
"rate_limit_qpm": (0, 100000),
|
||
"cooldown_seconds": (0, 3600),
|
||
}
|
||
LABELS = {
|
||
"timeout_seconds": "超时秒数",
|
||
"retries": "重试次数",
|
||
"cache_seconds": "缓存秒数",
|
||
"rate_limit_qpm": "每分钟调用上限",
|
||
"cooldown_seconds": "失败静默秒数",
|
||
}
|
||
|
||
#: provider=process 那份"响应"的固定外壳(见 service/processdata.payload_of / search_payload)
|
||
PROCESS_PICK_ROOT = "data"
|
||
PROCESS_LIST_PATH = "works"
|
||
PROCESS_LIST_VALUE = "id"
|
||
PROCESS_LIST_LABEL = "title"
|
||
|
||
|
||
def _clean(body: schemas.DataSourceBody, db: Session | None = None) -> dict:
|
||
"""把请求体收成能直接往列上赋的形状,顺手把明显不合法的挡在外面。"""
|
||
values = {column: getattr(body, column) for column in COLUMNS}
|
||
values["method"] = str(values["method"] or "POST").upper()
|
||
if values["method"] not in METHODS:
|
||
raise bad_request(f"请求方法只支持 {'、'.join(METHODS)}")
|
||
if values["kind"] not in (models.DataSource.KIND_FETCH, models.DataSource.KIND_SEARCH):
|
||
raise bad_request("数据源类型只支持 fetch(取一个值)或 search(取一个列表)")
|
||
if values["auth_type"] not in models.DataSource.AUTH_TYPES:
|
||
raise bad_request("鉴权方式不支持:" + str(values["auth_type"]))
|
||
if values["provider"] not in models.DataSource.PROVIDERS:
|
||
raise bad_request("取数通道只支持 http(调外部接口)、mock(样例数据)或 process(带出另一个流程的单据)")
|
||
url = str(values["url"] or "").strip()
|
||
if values["provider"] == models.DataSource.PROVIDER_HTTP:
|
||
if not url:
|
||
raise bad_request("接口地址不能为空")
|
||
if not url.lower().startswith(("http://", "https://")):
|
||
raise bad_request("接口地址要以 http:// 或 https:// 开头")
|
||
values["url"] = url
|
||
for column, (floor, ceil) in LIMITS.items():
|
||
value = int(values.get(column) or 0)
|
||
if not floor <= value <= ceil:
|
||
raise bad_request(f"{LABELS[column]}需要在 {floor}-{ceil} 之间")
|
||
values[column] = value
|
||
for column in ("headers", "body_template", "map_extra", "mock_payload", "param_meta"):
|
||
if not isinstance(values[column], dict):
|
||
raise bad_request(f"{column} 得是一个对象")
|
||
# ``param_meta`` 是界面自己的备注与停用行,收个尾:只认这三段,认不出的不收,
|
||
# 免得谁手滑写错键名之后库里越攒越多没人看得懂的段落。
|
||
meta = values["param_meta"]
|
||
values["param_meta"] = {
|
||
key: meta[key] for key in ("headers", "body", "extra") if isinstance(meta.get(key), dict)
|
||
}
|
||
if values["provider"] == models.DataSource.PROVIDER_MOCK and not values["mock_payload"]:
|
||
raise bad_request("样例数据源要先填一份样例响应,否则取出来永远是空")
|
||
direction = str(values["direction"] or models.DataSource.DIRECTION_IN)
|
||
if direction not in models.DataSource.DIRECTIONS:
|
||
raise bad_request("方向只支持 in(往里取数)、out(往外写回)或 both")
|
||
values["direction"] = direction
|
||
# 「值在响应哪里」「列表在响应哪里」留空 = 响应本身就是它(裸数组、裸数字都算)。
|
||
# 过去这两格是必填星号,逼得人在没见过真实响应之前先手打一个 data.xxx;
|
||
# 现在照样例反推能填就填、填不出留空,取不到时执行器会说清楚该填什么。
|
||
values["items_path"] = str(values["items_path"] or "").strip()
|
||
values["pick"] = str(values["pick"] or "").strip()
|
||
for column in ("success_path", "success_value", "message_path", "ref_path"):
|
||
values[column] = str(values[column] or "").strip()
|
||
values = _clean_process(values, body, db)
|
||
return values
|
||
|
||
|
||
def _clean_process(values: dict, body: schemas.DataSourceBody, db: Session | None) -> dict:
|
||
"""``provider=process``(带出另一个流程的单据)那一套请求的收尾检查。
|
||
|
||
切回 http / mock 时**不清空** ``src_process`` / ``src_match``:为了试一下而临时切个通道,
|
||
不该把人配好的匹配条件一起带走;这两个键只有 process 通道会读,留着不影响别的通道。
|
||
"""
|
||
values["src_process"] = str(values["src_process"] or "").strip()
|
||
if not isinstance(values["src_match"], dict):
|
||
raise bad_request("src_match 得是一个对象")
|
||
if values["provider"] != models.DataSource.PROVIDER_PROCESS:
|
||
return values
|
||
if values["direction"] == models.DataSource.DIRECTION_OUT:
|
||
raise bad_request("流程数据通道只能往里取数,不能当写回通道")
|
||
if not values["src_process"]:
|
||
raise bad_request("要先选带出哪个流程的数据")
|
||
if db is not None and db.get(models.Process, values["src_process"]) is None:
|
||
raise bad_request("要带出数据的那个流程不存在,重新选一个")
|
||
if values["kind"] == models.DataSource.KIND_SEARCH:
|
||
# 列表型的外壳是固定的,不该让人手打;只有单值型那条"取值路径"要人挑字段
|
||
values["items_path"] = PROCESS_LIST_PATH
|
||
values["map_value"] = PROCESS_LIST_VALUE
|
||
values["map_label"] = PROCESS_LIST_LABEL
|
||
problems = processdata.match_problems(values["src_match"], values["src_process"], db,
|
||
str(values["min_permission"] or ""))
|
||
if problems:
|
||
raise bad_request(problems[0])
|
||
return values
|
||
|
||
|
||
def integration_codes_using(db: Session, code: str) -> list[str]:
|
||
"""哪些写回模板引用了这张数据源(L1 不能删掉 L2 还在用的东西)。"""
|
||
rows = db.execute(
|
||
select(models.Integration.code).where(models.Integration.source == code)
|
||
).scalars().all()
|
||
return list(rows)
|
||
|
||
|
||
def dict_codes_using(db: Session, code: str) -> list[str]:
|
||
"""哪些字典把选项来源绑在这张数据源上。
|
||
|
||
字典那一头的引用藏在 ``oa_dict_type.source_code``,表单检查看不到它;
|
||
删掉源的后果是那个下拉从此只停在最后一次同步的选项上,还不报错——
|
||
所以这一条必须和表单引用同一次检查里挡掉。
|
||
"""
|
||
rows = db.execute(
|
||
select(models.DictType.code).where(models.DictType.source_code == code)
|
||
).scalars().all()
|
||
return list(rows)
|
||
|
||
|
||
def _draft(body: schemas.DataSourceBody, db: Session | None = None) -> models.DataSource:
|
||
"""拼一份**没保存的**数据源给「测试连通」用:先测通再存,而不是先存再试错。"""
|
||
draft = models.DataSource(code=str(body.code or "draft"), name=str(body.name or "待测试"))
|
||
for column, value in _clean(body, db).items():
|
||
setattr(draft, column, value)
|
||
draft.auth_secret = str(body.auth_secret or "")
|
||
return draft
|
||
|
||
|
||
@router.get("/design/data-sources")
|
||
def list_data_sources(
|
||
db: Session = Depends(get_db),
|
||
_: CurrentUser = Depends(current_user),
|
||
keyword: str = Query(""),
|
||
kind: str = Query(""),
|
||
enabledOnly: str = Query("", alias="enabledOnly"), # noqa: N803
|
||
) -> dict:
|
||
# 读列表只要登录:表单设计器要把数据源列成下拉给人挑
|
||
rows = fetch.list_sources(db, keyword, kind, enabledOnly.lower() in ("1", "true", "yes"))
|
||
return ok([fetch.view(row) for row in rows])
|
||
|
||
|
||
@router.get("/design/data-sources/presets")
|
||
def read_presets(_: CurrentUser = Depends(current_user)) -> dict:
|
||
"""新建数据源要用的那份**唯一**默认值:可靠性画像、响应外壳、初始字段。
|
||
|
||
默认值放在后端不是洁癖:过去 schemas、models、Vue 表单各存一份,改一处漏两处,
|
||
新建的源和半年前配的源行为悄悄就不一样了。界面问这里要,三处合成一处。
|
||
"""
|
||
return ok({
|
||
"reliability": presets.reliability_view(),
|
||
"envelopes": presets.envelope_view(),
|
||
"defaults": presets.defaults(),
|
||
})
|
||
|
||
|
||
@router.post("/design/data-sources/suggest")
|
||
def suggest_config(
|
||
body: schemas.DataSourceSuggestBody, _: CurrentUser = Depends(require_permission("design:datasource"))
|
||
) -> dict:
|
||
"""贴一份上游答应给你的响应,回一份能直接用的解析配置。
|
||
|
||
上游还没开发时这一条最省事:把接口文档里那段 JSON 贴进来,列表节点、值取自哪一列、
|
||
显示名取自哪一列、还能多带出哪几个键,一次填好。认不出的项目一律留空并说明,
|
||
不猜一个看着配好、实际取不到数的配置出来。
|
||
"""
|
||
sample = body.sample
|
||
if isinstance(sample, str):
|
||
try:
|
||
sample = json.loads(sample or "")
|
||
except ValueError:
|
||
raise bad_request("样例响应不是合法 JSON,检查一下有没有多出来的逗号或引号") from None
|
||
kind = body.kind if body.kind in (models.DataSource.KIND_FETCH, models.DataSource.KIND_SEARCH) else models.DataSource.KIND_FETCH
|
||
if sample in (None, "", {}, []):
|
||
raise bad_request("先贴一份样例响应(上游的返回体),才知道该往哪里取值")
|
||
return ok({"suggestions": presets.suggest(sample, kind)})
|
||
|
||
|
||
@router.get("/design/data-sources/usage/{code}")
|
||
def read_usage(code: str, db: Session = Depends(get_db), _: CurrentUser = Depends(current_user)) -> dict:
|
||
"""这张源被谁引用:表单上的取数字段、写回模板、当作选项来源的字典。"""
|
||
return ok({"forms": fetch.used_by_forms(db, code), "integrations": integration_codes_using(db, code),
|
||
"dicts": dict_codes_using(db, code)})
|
||
|
||
|
||
@router.post("/design/data-sources", dependencies=[Depends(require_permission("design:datasource"))])
|
||
def create_data_source(
|
||
body: schemas.DataSourceBody, user: CurrentUser = Depends(current_user), db: Session = Depends(get_db)
|
||
) -> dict:
|
||
code = str(body.code or "").strip()
|
||
if not CODE_RE.match(code):
|
||
raise bad_request("数据源编码只能用字母、数字、下划线和中划线,且不能为空")
|
||
if not str(body.name or "").strip():
|
||
raise bad_request("数据源名称不能为空")
|
||
if fetch.get_source(db, code) is not None:
|
||
raise bad_request(f"数据源编码已存在: {code}")
|
||
values = _clean(body, db)
|
||
row = models.DataSource(
|
||
code=code, auth_secret=str(body.auth_secret or ""),
|
||
creator=user.person_id, creator_name=user.display_name, **values
|
||
)
|
||
db.add(row)
|
||
db.commit()
|
||
fetch.clear_cache(code)
|
||
return ok(fetch.view(row))
|
||
|
||
|
||
@router.patch("/design/data-sources/{code}", dependencies=[Depends(require_permission("design:datasource"))])
|
||
def update_data_source(
|
||
code: str, body: schemas.DataSourceBody, user: CurrentUser = Depends(current_user), db: Session = Depends(get_db)
|
||
) -> dict:
|
||
row = fetch.get_source(db, code)
|
||
if row is None:
|
||
raise not_found("数据源不存在")
|
||
for column, value in _clean(body, db).items():
|
||
setattr(row, column, value)
|
||
if body.auth_secret: # 空串 = 不改:界面上密钥那一栏永远显示「已设置」,不回填明文
|
||
row.auth_secret = str(body.auth_secret)
|
||
db.commit()
|
||
fetch.clear_cache(row.code)
|
||
return ok(fetch.view(row))
|
||
|
||
|
||
@router.delete("/design/data-sources/{row_id}", dependencies=[Depends(require_permission("design:datasource"))])
|
||
def delete_data_source(row_id: str, db: Session = Depends(get_db), _: CurrentUser = Depends(current_user)) -> dict:
|
||
row = db.get(models.DataSource, row_id)
|
||
if row is None:
|
||
raise not_found("数据源不存在")
|
||
hits = fetch.used_by_forms(db, row.code)
|
||
if hits:
|
||
raise bad_request(f"这张数据源正被{'、'.join(hits[:5])}使用,先改掉表单上的引用再删")
|
||
used = integration_codes_using(db, row.code)
|
||
if used:
|
||
raise bad_request(f"这张数据源正被写回模板「{'、'.join(used[:5])}」使用,先改掉模板上的引用再删")
|
||
dicts_using = dict_codes_using(db, row.code)
|
||
if dicts_using:
|
||
raise bad_request(f"这张数据源是字典「{'、'.join(dicts_using[:5])}」的选项来源,先把那些字典改回手工维护再删")
|
||
db.delete(row)
|
||
db.commit()
|
||
fetch.clear_cache(row.code)
|
||
return ok({"deleted": True})
|
||
|
||
|
||
@router.get("/design/data-sources/process-fields")
|
||
def read_process_fields(
|
||
process: str = Query("", alias="process"),
|
||
db: Session = Depends(get_db),
|
||
_: CurrentUser = Depends(current_user),
|
||
) -> dict:
|
||
"""要带出数据的那个流程能给出哪些字段:默认表单 + 各环节表单,外加单据本体那几个。
|
||
|
||
可读性和 ``/process/processes/{id}`` 同一档(登录即可读,改配置才要权限)——
|
||
这里只回字段名与标签,不回任何一张单的实际内容。
|
||
"""
|
||
process_id = str(process or "").strip()
|
||
if not process_id:
|
||
raise bad_request("要先选一个流程")
|
||
row = db.get(models.Process, process_id)
|
||
if row is None:
|
||
raise not_found("流程不存在")
|
||
return ok({
|
||
"process": process_id,
|
||
"name": row.name,
|
||
"published": row.published,
|
||
"enabled": row.enabled,
|
||
"fields": processdata.fields_of_process(db, process_id),
|
||
})
|
||
|
||
|
||
@router.post("/design/data-sources/test", dependencies=[Depends(require_permission("design:datasource"))])
|
||
def test_data_source(
|
||
body: schemas.DataSourceTestBody, user: CurrentUser = Depends(current_user), db: Session = Depends(get_db)
|
||
) -> dict:
|
||
"""拿一组测试入参真调一次:左侧原始响应、右侧按解析规则取出的结果。
|
||
|
||
配歪了不该等到填单页面才暴露,所以这一句是这一整块配置的验收口。
|
||
"""
|
||
config = body.config or {}
|
||
code = str(config.get("code") or body.code or "").strip()
|
||
row: models.DataSource | None = None
|
||
if config:
|
||
draft = _draft(schemas.DataSourceBody(**config), db)
|
||
draft.code = code or "draft"
|
||
elif code and (row := fetch.get_source(db, code)) is not None:
|
||
draft = row
|
||
else:
|
||
raise bad_request("要么给一份待测试的配置,要么指定一个已保存的数据源编码")
|
||
# 测试走的是真调用,但不许污染那份「上次成功」的缓存:raw=True 拿原始响应,也不写缓存
|
||
result = fetch.preview(db, draft, dict(body.args or {}), actor=user)
|
||
if row is not None:
|
||
row.last_test_status = "ok" if result["ok"] else "error"
|
||
row.last_test_message = (result["error"] or f"{result['itemCount']} 项 / 值 {result['value']}")[:500]
|
||
row.last_test_ms = int(result["ms"])
|
||
row.last_test_at = models.localnow()
|
||
row.last_test_by = user.display_name
|
||
db.commit()
|
||
return ok(result)
|
||
|
||
|
||
@router.get("/data-source/options")
|
||
def search_options(
|
||
code: str = Query(...),
|
||
keyword: str = Query(""),
|
||
db: Session = Depends(get_db),
|
||
user: CurrentUser = Depends(current_user),
|
||
) -> dict:
|
||
"""大列表下拉的按需搜索:走同一个执行器,限流/缓存/审计一个都不少。"""
|
||
row = fetch.get_source(db, code)
|
||
if row is None or not row.enabled:
|
||
return ok({"items": [], "error": "数据源不存在或已停用"})
|
||
result = fetch.run(db, row, {"keyword": keyword}, actor=user)
|
||
# 留痕与熔断状态得落得住:提交链路有引擎兜底,这两条独立接口没人替我们 commit
|
||
db.commit()
|
||
return ok({"items": result.items if result.ok else [], "error": result.error,
|
||
"cached": result.cached, "ms": result.ms})
|
||
|
||
|
||
@router.post("/data-source/fetch")
|
||
def fetch_value(
|
||
body: schemas.DataSourceFetchBody, db: Session = Depends(get_db), user: CurrentUser = Depends(current_user)
|
||
) -> dict:
|
||
"""填单页面上的即时带出。**这个结果只用来显示**:提交时引擎按同样的入参再取一次。"""
|
||
row = fetch.get_source(db, body.code)
|
||
if row is None or not row.enabled:
|
||
raise not_found("数据源不存在或已停用")
|
||
if row.kind != models.DataSource.KIND_FETCH:
|
||
raise bad_request("这个数据源是列表型,请用下拉搜索接口")
|
||
result = fetch.run(db, row, dict(body.args or {}), actor=user)
|
||
# 同上:填单页面这一条路没人替我们 commit,不提交就等于限流与熔断全都没生效
|
||
db.commit()
|
||
if not result.ok:
|
||
return ok({"ok": False, "error": result.error, "value": None, "extras": {}, "ms": result.ms})
|
||
return ok({"ok": True, "value": result.value, "extras": result.extras, "ms": result.ms,
|
||
"cached": result.cached, "at": models.localnow().strftime("%H:%M:%S")})
|
||
|
||
|
||
@router.get("/design/data-sources/{row_id}/logs")
|
||
def read_logs(
|
||
row_id: str, db: Session = Depends(get_db), _: CurrentUser = Depends(require_permission("design:datasource"))
|
||
) -> dict:
|
||
"""调用留痕:谁在哪张单上调的、多久、成没成、有没有命中缓存。"""
|
||
row = db.get(models.DataSource, row_id)
|
||
if row is None:
|
||
raise not_found("数据源不存在")
|
||
rows = db.execute(
|
||
select(models.DataSourceLog)
|
||
.where(models.DataSourceLog.source == row.code)
|
||
.order_by(models.DataSourceLog.created_at.desc(), models.DataSourceLog.id.desc())
|
||
.limit(200)
|
||
).scalars().all()
|
||
return ok([
|
||
{
|
||
"id": item.id,
|
||
"kind": item.kind,
|
||
"status": item.status,
|
||
"httpStatus": item.http_status,
|
||
"ms": item.ms,
|
||
"cached": item.cached,
|
||
"job": item.job,
|
||
"activityName": item.activity,
|
||
"actorName": item.actor_name,
|
||
"args": dict(item.args or {}),
|
||
"message": item.message,
|
||
"createdAt": item.created_at.strftime("%Y-%m-%d %H:%M:%S") if item.created_at else "",
|
||
}
|
||
for item in rows
|
||
])
|