205 lines
6.9 KiB
Python
205 lines
6.9 KiB
Python
"""
|
||
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.dify_snapshot import capture_dify_execution_snapshot
|
||
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
|
||
from app.services.schedule.shipping_inventory_rpa_finalize import (
|
||
apply_deferred_schedule_run_state,
|
||
recover_stale_awaiting_rpa_schedule_runs,
|
||
should_defer_schedule_run_finalization,
|
||
)
|
||
|
||
internal_jobs_bp = Blueprint('internal_jobs', __name__)
|
||
|
||
|
||
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}'"
|
||
)
|
||
|
||
|
||
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 = 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:
|
||
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, 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:
|
||
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()
|
||
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
|
||
run.skipped_count = skipped_count
|
||
run.finished_at = datetime.utcnow()
|
||
if run.started_at and run.finished_at:
|
||
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()
|
||
|
||
|
||
@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)
|
||
recover_stale_awaiting_rpa_schedule_runs(task)
|
||
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,
|
||
},
|
||
},
|
||
)
|
||
|
||
if should_defer_schedule_run_finalization(task, step_logs):
|
||
apply_deferred_schedule_run_state(
|
||
run,
|
||
task,
|
||
total_count=total_count,
|
||
success_count=success_count,
|
||
failed_count=failed_count,
|
||
skipped_count=skipped_count,
|
||
details=details,
|
||
errors=errors,
|
||
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,
|
||
'awaiting_rpa_callback': True,
|
||
})
|
||
|
||
_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,
|
||
})
|