|
| 1 | +import { db } from '@sim/db' |
| 2 | +import { pausedExecutions } from '@sim/db/schema' |
| 3 | +import { createLogger } from '@sim/logger' |
| 4 | +import { toError } from '@sim/utils/errors' |
| 5 | +import { generateShortId } from '@sim/utils/id' |
| 6 | +import { and, eq, isNotNull, lte } from 'drizzle-orm' |
| 7 | +import { type NextRequest, NextResponse } from 'next/server' |
| 8 | +import { verifyCronAuth } from '@/lib/auth/internal' |
| 9 | +import { acquireLock, releaseLock } from '@/lib/core/config/redis' |
| 10 | +import { withRouteHandler } from '@/lib/core/utils/with-route-handler' |
| 11 | +import { PauseResumeManager } from '@/lib/workflows/executor/human-in-the-loop-manager' |
| 12 | + |
| 13 | +const logger = createLogger('TimePauseResumePoll') |
| 14 | + |
| 15 | +export const dynamic = 'force-dynamic' |
| 16 | +export const maxDuration = 120 |
| 17 | + |
| 18 | +const LOCK_KEY = 'time-pause-resume-poll-lock' |
| 19 | +const LOCK_TTL_SECONDS = 120 |
| 20 | +const POLL_BATCH_LIMIT = 200 |
| 21 | + |
| 22 | +interface StoredPausePoint { |
| 23 | + contextId?: string |
| 24 | + resumeStatus?: string |
| 25 | + pauseKind?: string |
| 26 | + resumeAt?: string |
| 27 | +} |
| 28 | + |
| 29 | +export const GET = withRouteHandler(async (request: NextRequest) => { |
| 30 | + const requestId = generateShortId() |
| 31 | + |
| 32 | + const authError = verifyCronAuth(request, 'Time-pause resume poll') |
| 33 | + if (authError) return authError |
| 34 | + |
| 35 | + const lockAcquired = await acquireLock(LOCK_KEY, requestId, LOCK_TTL_SECONDS) |
| 36 | + if (!lockAcquired) { |
| 37 | + return NextResponse.json( |
| 38 | + { success: true, message: 'Polling already in progress – skipped', requestId }, |
| 39 | + { status: 202 } |
| 40 | + ) |
| 41 | + } |
| 42 | + |
| 43 | + let claimedRows = 0 |
| 44 | + let dispatched = 0 |
| 45 | + const failures: { executionId: string; contextId: string; error: string }[] = [] |
| 46 | + |
| 47 | + try { |
| 48 | + const now = new Date() |
| 49 | + |
| 50 | + const dueRows = await db |
| 51 | + .select({ |
| 52 | + id: pausedExecutions.id, |
| 53 | + executionId: pausedExecutions.executionId, |
| 54 | + workflowId: pausedExecutions.workflowId, |
| 55 | + pausePoints: pausedExecutions.pausePoints, |
| 56 | + metadata: pausedExecutions.metadata, |
| 57 | + }) |
| 58 | + .from(pausedExecutions) |
| 59 | + .where( |
| 60 | + and( |
| 61 | + eq(pausedExecutions.status, 'paused'), |
| 62 | + isNotNull(pausedExecutions.nextResumeAt), |
| 63 | + lte(pausedExecutions.nextResumeAt, now) |
| 64 | + ) |
| 65 | + ) |
| 66 | + .limit(POLL_BATCH_LIMIT) |
| 67 | + |
| 68 | + claimedRows = dueRows.length |
| 69 | + |
| 70 | + for (const row of dueRows) { |
| 71 | + const points = (row.pausePoints ?? {}) as Record<string, StoredPausePoint> |
| 72 | + const metadata = (row.metadata ?? {}) as Record<string, unknown> |
| 73 | + const userId = typeof metadata.executorUserId === 'string' ? metadata.executorUserId : '' |
| 74 | + |
| 75 | + const duePoints: StoredPausePoint[] = [] |
| 76 | + let nextRemaining: Date | null = null |
| 77 | + |
| 78 | + for (const point of Object.values(points)) { |
| 79 | + if (point.pauseKind !== 'time' || !point.resumeAt) continue |
| 80 | + if (point.resumeStatus && point.resumeStatus !== 'paused') continue |
| 81 | + |
| 82 | + const resumeAt = new Date(point.resumeAt) |
| 83 | + if (Number.isNaN(resumeAt.getTime())) continue |
| 84 | + |
| 85 | + if (resumeAt <= now) { |
| 86 | + duePoints.push(point) |
| 87 | + } else if (!nextRemaining || resumeAt < nextRemaining) { |
| 88 | + nextRemaining = resumeAt |
| 89 | + } |
| 90 | + } |
| 91 | + |
| 92 | + for (const point of duePoints) { |
| 93 | + const contextId = point.contextId |
| 94 | + if (!contextId) continue |
| 95 | + try { |
| 96 | + const enqueueResult = await PauseResumeManager.enqueueOrStartResume({ |
| 97 | + executionId: row.executionId, |
| 98 | + contextId, |
| 99 | + resumeInput: {}, |
| 100 | + userId, |
| 101 | + }) |
| 102 | + |
| 103 | + if (enqueueResult.status === 'starting') { |
| 104 | + PauseResumeManager.startResumeExecution({ |
| 105 | + resumeEntryId: enqueueResult.resumeEntryId, |
| 106 | + resumeExecutionId: enqueueResult.resumeExecutionId, |
| 107 | + pausedExecution: enqueueResult.pausedExecution, |
| 108 | + contextId: enqueueResult.contextId, |
| 109 | + resumeInput: enqueueResult.resumeInput, |
| 110 | + userId: enqueueResult.userId, |
| 111 | + }).catch((error) => { |
| 112 | + logger.error('Background time-pause resume failed', { |
| 113 | + executionId: row.executionId, |
| 114 | + contextId, |
| 115 | + error: toError(error).message, |
| 116 | + }) |
| 117 | + }) |
| 118 | + } |
| 119 | + dispatched++ |
| 120 | + } catch (error) { |
| 121 | + const message = toError(error).message |
| 122 | + logger.warn('Failed to dispatch time-pause resume', { |
| 123 | + executionId: row.executionId, |
| 124 | + contextId, |
| 125 | + error: message, |
| 126 | + }) |
| 127 | + failures.push({ executionId: row.executionId, contextId, error: message }) |
| 128 | + } |
| 129 | + } |
| 130 | + |
| 131 | + await db |
| 132 | + .update(pausedExecutions) |
| 133 | + .set({ nextResumeAt: nextRemaining }) |
| 134 | + .where(eq(pausedExecutions.id, row.id)) |
| 135 | + } |
| 136 | + |
| 137 | + logger.info('Time-pause resume poll completed', { |
| 138 | + requestId, |
| 139 | + claimedRows, |
| 140 | + dispatched, |
| 141 | + failureCount: failures.length, |
| 142 | + }) |
| 143 | + |
| 144 | + return NextResponse.json({ |
| 145 | + success: true, |
| 146 | + requestId, |
| 147 | + claimedRows, |
| 148 | + dispatched, |
| 149 | + failures, |
| 150 | + }) |
| 151 | + } catch (error) { |
| 152 | + const message = toError(error).message |
| 153 | + logger.error('Time-pause resume poll failed', { requestId, error: message }) |
| 154 | + return NextResponse.json({ success: false, requestId, error: message }, { status: 500 }) |
| 155 | + } finally { |
| 156 | + await releaseLock(LOCK_KEY, requestId).catch(() => {}) |
| 157 | + } |
| 158 | +}) |
0 commit comments