185 lines
6.8 KiB
Python
185 lines
6.8 KiB
Python
from __future__ import annotations
|
|
|
|
import requests
|
|
from typing import Any, Callable
|
|
from urllib.parse import urlparse
|
|
|
|
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,
|
|
)
|
|
|
|
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str]]
|
|
ScheduleExecutor = Callable[[ScheduleTask, ScheduleRun], ScheduleExecuteResult]
|
|
|
|
|
|
def normalize_platform_api_path(path: str | None) -> str:
|
|
value = str(path or "").strip()
|
|
if not value:
|
|
return ""
|
|
parsed = urlparse(value)
|
|
if parsed.scheme in {"http", "https"}:
|
|
return value
|
|
if not value.startswith("/"):
|
|
value = "/" + value
|
|
return value
|
|
|
|
|
|
def _build_srm_conn_str() -> str:
|
|
host = str(current_app.config.get("SRM_SQLSERVER_HOST") or "").strip()
|
|
if not host:
|
|
raise RuntimeError("SRM_SQLSERVER_HOST is not configured")
|
|
|
|
port = str(current_app.config.get("SRM_SQLSERVER_PORT") or "1433").strip()
|
|
database = str(current_app.config.get("SRM_SQLSERVER_DATABASE") or "").strip()
|
|
username = str(current_app.config.get("SRM_SQLSERVER_USERNAME") or "").strip()
|
|
password = str(current_app.config.get("SRM_SQLSERVER_PASSWORD") or "").strip()
|
|
driver = str(current_app.config.get("SRM_SQLSERVER_DRIVER") or "SQL Server").strip()
|
|
encrypt = str(current_app.config.get("SRM_SQLSERVER_ENCRYPT") or "no").strip().lower()
|
|
trust_cert = str(current_app.config.get("SRM_SQLSERVER_TRUST_CERT") or "yes").strip().lower()
|
|
|
|
return (
|
|
f"DRIVER={{{driver}}};"
|
|
f"SERVER={host},{port};"
|
|
f"DATABASE={database};"
|
|
f"UID={username};"
|
|
f"PWD={password};"
|
|
f"Encrypt={encrypt};"
|
|
f"TrustServerCertificate={trust_cert};"
|
|
)
|
|
|
|
|
|
def _resolve_dify_agent(task: ScheduleTask):
|
|
agent = db.session.get(Agent, task.dify_agent_id) if task.dify_agent_id else None
|
|
if task.dify_agent_id and (not agent or not agent.dify_api_key):
|
|
raise RuntimeError("dify_agent_id is invalid or key is missing")
|
|
return agent
|
|
|
|
|
|
def _resolve_schedule_user(task: ScheduleTask) -> str:
|
|
return str(getattr(task.owner, "username", "") or task.owner_user_id or "schedule_system")
|
|
|
|
|
|
def _run_common_executor(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
|
endpoint = normalize_platform_api_path(task.platform_api_path)
|
|
if not endpoint:
|
|
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)
|
|
|
|
payload = {
|
|
"run_no": run.run_no,
|
|
"schedule_task_id": task.id,
|
|
"schedule_name": task.name,
|
|
"dify_agent_id": task.dify_agent_id,
|
|
}
|
|
|
|
run.api_request_json = payload
|
|
db.session.commit()
|
|
|
|
try:
|
|
resp = requests.post(url, json=payload, timeout=(5, 60))
|
|
resp.raise_for_status()
|
|
data = resp.json() if resp.content else {}
|
|
except requests.RequestException as e:
|
|
data = {}
|
|
if e.response is not None:
|
|
try:
|
|
data = e.response.json()
|
|
except Exception:
|
|
data = {"error_text": e.response.text}
|
|
else:
|
|
data = {"error": str(e)}
|
|
run.api_response_json = data
|
|
db.session.commit()
|
|
raise e
|
|
|
|
run.api_response_json = data
|
|
db.session.commit()
|
|
|
|
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 []
|
|
|
|
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()]
|
|
|
|
|
|
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(),
|
|
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,
|
|
)
|
|
|
|
|
|
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 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"]
|
|
|
|
|
|
_SCHEDULE_HEADER_REGISTRY: dict[str, tuple[list[str], dict[str, str]]] = {}
|
|
|
|
|
|
def register_schedule_header(name: str, header_order: list[str], header_labels: dict[str, str]) -> None:
|
|
key = str(name or "").strip().lower()
|
|
if not key:
|
|
raise ValueError("header name is required")
|
|
_SCHEDULE_HEADER_REGISTRY[key] = (header_order, header_labels)
|
|
|
|
|
|
def resolve_schedule_header(platform_api_path: str | None) -> tuple[list[str] | None, dict[str, str] | None]:
|
|
path = normalize_platform_api_path(platform_api_path)
|
|
if path:
|
|
key = path.lstrip("/").lower()
|
|
if key in _SCHEDULE_HEADER_REGISTRY:
|
|
return _SCHEDULE_HEADER_REGISTRY[key]
|
|
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)
|