// Package services holds the backend's stateful collaborators, reached // through handlers.Store. package services import ( "sync" "time" ) // RateLimiter is an in-memory sliding window per key, behind Caddy's limits. type RateLimiter struct { mu sync.Mutex attempts map[string][]time.Time max int window time.Duration lastSweep time.Time } func NewRateLimiter(max int, window time.Duration) *RateLimiter { return &RateLimiter{ attempts: make(map[string][]time.Time), max: max, window: window, } } // Allow doesn't record rejected attempts, so hammering doesn't extend a lockout. func (rl *RateLimiter) Allow(key string) bool { rl.mu.Lock() defer rl.mu.Unlock() now := time.Now() cutoff := now.Add(-rl.window) rl.sweep(now, cutoff) // Filtered in place, reusing the backing array. valid := rl.attempts[key][:0] for _, t := range rl.attempts[key] { if t.After(cutoff) { valid = append(valid, t) } } if len(valid) >= rl.max { rl.attempts[key] = valid return false } rl.attempts[key] = append(valid, now) return true } // sweep drops keys with no attempt inside the window, at most once a window, // so keys that are never seen again don't accumulate. func (rl *RateLimiter) sweep(now, cutoff time.Time) { if now.Sub(rl.lastSweep) < rl.window { return } rl.lastSweep = now for key, times := range rl.attempts { if len(times) == 0 || !times[len(times)-1].After(cutoff) { delete(rl.attempts, key) } } }