Files
mtusi2026lab3/internal/admission/limiter.go
T

74 lines
2.0 KiB
Go

// Package admission bounds request rate and concurrent execution independently of transport.
package admission
import (
"fmt"
"sync"
"time"
)
// Options defines the rate and execution bounds for one limiter.
type Options struct {
// MaxInFlight limits concurrent executions without an admission queue.
MaxInFlight int
// RequestsPerSecond is the token refill rate.
RequestsPerSecond int
// Burst is the maximum number of immediately available tokens.
Burst int
}
// Limiter owns synchronization for the token bucket and execution slots.
// It knows neither HTTP response codes nor application shutdown state.
type Limiter struct {
mu sync.Mutex
rate float64
burst float64
tokens float64
lastRefill time.Time
slots chan struct{}
}
// New validates limits and creates a full token bucket with bounded execution slots.
func New(cfg Options) (*Limiter, error) {
if cfg.MaxInFlight <= 0 || cfg.RequestsPerSecond <= 0 || cfg.Burst <= 0 {
return nil, fmt.Errorf("admission limits must be positive")
}
return &Limiter{
rate: float64(cfg.RequestsPerSecond),
burst: float64(cfg.Burst),
tokens: float64(cfg.Burst),
lastRefill: time.Now(),
slots: make(chan struct{}, cfg.MaxInFlight),
}, nil
}
// Allow refills the token bucket and consumes a token when one is available.
func (limiter *Limiter) Allow(now time.Time) bool {
limiter.mu.Lock()
defer limiter.mu.Unlock()
elapsed := max(0, now.Sub(limiter.lastRefill).Seconds())
limiter.tokens = min(limiter.burst, limiter.tokens+elapsed*limiter.rate)
limiter.lastRefill = now
if limiter.tokens < 1 {
return false
}
limiter.tokens--
return true
}
// Acquire reserves an execution slot without waiting.
func (limiter *Limiter) Acquire() bool {
select {
case limiter.slots <- struct{}{}:
return true
default:
return false
}
}
// Release returns an execution slot previously reserved by Acquire.
// Each successful Acquire must be paired with exactly one Release.
func (limiter *Limiter) Release() {
<-limiter.slots
}