|
| 1 | +import { nanoid } from 'nanoid' |
| 2 | +import { type NextRequest, NextResponse } from 'next/server' |
| 3 | +import { verifyCronAuth } from '@/lib/auth/internal' |
| 4 | +import { acquireLock, releaseLock } from '@/lib/core/config/redis' |
| 5 | +import { createLogger } from '@/lib/logs/console/logger' |
| 6 | +import { pollRssWebhooks } from '@/lib/webhooks/rss-polling-service' |
| 7 | + |
| 8 | +const logger = createLogger('RssPollingAPI') |
| 9 | + |
| 10 | +export const dynamic = 'force-dynamic' |
| 11 | +export const maxDuration = 180 // Allow up to 3 minutes for polling to complete |
| 12 | + |
| 13 | +const LOCK_KEY = 'rss-polling-lock' |
| 14 | +const LOCK_TTL_SECONDS = 180 // Same as maxDuration (3 min) |
| 15 | + |
| 16 | +export async function GET(request: NextRequest) { |
| 17 | + const requestId = nanoid() |
| 18 | + logger.info(`RSS webhook polling triggered (${requestId})`) |
| 19 | + |
| 20 | + let lockValue: string | undefined |
| 21 | + |
| 22 | + try { |
| 23 | + const authError = verifyCronAuth(request, 'RSS webhook polling') |
| 24 | + if (authError) { |
| 25 | + return authError |
| 26 | + } |
| 27 | + |
| 28 | + lockValue = requestId |
| 29 | + const locked = await acquireLock(LOCK_KEY, lockValue, LOCK_TTL_SECONDS) |
| 30 | + |
| 31 | + if (!locked) { |
| 32 | + return NextResponse.json( |
| 33 | + { |
| 34 | + success: true, |
| 35 | + message: 'Polling already in progress – skipped', |
| 36 | + requestId, |
| 37 | + status: 'skip', |
| 38 | + }, |
| 39 | + { status: 202 } |
| 40 | + ) |
| 41 | + } |
| 42 | + |
| 43 | + const results = await pollRssWebhooks() |
| 44 | + |
| 45 | + return NextResponse.json({ |
| 46 | + success: true, |
| 47 | + message: 'RSS polling completed', |
| 48 | + requestId, |
| 49 | + status: 'completed', |
| 50 | + ...results, |
| 51 | + }) |
| 52 | + } catch (error) { |
| 53 | + logger.error(`Error during RSS polling (${requestId}):`, error) |
| 54 | + return NextResponse.json( |
| 55 | + { |
| 56 | + success: false, |
| 57 | + message: 'RSS polling failed', |
| 58 | + error: error instanceof Error ? error.message : 'Unknown error', |
| 59 | + requestId, |
| 60 | + }, |
| 61 | + { status: 500 } |
| 62 | + ) |
| 63 | + } finally { |
| 64 | + await releaseLock(LOCK_KEY).catch(() => {}) |
| 65 | + } |
| 66 | +} |
0 commit comments