fix(api): 清理投稿限流器的过期 IP 记录 (#44)
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
@@ -8,10 +8,11 @@ import (
|
||||
// rateLimiter is a simple fixed-window per-key limiter used to throttle
|
||||
// anonymous public submissions (basic anti-spam; captcha can be added later).
|
||||
type rateLimiter struct {
|
||||
mu sync.Mutex
|
||||
hits map[string][]time.Time
|
||||
limit int
|
||||
window time.Duration
|
||||
mu sync.Mutex
|
||||
hits map[string][]time.Time
|
||||
limit int
|
||||
window time.Duration
|
||||
lastPrune time.Time
|
||||
}
|
||||
|
||||
func newRateLimiter(limit int, window time.Duration) *rateLimiter {
|
||||
@@ -26,12 +27,19 @@ func (r *rateLimiter) allow(key string) bool {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
|
||||
kept := r.hits[key][:0]
|
||||
for _, t := range r.hits[key] {
|
||||
if t.After(cutoff) {
|
||||
kept = append(kept, t)
|
||||
if now.Sub(r.lastPrune) > r.window {
|
||||
for expiredKey, hits := range r.hits {
|
||||
kept := pruneRateLimitHits(hits, cutoff)
|
||||
if len(kept) == 0 {
|
||||
delete(r.hits, expiredKey)
|
||||
} else {
|
||||
r.hits[expiredKey] = kept
|
||||
}
|
||||
}
|
||||
r.lastPrune = now
|
||||
}
|
||||
|
||||
kept := pruneRateLimitHits(r.hits[key], cutoff)
|
||||
if len(kept) >= r.limit {
|
||||
r.hits[key] = kept
|
||||
return false
|
||||
@@ -39,3 +47,13 @@ func (r *rateLimiter) allow(key string) bool {
|
||||
r.hits[key] = append(kept, now)
|
||||
return true
|
||||
}
|
||||
|
||||
func pruneRateLimitHits(hits []time.Time, cutoff time.Time) []time.Time {
|
||||
kept := hits[:0]
|
||||
for _, hit := range hits {
|
||||
if hit.After(cutoff) {
|
||||
kept = append(kept, hit)
|
||||
}
|
||||
}
|
||||
return kept
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user