detail.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. from utils.sync_mysql_help import mysql
  2. from utils.params import CapabilityEnum
  3. from loguru import logger
  4. import sys
  5. import json
  6. from typing import Optional, Dict, Any
  7. logger.add(sink=sys.stderr, level="ERROR", backtrace=True, diagnose=True)
  8. # 任务状态常量
  9. STATUS_PENDING = 0 # 待处理
  10. STATUS_RUNNING = 1 # 执行中
  11. STATUS_SUCCESS = 2 # 成功
  12. STATUS_FAILED = 3 # 失败
  13. # 不需要查询结果的状态(失败状态需要查询 error_message,因此不在此集合中)
  14. STATUS_WITHOUT_RESULT = {STATUS_PENDING, STATUS_RUNNING}
  15. def _build_response(data: Dict[str, Any]) -> Dict[str, Any]:
  16. """构建统一响应格式"""
  17. response = {
  18. "code": 0,
  19. "msg": "ok",
  20. "data": data
  21. }
  22. return response
  23. def _parse_result_payload(payload: Optional[str]) -> Any:
  24. """解析结果负载(JSON字符串转对象)"""
  25. if not payload:
  26. return None
  27. try:
  28. return json.loads(payload)
  29. except (json.JSONDecodeError, TypeError):
  30. return payload
  31. def _parse_web_url(web_url: Optional[str]) -> Any:
  32. """解析结果表中的 web_url 字段(JSON 字符串 -> 对象)"""
  33. if not web_url:
  34. return None
  35. try:
  36. return json.loads(web_url)
  37. except (json.JSONDecodeError, TypeError):
  38. # 如果不是合法 JSON,则原样返回,避免接口直接报错
  39. return web_url
  40. def _fetch_decode_result(task_id: str) -> Optional[Dict[str, Any]]:
  41. """获取解构任务结果"""
  42. sql = "SELECT result_payload, error_message, web_url FROM workflow_decode_task_result WHERE task_id = %s"
  43. result_record = mysql.fetchone(sql, (task_id,))
  44. if not result_record:
  45. return None
  46. return {
  47. "result": _parse_result_payload(result_record.get("result_payload")),
  48. "error_message": result_record.get("error_message"),
  49. "url": _parse_web_url(result_record.get("web_url"))
  50. }
  51. def _build_result_data(
  52. task_id: str,
  53. status: int,
  54. result: Any = None,
  55. reason: Optional[str] = None,
  56. url: Any = None
  57. ) -> Dict[str, Any]:
  58. """构建结果数据"""
  59. data: Dict[str, Any] = {
  60. "taskId": task_id,
  61. "status": status,
  62. "result": result,
  63. "reason": reason
  64. }
  65. # 对于解构任务,增加 url 字段(data.url.pointUrl / data.url.weightUrl)
  66. if url is not None:
  67. data["url"] = url
  68. return data
  69. def _handle_success_status(task_id: str, capability: int) -> Dict[str, Any]:
  70. """处理成功状态(status=2)"""
  71. # 只有解构任务需要查询结果表
  72. if capability != CapabilityEnum.DECODE.value:
  73. return _build_response(_build_result_data(task_id, STATUS_SUCCESS))
  74. # 查询解构结果
  75. decode_result = _fetch_decode_result(task_id)
  76. if not decode_result:
  77. return _build_response(_build_result_data(task_id, STATUS_SUCCESS))
  78. result_data = _build_result_data(
  79. task_id=task_id,
  80. status=STATUS_SUCCESS,
  81. result=decode_result.get("result"),
  82. reason=decode_result.get("error_message"),
  83. url=decode_result.get("url")
  84. )
  85. return _build_response(
  86. result_data
  87. )
  88. def get_decode_detail_by_task_id(task_id: str) -> Optional[Dict[str, Any]]:
  89. """获取任务详情"""
  90. # 查询任务基本信息
  91. sql = "SELECT task_id, status, capability FROM workflow_task WHERE task_id = %s"
  92. task = mysql.fetchone(sql, (task_id,))
  93. if not task:
  94. logger.info(f"task_id = {task_id} , 任务不存在")
  95. return None
  96. task_id_value = task.get("task_id")
  97. status = task.get("status")
  98. capability = task.get("capability")
  99. # 不需要查询结果的状态,直接返回
  100. if status in STATUS_WITHOUT_RESULT:
  101. result_data = _build_result_data(task_id_value, status)
  102. return _build_response(result_data)
  103. # 成功状态,需要查询结果
  104. if status == STATUS_SUCCESS:
  105. return _handle_success_status(task_id_value, capability)
  106. # 失败状态,需要返回 error_message 到 reason 字段,result 固定为 "[]"
  107. if status == STATUS_FAILED:
  108. error_message: Optional[str] = None
  109. # 仅对解构任务从结果表中查询失败原因
  110. if capability == CapabilityEnum.DECODE.value:
  111. decode_result = _fetch_decode_result(task_id_value)
  112. if decode_result:
  113. error_message = decode_result.get("error_message")
  114. result_data = _build_result_data(
  115. task_id=task_id_value,
  116. status=STATUS_FAILED,
  117. result="[]",
  118. reason=error_message or ""
  119. )
  120. return _build_response(
  121. result_data
  122. )
  123. # 其他未知状态,返回基础数据
  124. result_data = _build_result_data(task_id_value, status)
  125. return _build_response(result_data)