|
| 1 | +import { randomUUID } from 'crypto' |
| 2 | +import { createLogger } from '@sim/logger' |
| 3 | +import { NextResponse } from 'next/server' |
| 4 | + |
| 5 | +const logger = createLogger('BrightDataDatasetAPI') |
| 6 | + |
| 7 | +export const maxDuration = 600 |
| 8 | + |
| 9 | +export async function POST(request: Request) { |
| 10 | + const requestId = randomUUID().slice(0, 8) |
| 11 | + |
| 12 | + try { |
| 13 | + const body = await request.json() |
| 14 | + const datasetId = typeof body?.datasetId === 'string' ? body.datasetId : undefined |
| 15 | + const apiToken = typeof body?.apiToken === 'string' ? body.apiToken : undefined |
| 16 | + |
| 17 | + if (!datasetId || !apiToken) { |
| 18 | + return NextResponse.json({ error: 'Missing required parameters' }, { status: 400 }) |
| 19 | + } |
| 20 | + |
| 21 | + const params: Record<string, unknown> = { ...body } |
| 22 | + delete params.datasetId |
| 23 | + delete params.apiToken |
| 24 | + |
| 25 | + logger.info(`[${requestId}] Triggering dataset`, { datasetId }) |
| 26 | + |
| 27 | + const triggerResponse = await fetch( |
| 28 | + `https://api.brightdata.com/datasets/v3/trigger?dataset_id=${encodeURIComponent( |
| 29 | + datasetId |
| 30 | + )}&include_errors=true`, |
| 31 | + { |
| 32 | + method: 'POST', |
| 33 | + headers: { |
| 34 | + Authorization: `Bearer ${apiToken}`, |
| 35 | + 'Content-Type': 'application/json', |
| 36 | + }, |
| 37 | + body: JSON.stringify([params]), |
| 38 | + } |
| 39 | + ) |
| 40 | + |
| 41 | + const triggerText = await triggerResponse.text() |
| 42 | + let triggerPayload: unknown = triggerText |
| 43 | + |
| 44 | + try { |
| 45 | + triggerPayload = JSON.parse(triggerText) |
| 46 | + } catch { |
| 47 | + triggerPayload = triggerText |
| 48 | + } |
| 49 | + |
| 50 | + if (!triggerResponse.ok) { |
| 51 | + const errorMessage = |
| 52 | + typeof triggerPayload === 'object' && triggerPayload !== null && 'error' in triggerPayload |
| 53 | + ? String((triggerPayload as { error?: unknown }).error) |
| 54 | + : triggerResponse.statusText |
| 55 | + |
| 56 | + logger.error(`[${requestId}] Dataset trigger failed`, { |
| 57 | + datasetId, |
| 58 | + status: triggerResponse.status, |
| 59 | + error: errorMessage, |
| 60 | + }) |
| 61 | + |
| 62 | + return NextResponse.json( |
| 63 | + { error: errorMessage || 'Dataset trigger failed' }, |
| 64 | + { status: triggerResponse.status } |
| 65 | + ) |
| 66 | + } |
| 67 | + |
| 68 | + const snapshotId = |
| 69 | + typeof triggerPayload === 'object' && triggerPayload !== null && 'snapshot_id' in triggerPayload |
| 70 | + ? String((triggerPayload as { snapshot_id?: unknown }).snapshot_id ?? '') |
| 71 | + : '' |
| 72 | + |
| 73 | + if (!snapshotId) { |
| 74 | + logger.error(`[${requestId}] Dataset trigger missing snapshot ID`, { datasetId }) |
| 75 | + return NextResponse.json({ error: 'No snapshot ID returned from request' }, { status: 500 }) |
| 76 | + } |
| 77 | + |
| 78 | + logger.info(`[${requestId}] Dataset triggered`, { datasetId, snapshotId }) |
| 79 | + |
| 80 | + const maxAttempts = 600 |
| 81 | + let attempts = 0 |
| 82 | + |
| 83 | + while (attempts < maxAttempts) { |
| 84 | + const snapshotResponse = await fetch( |
| 85 | + `https://api.brightdata.com/datasets/v3/snapshot/${snapshotId}?format=json`, |
| 86 | + { |
| 87 | + method: 'GET', |
| 88 | + headers: { |
| 89 | + Authorization: `Bearer ${apiToken}`, |
| 90 | + 'Content-Type': 'application/json', |
| 91 | + }, |
| 92 | + } |
| 93 | + ) |
| 94 | + |
| 95 | + const snapshotText = await snapshotResponse.text() |
| 96 | + let snapshotPayload: unknown = snapshotText |
| 97 | + |
| 98 | + try { |
| 99 | + snapshotPayload = JSON.parse(snapshotText) |
| 100 | + } catch { |
| 101 | + snapshotPayload = snapshotText |
| 102 | + } |
| 103 | + |
| 104 | + if (!snapshotResponse.ok) { |
| 105 | + if (snapshotResponse.status === 400) { |
| 106 | + const errorMessage = |
| 107 | + typeof snapshotPayload === 'object' && |
| 108 | + snapshotPayload !== null && |
| 109 | + 'error' in snapshotPayload |
| 110 | + ? String((snapshotPayload as { error?: unknown }).error) |
| 111 | + : snapshotResponse.statusText |
| 112 | + |
| 113 | + logger.error(`[${requestId}] Dataset snapshot fetch failed`, { |
| 114 | + datasetId, |
| 115 | + snapshotId, |
| 116 | + status: snapshotResponse.status, |
| 117 | + error: errorMessage, |
| 118 | + }) |
| 119 | + |
| 120 | + return NextResponse.json( |
| 121 | + { error: errorMessage || 'Dataset snapshot fetch failed' }, |
| 122 | + { status: snapshotResponse.status } |
| 123 | + ) |
| 124 | + } |
| 125 | + |
| 126 | + attempts += 1 |
| 127 | + await new Promise((resolve) => setTimeout(resolve, 1000)) |
| 128 | + continue |
| 129 | + } |
| 130 | + |
| 131 | + const status = |
| 132 | + typeof snapshotPayload === 'object' && snapshotPayload !== null && 'status' in snapshotPayload |
| 133 | + ? String((snapshotPayload as { status?: unknown }).status ?? '') |
| 134 | + : '' |
| 135 | + |
| 136 | + if (['running', 'building', 'starting'].includes(status)) { |
| 137 | + attempts += 1 |
| 138 | + await new Promise((resolve) => setTimeout(resolve, 1000)) |
| 139 | + continue |
| 140 | + } |
| 141 | + |
| 142 | + const snapshotAt = |
| 143 | + typeof snapshotPayload === 'object' && |
| 144 | + snapshotPayload !== null && |
| 145 | + 'snapshot_at' in snapshotPayload |
| 146 | + ? String((snapshotPayload as { snapshot_at?: unknown }).snapshot_at ?? '') |
| 147 | + : undefined |
| 148 | + |
| 149 | + logger.info(`[${requestId}] Dataset snapshot received`, { datasetId, snapshotId }) |
| 150 | + |
| 151 | + return NextResponse.json({ |
| 152 | + data: snapshotPayload, |
| 153 | + snapshot_at: snapshotAt || undefined, |
| 154 | + }) |
| 155 | + } |
| 156 | + |
| 157 | + logger.error(`[${requestId}] Dataset snapshot timed out`, { datasetId, snapshotId }) |
| 158 | + return NextResponse.json( |
| 159 | + { error: 'Timeout waiting for dataset snapshot' }, |
| 160 | + { status: 504 } |
| 161 | + ) |
| 162 | + } catch (error) { |
| 163 | + const message = error instanceof Error ? error.message : 'Dataset fetch failed' |
| 164 | + logger.error(`[${requestId}] Dataset fetch failed`, { error: message }) |
| 165 | + return NextResponse.json({ error: message }, { status: 500 }) |
| 166 | + } |
| 167 | +} |
0 commit comments