|
| 1 | +import { runs } from '@trigger.dev/sdk/v3' |
| 2 | +import { eq } from 'drizzle-orm' |
| 3 | +import { type NextRequest, NextResponse } from 'next/server' |
| 4 | +import { getSession } from '@/lib/auth' |
| 5 | +import { createLogger } from '@/lib/logs/console-logger' |
| 6 | +import { db } from '@/db' |
| 7 | +import { apiKey as apiKeyTable } from '@/db/schema' |
| 8 | +import { createErrorResponse } from '../../workflows/utils' |
| 9 | + |
| 10 | +const logger = createLogger('TaskStatusAPI') |
| 11 | + |
| 12 | +export async function GET( |
| 13 | + request: NextRequest, |
| 14 | + { params }: { params: Promise<{ jobId: string }> } |
| 15 | +) { |
| 16 | + const { jobId: taskId } = await params |
| 17 | + const requestId = crypto.randomUUID().slice(0, 8) |
| 18 | + |
| 19 | + try { |
| 20 | + logger.debug(`[${requestId}] Getting status for task: ${taskId}`) |
| 21 | + |
| 22 | + // Try session auth first (for web UI) |
| 23 | + const session = await getSession() |
| 24 | + let authenticatedUserId: string | null = session?.user?.id || null |
| 25 | + |
| 26 | + if (!authenticatedUserId) { |
| 27 | + const apiKeyHeader = request.headers.get('x-api-key') |
| 28 | + if (apiKeyHeader) { |
| 29 | + const [apiKeyRecord] = await db |
| 30 | + .select({ userId: apiKeyTable.userId }) |
| 31 | + .from(apiKeyTable) |
| 32 | + .where(eq(apiKeyTable.key, apiKeyHeader)) |
| 33 | + .limit(1) |
| 34 | + |
| 35 | + if (apiKeyRecord) { |
| 36 | + authenticatedUserId = apiKeyRecord.userId |
| 37 | + } |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + if (!authenticatedUserId) { |
| 42 | + return createErrorResponse('Authentication required', 401) |
| 43 | + } |
| 44 | + |
| 45 | + // Fetch task status from Trigger.dev |
| 46 | + const run = await runs.retrieve(taskId) |
| 47 | + |
| 48 | + logger.debug(`[${requestId}] Task ${taskId} status: ${run.status}`) |
| 49 | + |
| 50 | + // Map Trigger.dev status to our format |
| 51 | + const statusMap = { |
| 52 | + QUEUED: 'queued', |
| 53 | + WAITING_FOR_DEPLOY: 'queued', |
| 54 | + EXECUTING: 'processing', |
| 55 | + RESCHEDULED: 'processing', |
| 56 | + FROZEN: 'processing', |
| 57 | + COMPLETED: 'completed', |
| 58 | + CANCELED: 'cancelled', |
| 59 | + FAILED: 'failed', |
| 60 | + CRASHED: 'failed', |
| 61 | + INTERRUPTED: 'failed', |
| 62 | + SYSTEM_FAILURE: 'failed', |
| 63 | + EXPIRED: 'failed', |
| 64 | + } as const |
| 65 | + |
| 66 | + const mappedStatus = statusMap[run.status as keyof typeof statusMap] || 'unknown' |
| 67 | + |
| 68 | + // Build response based on status |
| 69 | + const response: any = { |
| 70 | + success: true, |
| 71 | + taskId, |
| 72 | + status: mappedStatus, |
| 73 | + metadata: { |
| 74 | + startedAt: run.startedAt, |
| 75 | + }, |
| 76 | + } |
| 77 | + |
| 78 | + // Add completion details if finished |
| 79 | + if (mappedStatus === 'completed') { |
| 80 | + response.output = run.output // This contains the workflow execution results |
| 81 | + response.metadata.completedAt = run.finishedAt |
| 82 | + response.metadata.duration = run.durationMs |
| 83 | + } |
| 84 | + |
| 85 | + // Add error details if failed |
| 86 | + if (mappedStatus === 'failed') { |
| 87 | + response.error = run.error |
| 88 | + response.metadata.completedAt = run.finishedAt |
| 89 | + response.metadata.duration = run.durationMs |
| 90 | + } |
| 91 | + |
| 92 | + // Add progress info if still processing |
| 93 | + if (mappedStatus === 'processing' || mappedStatus === 'queued') { |
| 94 | + response.estimatedDuration = 180000 // 3 minutes max from our config |
| 95 | + } |
| 96 | + |
| 97 | + return NextResponse.json(response) |
| 98 | + } catch (error: any) { |
| 99 | + logger.error(`[${requestId}] Error fetching task status:`, error) |
| 100 | + |
| 101 | + if (error.message?.includes('not found') || error.status === 404) { |
| 102 | + return createErrorResponse('Task not found', 404) |
| 103 | + } |
| 104 | + |
| 105 | + return createErrorResponse('Failed to fetch task status', 500) |
| 106 | + } |
| 107 | +} |
| 108 | + |
| 109 | +// TODO: Implement task cancellation via Trigger.dev API if needed |
| 110 | +// export async function DELETE() { ... } |
0 commit comments