refactor(scheduler): 排程迁移出web进程,迁入scheduler worker

This commit is contained in:
sophie committed 2026-07-30 19:52:41 +08:00
1 parent 970ee06537
commit 74745a9d10
21 files changed
+652 -223

No files matched your search

@@ -0,0 +1,346 @@
"""
backend/app/services/schedule/queue_service.py
用途:把手动与 Cron 排程统一写入通用 Job 队列,并维护 ScheduleRun 业务状态。
依赖:models.ScheduleTask/ScheduleRun、jobs.queue、schedule timezone 与 RPA 收口服务。
逻辑:API 只创建 queued run;独立 schedule worker 扫描到期任务、领取 Job 后执行 scheduler_service。
"""
from __future__ import annotations
from datetime import datetime
from flask import current_app
from app import db
from app.jobs.queue import enqueue, fail_job, finish_job, recover_stale_jobs
from app.jobs.types import JobType
from app.models import Job, ScheduleRun, ScheduleTask
from app.services.schedule.shipping_inventory_rpa_finalize import (
recover_all_stale_awaiting_rpa_schedule_runs,
recover_stale_awaiting_rpa_schedule_runs,
)
from app.services.schedule.timezone_util import compute_next_run_at, utc_now_naive
_worker_initialized = False
def _active_run(task_id: int) -> ScheduleRun | None:
"""返回同一排程当前 queued/running 的运行记录,防止并发重复执行。"""
return (
db.session.query(ScheduleRun)
.filter(
ScheduleRun.schedule_task_id == int(task_id),
ScheduleRun.status.in_(("queued", "running")),
)
.order_by(ScheduleRun.id.asc())
.first()
)
def _advance_next_run(task: ScheduleTask) -> None:
"""Cron 触发入队后立即推进下次执行时间;无后续时间时停用任务。"""
if task.cron_expr:
task.next_run_at = compute_next_run_at(
task.cron_expr,
timezone_name=getattr(task, "schedule_timezone", None),
)
if task.next_run_at is None:
task.enabled = False
else:
task.next_run_at = None
def _create_queued_run(
task: ScheduleTask,
*,
trigger_type: str,
triggered_by_user_id: int | None,
) -> tuple[ScheduleRun, int]:
"""
在当前事务创建 ScheduleRun 与对应通用 Job。
Args:
task: 已由调用方锁定的排程任务。
trigger_type: `manual` 或 `cron`,禁止传入未知触发类型。
triggered_by_user_id: 手动触发用户 ID;Cron 为 None。
Returns:
`(ScheduleRun, job_id)`;调用方负责提交事务。
"""
normalized_trigger = str(trigger_type or "").strip().lower()
if normalized_trigger not in {"manual", "cron"}:
raise ValueError(f"unsupported schedule trigger_type={trigger_type!r}")
from app.services.schedule.scheduler_service import _generate_run_no
run = ScheduleRun(
run_no=_generate_run_no(),
schedule_task_id=task.id,
trigger_type=normalized_trigger,
triggered_by_user_id=triggered_by_user_id,
started_at=None,
status="queued",
)
db.session.add(run)
db.session.flush()
job_id = enqueue(
JobType.SCHEDULE_RUN,
{
"schedule_task_id": task.id,
"schedule_run_id": run.id,
"trigger_type": normalized_trigger,
"triggered_by_user_id": triggered_by_user_id,
},
domain="schedule",
business_ref=f"schedule_run:{run.id}",
created_by_id=triggered_by_user_id,
max_attempts=3,
message="排程等待后台执行",
dedupe_active=False,
commit=False,
)
return run, job_id
def enqueue_manual_schedule_run(
task_id: int,
*,
triggered_by_user_id: int | None,
) -> tuple[ScheduleRun, int, bool]:
"""
手动触发排程并写入 schedule 队列。
核心逻辑:锁定 ScheduleTask 后复检 queued/running;已有活动记录时直接返回,
否则同事务创建 ScheduleRun 与 Job,避免接口线程承担长耗时执行。
Returns:
`(run, job_id, created)`;created=False 表示已有活动 run。
"""
task = (
db.session.query(ScheduleTask)
.filter(ScheduleTask.id == int(task_id))
.with_for_update()
.first()
)
if task is None:
raise LookupError(f"schedule task {task_id} not found")
recover_stale_awaiting_rpa_schedule_runs(task)
active = _active_run(task.id)
if active is not None:
job = (
db.session.query(Job)
.filter(
Job.domain == "schedule",
Job.job_type == JobType.SCHEDULE_RUN.value,
Job.status.in_(("queued", "running")),
Job.business_ref == f"schedule_run:{active.id}",
)
.order_by(Job.id.asc())
.first()
)
return active, int(job.id) if job else 0, False
run, job_id = _create_queued_run(
task,
trigger_type="manual",
triggered_by_user_id=triggered_by_user_id,
)
db.session.commit()
return run, job_id, True
def enqueue_due_schedule_runs(*, limit: int = 5) -> int:
"""
扫描到期排程并入队,供独立 schedule worker 每轮轮询调用。
核心逻辑:`FOR UPDATE SKIP LOCKED` 保证多 worker 不会重复调度;同任务已有
queued/running 时保留原到期时间,待该 run 完成后立即补跑;无活动 run 时同事务
创建 run/job 并推进时间。
Returns:
本轮新建的 schedule Job 数量。
"""
now = utc_now_naive()
tasks = (
db.session.query(ScheduleTask)
.filter(
ScheduleTask.enabled.is_(True),
ScheduleTask.next_run_at.isnot(None),
ScheduleTask.next_run_at <= now,
)
.order_by(ScheduleTask.next_run_at.asc(), ScheduleTask.id.asc())
.limit(max(1, int(limit or 1)))
.with_for_update(skip_locked=True)
.all()
)
if not tasks:
db.session.rollback()
return 0
created = 0
for task in tasks:
if _active_run(task.id) is None:
_create_queued_run(task, trigger_type="cron", triggered_by_user_id=None)
_advance_next_run(task)
created += 1
db.session.commit()
return created
def _sync_run_after_stale_job(job: Job) -> None:
"""通用 Job 超时回收后同步 ScheduleRun,避免业务状态永久停留在 running。"""
payload = job.payload_json if isinstance(job.payload_json, dict) else {}
run_id = int(payload.get("schedule_run_id") or 0)
run = db.session.get(ScheduleRun, run_id) if run_id else None
if run is None or run.status not in {"queued", "running"}:
return
if job.status == "queued":
run.status = "queued"
run.started_at = None
run.error_message = "后台执行超时,等待重试"
elif job.status in {"failed", "dead", "cancelled"}:
run.status = "failed"
run.finished_at = datetime.utcnow()
run.error_message = job.error_message or "后台执行超时"
def prepare_schedule_queue() -> int:
"""
执行 schedule worker 的恢复维护、到期扫描和超时 Job 回收。
Returns:
本轮新入队的到期排程数量。
"""
global _worker_initialized
timeout_seconds = float(current_app.config.get("SCHEDULE_JOB_RUNNING_TIMEOUT_SECONDS", 7200))
recover_stale_jobs(
domain="schedule",
timeout_seconds=timeout_seconds,
job_type=JobType.SCHEDULE_RUN,
on_recovered=_sync_run_after_stale_job,
)
if not _worker_initialized:
# [STEP 1] 兼容升级前由 Web 线程留下的 running 记录;无活动 Job 承接时标记中断。
from app.services.schedule.shipping_inventory_rpa_finalize import is_awaiting_rpa_schedule_run
legacy_running = db.session.query(ScheduleRun).filter(ScheduleRun.status == "running").all()
interrupted = 0
for run in legacy_running:
if is_awaiting_rpa_schedule_run(run):
continue
active_job = (
db.session.query(Job.id)
.filter(
Job.domain == "schedule",
Job.job_type == JobType.SCHEDULE_RUN.value,
Job.business_ref == f"schedule_run:{run.id}",
Job.status.in_(("queued", "running")),
)
.first()
)
if active_job is None:
run.status = "failed"
run.finished_at = datetime.utcnow()
run.error_message = "排程 worker 升级重启,旧执行已中断"
interrupted += 1
if interrupted:
db.session.commit()
current_app.logger.warning("[schedule-worker] closed %d legacy running schedule runs", interrupted)
# [STEP 2] 恢复等待 RPA 的运行与回调清理任务。
recovered = recover_all_stale_awaiting_rpa_schedule_runs()
if recovered:
current_app.logger.info("[schedule-worker] recovered %d stale awaiting RPA runs", recovered)
from app.services.shipping_notice.inventory_rpa_callback_cleanup import (
recover_pending_rpa_callback_cleanup_jobs,
)
cleanup_count, cleanup_warnings = recover_pending_rpa_callback_cleanup_jobs()
if cleanup_count:
current_app.logger.info("[schedule-worker] processed %d RPA cleanup jobs", cleanup_count)
if cleanup_warnings:
current_app.logger.warning("[schedule-worker] RPA cleanup warnings: %s", "; ".join(cleanup_warnings[:5]))
_worker_initialized = True
try:
from app.services.shipping_notice.rpa_worker_heartbeat_alert import maybe_alert_rpa_worker_status
maybe_alert_rpa_worker_status(force=False)
except Exception as exc:
db.session.rollback()
current_app.logger.warning("[schedule-worker] RPA heartbeat alert check failed: %s", exc)
return enqueue_due_schedule_runs()
def execute_schedule_job(*, job_id: int, run_id: int, logger) -> ScheduleRun | None:
"""
执行已领取的排程 Job,并同步 Job 与 ScheduleRun 终态。
Args:
job_id: 通用 Job 主键。
run_id: ScheduleRun 主键。
logger: worker logger。
Returns:
已执行的 ScheduleRun;业务记录已被删除时返回 None 并将 Job 正常收口。
"""
run = db.session.get(ScheduleRun, int(run_id))
if run is None:
finish_job(job_id, result={"schedule_run_id": run_id, "status": "deleted"}, message="排程已删除")
return None
task = db.session.get(ScheduleTask, run.schedule_task_id)
if task is None:
finish_job(job_id, result={"schedule_run_id": run_id, "status": "task_deleted"}, message="排程已删除")
return None
if run.status in {"success", "failed", "partial_failed"}:
finish_job(
job_id,
result={"schedule_run_id": run.id, "status": run.status},
message="排程已处于终态",
)
return run
from app.services.schedule.scheduler_service import run_task_now
try:
run.status = "running"
run.started_at = run.started_at or datetime.utcnow()
run.error_message = None
db.session.commit()
result_run = run_task_now(
task,
trigger_type=run.trigger_type,
triggered_by_user_id=run.triggered_by_user_id,
run=run,
)
finish_job(
job_id,
result={"schedule_run_id": result_run.id, "status": result_run.status},
message="排程执行完成",
)
return result_run
except Exception as exc:
db.session.rollback()
job = db.session.get(Job, int(job_id))
run = db.session.get(ScheduleRun, int(run_id))
retrying = bool(job and int(job.attempts or 0) < int(job.max_attempts or 1))
if run and run.status in {"queued", "running"} and not (
run.status == "running" and isinstance(run.response_summary_json, dict) and run.response_summary_json.get("awaiting_rpa")
):
run.status = "queued" if retrying else "failed"
run.started_at = None if retrying else run.started_at
run.finished_at = None if retrying else datetime.utcnow()
run.error_message = str(exc)[:1000]
db.session.commit()
owned_attempt = int(job.attempts or 0) if job is not None else None
fail_job(
job_id,
error=str(exc),
retryable=True,
owned_attempt=owned_attempt,
)
logger.exception("schedule run failed run_id=%s job_id=%s", run_id, job_id)
return run