""" 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 下 failed Job 累计次数 + 5s/30s/120s 退避重新入队; 次数耗尽时 fail_job 并 complete_gate_attempt(blocked_retryable),保留人工恢复入口; 不修改 input_snapshot_json,以保持 input_snapshot_hash 与正文一致; 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 ( SHIPPING_PROCESS_GATE_JOB_DOMAIN, claim_and_run_gate_attempt, enqueue_gate_attempt_job, ) from app.services.shipping_notice.process_gate_service import complete_gate_attempt def _finalize_attempt_after_failure( *, attempt: ShippingProcessGateAttempt, exc: BaseException, ) -> None: """ 单次门禁执行失败:结束当前 Attempt,并将 Gate 收口为可人工恢复阻断。 核心逻辑:调用 complete_gate_attempt,避免 Job=failed 而 Gate 仍 running。 """ safe = sanitize_gate_error_text(exc, max_len=500) or 'technical_failure' if attempt.status == 'queued': attempt.status = 'running' db.session.flush() complete_gate_attempt( attempt_id=int(attempt.id), outcome='blocked_retryable', # 与 error_explainability_contract / PROCESS_GATE_BLOCKING 对齐,禁止写未登记的 technical_failure blocking_reason_code='technical_failure_present', blocking_reason_json={ 'reason_code': 'technical_failure_present', 'message': safe, }, effective_result_json={'findings': [], 'error': 'technical_failure'}, output_snapshot={'error': safe}, error_code='TECHNICAL_FAILURE', 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: # claim/execute 可能已经让 SQLAlchemy 事务进入 aborted 状态(例如死锁)。 # 任何失败收口前必须先回滚,避免把 Job 标记失败后留下 queued Attempt/Gate。 db.session.rollback() 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 safe_error = sanitize_gate_error_text(exc, max_len=1000) or 'technical_failure' # 先把 Attempt/Gate/Execution 收口,再独立结束 Job;即使 Runner 随后兜底标记 # Job failed,也不会再留下 failed Job + queued Attempt 的非法组合。 if attempt is not None: fresh_attempt = db.session.get(ShippingProcessGateAttempt, attempt_id) if fresh_attempt is not None and fresh_attempt.status in {'queued', 'running'}: _finalize_attempt_after_failure(attempt=fresh_attempt, exc=exc) db.session.commit() fail_job(job.id, error=safe_error, retryable=False, owned_attempt=owned_attempt) return finish_job(job.id, result=result if isinstance(result, dict) else {'status': 'ok'}, owned_attempt=owned_attempt)