Files
syops/backend/app/jobs/queue.py
T
hugo 1cf8ff40bd docs(tec): 更新货代发货通知批次库存能力文档
- 添加单票与多票发货需求的处理方式
- 说明库存 Excel 上传后的保存与关联机制
- 解释库存匹配与 Excel 生成的独立执行方式
- 明确批次库存的真相来源

feat(chat): 优化发货库存上传提示语
- 根据上传结果生成更详细的提示信息
- 增加批次号的提示逻辑
- 使用国际化支持替换硬编码字符串

refactor(chat): 重构发货库存上传处理逻辑
- 移除多余的任务选择逻辑
- 简化上传处理流程
- 增强代码可读性与维护性

feat(locales): 更新多语言支持的提示信息
- 添加库存上传与任务处理的多语言提示
- 更新库存缺口与任务状态的描述
2026-06-26 16:27:49 +08:00

261 lines
8.6 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/queue.py
用途:通用后台任务入队、领取与完成状态管理。
依赖:models.Job、jobs.types、Flask app.config。
逻辑:业务服务调用 enqueue 写入 jobs;worker 调用 claim/finish/fail 完成执行闭环。
"""
from __future__ import annotations
import socket
from datetime import datetime, timedelta
from typing import Any
from flask import current_app
from sqlalchemy.exc import OperationalError
from app import db
from app.jobs.types import JobType
from app.models import Job
ACTIVE_STATUSES = ("queued", "running")
TERMINAL_STATUSES = ("success", "failed", "dead", "cancelled")
def _normalize_job_type(job_type: JobType | str) -> str:
"""把 JobType 或字符串统一成数据库保存值。"""
return str(getattr(job_type, "value", job_type) or "").strip()
def _worker_id() -> str:
"""生成当前 worker 标识,用于锁记录和排障。"""
try:
host = socket.gethostname()
except Exception:
host = "unknown-host"
return f"{host}:{id(db.session)}"
def enqueue(
job_type: JobType | str,
payload: dict[str, Any],
*,
domain: str = "default",
business_ref: str | None = None,
created_by_id: int | None = None,
priority: int = 0,
max_attempts: int = 3,
message: str | None = None,
dedupe_active: bool = True,
correlation_id: str | None = None,
scheduled_at: Any = None,
) -> int:
"""
将任务写入通用 jobs 队列并返回 job id。
Args:
job_type: 任务类型。
payload: JSON payload。
domain: 业务域,如 shipping_notice。
business_ref: 业务幂等锚点,如发货任务号。
created_by_id: 创建人。
priority: 优先级,数值越大越先执行。
max_attempts: 最大尝试次数。
message: 初始状态说明。
dedupe_active: 是否复用 active 状态的同业务任务。
correlation_id: 兼容旧接口;business_ref 为空时作为业务锚点。
scheduled_at: 预留参数,当前阶段不启用延迟调度。
"""
normalized_type = _normalize_job_type(job_type)
normalized_domain = str(domain or "").strip() or "default"
normalized_ref = str(business_ref or correlation_id or "").strip() or None
if not normalized_type:
raise ValueError("job_type is required")
if not isinstance(payload, dict):
raise ValueError("payload must be a dict")
if dedupe_active and normalized_ref:
existing = (
db.session.query(Job)
.filter(
Job.domain == normalized_domain,
Job.job_type == normalized_type,
Job.business_ref == normalized_ref,
Job.status.in_(ACTIVE_STATUSES),
)
.order_by(Job.created_at.desc(), Job.id.desc())
.first()
)
if existing:
return int(existing.id)
now = datetime.utcnow()
job = Job(
domain=normalized_domain,
job_type=normalized_type,
status="queued",
priority=int(priority or 0),
business_ref=normalized_ref,
payload_json=payload,
progress=0,
message=message or "等待后台处理",
attempts=0,
max_attempts=max(1, int(max_attempts or 1)),
created_by_id=created_by_id,
created_at=now,
updated_at=now,
)
db.session.add(job)
db.session.commit()
return int(job.id)
def recover_stale_jobs(*, domain: str, timeout_seconds: float, job_type: str | JobType | None = None) -> int:
"""回收指定业务域内超时 running 的通用任务。"""
cutoff = datetime.utcnow() - timedelta(seconds=float(timeout_seconds))
query = (
db.session.query(Job)
.filter(
Job.domain == domain,
Job.status == "running",
Job.started_at.isnot(None),
Job.started_at < cutoff,
)
)
normalized_type = _normalize_job_type(job_type) if job_type else ""
if normalized_type:
query = query.filter(Job.job_type == normalized_type)
stale_jobs = query.order_by(Job.started_at.asc(), Job.id.asc()).all()
if not stale_jobs:
return 0
now = datetime.utcnow()
for job in stale_jobs:
if int(job.attempts or 0) < int(job.max_attempts or 1):
job.status = "queued"
job.message = "任务执行超时,已回收等待重试"
job.locked_by = None
job.locked_at = None
job.started_at = None
job.updated_at = now
continue
job.status = "failed"
job.error_message = f"任务执行超时(超过 {int(timeout_seconds)}s)"
job.message = job.error_message
job.progress = 100
job.locked_by = None
job.locked_at = None
job.finished_at = now
job.updated_at = now
db.session.commit()
return len(stale_jobs)
def claim_next_job(*, domain: str, job_types: list[str | JobType] | None = None, worker_id: str | None = None) -> Job | None:
"""原子领取指定业务域下一条 queued 任务。"""
normalized_types = [_normalize_job_type(item) for item in (job_types or []) if _normalize_job_type(item)]
now = datetime.utcnow()
try:
query = db.session.query(Job).filter(Job.domain == domain, Job.status == "queued")
if normalized_types:
query = query.filter(Job.job_type.in_(normalized_types))
job = (
query.order_by(Job.priority.desc(), Job.created_at.asc(), Job.id.asc())
.with_for_update(skip_locked=True)
.first()
)
except OperationalError:
db.session.rollback()
raise
if not job:
db.session.rollback()
return None
job.status = "running"
job.started_at = job.started_at or now
job.locked_at = now
job.locked_by = worker_id or _worker_id()
job.attempts = int(job.attempts or 0) + 1
job.progress = max(int(job.progress or 0), 1)
job.message = "worker 已领取任务"
job.updated_at = now
db.session.commit()
return job
def finish_job(job: Job, *, result: dict[str, Any] | None = None, message: str | None = None) -> None:
"""标记任务成功完成。"""
now = datetime.utcnow()
job.status = "success"
job.progress = 100
job.result_json = result or {}
job.message = message or "任务处理完成"
job.error_message = None
job.locked_by = None
job.locked_at = None
job.finished_at = now
job.updated_at = now
db.session.commit()
def fail_job(job: Job, *, error: str, result: dict[str, Any] | None = None, retryable: bool = False) -> None:
"""标记任务失败;retryable 且未达上限时重新排队。"""
now = datetime.utcnow()
can_retry = retryable and int(job.attempts or 0) < int(job.max_attempts or 1)
job.status = "queued" if can_retry else "failed"
job.progress = 0 if can_retry else 100
job.result_json = result or {}
job.error_message = str(error or "job failed")[:1000]
job.message = "任务失败,等待重试" if can_retry else job.error_message
job.locked_by = None
job.locked_at = None
job.finished_at = None if can_retry else now
job.updated_at = now
db.session.commit()
def process_next_job(
*,
ctx: Any,
domain: str,
job_types: list[str | JobType] | None = None,
timeout_config_key: str | None = None,
default_timeout_seconds: float = 300,
) -> tuple[bool, str]:
"""领取并分发一条通用任务。"""
import app.jobs.handlers # noqa: F401
from app.jobs.registry import get_handler
timeout_seconds = float(
current_app.config.get(timeout_config_key, default_timeout_seconds)
if timeout_config_key
else default_timeout_seconds
)
recover_stale_jobs(domain=domain, timeout_seconds=timeout_seconds)
job = claim_next_job(domain=domain, job_types=job_types)
if not job:
return False, "no_job"
job_id = int(job.id)
job_type_value = str(job.job_type or "").strip()
payload = dict(job.payload_json or {})
payload.setdefault("job_id", job_id)
handler = get_handler(JobType(job_type_value))
if handler is None:
fail_job(job, error=f"no handler registered for {job.job_type}")
return True, "missing_handler"
try:
handler(ctx, payload)
refreshed = db.session.get(Job, job_id)
if refreshed and refreshed.status == "running":
finish_job(refreshed, message="任务处理完成")
return True, job_type_value
except Exception as exc:
db.session.rollback()
refreshed = db.session.get(Job, job_id)
if refreshed:
fail_job(refreshed, error=str(exc), retryable=True)
raise