Files
syops/backend/app/jobs/store.py
T
hugo 0cc6506c0d Merge branch 'hugo-shipping-notice' into dev
# Conflicts:
#	backend/app/jobs/store.py
2026-09-27 20:44:24 +08:00

217 lines
8.2 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.
"""
backend/app/jobs/store.py
用途:Job 认领与状态读写(KbJob 双轨 adapter + 通用 Job)。
依赖:KbJob、各域 queue_service 的 claim/recover 逻辑。
逻辑:runner 通过 claim_next 获取 kb / shipping / contract / schedule / transfer 任务;返回归一化 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 Job, KbJob
def _normalize_generic_job(job: Job) -> dict[str, Any]:
"""将通用 Job ORM 实例转为 runner/handler 使用的归一化任务 dict。"""
job_type_value = str(job.job_type or '').strip()
return {
'id': job.id,
'job_type': JobType(job_type_value),
'raw_job_type': job_type_value,
# 领取时代次,供异常收口条件 UPDATE(勿信 Session 缓存)
'attempts': int(job.attempts or 0),
'payload': {
'job_id': job.id,
**(job.payload_json or {}),
},
}
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 / contract / schedule / transfer 队列;先 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 allowed_types & QUEUE_KB_JOB_TYPES['shipping']:
from app.services.shipping_notice.queue_service import recover_stale_shipping_notice_jobs
recover_stale_shipping_notice_jobs()
if JobType.PROCUREMENT_CONTRACT_REVIEW.value in allowed_types:
from app.jobs.queue import recover_stale_jobs
from flask import current_app
from app.services.procurement_contract.review_service import sync_review_after_job_recovery
recover_stale_jobs(
domain="procurement_contract",
timeout_seconds=float(current_app.config.get("PROCUREMENT_CONTRACT_JOB_TIMEOUT_SECONDS", 600)),
job_type=JobType.PROCUREMENT_CONTRACT_REVIEW,
on_recovered=sync_review_after_job_recovery,
)
contract_payment_types = (
JobType.CONTRACT_PAYMENT_SYNC,
JobType.CONTRACT_PAYMENT_ALERT,
JobType.CONTRACT_PAYMENT_ALERT_WEEKLY,
)
if {item.value for item in contract_payment_types} & allowed_types:
from app.jobs.queue import recover_stale_jobs
from flask import current_app
# [STEP 1] 合同付款与合同审核共用 procurement_contract 域,必须按 Job 类型
# 分别回收,不能错误使用不存在的 contract_payment 域或套用审核的较短超时。
for job_type in contract_payment_types:
if job_type.value not in allowed_types:
continue
recover_stale_jobs(
domain="procurement_contract",
timeout_seconds=float(current_app.config.get("CONTRACT_PAYMENT_JOB_TIMEOUT_SECONDS", 1800)),
job_type=job_type,
)
# [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_generic_job(job)
elif name == 'contract':
from app.jobs.queue import claim_next_job
job = claim_next_job(
domain="procurement_contract",
job_types=[
JobType.PROCUREMENT_CONTRACT_REVIEW,
JobType.CONTRACT_PAYMENT_SYNC,
JobType.CONTRACT_PAYMENT_ALERT,
JobType.CONTRACT_PAYMENT_ALERT_WEEKLY,
],
)
if job:
return _normalize_generic_job(job)
elif name == 'schedule':
from app.jobs.queue import claim_next_job
from app.services.schedule.queue_service import prepare_schedule_queue
prepare_schedule_queue()
job = claim_next_job(
domain="schedule",
job_types=[JobType.SCHEDULE_RUN],
)
if job:
return _normalize_generic_job(job)
# file-check / 企微通讯录同步与排程共用 schedule worker,但 domain 不同
job = claim_next_job(
domain=None,
job_types=[JobType.FILE_CHECK_RUN, JobType.WECOM_DIRECTORY_SYNC],
)
if job:
return _normalize_generic_job(job)
elif name == 'transfer':
# 在途调拨域:预检/票级执行/行级任务共用 domain="in_transit_transfer"
# (与 execution_service 入队口径一致);缺此分支时 transfer worker
# 会空轮询永远领不到任务,Run 卡在 queued。
from app.jobs.queue import claim_next_job
job = claim_next_job(
domain="in_transit_transfer",
job_types=[
JobType.TRANSFER_MATCH,
JobType.TRANSFER_RUN,
JobType.TRANSFER_ITEM,
],
)
if job:
return _normalize_generic_job(job)
return None
def mark_failed(job_id: int, *, message: str, owned_attempt: int | None = None) -> None:
"""
handler 未捕获异常时,将任务标记为 failed(KbJob 或通用 Job)。
Args:
job_id: 任务主键。
message: 失败原因(截断至 1000 字符)。
owned_attempt: 领取时的 Job.attempts;通用 Job 用条件 UPDATE,避免覆盖新代次。
"""
from datetime import datetime
from app import db
from app.jobs.queue import fail_job
# 通用 Job 表命中则条件收口(rowcount=0 即代次/状态已变,安全 no-op)
generic = db.session.query(Job.id).filter(Job.id == int(job_id)).first()
if generic is not None:
generic_job = db.session.get(Job, int(job_id))
fail_job(
int(job_id),
error=message[:1000],
# 发货通知失败即停止;Runner 的兜底异常也不得绕过业务 Gate 自动重新入队。
retryable=False if str(getattr(generic_job, 'domain', '') or '') == 'shipping_notice' else True,
owned_attempt=owned_attempt,
)
return
kb_job = db.session.get(KbJob, job_id)
if not kb_job or kb_job.status != 'running':
return
now = datetime.utcnow()
kb_job.status = 'failed'
kb_job.error_message = message[:1000]
kb_job.message = message[:500]
kb_job.finished_at = now
kb_job.progress = 100
db.session.commit()