1 import { rateLimitDelay, retryOnRateLimit } from "../rate-limit"
2
3 // Cloud answers a rate limit with 429 and a `Retry-After`; a zero wait keeps
4 // these tests from sitting through the backoff.
5 const rateLimited = () =>
6 Object.assign(new Error("Too many requests"), {
7 status: 429,
8 retry_after: 0,
9 })
10
11 describe("rateLimitDelay", () => {
12 it("should double the wait per attempt, up to a ceiling", () => {
13 const delays = [0, 1, 2, 3, 4, 5, 6].map((attempt) =>
14 rateLimitDelay(attempt, undefined, () => 1)
15 )
16
17 expect(delays).toEqual([
18 2_000, 4_000, 8_000, 16_000, 32_000, 60_000, 60_000,
19 ])
20 // Jittered across the lower half of each window.
21 expect(rateLimitDelay(0, undefined, () => 0)).toBe(1_000)
22 })
23
24 it("should prefer the wait Cloud asked for, capped", () => {
25 expect(rateLimitDelay(0, 12_345)).toBe(12_345)
26 expect(rateLimitDelay(0, 60 * 60 * 1000)).toBe(60_000)
27 })
28 })
29
30 describe("retryOnRateLimit", () => {
31 it("should wait out a rate limit and return the eventual result", async () => {
32 const operation = jest
33 .fn()
34 .mockRejectedValueOnce(rateLimited())
35 .mockRejectedValueOnce(rateLimited())
36 .mockResolvedValue("indexed")
37
38 await expect(
39 retryOnRateLimit(operation, { label: "a write" })
40 ).resolves.toBe("indexed")
41
42 expect(operation).toHaveBeenCalledTimes(3)
43 })
44
45 it("should not retry anything that is not a rate limit", async () => {
46 const operation = jest.fn().mockRejectedValue(new Error("bad schema"))
47
48 await expect(
49 retryOnRateLimit(operation, { label: "a write" })
50 ).rejects.toThrow("bad schema")
51
52 expect(operation).toHaveBeenCalledTimes(1)
53 })
54 })