ratelimit.go96 lines, 2.8 KB
| 1 | package gateway |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | _ "embed" |
| 6 | "fmt" |
| 7 | "log/slog" |
| 8 | "math" |
| 9 | "net" |
| 10 | "net/http" |
| 11 | "strconv" |
| 12 | "time" |
| 13 | |
| 14 | "github.com/fiston-user/payments/internal/platform/authn" |
| 15 | "github.com/fiston-user/payments/internal/platform/httpx" |
| 16 | "github.com/redis/go-redis/v9" |
| 17 | ) |
| 18 | |
| 19 | //go:embed ratelimit.lua |
| 20 | var tokenBucketLua string |
| 21 | |
| 22 | // tokenBucket runs with EVALSHA: after the first call, only its hash is sent. |
| 23 | var tokenBucket = redis.NewScript(tokenBucketLua) |
| 24 | |
| 25 | // A Limiter allows each client limit requests per period. Its buckets live in |
| 26 | // Redis, so every gateway instance shares them. |
| 27 | type Limiter struct { |
| 28 | rdb *redis.Client |
| 29 | limit int |
| 30 | period time.Duration |
| 31 | } |
| 32 | |
| 33 | // NewLimiter returns a Limiter that keeps its buckets in rdb. |
| 34 | func NewLimiter(rdb *redis.Client, limit int, period time.Duration) *Limiter { |
| 35 | return &Limiter{rdb: rdb, limit: limit, period: period} |
| 36 | } |
| 37 | |
| 38 | // A Decision is the limiter's answer for one request. |
| 39 | type Decision struct { |
| 40 | Allowed bool |
| 41 | Remaining int // requests left right now |
| 42 | RetryAfter time.Duration // until the next request is allowed |
| 43 | } |
| 44 | |
| 45 | // Allow takes a token from key's bucket, if there's one left. |
| 46 | func (l *Limiter) Allow(ctx context.Context, key string) (Decision, error) { |
| 47 | res, err := tokenBucket.Run(ctx, l.rdb, []string{"ratelimit:" + key}, |
| 48 | l.limit, l.period.Milliseconds()).Int64Slice() |
| 49 | if err != nil { |
| 50 | return Decision{}, fmt.Errorf("rate limit %s: %w", key, err) |
| 51 | } |
| 52 | return Decision{ |
| 53 | Allowed: res[0] == 1, |
| 54 | Remaining: int(res[1]), |
| 55 | RetryAfter: time.Duration(res[2]) * time.Millisecond, |
| 56 | }, nil |
| 57 | } |
| 58 | |
| 59 | // Middleware limits requests per client, as key names them. |
| 60 | func (l *Limiter) Middleware(key func(*http.Request) string) httpx.Middleware { |
| 61 | return func(next http.Handler) http.Handler { |
| 62 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 63 | d, err := l.Allow(r.Context(), key(r)) |
| 64 | if err != nil { |
| 65 | // Fail open: Redis being down mustn't take the whole API down. |
| 66 | slog.WarnContext(r.Context(), "rate limiter unavailable, request allowed", "err", err) |
| 67 | next.ServeHTTP(w, r) |
| 68 | return |
| 69 | } |
| 70 | w.Header().Set("X-RateLimit-Limit", strconv.Itoa(l.limit)) |
| 71 | w.Header().Set("X-RateLimit-Remaining", strconv.Itoa(d.Remaining)) |
| 72 | if !d.Allowed { |
| 73 | secs := math.Ceil(d.RetryAfter.Seconds()) // whole seconds, rounded up |
| 74 | w.Header().Set("Retry-After", strconv.Itoa(int(secs))) |
| 75 | httpx.Error(w, r, errRateLimited) |
| 76 | return |
| 77 | } |
| 78 | next.ServeHTTP(w, r) |
| 79 | }) |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | // clientIP keys public routes on the client's IP address. |
| 84 | func clientIP(r *http.Request) string { |
| 85 | ip, _, err := net.SplitHostPort(r.RemoteAddr) |
| 86 | if err != nil { |
| 87 | ip = r.RemoteAddr |
| 88 | } |
| 89 | return "ip:" + ip |
| 90 | } |
| 91 | |
| 92 | // userID keys private routes on the user that authn.Require found. |
| 93 | func userID(r *http.Request) string { |
| 94 | id, _ := authn.UserID(r.Context()) |
| 95 | return "user:" + id.String() |
| 96 | } |