Files
syops/backend/app/services/schedule/job_params.py
T

247 lines
9.8 KiB
Python
Raw 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/job_params.py
用途:平台任务 job_params 统一校验与契约归一化(保存排程、切换任务、导入、执行前共用)。
依赖:job_registry(读取 params_schema/defaults)、job_options(select 选项范围校验)、croniter(cron 校验)。
逻辑:scheduler_service.create_task/update_task 为唯一写入前归一化入口(API/import 只传原始值);
job_registry.run_platform_job 执行前调用 validate_task_params(check_options=False)。
"""
from __future__ import annotations
import json
from datetime import datetime
from typing import Any
# 高级参数逃生舱:折叠 JSON 区域的键,不做 schema 声明校验(兼容历史/特殊任务)
ADVANCED_PARAMS_KEY = "_advanced"
_SUPPORTED_TYPES = frozenset({
"text", "textarea", "number", "boolean", "select", "multi_select",
"date", "datetime", "cron", "json", "info",
})
class JobParamsValidationError(ValueError):
"""job_params 不满足注册表 params_schema。"""
def _validate_scalar(field: dict[str, Any], value: Any) -> Any:
"""
按字段 type 校验并归一化单个值。
核心逻辑:类型不符直接抛错,不做隐式转换(str "1" 不会转 number),
仅 number 允许 int/float 互通。
Raises:
JobParamsValidationError: 类型或格式非法
"""
key = field.get("key")
ftype = str(field.get("type") or "text")
if ftype in ("text", "textarea"):
if not isinstance(value, str):
raise JobParamsValidationError(f"param '{key}' must be a string")
return value
if ftype == "number":
if isinstance(value, bool) or not isinstance(value, (int, float)):
raise JobParamsValidationError(f"param '{key}' must be a number")
return value
if ftype == "boolean":
if not isinstance(value, bool):
raise JobParamsValidationError(f"param '{key}' must be a boolean")
return value
if ftype == "select":
if not isinstance(value, (str, int)):
raise JobParamsValidationError(f"param '{key}' must be a string or integer option value")
return value
if ftype == "multi_select":
if not isinstance(value, list) or any(not isinstance(item, (str, int)) for item in value):
raise JobParamsValidationError(f"param '{key}' must be a list of option values")
return value
if ftype == "date":
if not isinstance(value, str):
raise JobParamsValidationError(f"param '{key}' must be a YYYY-MM-DD date string")
try:
datetime.strptime(value, "%Y-%m-%d")
except ValueError:
raise JobParamsValidationError(f"param '{key}' is not a valid date (YYYY-MM-DD)")
return value
if ftype == "datetime":
if not isinstance(value, str):
raise JobParamsValidationError(f"param '{key}' must be an ISO datetime string")
try:
datetime.fromisoformat(value)
except ValueError:
raise JobParamsValidationError(f"param '{key}' is not a valid ISO datetime")
return value
if ftype == "cron":
if not isinstance(value, str) or len(value.split()) != 5:
raise JobParamsValidationError(f"param '{key}' must be a 5-field cron expression")
try:
from croniter import croniter
if not croniter.is_valid(value):
raise JobParamsValidationError(f"param '{key}' is not a valid cron expression")
except ImportError:
pass
return value
if ftype == "json":
if isinstance(value, (dict, list)):
return value
if isinstance(value, str):
try:
return json.loads(value)
except json.JSONDecodeError:
raise JobParamsValidationError(f"param '{key}' is not valid JSON")
raise JobParamsValidationError(f"param '{key}' must be a JSON object/array")
raise JobParamsValidationError(f"param '{key}' has unsupported type '{ftype}'")
def _check_option_range(field: dict[str, Any], value: Any) -> None:
"""
校验 select/multi_select 值是否在 options_source 当前选项范围内。
Raises:
JobParamsValidationError: 值不在选项范围
"""
source = str(field.get("options_source") or "").strip()
if not source:
return
from app.services.schedule.job_options import list_job_options
allowed = {str(option["value"]) for option in list_job_options(source)}
values = value if isinstance(value, list) else [value]
invalid = [str(item) for item in values if str(item) not in allowed]
if invalid:
raise JobParamsValidationError(
f"param '{field.get('key')}' has values not in options of '{source}': {invalid}"
)
def validate_task_params(
task_type: str,
job_params: dict[str, Any] | None,
*,
check_options: bool = True,
) -> dict[str, Any]:
"""
按注册表 params_schema 校验平台任务参数并返回归一化结果。
【AI 触发时机】:保存排程(POST/PATCH /schedules)与执行平台任务前均须调用本函数。
核心逻辑:
[STEP 1] 查注册表拿 params_schema;未注册 key 抛错。
[STEP 2] 未声明字段默认拒绝(_advanced 例外:原样透传,供折叠 JSON 高级配置兜底)。
[STEP 3] 逐字段校验必填 + 类型 + 格式;缺省回填 field.default / defaults。
[STEP 4] check_options=True 时校验 select/multi_select 值在选项范围内。
Args:
task_type: platform job key(如 shipping-inventory-rpa)。
job_params: 前端提交或 task.job_params 存储的参数 dict;None 视为空。
check_options: 是否联动 options_source 校验取值范围;执行期建议 False(选项可能漂移)。
Returns:
归一化后的参数 dict(含默认值回填与 _advanced 透传)。
Raises:
JobParamsValidationError: 未注册任务、未声明字段、必填缺失或类型/格式/范围非法。
"""
from app.services.schedule.job_registry import get_platform_job
definition = get_platform_job(task_type)
if not definition:
raise JobParamsValidationError(f"Unknown platform job: {task_type}")
raw = dict(job_params or {})
if not isinstance(raw, dict):
raise JobParamsValidationError("job_params must be a JSON object")
schema_fields = [f for f in definition.params_schema if f.get("type") != "info"]
declared_keys = {f.get("key") for f in schema_fields}
# [STEP 2] 未声明字段默认拒绝;_advanced 例外
advanced = raw.pop(ADVANCED_PARAMS_KEY, None)
if advanced is not None and not isinstance(advanced, dict):
raise JobParamsValidationError(f"'{ADVANCED_PARAMS_KEY}' must be a JSON object")
unknown = sorted(set(raw) - declared_keys)
if unknown:
raise JobParamsValidationError(f"unknown params for '{definition.key}': {unknown}")
# [STEP 3] 逐字段校验与默认值回填
result: dict[str, Any] = {}
for field in schema_fields:
key = field.get("key")
provided = key in raw
value = raw.get(key)
if value is None or (not provided):
default = field.get("default", definition.defaults.get(key))
result[key] = default
if field.get("required") and result[key] in (None, "", []):
raise JobParamsValidationError(f"param '{key}' is required")
continue
value = _validate_scalar(field, value)
if field.get("required") and value in ("", []):
raise JobParamsValidationError(f"param '{key}' is required")
# [STEP 4] 选项范围校验(仅保存期)
if check_options and field.get("type") in ("select", "multi_select") and value not in (None, []):
_check_option_range(field, value)
result[key] = value
if advanced:
result[ADVANCED_PARAMS_KEY] = advanced
return result
def normalize_job_params_for_contract(
schedule_type: str,
platform_api_path: str | None,
raw_job_params: Any = None,
*,
check_options: bool = True,
) -> dict[str, Any] | None:
"""
按排程契约归一化 job_params(保存 / 切换任务 / 导入共用)。
核心逻辑:
- 非 platform_job:禁止携带 job_params,返回 None。
- platform_job 有 params_schema:raw 为 None 时按 {} 校验并回填默认值。
- platform_job 无 params_schema:None → None;dict → 原样(空 dict 视为 None)。
Args:
schedule_type: data_pipeline | platform_job
platform_api_path: 平台任务 key
raw_job_params: 请求体或既有参数;切换任务且未传时可传 None 触发默认值重置
check_options: 是否校验 options_source 取值范围
Returns:
归一化后的 job_params,或 None(无 schema / 非平台任务)
Raises:
JobParamsValidationError: 类型非法、未知字段、schema/选项校验失败
"""
from app.services.schedule.schedule_contract import SCHEDULE_TYPE_PLATFORM_JOB
if schedule_type != SCHEDULE_TYPE_PLATFORM_JOB:
if raw_job_params is not None:
raise JobParamsValidationError("job_params is only supported for platform_job schedules")
return None
from app.services.schedule.job_registry import get_platform_job
definition = get_platform_job(platform_api_path)
has_schema = bool(definition and definition.params_schema)
if raw_job_params is None:
if not has_schema:
return None
raw_job_params = {}
if not isinstance(raw_job_params, dict):
raise JobParamsValidationError("job_params must be a JSON object")
if not has_schema:
return raw_job_params or None
return validate_task_params(
str(platform_api_path or ""),
raw_job_params,
check_options=check_options,
)