export const dynamic = "force-dynamic"
import type { NextRequest } from 'next/server';
import { adminDb } from '@/src/lib/firebase/admin';
import { getFirestore, QuerySnapshot } from 'firebase-admin/firestore';
export function GET(request: NextRequest) {
console.log('π€ Cron job started:', new Date().toISOString());
const authHeader = request.headers.get('authorization');
// if (authHeader !== `Bearer ${process.env.CRON_SECRET}`) {
// return new Response('Unauthorized', {
// status: 401,
// });
// }
checkAndCompleteExpiredTasks();
console.log('β
Cron job completed:', new Date().toISOString());
return Response.json({ success: true });
}
async function checkAndCompleteExpiredTasks() {
try {
const now = new Date().toISOString();
console.log('π
Checking for expired tasks at:', now);
const tasksRef = adminDb.collection('agent_tasks');
console.log('π Collection reference created');
let snapshot;
try {
snapshot = await tasksRef.where('status', '==', 'created').get();
console.log("Query executed, snapshot size:", snapshot.size);
} catch (error) {
console.error('Error fetching tasks:', error);
}
console.log("Query executed, snapshot size:", snapshot?.size)
let expiredTasks: Object[] = [];
snapshot?.forEach(doc => {
const data = doc.data();
if (data.taskFinishTime <= now) {
expiredTasks.push({
id: doc.id,
...data
});
console.log("Found expired task:", doc.id);
}
})
console.log("π Found", expiredTasks.length, "expired tasks");
if (expiredTasks.length > 0) {
const completionPromises = expiredTasks.map(async (task: any) => {
const taskId = task.id;
console.log(`β‘ Processing task ${taskId}`);
try {
const response = await fetch(
`${process.env.NEXT_PUBLIC_APP_URL}/api/agents/tasks/${taskId}/complete`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
// Add any necessary authentication headers
}
}
);
if (!response.ok) {
console.error(`β Failed to complete task ${taskId}: ${response.statusText}`);
throw new Error(`Failed to complete task ${taskId}: ${response.statusText}`);
}
console.log(`β
Successfully completed task ${taskId}`);
} catch (error) {
console.error(`β Error completing task ${taskId}:`, error);
}
});
}
console.log('π Finished processing all expired tasks');
} catch (error) {
console.error('π₯ Detailed error in checkAndCompleteExpiredTasks:', {
message: (error as Error).message,
code: (error as any).code,
stack: (error as Error).stack
});
throw error;
}
}
This code i use in nextjs and itβs accessible at /api/cron
I have this code, and it works everywhere fins, but not on Vercel. There is no any error, code just stopping execution seems on query to firebase.
Last console log message i see: console.log('π Collection reference created');
And this code does not work because I donβt see the next log.
const snapshot = await tasksRef
.where('status', '==', 'created')
.get()
On all other routes, even in Vercel, Firebase works fine.