|
| 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, asc, 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 { |
| 12 | + computeEarliestResumeAt, |
| 13 | + PauseResumeManager, |
| 14 | +} from '@/lib/workflows/executor/human-in-the-loop-manager' |
| 15 | +import type { PausePoint } from '@/executor/types' |
| 16 | + |
| 17 | +const logger = createLogger('TimePauseResumePoll') |
| 18 | + |
| 19 | +export const dynamic = 'force-dynamic' |
| 20 | +export const maxDuration = 120 |
| 21 | + |
| 22 | +const LOCK_KEY = 'time-pause-resume-poll-lock' |
| 23 | +const LOCK_TTL_SECONDS = 180 |
| 24 | +const POLL_BATCH_LIMIT = 200 |
| 25 | + |
| 26 | +interface DispatchFailure { |
| 27 | + executionId: string |
| 28 | + contextId: string |
| 29 | + error: string |
| 30 | +} |
| 31 | + |
| 32 | +interface RowResult { |
| 33 | + dispatched: number |
| 34 | + failures: DispatchFailure[] |
| 35 | +} |
| 36 | + |
| 37 | +export const GET = withRouteHandler(async (request: NextRequest) => { |
| 38 | + const requestId = generateShortId() |
| 39 | + |
| 40 | + const authError = verifyCronAuth(request, 'Time-pause resume poll') |
| 41 | + if (authError) return authError |
| 42 | + |
| 43 | + const lockAcquired = await acquireLock(LOCK_KEY, requestId, LOCK_TTL_SECONDS) |
| 44 | + if (!lockAcquired) { |
| 45 | + return NextResponse.json( |
| 46 | + { success: true, message: 'Polling already in progress – skipped', requestId }, |
| 47 | + { status: 202 } |
| 48 | + ) |
| 49 | + } |
| 50 | + |
| 51 | + try { |
| 52 | + const now = new Date() |
| 53 | + |
| 54 | + const dueRows = await db |
| 55 | + .select({ |
| 56 | + id: pausedExecutions.id, |
| 57 | + executionId: pausedExecutions.executionId, |
| 58 | + workflowId: pausedExecutions.workflowId, |
| 59 | + pausePoints: pausedExecutions.pausePoints, |
| 60 | + metadata: pausedExecutions.metadata, |
| 61 | + }) |
| 62 | + .from(pausedExecutions) |
| 63 | + .where( |
| 64 | + and( |
| 65 | + eq(pausedExecutions.status, 'paused'), |
| 66 | + isNotNull(pausedExecutions.nextResumeAt), |
| 67 | + lte(pausedExecutions.nextResumeAt, now) |
| 68 | + ) |
| 69 | + ) |
| 70 | + .orderBy(asc(pausedExecutions.nextResumeAt)) |
| 71 | + .limit(POLL_BATCH_LIMIT) |
| 72 | + |
| 73 | + const results = await Promise.all(dueRows.map((row) => dispatchRow(row, now))) |
| 74 | + const dispatched = results.reduce((sum, r) => sum + r.dispatched, 0) |
| 75 | + const failures = results.flatMap((r) => r.failures) |
| 76 | + |
| 77 | + logger.info('Time-pause resume poll completed', { |
| 78 | + requestId, |
| 79 | + claimedRows: dueRows.length, |
| 80 | + dispatched, |
| 81 | + failureCount: failures.length, |
| 82 | + }) |
| 83 | + |
| 84 | + return NextResponse.json({ |
| 85 | + success: true, |
| 86 | + requestId, |
| 87 | + claimedRows: dueRows.length, |
| 88 | + dispatched, |
| 89 | + failures, |
| 90 | + }) |
| 91 | + } catch (error) { |
| 92 | + const message = toError(error).message |
| 93 | + logger.error('Time-pause resume poll failed', { requestId, error: message }) |
| 94 | + return NextResponse.json({ success: false, requestId, error: message }, { status: 500 }) |
| 95 | + } finally { |
| 96 | + await releaseLock(LOCK_KEY, requestId).catch(() => {}) |
| 97 | + } |
| 98 | +}) |
| 99 | + |
| 100 | +interface DueRow { |
| 101 | + id: string |
| 102 | + executionId: string |
| 103 | + workflowId: string |
| 104 | + pausePoints: unknown |
| 105 | + metadata: unknown |
| 106 | +} |
| 107 | + |
| 108 | +async function dispatchRow(row: DueRow, now: Date): Promise<RowResult> { |
| 109 | + const points = (row.pausePoints ?? {}) as Record<string, PausePoint> |
| 110 | + const metadata = (row.metadata ?? {}) as Record<string, unknown> |
| 111 | + const userId = typeof metadata.executorUserId === 'string' ? metadata.executorUserId : '' |
| 112 | + |
| 113 | + const eligiblePoints = Object.values(points).filter( |
| 114 | + (point) => |
| 115 | + point.pauseKind === 'time' && (!point.resumeStatus || point.resumeStatus === 'paused') |
| 116 | + ) |
| 117 | + const duePoints = eligiblePoints.filter((point) => { |
| 118 | + if (!point.resumeAt) return false |
| 119 | + const at = new Date(point.resumeAt) |
| 120 | + return !Number.isNaN(at.getTime()) && at <= now |
| 121 | + }) |
| 122 | + |
| 123 | + const failures: DispatchFailure[] = [] |
| 124 | + let dispatched = 0 |
| 125 | + |
| 126 | + for (const point of duePoints) { |
| 127 | + if (!point.contextId) continue |
| 128 | + try { |
| 129 | + const enqueueResult = await PauseResumeManager.enqueueOrStartResume({ |
| 130 | + executionId: row.executionId, |
| 131 | + contextId: point.contextId, |
| 132 | + resumeInput: {}, |
| 133 | + userId, |
| 134 | + allowedPauseKinds: ['time'], |
| 135 | + }) |
| 136 | + |
| 137 | + if (enqueueResult.status === 'starting') { |
| 138 | + PauseResumeManager.startResumeExecution({ |
| 139 | + resumeEntryId: enqueueResult.resumeEntryId, |
| 140 | + resumeExecutionId: enqueueResult.resumeExecutionId, |
| 141 | + pausedExecution: enqueueResult.pausedExecution, |
| 142 | + contextId: enqueueResult.contextId, |
| 143 | + resumeInput: enqueueResult.resumeInput, |
| 144 | + userId: enqueueResult.userId, |
| 145 | + }).catch((error) => { |
| 146 | + logger.error('Background time-pause resume failed', { |
| 147 | + executionId: row.executionId, |
| 148 | + contextId: point.contextId, |
| 149 | + error: toError(error).message, |
| 150 | + }) |
| 151 | + }) |
| 152 | + } |
| 153 | + dispatched++ |
| 154 | + } catch (error) { |
| 155 | + const message = toError(error).message |
| 156 | + logger.warn('Failed to dispatch time-pause resume', { |
| 157 | + executionId: row.executionId, |
| 158 | + contextId: point.contextId, |
| 159 | + error: message, |
| 160 | + }) |
| 161 | + failures.push({ executionId: row.executionId, contextId: point.contextId, error: message }) |
| 162 | + } |
| 163 | + } |
| 164 | + |
| 165 | + // We never auto-retry a failed dispatch: workflow blocks aren't idempotent, and |
| 166 | + // an operator must investigate stranded rows by hand. The status='paused' guard |
| 167 | + // also prevents clobbering when a concurrent manual resume has already advanced |
| 168 | + // the row's state since we read it. |
| 169 | + await PauseResumeManager.setNextResumeAt({ |
| 170 | + pausedExecutionId: row.id, |
| 171 | + nextResumeAt: computeEarliestResumeAt(eligiblePoints, { after: now }), |
| 172 | + }) |
| 173 | + |
| 174 | + return { dispatched, failures } |
| 175 | +} |
0 commit comments