// batch-backfill.ts import { createClient } from '@supabase/supabase-js' const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL const serviceRoleKey = process.env.SUPABASE_SERVICE_ROLE_KEY if (!supabaseUrl || !serviceRoleKey) { throw new Error('Missing NEXT_PUBLIC_SUPABASE_URL or SUPABASE_SERVICE_ROLE_KEY') } const supabase = createClient(supabaseUrl, serviceRoleKey, { auth: { persistSession: false, autoRefreshToken: false, }, }) const batchSize = Number(process.env.BATCH_SIZE ?? 1000) const pauseMs = Number(process.env.PAUSE_MS ?? 250) const maxBatches = Number(process.env.MAX_BATCHES ?? 10_000) function sleep(ms: number) { return new Promise((resolve) => setTimeout(resolve, ms)) } async function runBackfill() { let totalUpdated = 0 for (let batch = 1; batch <= maxBatches; batch += 1) { const startedAt = Date.now() const { data, error } = await supabase.rpc('backfill_profile_display_names', { batch_size: batchSize, }) if (error) { throw new Error(`Backfill failed on batch ${batch}: ${error.message}`) } const updated = Number(data ?? 0) totalUpdated += updated console.log( JSON.stringify({ batch, updated, totalUpdated, ms: Date.now() - startedAt, }), ) if (updated === 0) { console.log('Backfill complete') return } await sleep(pauseMs) } throw new Error(`Stopped after MAX_BATCHES=${maxBatches}; backfill may still be incomplete`) } runBackfill().catch((error) => { console.error(error) process.exit(1) })