Files
syops/backend/app/jobs/handlers/shipping_process_gate.py
T
hugoandCursor 323928626b feat(shipping-process-gates): 落地全门禁中断恢复并消除双真相
纳入 Execution/Gate/Attempt 模型与迁移、Worker/API/前端恢复卡片与 Admin 诊断,
Gate 阻断时清零旧 action_buttons,异常摘要统一脱敏,并为运维筛选与 Attempt Diff 补齐入口。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-01 13:08:32 +08:00

112 lines
4.4 KiB
Python

"""
backend/app/jobs/handlers/shipping_process_gate.py
用途:消费门禁恢复 Attempt Job,领取租约并执行 process_gate_executor。
依赖:JobContext、process_gate_job_service、jobs.queue finish/fail。
逻辑:由 shipping worker 领取;技术失败按 5s/30s/120s 退避重新入队;
waiting_external 先结束当前 Job 再延迟入队新 Job(禁止复用仍 running 的 Job);
成功进入 waiting_external 时调度下一次 poll Attempt。
"""
from __future__ import annotations
from flask import current_app
from app import db
from app.jobs.context import JobContext
from app.jobs.queue import fail_job, finish_job
from app.jobs.registry import register_handler
from app.jobs.types import JobType
from app.models import Job, ShippingProcessGate, ShippingProcessGateAttempt
from app.services.shipping_notice.process_gate_job_service import (
claim_and_run_gate_attempt,
enqueue_gate_attempt_job,
schedule_waiting_external_poll,
)
# 方案规定的技术重试退避(秒):第 1/2/3 次失败后延迟。
_TECHNICAL_RETRY_BACKOFF_SECONDS: tuple[int, ...] = (5, 30, 120)
@register_handler(JobType.SHIPPING_PROCESS_GATE)
def run_shipping_process_gate(ctx: JobContext, payload: dict) -> None:
"""
执行门禁 Attempt。
Args:
ctx: Worker 上下文。
payload: 须含 attempt_id 与 job_id。
"""
attempt_id = int(payload.get('attempt_id') or 0)
raw_job_id = payload.get('job_id')
job = db.session.get(Job, int(raw_job_id)) if raw_job_id else None
if attempt_id <= 0 or job is None:
raise RuntimeError('missing_attempt_id_or_job_id')
owned_attempt = int(job.attempts or 0)
worker_id = str(ctx.extras.get('worker_label') or f'shipping-gate-{job.id}')
try:
result = claim_and_run_gate_attempt(attempt_id=attempt_id, worker_id=worker_id)
except Exception as exc:
attempt = db.session.get(ShippingProcessGateAttempt, attempt_id)
gate = None
gate_status = None
if attempt is not None:
gate = db.session.get(ShippingProcessGate, int(attempt.gate_id))
gate_status = gate.status if gate else None
# [STEP] 外部等待:先结束当前 Job,再清空 job_id 并延迟入队,避免复用 running Job。
if gate_status == 'waiting_external':
poll = max(int(current_app.config.get('SHIPPING_PROCESS_GATE_EXTERNAL_POLL_SECONDS', 30) or 30), 5)
finish_job(job.id, result={'status': 'waiting_external_requeued'}, owned_attempt=owned_attempt)
if attempt is not None:
attempt.job_id = None
db.session.flush()
enqueue_gate_attempt_job(
attempt_id=attempt_id,
delay_seconds=poll,
force_new=True,
)
db.session.commit()
return
# [STEP] 技术失败:先 fail 当前 Job,再按退避入队新 Job。
max_attempts = int(job.max_attempts or 3)
if attempt is not None and owned_attempt < max_attempts:
delay_idx = min(max(owned_attempt - 1, 0), len(_TECHNICAL_RETRY_BACKOFF_SECONDS) - 1)
delay = _TECHNICAL_RETRY_BACKOFF_SECONDS[delay_idx]
fail_job(
job.id,
error=str(exc)[:1000],
retryable=False,
owned_attempt=owned_attempt,
)
attempt.status = 'queued'
attempt.job_id = None
attempt.worker_id = None
attempt.lease_token = None
attempt.lease_expires_at = None
if gate is not None and gate.status == 'running':
gate.status = 'queued'
db.session.flush()
enqueue_gate_attempt_job(
attempt_id=attempt_id,
delay_seconds=delay,
force_new=True,
)
db.session.commit()
return
fail_job(job.id, error=str(exc)[:1000], retryable=False, owned_attempt=owned_attempt)
return
finish_job(job.id, result=result, owned_attempt=owned_attempt)
# [STEP] 成功落入 waiting_external:调度下一次 poll Attempt(含超时判定)。
if str((result or {}).get('gate_status') or '') == 'waiting_external':
schedule_waiting_external_poll(
attempt_id=int(attempt_id),
gate_code=str((result or {}).get('gate_code') or ''),
)
db.session.commit()