72 lines
2.8 KiB
Python
72 lines
2.8 KiB
Python
"""进行中的任务如何把自己「此刻在做什么」说出来。
|
||
|
||
为什么需要这一层:出图动辄四十几秒、出片动辄十几分钟,而调用模型的那段代码埋在
|
||
适配器深处(``providers/comfy_common.py``),手里既没有会话也不知道 task_id。
|
||
以前它什么都说不出来,界面上就只剩一个转圈的图标——用户分不清「模型正在算」
|
||
和「排在别人的任务后面」,只能一遍遍刷新页面去猜。
|
||
|
||
做法:执行线程起跑时把 task_id 绑到 thread-local(见 ``jobs/handlers.run``),
|
||
深处任何一层调 ``report("排队中:等待算力空闲")`` 就能写回任务行;
|
||
不在任务上下文里(普通请求线程)静默返回,调用点因此不需要判空。
|
||
|
||
写入走**另一条会话**并立刻提交:执行线程自己那条会话正握着业务事务,
|
||
在深处顺手 commit 会把事务提前收掉,半途失败的素材状态就会对不上。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import logging
|
||
import threading
|
||
from typing import Any
|
||
|
||
from sqlalchemy import update
|
||
|
||
from app.db import SessionLocal
|
||
from app.models import Task, now_utc
|
||
|
||
log = logging.getLogger("nex.progress")
|
||
|
||
_local = threading.local()
|
||
|
||
#: message 列宽 400,超了按字符砍掉——宁可截断也不要当场报错
|
||
MAX_MESSAGE_CHARS = 400
|
||
|
||
|
||
def bind(task_id: int) -> None:
|
||
"""声明「当前线程正在执行这条任务」;由 handlers.run 统一调用。"""
|
||
_local.task_id = int(task_id)
|
||
|
||
|
||
def unbind() -> None:
|
||
_local.task_id = None
|
||
|
||
|
||
def current_task_id() -> int | None:
|
||
return getattr(_local, "task_id", None)
|
||
|
||
|
||
def report(message: str, *, progress: float | None = None) -> None:
|
||
"""给进行中的任务补一句解释(可顺带推进度);不在任务上下文里时什么都不做。
|
||
|
||
这里**只写不读**、且永远不改 status:状态归执行体自己收口,
|
||
深处这一层只负责把过程说清楚,失败了也不该影响正在跑的模型调用。
|
||
"""
|
||
task_id = current_task_id()
|
||
if not task_id:
|
||
return
|
||
patch: dict[str, Any] = {"message": message[:MAX_MESSAGE_CHARS], "heartbeat_at": now_utc()}
|
||
if progress is not None:
|
||
patch["progress"] = max(0.0, min(1.0, float(progress)))
|
||
session = SessionLocal()
|
||
try:
|
||
session.execute(update(Task).where(Task.id == task_id).values(**patch)
|
||
.execution_options(synchronize_session=False))
|
||
session.commit()
|
||
except Exception as exc: # noqa: BLE001 - 说不出来不等于做错了
|
||
log.debug("任务 #%s 状态说明回写失败:%s", task_id, exc)
|
||
session.rollback()
|
||
finally:
|
||
session.close()
|
||
|
||
|
||
__all__ = ["MAX_MESSAGE_CHARS", "bind", "current_task_id", "report", "unbind"]
|