""" backend/app/jobs/runner.py 用途:Worker 主循环 poll → dispatch → ack/fail。 逻辑:worker.py 调用 run_forever(ctx);claim 走 store,执行走 registry handler。 """ from __future__ import annotations import time from typing import TYPE_CHECKING, Callable from app.jobs import store from app.jobs.registry import get_handler if TYPE_CHECKING: from app.jobs.context import JobContext def _resolve_poll_seconds(ctx: JobContext) -> float: """按队列配置读取轮询间隔。""" queues = ctx.extras.get('queues') or ['kb'] if 'schedule' in queues and len(queues) == 1: return float(ctx.config.get('SCHEDULE_WORKER_POLL_SECONDS', 30)) if 'shipping' in queues and 'kb' not in queues: return float(ctx.config.get('SHIPPING_NOTICE_WORKER_POLL_SECONDS', 2)) return float(ctx.config.get('KB_WORKER_POLL_SECONDS', 2)) def run_forever( ctx: JobContext, *, poll_interval_seconds: float | None = None, recovery_callback: Callable[[], int] | None = None, recovery_interval_seconds: float = 60.0, ) -> None: """ 持续轮询并执行任务。 核心逻辑:claim_next → get_handler → handler(ctx, payload);异常时 mark_failed。 支持 recovery_callback:启动立即执行一次,空闲睡眠和 claim 后检查 tick。 Args: ctx: Worker 上下文(extras.queues 指定消费队列)。 poll_interval_seconds: 无任务时的休眠秒数;默认按队列读 config。 recovery_callback: 恢复回调函数,返回本轮处理计数;默认 None 关闭。 recovery_interval_seconds: 两次 recovery tick 的最小间隔秒数;默认 60。 """ queues = ctx.extras.get('queues') or ['kb'] poll = poll_interval_seconds if poll_interval_seconds is not None else _resolve_poll_seconds(ctx) ctx.logger.info('Job runner started queues=%s poll_seconds=%s recovery=%s', queues, poll, recovery_callback is not None) if recovery_callback is not None: try: recovery_callback() except Exception: ctx.logger.exception('Recovery callback failed on BOOT') finally: last_recovery_ts = time.monotonic() else: last_recovery_ts = time.monotonic() while True: job = store.claim_next(queues=queues) if not job: current_ts = time.monotonic() if recovery_callback is not None and (current_ts - last_recovery_ts) >= recovery_interval_seconds: try: recovery_callback() except Exception: ctx.logger.exception('Recovery callback failed during idle poll') finally: last_recovery_ts = current_ts time.sleep(poll) continue handler = get_handler(job['job_type']) owned_attempt = job.get('attempts') owned_attempt_int = int(owned_attempt) if owned_attempt is not None else None if not handler: ctx.logger.error('No handler for job_type=%s job_id=%s', job.get('job_type'), job.get('id')) store.mark_failed( job['id'], message=f'no handler for {job.get("job_type")}', owned_attempt=owned_attempt_int, ) if recovery_callback is not None: current_ts = time.monotonic() if (current_ts - last_recovery_ts) >= recovery_interval_seconds: try: recovery_callback() except Exception: ctx.logger.exception('Recovery callback failed after no-handler job') finally: last_recovery_ts = current_ts continue try: handler(ctx, job.get('payload') or {}) except Exception as exc: ctx.logger.exception('Handler failed job_id=%s', job.get('id')) # Handler 可能在 flush/写库失败后留下 aborted transaction;先回滚, # 再查询并收口 Job,否则 mark_failed 自身会被 InFailedSqlTransaction 阻断。 try: from app import db db.session.rollback() except Exception: ctx.logger.exception('Session rollback failed after handler job_id=%s', job.get('id')) store.mark_failed( job['id'], message=str(exc), owned_attempt=owned_attempt_int, ) finally: if recovery_callback is not None: current_ts = time.monotonic() if (current_ts - last_recovery_ts) >= recovery_interval_seconds: try: recovery_callback() except Exception: ctx.logger.exception('Recovery callback failed after job execution') finally: last_recovery_ts = current_ts