2
This commit is contained in:
commit
21d41acf50
732 files changed
+55672
-15251
No files matched your search
@@ -4,6 +4,8 @@ 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
|
||||
@@ -29,6 +31,86 @@ from app.services.schedule.freight_receipt_rpa_finalize import (
|
||||
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:
|
||||
@@ -67,6 +149,9 @@ def _create_queued_run(
|
||||
"""
|
||||
在当前事务创建 ScheduleRun 与对应通用 Job。
|
||||
|
||||
核心逻辑:worker 认领仍靠 domain=schedule + job_type=schedule_run;
|
||||
业务身份写入 business_ref / payload.platform_api_path / message,避免 jobs 表全是 schedule。
|
||||
|
||||
Args:
|
||||
task: 已由调用方锁定的排程任务。
|
||||
trigger_type: `manual` 或 `cron`,禁止传入未知触发类型。
|
||||
@@ -93,19 +178,25 @@ def _create_queued_run(
|
||||
)
|
||||
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=f"schedule_run:{run.id}",
|
||||
business_ref=schedule_job_business_ref(run.id, task),
|
||||
created_by_id=triggered_by_user_id,
|
||||
max_attempts=3,
|
||||
message="排程等待后台执行",
|
||||
message=f"{task_label}等待后台执行",
|
||||
dedupe_active=False,
|
||||
commit=False,
|
||||
)
|
||||
@@ -145,13 +236,8 @@ def enqueue_manual_schedule_run(
|
||||
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}",
|
||||
)
|
||||
query_jobs_for_schedule_run(active.id)
|
||||
.filter(Job.status.in_(("queued", "running")))
|
||||
.order_by(Job.id.asc())
|
||||
.first()
|
||||
)
|
||||
@@ -253,13 +339,9 @@ def prepare_schedule_queue() -> int:
|
||||
if is_awaiting_rpa_schedule_run(run) or is_awaiting_receipt_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")),
|
||||
)
|
||||
query_jobs_for_schedule_run(run.id)
|
||||
.filter(Job.status.in_(("queued", "running")))
|
||||
.with_entities(Job.id)
|
||||
.first()
|
||||
)
|
||||
if active_job is None:
|
||||
@@ -319,11 +401,13 @@ def execute_schedule_job(*, job_id: int, run_id: int, logger) -> ScheduleRun | N
|
||||
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},
|
||||
message="排程已处于终态",
|
||||
result={"schedule_run_id": run.id, "status": run.status, "platform_api_path": platform_path},
|
||||
message=f"{task_label}已处于终态",
|
||||
)
|
||||
return run
|
||||
|
||||
@@ -334,6 +418,14 @@ def execute_schedule_job(*, job_id: int, run_id: int, logger) -> ScheduleRun | N
|
||||
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,
|
||||
@@ -342,8 +434,12 @@ def execute_schedule_job(*, job_id: int, run_id: int, logger) -> ScheduleRun | N
|
||||
)
|
||||
finish_job(
|
||||
job_id,
|
||||
result={"schedule_run_id": result_run.id, "status": result_run.status},
|
||||
message="排程执行完成",
|
||||
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:
|
||||
@@ -366,5 +462,11 @@ def execute_schedule_job(*, job_id: int, run_id: int, logger) -> ScheduleRun | N
|
||||
retryable=True,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
logger.exception("schedule run failed run_id=%s job_id=%s", run_id, job_id)
|
||||
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
|
||||
Reference in new issue
Block a user