650 lines
34 KiB
Python
650 lines
34 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 binding, embed as embed_svc, fetch, presets, processdata, sqlsource
|
||
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", "page_mode", "app_code",
|
||
"url_mode", "url_path", "view_url_path", "view_url", "url_links", "url_meta", "url_origins",
|
||
"abandon_url", "abandon_source", "abandon_method", "abandon_field", "abandon_expr", "abandon_body",
|
||
"auth_type", "auth_username", "items_path", "pick", "map_value", "map_label", "map_extra",
|
||
"src_process", "src_match", "sql_text",
|
||
"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"
|
||
#: provider=sql 的列表型响应外壳就是查出来的那些行(见 service/sqlsource.run)
|
||
SQL_LIST_PATH = "rows"
|
||
PROCESS_LIST_VALUE = "id"
|
||
PROCESS_LIST_LABEL = "title"
|
||
|
||
|
||
def _clean(body: schemas.DataSourceBody, db: Session | None = None, code: str = "") -> dict:
|
||
"""把请求体收成能直接往列上赋的形状,顺手把明显不合法的挡在外面。
|
||
|
||
``code`` 是这一条正要写进去的编码(新建时是请求里那个,改时是路径上那个):
|
||
「放弃时通知对方走哪条写回通道」那一栏要拿它判"别指自己"。
|
||
"""
|
||
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(带出另一个流程的单据)、sql(查本库的一条只读查询)"
|
||
"或 embed(让表单嵌这个页面)")
|
||
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} 得是一个对象")
|
||
if not isinstance(values["url_origins"], list):
|
||
raise bad_request("允许的来源要是一个数组(每一项写成一个 https://主机 那样)")
|
||
# ``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)
|
||
values = _clean_sql(values)
|
||
values = _clean_embed(values, db, code)
|
||
return values
|
||
|
||
|
||
def _clean_embed(values: dict, db: Session | None = None, code: str = "") -> dict:
|
||
"""``provider=embed``(让表单嵌这个页面)那一套的收尾检查,闸在 service/embed.py。
|
||
|
||
切回别的通道时**不清空** ``page_mode`` / ``app_code``,与 process / sql 那几格同一个
|
||
道理:临时切个通道试一下,不该把人配好的免登口径一起带走。
|
||
"""
|
||
values["page_mode"] = str(values["page_mode"] or "none").strip()
|
||
values["app_code"] = str(values["app_code"] or "").strip()
|
||
# 这三格用 .get 读:老调用方(与验收脚本那份 values())没带这几项时按默认档走
|
||
values["url_mode"] = str(values.get("url_mode") or embed_svc.URL_TEMPLATE).strip()
|
||
values["url_path"] = str(values.get("url_path") or "").strip()
|
||
# 查看页那两格同样用 .get 读:老调用方没带这几项时按"这条源只有一条地址"走
|
||
values["view_url_path"] = str(values.get("view_url_path") or "").strip()
|
||
values["view_url"] = str(values.get("view_url") or "").strip()
|
||
# 「还有哪几条链接」与「顺手带回的那几个值」同样用 .get 读:老调用方没带这两项时
|
||
# 按"这条源只有那两条地址、什么也不额外带"走(清成空表,别把上一次存的留在库里)。
|
||
# **先拿原样判一句再洗**(下面那两处 problem):洗过的表里根本看不见写歪的那一行,
|
||
# 报错就只会沉默地把人配的那一行吞掉
|
||
raw_links = values.get("url_links")
|
||
raw_meta = values.get("url_meta")
|
||
values["url_links"] = embed_svc.clean_links(raw_links)
|
||
values["url_meta"] = embed_svc.clean_link_meta(raw_meta)
|
||
# 「这一页被放弃时通知对方」那三格也用 .get 读:老调用方没带这几项时按"没配"走
|
||
values["abandon_url"] = str(values.get("abandon_url") or "").strip()
|
||
values["abandon_source"] = str(values.get("abandon_source") or "").strip()
|
||
values["abandon_method"] = str(values.get("abandon_method") or "").strip().upper()
|
||
values["abandon_field"] = str(values.get("abandon_field") or "").strip()
|
||
values["abandon_expr"] = str(values.get("abandon_expr") or "").strip()
|
||
raw_body = values.get("abandon_body") or {}
|
||
values["abandon_body"] = {str(k).strip(): str(v).strip()
|
||
for k, v in raw_body.items()
|
||
if str(k).strip()} if isinstance(raw_body, dict) else {}
|
||
if values["provider"] != models.DataSource.PROVIDER_EMBED:
|
||
return values
|
||
if values["page_mode"] not in embed_svc.MODES:
|
||
raise bad_request("免登方式只支持「不需要登录态」「走统一门户」「本系统发短码」这三种")
|
||
if values["page_mode"] not in embed_svc.MODE_READY:
|
||
# 「走统一门户」是方案 §9 的 P2:要等门户那边确认目标应用允许被嵌。就在保存这一刻挡:
|
||
# 存下一条永远打不开的配置、等有人点开表单才发现,是这里最没必要的两种报错
|
||
raise bad_request("「走统一门户」这一档还没开放(要等门户确认那个应用允许被嵌):"
|
||
"先选「本系统发短码」或「不需要登录态」")
|
||
if values["direction"] == models.DataSource.DIRECTION_OUT:
|
||
raise bad_request("可嵌入页面这一类只是把页面摆出来,不能当写回通道")
|
||
problem = embed_svc.url_problem(values["url"])
|
||
if problem:
|
||
raise bad_request(problem)
|
||
if values["page_mode"] == embed_svc.MODE_HUB and not values["app_code"]:
|
||
raise bad_request("用「走统一门户」免登要先填对方在门户上的应用编码")
|
||
if values["abandon_url"]:
|
||
problem = embed_svc.abandon_url_problem(values["abandon_url"], values["url"])
|
||
if problem:
|
||
raise bad_request(problem)
|
||
problem = embed_svc.abandon_source_problem(values["abandon_source"], code, db)
|
||
if problem:
|
||
raise bad_request(problem)
|
||
if not values["abandon_url"] and not values["abandon_source"]:
|
||
# 两样都没填就是这一档没开:方法/字段名那些留着没意义,只会被下一个人当成"配过了"
|
||
values["abandon_method"] = ""
|
||
values["abandon_field"] = ""
|
||
values["abandon_expr"] = ""
|
||
values["abandon_body"] = {}
|
||
if values["abandon_method"] and values["abandon_method"] not in embed_svc.ABANDON_METHODS:
|
||
raise bad_request("放弃时通知对方那一句只支持 POST / PUT / PATCH / DELETE(不给 GET:"
|
||
"一个会改对方数据的调用不该是幂等读)")
|
||
if values["url_mode"] not in embed_svc.URL_MODES:
|
||
raise bad_request("地址来源只支持「照地址模板拼」和「先调接口取链接」这两种")
|
||
problem = embed_svc.links_problem(raw_links, mode=values["url_mode"])
|
||
if problem:
|
||
raise bad_request(problem)
|
||
if values["url_mode"] == embed_svc.URL_API:
|
||
if not values["url_path"]:
|
||
raise bad_request("要先说清链接在接口返回的哪一栏(如 data.url),不然取回来不知道该用哪一段")
|
||
problem = embed_svc.origins_problem(values.get("url_origins"))
|
||
if problem:
|
||
raise bad_request(problem)
|
||
# 接口那一档没人读第二条地址模板:留着只会让下一个人以为它生效,清掉
|
||
values["view_url"] = ""
|
||
# 清单里那几条同理:这一档的地址是接口给的,模板填了也没人看,只留它在响应里的位置
|
||
values["url_links"] = [{k: v for k, v in item.items() if k != "template"}
|
||
for item in values["url_links"]]
|
||
problem = embed_svc.link_meta_problem(raw_meta)
|
||
if problem:
|
||
raise bad_request(problem)
|
||
else:
|
||
# 模板那一档反过来:那个"位置"没意义。第二条地址只要填了就得是一条能用的地址
|
||
values["view_url_path"] = ""
|
||
if values["view_url"]:
|
||
problem = embed_svc.url_problem(values["view_url"])
|
||
if problem:
|
||
raise bad_request(f"查看页那条地址不对:{problem}")
|
||
# 清单里那几条留地址模板、去掉"位置";额外带值那一栏也没人读——模板档不发任何请求
|
||
values["url_links"] = [{k: v for k, v in item.items() if k != "path"}
|
||
for item in values["url_links"]]
|
||
values["url_meta"] = {}
|
||
if values["url_mode"] != embed_svc.URL_API and values.get("mock_payload"):
|
||
# 样例响应只对"接口取链接"那一档有意义,而在那一档里它**顶掉真接口**。
|
||
# 切回模板档还留着它,万一哪天再切回去,那张源就悄悄不回真接口了——
|
||
# 而模板档本来一处都不读这一列,留着没有任何代价以外的意义
|
||
values["mock_payload"] = {}
|
||
values["url_origins"] = embed_svc.clean_origins(values.get("url_origins"))
|
||
return values
|
||
|
||
|
||
def _need_embed_key(values: dict, secret: str) -> None:
|
||
"""短码免登离不开那把共享密钥,缺了就别存下来——等人在表单上点开才报错太晚了。
|
||
|
||
单独一条而不并进 :func:`_clean_embed`:``auth_secret`` 走的是 PATCH 语义(空串=不改),
|
||
只有调用点知道"库里那条现在有没有值"。
|
||
"""
|
||
if (values.get("provider") == models.DataSource.PROVIDER_EMBED
|
||
and str(values.get("page_mode") or "") == embed_svc.MODE_TICKET
|
||
and not str(secret or "").strip()):
|
||
raise bad_request("用「本系统发短码」免登要先把与对方约定的应用密钥填上")
|
||
|
||
|
||
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 _clean_sql(values: dict) -> dict:
|
||
"""``provider=sql``(查本库的一条只读查询)那一套请求的收尾检查。
|
||
|
||
闸本身在 ``service/sqlsource.py``,这里做的是"别让人把配歪的 SQL 存下来":
|
||
切回别的通道时**不清空** ``sql_text``,跟 process 那两格同一个道理——
|
||
为了试一下而临时切个通道,不该把人写的查询一起带走。
|
||
"""
|
||
values["sql_text"] = str(values["sql_text"] or "").strip()
|
||
if values["provider"] != models.DataSource.PROVIDER_SQL:
|
||
return values
|
||
blocked = sqlsource.gate_problem()
|
||
if blocked:
|
||
raise bad_request(blocked)
|
||
if values["direction"] == models.DataSource.DIRECTION_OUT:
|
||
raise bad_request("SQL 通道只能往里取数,不能当写回通道")
|
||
issues = sqlsource.problems(values["sql_text"], (values["body_template"] or {}).keys())
|
||
if issues:
|
||
raise bad_request(issues[0])
|
||
if values["kind"] == models.DataSource.KIND_SEARCH:
|
||
# 列表外壳是固定的,不该让人手打(与 process 通道同一处理)
|
||
values["items_path"] = SQL_LIST_PATH
|
||
return values
|
||
if not values["pick"]:
|
||
columns = sqlsource.columns_sample(values["sql_text"])
|
||
if len(columns) == 1:
|
||
values["pick"] = columns[0]
|
||
else:
|
||
shown = "、".join(columns) if columns else "(这一句的列清单看不出有哪些列)"
|
||
raise bad_request(f"这条 SQL 查出多列,要说清带出哪一列:到「解析规则」的「取值路径」里填列名({shown})")
|
||
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 abandon_channel_users(db: Session, code: str) -> list[dict]:
|
||
"""哪些「可嵌入页面」把这张源当成「这一页被放弃时,通知对方」的出口。
|
||
|
||
这一档不在写回那三层里(人没保存就返回那一刻还没有单据),所以 ``used_by_forms`` 与
|
||
``integration_codes_using`` 都看不见这层引用:源一删,放弃通知就悄悄不发出去了,
|
||
而"悄悄不发出"正是这一档最坏的失效方式——两边都以为对方删过了。
|
||
"""
|
||
want = str(code or "").strip()
|
||
if not want:
|
||
return []
|
||
rows = db.execute(
|
||
select(models.DataSource.code, models.DataSource.name)
|
||
.where(models.DataSource.abandon_source == want)
|
||
).all()
|
||
return [{"code": str(row.code), "name": str(row.name or row.code)} for row in 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, str(body.code or '')).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(),
|
||
# 新建时先摆一份样例响应:样例本体也在 presets.py,界面不再自己抄一份
|
||
"samples": presets.samples_view(),
|
||
})
|
||
|
||
|
||
@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), "abandonBy": abandon_channel_users(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, code)
|
||
_need_embed_key(values, str(body.auth_secret or ""))
|
||
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)
|
||
embed_svc.cache_urls()
|
||
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("数据源不存在")
|
||
# 洗完那份要留在手上:下面判短码免登时要用到其中的 provider / page_mode,
|
||
# 顺手在 for 里丢掉就得再洗一次(而 _clean 是会报错的那种洗法,不该调两遍)
|
||
values = _clean(body, db, code)
|
||
for column, value in values.items():
|
||
setattr(row, column, value)
|
||
if body.auth_secret: # 空串 = 不改:界面上密钥那一栏永远显示「已设置」,不回填明文
|
||
row.auth_secret = str(body.auth_secret)
|
||
_need_embed_key(values, str(row.auth_secret or ""))
|
||
db.commit()
|
||
fetch.clear_cache(row.code)
|
||
embed_svc.cache_urls()
|
||
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])}」使用,先改掉模板上的引用再删")
|
||
abandoned = abandon_channel_users(db, row.code)
|
||
if abandoned:
|
||
names = "、".join(str(item["name"]) for item in abandoned[:5])
|
||
raise bad_request(
|
||
f"这张数据源是「{names}」那条可嵌入页面的放弃通知出口(那一页被放弃时要往这里发一句),"
|
||
"先把那条记录上的「这一页被放弃时,通知对方」改掉再删"
|
||
)
|
||
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)
|
||
embed_svc.cache_urls()
|
||
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("要么给一份待测试的配置,要么指定一个已保存的数据源编码")
|
||
# 可嵌入页面那一类测的不是"接口通不通"而是"这一页让不让嵌",走另一条探法
|
||
if draft.provider == models.DataSource.PROVIDER_EMBED:
|
||
result = embed_svc.probe(db, draft, ancestor=str(body.ancestor or ""), args=dict(body.args or {}))
|
||
if row is not None:
|
||
row.last_test_status = result["verdict"]
|
||
row.last_test_message = result["message"][:500]
|
||
row.last_test_ms = int(result["ms"])
|
||
row.last_test_at = models.localnow()
|
||
row.last_test_by = user.display_name
|
||
db.commit()
|
||
# 注册表一改,CSP 那份白名单立刻跟着失效,不用等它自己过期
|
||
embed_svc.cache_urls()
|
||
return ok(result)
|
||
# 测试走的是真调用,但不许污染那份「上次成功」的缓存: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
|
||
# 留痕两种情况都要落得住。过去只有"测已保存的源"这一支 commit,于是编辑弹窗里点
|
||
# 「拉取样例」(送的是没保存的草稿)失败时,上游挨了一下、本页与「调用留痕」里
|
||
# 却一个字都没有——配错的人连"到底打出去过没有"都查不到
|
||
db.commit()
|
||
return ok(result)
|
||
|
||
|
||
def _search_result(db: Session, code: str, keyword: str, args: dict, user) -> dict:
|
||
"""候选搜索那一条:按这一格配的入参 + 关键词搜一页。
|
||
|
||
入参是**前端已经算好的那份**(``{form.x}`` 在本地换成了真值),与
|
||
``POST /data-source/fetch`` 同一分寸:后端不猜表单上下文,只管按入参调、
|
||
按解析规则整形,限流 / 缓存 / 熔断 / 留痕照旧一样不落。
|
||
搜索不报错拦人:候选取不到就是空的一页,界面上给一句「没搜到 / 重新加载」。
|
||
"""
|
||
row = fetch.get_source(db, code)
|
||
problem = binding.source_problem(code, row, want=binding.WANT_SEARCH, want_noun="候选")
|
||
if problem:
|
||
return {"ok": False, "items": [], "error": problem, "itemCount": 0, "ms": 0}
|
||
payload = {str(key): value for key, value in (args or {}).items() if str(key) != "keyword"}
|
||
payload["keyword"] = str(keyword or "")
|
||
result = fetch.run(db, row, payload, actor=user)
|
||
# 留痕与熔断状态得落得住:提交链路有引擎兜底,这两条独立接口没人替我们 commit
|
||
db.commit()
|
||
return {"ok": result.ok, "items": result.items if result.ok else [], "error": result.error,
|
||
"itemCount": len(result.items) if result.ok else 0,
|
||
"cached": result.cached, "ms": result.ms}
|
||
|
||
|
||
@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:
|
||
"""大列表下拉的按需搜索(只有关键词的那一条老路)。
|
||
|
||
留着是给移动端与开放接口一个过渡:能带上下文字段当筛选条件的新调用走
|
||
``POST /data-source/options``,两者出来的是同一份 ``{items, error}``。
|
||
"""
|
||
return ok(_search_result(db, code, keyword, {}, user))
|
||
|
||
|
||
@router.post("/data-source/options")
|
||
def search_options_with_args(
|
||
body: schemas.DataSourceSearchBody,
|
||
db: Session = Depends(get_db),
|
||
user: CurrentUser = Depends(current_user),
|
||
) -> dict:
|
||
"""带上下文入参的候选搜索:「只显示所选品类下的物料」靠这一条配得出来。"""
|
||
return ok(_search_result(db, body.code, body.keyword, dict(body.args or {}), user))
|
||
|
||
|
||
@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,
|
||
pick=str(body.pick or "").strip(), extras=dict(body.extras or {}))
|
||
# 同上:填单页面这一条路没人替我们 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
|
||
])
|