feat(schedule): 优化排程任务配置与进度契约处理逻辑

This commit is contained in:
hugo committed 2026-07-08 16:09:28 +08:00
1 parent d54f51ddc3
commit 99453aa52a
65 files changed
+2837 -487

No files matched your search

+51 -19
View File
@@ -21,15 +21,21 @@ ScheduleExecutor = Callable[[ScheduleTask, ScheduleRun], ScheduleExecuteResult]
def normalize_platform_api_path(path: str | None) -> str:
"""
归一化 platform job key 或完整 URL。
核心逻辑:http(s) 完整 URL 原样返回(外部集成端点);
其余值统一委托 schedule_contract.normalize_job_key(契约层与执行层单一归一化入口)。
"""
value = str(path or "").strip()
if not value:
return ""
parsed = urlparse(value)
if parsed.scheme in {"http", "https"}:
return value
if not value.startswith("/"):
value = "/" + value
return value
from app.services.schedule.schedule_contract import normalize_job_key
return normalize_job_key(value)
def _build_srm_conn_str() -> str:
@@ -67,11 +73,38 @@ def _resolve_schedule_user(task: ScheduleTask) -> str:
return str(getattr(task.owner, "username", "") or task.owner_user_id or "schedule_system")
def _run_platform_job_in_process(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
"""
进程内执行已注册平台 Job(无需 HTTP,也不依赖 INTERNAL_API_BASE_URL)。
核心逻辑:从 job_registry 按 platform_api_path 查 handler 直接调用。
"""
from app.services.schedule.job_registry import run_platform_job
key = normalize_platform_api_path(task.platform_api_path)
payload = {
"run_no": run.run_no,
"schedule_task_id": task.id,
"schedule_name": task.name,
"dify_agent_id": task.dify_agent_id,
}
run.api_request_json = payload
db.session.commit()
return run_platform_job(key, task, run, payload)
def _run_common_executor(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
endpoint = normalize_platform_api_path(task.platform_api_path)
if not endpoint:
raise RuntimeError("platform_api_path is missing")
# [STEP 1] 普通 job key(非完整 URL)优先进程内直接调 registry,避免 HTTP 与 base URL 依赖
if not (endpoint.startswith("http://") or endpoint.startswith("https://")):
from app.services.schedule.job_registry import get_platform_job
if get_platform_job(endpoint):
return _run_platform_job_in_process(task, run)
# [STEP 2] 完整 URL(外部集成)仍走 HTTP;base URL 仅用于补全相对路径
base = str(current_app.config.get("INTERNAL_API_BASE_URL") or "").strip().rstrip("/")
if endpoint.startswith("http://") or endpoint.startswith("https://"):
url = endpoint
@@ -79,7 +112,9 @@ def _run_common_executor(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecut
name = endpoint.lstrip("/")
url = f"{base}/api/internal/jobs/{name}"
else:
url = endpoint
raise RuntimeError(
f"platform_api_path '{endpoint}' is not a registered job and INTERNAL_API_BASE_URL is not configured"
)
payload = {
"run_no": run.run_no,
@@ -185,6 +220,10 @@ def _run_generic_check_job(task: ScheduleTask, run: ScheduleRun) -> ScheduleExec
_build_record_text,
)
dst = getattr(task, "data_source_type", None)
if dst not in ("database", "external_api"):
raise RuntimeError(f"Invalid data_source_type for data_pipeline: {dst!r}")
cfg = get_schedule_sql_config_by_task_id(task.id)
if not cfg:
return 0, 0, 0, 0, [], [], []
@@ -263,25 +302,18 @@ def _run_generic_check_job(task: ScheduleTask, run: ScheduleRun) -> ScheduleExec
def list_registered_api_paths() -> list[dict[str, str]]:
from app.models import ScheduleTask
results: list[dict[str, str]] = []
tasks = ScheduleTask.query.filter(ScheduleTask.platform_api_path.isnot(None)).all()
for t in tasks:
results.append({"value": t.platform_api_path, "label": t.name or str(t.id)})
return results
from app.services.schedule.job_registry import list_platform_jobs
return [{"value": job.key, "label": job.label} for job in list_platform_jobs()]
def resolve_schedule_executor(task: ScheduleTask) -> ScheduleExecutor:
dst = getattr(task, "data_source_type", None) or "database"
if dst == "faq_hot_aggregate":
from app.services.schedule.faq_hot_aggregate_job import run_faq_hot_aggregate_schedule
return run_faq_hot_aggregate_schedule
if dst == "shipping_inventory_rpa":
from app.services.schedule.shipping_inventory_rpa_job import run_shipping_inventory_rpa_schedule
return run_shipping_inventory_rpa_schedule
if dst in ("database", "external_api"):
st = getattr(task, "schedule_type", None) or "data_pipeline"
if st == "data_pipeline":
return _run_generic_check_job
return _run_common_executor
if st == "platform_job":
return _run_common_executor
raise RuntimeError(f"Unsupported schedule_type: {st}")
_SCHEDULE_HEADER_REGISTRY: dict[str, tuple[list[str], dict[str, str]]] = {}
@@ -3,7 +3,7 @@ backend/app/services/schedule/faq_hot_aggregate_job.py
用途:排程管理触发的 FAQ 热点离线聚合执行器。
依赖:HotFaqAggregator、ScheduleTask、ScheduleRun。
逻辑:data_source_type=faq_hot_aggregate 时由 resolve_schedule_executor 调用。
逻辑:platform_api_path=faq-aggregate-hot 时由 job_registry 调用。
"""
from __future__ import annotations
@@ -0,0 +1,38 @@
"""
backend/app/services/schedule/fixed_assets_snapshot_job.py
用途:排程触发的固资快照同步执行器。
依赖:FixedAssetsSnapshotService、ScheduleTask、ScheduleRun。
逻辑:platform_api_path=fixed-assets-snapshot 时由 job_registry 调用。
"""
from __future__ import annotations
from typing import Any
from app.models import ScheduleRun, ScheduleTask
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
def run_fixed_assets_snapshot_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
"""
执行固资快照同步(薄封装)。
核心逻辑:委托 FixedAssetsSnapshotService.sync_once,结果写入 step_logs。
"""
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
summary = FixedAssetsSnapshotService.sync_once(reason="schedule", attempt=1)
row_count = int(summary.get("row_count") or 0)
step_logs: list[dict[str, Any]] = [
{
"step": "fixed_assets_snapshot_sync",
"status": "success",
"detail": {
"version": summary.get("current_version"),
"row_count": row_count,
"schedule_task_id": task.id,
},
}
]
return row_count, row_count, 0, 0, [summary], [], step_logs
+50 -34
View File
@@ -2,8 +2,8 @@
backend/app/services/schedule/import_service.py
用途:排程任务 JSON 批量导入(upsert by schedule_no)。
依赖:models、scheduler_service、sql_config。
逻辑:由 api/schedule/tasks.py import 路由调用。
依赖:models、scheduler_service、schedule_contract、sql_config。
逻辑:由 api/schedule/tasks.py import 路由调用;导入时自动迁移旧语义。
"""
from __future__ import annotations
@@ -12,6 +12,11 @@ from typing import Any
from app import db
from app.core.errors import ValidationError
from app.models import ScheduleTask
from app.services.schedule.schedule_contract import (
apply_schedule_contract_to_payload,
assert_schedule_config_writable,
migrate_legacy_schedule_payload,
)
from app.services.schedule.scheduler_service import create_task, update_task
from app.services.schedule.sql_config import upsert_schedule_task_config
@@ -38,67 +43,78 @@ def import_schedules_from_payload(schedules: list[Any], *, actor_id: int | None)
skipped += 1
continue
try:
name = str(item.get('name') or '').strip()
cron_expr = str(item.get('cron_expr') or '').strip()
owner_user_id = int(item.get('owner_user_id'))
migrated = migrate_legacy_schedule_payload(item)
name = str(migrated.get('name') or '').strip()
cron_expr = str(migrated.get('cron_expr') or '').strip()
owner_user_id = int(migrated.get('owner_user_id'))
if not name or not cron_expr:
raise ValueError('name or cron_expr missing')
contract = apply_schedule_contract_to_payload({
'schedule_type': migrated.get('schedule_type'),
'data_source_type': migrated.get('data_source_type'),
'platform_api_path': migrated.get('platform_api_path'),
})
cfg = migrated.get('config') if isinstance(migrated.get('config'), dict) else None
assert_schedule_config_writable(
schedule_type=contract['schedule_type'],
platform_api_path=contract['platform_api_path'],
config=cfg,
)
existing = None
schedule_no = str(item.get('schedule_no') or '').strip()
schedule_no = str(migrated.get('schedule_no') or '').strip()
if schedule_no:
existing = db.session.query(ScheduleTask).filter_by(schedule_no=schedule_no).first()
task_payload = {
'name': name,
'schedule_type': str(item.get('schedule_type') or 'platform_app'),
'schedule_type': contract['schedule_type'],
'owner_user_id': owner_user_id,
'cron_expr': cron_expr,
'schedule_timezone': item.get('schedule_timezone'),
'wait_seconds': int(item.get('wait_seconds') or 0),
'dify_agent_id': item.get('dify_agent_id'),
'platform_api_path': item.get('platform_api_path'),
'notify_user_ids_json': item.get('notify_user_ids_json')
if isinstance(item.get('notify_user_ids_json'), list)
'schedule_timezone': migrated.get('schedule_timezone'),
'wait_seconds': int(migrated.get('wait_seconds') or 0),
'dify_agent_id': migrated.get('dify_agent_id'),
'platform_api_path': contract['platform_api_path'],
'data_source_type': contract['data_source_type'],
'notify_user_ids_json': migrated.get('notify_user_ids_json')
if isinstance(migrated.get('notify_user_ids_json'), list)
else [],
'notify_enabled': bool(item.get('notify_enabled', True)),
'enabled': bool(item.get('enabled', True)),
'data_source_type': str(item.get('data_source_type') or 'database'),
'kb_sync_enabled': bool(item.get('kb_sync_enabled', False)),
'kb_group_id': item.get('kb_group_id'),
'notify_enabled': bool(migrated.get('notify_enabled', True)),
'enabled': bool(migrated.get('enabled', True)),
'kb_sync_enabled': bool(migrated.get('kb_sync_enabled', False)),
'kb_group_id': migrated.get('kb_group_id'),
}
cfg = item.get('config') if isinstance(item.get('config'), dict) else None
if existing:
update_task(existing, payload=task_payload, actor_id=actor_id)
existing.data_source_type = task_payload['data_source_type']
update_task(existing, payload=task_payload, actor_id=actor_id, commit=False)
if cfg:
upsert_schedule_task_config(existing.id, cfg)
upsert_schedule_task_config(existing.id, cfg, commit=False)
else:
task = create_task(
name=name,
schedule_type=task_payload['schedule_type'],
schedule_type=contract['schedule_type'],
owner_user_id=owner_user_id,
cron_expr=cron_expr,
schedule_timezone=task_payload['schedule_timezone'],
wait_seconds=task_payload['wait_seconds'],
dify_agent_id=task_payload['dify_agent_id'],
platform_api_path=task_payload['platform_api_path'],
platform_api_path=contract['platform_api_path'],
data_source_type=contract['data_source_type'],
notify_user_ids_json=task_payload['notify_user_ids_json'],
notify_enabled=task_payload['notify_enabled'],
enabled=task_payload['enabled'],
kb_sync_enabled=task_payload['kb_sync_enabled'],
kb_group_id=(
int(task_payload['kb_group_id'])
if task_payload.get('kb_group_id') not in (None, '', 0, '0')
else None
),
actor_id=actor_id,
commit=False,
)
task.data_source_type = task_payload['data_source_type']
task.kb_sync_enabled = task_payload['kb_sync_enabled']
task.kb_group_id = (
int(task_payload['kb_group_id'])
if task_payload.get('kb_group_id') not in (None, '', 0, '0')
else None
)
db.session.commit()
if cfg:
upsert_schedule_task_config(task.id, cfg)
upsert_schedule_task_config(task.id, cfg, commit=False)
db.session.commit()
imported += 1
except Exception as exc:
db.session.rollback()
errors.append(str(exc))
skipped += 1
db.session.commit()
return {'ok': True, 'imported': imported, 'skipped': skipped, 'errors': errors[:20]}
@@ -0,0 +1,119 @@
"""
backend/app/services/schedule/job_registry.py
用途:平台内置排程 Job Registry(key → handler)。
依赖:shipping_inventory_rpa_job、faq_hot_aggregate_job、fixed_assets_snapshot_job。
逻辑:internal_jobs API 与 platform_job 排程通过 platform_api_path 引用已注册 key。
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Callable
from app.models import ScheduleRun, ScheduleTask
from app.services.schedule.schedule_contract import normalize_job_key
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
PlatformJobHandler = Callable[[ScheduleTask, ScheduleRun], ScheduleExecuteResult]
_REGISTRY: dict[str, "PlatformJobDefinition"] = {}
@dataclass(frozen=True)
class PlatformJobDefinition:
"""平台内置 Job 元数据与执行 handler。"""
key: str
label: str
handler: PlatformJobHandler
description: str = ""
# 前端 i18n key(如 admin.schedule.form.platformJobShippingInventory);
# 前端下拉优先 $t(label_key),label 仅作 fallback/debug。
label_key: str = ""
def register_platform_job(definition: PlatformJobDefinition) -> None:
"""注册平台 Job;重复 key 覆盖(便于热重载测试)。"""
key = normalize_job_key(definition.key)
if not key:
raise ValueError("platform job key is required")
_REGISTRY[key] = PlatformJobDefinition(
key=key,
label=definition.label,
handler=definition.handler,
description=definition.description,
label_key=definition.label_key,
)
def get_platform_job(key: str) -> PlatformJobDefinition | None:
"""按 key 查询已注册 Job。"""
return _REGISTRY.get(normalize_job_key(key))
def list_platform_jobs() -> list[PlatformJobDefinition]:
"""返回全部已注册 Job(按 key 排序)。"""
return [_REGISTRY[k] for k in sorted(_REGISTRY)]
def is_registered_platform_job(key: str) -> bool:
"""判断 key 是否已注册。"""
return normalize_job_key(key) in _REGISTRY
def run_platform_job(
key: str,
task: ScheduleTask,
run: ScheduleRun,
payload: dict[str, Any] | None = None,
) -> ScheduleExecuteResult:
"""
执行已注册平台 Job。
Args:
key: platform_api_path job key
task: 排程任务
run: 执行批次
payload: internal API 请求体(部分 handler 可读 agent_id 等)
Returns:
ScheduleExecuteResult 七元组
Raises:
KeyError: 未注册 key
"""
definition = get_platform_job(key)
if not definition:
raise KeyError(f"Unknown platform job: {key}")
_ = payload # 预留扩展;FAQ 等从 task 读取 dify_agent_id
return definition.handler(task, run)
def _register_builtin_platform_jobs() -> None:
"""模块加载时注册内置平台 Job。"""
from app.services.schedule.faq_hot_aggregate_job import run_faq_hot_aggregate_schedule
from app.services.schedule.fixed_assets_snapshot_job import run_fixed_assets_snapshot_schedule
from app.services.schedule.shipping_inventory_rpa_job import run_shipping_inventory_rpa_schedule
register_platform_job(PlatformJobDefinition(
key="shipping-inventory-rpa",
label="货代库存 RPA",
label_key="admin.schedule.form.platformJobShippingInventory",
handler=run_shipping_inventory_rpa_schedule,
description="批量写入库存 RPA export trigger,由 freight_rpa_worker 异步导出。",
))
register_platform_job(PlatformJobDefinition(
key="faq-aggregate-hot",
label="FAQ 热点聚合",
label_key="admin.schedule.form.platformJobFaqHotAggregate",
handler=run_faq_hot_aggregate_schedule,
description="ChatLog 热点发现,结果写入 faq_hot_candidates。",
))
register_platform_job(PlatformJobDefinition(
key="fixed-assets-snapshot",
label="固资快照",
label_key="admin.schedule.form.platformJobFixedAssetsSnapshot",
handler=run_fixed_assets_snapshot_schedule,
description="同步 PLM 固资快照至本地 manifest。",
))
_register_builtin_platform_jobs()
@@ -0,0 +1,202 @@
"""
backend/app/services/schedule/schedule_contract.py
用途:排程三层语义校验与旧数据迁移(schedule_type / data_source_type / platform_api_path)。
依赖:job_registry.get_platform_job。
逻辑:scheduler_service、api/schedule/tasks、import_service 创建/更新/导入前调用。
"""
from __future__ import annotations
from typing import Any
SCHEDULE_TYPE_DATA_PIPELINE = "data_pipeline"
SCHEDULE_TYPE_PLATFORM_JOB = "platform_job"
DATA_SOURCE_DATABASE = "database"
DATA_SOURCE_EXTERNAL_API = "external_api"
VALID_SCHEDULE_TYPES = frozenset({SCHEDULE_TYPE_DATA_PIPELINE, SCHEDULE_TYPE_PLATFORM_JOB})
VALID_DATA_PIPELINE_SOURCES = frozenset({DATA_SOURCE_DATABASE, DATA_SOURCE_EXTERNAL_API})
LEGACY_SCHEDULE_TYPES = frozenset({"platform_app", "dify_app"})
LEGACY_DATA_SOURCE_TO_PLATFORM_JOB = {
"shipping_inventory_rpa": "shipping-inventory-rpa",
"faq_hot_aggregate": "faq-aggregate-hot",
}
# 允许写 ScheduleTaskConfig 的 platform_job(其余平台任务仅存 cron + job key,禁配置)
PLATFORM_JOBS_ALLOWING_CONFIG = frozenset({"shipping-inventory-rpa"})
def platform_job_allows_config(key: str | None) -> bool:
"""判断该 platform_job 是否允许写 ScheduleTaskConfig。"""
return normalize_job_key(key) in PLATFORM_JOBS_ALLOWING_CONFIG
def assert_schedule_config_writable(
*,
schedule_type: str,
platform_api_path: str | None,
config: dict[str, Any] | None,
) -> None:
"""
携带 config 时校验是否允许写入 ScheduleTaskConfig。
Raises:
ValueError: 非白名单 platform_job 携带 config
"""
if not config or not isinstance(config, dict):
return
st = str(schedule_type or "").strip().lower()
if st == SCHEDULE_TYPE_DATA_PIPELINE:
return
if st == SCHEDULE_TYPE_PLATFORM_JOB and platform_job_allows_config(platform_api_path):
return
key = normalize_job_key(platform_api_path) or "unknown"
raise ValueError(f"platform_job '{key}' does not accept ScheduleTaskConfig")
def normalize_job_key(value: str | None) -> str:
"""
归一化 platform job key。
核心逻辑:小写、去 query/hash、去首尾斜杠;历史数据可能存完整路径或 URL
(如 /api/internal/jobs/faq-aggregate-hot、http://host/api/internal/jobs/foo),
统一取最后一段;下划线转连字符。
"""
raw = str(value or "").strip().lower()
raw = raw.split("?", 1)[0].split("#", 1)[0]
raw = raw.strip("/")
if "/" in raw:
raw = raw.rsplit("/", 1)[-1]
return raw.replace("_", "-")
def _is_registered_platform_job(key: str) -> bool:
"""查询 job_registry 判断 key 是否已注册(懒加载避免循环 import)。"""
if not key:
return False
from app.services.schedule.job_registry import get_platform_job
return get_platform_job(key) is not None
def normalize_schedule_type(value: str | None, *, default: str = SCHEDULE_TYPE_DATA_PIPELINE) -> str:
"""
宽松解析 schedule_type;未知值回退 default。
仅用于 legacy 迁移兜底;创建/更新校验请用 validate_schedule_fields(对未知值报错)。
"""
raw = str(value or "").strip().lower()
if raw in VALID_SCHEDULE_TYPES:
return raw
return default
def normalize_data_source_type(value: str | None) -> str | None:
"""解析 data_pipeline 数据源;空值返回 None。"""
if value is None:
return None
raw = str(value).strip().lower()
if not raw:
return None
if raw in VALID_DATA_PIPELINE_SOURCES:
return raw
raise ValueError(f"Invalid data_source_type: {value!r}")
def migrate_legacy_schedule_payload(payload: dict[str, Any]) -> dict[str, Any]:
"""
导入/导出 JSON 旧语义自动迁移。
核心逻辑:旧 data_source_type 平台任务别名 → platform_job + job key;旧 platform_app → data_pipeline。
"""
out = dict(payload)
dst = str(out.get("data_source_type") or "").strip().lower()
st = str(out.get("schedule_type") or "").strip().lower()
path = normalize_job_key(str(out.get("platform_api_path") or ""))
if dst in LEGACY_DATA_SOURCE_TO_PLATFORM_JOB:
out["schedule_type"] = SCHEDULE_TYPE_PLATFORM_JOB
out["platform_api_path"] = LEGACY_DATA_SOURCE_TO_PLATFORM_JOB[dst]
out["data_source_type"] = None
return out
if _is_registered_platform_job(path):
out["schedule_type"] = SCHEDULE_TYPE_PLATFORM_JOB
out["platform_api_path"] = path
out["data_source_type"] = None
return out
if st in LEGACY_SCHEDULE_TYPES and dst in VALID_DATA_PIPELINE_SOURCES:
out["schedule_type"] = SCHEDULE_TYPE_DATA_PIPELINE
out["platform_api_path"] = None
return out
if st in LEGACY_SCHEDULE_TYPES and not dst:
if path:
out["schedule_type"] = SCHEDULE_TYPE_PLATFORM_JOB
out["platform_api_path"] = path
out["data_source_type"] = None
else:
out["schedule_type"] = SCHEDULE_TYPE_DATA_PIPELINE
out["data_source_type"] = DATA_SOURCE_DATABASE
out["platform_api_path"] = None
return out
def validate_schedule_fields(
*,
schedule_type: str,
data_source_type: str | None,
platform_api_path: str | None,
) -> tuple[str, str | None, str | None]:
"""
校验并归一化三层字段组合。
Args:
schedule_type: data_pipeline | platform_job
data_source_type: 仅 data_pipeline 必填
platform_api_path: 仅 platform_job 必填且须已注册
Returns:
(schedule_type, data_source_type, platform_api_path)
Raises:
ValueError: schedule_type 未知、字段组合非法或未注册 job key
"""
st = str(schedule_type or "").strip().lower()
if st not in VALID_SCHEDULE_TYPES:
raise ValueError(
f"Invalid schedule_type: {schedule_type!r} (expected data_pipeline | platform_job)"
)
path = normalize_job_key(platform_api_path) or None
if st == SCHEDULE_TYPE_DATA_PIPELINE:
dst = normalize_data_source_type(data_source_type)
if not dst:
raise ValueError("data_source_type is required for data_pipeline (database | external_api)")
return st, dst, None
if st == SCHEDULE_TYPE_PLATFORM_JOB:
if not path:
raise ValueError("platform_api_path is required for platform_job")
from app.services.schedule.job_registry import get_platform_job
if not get_platform_job(path):
raise ValueError(f"Unknown platform job key: {path}")
return st, None, path
raise ValueError(f"Unsupported schedule_type: {schedule_type}")
def apply_schedule_contract_to_payload(payload: dict[str, Any]) -> dict[str, Any]:
"""迁移旧字段后校验,返回可写入 ORM 的字段子集。"""
migrated = migrate_legacy_schedule_payload(payload)
st, dst, path = validate_schedule_fields(
schedule_type=str(migrated.get("schedule_type") or SCHEDULE_TYPE_DATA_PIPELINE),
data_source_type=migrated.get("data_source_type"),
platform_api_path=migrated.get("platform_api_path"),
)
return {
"schedule_type": st,
"data_source_type": dst,
"platform_api_path": path,
}
@@ -10,11 +10,11 @@ from flask import current_app
from app import db
from app.models import ScheduleRun, ScheduleTask, User
from app.services.schedule import normalize_platform_api_path, resolve_schedule_executor, resolve_schedule_header
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id
from app.services.schedule.excel_service import export_schedule_result_excel
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
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.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
_worker_started = False
@@ -165,22 +165,36 @@ def create_task(
wait_seconds: int,
dify_agent_id: int | None,
platform_api_path: str | None,
data_source_type: str | None,
notify_user_ids_json: list[int] | None,
notify_enabled: bool,
enabled: bool,
kb_sync_enabled: bool = False,
kb_group_id: int | None = None,
actor_id: int | None,
commit: bool = True,
) -> ScheduleTask:
from app.services.schedule.schedule_contract import apply_schedule_contract_to_payload
cron_expr = normalize_cron_expr(cron_expr)
contract = apply_schedule_contract_to_payload({
'schedule_type': schedule_type,
'data_source_type': data_source_type,
'platform_api_path': platform_api_path,
})
task = ScheduleTask(
schedule_no=_generate_schedule_no(),
name=name,
schedule_type="platform_app",
schedule_type=contract['schedule_type'],
owner_user_id=owner_user_id,
cron_expr=cron_expr,
schedule_timezone=normalize_schedule_timezone(schedule_timezone),
wait_seconds=max(0, int(wait_seconds or 0)),
dify_agent_id=dify_agent_id,
platform_api_path=normalize_platform_api_path(platform_api_path) or None,
platform_api_path=contract['platform_api_path'],
data_source_type=contract['data_source_type'],
kb_sync_enabled=bool(kb_sync_enabled),
kb_group_id=kb_group_id,
notify_user_ids_json=notify_user_ids_json or [],
notify_enabled=bool(notify_enabled),
enabled=bool(enabled),
@@ -192,11 +206,22 @@ def create_task(
if task.next_run_at is None:
task.enabled = False
db.session.add(task)
db.session.commit()
if commit:
db.session.commit()
else:
db.session.flush()
return task
def update_task(task: ScheduleTask, *, payload: dict[str, Any], actor_id: int | None) -> ScheduleTask:
def update_task(
task: ScheduleTask,
*,
payload: dict[str, Any],
actor_id: int | None,
commit: bool = True,
) -> ScheduleTask:
from app.services.schedule.schedule_contract import apply_schedule_contract_to_payload
for key in [
"name",
"owner_user_id",
@@ -215,8 +240,6 @@ def update_task(task: ScheduleTask, *, payload: dict[str, Any], actor_id: int |
else:
value = payload[key]
setattr(task, key, value)
if "platform_api_path" in payload:
task.platform_api_path = normalize_platform_api_path(payload.get("platform_api_path")) or None
if "notify_user_ids_json" in payload and isinstance(payload.get("notify_user_ids_json"), list):
task.notify_user_ids_json = payload.get("notify_user_ids_json")
if "kb_sync_enabled" in payload:
@@ -225,12 +248,15 @@ def update_task(task: ScheduleTask, *, payload: dict[str, Any], actor_id: int |
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 not normalize_platform_api_path(task.platform_api_path):
dst = str(getattr(task, "data_source_type", None) or "database")
if dst != "faq_hot_aggregate":
raise ValueError("platform_api_path is required for platform_app")
task.platform_api_path = "faq-aggregate-hot"
task.schedule_type = "platform_app"
if any(k in payload for k in ("schedule_type", "data_source_type", "platform_api_path")):
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),
"platform_api_path": payload.get("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 task.enabled and task.cron_expr:
task.schedule_timezone = normalize_schedule_timezone(getattr(task, "schedule_timezone", None))
@@ -239,7 +265,8 @@ def update_task(task: ScheduleTask, *, payload: dict[str, Any], actor_id: int |
task.next_run_at = None
task.updated_by = actor_id
db.session.commit()
if commit:
db.session.commit()
return task
@@ -3,7 +3,7 @@ backend/app/services/schedule/shipping_inventory_rpa_job.py
用途:排程触发货代库存 RPA 批量导出(各 Warehouse 一次登录多导出)。
依赖:inventory_sources、rpa.write_inventory_export_batch_trigger、ScheduleTask/ScheduleRun。
逻辑:data_source_type=shipping_inventory_rpa 时由 resolve_schedule_executor 调用。
逻辑:platform_api_path=shipping-inventory-rpa 时由 job_registry 调用。
"""
from __future__ import annotations
+25 -8
View File
@@ -159,16 +159,27 @@ def _config_from_model(cfg_model: Any) -> ScheduleSqlConfig:
def get_schedule_sql_config(name: str) -> ScheduleSqlConfig | None:
"""
按 task id 或 platform job key 精确查找 ScheduleSqlConfig。
核心逻辑:数字 name 走主键;否则归一化后与 platform_api_path 精确匹配(禁止模糊 ilike)。
Args:
name: 数字 task id,或 platform_api_path job key。
Returns:
找到则返回配置,否则 None。
"""
from app import db
from app.models import ScheduleTask, ScheduleTaskConfig
from app.services.schedule.schedule_contract import normalize_job_key
key = name.strip().lower()
raw = name.strip()
job_key = normalize_job_key(raw)
task = None
if key.isdigit():
task = db.session.get(ScheduleTask, int(key))
if not task:
if raw.isdigit():
task = db.session.get(ScheduleTask, int(raw))
if not task and job_key:
task = ScheduleTask.query.filter(
ScheduleTask.platform_api_path.ilike(f"%{key}%")
ScheduleTask.platform_api_path == job_key,
ScheduleTask.schedule_type == 'platform_job',
).first()
if not task:
return None
@@ -201,7 +212,12 @@ def get_all_schedule_sql_configs() -> dict[str, ScheduleSqlConfig]:
return results
def upsert_schedule_task_config(task_id: int, data: dict[str, Any]) -> ScheduleSqlConfig:
def upsert_schedule_task_config(
task_id: int,
data: dict[str, Any],
*,
commit: bool = True,
) -> ScheduleSqlConfig:
from app import db
from app.models import ScheduleTask, ScheduleTaskConfig
@@ -238,6 +254,7 @@ def upsert_schedule_task_config(task_id: int, data: dict[str, Any]) -> ScheduleS
elif k == "dify_system_prompt":
setattr(cfg_model, k, str(v) if v is not None else None)
db.session.commit()
db.session.refresh(cfg_model)
if commit:
db.session.commit()
db.session.refresh(cfg_model)
return _config_from_model(cfg_model)