fix(06-07): make limiter admission atomic

- Replace split store checks with one mutex-guarded Attempt operation
- Use domainless trusted-client keys for anonymous inline throttles
- Preserve fixed-window headers, expiry, stacking, and principal isolation
This commit is contained in:
Jakub Zych
2026-09-20 17:02:53 +02:00
parent 5bcd7ba011
commit 6852a8f8c3
4 changed files with 56 additions and 83 deletions

View File

@@ -5,14 +5,11 @@ import (
"time"
)
// Store mirrors Illuminate\Cache\RateLimiter's hit/tooManyAttempts/
// availableIn control flow: a fixed window, first-hit-wins (an existing
// unexpired window is never extended), with resetAttempts as a side effect
// of TooManyAttempts observing an expired window.
// Store owns fixed-window admission as one atomic operation. Attempt performs
// lazy expiry, threshold comparison, and an admitted increment together so
// concurrent callers cannot pass a split check-then-increment boundary.
type Store interface {
Hit(key string, decay time.Duration) (attempts int)
TooManyAttempts(key string, max int) bool
AvailableIn(key string) time.Duration
Attempt(key string, max int, decay time.Duration) (allowed bool, attempts int, retryAfter time.Duration)
}
type counterEntry struct {
@@ -68,48 +65,29 @@ func (s *MemoryStore) purge() {
}
}
// Hit increments key's counter, opening a decay window on first hit
// (first-hit-wins: an existing unexpired window is never extended).
func (s *MemoryStore) Hit(key string, decay time.Duration) int {
// Attempt admits and counts one request when key is below max. The first
// attempt opens the window; later attempts never extend it. A denied attempt
// leaves the exhausted count unchanged.
func (s *MemoryStore) Attempt(key string, max int, decay time.Duration) (bool, int, time.Duration) {
s.mu.Lock()
defer s.mu.Unlock()
now := time.Now()
e, ok := s.entries[key]
if !ok || now.After(e.resetAt) {
if ok && now.After(e.resetAt) {
delete(s.entries, key)
ok = false
}
if !ok {
e = &counterEntry{count: 0, resetAt: now.Add(decay)}
s.entries[key] = e
}
retryAfter := e.resetAt.Sub(now)
if retryAfter < 0 {
retryAfter = 0
}
if e.count >= max {
return false, e.count, retryAfter
}
e.count++
return e.count
}
// TooManyAttempts is true only while count >= max and the window has not
// expired. An expired window is deleted (PHP resetAttempts) and returns false.
func (s *MemoryStore) TooManyAttempts(key string, max int) bool {
s.mu.Lock()
defer s.mu.Unlock()
e, ok := s.entries[key]
if !ok {
return false
}
if time.Now().After(e.resetAt) {
delete(s.entries, key)
return false
}
return e.count >= max
}
// AvailableIn is the time until the window resets, or 0 if the key is absent.
func (s *MemoryStore) AvailableIn(key string) time.Duration {
s.mu.Lock()
defer s.mu.Unlock()
e, ok := s.entries[key]
if !ok {
return 0
}
d := e.resetAt.Sub(time.Now())
if d < 0 {
return 0
}
return d
return true, e.count, retryAfter
}