Drop narration, history and restated-code comments across the repo, keep short ones for security boundaries, upstream quirks and ordering constraints, and record the convention in CLAUDE.md. Co-Authored-By: Claude Opus 5.5 <[email protected]>
51 lines
1.1 KiB
Go
51 lines
1.1 KiB
Go
// 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
|
|
// Never evicted; grows with distinct client IPs.
|
|
attempts map[string][]time.Time
|
|
max int
|
|
window time.Duration
|
|
}
|
|
|
|
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)
|
|
|
|
// 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
|
|
}
|