|
1 | 1 | import { supabase } from './client'; |
2 | 2 |
|
3 | | -export const uploadFile = async (file: File, path: string, retries = 3) => { |
4 | | - let lastError: any; |
5 | | - |
6 | | - for (let attempt = 0; attempt < retries; attempt++) { |
7 | | - try { |
8 | | - // 1. Upload file to 'files' bucket (ensure this bucket exists in Supabase or change name) |
9 | | - const { data, error } = await supabase.storage |
| 3 | +const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); |
| 4 | + |
| 5 | +const isDuplicateError = (message: string) => { |
| 6 | + const lower = message.toLowerCase(); |
| 7 | + return lower.includes('already exists') || lower.includes('duplicate'); |
| 8 | +}; |
| 9 | + |
| 10 | +const isTransientUploadError = (error: unknown) => { |
| 11 | + const status = |
| 12 | + typeof error === 'object' && error !== null |
| 13 | + ? (error as { status?: number; statusCode?: number }).status ?? |
| 14 | + (error as { statusCode?: number }).statusCode |
| 15 | + : undefined; |
| 16 | + |
| 17 | + if (typeof status === 'number' && [408, 425, 429, 500, 502, 503, 504].includes(status)) { |
| 18 | + return true; |
| 19 | + } |
| 20 | + |
| 21 | + const message = |
| 22 | + typeof error === 'object' && error !== null && 'message' in error |
| 23 | + ? String((error as { message?: string }).message ?? '').toLowerCase() |
| 24 | + : String(error ?? '').toLowerCase(); |
| 25 | + |
| 26 | + return [ |
| 27 | + 'paused', |
| 28 | + 'waking', |
| 29 | + 'wake up', |
| 30 | + 'temporarily unavailable', |
| 31 | + 'gateway timeout', |
| 32 | + 'network', |
| 33 | + 'fetch failed', |
| 34 | + 'timeout', |
| 35 | + 'connection', |
| 36 | + ].some((token) => message.includes(token)); |
| 37 | +}; |
| 38 | + |
| 39 | +const wakeSupabaseProject = async () => { |
| 40 | + const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL; |
| 41 | + if (!supabaseUrl) return; |
| 42 | + |
| 43 | + const healthUrl = `${supabaseUrl.replace(/\/$/, '')}/auth/v1/health`; |
| 44 | + |
| 45 | + try { |
| 46 | + await fetch(healthUrl, { method: 'GET', cache: 'no-store' }); |
| 47 | + } catch (error) { |
| 48 | + console.warn('Supabase wake ping failed:', error); |
| 49 | + } |
| 50 | +}; |
| 51 | + |
| 52 | +const attemptUpload = async (file: File, path: string) => { |
| 53 | + const { error } = await supabase.storage |
| 54 | + .from('files') |
| 55 | + .upload(path, file, { |
| 56 | + cacheControl: '3600', |
| 57 | + upsert: false, |
| 58 | + contentType: file.type || 'application/octet-stream', |
| 59 | + }); |
| 60 | + |
| 61 | + if (error) { |
| 62 | + if (isDuplicateError(error.message || '')) { |
| 63 | + const { error: upsertError } = await supabase.storage |
10 | 64 | .from('files') |
11 | 65 | .upload(path, file, { |
12 | 66 | cacheControl: '3600', |
13 | | - upsert: false, |
| 67 | + upsert: true, |
14 | 68 | contentType: file.type || 'application/octet-stream', |
15 | 69 | }); |
16 | 70 |
|
17 | | - if (error) { |
18 | | - console.error(`Supabase upload error (attempt ${attempt + 1}/${retries}):`, error); |
19 | | - lastError = error; |
20 | | - |
21 | | - // If it's a duplicate file error, try with upsert |
22 | | - if (error.message?.includes('already exists') || error.message?.includes('duplicate')) { |
23 | | - const { data: upsertData, error: upsertError } = await supabase.storage |
24 | | - .from('files') |
25 | | - .upload(path, file, { |
26 | | - cacheControl: '3600', |
27 | | - upsert: true, |
28 | | - contentType: file.type || 'application/octet-stream', |
29 | | - }); |
30 | | - |
31 | | - if (upsertError) { |
32 | | - throw new Error(`Upload failed: ${upsertError.message}`); |
33 | | - } |
34 | | - |
35 | | - // Success with upsert |
36 | | - const { data: publicUrlData } = supabase.storage |
37 | | - .from('files') |
38 | | - .getPublicUrl(path); |
39 | | - return publicUrlData.publicUrl; |
40 | | - } |
41 | | - |
42 | | - // Retry on network errors |
43 | | - if (attempt < retries - 1) { |
44 | | - await new Promise(resolve => setTimeout(resolve, 1000 * (attempt + 1))); |
45 | | - continue; |
46 | | - } |
47 | | - |
48 | | - throw new Error(`Upload failed: ${error.message || 'Unknown error'}`); |
| 71 | + if (upsertError) { |
| 72 | + throw new Error(`Upload failed: ${upsertError.message}`); |
49 | 73 | } |
| 74 | + } else { |
| 75 | + throw error; |
| 76 | + } |
| 77 | + } |
50 | 78 |
|
51 | | - // 2. Get Public URL |
52 | | - const { data: publicUrlData } = supabase.storage |
53 | | - .from('files') |
54 | | - .getPublicUrl(path); |
55 | | - |
56 | | - return publicUrlData.publicUrl; |
57 | | - } catch (err: any) { |
58 | | - lastError = err; |
59 | | - if (attempt < retries - 1) { |
60 | | - console.log(`Retrying upload for ${path} (attempt ${attempt + 2}/${retries})`); |
61 | | - await new Promise(resolve => setTimeout(resolve, 1000 * (attempt + 1))); |
| 79 | + const { data: publicUrlData } = supabase.storage |
| 80 | + .from('files') |
| 81 | + .getPublicUrl(path); |
| 82 | + |
| 83 | + return publicUrlData.publicUrl; |
| 84 | +}; |
| 85 | + |
| 86 | +export const uploadFile = async (file: File, path: string, retries = 4) => { |
| 87 | + let lastError: unknown; |
| 88 | + |
| 89 | + await wakeSupabaseProject(); |
| 90 | + |
| 91 | + for (let attempt = 0; attempt < retries; attempt++) { |
| 92 | + try { |
| 93 | + return await attemptUpload(file, path); |
| 94 | + } catch (error) { |
| 95 | + lastError = error; |
| 96 | + const shouldRetry = attempt < retries - 1; |
| 97 | + |
| 98 | + if (!shouldRetry) { |
| 99 | + break; |
62 | 100 | } |
| 101 | + |
| 102 | + const transient = isTransientUploadError(error); |
| 103 | + const retryDelayMs = transient |
| 104 | + ? Math.min(30000, 5000 * (attempt + 1)) |
| 105 | + : 1000 * (attempt + 1); |
| 106 | + |
| 107 | + if (transient) { |
| 108 | + await wakeSupabaseProject(); |
| 109 | + } |
| 110 | + |
| 111 | + console.warn( |
| 112 | + `Supabase upload retry ${attempt + 1}/${retries - 1} for ${path} in ${retryDelayMs}ms:`, |
| 113 | + error |
| 114 | + ); |
| 115 | + await delay(retryDelayMs); |
63 | 116 | } |
64 | 117 | } |
65 | | - |
66 | | - throw lastError || new Error('Upload failed after retries'); |
| 118 | + |
| 119 | + const finalMessage = |
| 120 | + typeof lastError === 'object' && lastError !== null && 'message' in lastError |
| 121 | + ? String((lastError as { message?: string }).message ?? 'Unknown error') |
| 122 | + : 'Unknown error'; |
| 123 | + |
| 124 | + throw new Error(`Upload failed after retries: ${finalMessage}`); |
67 | 125 | }; |
68 | 126 |
|
69 | 127 | export const deleteFile = async (path: string) => { |
|
0 commit comments