Files
syops/backend/app/api/file_check_tools.py
T

407 lines
15 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
backend/app/api/file_check_tools.py
用途:文件检核 Chatflow 显式 HTTP Tool API。
依赖:workspace_file_check、file_check_tools、schedule.scheduler_service。
逻辑:Dify Chatflow 调用本蓝图发起检核、查询批次、下载 Excel。
"""
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.api.workspace_file_check import serialize_file_judgement
from app.errors import AppError, ConflictError, NotFoundError, ServiceUnavailableError, UnauthorizedError, ValidationError
from app.models import ScheduleRun, ScheduleTask
from app.services.file_check_tools.openapi_spec import build_file_check_openapi_spec
from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE
from app.services.schedule.query_service import get_run, serialize_run
from app.services.schedule.scheduler_service import _generate_run_no, run_task_now
file_check_bp = Blueprint("file_check_tools", __name__)
_EXCEL_TOKEN_SCOPES = {"file_check_excel", "file_schedule_excel"}
_RUN_START_LOCK = threading.Lock()
_TASK_LOCK_KEY_BASE = 8700000000
def _tool_token_secret() -> str:
return str(
current_app.config.get("FILE_CHECK_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("[file-check-tool] download token validation failed: %s", exc)
return None
def _require_tool_auth() -> None:
configured = str(
current_app.config.get("FILE_CHECK_TOOLS_API_KEY")
or current_app.config.get("INTEGRATION_API_KEY")
or ""
).strip()
if not configured:
raise ServiceUnavailableError(
"FILE_CHECK_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
@file_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 _acquire_task_start_lock(task_id: int) -> None:
"""按 schedule_task_id 串行化同任务启动检核(PostgreSQL advisory lock)。"""
bind = db.session.get_bind()
if bind.dialect.name != "postgresql":
return
lock_key = _TASK_LOCK_KEY_BASE + int(task_id)
db.session.execute(text("SELECT pg_advisory_xact_lock(:lock_key)"), {"lock_key": lock_key})
def _build_excel_download_url(run: ScheduleRun) -> str:
import jwt
payload = {
"scope": "file_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/file-check/tools/runs/{run.id}/excel?token={token}"
@file_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"],
"judgement": serialize_file_judgement(payload),
"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")
return task
@file_check_bp.route("/tools/tasks", methods=["GET"])
def list_file_check_tasks():
"""
查询指定检核任务摘要;须传 task_id(Agent 绑定的 schedule_task_id),不再返回全量任务列表。
"""
raw_task_id = request.args.get("task_id", type=int)
if raw_task_id is None:
raise ValidationError("task_id_required")
task = _resolve_check_task(task_id=raw_task_id)
latest = (
ScheduleRun.query.filter_by(schedule_task_id=task.id)
.order_by(ScheduleRun.id.desc())
.first()
)
tasks = [{
"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})
def _normalize_bind_payload(data: dict | None) -> dict:
"""规范化启动检核 Body;兼容 Chatflow 漏传 hxops_session_id。"""
payload = dict(data or {})
session_id = str(payload.get("hxops_session_id") or "").strip()
if session_id:
return payload
conversation_id = str(payload.get("conversation_id") or "").strip()
if not conversation_id:
return payload
from app.models import ChatSession
session = ChatSession.query.filter_by(session_id=conversation_id).first()
if session:
payload["hxops_session_id"] = conversation_id
return payload
def _prepare_bind_payload(data: dict | None) -> dict:
from app.services.file_check_tools.chat_turn_registry import infer_bind_context_for_run_request
payload = _normalize_bind_payload(data)
inferred = infer_bind_context_for_run_request(payload)
if inferred:
payload = {**payload, **inferred}
return payload
def _record_run_bind(run: ScheduleRun, data: dict) -> None:
from app.services.file_check_tools.chat_log_run_binding import merge_chat_log_bind_context
from app.services.file_check_tools.chat_turn_registry import attach_run_to_turn
merge_chat_log_bind_context(run, data)
turn_id = str(data.get("hxops_turn_id") or "").strip()
if turn_id:
attach_run_to_turn(turn_id, int(run.id))
@file_check_bp.route("/tools/tasks/run", methods=["POST"])
def run_file_check():
"""立即执行检核;任务 enabled 仅控制 cron,不限制人工或 Chatflow 触发。"""
perf_started = time.perf_counter()
data = _prepare_bind_payload(request.get_json(silent=True) or {})
task = _resolve_check_task(data)
resolve_ms = int((time.perf_counter() - perf_started) * 1000)
lock_started = time.perf_counter()
with _RUN_START_LOCK:
_acquire_task_start_lock(task.id)
existing = (
ScheduleRun.query.filter_by(schedule_task_id=task.id, status="running")
.order_by(ScheduleRun.id.desc())
.first()
)
if existing:
_record_run_bind(existing, data)
db.session.commit()
lock_ms = int((time.perf_counter() - lock_started) * 1000)
total_ms = int((time.perf_counter() - perf_started) * 1000)
current_app.logger.info(
"[file-check-tool-perf] run_file_check outcome=check_running resolve_ms=%s lock_ms=%s total_ms=%s run_id=%s",
resolve_ms,
lock_ms,
total_ms,
existing.id,
)
return jsonify({
"ok": False,
"error_code": "check_running",
"message": "该检核任务正在执行中,请稍后查询结果",
"run": _serialize_tool_run(existing),
})
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"),
"hxops_session_id": data.get("hxops_session_id"),
"hxops_turn_id": data.get("hxops_turn_id"),
"user_message": data.get("user_message"),
},
)
db.session.add(run)
db.session.commit()
_record_run_bind(run, data)
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("[file-check-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"file-check-run-{run_id}").start()
db.session.refresh(run)
lock_ms = int((time.perf_counter() - lock_started) * 1000)
total_ms = int((time.perf_counter() - perf_started) * 1000)
current_app.logger.info(
"[file-check-tool-perf] run_file_check outcome=started resolve_ms=%s lock_ms=%s total_ms=%s run_id=%s",
resolve_ms,
lock_ms,
total_ms,
run_id,
)
return jsonify({"ok": True, "message": "检核已启动", "run": _serialize_tool_run(run)})
@file_check_bp.route("/tools/runs/<int:run_id>", methods=["GET"])
def get_file_check_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)})
@file_check_bp.route("/tools/runs", methods=["GET"])
def list_file_check_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]
return jsonify({"ok": True, "runs": runs, "count": len(runs)})
@file_check_bp.route("/tools/runs/<int:run_id>/excel", methods=["GET"])
def download_file_check_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",
)
@file_check_bp.route("/tools/tasks/<int:task_id>/latest-run", methods=["GET"])
def get_latest_file_check_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)})
@file_check_bp.route("/tools/openapi.json", methods=["GET"])
def file_check_openapi_spec():
return jsonify(build_file_check_openapi_spec(resolve_HXOPS_TOOLS_API_BASE()))