556
Bn
bees-nest / files
bees-nest / src / app / api / queue / next / route.ts
1.2 KB
1import { desc, eq } from "drizzle-orm"; 2import { NextResponse } from "next/server"; 3import { urls } from "@/db/schema"; 4import { db } from "@/lib/db"; 5 6export const dynamic = "force-dynamic"; 7 8export async function GET() { 9 try { 10 const nextUrl = await db.transaction(async (tx) => { 11 // Find highest priority pending URL 12 // Use FOR UPDATE SKIP LOCKED to prevent race conditions with multiple workers 13 const result = await tx 14 .select() 15 .from(urls) 16 .where(eq(urls.status, "pending")) 17 .orderBy(desc(urls.priority), desc(urls.createdAt)) 18 .limit(1) 19 .for("update", { skipLocked: true }); 20 21 if (result.length === 0) return null; 22 23 const urlToProcess = result[0]; 24 25 // Update status to processing 26 await tx 27 .update(urls) 28 .set({ 29 status: "processing", 30 updatedAt: new Date(), 31 }) 32 .where(eq(urls.id, urlToProcess.id)); 33 34 return urlToProcess; 35 }); 36 37 if (!nextUrl) { 38 return NextResponse.json({ empty: true }, { status: 404 }); 39 } 40 41 return NextResponse.json(nextUrl); 42 } catch (error) { 43 console.error("Queue fetch error:", error); 44 return NextResponse.json({ error: "Queue error" }, { status: 500 }); 45 } 46}