feat(schedule): 新增平台任务参数契约与动态选项支持

This commit is contained in:
hugo committed 2026-07-09 13:19:36 +08:00
1 parent 2ce1aca023
commit 8b5b0b49bf
76 files changed
+7103 -1203

No files matched your search

@@ -1,3 +1,12 @@
"""
backend/app/services/schedule/scheduler_service.py
用途:排程任务生命周期(创建/更新/立即执行)与后台调度 worker。
依赖:schedule_contract、job_params、cron_util、timezone_util、excel_service、wecom_notify、kb_sync。
逻辑:api/schedule/tasks.py 与 import_service 调用 create_task/update_task/enable_task;
job_params 在本层经 normalize_job_params_for_contract 唯一归一化(含切换 platform_api_path
未传参时重置默认值);run_task_now 经 resolve_schedule_executor 分发 handler。
"""
from __future__ import annotations
import threading
@@ -14,6 +23,14 @@ from app.services.schedule.cron_util import normalize_cron_expr
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
from app.services.schedule.excel_service import export_schedule_result_excel
from app.services.schedule import resolve_schedule_executor, resolve_schedule_header
from app.services.schedule.shipping_inventory_rpa_finalize import (
apply_deferred_schedule_run_state,
is_awaiting_rpa_schedule_run,
recover_all_stale_awaiting_rpa_schedule_runs,
recover_stale_awaiting_rpa_schedule_runs,
should_defer_schedule_run_finalization,
)
from app.services.schedule.job_params import normalize_job_params_for_contract
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id
from app.services.schedule.timezone_util import compute_next_run_at, normalize_schedule_timezone, utc_now_naive
@@ -94,6 +111,9 @@ def _notify_schedule_run_wecom(task: ScheduleTask, run: ScheduleRun) -> None:
f'状态: {status_label}\n'
f'总数: {run.total_count} 成功: {run.success_count} 失败: {run.failed_count}'
)
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
if summary.get('excel_failed') or summary.get('excel_export_status') == 'failed':
description += '\n备注: 库存源已成功,但排程 Excel 生成失败'
media_id = None
if run.excel_file_data and run.excel_file_name:
@@ -166,6 +186,7 @@ def create_task(
dify_agent_id: int | None,
platform_api_path: str | None,
data_source_type: str | None,
job_params: dict[str, Any] | None = None,
notify_user_ids_json: list[int] | None,
notify_enabled: bool,
enabled: bool,
@@ -173,7 +194,15 @@ def create_task(
kb_group_id: int | None = None,
actor_id: int | None,
commit: bool = True,
check_options: bool = True,
) -> ScheduleTask:
"""
创建排程任务。
核心逻辑:契约校验后,job_params 经 normalize_job_params_for_contract 唯一归一化再写入。
Args:
check_options: 是否校验 select/multi_select 选项范围;导入跨环境时传 False。
"""
from app.services.schedule.schedule_contract import apply_schedule_contract_to_payload
cron_expr = normalize_cron_expr(cron_expr)
@@ -182,6 +211,12 @@ def create_task(
'data_source_type': data_source_type,
'platform_api_path': platform_api_path,
})
normalized_job_params = normalize_job_params_for_contract(
contract['schedule_type'],
contract['platform_api_path'],
job_params,
check_options=check_options,
)
task = ScheduleTask(
schedule_no=_generate_schedule_no(),
name=name,
@@ -193,6 +228,7 @@ def create_task(
dify_agent_id=dify_agent_id,
platform_api_path=contract['platform_api_path'],
data_source_type=contract['data_source_type'],
job_params=normalized_job_params,
kb_sync_enabled=bool(kb_sync_enabled),
kb_group_id=kb_group_id,
notify_user_ids_json=notify_user_ids_json or [],
@@ -219,8 +255,20 @@ def update_task(
payload: dict[str, Any],
actor_id: int | None,
commit: bool = True,
check_options: bool = True,
) -> ScheduleTask:
from app.services.schedule.schedule_contract import apply_schedule_contract_to_payload
"""
更新排程任务字段。
核心逻辑:契约字段与 job_params 在本层统一归一化——显式传 job_params 时按新契约校验;
切换 platform_api_path 且未传 job_params 时重置为新 schema 默认值(或清空)。
Args:
check_options: 是否校验 select/multi_select 选项范围;导入跨环境时传 False。
"""
from app.services.schedule.schedule_contract import (
apply_schedule_contract_to_payload,
normalize_job_key,
)
for key in [
"name",
@@ -248,7 +296,10 @@ def update_task(
raw_group_id = payload.get("kb_group_id")
task.kb_group_id = int(raw_group_id) if raw_group_id not in (None, "", 0, "0") else None
if any(k in payload for k in ("schedule_type", "data_source_type", "platform_api_path")):
# [STEP 1] 契约字段:有变更则校验并写回;否则沿用当前任务三层语义
previous_path = task.platform_api_path
contract_touched = any(k in payload for k in ("schedule_type", "data_source_type", "platform_api_path"))
if contract_touched:
contract = apply_schedule_contract_to_payload({
"schedule_type": payload.get("schedule_type", task.schedule_type),
"data_source_type": payload.get("data_source_type", task.data_source_type),
@@ -257,6 +308,32 @@ def update_task(
task.schedule_type = contract["schedule_type"]
task.data_source_type = contract["data_source_type"]
task.platform_api_path = contract["platform_api_path"]
else:
contract = {
"schedule_type": task.schedule_type,
"data_source_type": task.data_source_type,
"platform_api_path": task.platform_api_path,
}
# [STEP 2] job_params 唯一归一化入口:显式传参 / 切换 job key 重置 / 非平台任务清空
path_changed = normalize_job_key(previous_path) != normalize_job_key(contract["platform_api_path"])
if "job_params" in payload:
task.job_params = normalize_job_params_for_contract(
contract["schedule_type"],
contract["platform_api_path"],
payload.get("job_params"),
check_options=check_options,
)
elif contract_touched and (
contract["schedule_type"] != "platform_job"
or path_changed
):
task.job_params = normalize_job_params_for_contract(
contract["schedule_type"],
contract["platform_api_path"],
None,
check_options=check_options,
)
if task.enabled and task.cron_expr:
task.schedule_timezone = normalize_schedule_timezone(getattr(task, "schedule_timezone", None))
@@ -270,7 +347,51 @@ def update_task(
return task
def enable_task(task: ScheduleTask, *, commit: bool = True, check_options: bool = True) -> ScheduleTask:
"""
启用排程并重新计算 next_run_at。
核心逻辑:启用前重新校验三层契约(含 registry enabled);platform_job 顺带归一化 job_params,
避免停用任务或失效参数被重新放入调度队列。
Args:
check_options: 是否校验 select/multi_select 选项范围。
Raises:
ValueError: 契约非法、平台任务已停用或 job_params 校验失败。
"""
from app.services.schedule.schedule_contract import apply_schedule_contract_to_payload
contract = apply_schedule_contract_to_payload({
'schedule_type': task.schedule_type,
'data_source_type': task.data_source_type,
'platform_api_path': task.platform_api_path,
})
task.schedule_type = contract['schedule_type']
task.data_source_type = contract['data_source_type']
task.platform_api_path = contract['platform_api_path']
if contract['schedule_type'] == 'platform_job':
task.job_params = normalize_job_params_for_contract(
contract['schedule_type'],
contract['platform_api_path'],
task.job_params,
check_options=check_options,
)
task.enabled = True
if task.cron_expr:
task.cron_expr = normalize_cron_expr(task.cron_expr)
task.schedule_timezone = normalize_schedule_timezone(getattr(task, 'schedule_timezone', None))
task.next_run_at = compute_next_run_at(task.cron_expr, timezone_name=task.schedule_timezone)
else:
task.next_run_at = None
if commit:
db.session.commit()
return task
def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id: int | None, run: ScheduleRun | None = None) -> ScheduleRun:
recover_stale_awaiting_rpa_schedule_runs(task)
if run is None:
existing = db.session.query(ScheduleRun).filter(
ScheduleRun.schedule_task_id == task.id,
@@ -319,6 +440,19 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
clear_cancelled_run(run.id)
return run
if should_defer_schedule_run_finalization(task, step_logs):
return apply_deferred_schedule_run_state(
run,
task,
total_count=total_count,
success_count=success_count,
failed_count=failed_count,
skipped_count=skipped_count,
details=details,
errors=errors,
step_logs=step_logs,
)
duration_ms = int((time.time() - start_ts) * 1000)
if current_app:
current_app.logger.info(
@@ -449,13 +583,27 @@ def start_scheduler(app):
stuck = db.session.query(ScheduleRun).filter(
ScheduleRun.status == "running",
).all()
cleaned = 0
for r in stuck:
if is_awaiting_rpa_schedule_run(r):
continue
r.status = "failed"
r.error_message = "服务重启,执行中断"
r.finished_at = datetime.utcnow()
if stuck:
cleaned += 1
if cleaned:
db.session.commit()
current_app.logger.info("[schedule-worker] cleaned %d stuck running runs on startup", len(stuck))
current_app.logger.info(
"[schedule-worker] cleaned %d stuck running runs on startup (skipped awaiting RPA)",
cleaned,
)
recovered_awaiting = recover_all_stale_awaiting_rpa_schedule_runs()
if recovered_awaiting:
current_app.logger.info(
"[schedule-worker] recovered %d stale awaiting RPA runs on startup",
recovered_awaiting,
)
while True:
try:
@@ -466,6 +614,7 @@ def start_scheduler(app):
ScheduleTask.next_run_at <= now,
).limit(5).with_for_update(skip_locked=True).all()
for task in due_tasks:
recover_stale_awaiting_rpa_schedule_runs(task)
has_running = db.session.query(ScheduleRun).filter(
ScheduleRun.schedule_task_id == task.id,
ScheduleRun.status == "running",