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)