feat(rohs-check): 新增 RoHS 检核执行进度中增加 Excel 下载功能及相关配置
This commit is contained in:
1 parent
ee39270069
commit
599d492895
14 files changed
+845
-272
No files matched your search
@@ -1218,7 +1218,7 @@ def chat_completions():
|
||||
if provider_conversation_id and provider_conversation_id != known_provider_conversation_id:
|
||||
known_provider_conversation_id = provider_conversation_id
|
||||
should_touch = True
|
||||
if event_name == 'message_end':
|
||||
if event_name in ('message_end', 'workflow_finished'):
|
||||
known_status = 'done'
|
||||
should_touch = True
|
||||
elif event_name == 'error':
|
||||
|
||||
@@ -255,7 +255,7 @@ def run_rohs_check():
|
||||
"error_code": "check_running",
|
||||
"message": "该检核任务正在执行中,请稍后查询结果",
|
||||
"run": _serialize_tool_run(existing),
|
||||
}), 409
|
||||
})
|
||||
|
||||
run = ScheduleRun(
|
||||
run_no=_generate_run_no(),
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import Blueprint, jsonify, request
|
||||
from io import BytesIO
|
||||
|
||||
from flask import Blueprint, jsonify, request, send_file
|
||||
|
||||
from app.auth_jwt import get_current_user
|
||||
from app.errors import ForbiddenError, NotFoundError, UnauthorizedError
|
||||
@@ -90,7 +92,7 @@ def _serialize_progress_run(run: ScheduleRun) -> dict:
|
||||
"excel": {
|
||||
"file_name": payload.get("excel_file_name"),
|
||||
"file_size": payload.get("excel_file_size"),
|
||||
"download_url": f"/api/workspace/schedule-runs/{run.id}/excel" if payload.get("excel_file_name") else None,
|
||||
"download_url": f"/api/workspace/rohs-check/runs/{run.id}/excel" if payload.get("excel_file_name") else None,
|
||||
},
|
||||
"knowledge_base": {
|
||||
"sync_status": payload.get("kb_sync_status"),
|
||||
@@ -133,3 +135,21 @@ def workspace_rohs_run_detail(run_id: int):
|
||||
if not _is_rohs_check_task(run.task):
|
||||
raise ForbiddenError("Forbidden")
|
||||
return jsonify({"ok": True, "run": _serialize_progress_run(run)})
|
||||
|
||||
|
||||
@workspace_rohs_check_bp.route("/rohs-check/runs/<int:run_id>/excel", methods=["GET"])
|
||||
def workspace_rohs_run_excel(run_id: int):
|
||||
_require_user()
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
raise NotFoundError("run_not_found")
|
||||
if not _is_rohs_check_task(run.task):
|
||||
raise ForbiddenError("Forbidden")
|
||||
if not run.excel_file_data:
|
||||
raise NotFoundError("excel_not_found")
|
||||
return send_file(
|
||||
BytesIO(run.excel_file_data),
|
||||
as_attachment=True,
|
||||
download_name=run.excel_file_name or f"{run.run_no}.xlsx",
|
||||
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
)
|
||||
@@ -90,6 +90,8 @@ class Config:
|
||||
# Dify 网关配置
|
||||
DIFY_API_BASE = os.getenv('DIFY_API_BASE')
|
||||
DIFY_API_KEY = os.getenv('DIFY_API_KEY')
|
||||
DIFY_CHAT_CONNECT_TIMEOUT_SECONDS = int(os.getenv('DIFY_CHAT_CONNECT_TIMEOUT_SECONDS', '5'))
|
||||
DIFY_CHAT_READ_TIMEOUT_SECONDS = int(os.getenv('DIFY_CHAT_READ_TIMEOUT_SECONDS', '30'))
|
||||
# Redis 连接配置,默认使用本地 Redis + 密码
|
||||
REDIS_URL = os.getenv('REDIS_URL')
|
||||
FEEDBACK_ENABLED = os.getenv('FEEDBACK_ENABLED', 'true').lower() == 'true'
|
||||
|
||||
+161
-56
@@ -27,7 +27,7 @@ import os
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime, timedelta
|
||||
from threading import Lock
|
||||
from threading import Lock, Thread
|
||||
from typing import Any, List, Optional
|
||||
|
||||
import requests
|
||||
@@ -567,78 +567,76 @@ class DifyService:
|
||||
full_answer: List[str] = []
|
||||
retriever_resources: List[Any] = []
|
||||
attribution_parts: List[str] = []
|
||||
chat_logged = False
|
||||
chat_persist_started = False
|
||||
has_sent_answer = False
|
||||
|
||||
def persist_stream_chat(data: dict, event_name: str) -> None:
|
||||
nonlocal chat_logged
|
||||
if chat_logged:
|
||||
persist_stream_chat_async(data, event_name)
|
||||
|
||||
def persist_stream_chat_async(data: dict, event_name: str) -> None:
|
||||
nonlocal chat_persist_started
|
||||
if chat_persist_started:
|
||||
return
|
||||
chat_persist_started = True
|
||||
|
||||
if data.get('answer'):
|
||||
full_answer.append(data.get('answer', ''))
|
||||
app_obj = current_app._get_current_object() if current_app else None
|
||||
persist_data = json.loads(json.dumps(data, ensure_ascii=False, default=str))
|
||||
resources_snapshot = json.loads(json.dumps(retriever_resources, ensure_ascii=False, default=str))
|
||||
attribution_snapshot = list(attribution_parts)
|
||||
answer_snapshot = build_final_answer_text(persist_data, event_name)
|
||||
latency_snapshot = int((time.time() - start_time) * 1000)
|
||||
|
||||
def _persist() -> None:
|
||||
if not app_obj:
|
||||
return
|
||||
with app_obj.app_context():
|
||||
DifyService._persist_stream_chat_record(
|
||||
data=persist_data,
|
||||
event_name=event_name,
|
||||
request_id=request_id,
|
||||
user_id=user_id,
|
||||
agent_id=agent.id,
|
||||
session_id=session_id,
|
||||
normalized_conversation_id=normalized_conversation_id,
|
||||
query=query,
|
||||
answer_text=answer_snapshot,
|
||||
latency=latency_snapshot,
|
||||
retriever_resources=resources_snapshot,
|
||||
attribution_parts=attribution_snapshot,
|
||||
)
|
||||
|
||||
Thread(target=_persist, daemon=True, name=f"dify-chat-persist-{request_id or 'unknown'}").start()
|
||||
|
||||
def build_final_answer_text(data: dict, event_name: str) -> str:
|
||||
answer_text = ''.join(full_answer).strip()
|
||||
if data.get('answer'):
|
||||
answer_text = (answer_text + str(data.get('answer') or '')).strip()
|
||||
|
||||
if not answer_text and event_name == 'workflow_finished':
|
||||
wf_data = data.get('data') or {}
|
||||
outputs = wf_data.get('outputs') if isinstance(wf_data, dict) else None
|
||||
if isinstance(outputs, dict):
|
||||
for key in ('answer', 'text', 'result'):
|
||||
for key in ('answer', 'final_answer', 'output', 'text', 'result', 'message'):
|
||||
value = outputs.get(key)
|
||||
if isinstance(value, str) and value.strip():
|
||||
answer_text = value.strip()
|
||||
break
|
||||
if not answer_text:
|
||||
for value in outputs.values():
|
||||
if isinstance(value, str) and value.strip():
|
||||
answer_text = value.strip()
|
||||
break
|
||||
return answer_text
|
||||
|
||||
if not answer_text and not str(query or '').strip():
|
||||
return
|
||||
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[source-link] persist chat request_id=%s event=%s collected retriever_resources=%s",
|
||||
request_id,
|
||||
event_name,
|
||||
len(retriever_resources),
|
||||
)
|
||||
DifyService._enrich_retriever_resources_with_source_urls(retriever_resources)
|
||||
|
||||
metadata = data.get('metadata') or {}
|
||||
metadata['retriever_resources'] = retriever_resources
|
||||
data['metadata'] = metadata
|
||||
data['retriever_resources'] = retriever_resources
|
||||
|
||||
latency = int((time.time() - start_time) * 1000)
|
||||
usage = metadata.get('usage', {}) or {}
|
||||
db_write_started = time.time()
|
||||
with current_app.app_context():
|
||||
chat_log_id = DifyService._log_chat(
|
||||
user_id=user_id,
|
||||
agent_id=agent.id,
|
||||
session_id=session_id,
|
||||
conversation_id=data.get('conversation_id') or normalized_conversation_id,
|
||||
query=query,
|
||||
answer=answer_text,
|
||||
tokens=usage.get('total_tokens', 0),
|
||||
latency=latency,
|
||||
retriever_resources=retriever_resources,
|
||||
attribution_parts=attribution_parts,
|
||||
)
|
||||
if chat_log_id:
|
||||
data['chat_log_id'] = chat_log_id
|
||||
chat_logged = True
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[chat-perf] persisted request_id=%s event=%s total_ms=%s db_write_ms=%s answer_len=%s conversation_id=%s",
|
||||
request_id,
|
||||
event_name,
|
||||
latency,
|
||||
int((time.time() - db_write_started) * 1000),
|
||||
len(answer_text),
|
||||
data.get('conversation_id') or normalized_conversation_id,
|
||||
)
|
||||
|
||||
max_retries = 3
|
||||
for attempt in range(1, max_retries + 1):
|
||||
try:
|
||||
with requests.post(url, headers=headers, json=payload, stream=True, timeout=(5, 300)) as response:
|
||||
connect_timeout = max(1, int(getattr(Config, "DIFY_CHAT_CONNECT_TIMEOUT_SECONDS", 5) or 5))
|
||||
read_timeout = max(5, int(getattr(Config, "DIFY_CHAT_READ_TIMEOUT_SECONDS", 30) or 30))
|
||||
if attempt == 1:
|
||||
yield f"data: {json.dumps({'event': 'upstream_start', 'message': '正在连接 Dify'}, ensure_ascii=False)}\n\n"
|
||||
with requests.post(url, headers=headers, json=payload, stream=True, timeout=(connect_timeout, read_timeout)) as response:
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[chat-stream] dify response request_id=%s status=%s reason=%s attempt=%s",
|
||||
@@ -665,6 +663,7 @@ class DifyService:
|
||||
time.sleep(attempt * 2)
|
||||
continue
|
||||
response.raise_for_status()
|
||||
yield f"data: {json.dumps({'event': 'upstream_connected', 'message': 'Dify 已连接'}, ensure_ascii=False)}\n\n"
|
||||
|
||||
for line in response.iter_lines():
|
||||
if not line:
|
||||
@@ -696,6 +695,8 @@ class DifyService:
|
||||
|
||||
if event == 'message':
|
||||
message_count += 1
|
||||
if data.get('answer'):
|
||||
has_sent_answer = True
|
||||
if first_token_at is None:
|
||||
first_token_at = time.time()
|
||||
if current_app:
|
||||
@@ -709,20 +710,66 @@ class DifyService:
|
||||
DifyService._collect_metadata(retriever_resources, attribution_parts, data)
|
||||
|
||||
elif event in ('message_end', 'agent_message', 'workflow_finished'):
|
||||
if event in ('message_end', 'workflow_finished') or data.get('answer'):
|
||||
has_sent_answer = True
|
||||
DifyService._collect_metadata(retriever_resources, attribution_parts, data)
|
||||
|
||||
if event == 'workflow_finished' and not data.get('answer'):
|
||||
final_answer = build_final_answer_text(data, event)
|
||||
if final_answer:
|
||||
data['answer'] = final_answer
|
||||
data['replace_answer'] = True
|
||||
|
||||
if event in ('message_end', 'workflow_finished'):
|
||||
persist_stream_chat(data, event)
|
||||
|
||||
yield f"data: {json.dumps(data, ensure_ascii=False)}\n\n"
|
||||
if event in ('message_end', 'workflow_finished'):
|
||||
break
|
||||
break
|
||||
except requests.exceptions.RequestException as e:
|
||||
if current_app:
|
||||
current_app.logger.exception("[chat-stream] request exception request_id=%s attempt=%s: %s", request_id, attempt, e)
|
||||
if attempt < max_retries:
|
||||
is_timeout = isinstance(e, (requests.exceptions.ReadTimeout, requests.exceptions.ConnectTimeout))
|
||||
if isinstance(e, requests.exceptions.ReadTimeout) and has_sent_answer:
|
||||
if current_app:
|
||||
current_app.logger.warning(
|
||||
"[chat-stream] read timeout after answer request_id=%s attempt=%s; finish stream silently",
|
||||
request_id,
|
||||
attempt,
|
||||
)
|
||||
persist_stream_chat(
|
||||
{
|
||||
'event': 'message_end',
|
||||
'conversation_id': normalized_conversation_id,
|
||||
'answer': ''.join(full_answer).strip(),
|
||||
'metadata': {},
|
||||
},
|
||||
'message_end',
|
||||
)
|
||||
break
|
||||
if not is_timeout and attempt < max_retries:
|
||||
time.sleep(attempt * 2)
|
||||
continue
|
||||
error_msg = json.dumps({'event': 'error', 'message': str(e)})
|
||||
if isinstance(e, requests.exceptions.ReadTimeout):
|
||||
message = (
|
||||
f"Dify 在 {int(getattr(Config, 'DIFY_CHAT_READ_TIMEOUT_SECONDS', 30) or 30)} 秒内没有返回响应。"
|
||||
"请检查 Dify 应用地址/API Key、Chatflow 是否发布,以及 Dify 服务是否能正常执行。"
|
||||
)
|
||||
elif isinstance(e, requests.exceptions.ConnectTimeout):
|
||||
message = "连接 Dify 超时,请检查 Dify API Base URL 和网络连通性。"
|
||||
else:
|
||||
message = str(e)
|
||||
persist_stream_chat(
|
||||
{
|
||||
'event': 'error',
|
||||
'conversation_id': normalized_conversation_id,
|
||||
'answer': f"[Error: {message}]",
|
||||
'metadata': {},
|
||||
},
|
||||
'error',
|
||||
)
|
||||
error_msg = json.dumps({'event': 'error', 'message': message})
|
||||
yield f"data: {error_msg}\n\n"
|
||||
|
||||
@staticmethod
|
||||
@@ -775,6 +822,64 @@ class DifyService:
|
||||
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _persist_stream_chat_record(
|
||||
*,
|
||||
data: dict,
|
||||
event_name: str,
|
||||
request_id: str | None,
|
||||
user_id: int,
|
||||
agent_id: int,
|
||||
session_id: str | None,
|
||||
normalized_conversation_id: str | None,
|
||||
query: str,
|
||||
answer_text: str,
|
||||
latency: int,
|
||||
retriever_resources: List[Any],
|
||||
attribution_parts: List[str],
|
||||
) -> None:
|
||||
if not answer_text and not str(query or '').strip():
|
||||
return
|
||||
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[source-link] persist chat request_id=%s event=%s collected retriever_resources=%s",
|
||||
request_id,
|
||||
event_name,
|
||||
len(retriever_resources),
|
||||
)
|
||||
DifyService._enrich_retriever_resources_with_source_urls(retriever_resources)
|
||||
|
||||
metadata = data.get('metadata') if isinstance(data.get('metadata'), dict) else {}
|
||||
metadata['retriever_resources'] = retriever_resources
|
||||
data['metadata'] = metadata
|
||||
data['retriever_resources'] = retriever_resources
|
||||
|
||||
usage = metadata.get('usage', {}) or {}
|
||||
db_write_started = time.time()
|
||||
chat_log_id = DifyService._log_chat(
|
||||
user_id=user_id,
|
||||
agent_id=agent_id,
|
||||
session_id=session_id,
|
||||
conversation_id=data.get('conversation_id') or normalized_conversation_id,
|
||||
query=query,
|
||||
answer=answer_text,
|
||||
tokens=usage.get('total_tokens', 0),
|
||||
latency=latency,
|
||||
retriever_resources=retriever_resources,
|
||||
attribution_parts=attribution_parts,
|
||||
)
|
||||
if chat_log_id and current_app:
|
||||
current_app.logger.info(
|
||||
"[chat-perf] persisted async request_id=%s event=%s total_ms=%s db_write_ms=%s answer_len=%s conversation_id=%s",
|
||||
request_id,
|
||||
event_name,
|
||||
latency,
|
||||
int((time.time() - db_write_started) * 1000),
|
||||
len(answer_text),
|
||||
data.get('conversation_id') or normalized_conversation_id,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _normalize_resources(resources):
|
||||
"""
|
||||
|
||||
@@ -12,26 +12,38 @@
|
||||
}
|
||||
],
|
||||
"security": [
|
||||
{ "BearerAuth": [] },
|
||||
{ "IntegrationKey": [] }
|
||||
{
|
||||
"BearerAuth": []
|
||||
},
|
||||
{
|
||||
"IntegrationKey": []
|
||||
}
|
||||
],
|
||||
"paths": {
|
||||
"/api/rohs-check/tools/tasks": {
|
||||
"get": {
|
||||
"operationId": "list_rohs_tasks",
|
||||
"summary": "查询 RoHS 检核任务列表",
|
||||
"tags": ["RoHS Check"],
|
||||
"tags": [
|
||||
"RoHS Check"
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "成功",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/ListTasksResponse" }
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ListTasksResponse"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": { "$ref": "#/components/responses/Unauthorized" },
|
||||
"503": { "$ref": "#/components/responses/MissingAuth" }
|
||||
"401": {
|
||||
"$ref": "#/components/responses/Unauthorized"
|
||||
},
|
||||
"503": {
|
||||
"$ref": "#/components/responses/MissingAuth"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -39,35 +51,46 @@
|
||||
"post": {
|
||||
"operationId": "run_rohs_check",
|
||||
"summary": "异步启动 RoHS 检核",
|
||||
"tags": ["RoHS Check"],
|
||||
"tags": [
|
||||
"RoHS Check"
|
||||
],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/RunCheckRequest" }
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/RunCheckRequest"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "启动成功",
|
||||
"description": "启动成功;或已有 RoHS 检核进行中,返回 ok=false/error_code=check_running",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/RunCheckSuccessResponse" }
|
||||
"schema": {
|
||||
"oneOf": [
|
||||
{
|
||||
"$ref": "#/components/schemas/RunCheckSuccessResponse"
|
||||
},
|
||||
{
|
||||
"$ref": "#/components/schemas/CheckRunningResponse"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"409": {
|
||||
"description": "RoHS 检核进行中,全局不可重复启动",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/CheckRunningResponse" }
|
||||
}
|
||||
}
|
||||
"400": {
|
||||
"$ref": "#/components/responses/BadRequest"
|
||||
},
|
||||
"400": { "$ref": "#/components/responses/BadRequest" },
|
||||
"401": { "$ref": "#/components/responses/Unauthorized" },
|
||||
"404": { "$ref": "#/components/responses/TaskNotFound" }
|
||||
"401": {
|
||||
"$ref": "#/components/responses/Unauthorized"
|
||||
},
|
||||
"404": {
|
||||
"$ref": "#/components/responses/TaskNotFound"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -75,20 +98,30 @@
|
||||
"get": {
|
||||
"operationId": "list_rohs_runs",
|
||||
"summary": "查询 RoHS 检核批次列表",
|
||||
"tags": ["RoHS Check"],
|
||||
"tags": [
|
||||
"RoHS Check"
|
||||
],
|
||||
"parameters": [
|
||||
{
|
||||
"name": "task_id",
|
||||
"in": "query",
|
||||
"required": false,
|
||||
"schema": { "type": "integer", "example": 12 },
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"example": 12
|
||||
},
|
||||
"description": "可选;指定检核任务 ID 时只返回该任务批次"
|
||||
},
|
||||
{
|
||||
"name": "limit",
|
||||
"in": "query",
|
||||
"required": false,
|
||||
"schema": { "type": "integer", "minimum": 1, "maximum": 100, "default": 20 },
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"maximum": 100,
|
||||
"default": 20
|
||||
},
|
||||
"description": "返回条数,最大 100"
|
||||
}
|
||||
],
|
||||
@@ -97,12 +130,18 @@
|
||||
"description": "成功",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/ListRunsResponse" }
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ListRunsResponse"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": { "$ref": "#/components/responses/Unauthorized" },
|
||||
"404": { "$ref": "#/components/responses/TaskNotFound" }
|
||||
"401": {
|
||||
"$ref": "#/components/responses/Unauthorized"
|
||||
},
|
||||
"404": {
|
||||
"$ref": "#/components/responses/TaskNotFound"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -110,13 +149,18 @@
|
||||
"get": {
|
||||
"operationId": "get_rohs_run",
|
||||
"summary": "查询指定检核批次",
|
||||
"tags": ["RoHS Check"],
|
||||
"tags": [
|
||||
"RoHS Check"
|
||||
],
|
||||
"parameters": [
|
||||
{
|
||||
"name": "run_id",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"schema": { "type": "integer", "example": 88 }
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"example": 88
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
@@ -124,12 +168,18 @@
|
||||
"description": "成功",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/GetRunResponse" }
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/GetRunResponse"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": { "$ref": "#/components/responses/Unauthorized" },
|
||||
"404": { "$ref": "#/components/responses/RunNotFound" }
|
||||
"401": {
|
||||
"$ref": "#/components/responses/Unauthorized"
|
||||
},
|
||||
"404": {
|
||||
"$ref": "#/components/responses/RunNotFound"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -137,13 +187,18 @@
|
||||
"get": {
|
||||
"operationId": "get_latest_rohs_run",
|
||||
"summary": "查询检核任务最近一次检核",
|
||||
"tags": ["RoHS Check"],
|
||||
"tags": [
|
||||
"RoHS Check"
|
||||
],
|
||||
"parameters": [
|
||||
{
|
||||
"name": "task_id",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"schema": { "type": "integer", "example": 12 }
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"example": 12
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
@@ -151,12 +206,18 @@
|
||||
"description": "成功",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/GetRunResponse" }
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/GetRunResponse"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": { "$ref": "#/components/responses/Unauthorized" },
|
||||
"404": { "$ref": "#/components/responses/RunNotFound" }
|
||||
"401": {
|
||||
"$ref": "#/components/responses/Unauthorized"
|
||||
},
|
||||
"404": {
|
||||
"$ref": "#/components/responses/RunNotFound"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -164,21 +225,28 @@
|
||||
"get": {
|
||||
"operationId": "download_rohs_run_excel",
|
||||
"summary": "下载检核报告 Excel(短期签名 token)",
|
||||
"tags": ["RoHS Check"],
|
||||
"tags": [
|
||||
"RoHS Check"
|
||||
],
|
||||
"security": [],
|
||||
"parameters": [
|
||||
{
|
||||
"name": "run_id",
|
||||
"in": "path",
|
||||
"required": true,
|
||||
"schema": { "type": "integer", "example": 88 }
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"example": 88
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "token",
|
||||
"in": "query",
|
||||
"required": true,
|
||||
"description": "由 get_rohs_run 返回的 excel.download_url 中的 JWT,有效期 600 秒",
|
||||
"schema": { "type": "string" }
|
||||
"schema": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
@@ -186,11 +254,16 @@
|
||||
"description": "Excel 文件流",
|
||||
"content": {
|
||||
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": {
|
||||
"schema": { "type": "string", "format": "binary" }
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"format": "binary"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"409": { "$ref": "#/components/responses/ExcelNotReady" }
|
||||
"409": {
|
||||
"$ref": "#/components/responses/ExcelNotReady"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -213,20 +286,51 @@
|
||||
"TaskSummary": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"task_id": { "type": "integer", "example": 12 },
|
||||
"task_no": { "type": "string", "example": "CHK202606090001" },
|
||||
"name": { "type": "string", "example": "RoHS 自动检核" },
|
||||
"enabled": { "type": "boolean" },
|
||||
"last_status": { "type": "string", "nullable": true, "example": "success" },
|
||||
"last_run_at": { "type": "string", "format": "date-time", "nullable": true },
|
||||
"next_run_at": { "type": "string", "format": "date-time", "nullable": true }
|
||||
"task_id": {
|
||||
"type": "integer",
|
||||
"example": 12
|
||||
},
|
||||
"task_no": {
|
||||
"type": "string",
|
||||
"example": "CHK202606090001"
|
||||
},
|
||||
"name": {
|
||||
"type": "string",
|
||||
"example": "RoHS 自动检核"
|
||||
},
|
||||
"enabled": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"last_status": {
|
||||
"type": "string",
|
||||
"nullable": true,
|
||||
"example": "success"
|
||||
},
|
||||
"last_run_at": {
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"nullable": true
|
||||
},
|
||||
"next_run_at": {
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"nullable": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"RunExcel": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"file_name": { "type": "string", "nullable": true, "example": "RUN202606090001.xlsx" },
|
||||
"file_size": { "type": "integer", "nullable": true, "example": 45678 },
|
||||
"file_name": {
|
||||
"type": "string",
|
||||
"nullable": true,
|
||||
"example": "RUN202606090001.xlsx"
|
||||
},
|
||||
"file_size": {
|
||||
"type": "integer",
|
||||
"nullable": true,
|
||||
"example": 45678
|
||||
},
|
||||
"download_url": {
|
||||
"type": "string",
|
||||
"nullable": true,
|
||||
@@ -237,111 +341,265 @@
|
||||
"RunKnowledgeBase": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"enabled": { "type": "boolean" },
|
||||
"enabled": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"sync_status": {
|
||||
"type": "string",
|
||||
"nullable": true,
|
||||
"enum": ["skipped", "queued", "cleaning", "syncing", "ready", "success", "failed"]
|
||||
"enum": [
|
||||
"skipped",
|
||||
"queued",
|
||||
"cleaning",
|
||||
"syncing",
|
||||
"ready",
|
||||
"success",
|
||||
"failed"
|
||||
]
|
||||
},
|
||||
"group_id": { "type": "integer", "nullable": true },
|
||||
"document_id": { "type": "integer", "nullable": true },
|
||||
"document_version_id": { "type": "integer", "nullable": true },
|
||||
"sync_job_id": { "type": "integer", "nullable": true },
|
||||
"error_message": { "type": "string", "nullable": true }
|
||||
"group_id": {
|
||||
"type": "integer",
|
||||
"nullable": true
|
||||
},
|
||||
"document_id": {
|
||||
"type": "integer",
|
||||
"nullable": true
|
||||
},
|
||||
"document_version_id": {
|
||||
"type": "integer",
|
||||
"nullable": true
|
||||
},
|
||||
"sync_job_id": {
|
||||
"type": "integer",
|
||||
"nullable": true
|
||||
},
|
||||
"error_message": {
|
||||
"type": "string",
|
||||
"nullable": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"RunDetail": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"run_id": { "type": "integer", "example": 88 },
|
||||
"run_no": { "type": "string", "example": "RUN202606090001" },
|
||||
"task_id": { "type": "integer", "example": 12 },
|
||||
"task_name": { "type": "string", "example": "RoHS 自动检核" },
|
||||
"run_id": {
|
||||
"type": "integer",
|
||||
"example": 88
|
||||
},
|
||||
"run_no": {
|
||||
"type": "string",
|
||||
"example": "RUN202606090001"
|
||||
},
|
||||
"task_id": {
|
||||
"type": "integer",
|
||||
"example": 12
|
||||
},
|
||||
"task_name": {
|
||||
"type": "string",
|
||||
"example": "RoHS 自动检核"
|
||||
},
|
||||
"status": {
|
||||
"type": "string",
|
||||
"enum": ["running", "success", "partial_failed", "failed", "queued", "cancelled"]
|
||||
"enum": [
|
||||
"running",
|
||||
"success",
|
||||
"partial_failed",
|
||||
"failed",
|
||||
"queued",
|
||||
"cancelled"
|
||||
]
|
||||
},
|
||||
"total_count": { "type": "integer" },
|
||||
"success_count": { "type": "integer" },
|
||||
"failed_count": { "type": "integer" },
|
||||
"skipped_count": { "type": "integer" },
|
||||
"started_at": { "type": "string", "format": "date-time", "nullable": true },
|
||||
"finished_at": { "type": "string", "format": "date-time", "nullable": true },
|
||||
"duration_ms": { "type": "integer", "nullable": true },
|
||||
"error_message": { "type": "string", "nullable": true },
|
||||
"excel": { "$ref": "#/components/schemas/RunExcel" },
|
||||
"knowledge_base": { "$ref": "#/components/schemas/RunKnowledgeBase" }
|
||||
"total_count": {
|
||||
"type": "integer"
|
||||
},
|
||||
"success_count": {
|
||||
"type": "integer"
|
||||
},
|
||||
"failed_count": {
|
||||
"type": "integer"
|
||||
},
|
||||
"skipped_count": {
|
||||
"type": "integer"
|
||||
},
|
||||
"started_at": {
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"nullable": true
|
||||
},
|
||||
"finished_at": {
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"nullable": true
|
||||
},
|
||||
"duration_ms": {
|
||||
"type": "integer",
|
||||
"nullable": true
|
||||
},
|
||||
"error_message": {
|
||||
"type": "string",
|
||||
"nullable": true
|
||||
},
|
||||
"excel": {
|
||||
"$ref": "#/components/schemas/RunExcel"
|
||||
},
|
||||
"knowledge_base": {
|
||||
"$ref": "#/components/schemas/RunKnowledgeBase"
|
||||
}
|
||||
}
|
||||
},
|
||||
"ListTasksResponse": {
|
||||
"type": "object",
|
||||
"required": ["ok", "tasks"],
|
||||
"required": [
|
||||
"ok",
|
||||
"tasks"
|
||||
],
|
||||
"properties": {
|
||||
"ok": { "type": "boolean", "example": true },
|
||||
"ok": {
|
||||
"type": "boolean",
|
||||
"example": true
|
||||
},
|
||||
"tasks": {
|
||||
"type": "array",
|
||||
"items": { "$ref": "#/components/schemas/TaskSummary" }
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/TaskSummary"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"RunCheckRequest": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"task_id": { "type": "integer", "example": 12 },
|
||||
"task_no": { "type": "string", "example": "CHK202606090001" },
|
||||
"trigger_source": { "type": "string", "default": "dify_chatflow" },
|
||||
"conversation_id": { "type": "string", "nullable": true },
|
||||
"user_message": { "type": "string", "nullable": true }
|
||||
"task_id": {
|
||||
"type": "integer",
|
||||
"example": 12
|
||||
},
|
||||
"task_no": {
|
||||
"type": "string",
|
||||
"example": "CHK202606090001"
|
||||
},
|
||||
"trigger_source": {
|
||||
"type": "string",
|
||||
"default": "dify_chatflow"
|
||||
},
|
||||
"conversation_id": {
|
||||
"type": "string",
|
||||
"nullable": true
|
||||
},
|
||||
"user_message": {
|
||||
"type": "string",
|
||||
"nullable": true
|
||||
}
|
||||
},
|
||||
"required": ["task_id"],
|
||||
"required": [
|
||||
"task_id"
|
||||
],
|
||||
"description": "Chatflow Start 节点固定配置 task_id;后端仍兼容 task_no,但 RoHS Chatflow 不使用任务选择流程"
|
||||
},
|
||||
"RunCheckSuccessResponse": {
|
||||
"type": "object",
|
||||
"required": ["ok", "message", "run"],
|
||||
"required": [
|
||||
"ok",
|
||||
"message",
|
||||
"run"
|
||||
],
|
||||
"properties": {
|
||||
"ok": { "type": "boolean", "example": true },
|
||||
"message": { "type": "string", "example": "检核已启动" },
|
||||
"run": { "$ref": "#/components/schemas/RunDetail" }
|
||||
"ok": {
|
||||
"type": "boolean",
|
||||
"example": true
|
||||
},
|
||||
"message": {
|
||||
"type": "string",
|
||||
"example": "检核已启动"
|
||||
},
|
||||
"run": {
|
||||
"$ref": "#/components/schemas/RunDetail"
|
||||
}
|
||||
}
|
||||
},
|
||||
"CheckRunningResponse": {
|
||||
"type": "object",
|
||||
"required": ["ok", "error_code", "message", "run"],
|
||||
"required": [
|
||||
"ok",
|
||||
"error_code",
|
||||
"message",
|
||||
"run"
|
||||
],
|
||||
"properties": {
|
||||
"ok": { "type": "boolean", "example": false },
|
||||
"error_code": { "type": "string", "example": "check_running" },
|
||||
"message": { "type": "string", "example": "该检核任务正在执行中,请稍后查询结果" },
|
||||
"run": { "$ref": "#/components/schemas/RunDetail" }
|
||||
"ok": {
|
||||
"type": "boolean",
|
||||
"example": false
|
||||
},
|
||||
"error_code": {
|
||||
"type": "string",
|
||||
"example": "check_running"
|
||||
},
|
||||
"message": {
|
||||
"type": "string",
|
||||
"example": "该检核任务正在执行中,请稍后查询结果"
|
||||
},
|
||||
"run": {
|
||||
"$ref": "#/components/schemas/RunDetail"
|
||||
}
|
||||
}
|
||||
},
|
||||
"GetRunResponse": {
|
||||
"type": "object",
|
||||
"required": ["ok", "run"],
|
||||
"required": [
|
||||
"ok",
|
||||
"run"
|
||||
],
|
||||
"properties": {
|
||||
"ok": { "type": "boolean", "example": true },
|
||||
"run": { "$ref": "#/components/schemas/RunDetail" }
|
||||
"ok": {
|
||||
"type": "boolean",
|
||||
"example": true
|
||||
},
|
||||
"run": {
|
||||
"$ref": "#/components/schemas/RunDetail"
|
||||
}
|
||||
}
|
||||
},
|
||||
"ListRunsResponse": {
|
||||
"type": "object",
|
||||
"required": ["ok", "runs", "count"],
|
||||
"required": [
|
||||
"ok",
|
||||
"runs",
|
||||
"count"
|
||||
],
|
||||
"properties": {
|
||||
"ok": { "type": "boolean", "example": true },
|
||||
"count": { "type": "integer", "example": 2 },
|
||||
"ok": {
|
||||
"type": "boolean",
|
||||
"example": true
|
||||
},
|
||||
"count": {
|
||||
"type": "integer",
|
||||
"example": 2
|
||||
},
|
||||
"runs": {
|
||||
"type": "array",
|
||||
"items": { "$ref": "#/components/schemas/RunDetail" }
|
||||
"items": {
|
||||
"$ref": "#/components/schemas/RunDetail"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"ErrorResponse": {
|
||||
"type": "object",
|
||||
"required": ["ok", "error_code", "message"],
|
||||
"required": [
|
||||
"ok",
|
||||
"error_code",
|
||||
"message"
|
||||
],
|
||||
"properties": {
|
||||
"ok": { "type": "boolean", "example": false },
|
||||
"error_code": { "type": "string" },
|
||||
"message": { "type": "string" }
|
||||
"ok": {
|
||||
"type": "boolean",
|
||||
"example": false
|
||||
},
|
||||
"error_code": {
|
||||
"type": "string"
|
||||
},
|
||||
"message": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -350,13 +608,23 @@
|
||||
"description": "鉴权失败",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/ErrorResponse" },
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ErrorResponse"
|
||||
},
|
||||
"examples": {
|
||||
"missing_auth": {
|
||||
"value": { "ok": false, "error_code": "missing_auth", "message": "missing_auth" }
|
||||
"value": {
|
||||
"ok": false,
|
||||
"error_code": "missing_auth",
|
||||
"message": "missing_auth"
|
||||
}
|
||||
},
|
||||
"invalid_auth": {
|
||||
"value": { "ok": false, "error_code": "invalid_auth", "message": "invalid_auth" }
|
||||
"value": {
|
||||
"ok": false,
|
||||
"error_code": "invalid_auth",
|
||||
"message": "invalid_auth"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -366,7 +634,9 @@
|
||||
"description": "服务端未配置 ROHS_TOOLS_API_KEY / INTEGRATION_API_KEY",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/ErrorResponse" },
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ErrorResponse"
|
||||
},
|
||||
"example": {
|
||||
"ok": false,
|
||||
"error_code": "missing_auth",
|
||||
@@ -379,7 +649,9 @@
|
||||
"description": "请求参数无效",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/ErrorResponse" },
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ErrorResponse"
|
||||
},
|
||||
"example": {
|
||||
"ok": false,
|
||||
"error_code": "invalid_request",
|
||||
@@ -392,7 +664,9 @@
|
||||
"description": "检核任务不存在",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/ErrorResponse" },
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ErrorResponse"
|
||||
},
|
||||
"example": {
|
||||
"ok": false,
|
||||
"error_code": "task_not_found",
|
||||
@@ -405,7 +679,9 @@
|
||||
"description": "检核批次不存在",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/ErrorResponse" },
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ErrorResponse"
|
||||
},
|
||||
"example": {
|
||||
"ok": false,
|
||||
"error_code": "run_not_found",
|
||||
@@ -418,7 +694,9 @@
|
||||
"description": "Excel 尚未生成",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": { "$ref": "#/components/schemas/ErrorResponse" },
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/ErrorResponse"
|
||||
},
|
||||
"example": {
|
||||
"ok": false,
|
||||
"error_code": "excel_not_ready",
|
||||
@@ -430,6 +708,3 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -106,7 +106,7 @@ _MAX_DIFY_RESPONSE_LEN = 4000
|
||||
|
||||
|
||||
def _ts() -> str:
|
||||
return datetime.utcnow().isoformat()
|
||||
return datetime.utcnow().replace(microsecond=0).isoformat() + "Z"
|
||||
|
||||
|
||||
def _make_step(
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
"""Resync PostgreSQL serial sequences after manual imports or restores."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
from dotenv import load_dotenv
|
||||
from sqlalchemy import create_engine, text
|
||||
|
||||
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
|
||||
load_dotenv(os.path.join(ROOT, ".env.shared"))
|
||||
load_dotenv(os.path.join(ROOT, ".env.dev"))
|
||||
load_dotenv(os.path.join(ROOT, ".env.local"), override=True)
|
||||
|
||||
TABLES = ("chat_logs", "schedule_runs")
|
||||
|
||||
|
||||
def fix_sequence(conn, table: str) -> None:
|
||||
max_id = conn.execute(text(f"SELECT COALESCE(MAX(id), 0) FROM {table}")).scalar()
|
||||
seq = conn.execute(
|
||||
text("SELECT pg_get_serial_sequence(:table, 'id')"),
|
||||
{"table": table},
|
||||
).scalar()
|
||||
if not seq:
|
||||
print(f"{table}: no serial sequence, skipped")
|
||||
return
|
||||
before = conn.execute(text(f"SELECT last_value, is_called FROM {seq}")).fetchone()
|
||||
conn.execute(text("SELECT setval(:seq, :val, true)"), {"seq": seq, "val": max_id})
|
||||
after = conn.execute(text(f"SELECT last_value, is_called FROM {seq}")).fetchone()
|
||||
print(f"{table} max_id={max_id} sequence={seq}")
|
||||
print(f" before: last_value={before[0]} is_called={before[1]}")
|
||||
print(f" after: last_value={after[0]} is_called={after[1]}")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
url = os.environ.get("DATABASE_URL")
|
||||
if not url:
|
||||
print("DATABASE_URL not set", file=sys.stderr)
|
||||
return 1
|
||||
tables = sys.argv[1:] or TABLES
|
||||
engine = create_engine(url)
|
||||
with engine.begin() as conn:
|
||||
for table in tables:
|
||||
fix_sequence(conn, table)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,30 @@
|
||||
"""One-off: resync schedule_runs.id sequence after manual imports."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
from dotenv import load_dotenv
|
||||
from sqlalchemy import create_engine, text
|
||||
|
||||
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
|
||||
load_dotenv(os.path.join(ROOT, ".env.shared"))
|
||||
load_dotenv(os.path.join(ROOT, ".env.dev"))
|
||||
load_dotenv(os.path.join(ROOT, ".env.local"), override=True)
|
||||
|
||||
url = os.environ.get("DATABASE_URL")
|
||||
if not url:
|
||||
print("DATABASE_URL not set", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
engine = create_engine(url)
|
||||
with engine.begin() as conn:
|
||||
max_id = conn.execute(text("SELECT COALESCE(MAX(id), 0) FROM schedule_runs")).scalar()
|
||||
seq = conn.execute(text("SELECT pg_get_serial_sequence('schedule_runs', 'id')")).scalar()
|
||||
before = conn.execute(text(f"SELECT last_value, is_called FROM {seq}")).fetchone()
|
||||
conn.execute(text("SELECT setval(:seq, :val, true)"), {"seq": seq, "val": max_id})
|
||||
after = conn.execute(text(f"SELECT last_value, is_called FROM {seq}")).fetchone()
|
||||
|
||||
print(f"schedule_runs max_id={max_id} sequence={seq}")
|
||||
print(f"before: last_value={before[0]} is_called={before[1]}")
|
||||
print(f"after: last_value={after[0]} is_called={after[1]}")
|
||||
@@ -271,8 +271,9 @@ def test_rohs_tool_running_conflict(app, client):
|
||||
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
|
||||
json={'task_id': task_id},
|
||||
)
|
||||
assert res.status_code == 409
|
||||
assert res.status_code == 200
|
||||
data = res.get_json()
|
||||
assert data['ok'] is False
|
||||
assert data['error_code'] == 'check_running'
|
||||
|
||||
|
||||
@@ -331,8 +332,9 @@ def test_rohs_tool_running_conflict_is_global(app, client):
|
||||
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
|
||||
json={'task_id': second_task_id},
|
||||
)
|
||||
assert res.status_code == 409
|
||||
assert res.status_code == 200
|
||||
data = res.get_json()
|
||||
assert data['ok'] is False
|
||||
assert data['error_code'] == 'check_running'
|
||||
assert data['run']['run_id'] == running_id
|
||||
|
||||
|
||||
Reference in new issue
Block a user