from __future__ import annotations import traceback from datetime import datetime from flask import Blueprint, jsonify, request from app import db 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.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status internal_jobs_bp = Blueprint('internal_jobs', __name__) @internal_jobs_bp.route('/', methods=['POST']) def run_internal_job(name: str): key = name.strip().lower() data = request.get_json(silent=True) or {} run_no = str(data.get('run_no') or '').strip() 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)) 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}'") run = None if run_no: run = ScheduleRun.query.filter_by(run_no=run_no).first() 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') 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' 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() 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})