SPB Git

Repository Public

ratelimit.go 1.4 KB 60 lines go

1package httpx23import (4	"sync"5	"time"6)78// Limiter is an in-memory token bucket keyed by caller-chosen strings9// (e.g. "auth:"+ip). control-api runs as a single instance; limits are10// therefore exact. State is bounded: idle buckets are evicted.11type Limiter struct {12	mu      sync.Mutex13	rate    float64 // tokens per second14	burst   float6415	buckets map[string]*bucket16	lastGC  time.Time17	now     func() time.Time18}1920type bucket struct {21	tokens float6422	seen   time.Time23}2425// NewLimiter allows `burst` immediate events, then `perMinute` per minute.26func NewLimiter(perMinute, burst int) *Limiter {27	return &Limiter{rate: float64(perMinute) / 60, burst: float64(burst), buckets: map[string]*bucket{}, now: time.Now}28}2930// Allow consumes one token. When refused it returns the seconds to wait.31func (l *Limiter) Allow(key string) (ok bool, retryAfter int) {32	l.mu.Lock()33	defer l.mu.Unlock()34	now := l.now()35	if now.Sub(l.lastGC) > time.Minute {36		for k, b := range l.buckets {37			if now.Sub(b.seen).Seconds()*l.rate > l.burst {38				delete(l.buckets, k)39			}40		}41		l.lastGC = now42	}43	b := l.buckets[key]44	if b == nil {45		b = &bucket{tokens: l.burst, seen: now}46		l.buckets[key] = b47	}48	b.tokens += now.Sub(b.seen).Seconds() * l.rate49	if b.tokens > l.burst {50		b.tokens = l.burst51	}52	b.seen = now53	if b.tokens < 1 {54		wait := int((1-b.tokens)/l.rate) + 155		return false, wait56	}57	b.tokens--58	return true, 059}60
Files main
Menu

Theme