283 lines
11 KiB
Python
283 lines
11 KiB
Python
"""
|
|
backend/app/api/schedule/tasks.py
|
|
|
|
用途:排程任务 CRUD、导入导出、启用/禁用 API。
|
|
依赖:schedule.blueprint、schedule.common、services/schedule/*。
|
|
逻辑:/schedules* 路由(不含 run 触发与运行记录);job_params 归一化与切换重置
|
|
由 scheduler_service.create_task/update_task 唯一兜底;本层只做请求校验与
|
|
ValueError→ValidationError 映射。
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
from datetime import datetime
|
|
|
|
from flask import Response, jsonify, request
|
|
|
|
from app import db
|
|
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, 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
|
|
|
|
|
|
@schedule_admin_bp.route('/schedules', methods=['GET'])
|
|
@require_admin
|
|
def get_schedules():
|
|
"""返回全部排程任务列表。"""
|
|
return jsonify(list_tasks())
|
|
|
|
|
|
@schedule_admin_bp.route('/schedule/platform-jobs', methods=['GET'])
|
|
@require_admin
|
|
def get_platform_jobs():
|
|
"""
|
|
返回 Job Registry 已启用平台任务列表,供前端下拉动态加载。
|
|
与 /platform-tasks/definitions 一致:只返回 enabled=True,避免下拉可选却无参数定义。
|
|
"""
|
|
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,
|
|
'enabled': job.enabled,
|
|
}
|
|
for job in list_platform_jobs()
|
|
if job.enabled
|
|
])
|
|
|
|
|
|
@schedule_admin_bp.route('/schedules/<int:task_id>/export', methods=['GET'])
|
|
@require_admin
|
|
def export_schedule(task_id: int):
|
|
"""导出单条排程任务及配置为 JSON 文件。"""
|
|
task = db.session.get(ScheduleTask, task_id)
|
|
if not task:
|
|
raise NotFoundError('Not found')
|
|
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
|
payload = {
|
|
'schema_version': 1,
|
|
'exported_at': datetime.utcnow().isoformat(),
|
|
'schedules': [serialize_task_for_export(task, cfg_model)],
|
|
}
|
|
body = json.dumps(payload, ensure_ascii=False, indent=2)
|
|
filename = f"{task.schedule_no or f'schedule_{task.id}'}_export_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}.json"
|
|
return Response(
|
|
body,
|
|
mimetype='application/json; charset=utf-8',
|
|
headers={'Content-Disposition': f'attachment; filename="{filename}"'},
|
|
)
|
|
|
|
|
|
@schedule_admin_bp.route('/schedules/import', methods=['POST'])
|
|
@require_admin
|
|
def import_schedules():
|
|
"""批量导入排程 JSON(按 schedule_no upsert)。"""
|
|
data = request.get_json(silent=True) or {}
|
|
user = get_current_user()
|
|
result = import_schedules_from_payload(
|
|
data.get('schedules'),
|
|
actor_id=getattr(user, 'id', None),
|
|
)
|
|
return jsonify(result)
|
|
|
|
|
|
@schedule_admin_bp.route('/schedules', methods=['POST'])
|
|
@require_admin
|
|
def post_schedule():
|
|
"""创建排程任务。"""
|
|
data = request.get_json(silent=True) or {}
|
|
user = get_current_user()
|
|
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 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:
|
|
# [STEP 1] 契约与 config 写入权限预校验(失败不落库);job_params 由 create_task 归一化
|
|
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,
|
|
job_params=data.get('job_params'),
|
|
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 = task.config
|
|
if cfg_model is None:
|
|
with db.session.no_autoflush:
|
|
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
|
|
|
|
|
|
@schedule_admin_bp.route('/schedules/<int:task_id>', methods=['GET'])
|
|
@require_admin
|
|
def get_schedule(task_id: int):
|
|
"""返回单条排程任务详情。"""
|
|
task = db.session.get(ScheduleTask, task_id)
|
|
if not task:
|
|
raise NotFoundError('Not found')
|
|
return jsonify(serialize_task(task))
|
|
|
|
|
|
@schedule_admin_bp.route('/schedules/<int:task_id>', methods=['PATCH'])
|
|
@require_admin
|
|
def patch_schedule(task_id: int):
|
|
"""更新排程任务字段与关联配置。"""
|
|
task = db.session.get(ScheduleTask, task_id)
|
|
if not task:
|
|
raise NotFoundError('Not found')
|
|
data = request.get_json(silent=True) or {}
|
|
user = get_current_user()
|
|
config_data = data.get('config')
|
|
if config_data is not None and not isinstance(config_data, dict):
|
|
raise ValidationError('config must be a JSON object')
|
|
try:
|
|
# [STEP 1] 契约与 config 预校验;job_params 重置/归一化由 update_task 唯一兜底
|
|
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 = task.config
|
|
if cfg_model is None:
|
|
with db.session.no_autoflush:
|
|
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))
|
|
|
|
|
|
@schedule_admin_bp.route('/schedules/<int:task_id>', methods=['DELETE'])
|
|
@require_admin
|
|
def delete_schedule(task_id: int):
|
|
"""删除排程任务及其运行记录;中断进行中的 run。"""
|
|
task = db.session.get(ScheduleTask, task_id)
|
|
if not task:
|
|
raise NotFoundError('Not found')
|
|
from app.services.schedule.scheduler_service import request_cancel_run
|
|
|
|
active_runs = (
|
|
db.session.query(ScheduleRun)
|
|
.filter(ScheduleRun.schedule_task_id == task_id, ScheduleRun.status.in_(('queued', 'running')))
|
|
.all()
|
|
)
|
|
for rr in active_runs:
|
|
request_cancel_run(rr.id)
|
|
rr.status = 'failed'
|
|
rr.error_message = '排程已被删除,执行中断'
|
|
rr.finished_at = datetime.utcnow()
|
|
if active_runs:
|
|
db.session.commit()
|
|
db.session.query(ScheduleRun).filter(ScheduleRun.schedule_task_id == task_id).delete(synchronize_session=False)
|
|
db.session.delete(task)
|
|
db.session.commit()
|
|
return jsonify({'ok': True})
|
|
|
|
|
|
@schedule_admin_bp.route('/schedules/<int:task_id>/enable', methods=['POST'])
|
|
@require_admin
|
|
def enable_schedule(task_id: int):
|
|
"""
|
|
启用排程并重新计算 next_run_at。
|
|
核心逻辑:委托 enable_task 重新校验契约与 job_params,拒绝已停用 platform_job 重新入队。
|
|
"""
|
|
task = db.session.get(ScheduleTask, task_id)
|
|
if not task:
|
|
raise NotFoundError('Not found')
|
|
from app.services.schedule.scheduler_service import enable_task
|
|
|
|
try:
|
|
task = enable_task(task)
|
|
except ValueError as exc:
|
|
db.session.rollback()
|
|
raise ValidationError(str(exc)) from exc
|
|
return jsonify(serialize_task(task))
|
|
|
|
|
|
@schedule_admin_bp.route('/schedules/<int:task_id>/disable', methods=['POST'])
|
|
@require_admin
|
|
def disable_schedule(task_id: int):
|
|
"""禁用排程并清空 next_run_at。"""
|
|
task = db.session.get(ScheduleTask, task_id)
|
|
if not task:
|
|
raise NotFoundError('Not found')
|
|
task.enabled = False
|
|
task.next_run_at = None
|
|
db.session.commit()
|
|
return jsonify({'ok': True})
|