refactor(file-check): 增强文件检核服务,新增可靠性元信息与错误分类
This commit is contained in:
1 parent
f72c1c9f0e
commit
090281835a
14 files changed
+1093
-151
No files matched your search
+232
-63
@@ -324,6 +324,116 @@ class DifyService:
|
||||
}
|
||||
return data
|
||||
|
||||
@staticmethod
|
||||
def _classify_workflow_request_exception(exc: Exception) -> tuple[str, bool]:
|
||||
"""
|
||||
将 Workflow HTTP/网络异常归类为 error_type,并判断是否可重试。
|
||||
502/503/504 与连接/读超时视为可恢复;400/401/403 不重试。
|
||||
"""
|
||||
if isinstance(exc, requests.exceptions.ConnectTimeout):
|
||||
return "connect_timeout", True
|
||||
if isinstance(exc, requests.exceptions.ReadTimeout):
|
||||
return "read_timeout", True
|
||||
if isinstance(exc, requests.exceptions.ConnectionError):
|
||||
return "connection_error", True
|
||||
if isinstance(exc, requests.exceptions.HTTPError):
|
||||
status = int(getattr(getattr(exc, "response", None), "status_code", 0) or 0)
|
||||
if status in (502, 503, 504):
|
||||
return f"http_{status}", True
|
||||
if status in (400, 401, 403):
|
||||
return f"http_{status}", False
|
||||
return f"http_{status}", False
|
||||
return "request_error", False
|
||||
|
||||
@staticmethod
|
||||
def _attach_workflow_reliability_meta(
|
||||
result: dict[str, Any],
|
||||
*,
|
||||
poll_used: bool = False,
|
||||
retry_count: int = 0,
|
||||
error_type: str | None = None,
|
||||
workflow_run_id: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""在 Dify Workflow 响应上附加网关侧可靠性元信息(poll/重试/错误类型)。"""
|
||||
out = dict(result) if isinstance(result, dict) else {}
|
||||
if workflow_run_id and not out.get("workflow_run_id"):
|
||||
out["workflow_run_id"] = workflow_run_id
|
||||
out["_workflow_poll_used"] = bool(poll_used)
|
||||
out["_workflow_retry_count"] = max(0, int(retry_count))
|
||||
if error_type:
|
||||
out["_workflow_error_type"] = error_type
|
||||
return out
|
||||
|
||||
@staticmethod
|
||||
def _consume_workflow_stream(
|
||||
*,
|
||||
url: str,
|
||||
headers: dict[str, str],
|
||||
payload: dict[str, Any],
|
||||
timeout: tuple[int, int],
|
||||
state: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
执行一次 Workflow streaming POST 并消费 SSE 直至 workflow_finished。
|
||||
state 在解析过程中写入 workflow_run_id / result,供断连后补偿使用。
|
||||
"""
|
||||
result: dict[str, Any] = {}
|
||||
|
||||
with requests.post(url, headers=headers, json=payload, stream=True, timeout=timeout) as resp:
|
||||
if not resp.ok:
|
||||
body = resp.text[:2000]
|
||||
if current_app:
|
||||
current_app.logger.error(
|
||||
"[workflow-streaming] dify error status=%s url=%s body=%s",
|
||||
resp.status_code, url, body,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
|
||||
for line in resp.iter_lines(decode_unicode=True):
|
||||
if not line:
|
||||
continue
|
||||
if not line.startswith("data:"):
|
||||
continue
|
||||
raw = line[len("data:"):].strip()
|
||||
if not raw:
|
||||
continue
|
||||
try:
|
||||
evt = json.loads(raw)
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
|
||||
event_type = evt.get("event", "")
|
||||
|
||||
if event_type == "workflow_started":
|
||||
run_id = (evt.get("data") or {}).get("workflow_run_id")
|
||||
state["workflow_run_id"] = run_id
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[workflow-streaming] started run_id=%s",
|
||||
run_id,
|
||||
)
|
||||
|
||||
elif event_type == "workflow_finished":
|
||||
result = evt.get("data") or {}
|
||||
state["result"] = result
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[workflow-streaming] finished status=%s error=%s",
|
||||
result.get("status"),
|
||||
result.get("error"),
|
||||
)
|
||||
|
||||
elif event_type == "error":
|
||||
err_msg = evt.get("message") or str(evt)
|
||||
if current_app:
|
||||
current_app.logger.error(
|
||||
"[workflow-streaming] dify stream error: %s",
|
||||
err_msg,
|
||||
)
|
||||
raise RuntimeError(f"Dify workflow error: {err_msg}")
|
||||
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
def run_workflow_streaming(
|
||||
*,
|
||||
@@ -332,6 +442,10 @@ class DifyService:
|
||||
user: str = "system",
|
||||
timeout: tuple[int, int] = (5, 300),
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
调用 Dify Workflow(streaming),并在断连/超时时优先 poll 补偿结果。
|
||||
对可恢复网络错误最多重试 1 次;返回体附带 _workflow_* 可靠性元信息。
|
||||
"""
|
||||
base_url = agent.api_base_url if getattr(agent, "api_base_url", None) else Config.DIFY_API_BASE
|
||||
url = DifyService._build_workflow_url(base_url)
|
||||
|
||||
@@ -344,6 +458,12 @@ class DifyService:
|
||||
"response_mode": "streaming",
|
||||
"user": str(user or "system"),
|
||||
}
|
||||
max_wait = timeout[1] if isinstance(timeout, tuple) else 300
|
||||
max_attempts = 2
|
||||
retry_count = 0
|
||||
poll_used = False
|
||||
last_error_type: str | None = None
|
||||
last_workflow_run_id: str | None = None
|
||||
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
@@ -354,86 +474,135 @@ class DifyService:
|
||||
)
|
||||
|
||||
result: dict[str, Any] = {}
|
||||
workflow_run_id: str | None = None
|
||||
stream_state: dict[str, Any] = {"workflow_run_id": None, "result": {}}
|
||||
|
||||
try:
|
||||
with requests.post(url, headers=headers, json=payload, stream=True, timeout=timeout) as resp:
|
||||
if not resp.ok:
|
||||
body = resp.text[:2000]
|
||||
for attempt in range(max_attempts):
|
||||
try:
|
||||
result = DifyService._consume_workflow_stream(
|
||||
url=url,
|
||||
headers=headers,
|
||||
payload=payload,
|
||||
timeout=timeout,
|
||||
state=stream_state,
|
||||
)
|
||||
workflow_run_id = stream_state.get("workflow_run_id")
|
||||
if workflow_run_id:
|
||||
last_workflow_run_id = workflow_run_id
|
||||
|
||||
# [STEP] 连接正常结束但未收到 workflow_finished 时,用 poll 补偿最终结果
|
||||
if not result and workflow_run_id:
|
||||
poll_used = True
|
||||
if current_app:
|
||||
current_app.logger.error(
|
||||
"[workflow-streaming] dify error status=%s url=%s body=%s",
|
||||
resp.status_code, url, body,
|
||||
current_app.logger.warning(
|
||||
"[workflow-streaming] stream closed without finished event, polling run_id=%s",
|
||||
workflow_run_id,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
result = DifyService._poll_workflow_result(
|
||||
agent=agent,
|
||||
workflow_run_id=workflow_run_id,
|
||||
max_wait=max_wait,
|
||||
)
|
||||
poll_error_type = None if result else "poll_timeout"
|
||||
return DifyService._attach_workflow_reliability_meta(
|
||||
result,
|
||||
poll_used=True,
|
||||
retry_count=retry_count,
|
||||
error_type=poll_error_type or "stream_closed_early",
|
||||
workflow_run_id=workflow_run_id,
|
||||
)
|
||||
|
||||
for line in resp.iter_lines(decode_unicode=True):
|
||||
if not line:
|
||||
continue
|
||||
if not line.startswith("data:"):
|
||||
continue
|
||||
raw = line[len("data:"):].strip()
|
||||
if not raw:
|
||||
continue
|
||||
try:
|
||||
evt = json.loads(raw)
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
|
||||
event_type = evt.get("event", "")
|
||||
|
||||
if event_type == "workflow_started":
|
||||
workflow_run_id = (evt.get("data") or {}).get("workflow_run_id")
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[workflow-streaming] started run_id=%s",
|
||||
workflow_run_id,
|
||||
)
|
||||
|
||||
elif event_type == "workflow_finished":
|
||||
result = evt.get("data") or {}
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[workflow-streaming] finished status=%s error=%s",
|
||||
result.get("status"),
|
||||
result.get("error"),
|
||||
)
|
||||
|
||||
elif event_type == "error":
|
||||
err_msg = evt.get("message") or str(evt)
|
||||
if current_app:
|
||||
current_app.logger.error(
|
||||
"[workflow-streaming] dify stream error: %s",
|
||||
err_msg,
|
||||
)
|
||||
raise RuntimeError(f"Dify workflow error: {err_msg}")
|
||||
|
||||
except requests.exceptions.RequestException as exc:
|
||||
if result:
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[workflow-streaming] connection dropped but result already captured",
|
||||
"[workflow-streaming] attempt=%s finished run_id=%s retry_count=%s",
|
||||
attempt + 1,
|
||||
workflow_run_id,
|
||||
retry_count,
|
||||
)
|
||||
elif workflow_run_id:
|
||||
return DifyService._attach_workflow_reliability_meta(
|
||||
result,
|
||||
poll_used=False,
|
||||
retry_count=retry_count,
|
||||
workflow_run_id=workflow_run_id,
|
||||
)
|
||||
except requests.exceptions.RequestException as exc:
|
||||
error_type, retryable = DifyService._classify_workflow_request_exception(exc)
|
||||
last_error_type = error_type
|
||||
workflow_run_id = stream_state.get("workflow_run_id")
|
||||
partial_result = stream_state.get("result") or {}
|
||||
if workflow_run_id:
|
||||
last_workflow_run_id = workflow_run_id
|
||||
|
||||
if current_app:
|
||||
current_app.logger.warning(
|
||||
"[workflow-streaming] connection dropped, polling result for run_id=%s",
|
||||
"[workflow-streaming] attempt=%s error_type=%s retryable=%s run_id=%s err=%s",
|
||||
attempt + 1,
|
||||
error_type,
|
||||
retryable,
|
||||
workflow_run_id,
|
||||
exc,
|
||||
)
|
||||
result = DifyService._poll_workflow_result(
|
||||
agent=agent,
|
||||
workflow_run_id=workflow_run_id,
|
||||
max_wait=timeout[1] if isinstance(timeout, tuple) else 300,
|
||||
)
|
||||
else:
|
||||
|
||||
if partial_result:
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[workflow-streaming] connection dropped but result already captured run_id=%s",
|
||||
workflow_run_id,
|
||||
)
|
||||
return DifyService._attach_workflow_reliability_meta(
|
||||
partial_result,
|
||||
poll_used=False,
|
||||
retry_count=retry_count,
|
||||
error_type=error_type,
|
||||
workflow_run_id=workflow_run_id,
|
||||
)
|
||||
|
||||
if workflow_run_id:
|
||||
poll_used = True
|
||||
if current_app:
|
||||
current_app.logger.warning(
|
||||
"[workflow-streaming] polling after disconnect run_id=%s error_type=%s",
|
||||
workflow_run_id,
|
||||
error_type,
|
||||
)
|
||||
result = DifyService._poll_workflow_result(
|
||||
agent=agent,
|
||||
workflow_run_id=workflow_run_id,
|
||||
max_wait=max_wait,
|
||||
)
|
||||
poll_error_type = None if result else "poll_timeout"
|
||||
return DifyService._attach_workflow_reliability_meta(
|
||||
result,
|
||||
poll_used=True,
|
||||
retry_count=retry_count,
|
||||
error_type=poll_error_type or error_type,
|
||||
workflow_run_id=workflow_run_id,
|
||||
)
|
||||
|
||||
if retryable and attempt < max_attempts - 1:
|
||||
retry_count += 1
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[workflow-streaming] retrying attempt=%s error_type=%s",
|
||||
attempt + 2,
|
||||
error_type,
|
||||
)
|
||||
continue
|
||||
|
||||
if current_app:
|
||||
current_app.logger.error(
|
||||
"[workflow-streaming] request error (no run_id): %s",
|
||||
"[workflow-streaming] request failed (no run_id) error_type=%s err=%s",
|
||||
error_type,
|
||||
exc,
|
||||
)
|
||||
raise
|
||||
|
||||
return result if isinstance(result, dict) else {}
|
||||
return DifyService._attach_workflow_reliability_meta(
|
||||
result if isinstance(result, dict) else {},
|
||||
poll_used=poll_used,
|
||||
retry_count=retry_count,
|
||||
error_type=last_error_type,
|
||||
workflow_run_id=last_workflow_run_id,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _poll_workflow_result(
|
||||
|
||||
Reference in new issue
Block a user