fallback.go65 lines, 1.9 KB
| 1 | package ratelimit |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "log/slog" |
| 6 | "sync/atomic" |
| 7 | "time" |
| 8 | ) |
| 9 | |
| 10 | // A Fallback asks the shared limiter first. When that one fails, or takes too long, |
| 11 | // the spare answers, and the shared one is left alone for a moment. |
| 12 | type Fallback struct { |
| 13 | Allower // the shared buckets, in Redis |
| 14 | spare Allower // this server's own buckets, in memory |
| 15 | patience time.Duration // how long the shared limiter gets to answer |
| 16 | pause time.Duration // how long it is left alone after a failure |
| 17 | now func() time.Time |
| 18 | until atomic.Int64 // the end of that pause in unix nanoseconds, or zero |
| 19 | } |
| 20 | |
| 21 | // NewFallback returns shared, with spare to fall back on. |
| 22 | func NewFallback(shared, spare Allower) *Fallback { |
| 23 | return &Fallback{ |
| 24 | Allower: shared, |
| 25 | spare: spare, |
| 26 | patience: 250 * time.Millisecond, |
| 27 | pause: time.Second, |
| 28 | now: time.Now, |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | // Allow takes a token from the shared bucket, or from the spare one while Redis is away. |
| 33 | func (f *Fallback) Allow(ctx context.Context, key string) (Result, error) { |
| 34 | now, until := f.now(), f.until.Load() |
| 35 | next := now.Add(f.pause).UnixNano() |
| 36 | if until != 0 && (now.UnixNano() < until || !f.until.CompareAndSwap(until, next)) { |
| 37 | return f.spare.Allow(ctx, key) |
| 38 | } |
| 39 | brief, cancel := context.WithTimeout(ctx, f.patience) |
| 40 | defer cancel() |
| 41 | res, err := f.Allower.Allow(brief, key) |
| 42 | name, _ := f.Policy() |
| 43 | if err == nil { |
| 44 | if until != 0 { |
| 45 | f.until.Store(0) |
| 46 | slog.Info("rate limit is shared again", "limit", name) |
| 47 | } |
| 48 | return res, nil |
| 49 | } |
| 50 | if ctx.Err() != nil { |
| 51 | return Result{}, ctx.Err() |
| 52 | } |
| 53 | if until == 0 && f.until.CompareAndSwap(0, next) { |
| 54 | slog.Warn("rate limit falls back to this server's memory", "limit", name, "error", err) |
| 55 | } |
| 56 | return f.spare.Allow(ctx, key) |
| 57 | } |
| 58 | |
| 59 | // Away is 1 while the shared limiter is left alone and the spare answers, and 0 otherwise. |
| 60 | func (f *Fallback) Away() int { |
| 61 | if f.until.Load() != 0 { |
| 62 | return 1 |
| 63 | } |
| 64 | return 0 |
| 65 | } |