Files
syops/backend/app/jobs/store.py
T
hugo 1b6483a4ea feat(shipping-notice,receipt-report): 新增收料报表功能并优化发货通知流程
清理废弃的shipping xfa ocr automark相关代码和job配置
新增收料报表管理的前端页面、路由和侧边栏入口
新增后端收料报表配置接口、数据库模型和RPA脚本
优化发货通知流程的重试策略,将shipping相关job默认不自动重试
移除废弃的库存源确认相关逻辑,更新流程门禁规则
重构订单模板的值适配器模块,新增坐标OCR值适配器
清理前端shipping菜单和action的废弃选项
更新相关文档和测试用例,调整.gitignore忽略规则
2026-08-20 20:23:10 +08:00

170 lines
6.1 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 任务;返回归一化 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 队列;先 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,
)
# [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],
)
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)
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()