Merge branch 'dev' into hugo-shipping-notice

# Conflicts:
#	backend/app/jobs/queue.py
This commit is contained in:
hugo committed 2026-06-29 20:39:06 +08:00
commit ce80867d09
89 files changed
+10328 -4126

No files matched your search

+244 -44
View File
@@ -1,15 +1,39 @@
"""
backend/app/jobs/queue.py
用途:任务入队 API(Wave 2:adapter 至 KbJob + 域内 enqueue 函数)。
逻辑:API / services 在创建 KbJob 后调用 enqueue;sync 模式仍由域内函数同步执行。
用途:通用后台任务入队、领取与完成状态管理。
依赖: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 app.core.errors import ValidationError
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 _find_shipping_notice_job_id(task_no: str) -> int | None:
@@ -42,59 +66,59 @@ def _find_shipping_notice_job_id(task_no: str) -> int | None:
def enqueue(
job_type: JobType,
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:
"""
将任务提交执行并返回 job id(Wave 2 要求 payload 含已持久化的 KbJob id 或发货参数)。
核心逻辑:KB/发货任务委托既有 queue_service;未创建 KbJob 的调用方须先写库再 enqueue。
将任务写入通用 jobs 队列并返回 job id。
Args:
job_type: 任务类型。
payload: 任务参数;KB 类须含 job_id,发货类须含 task_no。
correlation_id: 关联业务 id(预留,当前未写入 KbJob)。
scheduled_at: 延迟执行时间(预留)。
Returns:
KbJob 主键。
Raises:
ValidationError: 参数缺失或域 enqueue 失败。
payload: JSON payload。
domain: 业务域,如 shipping_notice。
business_ref: 业务幂等锚点,如发货任务号。
created_by_id: 创建人。
priority: 优先级,数值越大越先执行。
max_attempts: 最大尝试次数。
message: 初始状态说明。
dedupe_active: 是否复用 active 状态的同业务任务。
correlation_id: 兼容旧接口;business_ref 为空时作为业务锚点。
scheduled_at: 未来时间则延迟到该时间后才可被 worker 领取。
"""
_ = correlation_id, scheduled_at # Wave 4 通用 Job 表再使用
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 job_type in (JobType.KB_CLEAN, JobType.KB_DIFY_SYNC):
job_id = payload.get('job_id')
if not job_id:
raise ValidationError('enqueue KB job 须在 payload 中提供 job_id(先创建 KbJob)')
from app.services.knowledge_cleaning.queue_service import enqueue_kb_job
ok, msg = enqueue_kb_job(int(job_id))
if not ok:
raise ValidationError(f'KB job enqueue failed: {msg}')
return int(job_id)
if job_type == JobType.SHIPPING_NOTICE_RUN:
task_no = str(payload.get('task_no') or '').strip()
if not task_no:
raise ValidationError('enqueue shipping job 须在 payload 中提供 task_no')
from app.services.shipping_notice.queue_service import enqueue_shipping_notice_job
ok, msg = enqueue_shipping_notice_job(
task_no=task_no,
created_by_id=payload.get('created_by_id'),
batch_no=payload.get('batch_no'),
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 not ok:
raise ValidationError(f'shipping job enqueue failed: {msg}')
# sync/worker/already_queued 均需按 task_no 精确回查,避免返回其他发货任务的 id。
if payload.get('job_id'):
return int(payload['job_id'])
job_id = _find_shipping_notice_job_id(task_no)
if job_id:
return job_id
raise ValidationError(f'shipping job enqueue ambiguous: {msg}')
if existing:
return int(existing.id)
<<<<<<< HEAD
raise ValidationError(f'JobType {job_type} enqueue not implemented in Wave 2')
@@ -145,3 +169,179 @@ def enqueue_shipping_notice_job(
created_by_id=created_by_id,
batch_no=batch_no,
)
=======
now = datetime.utcnow()
queue_at = scheduled_at if isinstance(scheduled_at, datetime) else now
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=queue_at,
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",
Job.created_at <= now,
)
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
>>>>>>> hugo-shipping-notice