Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

rateLimit.test.ts 3.9 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
  1. import type { Response } from 'node-fetch';
  2. import fetch from 'node-fetch';
  3. import { fetchWithRetries } from '../src/fetch';
  4. jest.mock('node-fetch');
  5. const mockedFetch = jest.mocked(fetch);
  6. const mockedFetchResponse = (
  7. ok: boolean,
  8. response: object,
  9. headers: Record<string, string> = {},
  10. ) => {
  11. return {
  12. ok,
  13. status: ok ? 200 : 429,
  14. statusText: ok ? 'OK' : 'Too Many Requests',
  15. data: response,
  16. headers: {
  17. get: (name: string) => {
  18. if (name === 'content-type') {
  19. return 'application/json';
  20. }
  21. if (headers[name] !== undefined) {
  22. return headers[name];
  23. }
  24. return null;
  25. },
  26. },
  27. } as unknown as Response;
  28. };
  29. const mockedSetTimeout = (reqTimeout: number) =>
  30. jest.spyOn(global, 'setTimeout').mockImplementation((cb: Function, ms?: number) => {
  31. if (ms !== reqTimeout) {
  32. cb();
  33. }
  34. return 0 as any;
  35. });
  36. describe('fetchWithRetries', () => {
  37. beforeEach(() => {
  38. jest.useFakeTimers();
  39. });
  40. afterEach(() => {
  41. mockedFetch.mockReset();
  42. jest.useRealTimers();
  43. });
  44. afterAll(() => {
  45. jest.clearAllMocks();
  46. });
  47. it('should fetch data', async () => {
  48. const url = 'https://api.example.com/data';
  49. const response = { data: 'test data' };
  50. mockedFetch.mockResolvedValueOnce(mockedFetchResponse(true, response));
  51. const result = await fetchWithRetries(url, {}, 1000);
  52. expect(mockedFetch).toHaveBeenCalledTimes(1);
  53. expect(result).toMatchObject({ data: response });
  54. });
  55. it('should retry after given time if rate limited, using X-Limit headers', async () => {
  56. const url = 'https://api.example.com/data';
  57. const response = { data: 'test data' };
  58. const rateLimitReset = 47_000;
  59. const timeout = 1234;
  60. const now = Date.now();
  61. const setTimoutMock = mockedSetTimeout(timeout);
  62. mockedFetch
  63. .mockResolvedValueOnce(
  64. mockedFetchResponse(false, response, {
  65. 'X-RateLimit-Remaining': '0',
  66. 'X-RateLimit-Reset': `${(now + rateLimitReset) / 1000}`,
  67. }),
  68. )
  69. .mockResolvedValueOnce(mockedFetchResponse(true, response));
  70. const result = await fetchWithRetries(url, {}, timeout);
  71. const waitTime = setTimoutMock.mock.calls[1][1];
  72. expect(mockedFetch).toHaveBeenCalledTimes(2);
  73. expect(waitTime).toBeGreaterThan(rateLimitReset);
  74. expect(waitTime).toBeLessThanOrEqual(rateLimitReset + 1000);
  75. expect(result).toMatchObject({ data: response });
  76. });
  77. it('should retry after given time if rate limited, using status and Retry-After', async () => {
  78. const url = 'https://api.example.com/data';
  79. const response = { data: 'test data' };
  80. const retryAfter = 15;
  81. const timeout = 1234;
  82. const setTimoutMock = mockedSetTimeout(timeout);
  83. mockedFetch
  84. .mockResolvedValueOnce(
  85. mockedFetchResponse(false, response, { 'Retry-After': String(retryAfter) }),
  86. )
  87. .mockResolvedValueOnce(mockedFetchResponse(true, response));
  88. const result = await fetchWithRetries(url, {}, timeout);
  89. const waitTime = setTimoutMock.mock.calls[1][1];
  90. expect(mockedFetch).toHaveBeenCalledTimes(2);
  91. expect(waitTime).toBe(retryAfter * 1000);
  92. expect(result).toMatchObject({ data: response });
  93. });
  94. it('should retry after default wait time if rate limited and wait time not found', async () => {
  95. const url = 'https://api.example.com/data';
  96. const response = { data: 'test data' };
  97. const timeout = 1234;
  98. const setTimoutMock = mockedSetTimeout(timeout);
  99. mockedFetch
  100. .mockResolvedValueOnce(mockedFetchResponse(false, response))
  101. .mockResolvedValueOnce(mockedFetchResponse(true, response));
  102. const result = await fetchWithRetries(url, {}, timeout);
  103. const waitTime = setTimoutMock.mock.calls[1][1];
  104. expect(mockedFetch).toHaveBeenCalledTimes(2);
  105. expect(waitTime).toBe(60_000);
  106. expect(result).toMatchObject({ data: response });
  107. });
  108. });
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...