Skip to content

Commit 1a33772

Browse files
committed
adjust rate limit
1 parent 50331da commit 1a33772

1 file changed

Lines changed: 27 additions & 10 deletions

File tree

lib/server/rate-limit.ts

Lines changed: 27 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
import { supabase } from './supabase'
22

3+
const MAX_RUNS_PER_PROVIDER = 10
4+
const ALLOWLISTED_IPS = ['130.41.220.17']
5+
36
type RateLimitResult =
47
| { allowed: true }
58
| { allowed: false; reason: string }
@@ -36,23 +39,37 @@ export async function checkAndRecordRun(
3639
// Ignore if RPC doesn't exist
3740
}
3841

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
4064
const { error: insertError } = await supabase.from('demo_runs').insert({
4165
ip,
4266
provider,
4367
prompt,
4468
})
4569

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)
5372
}
5473

55-
// Any other DB error — fail open
56-
console.error('[rate-limit] demo_runs insert failed:', insertError.message)
5774
return { allowed: true }
5875
}

0 commit comments

Comments
 (0)