This commit is contained in:
2026-04-23 00:49:22 +08:00
parent 882756412e
commit cccb0920ae
5 changed files with 314 additions and 312 deletions
+25 -99
View File
@@ -12,6 +12,9 @@ from core.geometry_analyzer import GeometryAnalyzer
from utils.file_handler import FileHandler
from utils.html_generator import HTMLGenerator
from services.storage_integration_rustfs import StorageIntegrationService
from services.redis_task_manager import redis_task_manager
from services.processing_service import processing_service
from services.task_query_service import TaskQueryService
from database.database import get_db_session
from utils.logger import get_logger
from sqlalchemy.ext.asyncio import AsyncSession
@@ -58,10 +61,12 @@ tasks = {}
@router.get("/health")
@router.post("/health")
async def health():
task_count = await redis_task_manager.get_task_count()
return {
"status": "healthy",
"pythonocc": True,
"total_tasks": len(tasks)
"total_tasks": task_count,
"redis_connected": redis_task_manager.is_connected,
}
@@ -97,8 +102,8 @@ async def upload_stp(
# 创建处理任务记录
await storage_service.create_processing_task(db_session, task_id, stp_file.id)
# 创建内存任务记录
tasks[task_id] = create_task_info(
# 创建任务记录(Redis 为主,内存为兼容回退)
task_info = create_task_info(
task_id=task_id,
status=ProcessingStatus.PROCESSING,
filename=file.filename,
@@ -106,9 +111,14 @@ async def upload_stp(
file_size=file_size,
upload_time=str(datetime.now())
)
await redis_task_manager.set_task(task_id, task_info)
tasks[task_id] = task_info
# 后台处理(包含数据库存储)
background_tasks.add_task(process_file_with_storage, task_id, file_path, stp_file.id, db_session, material)
# 后台处理(统一走 ProcessingService,使用独立数据库会话)
background_tasks.add_task(
processing_service.process_file_with_storage,
task_id, file_path, stp_file.id, material
)
return {
"task_id": task_id,
@@ -134,99 +144,12 @@ async def get_status(task_id: str, db_session: AsyncSession = Depends(get_db_ses
结构与内存任务保持尽量一致,便于前端集中展示总结性信息。
"""
try:
# 1. 内存任务(进行中的任务)
if task_id in tasks:
task = tasks[task_id]
logger.info(f"返回内存任务状态:{task_id} - {task['status']}")
logger.info(f"内存任务 analysis_result: {task.get('analysis_result', 'None')}")
logger.info(f"内存任务 html_file: {task.get('html_file', 'None')}")
return task
# 2. 持久化任务(已完成/失败,或服务重启后的任务)
from sqlalchemy import select
from models.database import ProcessingTask, STPFile, GeometryData, MeshData, MoldCavityData
storage_service = StorageIntegrationService()
# 查询任务和文件元数据
result = await db_session.execute(
select(ProcessingTask, STPFile)
.join(STPFile, ProcessingTask.stp_file_id == STPFile.id)
.where(ProcessingTask.task_id == task_id)
)
row = result.first()
if not row:
task_view = await TaskQueryService.get_task_view(db_session, task_id)
if task_view is None:
# 兼容老的仅内存任务
if task_id in tasks:
return tasks[task_id]
raise HTTPException(404, "任务不存在")
processing_task, stp_file = row
# 从 RustFS 取几何 / 型腔 / 网格详细 JSON(小量数据,便于前端展示汇总)
try:
file_with_data = await storage_service.get_stp_file_with_data(
db_session, stp_file_id=stp_file.id
)
except Exception as e:
logger.error(f"获取文件数据失败: {e}")
file_with_data = {}
geometry_json: Optional[Dict[str, Any]] = None
if file_with_data.get("geometry_data"):
geo_raw = file_with_data["geometry_data"]
if isinstance(geo_raw, dict):
if "geometry_data" in geo_raw:
geometry_json = geo_raw["geometry_data"]
else:
geometry_json = geo_raw
cavity_json: Optional[Dict[str, Any]] = file_with_data.get("mold_cavity_data")
features_json: List[Dict[str, Any]] = file_with_data.get("features", [])
recommendations_json: List[Dict[str, Any]] = file_with_data.get("recommendations", [])
# 组装网格摘要
mesh_summary = None
mesh_record = await db_session.execute(
select(MeshData).where(MeshData.stp_file_id == stp_file.id)
)
mesh_record = mesh_record.scalar_one_or_none()
if mesh_record:
mesh_summary = {
"vertex_count": mesh_record.vertex_count,
"face_count": mesh_record.face_count,
"point_count": mesh_record.point_count,
"quality": mesh_record.quality,
}
# 构造与内存任务兼容的任务视图
task_view = {
"task_id": processing_task.task_id,
"status": processing_task.status,
"filename": stp_file.original_filename if stp_file else "",
"file_path": stp_file.file_path or "",
"file_size": stp_file.file_size if stp_file else 0,
"upload_time": processing_task.created_time.isoformat()
if processing_task.created_time
else "",
"completed_at": processing_task.completed_time.isoformat()
if processing_task.completed_time
else "",
"geometry_data": geometry_json,
"key_info": cavity_json,
"cavity_data": cavity_json,
"mesh_summary": mesh_summary,
"analysis_result": {
"geometry_data": geometry_json,
"detected_features": features_json,
"design_recommendations": recommendations_json,
"quality_metrics": {
"volume_utilization": file_with_data.get("analysis_metrics", {}).get("volume_utilization", 0),
"topology_complexity": file_with_data.get("analysis_metrics", {}).get("topology_complexity", 0),
"wall_uniformity": file_with_data.get("analysis_metrics", {}).get("wall_uniformity", 0)
},
"analysis_summary": file_with_data.get("analysis_metrics", {}).get("analysis_summary", "分析完成")
} if geometry_json or features_json or recommendations_json else None,
"error": processing_task.error_message or stp_file.error_message or None,
}
logger.info(f"返回持久化任务状态: {task_id} - {processing_task.status}")
return task_view
except HTTPException:
raise
@@ -239,9 +162,12 @@ async def get_status(task_id: str, db_session: AsyncSession = Depends(get_db_ses
@router.post("/debug/tasks")
async def debug_tasks():
"""调试接口:查看所有任务"""
all_tasks = await redis_task_manager.get_all_tasks()
return {
"total_tasks": len(tasks),
"tasks": tasks
"total_tasks": len(all_tasks),
"tasks": all_tasks,
"redis_connected": redis_task_manager.is_connected,
"memory_fallback_tasks": len(tasks),
}