@zapier/zapier-sdk 0.8.1 → 0.8.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/dist/api/client.d.ts.map +1 -1
- package/dist/api/client.js +1 -2
- package/dist/api/polling.d.ts +36 -6
- package/dist/api/polling.d.ts.map +1 -1
- package/dist/api/polling.js +132 -28
- package/dist/api/polling.test.d.ts +2 -0
- package/dist/api/polling.test.d.ts.map +1 -0
- package/dist/api/polling.test.js +318 -0
- package/dist/api/types.d.ts +3 -4
- package/dist/api/types.d.ts.map +1 -1
- package/dist/index.cjs +144 -34
- package/dist/index.d.mts +1 -2
- package/dist/index.mjs +144 -34
- package/dist/plugins/findFirstAuthentication/schemas.d.ts +2 -1
- package/dist/plugins/findFirstAuthentication/schemas.d.ts.map +1 -1
- package/dist/plugins/findUniqueAuthentication/schemas.d.ts +2 -1
- package/dist/plugins/findUniqueAuthentication/schemas.d.ts.map +1 -1
- package/dist/plugins/getAction/schemas.d.ts +2 -1
- package/dist/plugins/getAction/schemas.d.ts.map +1 -1
- package/dist/plugins/getApp/index.d.ts +2 -2
- package/dist/plugins/getApp/index.d.ts.map +1 -1
- package/dist/plugins/getApp/schemas.d.ts +1 -1
- package/dist/plugins/getApp/schemas.d.ts.map +1 -1
- package/dist/plugins/getAuthentication/schemas.d.ts +2 -1
- package/dist/plugins/getAuthentication/schemas.d.ts.map +1 -1
- package/dist/plugins/getProfile/schemas.d.ts +1 -1
- package/dist/plugins/getProfile/schemas.d.ts.map +1 -1
- package/dist/plugins/listActions/index.d.ts +2 -2
- package/dist/plugins/listActions/index.d.ts.map +1 -1
- package/dist/plugins/listActions/schemas.d.ts +2 -1
- package/dist/plugins/listActions/schemas.d.ts.map +1 -1
- package/dist/plugins/listApps/schemas.d.ts +1 -1
- package/dist/plugins/listApps/schemas.d.ts.map +1 -1
- package/dist/plugins/listAuthentications/index.d.ts +2 -2
- package/dist/plugins/listAuthentications/index.d.ts.map +1 -1
- package/dist/plugins/listAuthentications/schemas.d.ts +2 -1
- package/dist/plugins/listAuthentications/schemas.d.ts.map +1 -1
- package/dist/plugins/listInputFields/index.d.ts +1 -1
- package/dist/plugins/listInputFields/index.d.ts.map +1 -1
- package/dist/plugins/listInputFields/schemas.d.ts +2 -1
- package/dist/plugins/listInputFields/schemas.d.ts.map +1 -1
- package/dist/plugins/lockVersion/index.d.ts +1 -1
- package/dist/plugins/lockVersion/index.d.ts.map +1 -1
- package/dist/plugins/manifest/index.d.ts +4 -5
- package/dist/plugins/manifest/index.d.ts.map +1 -1
- package/dist/plugins/manifest/schemas.d.ts +1 -1
- package/dist/plugins/manifest/schemas.d.ts.map +1 -1
- package/dist/plugins/registry/index.d.ts +1 -1
- package/dist/plugins/registry/index.d.ts.map +1 -1
- package/dist/plugins/request/schemas.d.ts +2 -1
- package/dist/plugins/request/schemas.d.ts.map +1 -1
- package/dist/plugins/runAction/index.d.ts +1 -1
- package/dist/plugins/runAction/index.d.ts.map +1 -1
- package/dist/plugins/runAction/schemas.d.ts +2 -1
- package/dist/plugins/runAction/schemas.d.ts.map +1 -1
- package/dist/sdk.d.ts +1 -1
- package/dist/sdk.d.ts.map +1 -1
- package/dist/types/functions.d.ts +2 -1
- package/dist/types/functions.d.ts.map +1 -1
- package/dist/types/functions.js +0 -3
- package/dist/types/plugin.d.ts +1 -1
- package/dist/types/plugin.d.ts.map +1 -1
- package/dist/types/sdk.d.ts +17 -17
- package/dist/types/sdk.d.ts.map +1 -1
- package/dist/utils/function-utils.d.ts +1 -1
- package/dist/utils/function-utils.d.ts.map +1 -1
- package/dist/utils/validation.d.ts +1 -1
- package/dist/utils/validation.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/api/client.ts +5 -4
- package/src/api/polling.test.ts +405 -0
- package/src/api/polling.ts +224 -44
- package/src/api/types.ts +3 -4
- package/src/plugins/apps/index.ts +1 -1
- package/src/plugins/fetch/index.ts +1 -1
- package/src/plugins/findFirstAuthentication/schemas.ts +10 -4
- package/src/plugins/findUniqueAuthentication/schemas.ts +12 -5
- package/src/plugins/getAction/schemas.ts +14 -6
- package/src/plugins/getApp/index.ts +2 -2
- package/src/plugins/getApp/schemas.ts +1 -1
- package/src/plugins/getAuthentication/schemas.ts +12 -5
- package/src/plugins/getProfile/schemas.ts +1 -1
- package/src/plugins/listActions/index.ts +2 -2
- package/src/plugins/listActions/schemas.ts +8 -3
- package/src/plugins/listApps/schemas.ts +1 -1
- package/src/plugins/listAuthentications/index.ts +2 -2
- package/src/plugins/listAuthentications/schemas.ts +12 -5
- package/src/plugins/listInputFields/index.ts +1 -1
- package/src/plugins/listInputFields/schemas.ts +14 -6
- package/src/plugins/lockVersion/index.ts +1 -1
- package/src/plugins/manifest/index.ts +6 -5
- package/src/plugins/manifest/schemas.ts +1 -1
- package/src/plugins/registry/index.ts +1 -1
- package/src/plugins/request/schemas.ts +8 -3
- package/src/plugins/runAction/index.ts +1 -1
- package/src/plugins/runAction/schemas.ts +10 -4
- package/src/sdk.ts +1 -1
- package/src/types/functions.ts +2 -1
- package/src/types/plugin.ts +1 -1
- package/src/types/sdk.ts +17 -17
- package/src/utils/function-utils.ts +1 -1
- package/src/utils/validation.ts +1 -1
- package/tsconfig.tsbuildinfo +1 -1
|
@@ -0,0 +1,405 @@
|
|
|
1
|
+
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
|
2
|
+
import { pollUntilComplete } from "./polling";
|
|
3
|
+
import {
|
|
4
|
+
ZapierTimeoutError,
|
|
5
|
+
ZapierApiError,
|
|
6
|
+
ZapierValidationError,
|
|
7
|
+
} from "../types/errors";
|
|
8
|
+
|
|
9
|
+
// Mock the timers/promises module
|
|
10
|
+
vi.mock("timers/promises", () => ({
|
|
11
|
+
setTimeout: vi.fn(() => Promise.resolve()),
|
|
12
|
+
}));
|
|
13
|
+
|
|
14
|
+
describe("pollUntilComplete", () => {
|
|
15
|
+
beforeEach(() => {
|
|
16
|
+
vi.clearAllMocks();
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
afterEach(() => {
|
|
20
|
+
vi.clearAllMocks();
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
describe("successful polling", () => {
|
|
24
|
+
it("should return immediately on first successful response", async () => {
|
|
25
|
+
const mockResponse = {
|
|
26
|
+
ok: true,
|
|
27
|
+
status: 200,
|
|
28
|
+
json: vi.fn().mockResolvedValue({ data: "success" }),
|
|
29
|
+
} as unknown as Response;
|
|
30
|
+
|
|
31
|
+
const fetchPoll = vi.fn().mockResolvedValue(mockResponse);
|
|
32
|
+
|
|
33
|
+
const result = await pollUntilComplete({ fetchPoll });
|
|
34
|
+
expect(result).toEqual({ data: "success" });
|
|
35
|
+
expect(fetchPoll).toHaveBeenCalledTimes(1);
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
it("should poll until success status is received", async () => {
|
|
39
|
+
const pendingResponse = {
|
|
40
|
+
ok: true,
|
|
41
|
+
status: 202,
|
|
42
|
+
} as Response;
|
|
43
|
+
|
|
44
|
+
const successResponse = {
|
|
45
|
+
ok: true,
|
|
46
|
+
status: 200,
|
|
47
|
+
json: vi.fn().mockResolvedValue({ data: "complete" }),
|
|
48
|
+
} as unknown as Response;
|
|
49
|
+
|
|
50
|
+
const fetchPoll = vi
|
|
51
|
+
.fn()
|
|
52
|
+
.mockResolvedValueOnce(pendingResponse)
|
|
53
|
+
.mockResolvedValueOnce(pendingResponse)
|
|
54
|
+
.mockResolvedValueOnce(successResponse);
|
|
55
|
+
|
|
56
|
+
const result = await pollUntilComplete({ fetchPoll });
|
|
57
|
+
expect(result).toEqual({ data: "complete" });
|
|
58
|
+
expect(fetchPoll).toHaveBeenCalledTimes(3);
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
it("should use custom success and pending status codes", async () => {
|
|
62
|
+
const pendingResponse = {
|
|
63
|
+
ok: true,
|
|
64
|
+
status: 301,
|
|
65
|
+
} as Response;
|
|
66
|
+
|
|
67
|
+
const successResponse = {
|
|
68
|
+
ok: true,
|
|
69
|
+
status: 204,
|
|
70
|
+
json: vi.fn().mockResolvedValue({ done: true }),
|
|
71
|
+
} as unknown as Response;
|
|
72
|
+
|
|
73
|
+
const fetchPoll = vi
|
|
74
|
+
.fn()
|
|
75
|
+
.mockResolvedValueOnce(pendingResponse)
|
|
76
|
+
.mockResolvedValueOnce(successResponse);
|
|
77
|
+
|
|
78
|
+
const result = await pollUntilComplete({
|
|
79
|
+
fetchPoll,
|
|
80
|
+
successStatus: 204,
|
|
81
|
+
pendingStatus: 301,
|
|
82
|
+
});
|
|
83
|
+
expect(result).toEqual({ done: true });
|
|
84
|
+
expect(fetchPoll).toHaveBeenCalledTimes(2);
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
it("should apply result extractor function", async () => {
|
|
88
|
+
const mockResponse = {
|
|
89
|
+
ok: true,
|
|
90
|
+
status: 200,
|
|
91
|
+
json: vi.fn().mockResolvedValue({
|
|
92
|
+
nested: { data: { value: "extracted" } },
|
|
93
|
+
}),
|
|
94
|
+
} as unknown as Response;
|
|
95
|
+
|
|
96
|
+
const fetchPoll = vi.fn().mockResolvedValue(mockResponse);
|
|
97
|
+
const resultExtractor = (response: any) => response.nested.data.value;
|
|
98
|
+
|
|
99
|
+
const result = await pollUntilComplete({
|
|
100
|
+
fetchPoll,
|
|
101
|
+
resultExtractor,
|
|
102
|
+
});
|
|
103
|
+
expect(result).toBe("extracted");
|
|
104
|
+
});
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
describe("initial delay", () => {
|
|
108
|
+
it("should wait for initial delay before first poll", async () => {
|
|
109
|
+
const mockResponse = {
|
|
110
|
+
ok: true,
|
|
111
|
+
status: 200,
|
|
112
|
+
json: vi.fn().mockResolvedValue({ data: "success" }),
|
|
113
|
+
} as unknown as Response;
|
|
114
|
+
|
|
115
|
+
const fetchPoll = vi.fn().mockResolvedValue(mockResponse);
|
|
116
|
+
const { setTimeout: mockSetTimeout } = await import("timers/promises");
|
|
117
|
+
|
|
118
|
+
const result = await pollUntilComplete({
|
|
119
|
+
fetchPoll,
|
|
120
|
+
initialDelay: 500,
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
expect(result).toEqual({ data: "success" });
|
|
124
|
+
expect(fetchPoll).toHaveBeenCalledTimes(1);
|
|
125
|
+
// Verify setTimeout was called with the initial delay
|
|
126
|
+
expect(mockSetTimeout).toHaveBeenCalledWith(500);
|
|
127
|
+
});
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
describe("error handling", () => {
|
|
131
|
+
it("should retry on transient network errors", async () => {
|
|
132
|
+
const successResponse = {
|
|
133
|
+
ok: true,
|
|
134
|
+
status: 200,
|
|
135
|
+
json: vi.fn().mockResolvedValue({ data: "recovered" }),
|
|
136
|
+
} as unknown as Response;
|
|
137
|
+
|
|
138
|
+
const fetchPoll = vi
|
|
139
|
+
.fn()
|
|
140
|
+
.mockRejectedValueOnce(new Error("Network error"))
|
|
141
|
+
.mockRejectedValueOnce(new Error("Network error"))
|
|
142
|
+
.mockResolvedValueOnce(successResponse);
|
|
143
|
+
|
|
144
|
+
const result = await pollUntilComplete({ fetchPoll });
|
|
145
|
+
expect(result).toEqual({ data: "recovered" });
|
|
146
|
+
expect(fetchPoll).toHaveBeenCalledTimes(3);
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
it("should fail after MAX_CONSECUTIVE_ERRORS network failures", async () => {
|
|
150
|
+
const fetchPoll = vi
|
|
151
|
+
.fn()
|
|
152
|
+
.mockRejectedValue(new Error("Persistent network error"));
|
|
153
|
+
|
|
154
|
+
await expect(pollUntilComplete({ fetchPoll })).rejects.toThrow(
|
|
155
|
+
ZapierApiError,
|
|
156
|
+
);
|
|
157
|
+
expect(fetchPoll).toHaveBeenCalledTimes(3);
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
it("should retry on HTTP error responses", async () => {
|
|
161
|
+
const errorResponse = {
|
|
162
|
+
ok: false,
|
|
163
|
+
status: 500,
|
|
164
|
+
statusText: "Internal Server Error",
|
|
165
|
+
} as Response;
|
|
166
|
+
|
|
167
|
+
const successResponse = {
|
|
168
|
+
ok: true,
|
|
169
|
+
status: 200,
|
|
170
|
+
json: vi.fn().mockResolvedValue({ data: "recovered" }),
|
|
171
|
+
} as unknown as Response;
|
|
172
|
+
|
|
173
|
+
const fetchPoll = vi
|
|
174
|
+
.fn()
|
|
175
|
+
.mockResolvedValueOnce(errorResponse)
|
|
176
|
+
.mockResolvedValueOnce(errorResponse)
|
|
177
|
+
.mockResolvedValueOnce(successResponse);
|
|
178
|
+
|
|
179
|
+
const result = await pollUntilComplete({ fetchPoll });
|
|
180
|
+
expect(result).toEqual({ data: "recovered" });
|
|
181
|
+
expect(fetchPoll).toHaveBeenCalledTimes(3);
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
it("should fail after MAX_CONSECUTIVE_ERRORS HTTP failures", async () => {
|
|
185
|
+
const errorResponse = {
|
|
186
|
+
ok: false,
|
|
187
|
+
status: 503,
|
|
188
|
+
statusText: "Service Unavailable",
|
|
189
|
+
} as Response;
|
|
190
|
+
|
|
191
|
+
const fetchPoll = vi.fn().mockResolvedValue(errorResponse);
|
|
192
|
+
|
|
193
|
+
await expect(pollUntilComplete({ fetchPoll })).rejects.toThrow(
|
|
194
|
+
ZapierApiError,
|
|
195
|
+
);
|
|
196
|
+
expect(fetchPoll).toHaveBeenCalledTimes(3);
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
it("should throw error for unexpected response status", async () => {
|
|
200
|
+
const unexpectedResponse = {
|
|
201
|
+
ok: true,
|
|
202
|
+
status: 301, // Not success (200) or pending (202)
|
|
203
|
+
} as Response;
|
|
204
|
+
|
|
205
|
+
const fetchPoll = vi.fn().mockResolvedValue(unexpectedResponse);
|
|
206
|
+
|
|
207
|
+
await expect(pollUntilComplete({ fetchPoll })).rejects.toThrow(
|
|
208
|
+
"Unexpected response status",
|
|
209
|
+
);
|
|
210
|
+
// Will retry 3 times before failing
|
|
211
|
+
expect(fetchPoll).toHaveBeenCalledTimes(3);
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
it("should throw error if successful response is not valid JSON", async () => {
|
|
215
|
+
const mockResponse = {
|
|
216
|
+
ok: true,
|
|
217
|
+
status: 200,
|
|
218
|
+
json: vi.fn().mockRejectedValue(new Error("Invalid JSON")),
|
|
219
|
+
} as unknown as Response;
|
|
220
|
+
|
|
221
|
+
const fetchPoll = vi.fn().mockResolvedValue(mockResponse);
|
|
222
|
+
|
|
223
|
+
await expect(pollUntilComplete({ fetchPoll })).rejects.toThrow(
|
|
224
|
+
"Failed to poll after 3 consecutive errors",
|
|
225
|
+
);
|
|
226
|
+
// Will retry 3 times before failing
|
|
227
|
+
expect(fetchPoll).toHaveBeenCalledTimes(3);
|
|
228
|
+
});
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
describe("timeout behavior", () => {
|
|
232
|
+
it("should timeout after specified duration", async () => {
|
|
233
|
+
// Mock Date.now to simulate time passing
|
|
234
|
+
const originalDateNow = Date.now;
|
|
235
|
+
let currentTime = 1000;
|
|
236
|
+
Date.now = vi.fn(() => currentTime);
|
|
237
|
+
|
|
238
|
+
const pendingResponse = {
|
|
239
|
+
ok: true,
|
|
240
|
+
status: 202,
|
|
241
|
+
} as Response;
|
|
242
|
+
|
|
243
|
+
const fetchPoll = vi.fn().mockImplementation(() => {
|
|
244
|
+
// Simulate time passing with each poll
|
|
245
|
+
currentTime += 500;
|
|
246
|
+
return Promise.resolve(pendingResponse);
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
try {
|
|
250
|
+
await expect(
|
|
251
|
+
pollUntilComplete({
|
|
252
|
+
fetchPoll,
|
|
253
|
+
timeoutMs: 1000,
|
|
254
|
+
initialDelay: 0,
|
|
255
|
+
}),
|
|
256
|
+
).rejects.toThrow(ZapierTimeoutError);
|
|
257
|
+
} finally {
|
|
258
|
+
Date.now = originalDateNow;
|
|
259
|
+
}
|
|
260
|
+
});
|
|
261
|
+
|
|
262
|
+
it("should use default timeout when not specified", async () => {
|
|
263
|
+
// Mock Date.now to simulate time passing beyond default timeout
|
|
264
|
+
const originalDateNow = Date.now;
|
|
265
|
+
let currentTime = 1000;
|
|
266
|
+
Date.now = vi.fn(() => currentTime);
|
|
267
|
+
|
|
268
|
+
const pendingResponse = {
|
|
269
|
+
ok: true,
|
|
270
|
+
status: 202,
|
|
271
|
+
} as Response;
|
|
272
|
+
|
|
273
|
+
const fetchPoll = vi.fn().mockImplementation(() => {
|
|
274
|
+
// Simulate time passing beyond default timeout (180 seconds + buffer)
|
|
275
|
+
currentTime += 50000;
|
|
276
|
+
return Promise.resolve(pendingResponse);
|
|
277
|
+
});
|
|
278
|
+
|
|
279
|
+
try {
|
|
280
|
+
await expect(
|
|
281
|
+
pollUntilComplete({
|
|
282
|
+
fetchPoll,
|
|
283
|
+
initialDelay: 0,
|
|
284
|
+
}),
|
|
285
|
+
).rejects.toThrow(ZapierTimeoutError);
|
|
286
|
+
} finally {
|
|
287
|
+
Date.now = originalDateNow;
|
|
288
|
+
}
|
|
289
|
+
});
|
|
290
|
+
});
|
|
291
|
+
|
|
292
|
+
describe("input validation", () => {
|
|
293
|
+
it("should throw error for invalid timeout", async () => {
|
|
294
|
+
const fetchPoll = vi.fn();
|
|
295
|
+
|
|
296
|
+
await expect(
|
|
297
|
+
pollUntilComplete({
|
|
298
|
+
fetchPoll,
|
|
299
|
+
timeoutMs: 0,
|
|
300
|
+
}),
|
|
301
|
+
).rejects.toThrow(ZapierValidationError);
|
|
302
|
+
|
|
303
|
+
await expect(
|
|
304
|
+
pollUntilComplete({
|
|
305
|
+
fetchPoll,
|
|
306
|
+
timeoutMs: -1000,
|
|
307
|
+
}),
|
|
308
|
+
).rejects.toThrow(/Timeout must be greater than 0/);
|
|
309
|
+
});
|
|
310
|
+
|
|
311
|
+
it("should throw error for negative initial delay", async () => {
|
|
312
|
+
const fetchPoll = vi.fn();
|
|
313
|
+
|
|
314
|
+
await expect(
|
|
315
|
+
pollUntilComplete({
|
|
316
|
+
fetchPoll,
|
|
317
|
+
initialDelay: -100,
|
|
318
|
+
}),
|
|
319
|
+
).rejects.toThrow(ZapierValidationError);
|
|
320
|
+
|
|
321
|
+
await expect(
|
|
322
|
+
pollUntilComplete({
|
|
323
|
+
fetchPoll,
|
|
324
|
+
initialDelay: -1,
|
|
325
|
+
}),
|
|
326
|
+
).rejects.toThrow(/Initial delay must be non-negative/);
|
|
327
|
+
});
|
|
328
|
+
});
|
|
329
|
+
|
|
330
|
+
describe("edge cases", () => {
|
|
331
|
+
it("should handle rapid status changes", async () => {
|
|
332
|
+
const responses = [
|
|
333
|
+
{ ok: true, status: 202 } as Response,
|
|
334
|
+
{ ok: false, status: 500 } as Response,
|
|
335
|
+
{ ok: true, status: 202 } as Response,
|
|
336
|
+
{
|
|
337
|
+
ok: true,
|
|
338
|
+
status: 200,
|
|
339
|
+
json: vi.fn().mockResolvedValue({ data: "success" }),
|
|
340
|
+
} as unknown as Response,
|
|
341
|
+
];
|
|
342
|
+
|
|
343
|
+
let index = 0;
|
|
344
|
+
const fetchPoll = vi.fn().mockImplementation(() => {
|
|
345
|
+
const response = responses[index];
|
|
346
|
+
index++;
|
|
347
|
+
return Promise.resolve(response);
|
|
348
|
+
});
|
|
349
|
+
|
|
350
|
+
const result = await pollUntilComplete({ fetchPoll });
|
|
351
|
+
expect(result).toEqual({ data: "success" });
|
|
352
|
+
expect(fetchPoll).toHaveBeenCalledTimes(4);
|
|
353
|
+
});
|
|
354
|
+
|
|
355
|
+
it("should handle immediate success with no initial delay", async () => {
|
|
356
|
+
const mockResponse = {
|
|
357
|
+
ok: true,
|
|
358
|
+
status: 200,
|
|
359
|
+
json: vi.fn().mockResolvedValue({ instant: true }),
|
|
360
|
+
} as unknown as Response;
|
|
361
|
+
|
|
362
|
+
const fetchPoll = vi.fn().mockResolvedValue(mockResponse);
|
|
363
|
+
|
|
364
|
+
const result = await pollUntilComplete({
|
|
365
|
+
fetchPoll,
|
|
366
|
+
initialDelay: 0,
|
|
367
|
+
});
|
|
368
|
+
|
|
369
|
+
expect(result).toEqual({ instant: true });
|
|
370
|
+
expect(fetchPoll).toHaveBeenCalledTimes(1);
|
|
371
|
+
});
|
|
372
|
+
|
|
373
|
+
it("should handle very short timeout", async () => {
|
|
374
|
+
// Mock Date.now to simulate time passing
|
|
375
|
+
const originalDateNow = Date.now;
|
|
376
|
+
let currentTime = 1000;
|
|
377
|
+
Date.now = vi.fn(() => currentTime);
|
|
378
|
+
|
|
379
|
+
const pendingResponse = {
|
|
380
|
+
ok: true,
|
|
381
|
+
status: 202,
|
|
382
|
+
} as Response;
|
|
383
|
+
|
|
384
|
+
const fetchPoll = vi.fn().mockImplementation(() => {
|
|
385
|
+
// Simulate time passing beyond the short timeout
|
|
386
|
+
currentTime += 200;
|
|
387
|
+
return Promise.resolve(pendingResponse);
|
|
388
|
+
});
|
|
389
|
+
|
|
390
|
+
try {
|
|
391
|
+
await expect(
|
|
392
|
+
pollUntilComplete({
|
|
393
|
+
fetchPoll,
|
|
394
|
+
timeoutMs: 100,
|
|
395
|
+
initialDelay: 0,
|
|
396
|
+
}),
|
|
397
|
+
).rejects.toThrow(ZapierTimeoutError);
|
|
398
|
+
// Should have made at least 1 attempt before timing out
|
|
399
|
+
expect(fetchPoll.mock.calls.length).toBeGreaterThanOrEqual(1);
|
|
400
|
+
} finally {
|
|
401
|
+
Date.now = originalDateNow;
|
|
402
|
+
}
|
|
403
|
+
});
|
|
404
|
+
});
|
|
405
|
+
});
|
package/src/api/polling.ts
CHANGED
|
@@ -5,69 +5,249 @@
|
|
|
5
5
|
* with configurable retry logic and exponential backoff.
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
|
-
import {
|
|
8
|
+
import {
|
|
9
|
+
ZapierTimeoutError,
|
|
10
|
+
ZapierApiError,
|
|
11
|
+
ZapierValidationError,
|
|
12
|
+
} from "../types/errors";
|
|
13
|
+
import { setTimeout } from "timers/promises";
|
|
9
14
|
|
|
10
|
-
|
|
15
|
+
// Constants
|
|
16
|
+
const DEFAULT_TIMEOUT_MS = 180_000;
|
|
17
|
+
const DEFAULT_SUCCESS_STATUS = 200;
|
|
18
|
+
const DEFAULT_PENDING_STATUS = 202;
|
|
19
|
+
const DEFAULT_INITIAL_DELAY_MS = 50;
|
|
20
|
+
const DEFAULT_MAX_POLLING_INTERVAL_MS = 10_000;
|
|
21
|
+
const MAX_CONSECUTIVE_ERRORS = 3;
|
|
22
|
+
const MAX_TIMEOUT_BUFFER_MS = 10_000;
|
|
23
|
+
const BASE_ERROR_BACKOFF_MS = 1_000;
|
|
24
|
+
const JITTER_FACTOR = 0.5;
|
|
25
|
+
|
|
26
|
+
// Polling stages: [threshold_ms, interval_ms]
|
|
27
|
+
// Note: These are default stages, actual hard timeout is enforced separately below
|
|
28
|
+
const DEFAULT_POLLING_STAGES = [
|
|
29
|
+
[125, 125], // Up to 125ms: poll every 125ms
|
|
30
|
+
[375, 250], // Up to 375ms: poll every 250ms
|
|
31
|
+
[875, 500], // Up to 875ms: poll every 500ms
|
|
32
|
+
[10_000, 1_000], // Up to 10s: poll every 1s
|
|
33
|
+
[30_000, 2_500], // Up to 30s: poll every 2.5s
|
|
34
|
+
[60_000, 5_000], // Up to 60s: poll every 5s
|
|
35
|
+
] as const satisfies Array<[number, number]>;
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Options for the polling function
|
|
39
|
+
*/
|
|
40
|
+
export interface PollOptions<TResult = unknown> {
|
|
41
|
+
/** Function that performs the HTTP request */
|
|
11
42
|
fetchPoll: () => Promise<Response>;
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
43
|
+
/** Maximum time to wait for completion (in milliseconds) */
|
|
44
|
+
timeoutMs?: number;
|
|
45
|
+
/** HTTP status code indicating successful completion */
|
|
15
46
|
successStatus?: number;
|
|
47
|
+
/** HTTP status code indicating the operation is still pending */
|
|
16
48
|
pendingStatus?: number;
|
|
17
|
-
|
|
18
|
-
|
|
49
|
+
/** Function to extract the result from the response */
|
|
50
|
+
resultExtractor?: (response: unknown) => TResult;
|
|
51
|
+
/** Initial delay before the first poll attempt (in milliseconds) */
|
|
52
|
+
initialDelay?: number;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const enum PollStatus {
|
|
56
|
+
Success = "success",
|
|
57
|
+
Continue = "continue",
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Result of a poll operation
|
|
62
|
+
*/
|
|
63
|
+
export type PollResult<TResult = unknown> = {
|
|
64
|
+
result?: TResult;
|
|
65
|
+
status: PollStatus;
|
|
66
|
+
errorCount: number;
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
// Helper to calculate wait time with jitter and error backoff
|
|
70
|
+
const calculateWaitTime = (
|
|
71
|
+
baseInterval: number,
|
|
72
|
+
errorCount: number,
|
|
73
|
+
): number => {
|
|
74
|
+
// Jitter to avoid thundering herd
|
|
75
|
+
const jitter = Math.random() * JITTER_FACTOR * baseInterval;
|
|
76
|
+
// More backoff added if errors are seen
|
|
77
|
+
const errorBackoff = Math.min(
|
|
78
|
+
BASE_ERROR_BACKOFF_MS * (errorCount / 2),
|
|
79
|
+
baseInterval * 2, // Cap error backoff at 2x the base interval
|
|
80
|
+
);
|
|
81
|
+
return Math.floor(baseInterval + jitter + errorBackoff);
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
const processResponse = async <TResult = unknown>(
|
|
85
|
+
response: Response,
|
|
86
|
+
successStatus: number,
|
|
87
|
+
pendingStatus: number,
|
|
88
|
+
resultExtractor: (response: unknown) => TResult,
|
|
89
|
+
errorCount: number,
|
|
90
|
+
): Promise<PollResult<TResult>> => {
|
|
91
|
+
// Handle other error responses
|
|
92
|
+
if (!response.ok) {
|
|
93
|
+
return {
|
|
94
|
+
status: PollStatus.Continue,
|
|
95
|
+
// If for some reason the status is pending, we don't want to increment the error count
|
|
96
|
+
errorCount:
|
|
97
|
+
response.status === pendingStatus ? errorCount : errorCount + 1,
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// Check for successful completion
|
|
102
|
+
if (response.status === successStatus) {
|
|
103
|
+
try {
|
|
104
|
+
const resultJson = await response.json();
|
|
105
|
+
return {
|
|
106
|
+
result: resultExtractor(resultJson),
|
|
107
|
+
status: PollStatus.Success,
|
|
108
|
+
errorCount: 0,
|
|
109
|
+
};
|
|
110
|
+
} catch (error) {
|
|
111
|
+
throw new ZapierApiError(
|
|
112
|
+
"Result extractor failed to parse successful response as JSON",
|
|
113
|
+
{
|
|
114
|
+
statusCode: response.status,
|
|
115
|
+
cause: error,
|
|
116
|
+
},
|
|
117
|
+
);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// If it's not pending, it's unexpected
|
|
122
|
+
if (response.status !== pendingStatus) {
|
|
123
|
+
throw new ZapierApiError(
|
|
124
|
+
`Unexpected response status during polling: ${response.status}`,
|
|
125
|
+
{
|
|
126
|
+
statusCode: response.status,
|
|
127
|
+
},
|
|
128
|
+
);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// It's still pending, so we continue polling
|
|
132
|
+
return {
|
|
133
|
+
status: PollStatus.Continue,
|
|
134
|
+
errorCount: 0,
|
|
135
|
+
};
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Polls an endpoint until completion, timeout, or error
|
|
140
|
+
* @param options Configuration options for polling
|
|
141
|
+
* @returns The extracted result from the successful response
|
|
142
|
+
* @throws {ZapierValidationError} When the input parameters are invalid
|
|
143
|
+
* @throws {ZapierTimeoutError} When the operation times out
|
|
144
|
+
* @throws {ZapierApiError} When the API returns consecutive errors
|
|
145
|
+
*/
|
|
146
|
+
export async function pollUntilComplete<TResult = unknown>(
|
|
147
|
+
options: PollOptions<TResult>,
|
|
148
|
+
): Promise<TResult> {
|
|
19
149
|
const {
|
|
20
150
|
fetchPoll,
|
|
21
|
-
|
|
22
|
-
initialDelay =
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
resultExtractor = (response) => response,
|
|
151
|
+
timeoutMs = DEFAULT_TIMEOUT_MS,
|
|
152
|
+
initialDelay = DEFAULT_INITIAL_DELAY_MS,
|
|
153
|
+
successStatus = DEFAULT_SUCCESS_STATUS,
|
|
154
|
+
pendingStatus = DEFAULT_PENDING_STATUS,
|
|
155
|
+
resultExtractor = (response) => response as TResult,
|
|
27
156
|
} = options;
|
|
28
157
|
|
|
29
|
-
|
|
158
|
+
// Validate input parameters
|
|
159
|
+
if (timeoutMs <= 0) {
|
|
160
|
+
throw new ZapierValidationError("Timeout must be greater than 0", {
|
|
161
|
+
details: { timeoutMs },
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
if (initialDelay < 0) {
|
|
166
|
+
throw new ZapierValidationError("Initial delay must be non-negative", {
|
|
167
|
+
details: { initialDelay },
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const startTime = Date.now();
|
|
172
|
+
let attempts = 0;
|
|
30
173
|
let errorCount = 0;
|
|
31
174
|
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
175
|
+
// Build polling stages with the actual timeout appended
|
|
176
|
+
const pollingStages = [
|
|
177
|
+
...DEFAULT_POLLING_STAGES,
|
|
178
|
+
[timeoutMs + MAX_TIMEOUT_BUFFER_MS, DEFAULT_MAX_POLLING_INTERVAL_MS], // Up to timeout + 10s: poll every 10s
|
|
179
|
+
] as const satisfies Array<[number, number]>;
|
|
180
|
+
|
|
181
|
+
// Apply initial delay if specified
|
|
182
|
+
if (initialDelay > 0) {
|
|
183
|
+
await setTimeout(initialDelay);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
while (true) {
|
|
187
|
+
attempts++;
|
|
188
|
+
const elapsedTime = Date.now() - startTime;
|
|
189
|
+
|
|
190
|
+
// Find the current polling stage
|
|
191
|
+
const pollingInterval = pollingStages.find(
|
|
192
|
+
([maxTimeForStage, _interval]) => {
|
|
193
|
+
return elapsedTime < maxTimeForStage;
|
|
194
|
+
},
|
|
195
|
+
);
|
|
196
|
+
|
|
197
|
+
// If there isn't a current stage, throw timeout error
|
|
198
|
+
if (!pollingInterval) {
|
|
199
|
+
throw new ZapierTimeoutError(
|
|
200
|
+
`Operation timed out after ${Math.floor(elapsedTime / 1000)}s (${attempts} attempts)`,
|
|
201
|
+
{
|
|
202
|
+
attempts,
|
|
203
|
+
},
|
|
204
|
+
);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// Wait before polling (except on first attempt)
|
|
208
|
+
if (attempts > 1) {
|
|
209
|
+
const waitTime = calculateWaitTime(pollingInterval[1], errorCount);
|
|
210
|
+
await setTimeout(waitTime);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// Perform the poll request
|
|
214
|
+
try {
|
|
215
|
+
const response = await fetchPoll();
|
|
216
|
+
const {
|
|
217
|
+
result,
|
|
218
|
+
errorCount: newErrorCount,
|
|
219
|
+
status,
|
|
220
|
+
} = await processResponse<TResult>(
|
|
221
|
+
response,
|
|
222
|
+
successStatus,
|
|
223
|
+
pendingStatus,
|
|
224
|
+
resultExtractor,
|
|
225
|
+
errorCount,
|
|
226
|
+
);
|
|
227
|
+
errorCount = newErrorCount;
|
|
228
|
+
|
|
229
|
+
if (status === PollStatus.Success) {
|
|
230
|
+
return result as TResult;
|
|
47
231
|
}
|
|
48
|
-
} else {
|
|
49
|
-
// Error occurred - increment error count
|
|
50
|
-
errorCount++;
|
|
51
232
|
|
|
52
|
-
if (errorCount >=
|
|
233
|
+
if (errorCount >= MAX_CONSECUTIVE_ERRORS) {
|
|
53
234
|
// Too many consecutive errors, fail
|
|
54
235
|
throw new ZapierApiError(
|
|
55
236
|
`Poll request failed: ${response.status} ${response.statusText}`,
|
|
56
237
|
{ statusCode: response.status },
|
|
57
238
|
);
|
|
58
239
|
}
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
if (
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
240
|
+
} catch (error) {
|
|
241
|
+
errorCount++;
|
|
242
|
+
if (errorCount >= MAX_CONSECUTIVE_ERRORS) {
|
|
243
|
+
throw new ZapierApiError(
|
|
244
|
+
`Failed to poll after ${errorCount} consecutive errors: ${error instanceof Error ? error.message : String(error)}`,
|
|
245
|
+
{
|
|
246
|
+
cause: error,
|
|
247
|
+
},
|
|
248
|
+
);
|
|
65
249
|
}
|
|
66
250
|
}
|
|
251
|
+
// Continue polling if status is pending
|
|
67
252
|
}
|
|
68
|
-
|
|
69
|
-
throw new ZapierTimeoutError(
|
|
70
|
-
`Operation timed out after ${maxAttempts} attempts`,
|
|
71
|
-
{ attempts: maxAttempts, maxAttempts: maxAttempts },
|
|
72
|
-
);
|
|
73
253
|
}
|