|
1 | 1 | import { supabase } from './supabase' |
2 | 2 |
|
| 3 | +const MAX_RUNS_PER_PROVIDER = 10 |
| 4 | +const ALLOWLISTED_IPS = ['130.41.220.17'] |
| 5 | + |
3 | 6 | type RateLimitResult = |
4 | 7 | | { allowed: true } |
5 | 8 | | { allowed: false; reason: string } |
@@ -36,23 +39,37 @@ export async function checkAndRecordRun( |
36 | 39 | // Ignore if RPC doesn't exist |
37 | 40 | } |
38 | 41 |
|
39 | | - // Attempt to insert the (ip, provider) run — UNIQUE constraint enforces the limit |
| 42 | + if (ALLOWLISTED_IPS.includes(ip)) { |
| 43 | + return { allowed: true } |
| 44 | + } |
| 45 | + |
| 46 | + // Count how many runs this IP has already made for this provider |
| 47 | + const { count, error: countError } = await supabase |
| 48 | + .from('demo_runs') |
| 49 | + .select('*', { count: 'exact', head: true }) |
| 50 | + .eq('ip', ip) |
| 51 | + .eq('provider', provider) |
| 52 | + |
| 53 | + if (countError) { |
| 54 | + console.error('[rate-limit] demo_runs count failed:', countError.message) |
| 55 | + // Fail open — don't block the user if counting breaks |
| 56 | + return { allowed: true } |
| 57 | + } |
| 58 | + |
| 59 | + if ((count ?? 0) >= MAX_RUNS_PER_PROVIDER) { |
| 60 | + return { allowed: false, reason: `Rate limit reached for provider: ${provider}` } |
| 61 | + } |
| 62 | + |
| 63 | + // Insert the run record |
40 | 64 | const { error: insertError } = await supabase.from('demo_runs').insert({ |
41 | 65 | ip, |
42 | 66 | provider, |
43 | 67 | prompt, |
44 | 68 | }) |
45 | 69 |
|
46 | | - if (!insertError) { |
47 | | - return { allowed: true } |
48 | | - } |
49 | | - |
50 | | - // Postgres unique_violation code = '23505' |
51 | | - if (insertError.code === '23505') { |
52 | | - return { allowed: false, reason: `Rate limit reached for provider: ${provider}` } |
| 70 | + if (insertError) { |
| 71 | + console.error('[rate-limit] demo_runs insert failed:', insertError.message) |
53 | 72 | } |
54 | 73 |
|
55 | | - // Any other DB error — fail open |
56 | | - console.error('[rate-limit] demo_runs insert failed:', insertError.message) |
57 | 74 | return { allowed: true } |
58 | 75 | } |
0 commit comments