feat(schedule): 优化排程任务配置与进度契约处理逻辑
This commit is contained in:
1 parent
d54f51ddc3
commit
99453aa52a
65 files changed
+2837
-487
No files matched your search
@@ -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))
|
||||
|
||||
@@ -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))
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user