|
| 1 | +import { db, workflow as workflowTable } from '@sim/db' |
| 2 | +import { createLogger } from '@sim/logger' |
| 3 | +import { eq } from 'drizzle-orm' |
| 4 | +import { type NextRequest, NextResponse } from 'next/server' |
| 5 | +import { v4 as uuidv4 } from 'uuid' |
| 6 | +import { z } from 'zod' |
| 7 | +import { checkHybridAuth } from '@/lib/auth/hybrid' |
| 8 | +import { generateRequestId } from '@/lib/core/utils/request' |
| 9 | +import { SSE_HEADERS } from '@/lib/core/utils/sse' |
| 10 | +import { markExecutionCancelled } from '@/lib/execution/cancellation' |
| 11 | +import { LoggingSession } from '@/lib/logs/execution/logging-session' |
| 12 | +import { executeWorkflowCore } from '@/lib/workflows/executor/execution-core' |
| 13 | +import { createSSECallbacks } from '@/lib/workflows/executor/execution-events' |
| 14 | +import { ExecutionSnapshot } from '@/executor/execution/snapshot' |
| 15 | +import type { ExecutionMetadata, SerializableExecutionState } from '@/executor/execution/types' |
| 16 | +import { hasExecutionResult } from '@/executor/utils/errors' |
| 17 | + |
| 18 | +const logger = createLogger('ExecuteFromBlockAPI') |
| 19 | + |
| 20 | +const ExecuteFromBlockSchema = z.object({ |
| 21 | + startBlockId: z.string().min(1, 'Start block ID is required'), |
| 22 | + sourceSnapshot: z.object({ |
| 23 | + blockStates: z.record(z.any()), |
| 24 | + executedBlocks: z.array(z.string()), |
| 25 | + blockLogs: z.array(z.any()), |
| 26 | + decisions: z.object({ |
| 27 | + router: z.record(z.string()), |
| 28 | + condition: z.record(z.string()), |
| 29 | + }), |
| 30 | + completedLoops: z.array(z.string()), |
| 31 | + loopExecutions: z.record(z.any()).optional(), |
| 32 | + parallelExecutions: z.record(z.any()).optional(), |
| 33 | + parallelBlockMapping: z.record(z.any()).optional(), |
| 34 | + activeExecutionPath: z.array(z.string()), |
| 35 | + }), |
| 36 | + input: z.any().optional(), |
| 37 | +}) |
| 38 | + |
| 39 | +export const runtime = 'nodejs' |
| 40 | +export const dynamic = 'force-dynamic' |
| 41 | + |
| 42 | +export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string }> }) { |
| 43 | + const requestId = generateRequestId() |
| 44 | + const { id: workflowId } = await params |
| 45 | + |
| 46 | + try { |
| 47 | + const auth = await checkHybridAuth(req, { requireWorkflowId: false }) |
| 48 | + if (!auth.success || !auth.userId) { |
| 49 | + return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 }) |
| 50 | + } |
| 51 | + const userId = auth.userId |
| 52 | + |
| 53 | + let body: unknown |
| 54 | + try { |
| 55 | + body = await req.json() |
| 56 | + } catch { |
| 57 | + return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 }) |
| 58 | + } |
| 59 | + |
| 60 | + const validation = ExecuteFromBlockSchema.safeParse(body) |
| 61 | + if (!validation.success) { |
| 62 | + logger.warn(`[${requestId}] Invalid request body:`, validation.error.errors) |
| 63 | + return NextResponse.json( |
| 64 | + { |
| 65 | + error: 'Invalid request body', |
| 66 | + details: validation.error.errors.map((e) => ({ |
| 67 | + path: e.path.join('.'), |
| 68 | + message: e.message, |
| 69 | + })), |
| 70 | + }, |
| 71 | + { status: 400 } |
| 72 | + ) |
| 73 | + } |
| 74 | + |
| 75 | + const { startBlockId, sourceSnapshot, input } = validation.data |
| 76 | + const executionId = uuidv4() |
| 77 | + |
| 78 | + const [workflowRecord] = await db |
| 79 | + .select({ workspaceId: workflowTable.workspaceId, userId: workflowTable.userId }) |
| 80 | + .from(workflowTable) |
| 81 | + .where(eq(workflowTable.id, workflowId)) |
| 82 | + .limit(1) |
| 83 | + |
| 84 | + if (!workflowRecord?.workspaceId) { |
| 85 | + return NextResponse.json({ error: 'Workflow not found or has no workspace' }, { status: 404 }) |
| 86 | + } |
| 87 | + |
| 88 | + const workspaceId = workflowRecord.workspaceId |
| 89 | + const workflowUserId = workflowRecord.userId |
| 90 | + |
| 91 | + logger.info(`[${requestId}] Starting run-from-block execution`, { |
| 92 | + workflowId, |
| 93 | + startBlockId, |
| 94 | + executedBlocksCount: sourceSnapshot.executedBlocks.length, |
| 95 | + }) |
| 96 | + |
| 97 | + const loggingSession = new LoggingSession(workflowId, executionId, 'manual', requestId) |
| 98 | + const abortController = new AbortController() |
| 99 | + let isStreamClosed = false |
| 100 | + |
| 101 | + const stream = new ReadableStream<Uint8Array>({ |
| 102 | + async start(controller) { |
| 103 | + const { sendEvent, onBlockStart, onBlockComplete, onStream } = createSSECallbacks({ |
| 104 | + executionId, |
| 105 | + workflowId, |
| 106 | + controller, |
| 107 | + isStreamClosed: () => isStreamClosed, |
| 108 | + setStreamClosed: () => { |
| 109 | + isStreamClosed = true |
| 110 | + }, |
| 111 | + }) |
| 112 | + |
| 113 | + const metadata: ExecutionMetadata = { |
| 114 | + requestId, |
| 115 | + workflowId, |
| 116 | + userId, |
| 117 | + executionId, |
| 118 | + triggerType: 'manual', |
| 119 | + workspaceId, |
| 120 | + workflowUserId, |
| 121 | + useDraftState: true, |
| 122 | + isClientSession: true, |
| 123 | + startTime: new Date().toISOString(), |
| 124 | + } |
| 125 | + |
| 126 | + const snapshot = new ExecutionSnapshot(metadata, {}, input || {}, {}) |
| 127 | + |
| 128 | + try { |
| 129 | + const startTime = new Date() |
| 130 | + |
| 131 | + sendEvent({ |
| 132 | + type: 'execution:started', |
| 133 | + timestamp: startTime.toISOString(), |
| 134 | + executionId, |
| 135 | + workflowId, |
| 136 | + data: { startTime: startTime.toISOString() }, |
| 137 | + }) |
| 138 | + |
| 139 | + const result = await executeWorkflowCore({ |
| 140 | + snapshot, |
| 141 | + loggingSession, |
| 142 | + abortSignal: abortController.signal, |
| 143 | + runFromBlock: { |
| 144 | + startBlockId, |
| 145 | + sourceSnapshot: sourceSnapshot as SerializableExecutionState, |
| 146 | + }, |
| 147 | + callbacks: { onBlockStart, onBlockComplete, onStream }, |
| 148 | + }) |
| 149 | + |
| 150 | + if (result.status === 'cancelled') { |
| 151 | + sendEvent({ |
| 152 | + type: 'execution:cancelled', |
| 153 | + timestamp: new Date().toISOString(), |
| 154 | + executionId, |
| 155 | + workflowId, |
| 156 | + data: { duration: result.metadata?.duration || 0 }, |
| 157 | + }) |
| 158 | + } else { |
| 159 | + sendEvent({ |
| 160 | + type: 'execution:completed', |
| 161 | + timestamp: new Date().toISOString(), |
| 162 | + executionId, |
| 163 | + workflowId, |
| 164 | + data: { |
| 165 | + success: result.success, |
| 166 | + output: result.output, |
| 167 | + duration: result.metadata?.duration || 0, |
| 168 | + startTime: result.metadata?.startTime || startTime.toISOString(), |
| 169 | + endTime: result.metadata?.endTime || new Date().toISOString(), |
| 170 | + }, |
| 171 | + }) |
| 172 | + } |
| 173 | + } catch (error: unknown) { |
| 174 | + const errorMessage = error instanceof Error ? error.message : 'Unknown error' |
| 175 | + logger.error(`[${requestId}] Run-from-block execution failed: ${errorMessage}`) |
| 176 | + |
| 177 | + const executionResult = hasExecutionResult(error) ? error.executionResult : undefined |
| 178 | + |
| 179 | + sendEvent({ |
| 180 | + type: 'execution:error', |
| 181 | + timestamp: new Date().toISOString(), |
| 182 | + executionId, |
| 183 | + workflowId, |
| 184 | + data: { |
| 185 | + error: executionResult?.error || errorMessage, |
| 186 | + duration: executionResult?.metadata?.duration || 0, |
| 187 | + }, |
| 188 | + }) |
| 189 | + } finally { |
| 190 | + if (!isStreamClosed) { |
| 191 | + try { |
| 192 | + controller.enqueue(new TextEncoder().encode('data: [DONE]\n\n')) |
| 193 | + controller.close() |
| 194 | + } catch {} |
| 195 | + } |
| 196 | + } |
| 197 | + }, |
| 198 | + cancel() { |
| 199 | + isStreamClosed = true |
| 200 | + abortController.abort() |
| 201 | + markExecutionCancelled(executionId).catch(() => {}) |
| 202 | + }, |
| 203 | + }) |
| 204 | + |
| 205 | + return new NextResponse(stream, { |
| 206 | + headers: { ...SSE_HEADERS, 'X-Execution-Id': executionId }, |
| 207 | + }) |
| 208 | + } catch (error: unknown) { |
| 209 | + const errorMessage = error instanceof Error ? error.message : 'Unknown error' |
| 210 | + logger.error(`[${requestId}] Failed to start run-from-block execution:`, error) |
| 211 | + return NextResponse.json( |
| 212 | + { error: errorMessage || 'Failed to start execution' }, |
| 213 | + { status: 500 } |
| 214 | + ) |
| 215 | + } |
| 216 | +} |
0 commit comments