""" backend/app/jobs/handlers/shipping_process_gate.py 用途:消费门禁恢复 Attempt Job,领取租约并执行 process_gate_executor。 依赖:JobContext、process_gate_job_service、process_gate_service、jobs.queue finish/fail、 process_gate_error_sanitizer。 逻辑:由 shipping worker 领取;技术失败按 Attempt 累计次数 + 5s/30s/120s 退避重新入队; 次数耗尽时 fail_job 并 complete_gate_attempt(failed_terminal); waiting_external 先结束当前 Job 再延迟入队新 Job; healthcheck_probe 载荷用于部署探针,不依赖真实 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_error_sanitizer import sanitize_gate_error_text from app.services.shipping_notice.process_gate_job_service import ( claim_and_run_gate_attempt, enqueue_gate_attempt_job, schedule_waiting_external_poll, ) from app.services.shipping_notice.process_gate_service import complete_gate_attempt # 方案规定的技术重试退避(秒):第 1/2/3 次失败后延迟。 _TECHNICAL_RETRY_BACKOFF_SECONDS: tuple[int, ...] = (5, 30, 120) _TECH_RETRY_KEY = 'technical_retry_count' def _technical_retry_count(attempt: ShippingProcessGateAttempt) -> int: """读取 Attempt 上累计的技术失败次数(跨 force_new Job 保留)。""" snap = attempt.input_snapshot_json if isinstance(attempt.input_snapshot_json, dict) else {} try: return max(int(snap.get(_TECH_RETRY_KEY) or 0), 0) except (TypeError, ValueError): return 0 def _bump_technical_retry_count(attempt: ShippingProcessGateAttempt) -> int: """递增并回写技术失败次数,返回递增后的值。""" snap = dict(attempt.input_snapshot_json) if isinstance(attempt.input_snapshot_json, dict) else {} next_count = _technical_retry_count(attempt) + 1 snap[_TECH_RETRY_KEY] = next_count attempt.input_snapshot_json = snap return next_count def _finalize_attempt_after_retry_exhausted( *, attempt: ShippingProcessGateAttempt, exc: BaseException, ) -> None: """ 技术重试耗尽:将 Attempt/Gate 收口为 failed_terminal。 核心逻辑:调用 complete_gate_attempt,避免 Job=failed 而 Gate 仍 running。 """ safe = sanitize_gate_error_text(exc, max_len=500) or 'technical_retry_exhausted' if attempt.status == 'queued': attempt.status = 'running' db.session.flush() complete_gate_attempt( attempt_id=int(attempt.id), outcome='failed_terminal', blocking_reason_code='technical_failure', blocking_reason_json={'message': safe, 'technical_retry_exhausted': True}, effective_result_json={'findings': [], 'error': 'technical_retry_exhausted'}, output_snapshot={'error': safe, 'technical_retry_exhausted': True}, error_code='TECHNICAL_RETRY_EXHAUSTED', error_summary=safe, ) @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;healthcheck_probe=True 时仅证明领取能力。 """ # [STEP] 部署探针:Worker 领取后立即成功结束,不触碰业务 Attempt。 if bool(payload.get('healthcheck_probe')): raw_job_id = payload.get('job_id') job = db.session.get(Job, int(raw_job_id)) if raw_job_id else None if job is None: raise RuntimeError('missing_job_id_for_healthcheck_probe') finish_job( job.id, result={'status': 'healthcheck_probe_ok'}, owned_attempt=int(job.attempts or 0), ) return 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] 技术失败:按 Attempt 累计次数判定,禁止因 force_new Job.attempts=0 无限重试。 max_attempts = max( int(current_app.config.get('SHIPPING_PROCESS_GATE_TECHNICAL_RETRIES', 3) or 3), 1, ) retries_done = _technical_retry_count(attempt) if attempt is not None else max_attempts safe_error = sanitize_gate_error_text(exc, max_len=1000) or 'technical_failure' if attempt is not None and retries_done + 1 < max_attempts: delay_idx = min(retries_done, len(_TECHNICAL_RETRY_BACKOFF_SECONDS) - 1) delay = _TECHNICAL_RETRY_BACKOFF_SECONDS[delay_idx] fail_job( job.id, error=safe_error, retryable=False, owned_attempt=owned_attempt, ) _bump_technical_retry_count(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=safe_error, retryable=False, owned_attempt=owned_attempt) if attempt is not None: _finalize_attempt_after_retry_exhausted(attempt=attempt, exc=exc) db.session.commit() 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()