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 run_rohs_doc_check_dify_job ScheduleExecuteResult = tuple[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 _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, details, [str(e) for e in errors if str(e).strip()] def _run_srm_rohs_doc_check_executor(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult: 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") 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() conn_str = ( f"DRIVER={{{driver}}};" f"SERVER={host},{port};" f"DATABASE={database};" f"UID={username};" f"PWD={password};" f"Encrypt={encrypt};" f"TrustServerCertificate={trust_cert};" ) return run_rohs_doc_check_dify_job( conn_str=conn_str, run_no=run.run_no, agent=agent, user=str(getattr(task.owner, "username", "") or task.owner_user_id or "schedule_system"), wait_seconds=task.wait_seconds or 120, ) _SCHEDULE_EXECUTOR_REGISTRY: dict[str, ScheduleExecutor] = { "default": _run_common_executor, "srm_rohs_doc_check": _run_srm_rohs_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"]