1.排程管理功能更新,支持数据源配置以及自定义查询条件测试
2.应用管理增加Dify应用类型,支持不同类型下的连通性测试
This commit is contained in:
1 parent
72642b981e
commit
6ada6810c5
18 files changed
+2185
-535
No files matched your search
@@ -8,16 +8,15 @@ from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.models import Agent, ScheduleRun, ScheduleTask
|
||||
from app.services.schedule.srm_service import (
|
||||
SRM_MSDS_HEADER_LABELS,
|
||||
SRM_MSDS_SQL_ALIAS_ORDER,
|
||||
SRM_ROHS_HEADER_LABELS,
|
||||
SRM_ROHS_SQL_ALIAS_ORDER,
|
||||
run_msds_doc_check_dify_job,
|
||||
run_rohs_doc_check_dify_job,
|
||||
from app.services.schedule.sql_config import (
|
||||
get_schedule_sql_config,
|
||||
get_schedule_sql_config_by_task_id,
|
||||
get_all_schedule_sql_configs,
|
||||
upsert_schedule_task_config,
|
||||
ScheduleSqlConfig,
|
||||
)
|
||||
|
||||
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str]]
|
||||
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
|
||||
ScheduleExecutor = Callable[[ScheduleTask, ScheduleRun], ScheduleExecuteResult]
|
||||
|
||||
|
||||
@@ -74,7 +73,13 @@ def _run_common_executor(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecut
|
||||
raise RuntimeError("platform_api_path is missing")
|
||||
|
||||
base = str(current_app.config.get("INTERNAL_API_BASE_URL") or "").strip().rstrip("/")
|
||||
url = endpoint if endpoint.startswith("http://") or endpoint.startswith("https://") else (f"{base}{endpoint}" if base else endpoint)
|
||||
if endpoint.startswith("http://") or endpoint.startswith("https://"):
|
||||
url = endpoint
|
||||
elif base:
|
||||
name = endpoint.lstrip("/")
|
||||
url = f"{base}/api/internal/jobs/{name}"
|
||||
else:
|
||||
url = endpoint
|
||||
|
||||
payload = {
|
||||
"run_no": run.run_no,
|
||||
@@ -83,13 +88,21 @@ def _run_common_executor(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecut
|
||||
"dify_agent_id": task.dify_agent_id,
|
||||
}
|
||||
|
||||
step_logs: list[dict[str, Any]] = []
|
||||
|
||||
run.api_request_json = payload
|
||||
db.session.commit()
|
||||
|
||||
try:
|
||||
resp = requests.post(url, json=payload, timeout=(5, 60))
|
||||
timeout = max(5, (task.wait_seconds or 120) + 30)
|
||||
resp = requests.post(url, json=payload, timeout=(5, timeout))
|
||||
resp.raise_for_status()
|
||||
data = resp.json() if resp.content else {}
|
||||
step_logs.append({
|
||||
"step": "call_internal_api",
|
||||
"status": "success",
|
||||
"detail": {"url": url, "status_code": resp.status_code},
|
||||
})
|
||||
except requests.RequestException as e:
|
||||
data = {}
|
||||
if e.response is not None:
|
||||
@@ -99,6 +112,11 @@ def _run_common_executor(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecut
|
||||
data = {"error_text": e.response.text}
|
||||
else:
|
||||
data = {"error": str(e)}
|
||||
step_logs.append({
|
||||
"step": "call_internal_api",
|
||||
"status": "failed",
|
||||
"detail": {"url": url, "error": str(e)},
|
||||
})
|
||||
run.api_response_json = data
|
||||
db.session.commit()
|
||||
raise e
|
||||
@@ -109,56 +127,151 @@ def _run_common_executor(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecut
|
||||
summary = data.get("summary") if isinstance(data, dict) and isinstance(data.get("summary"), dict) else {}
|
||||
details = data.get("details") if isinstance(data, dict) and isinstance(data.get("details"), list) else []
|
||||
errors = data.get("errors") if isinstance(data, dict) and isinstance(data.get("errors"), list) else []
|
||||
remote_step_logs = data.get("step_logs") if isinstance(data, dict) and isinstance(data.get("step_logs"), list) else []
|
||||
|
||||
total = int(summary.get("total_count") if summary.get("total_count") is not None else (len(details) or 1))
|
||||
success = int(summary.get("success_count") if summary.get("success_count") is not None else total)
|
||||
failed = int(summary.get("failed_count") if summary.get("failed_count") is not None else max(0, total - success))
|
||||
return total, success, failed, 0, details, [str(e) for e in errors if str(e).strip()]
|
||||
skipped = int(summary.get("skipped_count") if summary.get("skipped_count") is not None else 0)
|
||||
|
||||
if remote_step_logs:
|
||||
step_logs.extend(remote_step_logs)
|
||||
|
||||
return total, success, failed, skipped, details, [str(e) for e in errors if str(e).strip()], step_logs
|
||||
|
||||
|
||||
def _run_srm_rohs_doc_check_executor(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||
return run_rohs_doc_check_dify_job(
|
||||
conn_str=_build_srm_conn_str(),
|
||||
def _run_external_api_job(task: ScheduleTask, run: ScheduleRun, cfg: ScheduleSqlConfig) -> ScheduleExecuteResult:
|
||||
import requests as http_requests
|
||||
|
||||
ext = cfg.external_api
|
||||
if not ext.url:
|
||||
return 0, 0, 0, 0, [], ["external_api url is empty"], []
|
||||
|
||||
step_logs: list[dict[str, Any]] = []
|
||||
step_logs.append({"step": "call_external_api", "status": "started", "url": ext.url, "method": ext.method})
|
||||
|
||||
try:
|
||||
headers = dict(ext.headers) if ext.headers else {}
|
||||
body = ext.body_template or "{}"
|
||||
resp = http_requests.request(
|
||||
method=ext.method,
|
||||
url=ext.url,
|
||||
headers=headers,
|
||||
data=body,
|
||||
timeout=120,
|
||||
)
|
||||
step_logs.append({"step": "call_external_api", "status": "completed", "status_code": resp.status_code})
|
||||
if not resp.ok:
|
||||
return 0, 0, 0, 1, [], [f"external API returned {resp.status_code}: {resp.text[:500]}"], step_logs
|
||||
try:
|
||||
result_data = resp.json()
|
||||
except Exception:
|
||||
result_data = {"raw": resp.text[:2000]}
|
||||
|
||||
total = 1
|
||||
details = [result_data] if isinstance(result_data, dict) else (result_data if isinstance(result_data, list) else [{"raw": str(result_data)}])
|
||||
step_logs.append({"step": "call_external_api", "status": "success", "total": total})
|
||||
return total, total, 0, 0, details, [], step_logs
|
||||
except Exception as e:
|
||||
step_logs.append({"step": "call_external_api", "status": "error", "error": str(e)})
|
||||
return 0, 0, 1, 0, [], [str(e)], step_logs
|
||||
|
||||
|
||||
def _run_generic_check_job(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||
from app.services.schedule.srm_service import (
|
||||
_run_check_job_loop,
|
||||
_fetch_records,
|
||||
_execute_writeback,
|
||||
_build_record_text,
|
||||
)
|
||||
|
||||
cfg = get_schedule_sql_config_by_task_id(task.id)
|
||||
if not cfg:
|
||||
return 0, 0, 0, 0, [], [], []
|
||||
|
||||
if cfg.data_source_type == "external_api":
|
||||
return _run_external_api_job(task, run, cfg)
|
||||
|
||||
if not cfg.fetch_sql:
|
||||
return 0, 0, 0, 0, [], [], []
|
||||
|
||||
if cfg.data_source and not cfg.data_source.is_empty():
|
||||
conn_str = cfg.data_source.build_connection_string()
|
||||
else:
|
||||
conn_str = _build_srm_conn_str()
|
||||
agent = _resolve_dify_agent(task)
|
||||
user = _resolve_schedule_user(task)
|
||||
has_detail = bool(cfg.detail_sql)
|
||||
|
||||
def fetch_fn(cs: str):
|
||||
return _fetch_records(cs, cfg.fetch_sql)
|
||||
|
||||
def writeback_fn(cs: str, *, row_id: str, run_no: str, dify_result: str, dify_message: str):
|
||||
_execute_writeback(cs, cfg.writeback_sql, (run_no, dify_result, dify_message, str(row_id)))
|
||||
|
||||
pre_dify_fn = None
|
||||
build_record_fn = None
|
||||
|
||||
if has_detail:
|
||||
def _pre_dify(cs: str, item: dict[str, Any], row_id_value: str) -> dict[str, Any] | None:
|
||||
try:
|
||||
detail_rows = _fetch_records(cs, cfg.detail_sql, params=(str(row_id_value),))
|
||||
except Exception as detail_exc:
|
||||
return {
|
||||
"dify_result": "人工判定",
|
||||
"dify_message": f"查询成分明细失败:{detail_exc}",
|
||||
"writeback_srm": False,
|
||||
"writeback_err": str(detail_exc),
|
||||
}
|
||||
detail_summary_lines: list[str] = []
|
||||
for dr in detail_rows:
|
||||
parts = [f"{cfg.header_labels.get(dk, dk)}: {dr.get(dk, '')}" for dk in cfg.detail_alias_order]
|
||||
detail_summary_lines.append(", ".join(parts))
|
||||
item["detail_text"] = "; ".join(detail_summary_lines) if detail_summary_lines else ""
|
||||
item["_detail_rows"] = detail_rows
|
||||
return None
|
||||
pre_dify_fn = _pre_dify
|
||||
|
||||
def _build_with_detail(cs: str, item: dict[str, Any], row_id_value: str) -> tuple[str, str | None]:
|
||||
detail_rows = item.pop("_detail_rows", [])
|
||||
text = _build_record_text(item, cfg.alias_order, cfg.header_labels, detail_rows, cfg.detail_alias_order)
|
||||
return text, item.get("attachment")
|
||||
build_record_fn = _build_with_detail
|
||||
else:
|
||||
def _build_simple(cs: str, item: dict[str, Any], row_id_value: str) -> tuple[str, str | None]:
|
||||
text = _build_record_text(item, cfg.alias_order, cfg.header_labels)
|
||||
return text, item.get("attachment")
|
||||
build_record_fn = _build_simple
|
||||
|
||||
return _run_check_job_loop(
|
||||
conn_str=conn_str,
|
||||
run_no=run.run_no,
|
||||
agent=_resolve_dify_agent(task),
|
||||
user=_resolve_schedule_user(task),
|
||||
agent=agent,
|
||||
user=user,
|
||||
wait_seconds=task.wait_seconds or 120,
|
||||
run_id=run.id,
|
||||
fetch_fn=fetch_fn,
|
||||
build_record_fn=build_record_fn,
|
||||
writeback_fn=writeback_fn,
|
||||
writeback_sql=cfg.writeback_sql,
|
||||
row_id_key=cfg.row_id_key,
|
||||
log_prefix=cfg.log_prefix,
|
||||
fetch_sql=cfg.fetch_sql,
|
||||
pre_dify_fn=pre_dify_fn,
|
||||
)
|
||||
|
||||
|
||||
def _run_srm_msds_doc_check_executor(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||
return run_msds_doc_check_dify_job(
|
||||
conn_str=_build_srm_conn_str(),
|
||||
run_no=run.run_no,
|
||||
agent=_resolve_dify_agent(task),
|
||||
user=_resolve_schedule_user(task),
|
||||
wait_seconds=task.wait_seconds or 120,
|
||||
run_id=run.id,
|
||||
)
|
||||
|
||||
|
||||
_SCHEDULE_EXECUTOR_REGISTRY: dict[str, ScheduleExecutor] = {
|
||||
"default": _run_common_executor,
|
||||
"srm_rohs_doc_check": _run_srm_rohs_doc_check_executor,
|
||||
"srm_msds_doc_check": _run_srm_msds_doc_check_executor,
|
||||
}
|
||||
|
||||
|
||||
def register_schedule_executor(name: str, executor: ScheduleExecutor) -> None:
|
||||
key = str(name or "").strip().lower()
|
||||
if not key:
|
||||
raise ValueError("executor name is required")
|
||||
_SCHEDULE_EXECUTOR_REGISTRY[key] = executor
|
||||
def list_registered_api_paths() -> list[dict[str, str]]:
|
||||
from app.models import ScheduleTask
|
||||
results: list[dict[str, str]] = []
|
||||
tasks = ScheduleTask.query.filter(ScheduleTask.platform_api_path.isnot(None)).all()
|
||||
for t in tasks:
|
||||
results.append({"value": t.platform_api_path, "label": t.name or str(t.id)})
|
||||
return results
|
||||
|
||||
|
||||
def resolve_schedule_executor(task: ScheduleTask) -> ScheduleExecutor:
|
||||
path = normalize_platform_api_path(task.platform_api_path)
|
||||
if path:
|
||||
lookup_key = path.lstrip("/").lower()
|
||||
if lookup_key in _SCHEDULE_EXECUTOR_REGISTRY:
|
||||
return _SCHEDULE_EXECUTOR_REGISTRY[lookup_key]
|
||||
return _SCHEDULE_EXECUTOR_REGISTRY["default"]
|
||||
return _run_common_executor
|
||||
|
||||
|
||||
_SCHEDULE_HEADER_REGISTRY: dict[str, tuple[list[str], dict[str, str]]] = {}
|
||||
@@ -180,5 +293,23 @@ def resolve_schedule_header(platform_api_path: str | None) -> tuple[list[str] |
|
||||
return None, None
|
||||
|
||||
|
||||
register_schedule_header("srm_rohs_doc_check", SRM_ROHS_SQL_ALIAS_ORDER, SRM_ROHS_HEADER_LABELS)
|
||||
register_schedule_header("srm_msds_doc_check", SRM_MSDS_SQL_ALIAS_ORDER, SRM_MSDS_HEADER_LABELS)
|
||||
def _register_headers_from_config() -> None:
|
||||
_SCHEDULE_HEADER_REGISTRY.clear()
|
||||
for name, cfg in get_all_schedule_sql_configs().items():
|
||||
if cfg.alias_order and cfg.header_labels:
|
||||
register_schedule_header(name, cfg.alias_order, cfg.header_labels)
|
||||
|
||||
|
||||
def reload_config() -> dict[str, Any]:
|
||||
_register_headers_from_config()
|
||||
return {"reloaded": []}
|
||||
|
||||
|
||||
_HEADERS_LOADED = False
|
||||
|
||||
|
||||
def ensure_headers_loaded() -> None:
|
||||
global _HEADERS_LOADED
|
||||
if not _HEADERS_LOADED:
|
||||
_register_headers_from_config()
|
||||
_HEADERS_LOADED = True
|
||||
Reference in new issue
Block a user