|
| 1 | +import { type NextRequest, NextResponse } from "next/server"; |
| 2 | +import { requireCronAuth } from "@/lib/cron-auth"; |
| 3 | +import { |
| 4 | + archivePluginScan, |
| 5 | + PLUGIN_SCAN_QUEUE, |
| 6 | + readNextPluginScan, |
| 7 | +} from "@/lib/plugins/queue"; |
| 8 | +import { |
| 9 | + FatalScanError, |
| 10 | + markScanFailed, |
| 11 | + runPluginScan, |
| 12 | +} from "@/lib/plugins/scan"; |
| 13 | + |
| 14 | +// Vercel max for Pro / Enterprise + Fluid Compute (default since 2025) is 800s. |
| 15 | +// Source: https://vercel.com/docs/functions/configuring-functions/duration |
| 16 | +// |
| 17 | +// The `Agent.prompt` step can take 1–3 minutes for a typical plugin; the git |
| 18 | +// clone is bounded by CLONE_TIMEOUT_MS (60s) inside scan.ts. 800s gives us |
| 19 | +// generous headroom for the worst-case agent run. |
| 20 | +export const dynamic = "force-dynamic"; |
| 21 | +export const maxDuration = 800; |
| 22 | + |
| 23 | +// Visibility timeout: how long the message is invisible to other consumers |
| 24 | +// after a successful `read`. Set comfortably longer than `maxDuration` so we |
| 25 | +// can never hand the same message to a second drain invocation while the |
| 26 | +// first one is still running. |
| 27 | +const VT_SECONDS = 900; |
| 28 | + |
| 29 | +// Bury after this many delivery attempts. With per-cron `n=1` and a 1-min |
| 30 | +// schedule, this means a poisonous message stays in the queue for ~5 min |
| 31 | +// after `read_ct=1` (we only see read_ct on the next read after the VT |
| 32 | +// expires) before we mark the plugin errored and stop retrying. |
| 33 | +const MAX_ATTEMPTS = 5; |
| 34 | + |
| 35 | +function logInfo(msg: string, meta?: Record<string, unknown>) { |
| 36 | + console.log(`[scan-drain] ${msg}${meta ? ` ${JSON.stringify(meta)}` : ""}`); |
| 37 | +} |
| 38 | + |
| 39 | +function logError(msg: string, err: unknown) { |
| 40 | + const detail = |
| 41 | + err instanceof Error |
| 42 | + ? { name: err.name, message: err.message, stack: err.stack } |
| 43 | + : { value: String(err) }; |
| 44 | + console.error(`[scan-drain] ${msg}`, detail); |
| 45 | +} |
| 46 | + |
| 47 | +export async function GET(request: NextRequest) { |
| 48 | + const unauthorized = requireCronAuth(request); |
| 49 | + if (unauthorized) return unauthorized; |
| 50 | + |
| 51 | + let msg: Awaited<ReturnType<typeof readNextPluginScan>>; |
| 52 | + try { |
| 53 | + msg = await readNextPluginScan(VT_SECONDS); |
| 54 | + } catch (err) { |
| 55 | + logError("readNextPluginScan failed", err); |
| 56 | + return NextResponse.json( |
| 57 | + { ok: false, error: "queue_read_failed" }, |
| 58 | + { status: 500 }, |
| 59 | + ); |
| 60 | + } |
| 61 | + |
| 62 | + if (!msg) { |
| 63 | + return NextResponse.json({ |
| 64 | + ok: true, |
| 65 | + queue: PLUGIN_SCAN_QUEUE, |
| 66 | + drained: 0, |
| 67 | + }); |
| 68 | + } |
| 69 | + |
| 70 | + const { msg_id, read_ct, message } = msg; |
| 71 | + const pluginId = message.plugin_id; |
| 72 | + |
| 73 | + if (!pluginId || typeof pluginId !== "string") { |
| 74 | + // Malformed payload — archive it so it doesn't keep getting retried. |
| 75 | + logError( |
| 76 | + "malformed message; archiving", |
| 77 | + new Error(JSON.stringify(message)), |
| 78 | + ); |
| 79 | + await archivePluginScan(msg_id).catch((err) => |
| 80 | + logError("archive (malformed) failed", err), |
| 81 | + ); |
| 82 | + return NextResponse.json( |
| 83 | + { ok: false, archived: msg_id, reason: "malformed_message" }, |
| 84 | + { status: 200 }, |
| 85 | + ); |
| 86 | + } |
| 87 | + |
| 88 | + if (read_ct > MAX_ATTEMPTS) { |
| 89 | + logInfo("exceeded MAX_ATTEMPTS; burying", { |
| 90 | + pluginId, |
| 91 | + msg_id, |
| 92 | + read_ct, |
| 93 | + max: MAX_ATTEMPTS, |
| 94 | + }); |
| 95 | + await markScanFailed(pluginId, `Exceeded ${MAX_ATTEMPTS} scan attempts`); |
| 96 | + await archivePluginScan(msg_id); |
| 97 | + return NextResponse.json({ |
| 98 | + ok: true, |
| 99 | + buried: pluginId, |
| 100 | + msg_id, |
| 101 | + read_ct, |
| 102 | + }); |
| 103 | + } |
| 104 | + |
| 105 | + logInfo("processing", { pluginId, msg_id, read_ct }); |
| 106 | + |
| 107 | + try { |
| 108 | + await runPluginScan(pluginId); |
| 109 | + await archivePluginScan(msg_id); |
| 110 | + logInfo("scanned ok", { pluginId, msg_id }); |
| 111 | + return NextResponse.json({ ok: true, scanned: pluginId, msg_id }); |
| 112 | + } catch (err) { |
| 113 | + if (err instanceof FatalScanError) { |
| 114 | + // runPluginScan already wrote `scan_status='error'` via its compensation |
| 115 | + // path. Archive so the message doesn't get retried. |
| 116 | + logError("fatal; archiving", err); |
| 117 | + await archivePluginScan(msg_id).catch((archiveErr) => |
| 118 | + logError("archive (fatal) failed", archiveErr), |
| 119 | + ); |
| 120 | + return NextResponse.json( |
| 121 | + { |
| 122 | + ok: false, |
| 123 | + fatal: true, |
| 124 | + pluginId, |
| 125 | + msg_id, |
| 126 | + error: err.message, |
| 127 | + }, |
| 128 | + { status: 200 }, |
| 129 | + ); |
| 130 | + } |
| 131 | + |
| 132 | + // Retryable: do NOT archive. The pgmq visibility timeout (VT_SECONDS) |
| 133 | + // expires and the next cron tick re-reads the message with read_ct + 1. |
| 134 | + logError("retryable; leaving message for VT to expire", err); |
| 135 | + return NextResponse.json( |
| 136 | + { |
| 137 | + ok: false, |
| 138 | + retryable: true, |
| 139 | + pluginId, |
| 140 | + msg_id, |
| 141 | + read_ct, |
| 142 | + error: err instanceof Error ? err.message : String(err), |
| 143 | + }, |
| 144 | + { status: 500 }, |
| 145 | + ); |
| 146 | + } |
| 147 | +} |
0 commit comments