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

+143 -103
View File
@@ -1,126 +1,109 @@
"""
backend/app/api/internal_jobs.py
用途:平台内置 Job 内部 API(POST /api/internal/jobs/<job_key>)。
依赖:job_registry、schedule_contract、scheduler_service。
逻辑:标准化 job key → registry 查 handler → 解析 ScheduleRun → 返回统一结构。
"""
from __future__ import annotations
import traceback
from datetime import datetime
from flask import Blueprint, jsonify, request
from app import db
from app.core.errors import AppError, NotFoundError, ValidationError
from app.models import ScheduleRun, ScheduleTask
from app.services.schedule import _run_generic_check_job
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
from app.core.errors import (
AppError,
ConflictError,
ForbiddenError,
NotFoundError,
ServiceUnavailableError,
UnauthorizedError,
ValidationError,
raise_for_status,
)
from app.services.schedule.job_registry import get_platform_job, run_platform_job
from app.services.schedule.schedule_contract import normalize_job_key
from app.services.schedule.scheduler_service import _generate_run_no
internal_jobs_bp = Blueprint('internal_jobs', __name__)
@internal_jobs_bp.route('/<name>', methods=['POST'])
def run_internal_job(name: str):
key = name.strip().lower()
data = request.get_json(silent=True) or {}
if key in {'fixed-assets-snapshot', 'fixed_assets_snapshot', 'fixedassets'}:
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
summary = FixedAssetsSnapshotService.sync_once(reason='internal_api', attempt=1)
row_count = int(summary.get('row_count') or 0)
return jsonify({
'summary': {
'total_count': row_count,
'success_count': row_count,
'failed_count': 0,
'skipped_count': 0,
},
'details': [summary],
'errors': [],
'step_logs': [
{
'step': 'fixed_assets_snapshot_sync',
'status': 'success',
'detail': {
'version': summary.get('current_version'),
'row_count': row_count,
},
}
],
})
if key in {'faq-aggregate-hot', 'faq_hot_aggregate', 'faq-hot-aggregate'}:
from app.services.hot_faq_aggregator import HotFaqAggregator
schedule_task_id = data.get('schedule_task_id')
agent_id = data.get('agent_id')
if schedule_task_id:
task = db.session.get(ScheduleTask, int(schedule_task_id))
if task and task.dify_agent_id:
agent_id = task.dify_agent_id
result = HotFaqAggregator.aggregate_hot_faq_candidates(
agent_id=int(agent_id) if agent_id else None,
dry_run=False,
def _assert_task_matches_job_key(task: ScheduleTask, job_key: str) -> None:
"""
校验 task 与 URL job key 一致,防止 schedule_task_id 指向错误 handler。
Raises:
ValidationError: 非 platform_job 或 platform_api_path 不匹配
"""
if task.schedule_type != 'platform_job':
raise ValidationError(f"schedule_task_id {task.id} is not a platform_job task")
task_key = normalize_job_key(task.platform_api_path)
if task_key != job_key:
raise ValidationError(
f"schedule_task_id {task.id} platform_api_path '{task.platform_api_path}' "
f"does not match job key '{job_key}'"
)
if not result.get('enabled'):
message = str(result.get('message') or 'FAQ_HOT_ENABLED is false')
return jsonify({
'summary': {'total_count': 0, 'success_count': 0, 'failed_count': 0, 'skipped_count': 1},
'details': [],
'errors': [message],
'step_logs': [{'step': 'faq_hot_aggregate', 'status': 'skipped', 'detail': {'message': message}}],
})
promoted = int(result.get('promoted_count') or 0)
skipped = int(result.get('skipped_count') or 0)
total = max(promoted + skipped, 1)
return jsonify({
'summary': {
'total_count': total,
'success_count': promoted,
'failed_count': 0,
'skipped_count': skipped,
},
'details': (result.get('candidates') or [])[:20],
'errors': [],
'step_logs': [{
'step': 'faq_hot_aggregate',
'status': 'success',
'detail': {
'scanned_logs': result.get('scanned_logs'),
'promoted_count': promoted,
'skipped_count': skipped,
},
}],
})
run_no = str(data.get('run_no') or '').strip()
def _resolve_schedule_task_and_run(job_key: str, data: dict) -> tuple[ScheduleTask, ScheduleRun]:
"""
解析或创建 ScheduleTask / ScheduleRun。
核心逻辑:优先 schedule_task_id(须匹配 job key);否则按 platform_api_path 匹配 job key。
run_no 查询限定 schedule_task_id,避免跨任务写入。
"""
schedule_task_id = data.get('schedule_task_id')
task = None
if schedule_task_id:
task = db.session.get(ScheduleTask, int(schedule_task_id))
if not task and key.isdigit():
task = db.session.get(ScheduleTask, int(key))
task = db.session.get(ScheduleTask, int(schedule_task_id)) if schedule_task_id else None
if task:
_assert_task_matches_job_key(task, job_key)
else:
task = (
ScheduleTask.query.filter(
ScheduleTask.platform_api_path == job_key,
ScheduleTask.schedule_type == 'platform_job',
)
.order_by(ScheduleTask.id.desc())
.first()
)
if not task:
task = ScheduleTask.query.filter(ScheduleTask.platform_api_path.ilike(f'%{key}%')).first()
if not task:
raise NotFoundError(f"No schedule task found for '{name}'")
raise NotFoundError(f"No schedule task found for platform job '{job_key}'")
run_no = str(data.get('run_no') or '').strip()
run = None
if run_no:
run = ScheduleRun.query.filter_by(run_no=run_no).first()
run = ScheduleRun.query.filter_by(run_no=run_no, schedule_task_id=task.id).first()
if not run:
foreign = ScheduleRun.query.filter_by(run_no=run_no).first()
if foreign and foreign.schedule_task_id != task.id:
raise ValidationError(
f"run_no '{run_no}' belongs to schedule_task_id {foreign.schedule_task_id}, "
f"not {task.id}"
)
if not run:
from app.services.schedule.scheduler_service import _generate_run_no
run = ScheduleRun(run_no=run_no or _generate_run_no(), schedule_task_id=task.id, trigger_type='api', started_at=datetime.utcnow(), status='running')
run = ScheduleRun(
run_no=run_no or _generate_run_no(),
schedule_task_id=task.id,
trigger_type='api',
started_at=datetime.utcnow(),
status='running',
)
db.session.add(run)
db.session.commit()
if not run.dify_execution_snapshot:
capture_dify_execution_snapshot(run, task)
db.session.commit()
try:
total_count, success_count, failed_count, skipped_count, details, errors, step_logs = _run_generic_check_job(task, run)
except Exception as exc:
run.status = 'failed'
run.error_message = str(exc)
run.finished_at = datetime.utcnow()
db.session.commit()
raise AppError(code='SYSTEM.HTTP_ERROR', message=str(exc), http_status=500, details={'traceback': traceback.format_exc(), 'summary': {'total_count': 0, 'success_count': 0, 'failed_count': 0, 'skipped_count': 0}})
run.status = 'success' if failed_count == 0 else 'failed' if success_count == 0 else 'partial_failed'
return task, run
def _finalize_run(
run: ScheduleRun,
*,
total_count: int,
success_count: int,
failed_count: int,
skipped_count: int,
step_logs: list | None,
) -> None:
"""写入 run 汇总字段并 commit。"""
run.status = (
'success' if failed_count == 0
else 'failed' if success_count == 0
else 'partial_failed'
)
run.total_count = total_count
run.success_count = success_count
run.failed_count = failed_count
@@ -130,4 +113,61 @@ def run_internal_job(name: str):
run.duration_ms = int((run.finished_at - run.started_at).total_seconds() * 1000)
run.step_logs = step_logs if step_logs else None
db.session.commit()
return jsonify({'summary': {'total_count': total_count, 'success_count': success_count, 'failed_count': failed_count, 'skipped_count': skipped_count}, 'details': details, 'errors': errors, 'step_logs': step_logs})
@internal_jobs_bp.route('/<name>', methods=['POST'])
def run_internal_job(name: str):
"""
执行已注册平台 Job。
核心逻辑:标准化 job key → registry 查 handler → 解析 ScheduleRun → 返回统一结构。
"""
key = normalize_job_key(name)
data = request.get_json(silent=True) or {}
if not get_platform_job(key):
raise NotFoundError(f"Unknown platform job: {name}")
task, run = _resolve_schedule_task_and_run(key, data)
try:
total_count, success_count, failed_count, skipped_count, details, errors, step_logs = run_platform_job(
key, task, run, data,
)
except Exception as exc:
run.status = 'failed'
run.error_message = str(exc)
run.finished_at = datetime.utcnow()
db.session.commit()
raise AppError(
code='SYSTEM.HTTP_ERROR',
message=str(exc),
http_status=500,
details={
'traceback': traceback.format_exc(),
'summary': {
'total_count': 0,
'success_count': 0,
'failed_count': 0,
'skipped_count': 0,
},
},
)
_finalize_run(
run,
total_count=total_count,
success_count=success_count,
failed_count=failed_count,
skipped_count=skipped_count,
step_logs=step_logs,
)
return jsonify({
'summary': {
'total_count': total_count,
'success_count': success_count,
'failed_count': failed_count,
'skipped_count': skipped_count,
},
'details': details,
'errors': errors,
'step_logs': step_logs,
})
+36 -7
View File
@@ -2,8 +2,8 @@
backend/app/api/schedule/config.py
用途:排程任务 SQL/数据源配置 API 与测试接口(薄路由层)。
依赖:schedule.blueprint、schedule.common、services/schedule/*。
逻辑:/schedule-config/* 路由。
依赖:schedule.blueprint、schedule.common、schedule_contract、services/schedule/*。
逻辑:/schedule-config/* 路由;配置更新仅允许 data_pipeline 任务修改 data_source_type。
"""
from __future__ import annotations
@@ -16,6 +16,11 @@ from app.core.auth.jwt import get_current_user
from app.core.decorators import require_admin
from app.core.errors import NotFoundError, ValidationError
from app.models import ScheduleTask, ScheduleTaskConfig
from app.services.schedule.schedule_contract import (
SCHEDULE_TYPE_DATA_PIPELINE,
apply_schedule_contract_to_payload,
platform_job_allows_config,
)
from app.services.schedule.sql_config import upsert_schedule_task_config
from app.services.schedule.sql_preview_service import preview_fetch_sql
from app.services.schedule.test_run_service import execute_test_run
@@ -37,22 +42,46 @@ def get_schedule_task_config(task_id: int):
@schedule_admin_bp.route('/schedule-config/<int:task_id>', methods=['PUT'])
@require_admin
def update_schedule_task_config(task_id: int):
"""更新排程 data_source_type 与 ScheduleTaskConfig。"""
"""
更新排程 data_source_type 与 ScheduleTaskConfig。
核心逻辑:仅 data_pipeline 允许改 data_source_type;platform_job 禁止经此接口绕过契约。
"""
task = db.session.get(ScheduleTask, task_id)
if not task:
raise NotFoundError('Not found')
data = request.get_json(silent=True) or {}
try:
if 'data_source_type' in data:
task.data_source_type = str(data['data_source_type'])
db.session.commit()
if task.schedule_type != SCHEDULE_TYPE_DATA_PIPELINE:
if 'data_source_type' in data:
raise ValidationError(
'data_source_type can only be updated for data_pipeline schedules; '
'use schedule task PATCH for platform_job'
)
elif 'data_source_type' in data:
contract = apply_schedule_contract_to_payload({
'schedule_type': task.schedule_type,
'data_source_type': data.get('data_source_type'),
'platform_api_path': task.platform_api_path,
})
task.data_source_type = contract['data_source_type']
config_data = data.get('config', data)
upsert_schedule_task_config(task_id, config_data)
if isinstance(config_data, dict) and config_data:
# platform_job 仅白名单任务(如 shipping-inventory-rpa)允许写 ScheduleTaskConfig
if task.schedule_type != SCHEDULE_TYPE_DATA_PIPELINE and not platform_job_allows_config(task.platform_api_path):
raise ValidationError(
f"platform_job '{task.platform_api_path}' does not accept ScheduleTaskConfig"
)
upsert_schedule_task_config(task_id, config_data, commit=False)
db.session.commit()
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
return jsonify({
'data_source_type': task.data_source_type,
'config': serialize_task_config(cfg_model) if cfg_model else None,
})
except ValidationError:
db.session.rollback()
raise
except Exception as exc:
db.session.rollback()
raise ValidationError(str(exc))
+107 -45
View File
@@ -17,10 +17,14 @@ from app.api.schedule.blueprint import schedule_admin_bp
from app.api.schedule.common import serialize_task_for_export
from app.core.auth.jwt import get_current_user
from app.core.decorators import require_admin
from app.core.errors import NotFoundError
from app.core.errors import NotFoundError, ValidationError
from app.models import ScheduleRun, ScheduleTask, ScheduleTaskConfig
from app.services.schedule.query_service import list_tasks, serialize_task
from app.services.schedule.import_service import import_schedules_from_payload
from app.services.schedule.schedule_contract import (
apply_schedule_contract_to_payload,
assert_schedule_config_writable,
)
from app.services.schedule.scheduler_service import create_task, update_task
from app.services.schedule.sql_config import upsert_schedule_task_config
@@ -32,6 +36,23 @@ def get_schedules():
return jsonify(list_tasks())
@schedule_admin_bp.route('/schedule/platform-jobs', methods=['GET'])
@require_admin
def get_platform_jobs():
"""返回 Job Registry 已注册平台任务列表,供前端下拉动态加载。"""
from app.services.schedule.job_registry import list_platform_jobs
return jsonify([
{
'key': job.key,
'label_key': job.label_key or None,
'label': job.label,
'description': job.description,
}
for job in list_platform_jobs()
])
@schedule_admin_bp.route('/schedules/<int:task_id>/export', methods=['GET'])
@require_admin
def export_schedule(task_id: int):
@@ -73,41 +94,59 @@ def post_schedule():
"""创建排程任务。"""
data = request.get_json(silent=True) or {}
user = get_current_user()
data_source_type = str(data.get('data_source_type') or 'database')
task = create_task(
name=str(data.get('name') or '').strip(),
schedule_type='platform_app',
owner_user_id=int(data.get('owner_user_id')),
cron_expr=str(data.get('cron_expr') or '').strip(),
schedule_timezone=data.get('schedule_timezone'),
wait_seconds=int(data.get('wait_seconds') or 0),
dify_agent_id=int(data.get('dify_agent_id')) if data.get('dify_agent_id') is not None else None,
platform_api_path=str(data.get('platform_api_path') or '').strip() or None,
notify_user_ids_json=data.get('notify_user_ids_json')
if isinstance(data.get('notify_user_ids_json'), list)
else [],
notify_enabled=bool(data.get('notify_enabled', True)),
enabled=bool(data.get('enabled', True)),
actor_id=getattr(user, 'id', None),
)
task.data_source_type = data_source_type
task.kb_sync_enabled = bool(data.get('kb_sync_enabled', False))
raw_kb_group_id = data.get('kb_group_id')
task.kb_group_id = int(raw_kb_group_id) if raw_kb_group_id not in (None, '', 0, '0') else None
if data_source_type == 'faq_hot_aggregate':
task.platform_api_path = 'faq-aggregate-hot'
else:
task.platform_api_path = f'/{task.id}'
db.session.commit()
db.session.refresh(task)
schedule_type = str(data.get('schedule_type') or 'data_pipeline')
data_source_type = data.get('data_source_type')
platform_api_path = data.get('platform_api_path')
config_data = data.get('config')
if config_data and data_source_type != 'faq_hot_aggregate':
upsert_schedule_task_config(task.id, config_data)
if not task.dify_agent_id:
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task.id).first()
if cfg_model and cfg_model.dify_system_prompt:
cfg_model.dify_system_prompt = None
db.session.commit()
if config_data is not None and not isinstance(config_data, dict):
raise ValidationError('config must be a JSON object')
if schedule_type.strip().lower() == 'data_pipeline' and data_source_type in (None, ''):
data_source_type = 'database'
try:
contract = apply_schedule_contract_to_payload({
'schedule_type': schedule_type,
'data_source_type': data_source_type,
'platform_api_path': platform_api_path,
})
assert_schedule_config_writable(
schedule_type=contract['schedule_type'],
platform_api_path=contract['platform_api_path'],
config=config_data,
)
task = create_task(
name=str(data.get('name') or '').strip(),
schedule_type=schedule_type,
owner_user_id=int(data.get('owner_user_id')),
cron_expr=str(data.get('cron_expr') or '').strip(),
schedule_timezone=data.get('schedule_timezone'),
wait_seconds=int(data.get('wait_seconds') or 0),
dify_agent_id=int(data.get('dify_agent_id')) if data.get('dify_agent_id') is not None else None,
platform_api_path=str(platform_api_path).strip() if platform_api_path else None,
data_source_type=str(data_source_type) if data_source_type is not None else None,
notify_user_ids_json=data.get('notify_user_ids_json')
if isinstance(data.get('notify_user_ids_json'), list)
else [],
notify_enabled=bool(data.get('notify_enabled', True)),
enabled=bool(data.get('enabled', True)),
kb_sync_enabled=bool(data.get('kb_sync_enabled', False)),
kb_group_id=int(data.get('kb_group_id')) if data.get('kb_group_id') not in (None, '', 0, '0') else None,
actor_id=getattr(user, 'id', None),
commit=not config_data,
)
except ValueError as exc:
raise ValidationError(str(exc))
if config_data:
try:
upsert_schedule_task_config(task.id, config_data, commit=False)
if not task.dify_agent_id:
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task.id).first()
if cfg_model and cfg_model.dify_system_prompt:
cfg_model.dify_system_prompt = None
db.session.commit()
except Exception:
db.session.rollback()
raise
db.session.refresh(task)
return jsonify(serialize_task(task)), 201
@@ -130,18 +169,41 @@ def patch_schedule(task_id: int):
raise NotFoundError('Not found')
data = request.get_json(silent=True) or {}
user = get_current_user()
if 'data_source_type' in data:
task.data_source_type = str(data['data_source_type'])
db.session.commit()
config_data = data.get('config')
if config_data:
upsert_schedule_task_config(task_id, config_data)
task = update_task(task, payload=data, actor_id=getattr(user, 'id', None))
if not task.dify_agent_id:
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
if cfg_model and cfg_model.dify_system_prompt:
cfg_model.dify_system_prompt = None
if config_data is not None and not isinstance(config_data, dict):
raise ValidationError('config must be a JSON object')
try:
# [STEP 1] 先校验契约与 config 写入权限,避免 update_task 已提交后 config 被拒产生半更新
contract = apply_schedule_contract_to_payload({
'schedule_type': data.get('schedule_type', task.schedule_type),
'data_source_type': data.get('data_source_type', task.data_source_type),
'platform_api_path': data.get('platform_api_path', task.platform_api_path),
})
assert_schedule_config_writable(
schedule_type=contract['schedule_type'],
platform_api_path=contract['platform_api_path'],
config=config_data,
)
task = update_task(
task,
payload=data,
actor_id=getattr(user, 'id', None),
commit=not config_data,
)
if config_data:
upsert_schedule_task_config(task_id, config_data, commit=False)
if not task.dify_agent_id:
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
if cfg_model and cfg_model.dify_system_prompt:
cfg_model.dify_system_prompt = None
if config_data:
db.session.commit()
except ValueError as exc:
db.session.rollback()
raise ValidationError(str(exc))
except Exception:
db.session.rollback()
raise
return jsonify(serialize_task(task))
+2 -2
View File
@@ -25,14 +25,14 @@ class ScheduleTask(Base):
id: Mapped[int] = mapped_column(primary_key=True)
schedule_no: Mapped[str] = mapped_column(String(64), unique=True, index=True)
name: Mapped[str] = mapped_column(String(128), index=True)
schedule_type: Mapped[str] = mapped_column(String(32), default='platform_app')
schedule_type: Mapped[str] = mapped_column(String(32), default='data_pipeline')
owner_user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), index=True)
cron_expr: Mapped[str] = mapped_column(String(64))
schedule_timezone: Mapped[str] = mapped_column(String(64), default='Asia/Shanghai', server_default=text("'Asia/Shanghai'"))
wait_seconds: Mapped[int] = mapped_column(Integer, default=0)
dify_agent_id: Mapped[Optional[int]] = mapped_column(ForeignKey('agents.id'), nullable=True, index=True)
platform_api_path: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
data_source_type: Mapped[str] = mapped_column(String(32), default='database')
data_source_type: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
kb_sync_enabled: Mapped[bool] = mapped_column(Boolean, default=False, server_default=text('false'))
kb_group_id: Mapped[Optional[int]] = mapped_column(ForeignKey('kb_groups.id'), nullable=True, index=True)
notify_user_ids_json: Mapped[Optional[list]] = mapped_column(JSON, default=[])
@@ -20,6 +20,7 @@ from app.services.agent_registry.catalog_loader import (
)
from app.services.agent_registry.catalog_validation import (
apply_catalog_capabilities,
catalog_progress_requires_schedule_task,
default_capabilities_copy,
normalize_handler_config,
validate_required_fields,
@@ -176,6 +177,8 @@ def validate_agent_payload(
bound_schedule_task_id = data.get('bound_schedule_task_id', getattr(agent, 'bound_schedule_task_id', None) if agent else None)
bound_schedule_task_id = _parse_bound_schedule_task_id(bound_schedule_task_id)
if not catalog_progress_requires_schedule_task(agent_code):
bound_schedule_task_id = None
capabilities = _parse_capabilities(data.get('capabilities', getattr(agent, 'capabilities', None) if agent else None))
capabilities = apply_catalog_capabilities(agent_code, capabilities)
@@ -12,6 +12,7 @@ from typing import Any
from app.services.agent_registry.catalog_loader import (
build_agent_type_catalog,
get_agent_type_default_capabilities,
get_default_capabilities,
get_platform_config,
get_tool_run_progress_defaults,
@@ -41,7 +42,9 @@ def build_agent_registry_schema() -> dict[str, Any]:
agent_types.append({
**item,
'required_fields': list(entry.get('required_fields') or []),
'default_capabilities': get_agent_type_default_capabilities(str(code or '')),
'forced_capabilities': dict(entry.get('forced_capabilities') or {}),
'progress_contract': deepcopy_schema(entry.get('progress_contract')),
'default_intent_routes': list(entry.get('default_intent_routes') or []),
})
@@ -20,6 +20,17 @@ from app.services.agent_registry.catalog_bindings import RUNTIME_HANDLER_BINDING
_MANIFEST_PATH = Path(__file__).resolve().parent / 'data' / 'catalog_manifest.yaml'
_PROGRESS_DATA_SOURCES = frozenset({
'schedule_run',
'domain_state',
'job_queue',
'external_callback',
})
_PROGRESS_TRANSPORTS = frozenset({'polling', 'sse', 'manual_refresh'})
_PROGRESS_BINDINGS = frozenset({'chat_log_run', 'conversation_context', 'domain_key'})
_PROGRESS_LAYOUTS = frozenset({'card', 'workspace', 'inline', 'drawer'})
_PROGRESS_VISUALIZATIONS = frozenset({'counter', 'stepper', 'timeline', 'percent', 'hybrid'})
def coerce_manifest_boolean(value: Any, *, context: str = 'manifest') -> bool:
"""
@@ -128,6 +139,24 @@ def get_default_capabilities() -> dict[str, bool]:
return result
def get_agent_type_default_capabilities(agent_code: str) -> dict[str, bool]:
"""
合并 platform 与 agent_types 段 default_capabilities。
核心逻辑:平台默认为基础,类型级 default_capabilities 覆盖同名字段。
"""
merged = dict(get_default_capabilities())
entry = get_catalog_entry(agent_code) or {}
type_defaults = entry.get('default_capabilities') or {}
if isinstance(type_defaults, dict):
for key, value in type_defaults.items():
merged[str(key)] = coerce_manifest_boolean(
value,
context=f'agent_types.{agent_code}.default_capabilities.{key}',
)
return merged
def get_tool_run_progress_defaults() -> dict[str, Any]:
"""task_progress 视图默认值(含 progress_type);布尔/整数字段经 coercion。"""
platform = get_platform_config()
@@ -151,6 +180,134 @@ def get_tool_run_progress_defaults() -> dict[str, Any]:
}
def _enum_value(
value: Any,
*,
allowed: frozenset[str],
context: str,
default: str | None = None,
) -> str | None:
text = str(value or '').strip()
if not text:
return default
if text not in allowed:
raise ValidationError(f'{context} 取值无效: {text}')
return text
def normalize_progress_contract(raw: Any, *, context: str = 'progress_contract') -> dict[str, Any] | None:
"""
归一化通用进度契约。
核心逻辑:catalog 只声明通用 source/update/binding/presentation 维度,
不以 agent_code 作为进度类型。
"""
if raw in (None, False):
return None
if not isinstance(raw, dict):
raise ValidationError(f'{context} 必须为 JSON 对象')
enabled = coerce_manifest_boolean(raw.get('enabled', True), context=f'{context}.enabled')
if not enabled:
return {'enabled': False}
data_source_raw = raw.get('data_source') if isinstance(raw.get('data_source'), dict) else {}
update_raw = raw.get('update') if isinstance(raw.get('update'), dict) else {}
binding_raw = raw.get('binding') if isinstance(raw.get('binding'), dict) else {}
presentation_raw = raw.get('presentation') if isinstance(raw.get('presentation'), dict) else {}
data_source_type = _enum_value(
data_source_raw.get('type'),
allowed=_PROGRESS_DATA_SOURCES,
context=f'{context}.data_source.type',
)
if not data_source_type:
raise ValidationError(f'{context}.data_source.type 必填')
transport = _enum_value(
update_raw.get('transport'),
allowed=_PROGRESS_TRANSPORTS,
context=f'{context}.update.transport',
default='polling',
)
binding_type = _enum_value(
binding_raw.get('type'),
allowed=_PROGRESS_BINDINGS,
context=f'{context}.binding.type',
default='chat_log_run',
)
layout = _enum_value(
presentation_raw.get('layout'),
allowed=_PROGRESS_LAYOUTS,
context=f'{context}.presentation.layout',
default='card',
)
visualization = _enum_value(
presentation_raw.get('visualization'),
allowed=_PROGRESS_VISUALIZATIONS,
context=f'{context}.presentation.visualization',
default='counter',
)
interval_raw = update_raw.get('interval_seconds')
interval_seconds = None
if interval_raw is not None:
try:
interval_seconds = max(1, min(int(interval_raw), 30))
except (TypeError, ValueError):
raise ValidationError(f'{context}.update.interval_seconds 必须为整数')
keys_raw = binding_raw.get('keys')
keys = [
str(item or '').strip()
for item in keys_raw
if str(item or '').strip()
] if isinstance(keys_raw, list) else []
contract: dict[str, Any] = {
'enabled': True,
'data_source': {
'type': data_source_type,
},
'update': {
'transport': transport,
},
'binding': {
'type': binding_type,
'requires_schedule_task': coerce_manifest_boolean(
binding_raw.get('requires_schedule_task', False),
context=f'{context}.binding.requires_schedule_task',
),
},
'presentation': {
'layout': layout,
'visualization': visualization,
},
}
domain = str(data_source_raw.get('domain') or '').strip()
if domain:
contract['data_source']['domain'] = domain
event = str(update_raw.get('event') or '').strip()
if event:
contract['update']['event'] = event
if interval_seconds is not None:
contract['update']['interval_seconds'] = interval_seconds
fallback = str(binding_raw.get('fallback') or '').strip()
if fallback:
contract['binding']['fallback'] = fallback
if keys:
contract['binding']['keys'] = keys
# [STEP 组合校验] manifest 配错时 fail-fast,避免运行时静默失效。
if transport == 'sse' and not event:
raise ValidationError(f'{context}.update.transport=sse 时 update.event 必填')
if data_source_type == 'schedule_run' and contract['binding']['requires_schedule_task'] is not True:
raise ValidationError(
f'{context}.data_source.type=schedule_run 时 binding.requires_schedule_task 必须为 true',
)
return contract
@lru_cache(maxsize=1)
def build_agent_type_catalog() -> dict[str, dict[str, Any]]:
"""
@@ -169,6 +326,14 @@ def build_agent_type_catalog() -> dict[str, dict[str, Any]]:
continue
merged = deepcopy(entry)
merged['runtime_handler'] = RUNTIME_HANDLER_BINDINGS.get(str(code)) or None
if isinstance(merged.get('default_capabilities'), dict):
merged['default_capabilities'] = {
str(cap_key): coerce_manifest_boolean(
cap_value,
context=f'agent_types.{code}.default_capabilities.{cap_key}',
)
for cap_key, cap_value in merged['default_capabilities'].items()
}
if isinstance(merged.get('forced_capabilities'), dict):
merged['forced_capabilities'] = {
str(cap_key): coerce_manifest_boolean(
@@ -177,6 +342,10 @@ def build_agent_type_catalog() -> dict[str, dict[str, Any]]:
)
for cap_key, cap_value in merged['forced_capabilities'].items()
}
merged['progress_contract'] = normalize_progress_contract(
merged.get('progress_contract'),
context=f'agent_types.{code}.progress_contract',
)
catalog[str(code)] = merged
return catalog
@@ -42,22 +42,37 @@ def apply_catalog_capabilities(agent_code: str, capabilities: dict[str, bool]) -
return merged
def catalog_progress_requires_schedule_task(agent_code: str) -> bool:
"""
判断 Catalog progress_contract 是否要求绑定排程任务。
核心逻辑:优先读 progress_contract.binding.requires_schedule_task;
兼容 required_fields 中的 bound_schedule_task_id 声明。
"""
entry = get_catalog_entry(agent_code) or {}
progress = entry.get('progress_contract') if isinstance(entry.get('progress_contract'), dict) else {}
if progress.get('enabled') is True:
binding = progress.get('binding') if isinstance(progress.get('binding'), dict) else {}
if binding.get('requires_schedule_task') is True:
return True
required = entry.get('required_fields') or []
return isinstance(required, list) and 'bound_schedule_task_id' in required
def validate_required_fields(
agent_code: str,
*,
bound_schedule_task_id: int | None = None,
) -> None:
"""
校验 Catalog 声明的 required_fields。
校验 Catalog 声明的 required_fields 与 progress_contract.binding。
Raises:
ValidationError: 必填列缺失。
"""
entry = get_catalog_entry(agent_code) or {}
required = entry.get('required_fields') or []
if not isinstance(required, list):
if not catalog_progress_requires_schedule_task(agent_code):
return
if 'bound_schedule_task_id' in required and not bound_schedule_task_id:
if not bound_schedule_task_id:
raise ValidationError(f'agent_code={agent_code} 时 bound_schedule_task_id 必填')
@@ -58,7 +58,30 @@ agent_types:
- ShippingTask
- ShippingTaskEvent
required_fields: []
forced_capabilities: {}
default_capabilities:
file_upload: true
task_progress: true
forced_capabilities:
file_upload: true
task_progress: true
human_confirm: true
progress_contract:
enabled: true
data_source:
type: domain_state
domain: shipping_notice
update:
transport: sse
event: shipping_ui_state
binding:
type: conversation_context
keys:
- batch_no
- task_no
requires_schedule_task: false
presentation:
layout: workspace
visualization: stepper
handler_config_schema: {}
file_check:
label: 文件检核
@@ -70,6 +93,20 @@ agent_types:
- bound_schedule_task_id
forced_capabilities:
task_progress: true
progress_contract:
enabled: true
data_source:
type: schedule_run
update:
transport: polling
interval_seconds: 2
binding:
type: chat_log_run
fallback: chat_log_id
requires_schedule_task: true
presentation:
layout: card
visualization: counter
handler_config_schema:
poll_interval_seconds:
type: integer
@@ -2,7 +2,7 @@
backend/app/services/agent_registry/handlers/file_check.py
用途:文件检核 Agent Handler — 聊天流 turn 注册与 Dify 进度绑定。
依赖:file_check_tools.chat_turn_registry、agent_registry.handlers.registry。
依赖:file_check_tools.chat_turn_registry、agent_registry.handlers.registry、resolver。
逻辑:DifyChatExecutor 经 resolve_handler_for_agent_code 调用 prepare_stream 注册 hxops_turn_id。
"""
@@ -12,7 +12,16 @@ import uuid
from app.services.agent_registry.handlers.base import AgentHandler, ChatStreamContext
from app.services.agent_registry.handlers.registry import register_handler
from app.services.agent_registry.resolver import agent_declares_task_progress
from app.services.agent_registry.resolver import resolve_progress_contract
def _uses_schedule_run_progress(agent) -> bool:
"""progress_contract 声明 schedule_run 数据源时才注册检核 turn。"""
contract = resolve_progress_contract(agent)
if not contract:
return False
data_source = contract.get('data_source') if isinstance(contract.get('data_source'), dict) else {}
return data_source.get('type') == 'schedule_run'
@register_handler('file_check')
@@ -20,12 +29,12 @@ class FileCheckHandler(AgentHandler):
"""
文件检核业务 Handler。
核心逻辑:capabilities.task_progress === true 时在 Dify 流开始前注册 hxops_turn_id,
供检核进度轮询绑定 chat_log;capabilities 本身仅控制前端是否展示进度 UI。
核心逻辑:progress_contract.data_source=schedule_run 时在 Dify 流开始前注册 hxops_turn_id,
供检核进度轮询绑定 chat_log;capabilities.task_progress 仅作能力门禁。
"""
def prepare_stream(self, ctx: ChatStreamContext) -> ChatStreamContext:
if not agent_declares_task_progress(ctx.agent):
if not _uses_schedule_run_progress(ctx.agent):
return ctx
turn_id = uuid.uuid4().hex
@@ -15,6 +15,22 @@ from flask import current_app
from app.services.agent_registry.handlers.base import AgentHandler, ChatStreamContext
from app.services.agent_registry.handlers.registry import register_handler
from app.services.agent_registry.resolver import resolve_progress_contract
def _uses_shipping_ui_state_progress(agent) -> bool:
"""progress_contract 声明 domain_state + shipping_ui_state SSE 时才下发 UI State。"""
contract = resolve_progress_contract(agent)
if not contract:
return False
data_source = contract.get('data_source') if isinstance(contract.get('data_source'), dict) else {}
update = contract.get('update') if isinstance(contract.get('update'), dict) else {}
return (
data_source.get('type') == 'domain_state'
and data_source.get('domain') == 'shipping_notice'
and update.get('transport') == 'sse'
and update.get('event') == 'shipping_ui_state'
)
@register_handler('shipping_notice')
@@ -31,6 +47,9 @@ class ShippingNoticeHandler(AgentHandler):
核心逻辑:优先显式 task_id,其次 batch 焦点任务;失败时记录日志并返回 None。
"""
if not _uses_shipping_ui_state_progress(ctx.agent):
return None
task_id = str(ctx.shipping_task_id or '').strip()
batch_no = str(ctx.shipping_batch_no or '').strip()
if not task_id and not batch_no:
@@ -287,6 +287,40 @@ def agent_declares_task_progress(agent) -> bool:
return resolve_capabilities(agent).get('task_progress') is True
def resolve_progress_contract(agent) -> dict[str, Any] | None:
"""
解析 Agent 通用进度契约。
核心逻辑:读 catalog 中的 progress_contract;task_progress 门禁同时合并
Catalog forced_capabilities,避免存量行 capabilities 缺失导致进度 UI 消失。
"""
entry = get_catalog_entry(resolve_agent_code(agent)) or {}
forced = entry.get('forced_capabilities') if isinstance(entry.get('forced_capabilities'), dict) else {}
task_progress_enabled = (
agent_declares_task_progress(agent)
or forced.get('task_progress') is True
)
if not task_progress_enabled:
return None
contract = entry.get('progress_contract')
if not isinstance(contract, dict) or contract.get('enabled') is not True:
return None
import copy
return copy.deepcopy(contract)
def agent_has_progress(agent) -> bool:
"""判断 Agent 是否有可用通用进度契约。"""
return resolve_progress_contract(agent) is not None
def agent_progress_requires_schedule_task(agent) -> bool:
"""判断 Agent 进度契约是否需要绑定 ScheduleTask。"""
contract = resolve_progress_contract(agent)
binding = contract.get('binding') if isinstance(contract, dict) else None
return isinstance(binding, dict) and binding.get('requires_schedule_task') is True
def is_file_check_runtime_ready(agent) -> bool:
"""
判断 file_check 对话入口是否已完整配置(可注入 task_id、绑定 chat_log.run_id)。
@@ -299,7 +333,7 @@ def is_file_check_runtime_ready(agent) -> bool:
Returns:
能力声明且 task_id 列已配置时返回 True。
"""
if not agent_declares_task_progress(agent):
if not agent_progress_requires_schedule_task(agent):
return False
from app.services.file_check_tools.task_resolver import resolve_schedule_task_id_from_agent
@@ -12,10 +12,10 @@ from typing import Any
from app.models import Agent
from app.services.agent_registry.resolver import (
normalize_capabilities,
resolve_agent_code,
resolve_capabilities,
resolve_conversation_mode,
resolve_progress_contract,
resolve_runtime_provider,
)
@@ -43,6 +43,7 @@ def serialize_registry_fields(agent: Agent | Any) -> dict[str, Any]:
handler_config = getattr(agent, 'handler_config', None)
intent_meta = resolve_agent_intent_metadata(agent)
tool_run_progress = build_tool_run_progress_view(agent)
progress_contract = resolve_progress_contract(agent)
return {
'agent_code': resolve_agent_code(agent),
'runtime_provider': resolve_runtime_provider(agent),
@@ -60,12 +61,13 @@ def serialize_registry_fields(agent: Agent | Any) -> dict[str, Any]:
'bound_schedule_task_id': getattr(agent, 'bound_schedule_task_id', None),
'handler_config': handler_config if isinstance(handler_config, dict) else None,
'tool_run_progress': tool_run_progress,
'progress_contract': progress_contract,
**intent_meta,
}
def serialize_agent_for_admin(agent: Agent) -> dict[str, Any]:
"""Agent ORM → 管理端列表/详情 JSON(API Key 仅返回脱敏值,明文不可读)。"""
"""Agent ORM → 管理端列表/详情 JSON(含 dify_api_key 供编辑表单密码框回填)。"""
registry = serialize_registry_fields(agent)
return {
'id': agent.id,
@@ -75,6 +77,7 @@ def serialize_agent_for_admin(agent: Agent) -> dict[str, Any]:
'is_active': agent.is_active,
'type': agent.type,
'dify_app_id': agent.dify_app_id,
'dify_api_key': agent.dify_api_key,
'dify_api_key_masked': mask_dify_api_key(agent.dify_api_key),
'api_base_url': agent.api_base_url,
'extra_config': agent.extra_config if isinstance(agent.extra_config, dict) else {},
@@ -123,13 +126,18 @@ def serialize_agent_for_user_detail(
def build_tool_run_progress_view(agent: Agent) -> dict[str, Any] | None:
"""
从 Registry 列构建前端 tool_run_progress 视图(迁移期兼容 extra 读者)。
从 Registry 列构建前端 tool_run_progress 视图(schedule_run 进度兼容层)。
核心逻辑:capabilities.task_progress 为 true 且 bound_schedule_task_id 已注册时返回配置 dict。
核心逻辑:progress_contract.data_source.type=schedule_run 且 bound_schedule_task_id
已注册时返回配置 dict;domain_state 等其它进度类型不走本视图。
"""
caps = resolve_capabilities(agent)
if not caps.get('task_progress'):
contract = resolve_progress_contract(agent)
if not contract:
return None
data_source = contract.get('data_source') if isinstance(contract.get('data_source'), dict) else {}
if data_source.get('type') != 'schedule_run':
return None
task_id = getattr(agent, 'bound_schedule_task_id', None)
try:
schedule_task_id = int(task_id)
@@ -143,11 +151,12 @@ def build_tool_run_progress_view(agent: Agent) -> dict[str, Any] | None:
from app.services.agent_registry.resolver import resolve_agent_code
defaults = get_tool_run_progress_defaults()
update = contract.get('update') if isinstance(contract.get('update'), dict) else {}
cfg: dict[str, Any] = {
'type': str(defaults.get('progress_type') or resolve_agent_code(agent) or 'file_check'),
'schedule_task_id': schedule_task_id,
}
cfg['poll_interval_seconds'] = defaults.get('poll_interval_seconds', 2)
cfg['poll_interval_seconds'] = update.get('interval_seconds') or defaults.get('poll_interval_seconds', 2)
cfg['lock_input_when_running'] = defaults.get('lock_input_when_running', True)
if isinstance(handler_config, dict):
if handler_config.get('poll_interval_seconds') is not None:
+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)
@@ -0,0 +1,135 @@
"""schedule_type platform_job split
Revision ID: b9c0d1e2f3a4
Revises: a8b9c0d1e2f3
Create Date: 2026-07-08
用途:激活 schedule_type 执行模式;data_source_type 仅 data_pipeline;platform_job 用 platform_api_path。
"""
from alembic import op
import sqlalchemy as sa
revision = 'b9c0d1e2f3a4'
down_revision = 'a8b9c0d1e2f3'
branch_labels = None
depends_on = None
def upgrade():
with op.batch_alter_table('schedule_tasks', schema=None) as batch_op:
batch_op.alter_column(
'data_source_type',
existing_type=sa.String(length=32),
nullable=True,
server_default=None,
)
batch_op.alter_column(
'schedule_type',
existing_type=sa.String(length=32),
server_default='data_pipeline',
)
op.execute("""
UPDATE schedule_tasks
SET schedule_type = 'platform_job',
platform_api_path = 'shipping-inventory-rpa',
data_source_type = NULL
WHERE data_source_type = 'shipping_inventory_rpa'
""")
op.execute("""
UPDATE schedule_tasks
SET schedule_type = 'platform_job',
platform_api_path = 'faq-aggregate-hot',
data_source_type = NULL
WHERE data_source_type = 'faq_hot_aggregate'
""")
op.execute("""
UPDATE schedule_tasks
SET schedule_type = 'platform_job',
data_source_type = NULL,
platform_api_path = LTRIM(RTRIM(REPLACE(REPLACE(platform_api_path, '/', ''), '\\', '')))
WHERE LTRIM(RTRIM(REPLACE(REPLACE(platform_api_path, '/', ''), '\\', ''))) IN (
'faq-aggregate-hot', 'fixed-assets-snapshot', 'shipping-inventory-rpa'
)
AND schedule_type IN ('platform_app', 'dify_app')
""")
# 兜底:历史 platform_api_path 可能存完整路径/URL(如 /api/internal/jobs/foo),
# 精确匹配失败时按包含关系归一到对应 job key。
op.execute("""
UPDATE schedule_tasks
SET schedule_type = 'platform_job',
platform_api_path = 'faq-aggregate-hot',
data_source_type = NULL
WHERE schedule_type IN ('platform_app', 'dify_app')
AND REPLACE(LOWER(platform_api_path), '_', '-') LIKE '%faq-aggregate-hot%'
""")
op.execute("""
UPDATE schedule_tasks
SET schedule_type = 'platform_job',
platform_api_path = 'shipping-inventory-rpa',
data_source_type = NULL
WHERE schedule_type IN ('platform_app', 'dify_app')
AND REPLACE(LOWER(platform_api_path), '_', '-') LIKE '%shipping-inventory-rpa%'
""")
op.execute("""
UPDATE schedule_tasks
SET schedule_type = 'platform_job',
platform_api_path = 'fixed-assets-snapshot',
data_source_type = NULL
WHERE schedule_type IN ('platform_app', 'dify_app')
AND REPLACE(LOWER(platform_api_path), '_', '-') LIKE '%fixed-assets-snapshot%'
""")
op.execute("""
UPDATE schedule_tasks
SET schedule_type = 'data_pipeline',
platform_api_path = NULL
WHERE schedule_type IN ('platform_app', 'dify_app')
AND data_source_type IN ('database', 'external_api')
""")
op.execute("""
UPDATE schedule_tasks
SET platform_api_path = TRIM(BOTH '/' FROM platform_api_path)
WHERE platform_api_path IS NOT NULL
AND platform_api_path LIKE '/%'
""")
def downgrade():
op.execute("""
UPDATE schedule_tasks
SET schedule_type = 'platform_app',
data_source_type = 'shipping_inventory_rpa',
platform_api_path = 'shipping-inventory-rpa'
WHERE schedule_type = 'platform_job'
AND platform_api_path = 'shipping-inventory-rpa'
""")
op.execute("""
UPDATE schedule_tasks
SET schedule_type = 'platform_app',
data_source_type = 'faq_hot_aggregate',
platform_api_path = 'faq-aggregate-hot'
WHERE schedule_type = 'platform_job'
AND platform_api_path = 'faq-aggregate-hot'
""")
# fixed-assets-snapshot 等其余 platform_job 统一回落旧语义(platform_app + database),
# 避免 data_source_type 改回 NOT NULL 后残留 NULL 行导致约束失败。
op.execute("""
UPDATE schedule_tasks
SET schedule_type = 'platform_app',
data_source_type = 'database'
WHERE schedule_type = 'platform_job'
AND (data_source_type IS NULL OR data_source_type = '')
""")
with op.batch_alter_table('schedule_tasks', schema=None) as batch_op:
batch_op.alter_column(
'data_source_type',
existing_type=sa.String(length=32),
nullable=False,
server_default='database',
)
batch_op.alter_column(
'schedule_type',
existing_type=sa.String(length=32),
server_default='platform_app',
)
+1 -1
View File
@@ -27,7 +27,7 @@ def test_agent_lifecycle(client, admin_headers):
assert len(agents) == 1
assert agents[0]['name'] == "Test Agent"
assert agents[0]['description'] == "Initial Description"
assert 'dify_api_key' not in agents[0]
assert agents[0]['dify_api_key'] == "key-123"
assert agents[0]['dify_api_key_masked']
# 3. Update Agent
+1 -1
View File
@@ -89,7 +89,7 @@ def test_agent_crud(client):
agents = parse_api_data(res.get_json())
assert len(agents) == 1
assert agents[0]['name'] == 'Test Agent'
assert 'dify_api_key' not in agents[0]
assert agents[0]['dify_api_key'] == 'sk-test-key'
# Update
res = client.put(f'/api/admin/agents/{agent_id}', json={
@@ -133,6 +133,19 @@ def test_validate_omitted_handler_config_preserves_existing(app):
assert normalized['handler_config']['intent_routes'] == ['text2sql']
def test_validate_shipping_notice_clears_bound_schedule_task_id():
normalized = validate_agent_payload({
'name': 'Shipping Bot',
'agent_code': 'shipping_notice',
'runtime_provider': 'hybrid',
'conversation_mode': 'task_chat',
'dify_app_id': 'app-ship',
'bound_schedule_task_id': 42,
'capabilities': {'task_progress': True},
})
assert normalized['bound_schedule_task_id'] is None
def test_strip_migrated_extra_registry_keys_preserves_training(app):
with app.app_context():
agent = Agent(
@@ -23,12 +23,26 @@ def test_build_agent_registry_schema_includes_platform_enums():
def test_build_agent_registry_schema_agent_types_include_validation_rules():
"""agent_types 每条应含 required_fields 与 forced_capabilities。"""
"""agent_types 每条应含 required_fields、default_capabilities、forced_capabilities 与 progress_contract。"""
schema = build_agent_registry_schema()
by_code = {item['agent_code']: item for item in schema['agent_types']}
assert by_code['file_check']['required_fields'] == ['bound_schedule_task_id']
assert by_code['file_check']['forced_capabilities']['task_progress'] is True
assert by_code['generic']['required_fields'] == []
file_check_contract = by_code['file_check']['progress_contract']
assert file_check_contract['data_source']['type'] == 'schedule_run'
assert file_check_contract['binding']['requires_schedule_task'] is True
shipping = by_code['shipping_notice']
assert shipping['default_capabilities']['file_upload'] is True
assert shipping['default_capabilities']['task_progress'] is True
assert shipping['forced_capabilities'] == {
'file_upload': True,
'task_progress': True,
'human_confirm': True,
}
assert shipping['progress_contract']['presentation']['layout'] == 'workspace'
assert shipping['progress_contract']['binding']['requires_schedule_task'] is False
assert 'erp_kb' not in shipping['forced_capabilities']
def test_build_agent_registry_schema_handler_config_schemas():
@@ -12,7 +12,9 @@ from app.core.errors import ValidationError
from app.services.agent_registry.catalog_loader import (
clear_catalog_cache,
coerce_manifest_boolean,
get_agent_type_default_capabilities,
get_default_capabilities,
normalize_progress_contract,
)
@@ -46,6 +48,53 @@ def test_get_default_capabilities_uses_manifest_boolean_coercion(monkeypatch):
assert caps['task_progress'] is False
def test_get_agent_type_default_capabilities_merges_platform_and_type_defaults():
"""agent_types.default_capabilities 应覆盖 platform 同名字段。"""
clear_catalog_cache()
caps = get_agent_type_default_capabilities('shipping_notice')
assert caps['streaming'] is True
assert caps['file_upload'] is True
assert caps['task_progress'] is True
assert caps['erp_kb'] is False
def test_normalize_progress_contract_file_check_shape():
contract = normalize_progress_contract({
'enabled': True,
'data_source': {'type': 'schedule_run'},
'update': {'transport': 'polling', 'interval_seconds': 2},
'binding': {'type': 'chat_log_run', 'requires_schedule_task': True},
'presentation': {'layout': 'card', 'visualization': 'counter'},
})
assert contract is not None
assert contract['data_source']['type'] == 'schedule_run'
assert contract['binding']['requires_schedule_task'] is True
def test_normalize_progress_contract_sse_requires_event():
"""transport=sse 但缺 event 时应 fail-fast,避免运行时静默不发进度。"""
with pytest.raises(ValidationError, match='update.event'):
normalize_progress_contract({
'enabled': True,
'data_source': {'type': 'domain_state', 'domain': 'shipping_notice'},
'update': {'transport': 'sse'},
'binding': {'type': 'conversation_context'},
'presentation': {'layout': 'workspace', 'visualization': 'stepper'},
})
def test_normalize_progress_contract_schedule_run_requires_schedule_task_binding():
"""schedule_run 数据源必须声明 binding.requires_schedule_task=true。"""
with pytest.raises(ValidationError, match='requires_schedule_task'):
normalize_progress_contract({
'enabled': True,
'data_source': {'type': 'schedule_run'},
'update': {'transport': 'polling'},
'binding': {'type': 'chat_log_run', 'requires_schedule_task': False},
'presentation': {'layout': 'card', 'visualization': 'counter'},
})
def test_get_tool_run_progress_defaults_coerces_boolean_string(monkeypatch):
from app.services.agent_registry import catalog_loader
from app.services.agent_registry.catalog_loader import get_tool_run_progress_defaults
@@ -16,6 +16,7 @@ from app.services.agent_registry.catalog import AGENT_TYPE_CATALOG, clear_catalo
from app.services.agent_registry.catalog_loader import list_agent_type_codes
from app.services.agent_registry.catalog_validation import (
apply_catalog_capabilities,
catalog_progress_requires_schedule_task,
normalize_handler_config,
validate_required_fields,
)
@@ -110,6 +111,11 @@ def test_normalize_handler_config_rejects_invalid_boolean_string():
normalize_handler_config('file_check', {'lock_input_when_running': 'maybe'})
def test_catalog_progress_requires_schedule_task_follows_contract():
assert catalog_progress_requires_schedule_task('file_check') is True
assert catalog_progress_requires_schedule_task('shipping_notice') is False
def test_normalize_handler_config_empty_schema_rejects_any_field():
"""空 handler_config_schema 表示不允许任何 handler_config 字段。"""
with pytest.raises(ValidationError, match='不允许配置 handler_config'):
+48 -1
View File
@@ -13,6 +13,8 @@ from app.services.agent_registry.resolver import (
agent_declares_task_progress,
agent_has_erp_kb,
agent_has_intent_route,
agent_has_progress,
agent_progress_requires_schedule_task,
is_file_check_runtime_ready,
normalize_capabilities,
resolve_agent_code,
@@ -20,6 +22,7 @@ from app.services.agent_registry.resolver import (
resolve_conversation_mode,
resolve_handler_key,
resolve_intent_routes,
resolve_progress_contract,
resolve_runtime_provider,
)
from app.services.file_check_tools.task_resolver import resolve_schedule_task_id_from_agent
@@ -184,7 +187,7 @@ def test_agent_declares_task_progress_reads_registry_columns():
def test_is_file_check_runtime_ready_requires_bound_task_id():
"""完整 file_check 入口须 capabilities.task_progress 与 bound_schedule_task_id。"""
"""完整 file_check 入口须 progress_contract 要求排程且 bound_schedule_task_id 已配置。"""
ready = _agent(
agent_code='file_check',
capabilities={'task_progress': True},
@@ -196,3 +199,47 @@ def test_is_file_check_runtime_ready_requires_bound_task_id():
)
assert is_file_check_runtime_ready(ready) is True
assert is_file_check_runtime_ready(misconfigured) is False
def test_resolve_progress_contract_reads_catalog_for_file_check():
agent = _agent(agent_code='file_check', capabilities={'task_progress': True})
contract = resolve_progress_contract(agent)
assert contract is not None
assert contract['data_source']['type'] == 'schedule_run'
assert contract['presentation']['visualization'] == 'counter'
def test_resolve_progress_contract_reads_catalog_for_shipping_notice():
agent = _agent(agent_code='shipping_notice', capabilities={'task_progress': True})
contract = resolve_progress_contract(agent)
assert contract is not None
assert contract['data_source']['type'] == 'domain_state'
assert contract['update']['event'] == 'shipping_ui_state'
def test_agent_has_progress_merges_catalog_forced_capabilities():
"""capabilities 列缺失时,Catalog forced_capabilities.task_progress 也应放行 contract。"""
assert agent_has_progress(_agent(agent_code='file_check')) is True
assert agent_has_progress(_agent(agent_code='file_check', capabilities={'task_progress': True})) is True
assert agent_has_progress(_agent(agent_code='generic')) is False
def test_resolve_progress_contract_shipping_notice_without_capabilities_column():
"""存量 shipping_notice 行 capabilities.task_progress 缺失/false 时仍应返回 contract。"""
missing = _agent(agent_code='shipping_notice', capabilities=None)
stale_false = _agent(agent_code='shipping_notice', capabilities={'task_progress': False})
for agent in (missing, stale_false):
contract = resolve_progress_contract(agent)
assert contract is not None
assert contract['update']['event'] == 'shipping_ui_state'
def test_agent_progress_requires_schedule_task_only_for_file_check():
assert agent_progress_requires_schedule_task(_agent(
agent_code='file_check',
capabilities={'task_progress': True},
)) is True
assert agent_progress_requires_schedule_task(_agent(
agent_code='shipping_notice',
capabilities={'task_progress': True},
)) is False
@@ -6,7 +6,12 @@ tests/test_agent_registry_serialization.py
from types import SimpleNamespace
from app.services.agent_registry.serialization import mask_dify_api_key, serialize_agent_for_admin
from app.services.agent_registry.serialization import (
build_tool_run_progress_view,
mask_dify_api_key,
serialize_agent_for_admin,
serialize_registry_fields,
)
def test_mask_dify_api_key():
@@ -15,7 +20,7 @@ def test_mask_dify_api_key():
assert mask_dify_api_key('sk-abcdefghijklmnop') == 'sk-a****mnop'
def test_serialize_agent_for_admin_does_not_expose_plain_api_key():
def test_serialize_agent_for_admin_includes_api_key_for_admin_edit():
agent = SimpleNamespace(
id=1,
name='Bot',
@@ -44,5 +49,38 @@ def test_serialize_agent_for_admin_does_not_expose_plain_api_key():
handler_config=None,
)
payload = serialize_agent_for_admin(agent)
assert 'dify_api_key' not in payload
assert payload['dify_api_key'] == agent.dify_api_key
assert payload['dify_api_key_masked'] == mask_dify_api_key(agent.dify_api_key)
def test_serialize_registry_fields_includes_progress_contract():
file_check = SimpleNamespace(
agent_code='file_check',
runtime_provider='dify',
conversation_mode='task_chat',
capabilities={'task_progress': True},
bound_schedule_task_id=42,
handler_config={'poll_interval_seconds': 2, 'lock_input_when_running': True},
dify_app_type='chatflow',
iframe_url=None,
category=None,
sub_category=None,
sort_order=0,
welcome_message=None,
suggested_questions_style='plain',
suggested_questions=[],
file_upload_policy=None,
)
payload = serialize_registry_fields(file_check)
assert payload['progress_contract']['data_source']['type'] == 'schedule_run'
assert payload['tool_run_progress']['schedule_task_id'] == 42
def test_build_tool_run_progress_view_skips_domain_state_contract():
shipping = SimpleNamespace(
agent_code='shipping_notice',
capabilities={'task_progress': True},
bound_schedule_task_id=99,
handler_config=None,
)
assert build_tool_run_progress_view(shipping) is None
+8 -6
View File
@@ -49,11 +49,12 @@ def _mk_check_task(owner_id: int, *, enabled=True):
task = ScheduleTask(
schedule_no='CHK-ROHS-001',
name='RoHS 自动检核',
schedule_type='platform_app',
schedule_type='data_pipeline',
data_source_type='database',
owner_user_id=owner_id,
cron_expr='0 * * * *',
wait_seconds=5,
platform_api_path='/1',
platform_api_path=None,
enabled=enabled,
)
db.session.add(task)
@@ -65,11 +66,12 @@ def _mk_other_check_task(owner_id: int):
task = ScheduleTask(
schedule_no='CHK-GENERAL-001',
name='通用检核',
schedule_type='platform_app',
schedule_type='data_pipeline',
data_source_type='database',
owner_user_id=owner_id,
cron_expr='0 * * * *',
wait_seconds=5,
platform_api_path='/general-check',
platform_api_path=None,
enabled=True,
)
db.session.add(task)
@@ -512,7 +514,7 @@ def test_file_check_tool_running_conflict_is_per_task(app, client, monkeypatch):
second_task = ScheduleTask(
schedule_no='CHK-ROHS-002',
name='RoHS 文件检核备用',
schedule_type='platform_app',
schedule_type='data_pipeline',
owner_user_id=admin.id,
cron_expr='0 * * * *',
wait_seconds=5,
@@ -609,7 +611,7 @@ def test_workspace_file_check_active_run_filters_by_task_id(app, client):
task_b = ScheduleTask(
schedule_no='CHK-ROHS-002',
name='RoHS 文件检核 B',
schedule_type='platform_app',
schedule_type='data_pipeline',
owner_user_id=admin.id,
cron_expr='0 * * * *',
wait_seconds=5,
@@ -0,0 +1,138 @@
"""internal_jobs API registry 集成测试。"""
import json
from app.models import ScheduleRun, ScheduleTask, User
def test_internal_job_shipping_inventory_rpa_writes_trigger(client, app, tmp_path):
"""POST /api/internal/jobs/shipping-inventory-rpa 应写入 batch trigger。"""
trigger_dir = tmp_path / "triggers"
trigger_dir.mkdir()
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
with app.app_context():
from app import db
user = User(username="internal_job_user", email="internal_job_user@example.com")
db.session.add(user)
db.session.flush()
task = ScheduleTask(
schedule_no="SCH-IJ-001",
name="货代库存每日导出",
schedule_type="platform_job",
platform_api_path="shipping-inventory-rpa",
data_source_type=None,
owner_user_id=user.id,
cron_expr="0 3 * * *",
enabled=True,
)
db.session.add(task)
db.session.flush()
run = ScheduleRun(
run_no="RUN20260708030000",
schedule_task_id=task.id,
status="running",
)
db.session.add(run)
db.session.commit()
run_no = run.run_no
task_id = task.id
resp = client.post(
"/api/internal/jobs/shipping-inventory-rpa",
data=json.dumps({"run_no": run_no, "schedule_task_id": task_id}),
content_type="application/json",
)
assert resp.status_code == 200
body = resp.get_json()
assert body["summary"]["success_count"] >= 1
assert list(trigger_dir.glob("inventory_export_batch_*.json"))
def test_internal_job_unknown_key_returns_404(client):
"""未注册 job key 应返回 404。"""
resp = client.post(
"/api/internal/jobs/not-registered-job",
data=json.dumps({}),
content_type="application/json",
)
assert resp.status_code == 404
def test_internal_job_rejects_mismatched_schedule_task_id(client, app):
"""schedule_task_id 与 URL job key 不匹配应 400。"""
with app.app_context():
from app import db
user = User(username="ij_mismatch_user", email="ij_mismatch_user@example.com")
db.session.add(user)
db.session.flush()
task = ScheduleTask(
schedule_no="SCH-IJ-MISMATCH",
name="固资快照",
schedule_type="platform_job",
platform_api_path="fixed-assets-snapshot",
data_source_type=None,
owner_user_id=user.id,
cron_expr="0 3 * * *",
enabled=True,
)
db.session.add(task)
db.session.commit()
task_id = task.id
resp = client.post(
"/api/internal/jobs/shipping-inventory-rpa",
data=json.dumps({"schedule_task_id": task_id}),
content_type="application/json",
)
assert resp.status_code == 400
def test_internal_job_rejects_foreign_run_no(client, app):
"""run_no 属于其他任务时应 400。"""
with app.app_context():
from app import db
user = User(username="ij_run_user", email="ij_run_user@example.com")
db.session.add(user)
db.session.flush()
task_a = ScheduleTask(
schedule_no="SCH-IJ-A",
name="shipping task",
schedule_type="platform_job",
platform_api_path="shipping-inventory-rpa",
data_source_type=None,
owner_user_id=user.id,
cron_expr="0 3 * * *",
enabled=True,
)
task_b = ScheduleTask(
schedule_no="SCH-IJ-B",
name="faq task",
schedule_type="platform_job",
platform_api_path="faq-aggregate-hot",
data_source_type=None,
owner_user_id=user.id,
cron_expr="0 4 * * *",
enabled=True,
)
db.session.add_all([task_a, task_b])
db.session.flush()
run = ScheduleRun(
run_no="RUN-FOREIGN-001",
schedule_task_id=task_b.id,
status="running",
)
db.session.add(run)
db.session.commit()
task_a_id = task_a.id
run_no = run.run_no
resp = client.post(
"/api/internal/jobs/shipping-inventory-rpa",
data=json.dumps({"schedule_task_id": task_a_id, "run_no": run_no}),
content_type="application/json",
)
assert resp.status_code == 400
+79 -10
View File
@@ -1,12 +1,30 @@
import pytest
from app import db
from app.core.auth.jwt import issue_local_access_token
from app.models import Agent, ScheduleRun, ScheduleTask, User
def _mk_admin():
admin = User(username='admin', email='admin@example.com', role='admin', status='active')
admin.set_password('x')
db.session.add(admin)
return admin
@pytest.fixture
def admin_jwt_headers(app):
"""创建 admin 用户并签发 Bearer JWT。"""
with app.app_context():
user = db.session.query(User).filter_by(username='admin').first()
if not user:
user = User(
username='admin',
email='admin@example.com',
role='admin',
status='active',
)
user.set_password('admin')
db.session.add(user)
db.session.commit()
token = issue_local_access_token(user)
return {
'Authorization': f'Bearer {token}',
'Content-Type': 'application/json',
}
def _mk_user(name: str, email: str):
@@ -16,9 +34,8 @@ def _mk_user(name: str, email: str):
return user
def test_schedule_crud_and_workspace_visibility(app, client, admin_headers):
def test_schedule_crud_and_workspace_visibility(app, client, admin_jwt_headers):
with app.app_context():
_mk_admin()
owner = _mk_user('owner_u', 'owner@example.com')
notify = _mk_user('notify_u', 'notify@example.com')
other = _mk_user('other_u', 'other@example.com')
@@ -31,9 +48,10 @@ def test_schedule_crud_and_workspace_visibility(app, client, admin_headers):
other_id = other.id
agent_id = agent.id
create_res = client.post('/api/admin/schedules', headers=admin_headers, json={
create_res = client.post('/api/admin/schedules', headers=admin_jwt_headers, json={
'name': 'rohs-schedule',
'schedule_type': 'dify_app',
'schedule_type': 'data_pipeline',
'data_source_type': 'database',
'owner_user_id': owner_id,
'cron_expr': '0 */30 * * *',
'wait_seconds': 5,
@@ -46,7 +64,7 @@ def test_schedule_crud_and_workspace_visibility(app, client, admin_headers):
task = create_res.get_json()
task_id = task['id']
list_res = client.get('/api/admin/schedules', headers=admin_headers)
list_res = client.get('/api/admin/schedules', headers=admin_jwt_headers)
assert list_res.status_code == 200
assert any(x['id'] == task_id for x in list_res.get_json())
@@ -85,3 +103,54 @@ def test_schedule_crud_and_workspace_visibility(app, client, admin_headers):
denied = client.get(f'/api/workspace/schedule-runs/{run_id}', headers=other_headers)
assert denied.status_code == 403
def test_post_schedule_defaults_data_source_type_to_database(app, client, admin_jwt_headers):
"""兼容旧客户端:data_pipeline 不传 data_source_type 时应默认 database 而非 400。"""
with app.app_context():
owner = _mk_user('legacy_owner_u', 'legacy_owner@example.com')
db.session.commit()
owner_id = owner.id
res = client.post('/api/admin/schedules', headers=admin_jwt_headers, json={
'name': 'legacy-minimal-schedule',
'owner_user_id': owner_id,
'cron_expr': '0 3 * * *',
})
assert res.status_code == 201
body = res.get_json()
assert body['schedule_type'] == 'data_pipeline'
assert body['data_source_type'] == 'database'
def test_post_and_patch_schedule_reject_non_object_config(app, client, admin_jwt_headers):
"""POST/PATCH config 传非 JSON 对象(数组/字符串)应 400,而非 500。"""
with app.app_context():
owner = _mk_user('cfg_type_owner_u', 'cfg_type_owner@example.com')
db.session.commit()
owner_id = owner.id
post_res = client.post('/api/admin/schedules', headers=admin_jwt_headers, json={
'name': 'bad-config-schedule',
'schedule_type': 'data_pipeline',
'data_source_type': 'database',
'owner_user_id': owner_id,
'cron_expr': '0 3 * * *',
'config': ['not-an-object'],
})
assert post_res.status_code == 400
create_res = client.post('/api/admin/schedules', headers=admin_jwt_headers, json={
'name': 'good-schedule',
'schedule_type': 'data_pipeline',
'data_source_type': 'database',
'owner_user_id': owner_id,
'cron_expr': '0 3 * * *',
})
assert create_res.status_code == 201
task_id = create_res.get_json()['id']
patch_res = client.patch(f'/api/admin/schedules/{task_id}', headers=admin_jwt_headers, json={
'config': 'not-an-object',
})
assert patch_res.status_code == 400
+289
View File
@@ -0,0 +1,289 @@
"""排程 Job Registry 与 executor 分发测试。"""
import pytest
from app import db
from app.core.auth.jwt import issue_local_access_token
from app.models import ScheduleTask, User
from app.services.schedule import _run_common_executor, _run_generic_check_job, resolve_schedule_executor
from app.services.schedule.job_registry import get_platform_job, list_platform_jobs, run_platform_job
from app.services.schedule.schedule_contract import migrate_legacy_schedule_payload, normalize_job_key
@pytest.fixture
def admin_jwt_headers(app):
"""创建 admin 用户并签发 Bearer JWT。"""
with app.app_context():
user = db.session.query(User).filter_by(username='admin').first()
if not user:
user = User(
username='admin',
email='admin@example.com',
role='admin',
status='active',
)
user.set_password('admin')
db.session.add(user)
db.session.commit()
token = issue_local_access_token(user)
return {
'Authorization': f'Bearer {token}',
'Content-Type': 'application/json',
}
def test_platform_jobs_registered():
"""内置 platform job 应已注册。"""
keys = {job.key for job in list_platform_jobs()}
assert "shipping-inventory-rpa" in keys
assert "faq-aggregate-hot" in keys
assert "fixed-assets-snapshot" in keys
assert get_platform_job("shipping-inventory-rpa") is not None
def test_unknown_platform_job_raises():
"""未注册 key 应无法 resolve。"""
assert get_platform_job("not-a-real-job") is None
def test_resolve_schedule_executor_dispatch():
"""schedule_type 决定 executor 分发。"""
pipeline_task = ScheduleTask(schedule_type="data_pipeline", data_source_type="database")
platform_task = ScheduleTask(schedule_type="platform_job", platform_api_path="faq-aggregate-hot")
assert resolve_schedule_executor(pipeline_task) is _run_generic_check_job
assert resolve_schedule_executor(platform_task) is _run_common_executor
with pytest.raises(RuntimeError, match="Unsupported schedule_type"):
resolve_schedule_executor(ScheduleTask(schedule_type="legacy_type"))
def test_normalize_job_key_extracts_last_segment_from_full_path():
"""历史数据存完整内部路径或 URL 时,应提取最后一段作为 job key。"""
assert normalize_job_key('/api/internal/jobs/faq-aggregate-hot') == 'faq-aggregate-hot'
assert normalize_job_key('http://hxops.local/api/internal/jobs/shipping-inventory-rpa') == 'shipping-inventory-rpa'
assert normalize_job_key('/api/internal/jobs/fixed_assets_snapshot?token=x') == 'fixed-assets-snapshot'
assert normalize_job_key('faq_aggregate_hot') == 'faq-aggregate-hot'
assert normalize_job_key(None) == ''
def test_normalize_platform_api_path_delegates_to_job_key():
"""执行层归一化应与契约层 normalize_job_key 一致;完整 URL 原样透传。"""
from app.services.schedule import normalize_platform_api_path
assert normalize_platform_api_path('/api/internal/jobs/faq-aggregate-hot') == 'faq-aggregate-hot'
assert normalize_platform_api_path('faq_aggregate_hot') == 'faq-aggregate-hot'
assert normalize_platform_api_path('http://external.host/hook') == 'http://external.host/hook'
assert normalize_platform_api_path(None) == ''
def test_migrate_legacy_full_path_platform_api_path():
"""旧 platform_app + 完整路径 platform_api_path 应迁移为 platform_job。"""
migrated = migrate_legacy_schedule_payload({
"schedule_type": "platform_app",
"platform_api_path": "/api/internal/jobs/fixed-assets-snapshot",
})
assert migrated["schedule_type"] == "platform_job"
assert migrated["platform_api_path"] == "fixed-assets-snapshot"
assert migrated["data_source_type"] is None
def test_migrate_legacy_shipping_inventory_rpa():
"""旧 shipping_inventory_rpa 语义应迁移为 platform_job。"""
migrated = migrate_legacy_schedule_payload({
"schedule_type": "platform_app",
"data_source_type": "shipping_inventory_rpa",
"platform_api_path": "/123",
})
assert migrated["schedule_type"] == "platform_job"
assert migrated["platform_api_path"] == "shipping-inventory-rpa"
assert migrated["data_source_type"] is None
def test_migrate_legacy_faq_hot_aggregate():
"""旧 faq_hot_aggregate 语义应迁移为 platform_job。"""
migrated = migrate_legacy_schedule_payload({
"data_source_type": "faq_hot_aggregate",
})
assert migrated["schedule_type"] == "platform_job"
assert migrated["platform_api_path"] == "faq-aggregate-hot"
assert migrated["data_source_type"] is None
def test_migrate_legacy_database_pipeline():
"""旧 platform_app + database 应迁移为 data_pipeline。"""
migrated = migrate_legacy_schedule_payload({
"schedule_type": "platform_app",
"data_source_type": "database",
"platform_api_path": "/42",
})
assert migrated["schedule_type"] == "data_pipeline"
assert migrated["platform_api_path"] is None
assert migrated["data_source_type"] == "database"
def test_run_platform_job_unknown_key(app):
"""run_platform_job 对未知 key 应抛 KeyError。"""
with app.app_context():
user = User(username="registry_user", email="registry_user@example.com")
from app import db
db.session.add(user)
db.session.flush()
task = ScheduleTask(
schedule_no="SCH-REG-001",
name="test",
schedule_type="platform_job",
platform_api_path="shipping-inventory-rpa",
owner_user_id=user.id,
cron_expr="0 3 * * *",
)
from app.models import ScheduleRun
run = ScheduleRun(run_no="RUN-REG-001", schedule_task_id=1, status="running")
with pytest.raises(KeyError):
run_platform_job("unknown-job-key", task, run, {})
def test_common_executor_in_process_without_base_url(app, monkeypatch):
"""已注册 job key 在无 INTERNAL_API_BASE_URL 时应进程内执行,不走 HTTP。"""
with app.app_context():
from app import db
from app.models import ScheduleRun
app.config["INTERNAL_API_BASE_URL"] = ""
user = User(username="inproc_exec_user", email="inproc_exec_user@example.com")
db.session.add(user)
db.session.flush()
task = ScheduleTask(
schedule_no="SCH-INPROC-001",
name="in-process job",
schedule_type="platform_job",
platform_api_path="faq-aggregate-hot",
data_source_type=None,
owner_user_id=user.id,
cron_expr="0 3 * * *",
)
db.session.add(task)
db.session.flush()
run = ScheduleRun(run_no="RUN-INPROC-001", schedule_task_id=task.id, status="running")
db.session.add(run)
db.session.commit()
called: dict[str, str] = {}
def _fake_run_platform_job(key, t, r, payload=None):
called["key"] = key
return 1, 1, 0, 0, [{"ok": True}], [], [{"step": "in_process", "status": "success"}]
monkeypatch.setattr(
"app.services.schedule.job_registry.run_platform_job",
_fake_run_platform_job,
)
total, success, failed, skipped, details, errors, logs = _run_common_executor(task, run)
assert called["key"] == "faq-aggregate-hot"
assert total == 1 and success == 1
assert any(log.get("step") == "in_process" for log in logs)
def test_get_platform_jobs_api(client, admin_jwt_headers):
"""GET /api/admin/schedule/platform-jobs 应返回 registry 列表及 label_key。"""
res = client.get("/api/admin/schedule/platform-jobs", headers=admin_jwt_headers)
assert res.status_code == 200
body = res.get_json()
keys = {item["key"] for item in body}
assert "shipping-inventory-rpa" in keys
assert "faq-aggregate-hot" in keys
assert all("label" in item for item in body)
# 内置 job 应返回稳定 i18n key,供前端 $t(label_key) 渲染
by_key = {item["key"]: item for item in body}
assert by_key["shipping-inventory-rpa"]["label_key"] == "admin.schedule.form.platformJobShippingInventory"
assert by_key["faq-aggregate-hot"]["label_key"] == "admin.schedule.form.platformJobFaqHotAggregate"
assert by_key["fixed-assets-snapshot"]["label_key"] == "admin.schedule.form.platformJobFixedAssetsSnapshot"
def test_schedule_config_rejects_data_source_type_for_platform_job(client, admin_jwt_headers, app):
"""platform_job 经 schedule-config PUT 改 data_source_type 应被拒绝。"""
with app.app_context():
from app import db
user = User(username="cfg_platform_user", email="cfg_platform_user@example.com")
db.session.add(user)
db.session.flush()
task = ScheduleTask(
schedule_no="SCH-CFG-001",
name="platform cfg guard",
schedule_type="platform_job",
platform_api_path="fixed-assets-snapshot",
data_source_type=None,
owner_user_id=user.id,
cron_expr="0 3 * * *",
)
db.session.add(task)
db.session.commit()
task_id = task.id
res = client.put(
f"/api/admin/schedule-config/{task_id}",
headers=admin_jwt_headers,
json={"data_source_type": "database"},
)
assert res.status_code == 400
def test_post_platform_job_rejects_illegal_config(client, admin_jwt_headers, app):
"""创建 platform_job 携带非白名单 config 应 400。"""
with app.app_context():
user = User(username="post_cfg_user", email="post_cfg_user@example.com")
db.session.add(user)
db.session.commit()
owner_id = user.id
res = client.post(
"/api/admin/schedules",
headers=admin_jwt_headers,
json={
"name": "faq with config",
"schedule_type": "platform_job",
"platform_api_path": "faq-aggregate-hot",
"owner_user_id": owner_id,
"cron_expr": "0 3 * * *",
"config": {"api_body_template": "{}"},
},
)
assert res.status_code == 400
def test_patch_platform_job_rejects_illegal_config_without_partial_update(client, admin_jwt_headers, app):
"""PATCH 携带非法 config 应 400,且任务主字段不被半更新。"""
with app.app_context():
user = User(username="patch_cfg_user", email="patch_cfg_user@example.com")
db.session.add(user)
db.session.flush()
task = ScheduleTask(
schedule_no="SCH-PATCH-CFG-001",
name="before patch",
schedule_type="platform_job",
platform_api_path="fixed-assets-snapshot",
data_source_type=None,
owner_user_id=user.id,
cron_expr="0 3 * * *",
)
db.session.add(task)
db.session.commit()
task_id = task.id
res = client.patch(
f"/api/admin/schedules/{task_id}",
headers=admin_jwt_headers,
json={
"name": "after patch",
"config": {"api_body_template": "{}"},
},
)
assert res.status_code == 400
with app.app_context():
refreshed = db.session.get(ScheduleTask, task_id)
assert refreshed.name == "before patch"
@@ -19,9 +19,11 @@ def test_shipping_inventory_rpa_schedule_writes_batch_trigger(app, tmp_path):
task = ScheduleTask(
schedule_no="SCH-INV-001",
name="货代库存每日导出",
schedule_type="platform_job",
platform_api_path="shipping-inventory-rpa",
data_source_type=None,
owner_user_id=user.id,
cron_expr="0 3 * * *",
data_source_type="shipping_inventory_rpa",
enabled=True,
)
db.session.add(task)