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.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], list[dict[str, Any]]] ScheduleExecutor = Callable[[ScheduleTask, ScheduleRun], ScheduleExecuteResult] def normalize_platform_api_path(path: str | None) -> str: """ 归一化 platform job key 或完整 URL。 核心逻辑:http(s) 完整 URL 原样返回(外部集成端点); 其余值统一委托 schedule_contract.normalize_job_key(契约层与执行层单一归一化入口)。 """ value = str(path or "").strip() if not value: return "" parsed = urlparse(value) if parsed.scheme in {"http", "https"}: return value from app.services.schedule.schedule_contract import normalize_job_key return normalize_job_key(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_platform_job_in_process(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult: """ 进程内执行已注册平台 Job(无需 HTTP,也不依赖 INTERNAL_API_BASE_URL)。 核心逻辑:从 job_registry 按 platform_api_path 查 handler 直接调用。 """ from app.services.schedule.job_registry import run_platform_job key = normalize_platform_api_path(task.platform_api_path) # [STEP 1] 合并而非覆盖:保留会话触发写入的 run_options 等字段 existing = run.api_request_json if isinstance(run.api_request_json, dict) else {} payload = { **existing, "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() return run_platform_job(key, task, run, payload) 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") # [STEP 1] 普通 job key(非完整 URL)优先进程内直接调 registry,避免 HTTP 与 base URL 依赖 if not (endpoint.startswith("http://") or endpoint.startswith("https://")): from app.services.schedule.job_registry import get_platform_job if get_platform_job(endpoint): return _run_platform_job_in_process(task, run) # [STEP 2] 完整 URL(外部集成)仍走 HTTP;base URL 仅用于补全相对路径 base = str(current_app.config.get("INTERNAL_API_BASE_URL") or "").strip().rstrip("/") if endpoint.startswith("http://") or endpoint.startswith("https://"): url = endpoint elif base: name = endpoint.lstrip("/") url = f"{base}/api/internal/jobs/{name}" else: raise RuntimeError( f"platform_api_path '{endpoint}' is not a registered job and INTERNAL_API_BASE_URL is not configured" ) payload = { "run_no": run.run_no, "schedule_task_id": task.id, "schedule_name": task.name, "dify_agent_id": task.dify_agent_id, } step_logs: list[dict[str, Any]] = [] run.api_request_json = payload db.session.commit() try: 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: try: data = e.response.json() except Exception: 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 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 [] 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)) 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_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, ) dst = getattr(task, "data_source_type", None) if dst not in ("database", "external_api"): raise RuntimeError(f"Invalid data_source_type for data_pipeline: {dst!r}") 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.get("_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=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, dify_system_prompt=cfg.dify_system_prompt, ) def list_registered_api_paths() -> list[dict[str, str]]: from app.services.schedule.job_registry import list_platform_jobs return [{"value": job.key, "label": job.label} for job in list_platform_jobs()] def resolve_schedule_executor(task: ScheduleTask) -> ScheduleExecutor: st = getattr(task, "schedule_type", None) or "data_pipeline" if st == "data_pipeline": return _run_generic_check_job if st == "platform_job": return _run_common_executor raise RuntimeError(f"Unsupported schedule_type: {st}") _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 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) from app.services.schedule.freight_rpa_onhand_finalize import register_inventory_rpa_excel_headers from app.services.schedule.freight_rpa_inbound_finalize import register_inbound_rpa_excel_headers from app.services.schedule.freight_rpa_outbound_finalize import register_outbound_rpa_excel_headers register_inventory_rpa_excel_headers() register_inbound_rpa_excel_headers() register_outbound_rpa_excel_headers() 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