Mining/pkg/mining/ratelimiter.go
Claude 6bc7812514
Some checks are pending
Security Scan / security (push) Waiting to run
Test / test (push) Waiting to run
ax(mining): replace prose comments with usage examples in ratelimiter.go
All four exported function comments in ratelimiter.go were prose
descriptions that restate the signature (AX Principle 2 violation).
Replaced with concrete usage examples showing realistic call sites.

Co-Authored-By: Charon <charon@lethean.io>
2026-04-02 08:18:40 +01:00

120 lines
2.5 KiB
Go

package mining
import (
"net/http"
"sync"
"time"
"github.com/gin-gonic/gin"
)
// RateLimiter provides token bucket rate limiting per IP address
type RateLimiter struct {
requestsPerSecond int
burst int
clients map[string]*rateLimitClient
mu sync.RWMutex
stopChan chan struct{}
stopped bool
}
type rateLimitClient struct {
tokens float64
lastCheck time.Time
}
// rl := NewRateLimiter(10, 20) // 10 requests/second, burst of 20
// defer rl.Stop()
func NewRateLimiter(requestsPerSecond, burst int) *RateLimiter {
rl := &RateLimiter{
requestsPerSecond: requestsPerSecond,
burst: burst,
clients: make(map[string]*rateLimitClient),
stopChan: make(chan struct{}),
}
// Start cleanup goroutine
go rl.cleanupLoop()
return rl
}
// cleanupLoop removes stale clients periodically
func (rl *RateLimiter) cleanupLoop() {
ticker := time.NewTicker(time.Minute)
defer ticker.Stop()
for {
select {
case <-rl.stopChan:
return
case <-ticker.C:
rl.cleanup()
}
}
}
// cleanup removes clients that haven't made requests in 5 minutes
func (rl *RateLimiter) cleanup() {
rl.mu.Lock()
defer rl.mu.Unlock()
for ip, client := range rl.clients {
if time.Since(client.lastCheck) > 5*time.Minute {
delete(rl.clients, ip)
}
}
}
// rl.Stop() // call on shutdown to release the cleanup goroutine
func (rl *RateLimiter) Stop() {
rl.mu.Lock()
defer rl.mu.Unlock()
if !rl.stopped {
close(rl.stopChan)
rl.stopped = true
}
}
// router.Use(rl.Middleware()) // install before route handlers
func (rl *RateLimiter) Middleware() gin.HandlerFunc {
return func(c *gin.Context) {
ip := c.ClientIP()
rl.mu.Lock()
client, exists := rl.clients[ip]
if !exists {
client = &rateLimitClient{tokens: float64(rl.burst), lastCheck: time.Now()}
rl.clients[ip] = client
}
// Token bucket algorithm
now := time.Now()
elapsed := now.Sub(client.lastCheck).Seconds()
client.tokens += elapsed * float64(rl.requestsPerSecond)
if client.tokens > float64(rl.burst) {
client.tokens = float64(rl.burst)
}
client.lastCheck = now
if client.tokens < 1 {
rl.mu.Unlock()
respondWithError(c, http.StatusTooManyRequests, "RATE_LIMITED",
"too many requests", "rate limit exceeded")
c.Abort()
return
}
client.tokens--
rl.mu.Unlock()
c.Next()
}
}
// if rl.ClientCount() == 0 { /* no active clients */ }
func (rl *RateLimiter) ClientCount() int {
rl.mu.RLock()
defer rl.mu.RUnlock()
return len(rl.clients)
}