- 新增 common/trigger_consumer 领取/归档原语,库存与收料 Worker 统一四态目录契约,README 载明契约 - 触发先落单元行再原子写 trigger;假触发器委托真实服务;触发目录不可用单元标 failed - 回调终态桥接推进调拨来源任务,有推进即 commit 保证持久 - 预检接真实异动文件仓库与 parse_movement_rows,行合成 sheet/row_no 溯源 - 等待回调来源任务超时回收挂每轮排程领取,绝不自动重试 - 三环境补收料共享目录 env,值对齐 §1.9.3 挂载约定
481 lines
18 KiB
Python
481 lines
18 KiB
Python
"""
|
||
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。
|
||
domain/job_type 固定 schedule/schedule_run 供 worker 认领;业务身份写入
|
||
business_ref(schedule_run:{id}:{platform_api_path})、payload 与 message。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
from datetime import datetime
|
||
from typing import Any
|
||
|
||
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.freight_receipt_rpa_finalize import (
|
||
recover_all_stale_receipt_rpa_schedule_runs,
|
||
recover_stale_receipt_rpa_schedule_runs,
|
||
is_awaiting_receipt_rpa_schedule_run,
|
||
)
|
||
from app.services.schedule.timezone_util import compute_next_run_at, utc_now_naive
|
||
|
||
_worker_initialized = False
|
||
_BUSINESS_REF_SLUG_MAX = 80
|
||
|
||
|
||
def _schedule_job_slug(task: ScheduleTask) -> str:
|
||
"""
|
||
从排程任务生成写入 jobs.business_ref 的业务短码。
|
||
|
||
核心逻辑:优先 platform_api_path(如 accounting-voucher-check);无 path 时用 untagged。
|
||
冒号替换为连字符,避免破坏 `schedule_run:{id}:{slug}` 三段格式。
|
||
|
||
Args:
|
||
task: 排程任务。
|
||
|
||
Returns:
|
||
最长 80 字符的 slug。
|
||
"""
|
||
from app.services.schedule import normalize_platform_api_path
|
||
|
||
slug = normalize_platform_api_path(getattr(task, "platform_api_path", None)) or "untagged"
|
||
slug = slug.replace(":", "-").replace("/", "-")
|
||
return slug[:_BUSINESS_REF_SLUG_MAX]
|
||
|
||
|
||
def _schedule_task_label(task: ScheduleTask) -> str:
|
||
"""
|
||
jobs.message 与 worker 日志用的任务显示名。
|
||
|
||
核心逻辑:优先中文 name(如「立账凭证检核」);否则回落到 platform_api_path。
|
||
|
||
Args:
|
||
task: 排程任务。
|
||
|
||
Returns:
|
||
非空显示名。
|
||
"""
|
||
name = str(getattr(task, "name", None) or "").strip()
|
||
if name:
|
||
return name
|
||
slug = _schedule_job_slug(task)
|
||
return slug if slug != "untagged" else "未命名排程"
|
||
|
||
|
||
def schedule_job_business_ref(run_id: int, task: ScheduleTask) -> str:
|
||
"""
|
||
生成 schedule Job 的 business_ref。
|
||
|
||
格式:`schedule_run:{run_id}:{platform_api_path}`,便于在 jobs 表区分立账凭证检核等任务。
|
||
仍保留 run_id,取消/回收可按前缀精确匹配,避免 `schedule_run:1` 误伤 `schedule_run:13`。
|
||
|
||
Args:
|
||
run_id: ScheduleRun 主键。
|
||
task: 排程任务。
|
||
|
||
Returns:
|
||
长度不超过 128 的 business_ref。
|
||
"""
|
||
return f"schedule_run:{int(run_id)}:{_schedule_job_slug(task)}"
|
||
|
||
|
||
def query_jobs_for_schedule_run(run_id: int):
|
||
"""
|
||
按 ScheduleRun 主键查找对应通用 Job。
|
||
|
||
核心逻辑:兼容旧格式 `schedule_run:{id}` 与新格式 `schedule_run:{id}:{path}`。
|
||
新格式必须带 `id` 后的冒号,避免 run_id=1 匹配到 10/11/13。
|
||
|
||
Args:
|
||
run_id: ScheduleRun 主键。
|
||
|
||
Returns:
|
||
已过滤 domain/job_type/business_ref 的 Query;调用方可继续按 status 收窄。
|
||
"""
|
||
run_id = int(run_id)
|
||
legacy = f"schedule_run:{run_id}"
|
||
prefix = f"schedule_run:{run_id}:"
|
||
return db.session.query(Job).filter(
|
||
Job.domain == "schedule",
|
||
Job.job_type == JobType.SCHEDULE_RUN.value,
|
||
db.or_(Job.business_ref == legacy, Job.business_ref.startswith(prefix)),
|
||
)
|
||
|
||
|
||
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,
|
||
api_request_json: dict[str, Any] | None = None,
|
||
) -> tuple[ScheduleRun, int]:
|
||
"""
|
||
在当前事务创建 ScheduleRun 与对应通用 Job。
|
||
|
||
核心逻辑:worker 认领仍靠 domain=schedule + job_type=schedule_run;
|
||
业务身份写入 business_ref / payload.platform_api_path / message,避免 jobs 表全是 schedule。
|
||
|
||
Args:
|
||
task: 已由调用方锁定的排程任务。
|
||
trigger_type: `manual` 或 `cron`,禁止传入未知触发类型。
|
||
triggered_by_user_id: 手动触发用户 ID;Cron 为 None。
|
||
api_request_json: 可选运行参数(如立账凭证 `run_options.mode=force_all`),须在入队前写入以免 worker 抢跑。
|
||
|
||
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",
|
||
api_request_json=api_request_json,
|
||
)
|
||
db.session.add(run)
|
||
db.session.flush()
|
||
task_label = _schedule_task_label(task)
|
||
platform_path = str(getattr(task, "platform_api_path", None) or "").strip()
|
||
job_id = enqueue(
|
||
JobType.SCHEDULE_RUN,
|
||
{
|
||
"schedule_task_id": task.id,
|
||
"schedule_run_id": run.id,
|
||
"schedule_no": task.schedule_no,
|
||
"run_no": run.run_no,
|
||
"task_name": task_label,
|
||
"platform_api_path": platform_path,
|
||
"trigger_type": normalized_trigger,
|
||
"triggered_by_user_id": triggered_by_user_id,
|
||
},
|
||
domain="schedule",
|
||
business_ref=schedule_job_business_ref(run.id, task),
|
||
created_by_id=triggered_by_user_id,
|
||
max_attempts=3,
|
||
message=f"{task_label}等待后台执行",
|
||
dedupe_active=False,
|
||
commit=False,
|
||
)
|
||
return run, job_id
|
||
|
||
|
||
def enqueue_manual_schedule_run(
|
||
task_id: int,
|
||
*,
|
||
triggered_by_user_id: int | None,
|
||
api_request_json: dict[str, Any] | None = None,
|
||
) -> tuple[ScheduleRun, int, bool]:
|
||
"""
|
||
手动触发排程并写入 schedule 队列。
|
||
|
||
核心逻辑:锁定 ScheduleTask 后复检 queued/running;已有活动记录时直接返回,
|
||
否则同事务创建 ScheduleRun 与 Job,避免接口线程承担长耗时执行。
|
||
|
||
Args:
|
||
task_id: 排程任务主键。
|
||
triggered_by_user_id: 触发人;系统触发可为空。
|
||
api_request_json: 写入新 run 的请求快照;已有活动 run 时不会覆盖。
|
||
|
||
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)
|
||
recover_stale_receipt_rpa_schedule_runs(task)
|
||
active = _active_run(task.id)
|
||
if active is not None:
|
||
job = (
|
||
query_jobs_for_schedule_run(active.id)
|
||
.filter(Job.status.in_(("queued", "running")))
|
||
.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,
|
||
api_request_json=api_request_json,
|
||
)
|
||
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:
|
||
# 每轮都回收当前任务已超时的外部 RPA 回调,不能仅依赖 worker 启动时扫一次;
|
||
# 这只是终态化失败,不会自动重新导出。
|
||
recover_stale_awaiting_rpa_schedule_runs(task)
|
||
recover_stale_receipt_rpa_schedule_runs(task)
|
||
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) or is_awaiting_receipt_rpa_schedule_run(run):
|
||
continue
|
||
active_job = (
|
||
query_jobs_for_schedule_run(run.id)
|
||
.filter(Job.status.in_(("queued", "running")))
|
||
.with_entities(Job.id)
|
||
.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)
|
||
receipt_recovered = recover_all_stale_receipt_rpa_schedule_runs()
|
||
if receipt_recovered:
|
||
current_app.logger.info("[schedule-worker] recovered %d stale receipt RPA runs", receipt_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
|
||
|
||
# 调拨来源等待回调 Job 的超时回收与下方 RPA 心跳告警同属每轮领取维护:
|
||
# 不能挂在 worker 启动一次性分支里,否则进程长期驻留期间超时任务永远无法终态化。
|
||
from app.services.in_transit_transfer.receipt_callback_bridge import recover_stale_waiting_source_jobs
|
||
|
||
transfer_stale = recover_stale_waiting_source_jobs()
|
||
if transfer_stale:
|
||
current_app.logger.info("[schedule-worker] recovered %d stale transfer waiting source jobs", transfer_stale)
|
||
|
||
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
|
||
task_label = _schedule_task_label(task)
|
||
platform_path = str(getattr(task, "platform_api_path", None) or "").strip() or "untagged"
|
||
if run.status in {"success", "failed", "partial_failed"}:
|
||
finish_job(
|
||
job_id,
|
||
result={"schedule_run_id": run.id, "status": run.status, "platform_api_path": platform_path},
|
||
message=f"{task_label}已处于终态",
|
||
)
|
||
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()
|
||
logger.info(
|
||
"[schedule-run] start name=%s path=%s run_no=%s run_id=%s job_id=%s",
|
||
task_label,
|
||
platform_path,
|
||
run.run_no,
|
||
run.id,
|
||
job_id,
|
||
)
|
||
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,
|
||
"platform_api_path": platform_path,
|
||
},
|
||
message=f"{task_label}执行完成",
|
||
)
|
||
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 name=%s path=%s run_id=%s job_id=%s",
|
||
task_label,
|
||
platform_path,
|
||
run_id,
|
||
job_id,
|
||
)
|
||
return run
|