| 1 | package ratelimit |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "testing" |
| 6 | "time" |
| 7 | ) |
| 8 | |
| 9 | // In Redis nobody sweeps. Every bucket carries its own expiry: as long as it takes to fill. |
| 10 | func TestSharedBucketExpires(t *testing.T) { |
| 11 | s, _ := shared(t, 3, 60) |
| 12 | s.Allow(context.Background(), "ann") |
| 13 | ttl := s.rdb.PTTL(context.Background(), "ratelimit:test:ann").Val() |
| 14 | if ttl <= 0 || ttl > 3*time.Second { |
| 15 | t.Fatalf("the bucket expires in %v, want within three seconds", ttl) |
| 16 | } |
| 17 | } |
| 18 | |
| 19 | // Two servers have two clocks. One that runs behind must not hand out tokens, |
| 20 | // and it must not turn the bucket's own clock back. |
| 21 | func TestSharedClockBehind(t *testing.T) { |
| 22 | s, clock := shared(t, 1, 60) |
| 23 | ask := func() bool { |
| 24 | res, err := s.Allow(context.Background(), "ann") |
| 25 | if err != nil { |
| 26 | t.Fatal(err) |
| 27 | } |
| 28 | return res.Allowed |
| 29 | } |
| 30 | if !ask() { |
| 31 | t.Fatal("the first request was refused") |
| 32 | } |
| 33 | *clock = clock.Add(-10 * time.Second) // a server whose clock is ten seconds behind |
| 34 | if ask() { |
| 35 | t.Fatal("a clock that runs behind got a token") |
| 36 | } |
| 37 | *clock = clock.Add(10*time.Second + 500*time.Millisecond) // the first server, half a second on |
| 38 | if ask() { |
| 39 | t.Fatal("half a second bought a whole token") |
| 40 | } |
| 41 | } |