Fix rate limiting: handle Redis unavailability gracefully to prevent email failures
This commit is contained in:
parent
788ce88288
commit
265b439449
1 changed files with 28 additions and 16 deletions
|
|
@ -39,24 +39,36 @@ export class RateLimit {
|
||||||
}
|
}
|
||||||
|
|
||||||
async check(config: RateLimitConfig): Promise<RateLimitResult> {
|
async check(config: RateLimitConfig): Promise<RateLimitResult> {
|
||||||
const ip = await this.getIP()
|
try {
|
||||||
const key = this.getKey(ip)
|
const ip = await this.getIP()
|
||||||
const now = Math.floor(Date.now() / 1000)
|
const key = this.getKey(ip)
|
||||||
const windowStart = now - (now % config.interval)
|
const now = Math.floor(Date.now() / 1000)
|
||||||
const windowKey = `${key}:${windowStart}`
|
const windowStart = now - (now % config.interval)
|
||||||
|
const windowKey = `${key}:${windowStart}`
|
||||||
|
|
||||||
const pipeline = this.redis.pipeline()
|
const pipeline = this.redis.pipeline()
|
||||||
pipeline.incr(windowKey)
|
pipeline.incr(windowKey)
|
||||||
pipeline.expire(windowKey, config.interval)
|
pipeline.expire(windowKey, config.interval)
|
||||||
|
|
||||||
const [count] = await pipeline.exec()
|
const [count] = await pipeline.exec()
|
||||||
const remaining = Math.max(0, config.limit - (count as number))
|
const remaining = Math.max(0, config.limit - (count as number))
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: (count as number) <= config.limit,
|
success: (count as number) <= config.limit,
|
||||||
limit: config.limit,
|
limit: config.limit,
|
||||||
remaining,
|
remaining,
|
||||||
reset: windowStart + config.interval
|
reset: windowStart + config.interval
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.warn('Redis unavailable, allowing request (rate limiting disabled):', error)
|
||||||
|
// Fallback: allow the request when Redis is unavailable
|
||||||
|
// TODO: Fix Redis connection or create new instance
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
limit: config.limit,
|
||||||
|
remaining: config.limit - 1,
|
||||||
|
reset: Math.floor(Date.now() / 1000) + config.interval
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue