177 lines
5.2 KiB
TypeScript
177 lines
5.2 KiB
TypeScript
import { NextResponse } from 'next/server';
|
|
import { getDb } from '@/lib/db';
|
|
import { polls } from '@/lib/db/schema';
|
|
import { eq, and, lt } from 'drizzle-orm';
|
|
import { verifyPoll, VerificationResult } from '@/lib/oracle';
|
|
import { markPollVerified, getPollsPendingVerification, logVerificationAttempt } from '@/lib/db/polls';
|
|
|
|
interface CronRunLog {
|
|
timestamp: number;
|
|
runId: string;
|
|
processedPolls: number;
|
|
successfulVerifications: number;
|
|
failedVerifications: number;
|
|
errors: string[];
|
|
}
|
|
|
|
function generateRunId(): string {
|
|
return `verify-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
|
|
}
|
|
|
|
function logCronRun(log: CronRunLog) {
|
|
console.log(`[${log.timestamp}] Cron Verification Run ${log.runId}:`, {
|
|
processed: log.processedPolls,
|
|
successful: log.successfulVerifications,
|
|
failed: log.failedVerifications,
|
|
errors: log.errors
|
|
});
|
|
|
|
// In production, you would send this to your logging service
|
|
if (process.env.NODE_ENV === 'production') {
|
|
// Send to monitoring service (e.g., DataDog, New Relic, etc.)
|
|
}
|
|
}
|
|
|
|
export async function GET(request: Request) {
|
|
const runId = generateRunId();
|
|
const startTime = Date.now();
|
|
const log: CronRunLog = {
|
|
timestamp: startTime,
|
|
runId,
|
|
processedPolls: 0,
|
|
successfulVerifications: 0,
|
|
failedVerifications: 0,
|
|
errors: []
|
|
};
|
|
|
|
try {
|
|
// Security: Verify cron secret
|
|
const cronSecret = process.env.CRON_SECRET;
|
|
if (cronSecret) {
|
|
const authHeader = request.headers.get('Authorization');
|
|
const expectedAuth = `Bearer ${cronSecret}`;
|
|
|
|
if (authHeader !== expectedAuth) {
|
|
console.warn(`[${runId}] Unauthorized cron attempt from ${request.headers.get('user-agent')}`);
|
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
|
}
|
|
}
|
|
|
|
console.log(`[${runId}] Starting verification cron job...`);
|
|
|
|
const db = getDb(process.env.DATABASE_URL!);
|
|
|
|
// Get polls that need verification (closed but not verified)
|
|
const now = Date.now();
|
|
const pollsToVerify = await db.select()
|
|
.from(polls)
|
|
.where(and(
|
|
eq(polls.status, 'active'),
|
|
lt(polls.endTime, now)
|
|
))
|
|
.limit(50); // Process max 50 polls per run
|
|
|
|
log.processedPolls = pollsToVerify.length;
|
|
console.log(`[${runId}] Found ${pollsToVerify.length} polls to verify`);
|
|
|
|
for (const poll of pollsToVerify) {
|
|
try {
|
|
console.log(`[${runId}] Verifying poll ${poll.id}: ${poll.question}`);
|
|
|
|
// Get poll options
|
|
const { getPollById } = await import('@/lib/db/polls');
|
|
const fullPoll = await getPollById(poll.id);
|
|
|
|
if (!fullPoll) {
|
|
throw new Error(`Poll ${poll.id} not found`);
|
|
}
|
|
|
|
// Perform verification
|
|
const verificationResult: VerificationResult = await verifyPoll(
|
|
poll.id,
|
|
fullPoll.options,
|
|
{
|
|
verificationType: poll.verificationType as any,
|
|
verificationConfig: poll.verificationConfig as any
|
|
},
|
|
poll.endTime
|
|
);
|
|
|
|
if (verificationResult.success && verificationResult.correctOptionId) {
|
|
// Mark poll as verified
|
|
await markPollVerified(
|
|
poll.id,
|
|
verificationResult.correctOptionId,
|
|
verificationResult.proof
|
|
);
|
|
|
|
log.successfulVerifications++;
|
|
console.log(`[${runId}] ✅ Poll ${poll.id} verified: option ${verificationResult.correctOptionId}`);
|
|
} else {
|
|
// Mark poll as closed (manual verification needed)
|
|
await db.update(polls)
|
|
.set({ status: 'closed' })
|
|
.where(eq(polls.id, poll.id));
|
|
|
|
log.failedVerifications++;
|
|
console.log(`[${runId}] ⚠️ Poll ${poll.id} marked for manual verification: ${verificationResult.error}`);
|
|
}
|
|
|
|
// Log verification attempt
|
|
await logVerificationAttempt(
|
|
poll.id,
|
|
verificationResult.success,
|
|
verificationResult,
|
|
verificationResult.error
|
|
);
|
|
|
|
} catch (error) {
|
|
const errorMsg = `Failed to verify poll ${poll.id}: ${error}`;
|
|
log.errors.push(errorMsg);
|
|
log.failedVerifications++;
|
|
console.error(`[${runId}] ${errorMsg}`);
|
|
|
|
// Log the error for debugging
|
|
await logVerificationAttempt(
|
|
poll.id,
|
|
false,
|
|
null,
|
|
error instanceof Error ? error.message : String(error)
|
|
);
|
|
}
|
|
}
|
|
|
|
const duration = Date.now() - startTime;
|
|
console.log(`[${runId}] Verification cron completed in ${duration}ms`);
|
|
|
|
logCronRun(log);
|
|
|
|
return NextResponse.json({
|
|
success: true,
|
|
duration,
|
|
...log
|
|
});
|
|
|
|
} catch (error) {
|
|
const errorMsg = `Critical error in verification cron: ${error}`;
|
|
log.errors.push(errorMsg);
|
|
logCronRun(log);
|
|
|
|
console.error(`[${runId}] ${errorMsg}`);
|
|
|
|
// In production, you would alert on critical failures
|
|
if (process.env.NODE_ENV === 'production') {
|
|
// Send critical alert (email, Slack, etc.)
|
|
}
|
|
|
|
return NextResponse.json(
|
|
{
|
|
error: 'Internal server error',
|
|
runId,
|
|
errors: log.errors
|
|
},
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|