various: cleanup

Fixes a status code conflict in `LimitedResponseWriter`, and a clock
skew bug that I probably introduced last time I dealt with time. I hate
computers.

We now use `tie.Since()`, which employs a monotonic clock that is immune
to system wall clock changes. 

Signed-off-by: NotAShelf <raf@notashelf.dev>
Change-Id: Iec3147c21c5a295170f48cbf1a4620596a6a6964
This commit is contained in:
raf 2026-03-10 12:57:14 +03:00
commit 7ecc03ac19
Signed by: NotAShelf
GPG key ID: 29D95B64378DB4BF
3 changed files with 79 additions and 13 deletions

View file

@ -27,13 +27,14 @@ func NewTokenBucket(capacity, refillPerInterval int, interval time.Duration) *To
}
// Allow checks if a request should be allowed
// Uses monotonic time via time.Since() to prevent clock skew issues
func (tb *TokenBucket) Allow() bool {
tb.mu.Lock()
defer tb.mu.Unlock()
// Refill tokens based on elapsed time
now := time.Now()
elapsed := now.Sub(tb.lastFill)
// Refill tokens based on elapsed time using monotonic clock
// time.Since() uses monotonic readings when available, unaffected by wall clock changes
elapsed := time.Since(tb.lastFill)
if elapsed >= tb.interval {
periods := int(elapsed / tb.interval)
tb.tokens += periods * tb.refill