|
| 1 | +import { NextRequest, NextResponse } from 'next/server' |
| 2 | +import { nanoid } from 'nanoid' |
| 3 | +import { Logger } from '@/lib/logs/console-logger' |
| 4 | +import { pollGmailWebhooks } from '@/lib/webhooks/gmail-polling-service' |
| 5 | + |
| 6 | +const logger = new Logger('GmailPollingAPI') |
| 7 | + |
| 8 | +export const dynamic = 'force-dynamic' |
| 9 | +export const maxDuration = 300 // Allow up to 5 minutes for polling to complete |
| 10 | + |
| 11 | +interface PollingTask { |
| 12 | + promise: Promise<any> |
| 13 | + startedAt: number |
| 14 | +} |
| 15 | + |
| 16 | +const activePollingTasks = new Map<string, PollingTask>() |
| 17 | +const STALE_TASK_THRESHOLD_MS = 10 * 60 * 1000 // 10 minutes |
| 18 | + |
| 19 | +function cleanupStaleTasks() { |
| 20 | + const now = Date.now() |
| 21 | + let removedCount = 0 |
| 22 | + |
| 23 | + for (const [requestId, task] of activePollingTasks.entries()) { |
| 24 | + if (now - task.startedAt > STALE_TASK_THRESHOLD_MS) { |
| 25 | + activePollingTasks.delete(requestId) |
| 26 | + removedCount++ |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + if (removedCount > 0) { |
| 31 | + logger.info(`Cleaned up ${removedCount} stale polling tasks`) |
| 32 | + } |
| 33 | + |
| 34 | + return removedCount |
| 35 | +} |
| 36 | + |
| 37 | +export async function GET(request: NextRequest) { |
| 38 | + const requestId = nanoid() |
| 39 | + logger.info(`Gmail webhook polling triggered (${requestId})`) |
| 40 | + |
| 41 | + try { |
| 42 | + const authHeader = request.headers.get('authorization') |
| 43 | + const webhookSecret = process.env.WEBHOOK_POLLING_SECRET |
| 44 | + |
| 45 | + if (!webhookSecret) { |
| 46 | + logger.warn(`WEBHOOK_POLLING_SECRET is not set`) |
| 47 | + return new NextResponse('Configuration error: Webhook secret is not set', { status: 500 }) |
| 48 | + } |
| 49 | + |
| 50 | + if (!authHeader || authHeader !== `Bearer ${webhookSecret}`) { |
| 51 | + logger.warn(`Unauthorized access attempt to Gmail polling endpoint (${requestId})`) |
| 52 | + return new NextResponse('Unauthorized', { status: 401 }) |
| 53 | + } |
| 54 | + |
| 55 | + cleanupStaleTasks() |
| 56 | + |
| 57 | + const pollingTask: PollingTask = { |
| 58 | + promise: null as any, |
| 59 | + startedAt: Date.now(), |
| 60 | + } |
| 61 | + |
| 62 | + pollingTask.promise = pollGmailWebhooks() |
| 63 | + .then((results) => { |
| 64 | + logger.info(`Gmail polling completed successfully (${requestId})`, { |
| 65 | + userCount: results?.total || 0, |
| 66 | + successful: results?.successful || 0, |
| 67 | + failed: results?.failed || 0, |
| 68 | + }) |
| 69 | + activePollingTasks.delete(requestId) |
| 70 | + return results |
| 71 | + }) |
| 72 | + .catch((error) => { |
| 73 | + logger.error(`Error in background Gmail polling task (${requestId}):`, error) |
| 74 | + activePollingTasks.delete(requestId) |
| 75 | + throw error |
| 76 | + }) |
| 77 | + |
| 78 | + activePollingTasks.set(requestId, pollingTask) |
| 79 | + |
| 80 | + return NextResponse.json({ |
| 81 | + success: true, |
| 82 | + message: 'Gmail webhook polling started successfully', |
| 83 | + requestId, |
| 84 | + status: 'polling_started', |
| 85 | + activeTasksCount: activePollingTasks.size, |
| 86 | + }) |
| 87 | + } catch (error) { |
| 88 | + logger.error(`Error initiating Gmail webhook polling (${requestId}):`, error) |
| 89 | + |
| 90 | + return NextResponse.json( |
| 91 | + { |
| 92 | + success: false, |
| 93 | + message: 'Failed to start Gmail webhook polling', |
| 94 | + error: error instanceof Error ? error.message : 'Unknown error', |
| 95 | + requestId, |
| 96 | + }, |
| 97 | + { status: 500 } |
| 98 | + ) |
| 99 | + } |
| 100 | +} |
0 commit comments