fix(api): 清理投稿限流器的过期 IP 记录 (#44)

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
fu500f
2026-10-31 00:52:56 +00:00
co-authored by Devin AI
parent 36f9c95fa7
commit 31e1a8977b
2 changed files with 57 additions and 8 deletions
+26 -8
View File
@@ -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
}