353 lines
13 KiB
Python
353 lines
13 KiB
Python
"""
|
|
backend/app/api/rohs_check_tools.py
|
|
文件用途:RoHS Chatflow 显式 HTTP Tool API。
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import threading
|
|
import time
|
|
from io import BytesIO
|
|
from datetime import datetime
|
|
|
|
from flask import Blueprint, current_app, jsonify, request, send_file
|
|
from sqlalchemy import text
|
|
|
|
from app import db
|
|
from app.errors import AppError, ConflictError, NotFoundError, ServiceUnavailableError, UnauthorizedError, ValidationError
|
|
from app.models import ScheduleRun, ScheduleTask
|
|
from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE
|
|
from app.services.rohs_check_tools.openapi_spec import build_rohs_openapi_spec
|
|
from app.services.schedule.query_service import get_run, serialize_run
|
|
from app.services.schedule.scheduler_service import _generate_run_no, run_task_now
|
|
|
|
rohs_check_bp = Blueprint("rohs_check_tools", __name__)
|
|
|
|
_EXCEL_TOKEN_SCOPES = {"rohs_check_excel", "rohs_schedule_excel"}
|
|
_RUN_START_LOCK = threading.Lock()
|
|
_ROHS_GLOBAL_LOCK_KEY = 8700000000
|
|
_ROHS_TASK_KEYWORDS = ("rohs", "rohs文件检核", "rohs 文件检核")
|
|
|
|
|
|
def _tool_token_secret() -> str:
|
|
return str(
|
|
current_app.config.get("ROHS_TOOLS_API_KEY")
|
|
or current_app.config.get("INTEGRATION_API_KEY")
|
|
or current_app.config.get("SECRET_KEY")
|
|
or "default-secret"
|
|
).strip()
|
|
|
|
|
|
def _decode_download_token(token: str | None) -> dict | None:
|
|
normalized = str(token or "").strip()
|
|
if not normalized:
|
|
return None
|
|
try:
|
|
import jwt
|
|
|
|
payload = jwt.decode(normalized, _tool_token_secret(), algorithms=["HS256"])
|
|
return payload if isinstance(payload, dict) else None
|
|
except Exception as exc:
|
|
current_app.logger.warning("[rohs-tool] download token validation failed: %s", exc)
|
|
return None
|
|
|
|
|
|
def _require_tool_auth() -> None:
|
|
configured = str(
|
|
current_app.config.get("ROHS_TOOLS_API_KEY")
|
|
or current_app.config.get("INTEGRATION_API_KEY")
|
|
or ""
|
|
).strip()
|
|
if not configured:
|
|
raise ServiceUnavailableError(
|
|
"ROHS_TOOLS_API_KEY or INTEGRATION_API_KEY is not configured",
|
|
code="missing_auth",
|
|
)
|
|
|
|
bearer = str(request.headers.get("Authorization") or "").strip()
|
|
token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
|
|
integration_key = str(request.headers.get("X-Integration-Key") or "").strip()
|
|
if configured in {token, integration_key}:
|
|
return
|
|
if request.path.endswith("/excel") and _decode_download_token(request.args.get("token")):
|
|
return
|
|
if not token and not integration_key:
|
|
raise UnauthorizedError("missing_auth")
|
|
raise UnauthorizedError("invalid_auth")
|
|
|
|
|
|
def _tool_error_code(exc: AppError) -> str:
|
|
message = str(exc.message or "").strip()
|
|
if message in {
|
|
"missing_auth",
|
|
"invalid_auth",
|
|
"task_not_found",
|
|
"run_not_found",
|
|
"excel_not_ready",
|
|
"kb_sync_failed",
|
|
}:
|
|
return message
|
|
if exc.code == "AUTH.UNAUTHORIZED":
|
|
return "invalid_auth"
|
|
if exc.code == "SYSTEM.SERVICE_UNAVAILABLE" and "not configured" in message.lower():
|
|
return "missing_auth"
|
|
if exc.code == "RESOURCE.NOT_FOUND":
|
|
return message or "run_not_found"
|
|
if exc.code == "VALIDATION.INVALID_PARAM":
|
|
return message or "invalid_request"
|
|
if exc.code == "RESOURCE.CONFLICT":
|
|
return message or "conflict"
|
|
return exc.code
|
|
|
|
|
|
@rohs_check_bp.errorhandler(AppError)
|
|
def _handle_tool_app_error(exc: AppError):
|
|
status = exc.http_status
|
|
return jsonify({
|
|
"ok": False,
|
|
"error_code": _tool_error_code(exc),
|
|
"message": exc.message,
|
|
}), status
|
|
|
|
|
|
def _public_base_url() -> str:
|
|
return resolve_HXOPS_TOOLS_API_BASE()
|
|
|
|
|
|
def _is_rohs_check_task(task: ScheduleTask | None) -> bool:
|
|
if not task:
|
|
return False
|
|
values = (
|
|
getattr(task, "schedule_no", None),
|
|
getattr(task, "name", None),
|
|
getattr(task, "platform_api_path", None),
|
|
)
|
|
haystack = " ".join(str(item or "").lower() for item in values)
|
|
return any(keyword in haystack for keyword in _ROHS_TASK_KEYWORDS)
|
|
|
|
|
|
def _acquire_rohs_start_lock() -> None:
|
|
"""Serialize RoHS start checks across processes when PostgreSQL is used."""
|
|
bind = db.session.get_bind()
|
|
if bind.dialect.name != "postgresql":
|
|
return
|
|
db.session.execute(text("SELECT pg_advisory_xact_lock(:lock_key)"), {"lock_key": _ROHS_GLOBAL_LOCK_KEY})
|
|
|
|
|
|
def _build_excel_download_url(run: ScheduleRun) -> str:
|
|
import jwt
|
|
|
|
payload = {
|
|
"scope": "rohs_check_excel",
|
|
"run_id": run.id,
|
|
"exp": int(time.time()) + 600,
|
|
}
|
|
token = jwt.encode(payload, _tool_token_secret(), algorithm="HS256")
|
|
return f"{_public_base_url()}/api/rohs-check/tools/runs/{run.id}/excel?token={token}"
|
|
|
|
|
|
@rohs_check_bp.before_request
|
|
def _verify_tool_access():
|
|
if request.path.endswith("/openapi.json"):
|
|
return None
|
|
_require_tool_auth()
|
|
return None
|
|
|
|
|
|
def _serialize_tool_run(run: ScheduleRun) -> dict:
|
|
payload = serialize_run(run)
|
|
return {
|
|
"run_id": payload["id"],
|
|
"run_no": payload["run_no"],
|
|
"task_id": payload["schedule_task_id"],
|
|
"task_name": payload.get("schedule_name"),
|
|
"status": payload["status"],
|
|
"total_count": payload["total_count"],
|
|
"success_count": payload["success_count"],
|
|
"failed_count": payload["failed_count"],
|
|
"skipped_count": payload["skipped_count"],
|
|
"started_at": payload.get("started_at"),
|
|
"finished_at": payload.get("finished_at"),
|
|
"duration_ms": payload.get("duration_ms"),
|
|
"error_message": payload.get("error_message"),
|
|
"excel": {
|
|
"file_name": payload.get("excel_file_name"),
|
|
"file_size": payload.get("excel_file_size"),
|
|
"download_url": _build_excel_download_url(run) if payload.get("excel_file_name") else None,
|
|
},
|
|
"knowledge_base": {
|
|
"enabled": bool(getattr(run.task, "kb_sync_enabled", False)) if run.task else bool(payload.get("kb_group_id")),
|
|
"sync_status": payload.get("kb_sync_status"),
|
|
"group_id": payload.get("kb_group_id"),
|
|
"document_id": payload.get("kb_document_id"),
|
|
"document_version_id": payload.get("kb_document_version_id"),
|
|
"sync_job_id": payload.get("kb_sync_job_id"),
|
|
"error_message": payload.get("kb_sync_error"),
|
|
},
|
|
}
|
|
|
|
|
|
def _resolve_check_task(data: dict | None = None, *, task_id: int | None = None) -> ScheduleTask:
|
|
data = data or {}
|
|
raw_task_id = task_id if task_id is not None else data.get("task_id")
|
|
if raw_task_id in (None, "", 0, "0") and not str(data.get("task_no") or "").strip():
|
|
raise ValidationError("task_id_required")
|
|
try:
|
|
normalized_task_id = int(raw_task_id) if raw_task_id not in (None, "", 0, "0") else None
|
|
except (TypeError, ValueError):
|
|
raise ValidationError("task_id_invalid")
|
|
task = db.session.get(ScheduleTask, normalized_task_id) if normalized_task_id is not None else None
|
|
if not task:
|
|
task_no = str(data.get("task_no") or "").strip()
|
|
if task_no:
|
|
task = ScheduleTask.query.filter_by(schedule_no=task_no).first()
|
|
if not task:
|
|
raise NotFoundError("task_not_found")
|
|
if not _is_rohs_check_task(task):
|
|
raise NotFoundError("task_not_found")
|
|
return task
|
|
|
|
|
|
@rohs_check_bp.route("/tools/tasks", methods=["GET"])
|
|
def list_rohs_tasks():
|
|
rows = ScheduleTask.query.order_by(ScheduleTask.created_at.desc()).all()
|
|
tasks = []
|
|
for task in rows:
|
|
if not _is_rohs_check_task(task):
|
|
continue
|
|
latest = (
|
|
ScheduleRun.query.filter_by(schedule_task_id=task.id)
|
|
.order_by(ScheduleRun.id.desc())
|
|
.first()
|
|
)
|
|
tasks.append({
|
|
"task_id": task.id,
|
|
"task_no": task.schedule_no,
|
|
"name": task.name,
|
|
"enabled": bool(task.enabled),
|
|
"last_status": latest.status if latest else None,
|
|
"last_run_at": task.last_run_at.isoformat() if task.last_run_at else None,
|
|
"next_run_at": task.next_run_at.isoformat() if task.next_run_at else None,
|
|
})
|
|
return jsonify({"ok": True, "tasks": tasks})
|
|
|
|
|
|
@rohs_check_bp.route("/tools/tasks/run", methods=["POST"])
|
|
def run_rohs_check():
|
|
"""立即执行检核;任务 enabled 仅控制 cron,不限制人工或 Chatflow 触发。"""
|
|
data = request.get_json(silent=True) or {}
|
|
task = _resolve_check_task(data)
|
|
|
|
with _RUN_START_LOCK:
|
|
_acquire_rohs_start_lock()
|
|
existing = (
|
|
ScheduleRun.query.join(ScheduleTask, ScheduleTask.id == ScheduleRun.schedule_task_id)
|
|
.filter(ScheduleRun.status == "running")
|
|
.order_by(ScheduleRun.id.desc())
|
|
.all()
|
|
)
|
|
existing = next((row for row in existing if _is_rohs_check_task(row.task)), None)
|
|
if existing:
|
|
db.session.commit()
|
|
return jsonify({
|
|
"ok": False,
|
|
"error_code": "check_running",
|
|
"message": "该检核任务正在执行中,请稍后查询结果",
|
|
"run": _serialize_tool_run(existing),
|
|
}), 409
|
|
|
|
run = ScheduleRun(
|
|
run_no=_generate_run_no(),
|
|
schedule_task_id=task.id,
|
|
trigger_type="dify_chatflow",
|
|
started_at=datetime.utcnow(),
|
|
status="running",
|
|
api_request_json={
|
|
"trigger_source": data.get("trigger_source") or "dify_chatflow",
|
|
"conversation_id": data.get("conversation_id"),
|
|
"user_message": data.get("user_message"),
|
|
},
|
|
)
|
|
db.session.add(run)
|
|
db.session.commit()
|
|
app = current_app._get_current_object()
|
|
run_id = run.id
|
|
task_id = task.id
|
|
|
|
def _background():
|
|
with app.app_context():
|
|
t = db.session.get(ScheduleTask, task_id)
|
|
r = db.session.get(ScheduleRun, run_id)
|
|
if not t or not r:
|
|
return
|
|
try:
|
|
run_task_now(t, trigger_type="dify_chatflow", triggered_by_user_id=None, run=r)
|
|
except Exception as exc:
|
|
current_app.logger.error("[rohs-tool] run_id=%s failed: %s", run_id, exc, exc_info=True)
|
|
r = db.session.get(ScheduleRun, run_id)
|
|
if r and r.status == "running":
|
|
r.status = "failed"
|
|
r.error_message = str(exc)
|
|
r.finished_at = datetime.utcnow()
|
|
db.session.commit()
|
|
|
|
threading.Thread(target=_background, daemon=True, name=f"rohs-check-run-{run_id}").start()
|
|
db.session.refresh(run)
|
|
return jsonify({"ok": True, "message": "检核已启动", "run": _serialize_tool_run(run)})
|
|
|
|
|
|
@rohs_check_bp.route("/tools/runs/<int:run_id>", methods=["GET"])
|
|
def get_rohs_run(run_id: int):
|
|
run = get_run(run_id)
|
|
if not run:
|
|
raise NotFoundError("run_not_found")
|
|
return jsonify({"ok": True, "run": _serialize_tool_run(run)})
|
|
|
|
|
|
@rohs_check_bp.route("/tools/runs", methods=["GET"])
|
|
def list_rohs_runs():
|
|
raw_task_id = request.args.get("task_id", type=int)
|
|
raw_limit = request.args.get("limit", default=20, type=int)
|
|
limit = max(1, min(int(raw_limit or 20), 100))
|
|
if raw_task_id is not None:
|
|
task = _resolve_check_task(task_id=raw_task_id)
|
|
query = ScheduleRun.query.filter_by(schedule_task_id=task.id)
|
|
else:
|
|
query = ScheduleRun.query.join(ScheduleTask, ScheduleTask.id == ScheduleRun.schedule_task_id)
|
|
rows = query.order_by(ScheduleRun.created_at.desc()).limit(limit).all()
|
|
runs = [_serialize_tool_run(row) for row in rows if _is_rohs_check_task(row.task)]
|
|
return jsonify({"ok": True, "runs": runs, "count": len(runs)})
|
|
|
|
|
|
@rohs_check_bp.route("/tools/runs/<int:run_id>/excel", methods=["GET"])
|
|
def download_rohs_run_excel(run_id: int):
|
|
token_payload = _decode_download_token(request.args.get("token"))
|
|
if token_payload:
|
|
if token_payload.get("scope") not in _EXCEL_TOKEN_SCOPES or int(token_payload.get("run_id") or 0) != run_id:
|
|
raise UnauthorizedError("Unauthorized")
|
|
run = get_run(run_id)
|
|
if not run:
|
|
raise NotFoundError("run_not_found")
|
|
if not run.excel_file_data:
|
|
raise ConflictError("excel_not_ready")
|
|
filename = run.excel_file_name or f"{run.run_no}.xlsx"
|
|
return send_file(
|
|
BytesIO(run.excel_file_data),
|
|
as_attachment=True,
|
|
download_name=filename,
|
|
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
)
|
|
|
|
|
|
@rohs_check_bp.route("/tools/tasks/<int:task_id>/latest-run", methods=["GET"])
|
|
def get_latest_rohs_run(task_id: int):
|
|
task = _resolve_check_task(task_id=task_id)
|
|
run = ScheduleRun.query.filter_by(schedule_task_id=task.id).order_by(ScheduleRun.id.desc()).first()
|
|
if not run:
|
|
raise NotFoundError("run_not_found")
|
|
return jsonify({"ok": True, "run": _serialize_tool_run(run)})
|
|
|
|
|
|
@rohs_check_bp.route("/tools/openapi.json", methods=["GET"])
|
|
def rohs_openapi_spec():
|
|
return jsonify(build_rohs_openapi_spec(resolve_HXOPS_TOOLS_API_BASE()))
|