Files
life-echo/api/app/core/task_tracker.py
Kevin 309a051038 feat: 回忆录证据血缘与内部评测可追溯,顺带对齐本地评测台与 CI
数据库与模型:新增多版迁移(章节证据快照、对话血缘、记忆事实/时间线 lineage 等),把「成稿 ↔ 对话/记忆」的溯源信息落到表结构里。
业务链路:会话与 WS、回忆录/故事流水线、记忆写入与 enrichment 等跟着接上线索与快照;新增章节证据快照与评测侧 EvalTraceService 等模块,方便组评审用的证据包。
内部评测:自动化 run 与手工 memoir 评审共用可追溯证据;rubric/ judge 相关脚本与文档有配套调整。
app-eval-web:Memoir/实验详情里能展开看证据摘要与 evidence_trace(含对话轮次 id);Vite 代理与 development.sh 注入的 API 端口与当前默认内部评测端口一致,避免改端口后页面连错服务。
工程杂项:GitHub Actions / 仓库说明有更新;各适配器与支付/配额/plan 等多处为小改动或跟随主改动的收尾;新增/扩充了?
2026-04-08 15:37:09 +08:00

118 lines
4.0 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.
"""
任务追踪服务:追踪 Celery 任务状态(从 services 迁入 core
"""
import json
from datetime import datetime, timezone
from typing import Any, Dict, List
from app.core.logging import get_logger
from app.core.redis import redis_service
logger = get_logger(__name__)
class TaskTracker:
"""任务追踪器,使用 Redis 存储任务状态"""
KEY_PREFIX = "task:user:"
TASK_TTL = 3600
async def add_task(
self, user_id: str, task_id: str, task_type: str = "memoir"
) -> bool:
try:
client = await redis_service.get_client()
key = f"{self.KEY_PREFIX}{user_id}:tasks"
task_info = {
"task_id": task_id,
"task_type": task_type,
"status": "pending",
"created_at": datetime.now(timezone.utc).isoformat(),
}
await client.hset(key, task_id, json.dumps(task_info))
await client.expire(key, self.TASK_TTL)
logger.debug("任务已记录: user_id={}, task_id={}", user_id, task_id)
return True
except Exception as e:
logger.error("记录任务失败: {}", e)
return False
async def update_task_status(
self, user_id: str, task_id: str, status: str, result: Any = None
) -> bool:
try:
client = await redis_service.get_client()
key = f"{self.KEY_PREFIX}{user_id}:tasks"
data = await client.hget(key, task_id)
if data:
task_info = json.loads(data)
else:
task_info = {"task_id": task_id}
task_info["status"] = status
task_info["updated_at"] = datetime.now(timezone.utc).isoformat()
if result is not None:
task_info["result"] = result
await client.hset(key, task_id, json.dumps(task_info))
return True
except Exception as e:
logger.error("更新任务状态失败: {}", e)
return False
async def get_user_tasks(self, user_id: str) -> List[Dict]:
try:
client = await redis_service.get_client()
key = f"{self.KEY_PREFIX}{user_id}:tasks"
tasks_data = await client.hgetall(key)
return [json.loads(data) for data in tasks_data.values()]
except Exception as e:
logger.error("获取用户任务失败: {}", e)
return []
async def get_pending_tasks(self, user_id: str) -> List[Dict]:
tasks = await self.get_user_tasks(user_id)
return [t for t in tasks if t.get("status") in ("pending", "running")]
async def check_tasks_status(self, user_id: str) -> Dict:
tasks = await self.get_user_tasks(user_id)
status_counts: Dict[str, int] = {
"total": len(tasks),
"pending": 0,
"running": 0,
"success": 0,
"failure": 0,
}
for task in tasks:
status = task.get("status", "pending")
if status in status_counts:
status_counts[status] += 1
status_counts["all_completed"] = (
status_counts["total"] > 0
and status_counts["pending"] == 0
and status_counts["running"] == 0
)
return status_counts
async def clear_user_tasks(self, user_id: str) -> bool:
try:
client = await redis_service.get_client()
key = f"{self.KEY_PREFIX}{user_id}:tasks"
await client.delete(key)
return True
except Exception as e:
logger.error("清除用户任务失败: {}", e)
return False
async def remove_task(self, user_id: str, task_id: str) -> bool:
try:
client = await redis_service.get_client()
key = f"{self.KEY_PREFIX}{user_id}:tasks"
await client.hdel(key, task_id)
return True
except Exception as e:
logger.error("移除任务失败: {}", e)
return False
task_tracker = TaskTracker()