Merge pull request 'fix(api): 公开投稿限流器定期清理过期记录 (#44)' (#54) from devin/1793407948-goods-44-submission-rate-prune into main

This commit was merged in pull request #54.
This commit is contained in:
2026-10-31 09:45:29 +08:00
2 changed files with 57 additions and 8 deletions
+22 -4
View File
@@ -12,6 +12,7 @@ type rateLimiter struct {
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
}
@@ -0,0 +1,31 @@
package adminhandler
import (
"testing"
"time"
)
func TestRateLimiterPrunesExpiredKeysAndPreservesLiveLimits(t *testing.T) {
window := time.Minute
now := time.Now()
limiter := newRateLimiter(2, window)
limiter.hits["expired"] = []time.Time{now.Add(-2 * window)}
limiter.hits["live"] = []time.Time{now.Add(-time.Second)}
limiter.lastPrune = now.Add(-2 * window)
if !limiter.allow("live") {
t.Fatal("allow rejected a live key below its limit")
}
if _, ok := limiter.hits["expired"]; ok {
t.Fatal("expired key was not pruned")
}
if got := len(limiter.hits["live"]); got != 2 {
t.Fatalf("live key hit count = %d, want 2", got)
}
if limiter.allow("live") {
t.Fatal("allow accepted a live key at its limit")
}
if got := len(limiter.hits["live"]); got != 2 {
t.Fatalf("live key hit count after rejection = %d, want 2", got)
}
}