Files
hugo 911afa0f73 feat(freight-rpa): 增加出站报表配置与回调支持,重构相关服务
- 将 RPA 管理 API 扩展至出站报表配置,新增出站相关的回调接口。
- 重构 freight_rpa_report_config_service,支持入站与出站报表配置的管理。
- 更新 ORM 模型,增加出站报表相关的持久化模型。
- 统一命名规范,确保在手、入站与出站的概念一致性。
2026-10-19 18:45:16 +08:00

509 lines
19 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
backend/app/services/schedule/queue_service.py
用途:把手动与 Cron 排程统一写入通用 Job 队列,并维护 ScheduleRun 业务状态。
依赖:models.ScheduleTask/ScheduleRun、jobs.queue、schedule timezone 与 RPA 收口服务
(onhand / inbound / outbound finalize 超时回收)。
逻辑: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.freight_rpa_onhand_finalize import (
recover_all_stale_awaiting_rpa_schedule_runs,
recover_stale_awaiting_rpa_schedule_runs,
)
from app.services.schedule.freight_rpa_inbound_finalize import (
recover_all_stale_orphan_inbound_units,
recover_all_stale_inbound_rpa_schedule_runs,
recover_stale_inbound_rpa_schedule_runs,
is_awaiting_inbound_rpa_schedule_run,
)
from app.services.schedule.freight_rpa_outbound_finalize import (
recover_all_stale_orphan_outbound_units,
recover_all_stale_outbound_rpa_schedule_runs,
recover_stale_outbound_rpa_schedule_runs,
)
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_inbound_rpa_schedule_runs(task)
recover_stale_outbound_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_inbound_rpa_schedule_runs(task)
recover_stale_outbound_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.freight_rpa_onhand_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_inbound_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)
from app.services.freight_rpa.onhand.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.inbound_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)
# 收料 run 超时对账同为每轮领取维护(2026-10-07 从启动一次性分支迁出):
# 此前长驻进程期间超时 run 永不终态(RUN20261001131705E5E5 卡执行中的根因)。
# 回收判据为最后活动锚(笔间静默),健康长批次不被误杀,见 freight_rpa_inbound_finalize。
inbound_stale = recover_all_stale_inbound_rpa_schedule_runs()
if inbound_stale:
current_app.logger.info("[schedule-worker] recovered %d stale inbound RPA runs", inbound_stale)
# 按需触发(无排程)孤儿单元同口径回收(2026-10-16):调拨工作台重试/自动调拨
# 补抓创建的单元 schedule_run_id 为 NULL,上方 run 级扫描按 run 遍历覆盖不到;
# 网页异常关闭后回调永不到达,不回收则来源投影永久 fetching、重试按钮永久锁死。
orphan_stale = recover_all_stale_orphan_inbound_units()
if orphan_stale:
current_app.logger.info("[schedule-worker] recovered %d stale orphan inbound RPA units", orphan_stale)
# 出站 run / 孤儿单元超时对账与入站同属每轮领取维护,不得挂启动一次性分支。
outbound_stale = recover_all_stale_outbound_rpa_schedule_runs()
if outbound_stale:
current_app.logger.info("[schedule-worker] recovered %d stale outbound RPA runs", outbound_stale)
outbound_orphan_stale = recover_all_stale_orphan_outbound_units()
if outbound_orphan_stale:
current_app.logger.info("[schedule-worker] recovered %d stale orphan outbound RPA units", outbound_orphan_stale)
try:
from app.services.freight_rpa.common.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