feat(shipping-notice): 新增发货通知重复检测与处理接口,支持重复决策保存与重新执行检测
This commit is contained in:
1 parent
729546a7b7
commit
ceb49461e8
72 files changed
+14270
-460
No files matched your search
+757
-73
@@ -2,17 +2,25 @@
|
||||
backend/app/jobs/queue.py
|
||||
|
||||
用途:通用后台任务入队、领取与完成状态管理,并保留旧 KB 入队兼容入口。
|
||||
依赖:models.Job、jobs.types、Flask app.config、knowledge_cleaning 队列适配层。
|
||||
逻辑:业务服务调用 enqueue 写入 jobs;旧 KB 清洗入口委托 legacy KbJob 队列;worker 调用 claim/finish/fail 完成执行闭环。
|
||||
依赖:models.Job、jobs.types、Flask app.config、knowledge_cleaning 队列适配层;
|
||||
shipping_notice Intake 仅在预解析 Job 被 queued 同伴取代时同事务重指 parse_job_id。
|
||||
逻辑:业务服务调用 enqueue 写入 jobs;旧 KB 清洗入口委托 legacy KbJob 队列;worker 调用 claim/finish/fail 完成执行闭环;
|
||||
recover 使用 FOR UPDATE SKIP LOCKED + 条件 UPDATE;finish/fail 以 status/attempts 条件 UPDATE;
|
||||
enqueue 仅在 SAVEPOINT 内 add+flush,唯一冲突回落已有 Job;
|
||||
running→queued 若撞 shipping_notice_parse queued 唯一索引则标 cancelled;
|
||||
替代 Job 须 FOR UPDATE;仅 queued 或已真正持有 Intake lease 的 running 可 supersede。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import socket
|
||||
from datetime import datetime, timedelta
|
||||
from collections.abc import Callable, Sequence
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
from sqlalchemy.exc import OperationalError
|
||||
from sqlalchemy import update
|
||||
from sqlalchemy.exc import IntegrityError, OperationalError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ValidationError
|
||||
@@ -20,7 +28,43 @@ from app.jobs.types import JobType
|
||||
from app.models import Job
|
||||
|
||||
ACTIVE_STATUSES = ("queued", "running")
|
||||
QUEUED_ONLY_STATUSES = ("queued",)
|
||||
TERMINAL_STATUSES = ("success", "failed", "dead", "cancelled")
|
||||
# 与 models.Job.uq_jobs_shipping_parse_queued_ref 对齐
|
||||
_PARSE_QUEUED_UNIQUE_TYPE = JobType.SHIPPING_NOTICE_PARSE.value
|
||||
|
||||
|
||||
def _orm_session() -> Session:
|
||||
"""
|
||||
取得底层 Session。
|
||||
|
||||
scoped_session 代理不转发 in_transaction/get_transaction,须解包后使用。
|
||||
"""
|
||||
return db.session()
|
||||
|
||||
|
||||
def _ensure_outer_dbapi_transaction(session: Session) -> None:
|
||||
"""
|
||||
确保 begin_nested() 不会成为数据库最外层事务。
|
||||
|
||||
核心逻辑:SQLite 在尚未 BEGIN 时执行 SAVEPOINT,随后 RELEASE 等价于 COMMIT,
|
||||
会破坏 commit=False / 外层 rollback。先 materialize 连接事务;SQLite 必要时
|
||||
显式 DBAPI BEGIN(已在事务中则忽略)。
|
||||
"""
|
||||
if not session.in_transaction():
|
||||
session.begin()
|
||||
bind = session.connection()
|
||||
if str(bind.dialect.name or "") != "sqlite":
|
||||
return
|
||||
dbapi_conn = bind.connection.dbapi_connection
|
||||
in_txn = getattr(dbapi_conn, "in_transaction", None)
|
||||
if callable(in_txn) and in_txn():
|
||||
return
|
||||
try:
|
||||
dbapi_conn.execute("BEGIN")
|
||||
except Exception:
|
||||
# 已在事务中:sqlite 会报错,可安全忽略
|
||||
pass
|
||||
|
||||
|
||||
def _normalize_job_type(job_type: JobType | str) -> str:
|
||||
@@ -28,6 +72,242 @@ def _normalize_job_type(job_type: JobType | str) -> str:
|
||||
return str(getattr(job_type, "value", job_type) or "").strip()
|
||||
|
||||
|
||||
def _subject_to_parse_queued_unique(job_type: str | None) -> bool:
|
||||
"""是否受 shipping_notice_parse queued 部分唯一索引约束。"""
|
||||
return str(job_type or "").strip() == _PARSE_QUEUED_UNIQUE_TYPE
|
||||
|
||||
|
||||
def _lock_other_active_parse_job(
|
||||
*,
|
||||
domain: str,
|
||||
job_type: str,
|
||||
business_ref: str | None,
|
||||
exclude_id: int,
|
||||
) -> Job | None:
|
||||
"""
|
||||
FOR UPDATE 锁定同业务锚点下优先级最高的 queued/running 预解析 Job。
|
||||
|
||||
核心逻辑:queued 受部分唯一索引保护且天然可安全替代,因此必须优先于
|
||||
running;仅无 queued 时才按最小 id 选择 running,并交由
|
||||
`_is_safe_supersede_target` 校验精确 Intake lease。持锁期间 Worker 的
|
||||
claim(SKIP LOCKED)会跳过最终候选。
|
||||
|
||||
Args:
|
||||
domain / job_type / business_ref: 与待降级 Job 相同的锚点。
|
||||
exclude_id: 排除自身主键。
|
||||
|
||||
Returns:
|
||||
锁定的最高优先级同伴;没有则 None。
|
||||
"""
|
||||
ref = str(business_ref or "").strip() or None
|
||||
if not ref:
|
||||
return None
|
||||
return (
|
||||
db.session.query(Job)
|
||||
.filter(
|
||||
Job.domain == str(domain),
|
||||
Job.job_type == str(job_type),
|
||||
Job.business_ref == ref,
|
||||
Job.status.in_(("queued", "running")),
|
||||
Job.id != int(exclude_id),
|
||||
)
|
||||
.order_by((Job.status == "queued").desc(), Job.id.asc())
|
||||
.execution_options(populate_existing=True)
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
def _parse_lease_for_job(job: Job) -> str:
|
||||
"""构造 `{job_id}:{attempts}` 执行代次 lease。"""
|
||||
return f"{int(job.id)}:{int(job.attempts or 0)}"
|
||||
|
||||
|
||||
def _is_safe_supersede_target(sibling: Job, *, cancelled_job: Job) -> bool:
|
||||
"""
|
||||
判定锁定的同伴是否可安全取代旧 running Job。
|
||||
|
||||
核心逻辑:
|
||||
- queued:可 supersede(旧取消,Intake 回到排队挂 keep);
|
||||
- running:仅当 Intake 已明确持有该 Job 的精确 parse_job_id + parse_lease
|
||||
(Worker 已真正 claim Intake)。否则可能 Worker 已按旧 id 决定 skip+finish,
|
||||
若此时伪造 lease 会导致 Intake 永久 parsing。
|
||||
|
||||
Returns:
|
||||
True 表示可取消旧 Job 并重指;False 表示应让旧 Job 正常 requeue。
|
||||
"""
|
||||
db.session.refresh(sibling)
|
||||
status = str(sibling.status or "")
|
||||
if status == "queued":
|
||||
return True
|
||||
if status != "running":
|
||||
return False
|
||||
|
||||
from app.models import ShippingNoticeIntake
|
||||
|
||||
intake_no = str(
|
||||
(cancelled_job.payload_json or {}).get("intake_no")
|
||||
or cancelled_job.business_ref
|
||||
or sibling.business_ref
|
||||
or ""
|
||||
).strip().upper()
|
||||
if not intake_no:
|
||||
return False
|
||||
locked = (
|
||||
db.session.query(ShippingNoticeIntake)
|
||||
.filter(ShippingNoticeIntake.intake_no == intake_no)
|
||||
.execution_options(populate_existing=True)
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
if locked is None:
|
||||
return False
|
||||
expected_lease = _parse_lease_for_job(sibling)
|
||||
return (
|
||||
str(locked.parse_status or "") == "parsing"
|
||||
and locked.parse_job_id is not None
|
||||
and int(locked.parse_job_id) == int(sibling.id)
|
||||
and str(locked.parse_lease or "") == expected_lease
|
||||
)
|
||||
|
||||
|
||||
def _resolve_safe_supersede_sibling(
|
||||
*,
|
||||
domain: str,
|
||||
job_type: str,
|
||||
business_ref: str | None,
|
||||
exclude_id: int,
|
||||
cancelled_job: Job,
|
||||
) -> Job | None:
|
||||
"""
|
||||
锁定同伴并过滤为可安全 supersede 的目标;不安全则视为无替代者。
|
||||
"""
|
||||
sibling = _lock_other_active_parse_job(
|
||||
domain=domain,
|
||||
job_type=job_type,
|
||||
business_ref=business_ref,
|
||||
exclude_id=exclude_id,
|
||||
)
|
||||
if sibling is None:
|
||||
return None
|
||||
if not _is_safe_supersede_target(sibling, cancelled_job=cancelled_job):
|
||||
return None
|
||||
return sibling
|
||||
|
||||
|
||||
def _retarget_intake_parse_job_after_supersede(
|
||||
*,
|
||||
cancelled_job: Job,
|
||||
keep_job: Job,
|
||||
) -> None:
|
||||
"""
|
||||
旧 running 预解析 Job 被安全同伴取代时,同事务重指 Intake.parse_job_id。
|
||||
|
||||
核心逻辑:FOR UPDATE Intake 后复检 keep_job.status——
|
||||
keep 仍为 queued:parsing→queued 并清 parse_lease;
|
||||
keep 已 running:仅在 Intake 已持有其精确 lease 时保留状态,绝不伪造 lease
|
||||
(否则会踩到已决定 skip+finish 的 Worker,造成永久 parsing)。
|
||||
"""
|
||||
if not _subject_to_parse_queued_unique(str(cancelled_job.job_type or "")):
|
||||
return
|
||||
from app.models import ShippingNoticeIntake
|
||||
|
||||
intake_no = str(
|
||||
(cancelled_job.payload_json or {}).get("intake_no")
|
||||
or cancelled_job.business_ref
|
||||
or ""
|
||||
).strip().upper()
|
||||
if not intake_no:
|
||||
return
|
||||
|
||||
# 锁内复检同伴状态(调用方应已 FOR UPDATE keep_job)
|
||||
db.session.refresh(keep_job)
|
||||
keep_status = str(keep_job.status or "")
|
||||
if keep_status not in {"queued", "running"}:
|
||||
return
|
||||
|
||||
locked = (
|
||||
db.session.query(ShippingNoticeIntake)
|
||||
.filter(ShippingNoticeIntake.intake_no == intake_no)
|
||||
.execution_options(populate_existing=True)
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
if locked is None:
|
||||
return
|
||||
current_job_id = int(locked.parse_job_id) if locked.parse_job_id is not None else None
|
||||
cancelled_id = int(cancelled_job.id)
|
||||
keep_id = int(keep_job.id)
|
||||
# 已指向第三方 Job:不抢占
|
||||
if current_job_id is not None and current_job_id not in {cancelled_id, keep_id}:
|
||||
return
|
||||
now = datetime.utcnow()
|
||||
current_lease = str(locked.parse_lease or "") or None
|
||||
status_now = str(locked.parse_status or "")
|
||||
|
||||
if keep_status == "queued":
|
||||
if current_job_id in {cancelled_id, None}:
|
||||
locked.parse_job_id = keep_id
|
||||
# 仅当仍挂旧 Job/旧代次时才打回 queued,避免清掉 keep 新 Worker 的 lease
|
||||
if status_now == "parsing" and (
|
||||
current_job_id == cancelled_id
|
||||
or current_lease is None
|
||||
or str(current_lease).startswith(f"{cancelled_id}:")
|
||||
):
|
||||
locked.parse_status = "queued"
|
||||
locked.parse_lease = None
|
||||
locked.updated_at = now
|
||||
return
|
||||
|
||||
# keep 已 running:只保留已真正接管的状态,禁止伪造 lease 转移
|
||||
keep_lease = _parse_lease_for_job(keep_job)
|
||||
if (
|
||||
status_now == "parsing"
|
||||
and current_job_id == keep_id
|
||||
and current_lease == keep_lease
|
||||
):
|
||||
locked.updated_at = now
|
||||
return
|
||||
# 未真正接管:调用方本不应 supersede;此处 no-op 防误伤
|
||||
return
|
||||
|
||||
|
||||
def _cancel_running_job_superseded(
|
||||
*,
|
||||
job_id: int,
|
||||
now: datetime,
|
||||
message: str,
|
||||
owned_attempt: int | None = None,
|
||||
snap_attempts: int | None = None,
|
||||
) -> int:
|
||||
"""
|
||||
将仍为 running 的 Job 标为 cancelled(已被新 queued 取代)。
|
||||
|
||||
Returns:
|
||||
条件 UPDATE 影响行数。
|
||||
"""
|
||||
where = [Job.id == int(job_id), Job.status == "running"]
|
||||
if owned_attempt is not None:
|
||||
where.append(Job.attempts == int(owned_attempt))
|
||||
elif snap_attempts is not None:
|
||||
where.append(Job.attempts == int(snap_attempts))
|
||||
stmt = (
|
||||
update(Job)
|
||||
.where(*where)
|
||||
.values(
|
||||
status="cancelled",
|
||||
progress=100,
|
||||
message=str(message or "已被新的 queued Job 取代")[:500],
|
||||
locked_by=None,
|
||||
locked_at=None,
|
||||
started_at=None,
|
||||
finished_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
)
|
||||
return int(db.session.execute(stmt).rowcount or 0)
|
||||
|
||||
|
||||
def _worker_id() -> str:
|
||||
"""生成当前 worker 标识,用于锁记录和排障。"""
|
||||
try:
|
||||
@@ -103,12 +383,19 @@ def enqueue(
|
||||
max_attempts: int = 3,
|
||||
message: str | None = None,
|
||||
dedupe_active: bool = True,
|
||||
dedupe_statuses: Sequence[str] | None = None,
|
||||
commit: bool = True,
|
||||
correlation_id: str | None = None,
|
||||
scheduled_at: Any = None,
|
||||
) -> int:
|
||||
"""
|
||||
将任务写入通用 jobs 队列并返回 job id。
|
||||
|
||||
核心逻辑:先按 domain/type/business_ref + dedupe_statuses 查复用;
|
||||
无则 SAVEPOINT 插入。撞上 shipping_notice_parse 的 queued 部分唯一索引时
|
||||
IntegrityError 回读已有 Job(并发双插幂等)。commit=False 时不开自动提交,
|
||||
由调用方与业务行同事务提交。
|
||||
|
||||
Args:
|
||||
job_type: 任务类型。
|
||||
payload: JSON payload。
|
||||
@@ -118,7 +405,10 @@ def enqueue(
|
||||
priority: 优先级,数值越大越先执行。
|
||||
max_attempts: 最大尝试次数。
|
||||
message: 初始状态说明。
|
||||
dedupe_active: 是否复用 active 状态的同业务任务。
|
||||
dedupe_active: 是否复用同业务键下指定状态中的任务。
|
||||
dedupe_statuses: 去重匹配的 Job.status 集合;默认 queued+running。
|
||||
重试场景应传仅 queued,避免复用即将结束的 running Job。
|
||||
commit: False 时仅 flush,由调用方与业务行同一事务提交。
|
||||
correlation_id: 兼容旧接口;business_ref 为空时作为业务锚点。
|
||||
scheduled_at: 未来时间则延迟到该时间后才可被 worker 领取。
|
||||
"""
|
||||
@@ -139,20 +429,26 @@ def enqueue(
|
||||
if not isinstance(payload, dict):
|
||||
raise ValueError("payload must be a dict")
|
||||
|
||||
if dedupe_active and normalized_ref:
|
||||
existing = (
|
||||
statuses = tuple(dedupe_statuses) if dedupe_statuses is not None else ACTIVE_STATUSES
|
||||
|
||||
def _find_active_dedupe_job() -> Job | None:
|
||||
if not (dedupe_active and normalized_ref and statuses):
|
||||
return None
|
||||
return (
|
||||
db.session.query(Job)
|
||||
.filter(
|
||||
Job.domain == normalized_domain,
|
||||
Job.job_type == normalized_type,
|
||||
Job.business_ref == normalized_ref,
|
||||
Job.status.in_(ACTIVE_STATUSES),
|
||||
Job.status.in_(statuses),
|
||||
)
|
||||
.order_by(Job.created_at.desc(), Job.id.desc())
|
||||
.first()
|
||||
)
|
||||
if existing:
|
||||
return int(existing.id)
|
||||
|
||||
existing = _find_active_dedupe_job()
|
||||
if existing is not None:
|
||||
return int(existing.id)
|
||||
|
||||
now = datetime.utcnow()
|
||||
queue_at = scheduled_at if isinstance(scheduled_at, datetime) else now
|
||||
@@ -171,50 +467,207 @@ def enqueue(
|
||||
created_at=queue_at,
|
||||
updated_at=now,
|
||||
)
|
||||
db.session.add(job)
|
||||
db.session.commit()
|
||||
# [STEP] SAVEPOINT 边界:仅在 begin_nested 内 add+flush。
|
||||
# begin_nested 会先 autoflush pending;若 Job 提前进入 Session,冲突会落在 SAVEPOINT 之外,
|
||||
# 毒化外层事务并在异常分支触发 PendingRollbackError。
|
||||
session = _orm_session()
|
||||
_ensure_outer_dbapi_transaction(session)
|
||||
try:
|
||||
with session.begin_nested():
|
||||
session.add(job)
|
||||
session.flush()
|
||||
except IntegrityError:
|
||||
# SAVEPOINT 已回滚;确保失败对象不残留为 pending
|
||||
try:
|
||||
session.expunge(job)
|
||||
except Exception:
|
||||
pass
|
||||
# 即使 dedupe_active=False,唯一冲突仍须回落已有 queued(索引层幂等)
|
||||
raced = _find_active_dedupe_job()
|
||||
if raced is None and normalized_ref:
|
||||
raced = (
|
||||
db.session.query(Job)
|
||||
.filter(
|
||||
Job.domain == normalized_domain,
|
||||
Job.job_type == normalized_type,
|
||||
Job.business_ref == normalized_ref,
|
||||
Job.status == "queued",
|
||||
)
|
||||
.order_by(Job.id.asc())
|
||||
.first()
|
||||
)
|
||||
if raced is not None:
|
||||
return int(raced.id)
|
||||
raise
|
||||
if commit:
|
||||
session.commit()
|
||||
return int(job.id)
|
||||
|
||||
|
||||
def recover_stale_jobs(*, domain: str, timeout_seconds: float, job_type: str | JobType | None = None) -> int:
|
||||
"""回收指定业务域内超时 running 的通用任务。"""
|
||||
def _job_id(job: Job | int) -> int:
|
||||
"""统一解析 Job 主键。"""
|
||||
return int(job if isinstance(job, int) else job.id)
|
||||
|
||||
|
||||
def recover_stale_jobs(
|
||||
*,
|
||||
domain: str,
|
||||
timeout_seconds: float,
|
||||
job_type: str | JobType | None = None,
|
||||
on_recovered: Callable[[Job], None] | None = None,
|
||||
) -> int:
|
||||
"""
|
||||
回收指定业务域内超时 running 的通用任务。
|
||||
|
||||
核心逻辑:FOR UPDATE SKIP LOCKED 领取待回收行,再以
|
||||
status=running AND attempts=快照 条件 UPDATE;同事务回调 on_recovered。
|
||||
多 Worker 并发回收时不会双写同一 Job,也不会把已被新 Worker 领取的代次打回 queued。
|
||||
若已存在同锚点 queued 同伴(parse 唯一索引),旧 Job 标 cancelled 并重指 Intake,
|
||||
每条更新包在 SAVEPOINT 内,避免单行 IntegrityError 毒化整批回收。
|
||||
|
||||
Args:
|
||||
on_recovered: 每条 Job 条件更新成功后、统一 commit 前的回调。
|
||||
"""
|
||||
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,
|
||||
)
|
||||
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()
|
||||
|
||||
try:
|
||||
stale_jobs = (
|
||||
query.order_by(Job.started_at.asc(), Job.id.asc())
|
||||
.with_for_update(skip_locked=True)
|
||||
.all()
|
||||
)
|
||||
except OperationalError:
|
||||
db.session.rollback()
|
||||
raise
|
||||
|
||||
if not stale_jobs:
|
||||
db.session.rollback()
|
||||
return 0
|
||||
|
||||
session = _orm_session()
|
||||
_ensure_outer_dbapi_transaction(session)
|
||||
now = datetime.utcnow()
|
||||
recovered = 0
|
||||
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
|
||||
# 锁内复检:可能已被他事务终态化(本连接持锁期间一般仍为 running)
|
||||
if str(job.status or "") != "running":
|
||||
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
|
||||
if job.started_at is None or job.started_at >= cutoff:
|
||||
continue
|
||||
snap_attempts = int(job.attempts or 0)
|
||||
max_attempts = int(job.max_attempts or 1)
|
||||
job_id = int(job.id)
|
||||
sibling: Job | None = None
|
||||
rowcount = 0
|
||||
|
||||
if snap_attempts < max_attempts:
|
||||
if _subject_to_parse_queued_unique(str(job.job_type or "")):
|
||||
try:
|
||||
sibling = _resolve_safe_supersede_sibling(
|
||||
domain=str(job.domain),
|
||||
job_type=str(job.job_type),
|
||||
business_ref=job.business_ref,
|
||||
exclude_id=job_id,
|
||||
cancelled_job=job,
|
||||
)
|
||||
except OperationalError:
|
||||
# 死锁会使整个事务失败;回滚后由下一轮回收重试
|
||||
db.session.rollback()
|
||||
return 0
|
||||
# [STEP] SAVEPOINT:queued 唯一冲突不得毁掉整批外层事务
|
||||
try:
|
||||
with session.begin_nested():
|
||||
if sibling is not None:
|
||||
rowcount = _cancel_running_job_superseded(
|
||||
job_id=job_id,
|
||||
now=now,
|
||||
message="超时回收:已存在安全替代解析 Job,旧 Job 已取消",
|
||||
snap_attempts=snap_attempts,
|
||||
)
|
||||
else:
|
||||
result = db.session.execute(
|
||||
update(Job)
|
||||
.where(
|
||||
Job.id == job_id,
|
||||
Job.status == "running",
|
||||
Job.attempts == snap_attempts,
|
||||
)
|
||||
.values(
|
||||
status="queued",
|
||||
message="任务执行超时,已回收等待重试",
|
||||
locked_by=None,
|
||||
locked_at=None,
|
||||
started_at=None,
|
||||
updated_at=now,
|
||||
)
|
||||
)
|
||||
rowcount = int(result.rowcount or 0)
|
||||
except IntegrityError:
|
||||
try:
|
||||
sibling = _resolve_safe_supersede_sibling(
|
||||
domain=str(job.domain),
|
||||
job_type=str(job.job_type),
|
||||
business_ref=job.business_ref,
|
||||
exclude_id=job_id,
|
||||
cancelled_job=job,
|
||||
)
|
||||
except OperationalError:
|
||||
db.session.rollback()
|
||||
return 0
|
||||
if sibling is None:
|
||||
continue
|
||||
with session.begin_nested():
|
||||
rowcount = _cancel_running_job_superseded(
|
||||
job_id=job_id,
|
||||
now=now,
|
||||
message="超时回收:queued 唯一冲突,旧 Job 已取消",
|
||||
snap_attempts=snap_attempts,
|
||||
)
|
||||
else:
|
||||
timeout_msg = f"任务执行超时(超过 {int(timeout_seconds)}s)"
|
||||
result = db.session.execute(
|
||||
update(Job)
|
||||
.where(
|
||||
Job.id == job_id,
|
||||
Job.status == "running",
|
||||
Job.attempts == snap_attempts,
|
||||
)
|
||||
.values(
|
||||
status="failed",
|
||||
error_message=timeout_msg,
|
||||
message=timeout_msg,
|
||||
progress=100,
|
||||
locked_by=None,
|
||||
locked_at=None,
|
||||
finished_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
)
|
||||
rowcount = int(result.rowcount or 0)
|
||||
|
||||
if rowcount != 1:
|
||||
continue
|
||||
db.session.expire(job)
|
||||
db.session.refresh(job)
|
||||
if str(job.status or "") == "cancelled" and sibling is not None:
|
||||
_retarget_intake_parse_job_after_supersede(
|
||||
cancelled_job=job,
|
||||
keep_job=sibling,
|
||||
)
|
||||
if on_recovered is not None:
|
||||
on_recovered(job)
|
||||
recovered += 1
|
||||
db.session.commit()
|
||||
return len(stale_jobs)
|
||||
return recovered
|
||||
|
||||
|
||||
def claim_next_job(*, domain: str, job_types: list[str | JobType] | None = None, worker_id: str | None = None) -> Job | None:
|
||||
@@ -243,7 +696,8 @@ def claim_next_job(*, domain: str, job_types: list[str | JobType] | None = None,
|
||||
return None
|
||||
|
||||
job.status = "running"
|
||||
job.started_at = job.started_at or now
|
||||
# 每次领取刷新 started_at,避免 fail_job requeue 残留旧时间导致立刻被超时回收
|
||||
job.started_at = now
|
||||
job.locked_at = now
|
||||
job.locked_by = worker_id or _worker_id()
|
||||
job.attempts = int(job.attempts or 0) + 1
|
||||
@@ -254,35 +708,235 @@ def claim_next_job(*, domain: str, job_types: list[str | JobType] | None = None,
|
||||
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 _sync_parse_intake_after_job_mutation(job_id: int) -> None:
|
||||
"""
|
||||
shipping_notice_parse Job 状态变更后同步 Intake(同事务、commit 前)。
|
||||
|
||||
核心逻辑:委托 sync_intake_after_parse_job_recovery,覆盖 requeue→queued、
|
||||
failed→parse_failed、cancelled→安全重指/终态清理,避免 Intake 永久 parsing。
|
||||
"""
|
||||
job = db.session.get(Job, int(job_id))
|
||||
if job is None or not _subject_to_parse_queued_unique(str(job.job_type or "")):
|
||||
return
|
||||
db.session.expire(job)
|
||||
db.session.refresh(job)
|
||||
from app.services.shipping_notice.intake_parse_workflow import (
|
||||
sync_intake_after_parse_job_recovery,
|
||||
)
|
||||
|
||||
sync_intake_after_parse_job_recovery(job)
|
||||
|
||||
|
||||
def fail_job(job: Job, *, error: str, result: dict[str, Any] | None = None, retryable: bool = False) -> None:
|
||||
"""标记任务失败;retryable 且未达上限时重新排队。"""
|
||||
def finish_job(
|
||||
job: Job | int,
|
||||
*,
|
||||
result: dict[str, Any] | None = None,
|
||||
message: str | None = None,
|
||||
owned_attempt: int | None = None,
|
||||
) -> bool:
|
||||
"""
|
||||
条件收口为 success:仅当 Job 仍为 running(且可选 attempts 匹配)时生效。
|
||||
|
||||
Returns:
|
||||
是否实际更新到一行(False 表示代次失效或已非 running,调用方应视为 no-op)。
|
||||
"""
|
||||
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
|
||||
job_id = _job_id(job)
|
||||
where = [Job.id == job_id, Job.status == "running"]
|
||||
if owned_attempt is not None:
|
||||
where.append(Job.attempts == int(owned_attempt))
|
||||
stmt = (
|
||||
update(Job)
|
||||
.where(*where)
|
||||
.values(
|
||||
status="success",
|
||||
progress=100,
|
||||
result_json=result or {},
|
||||
message=message or "任务处理完成",
|
||||
error_message=None,
|
||||
locked_by=None,
|
||||
locked_at=None,
|
||||
finished_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
)
|
||||
rowcount = int(db.session.execute(stmt).rowcount or 0)
|
||||
db.session.commit()
|
||||
cached = db.session.get(Job, job_id)
|
||||
if cached is not None:
|
||||
db.session.expire(cached)
|
||||
return rowcount == 1
|
||||
|
||||
|
||||
def fail_job(
|
||||
job: Job | int,
|
||||
*,
|
||||
error: str,
|
||||
result: dict[str, Any] | None = None,
|
||||
retryable: bool = False,
|
||||
owned_attempt: int | None = None,
|
||||
) -> bool:
|
||||
"""
|
||||
条件收口失败:仅 running(且可选 attempts 匹配)时改 queued/failed/cancelled。
|
||||
|
||||
核心逻辑:retryable 且 attempts 未耗尽时,优先安全 supersede,否则 requeue
|
||||
(清空 started_at)并同步 Intake;唯一冲突窗口消失时保持 running 返回 False,
|
||||
禁止误标 failed。attempts 耗尽则 failed 并同步 Intake 离开 parsing。
|
||||
|
||||
Returns:
|
||||
是否实际更新到一行。
|
||||
"""
|
||||
now = datetime.utcnow()
|
||||
job_id = _job_id(job)
|
||||
error_text = str(error or "job failed")[:1000]
|
||||
payload = result or {}
|
||||
base_where = [Job.id == job_id, Job.status == "running"]
|
||||
if owned_attempt is not None:
|
||||
base_where.append(Job.attempts == int(owned_attempt))
|
||||
|
||||
session = _orm_session()
|
||||
_ensure_outer_dbapi_transaction(session)
|
||||
|
||||
def _expire_cached() -> None:
|
||||
cached = db.session.get(Job, job_id)
|
||||
if cached is not None:
|
||||
db.session.expire(cached)
|
||||
|
||||
if retryable:
|
||||
# 先锁住自身 running 行,再锁同伴,缩短无锁窗口且便于复检 attempts
|
||||
job_row = (
|
||||
db.session.query(Job)
|
||||
.filter(Job.id == job_id, Job.status == "running")
|
||||
.execution_options(populate_existing=True)
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
sibling: Job | None = None
|
||||
if job_row is not None and _subject_to_parse_queued_unique(str(job_row.job_type or "")):
|
||||
try:
|
||||
sibling = _resolve_safe_supersede_sibling(
|
||||
domain=str(job_row.domain),
|
||||
job_type=str(job_row.job_type),
|
||||
business_ref=job_row.business_ref,
|
||||
exclude_id=job_id,
|
||||
cancelled_job=job_row,
|
||||
)
|
||||
except OperationalError:
|
||||
db.session.rollback()
|
||||
return False
|
||||
|
||||
attempts_ok = (
|
||||
job_row is not None
|
||||
and int(job_row.attempts or 0) < int(job_row.max_attempts or 1)
|
||||
)
|
||||
if sibling is not None and attempts_ok:
|
||||
# 仅安全替代者:取消旧 Job(running 且已真正接管 Intake,或仍为 queued)
|
||||
rowcount = _cancel_running_job_superseded(
|
||||
job_id=job_id,
|
||||
now=now,
|
||||
message="失败重试:已存在安全替代解析 Job,旧 Job 已取消",
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
if rowcount == 1:
|
||||
cancelled = db.session.get(Job, job_id)
|
||||
if cancelled is not None:
|
||||
_retarget_intake_parse_job_after_supersede(
|
||||
cancelled_job=cancelled,
|
||||
keep_job=sibling,
|
||||
)
|
||||
_sync_parse_intake_after_job_mutation(job_id)
|
||||
db.session.commit()
|
||||
_expire_cached()
|
||||
return True
|
||||
elif sibling is None and attempts_ok:
|
||||
# 无安全替代(含:同伴 running 但尚未 claim Intake)→ 正常 requeue
|
||||
requeue_stmt = (
|
||||
update(Job)
|
||||
.where(*base_where, Job.attempts < Job.max_attempts)
|
||||
.values(
|
||||
status="queued",
|
||||
progress=0,
|
||||
result_json=payload,
|
||||
error_message=error_text,
|
||||
message="任务失败,等待重试",
|
||||
locked_by=None,
|
||||
locked_at=None,
|
||||
started_at=None,
|
||||
finished_at=None,
|
||||
updated_at=now,
|
||||
)
|
||||
)
|
||||
try:
|
||||
with session.begin_nested():
|
||||
rowcount = int(db.session.execute(requeue_stmt).rowcount or 0)
|
||||
except IntegrityError:
|
||||
try:
|
||||
sibling = (
|
||||
_resolve_safe_supersede_sibling(
|
||||
domain=str(job_row.domain),
|
||||
job_type=str(job_row.job_type),
|
||||
business_ref=job_row.business_ref,
|
||||
exclude_id=job_id,
|
||||
cancelled_job=job_row,
|
||||
)
|
||||
if job_row is not None
|
||||
else None
|
||||
)
|
||||
except OperationalError:
|
||||
db.session.rollback()
|
||||
return False
|
||||
if sibling is None:
|
||||
# 唯一冲突窗口已消失:保持 running,勿强行 failed 造成永久 parsing
|
||||
db.session.rollback()
|
||||
return False
|
||||
with session.begin_nested():
|
||||
rowcount = _cancel_running_job_superseded(
|
||||
job_id=job_id,
|
||||
now=now,
|
||||
message="失败重试:queued 唯一冲突,旧 Job 已取消",
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
if rowcount == 1:
|
||||
cancelled = db.session.get(Job, job_id)
|
||||
if cancelled is not None:
|
||||
_retarget_intake_parse_job_after_supersede(
|
||||
cancelled_job=cancelled,
|
||||
keep_job=sibling,
|
||||
)
|
||||
_sync_parse_intake_after_job_mutation(job_id)
|
||||
db.session.commit()
|
||||
_expire_cached()
|
||||
return True
|
||||
else:
|
||||
if rowcount == 1:
|
||||
_sync_parse_intake_after_job_mutation(job_id)
|
||||
db.session.commit()
|
||||
_expire_cached()
|
||||
return True
|
||||
|
||||
# 终态 failed:同步 Intake 离开 parsing,避免永久卡住
|
||||
fail_stmt = (
|
||||
update(Job)
|
||||
.where(*base_where)
|
||||
.values(
|
||||
status="failed",
|
||||
progress=100,
|
||||
result_json=payload,
|
||||
error_message=error_text,
|
||||
message=error_text,
|
||||
locked_by=None,
|
||||
locked_at=None,
|
||||
started_at=None,
|
||||
finished_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
)
|
||||
rowcount = int(db.session.execute(fail_stmt).rowcount or 0)
|
||||
if rowcount == 1:
|
||||
_sync_parse_intake_after_job_mutation(job_id)
|
||||
db.session.commit()
|
||||
_expire_cached()
|
||||
return rowcount == 1
|
||||
|
||||
|
||||
def process_next_job(
|
||||
@@ -293,7 +947,12 @@ def process_next_job(
|
||||
timeout_config_key: str | None = None,
|
||||
default_timeout_seconds: float = 300,
|
||||
) -> tuple[bool, str]:
|
||||
"""领取并分发一条通用任务。"""
|
||||
"""
|
||||
领取并分发一条通用任务。
|
||||
|
||||
核心逻辑:超时回收必须与本次允许领取的 job_types 同范围,避免同 domain
|
||||
下其他类型被错误阈值或缺少业务回调的入口提前回收;未指定类型时才回收整个 domain。
|
||||
"""
|
||||
import app.jobs.handlers # noqa: F401
|
||||
from app.jobs.registry import get_handler
|
||||
|
||||
@@ -302,29 +961,54 @@ def process_next_job(
|
||||
if timeout_config_key
|
||||
else default_timeout_seconds
|
||||
)
|
||||
recover_stale_jobs(domain=domain, timeout_seconds=timeout_seconds)
|
||||
normalized_types = list(
|
||||
dict.fromkeys(
|
||||
_normalize_job_type(item)
|
||||
for item in (job_types or [])
|
||||
if _normalize_job_type(item)
|
||||
)
|
||||
)
|
||||
if normalized_types:
|
||||
for normalized_type in normalized_types:
|
||||
on_recovered = None
|
||||
if normalized_type == JobType.SHIPPING_NOTICE_PARSE.value:
|
||||
from app.services.shipping_notice.intake_parse_workflow import (
|
||||
sync_intake_after_parse_job_recovery,
|
||||
)
|
||||
|
||||
on_recovered = sync_intake_after_parse_job_recovery
|
||||
recover_stale_jobs(
|
||||
domain=domain,
|
||||
timeout_seconds=timeout_seconds,
|
||||
job_type=normalized_type,
|
||||
on_recovered=on_recovered,
|
||||
)
|
||||
else:
|
||||
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)
|
||||
owned_attempt = int(job.attempts or 0)
|
||||
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}")
|
||||
fail_job(
|
||||
job_id,
|
||||
error=f"no handler registered for {job.job_type}",
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
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="任务处理完成")
|
||||
# 条件收口:Handler 已 finish/fail 或代次失效时 rowcount=0,不覆盖
|
||||
finish_job(job_id, message="任务处理完成", owned_attempt=owned_attempt)
|
||||
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)
|
||||
fail_job(job_id, error=str(exc), retryable=True, owned_attempt=owned_attempt)
|
||||
raise
|
||||
Reference in new issue
Block a user