107 lines
3.4 KiB
Python
107 lines
3.4 KiB
Python
"""
|
||
backend/app/jobs/store.py
|
||
|
||
用途:Job 认领与状态读写(Wave 2:KbJob 双轨 adapter,无新表)。
|
||
依赖:KbJob、各域 queue_service 的 claim/recover 逻辑。
|
||
逻辑:runner 通过 claim_next 获取待执行任务;返回归一化 dict 供 handler 分发。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
from typing import Any
|
||
|
||
from app.jobs.types import QUEUE_KB_JOB_TYPES, JobType, handler_type_for_kb_job
|
||
from app.models import KbJob
|
||
|
||
|
||
def _normalize_kb_job(job: KbJob) -> dict[str, Any]:
|
||
"""
|
||
将 KbJob ORM 实例转为 runner/handler 使用的归一化任务 dict。
|
||
Args:
|
||
job: 已 claim 的 KbJob。
|
||
Returns:
|
||
含 id、job_type(handler 键)、payload、raw_job_type 的字典。
|
||
"""
|
||
handler_type = handler_type_for_kb_job(job.job_type)
|
||
if handler_type is None:
|
||
raise ValueError(f'unsupported kb job_type={job.job_type!r}')
|
||
|
||
return {
|
||
'id': job.id,
|
||
'job_type': handler_type,
|
||
'raw_job_type': job.job_type,
|
||
'payload': {
|
||
'job_id': job.id,
|
||
'raw_job_type': job.job_type,
|
||
**(job.payload_json or {}),
|
||
},
|
||
}
|
||
|
||
|
||
def claim_next(*, queues: list[str] | None = None) -> dict[str, Any] | None:
|
||
"""
|
||
认领下一条待执行 Job(SELECT FOR UPDATE SKIP LOCKED,委托各域 queue_service)。
|
||
核心逻辑:按 queues 顺序依次尝试 kb / shipping 队列;先 recover 卡死 running 任务。
|
||
Args:
|
||
queues: worker 消费的队列名,如 ['kb'] 或 ['kb', 'shipping']。
|
||
Returns:
|
||
归一化 job dict 或 None(无任务)。
|
||
"""
|
||
queue_names = [q.strip() for q in (queues or ['kb']) if q and q.strip()]
|
||
if not queue_names:
|
||
queue_names = ['kb']
|
||
|
||
# [STEP 1] 超时回收(按队列涉及的类型)
|
||
allowed_types: set[str] = set()
|
||
for name in queue_names:
|
||
allowed_types.update(QUEUE_KB_JOB_TYPES.get(name, frozenset()))
|
||
|
||
if allowed_types & QUEUE_KB_JOB_TYPES['kb']:
|
||
from app.services.knowledge_cleaning.queue_service import recover_stale_running_jobs
|
||
|
||
recover_stale_running_jobs()
|
||
if 'shipping_notice_run' in allowed_types:
|
||
from app.services.shipping_notice.queue_service import recover_stale_shipping_notice_jobs
|
||
|
||
recover_stale_shipping_notice_jobs()
|
||
|
||
# [STEP 2] 按队列优先级 claim
|
||
for name in queue_names:
|
||
if name == 'kb':
|
||
from app.services.knowledge_cleaning.queue_service import claim_next_kb_job
|
||
|
||
job = claim_next_kb_job()
|
||
if job:
|
||
return _normalize_kb_job(job)
|
||
elif name == 'shipping':
|
||
from app.services.shipping_notice.queue_service import claim_next_shipping_notice_job
|
||
|
||
job = claim_next_shipping_notice_job()
|
||
if job:
|
||
return _normalize_kb_job(job)
|
||
|
||
return None
|
||
|
||
|
||
def mark_failed(job_id: int, *, message: str) -> None:
|
||
"""
|
||
handler 未捕获异常时,将 KbJob 标记为 failed。
|
||
Args:
|
||
job_id: KbJob 主键。
|
||
message: 失败原因(截断至 1000 字符)。
|
||
"""
|
||
from datetime import datetime
|
||
|
||
from app import db
|
||
|
||
job = db.session.get(KbJob, job_id)
|
||
if not job or job.status != 'running':
|
||
return
|
||
|
||
now = datetime.utcnow()
|
||
job.status = 'failed'
|
||
job.error_message = message[:1000]
|
||
job.message = message[:500]
|
||
job.finished_at = now
|
||
job.progress = 100
|
||
db.session.commit()
|