@terreno/api 0.24.0 → 0.26.0
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/.ai/guidelines/core.md +1 -0
- package/README.md +5 -3
- package/dist/__tests__/versionCheckPlugin.test.js +62 -2
- package/dist/api.query.test.js +99 -0
- package/dist/auth.compile.test.d.ts +1 -0
- package/dist/auth.compile.test.js +201 -0
- package/dist/auth.js +38 -7
- package/dist/auth.test.js +119 -1
- package/dist/betterAuthApp.test.js +1 -2
- package/dist/betterAuthSetup.test.js +76 -0
- package/dist/expressServer.js +6 -6
- package/dist/expressServer.test.js +37 -8
- package/dist/httpClient.d.ts +119 -0
- package/dist/httpClient.js +412 -0
- package/dist/httpClient.test.d.ts +1 -0
- package/dist/httpClient.test.js +1470 -0
- package/dist/index.d.ts +10 -2
- package/dist/index.js +29 -3
- package/dist/openApi.test.js +51 -0
- package/dist/realtime/queryStore.d.ts +3 -3
- package/dist/realtime/queryStore.js +0 -1
- package/dist/realtime/realtime.test.js +22 -0
- package/dist/tests/fixtures/compileAuthEntry.d.ts +1 -0
- package/dist/tests/fixtures/compileAuthEntry.js +37 -0
- package/package.json +2 -2
- package/src/__tests__/versionCheckPlugin.test.ts +46 -2
- package/src/api.query.test.ts +59 -0
- package/src/auth.compile.test.ts +106 -0
- package/src/auth.test.ts +81 -1
- package/src/auth.ts +49 -7
- package/src/betterAuthApp.test.ts +3 -3
- package/src/betterAuthSetup.test.ts +65 -0
- package/src/expressServer.test.ts +29 -8
- package/src/expressServer.ts +1 -1
- package/src/httpClient.test.ts +979 -0
- package/src/httpClient.ts +464 -0
- package/src/index.ts +41 -2
- package/src/openApi.test.ts +53 -0
- package/src/realtime/queryStore.ts +6 -7
- package/src/realtime/realtime.test.ts +28 -2
- package/src/realtime/realtimeApp.ts +3 -3
- package/src/tests/fixtures/compileAuthEntry.ts +43 -0
- package/dist/notifiers/index.d.ts +0 -3
- package/dist/notifiers/index.js +0 -19
- package/dist/realtime/index.d.ts +0 -6
- package/dist/realtime/index.js +0 -27
- package/src/notifiers/index.ts +0 -3
- package/src/realtime/index.ts +0 -34
|
@@ -0,0 +1,979 @@
|
|
|
1
|
+
import {describe, expect, it} from "bun:test";
|
|
2
|
+
import type {Server} from "node:http";
|
|
3
|
+
import type {AddressInfo} from "node:net";
|
|
4
|
+
import {AxiosError, type AxiosRequestHeaders, type AxiosResponse, isAxiosError} from "axios";
|
|
5
|
+
import express from "express";
|
|
6
|
+
|
|
7
|
+
import {APIError} from "./errors";
|
|
8
|
+
import {
|
|
9
|
+
createAuthenticatedClient,
|
|
10
|
+
type HttpClientLogger,
|
|
11
|
+
markRetryUnsafe,
|
|
12
|
+
normalizeApiError,
|
|
13
|
+
withApiErrorHandling,
|
|
14
|
+
} from "./httpClient";
|
|
15
|
+
|
|
16
|
+
const startTestServer = async (
|
|
17
|
+
configure: (app: express.Express) => void
|
|
18
|
+
): Promise<{baseURL: string; close: () => Promise<void>}> => {
|
|
19
|
+
const app = express();
|
|
20
|
+
app.use(express.json());
|
|
21
|
+
app.use(express.urlencoded({extended: false}));
|
|
22
|
+
configure(app);
|
|
23
|
+
const server = await new Promise<Server>((resolve) => {
|
|
24
|
+
const listening = app.listen(0, () => resolve(listening));
|
|
25
|
+
});
|
|
26
|
+
const {port} = server.address() as AddressInfo;
|
|
27
|
+
return {
|
|
28
|
+
baseURL: `http://127.0.0.1:${port}`,
|
|
29
|
+
close: () => new Promise((resolve) => server.close(() => resolve())),
|
|
30
|
+
};
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
// Tests use a 1ms base delay so retry backoff doesn't slow the suite.
|
|
34
|
+
const FAST_RETRY = {baseDelayMs: 1};
|
|
35
|
+
|
|
36
|
+
const createRecordingLogger = (): {
|
|
37
|
+
logger: HttpClientLogger;
|
|
38
|
+
entries: {level: string; msg: string; args: unknown[]}[];
|
|
39
|
+
} => {
|
|
40
|
+
const entries: {level: string; msg: string; args: unknown[]}[] = [];
|
|
41
|
+
const record =
|
|
42
|
+
(level: string) =>
|
|
43
|
+
(msg: string, ...args: unknown[]): void => {
|
|
44
|
+
entries.push({args, level, msg});
|
|
45
|
+
};
|
|
46
|
+
return {
|
|
47
|
+
entries,
|
|
48
|
+
logger: {debug: record("debug"), error: record("error"), warn: record("warn")},
|
|
49
|
+
};
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
const CONTEXT = {apiName: "testApi", operation: "getWidget"};
|
|
53
|
+
|
|
54
|
+
const buildAxiosError = ({
|
|
55
|
+
status,
|
|
56
|
+
data,
|
|
57
|
+
code,
|
|
58
|
+
}: {
|
|
59
|
+
status?: number;
|
|
60
|
+
data?: unknown;
|
|
61
|
+
code?: string;
|
|
62
|
+
}): AxiosError => {
|
|
63
|
+
const config = {headers: {} as AxiosRequestHeaders, url: "/widgets"};
|
|
64
|
+
let response: AxiosResponse | undefined;
|
|
65
|
+
if (status !== undefined) {
|
|
66
|
+
response = {
|
|
67
|
+
config,
|
|
68
|
+
data,
|
|
69
|
+
headers: {},
|
|
70
|
+
status,
|
|
71
|
+
statusText: "",
|
|
72
|
+
} as AxiosResponse;
|
|
73
|
+
}
|
|
74
|
+
return new AxiosError(
|
|
75
|
+
status !== undefined ? `Request failed with status code ${status}` : "Network Error",
|
|
76
|
+
code,
|
|
77
|
+
config,
|
|
78
|
+
undefined,
|
|
79
|
+
response
|
|
80
|
+
);
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
describe("normalizeApiError", () => {
|
|
84
|
+
it("classifies HTTP statuses from an axios error response", () => {
|
|
85
|
+
const cases: [number, string][] = [
|
|
86
|
+
[429, "rateLimited"],
|
|
87
|
+
[401, "unauthorized"],
|
|
88
|
+
[403, "unauthorized"],
|
|
89
|
+
[404, "notFound"],
|
|
90
|
+
[400, "validation"],
|
|
91
|
+
[422, "validation"],
|
|
92
|
+
[500, "server"],
|
|
93
|
+
[503, "server"],
|
|
94
|
+
];
|
|
95
|
+
for (const [status, classification] of cases) {
|
|
96
|
+
const normalized = normalizeApiError(buildAxiosError({status}), CONTEXT);
|
|
97
|
+
expect(normalized.isAxios).toBe(true);
|
|
98
|
+
expect(normalized.statusCode).toBe(status);
|
|
99
|
+
expect(normalized.classification).toBe(classification as typeof normalized.classification);
|
|
100
|
+
}
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
it("extracts messages from a {message} response body", () => {
|
|
104
|
+
const error = buildAxiosError({data: {message: "Widget not found"}, status: 404});
|
|
105
|
+
const normalized = normalizeApiError(error, CONTEXT);
|
|
106
|
+
expect(normalized.messages).toEqual(["Widget not found"]);
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
it("extracts messages from a JSONAPI-style {errors: [{title, detail}]} body", () => {
|
|
110
|
+
const error = buildAxiosError({
|
|
111
|
+
data: {
|
|
112
|
+
errors: [
|
|
113
|
+
{detail: "name is required", title: "Validation failed"},
|
|
114
|
+
{title: "Another problem"},
|
|
115
|
+
],
|
|
116
|
+
},
|
|
117
|
+
status: 422,
|
|
118
|
+
});
|
|
119
|
+
const normalized = normalizeApiError(error, CONTEXT);
|
|
120
|
+
expect(normalized.messages).toEqual(["Validation failed: name is required", "Another problem"]);
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
it("extracts a plain-string response body as the message", () => {
|
|
124
|
+
const error = buildAxiosError({data: "Service unavailable", status: 503});
|
|
125
|
+
const normalized = normalizeApiError(error, CONTEXT);
|
|
126
|
+
expect(normalized.messages).toEqual(["Service unavailable"]);
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
it("falls back to the axios error message when the body has no recognizable message", () => {
|
|
130
|
+
const error = buildAxiosError({data: {unexpected: true}, status: 500});
|
|
131
|
+
const normalized = normalizeApiError(error, CONTEXT);
|
|
132
|
+
expect(normalized.messages).toEqual(["Request failed with status code 500"]);
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
it("classifies an axios error without a response as network", () => {
|
|
136
|
+
const error = buildAxiosError({code: "ECONNREFUSED"});
|
|
137
|
+
const normalized = normalizeApiError(error, CONTEXT);
|
|
138
|
+
expect(normalized.isAxios).toBe(true);
|
|
139
|
+
expect(normalized.statusCode).toBeUndefined();
|
|
140
|
+
expect(normalized.classification).toBe("network");
|
|
141
|
+
expect(normalized.messages).toEqual(["Network Error"]);
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
it("classifies a sub-400 response status as unknown", () => {
|
|
145
|
+
const normalized = normalizeApiError(buildAxiosError({status: 302}), CONTEXT);
|
|
146
|
+
expect(normalized.classification).toBe("unknown");
|
|
147
|
+
expect(normalized.statusCode).toBe(302);
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
it("extracts detail-only JSONAPI error entries", () => {
|
|
151
|
+
const error = buildAxiosError({data: {errors: [{detail: "just a detail"}]}, status: 400});
|
|
152
|
+
const normalized = normalizeApiError(error, CONTEXT);
|
|
153
|
+
expect(normalized.messages).toEqual(["just a detail"]);
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
it("falls back to the axios message for empty-string, empty-message, and empty-errors bodies", () => {
|
|
157
|
+
for (const data of ["", {message: ""}, {errors: []}]) {
|
|
158
|
+
const normalized = normalizeApiError(buildAxiosError({data, status: 500}), CONTEXT);
|
|
159
|
+
expect(normalized.messages).toEqual(["Request failed with status code 500"]);
|
|
160
|
+
}
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
it("falls back to the axios message when the errors array has no usable entries", () => {
|
|
164
|
+
const error = buildAxiosError({data: {errors: ["oops", null, 42, {title: 5}]}, status: 500});
|
|
165
|
+
const normalized = normalizeApiError(error, CONTEXT);
|
|
166
|
+
expect(normalized.messages).toEqual(["Request failed with status code 500"]);
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
it("truncates long plain-string bodies so unbounded payloads never reach the logger", () => {
|
|
170
|
+
const error = buildAxiosError({data: "x".repeat(2000), status: 503});
|
|
171
|
+
const normalized = normalizeApiError(error, CONTEXT);
|
|
172
|
+
expect(normalized.messages[0].length).toBeLessThanOrEqual(512);
|
|
173
|
+
expect(normalized.messages[0].endsWith("…")).toBe(true);
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
it("classifies a plain Error as unknown and preserves its message", () => {
|
|
177
|
+
const normalized = normalizeApiError(new Error("boom"), CONTEXT);
|
|
178
|
+
expect(normalized.isAxios).toBe(false);
|
|
179
|
+
expect(normalized.statusCode).toBeUndefined();
|
|
180
|
+
expect(normalized.classification).toBe("unknown");
|
|
181
|
+
expect(normalized.messages).toEqual(["boom"]);
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
it("classifies a non-Error thrown value as unknown with a stringified message", () => {
|
|
185
|
+
const normalized = normalizeApiError("total failure", CONTEXT);
|
|
186
|
+
expect(normalized.classification).toBe("unknown");
|
|
187
|
+
expect(normalized.messages).toEqual(["total failure"]);
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
it("echoes apiName and operation for structured logging", () => {
|
|
191
|
+
const normalized = normalizeApiError(new Error("boom"), CONTEXT);
|
|
192
|
+
expect(normalized.apiName).toBe("testApi");
|
|
193
|
+
expect(normalized.operation).toBe("getWidget");
|
|
194
|
+
});
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
describe("withApiErrorHandling", () => {
|
|
198
|
+
it("returns the wrapped function's result on success and logs nothing", async () => {
|
|
199
|
+
const {logger, entries} = createRecordingLogger();
|
|
200
|
+
const result = await withApiErrorHandling(async () => "ok", {...CONTEXT, logger});
|
|
201
|
+
expect(result).toBe("ok");
|
|
202
|
+
expect(entries).toHaveLength(0);
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
it("logs the normalized error and rethrows the original error by default", async () => {
|
|
206
|
+
const {logger, entries} = createRecordingLogger();
|
|
207
|
+
const original = buildAxiosError({data: {message: "nope"}, status: 404});
|
|
208
|
+
let caught: unknown;
|
|
209
|
+
try {
|
|
210
|
+
await withApiErrorHandling(
|
|
211
|
+
async () => {
|
|
212
|
+
throw original;
|
|
213
|
+
},
|
|
214
|
+
{...CONTEXT, logger}
|
|
215
|
+
);
|
|
216
|
+
} catch (error) {
|
|
217
|
+
caught = error;
|
|
218
|
+
}
|
|
219
|
+
expect(caught).toBe(original);
|
|
220
|
+
expect(entries).toHaveLength(1);
|
|
221
|
+
expect(entries[0].level).toBe("error");
|
|
222
|
+
expect(entries[0].msg).toContain("testApi");
|
|
223
|
+
expect(entries[0].msg).toContain("getWidget");
|
|
224
|
+
const normalized = entries[0].args[0] as {statusCode?: number; classification?: string};
|
|
225
|
+
expect(normalized.statusCode).toBe(404);
|
|
226
|
+
expect(normalized.classification).toBe("notFound");
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
it("converts to an APIError when rethrowAs is apiError, logging via APIError only", async () => {
|
|
230
|
+
const {logger, entries} = createRecordingLogger();
|
|
231
|
+
const original = buildAxiosError({data: {message: "Rate limit exceeded"}, status: 429});
|
|
232
|
+
let caught: unknown;
|
|
233
|
+
try {
|
|
234
|
+
await withApiErrorHandling(
|
|
235
|
+
async () => {
|
|
236
|
+
throw original;
|
|
237
|
+
},
|
|
238
|
+
{...CONTEXT, logger, rethrowAs: "apiError"}
|
|
239
|
+
);
|
|
240
|
+
} catch (error) {
|
|
241
|
+
caught = error;
|
|
242
|
+
}
|
|
243
|
+
expect(caught).toBeInstanceOf(APIError);
|
|
244
|
+
const apiError = caught as APIError;
|
|
245
|
+
expect(apiError.status).toBe(429);
|
|
246
|
+
expect(apiError.title).toBe("testApi getWidget request failed");
|
|
247
|
+
expect(apiError.detail).toBe("Rate limit exceeded");
|
|
248
|
+
expect(apiError.error).toBe(original);
|
|
249
|
+
expect(apiError.meta?.classification).toBe("rateLimited");
|
|
250
|
+
// Logged exactly once: the APIError constructor logs, so the wrapper must not.
|
|
251
|
+
expect(entries).toHaveLength(0);
|
|
252
|
+
});
|
|
253
|
+
|
|
254
|
+
it("defaults the APIError status to 500 when the failure has no status code", async () => {
|
|
255
|
+
const {logger} = createRecordingLogger();
|
|
256
|
+
let caught: unknown;
|
|
257
|
+
try {
|
|
258
|
+
await withApiErrorHandling(
|
|
259
|
+
async () => {
|
|
260
|
+
throw new Error("boom");
|
|
261
|
+
},
|
|
262
|
+
{...CONTEXT, logger, rethrowAs: "apiError"}
|
|
263
|
+
);
|
|
264
|
+
} catch (error) {
|
|
265
|
+
caught = error;
|
|
266
|
+
}
|
|
267
|
+
expect(caught).toBeInstanceOf(APIError);
|
|
268
|
+
expect((caught as APIError).status).toBe(500);
|
|
269
|
+
});
|
|
270
|
+
|
|
271
|
+
it("clamps sub-400 response statuses to a 500 APIError", async () => {
|
|
272
|
+
const {logger} = createRecordingLogger();
|
|
273
|
+
let caught: unknown;
|
|
274
|
+
try {
|
|
275
|
+
await withApiErrorHandling(
|
|
276
|
+
async () => {
|
|
277
|
+
throw buildAxiosError({status: 302});
|
|
278
|
+
},
|
|
279
|
+
{...CONTEXT, logger, rethrowAs: "apiError"}
|
|
280
|
+
);
|
|
281
|
+
} catch (error) {
|
|
282
|
+
caught = error;
|
|
283
|
+
}
|
|
284
|
+
expect((caught as APIError).status).toBe(500);
|
|
285
|
+
});
|
|
286
|
+
|
|
287
|
+
it("applies the redactError hook before logging", async () => {
|
|
288
|
+
const {logger, entries} = createRecordingLogger();
|
|
289
|
+
const original = buildAxiosError({data: {message: "patient 12345 not found"}, status: 404});
|
|
290
|
+
let caught: unknown;
|
|
291
|
+
try {
|
|
292
|
+
await withApiErrorHandling(
|
|
293
|
+
async () => {
|
|
294
|
+
throw original;
|
|
295
|
+
},
|
|
296
|
+
{
|
|
297
|
+
...CONTEXT,
|
|
298
|
+
logger,
|
|
299
|
+
redactError: (normalized) => ({...normalized, messages: ["[redacted]"]}),
|
|
300
|
+
}
|
|
301
|
+
);
|
|
302
|
+
} catch (error) {
|
|
303
|
+
caught = error;
|
|
304
|
+
}
|
|
305
|
+
expect(caught).toBe(original);
|
|
306
|
+
const logged = entries[0].args[0] as {messages: string[]};
|
|
307
|
+
expect(logged.messages).toEqual(["[redacted]"]);
|
|
308
|
+
});
|
|
309
|
+
|
|
310
|
+
it("uses redacted messages in the APIError detail when combined with rethrowAs apiError", async () => {
|
|
311
|
+
const {logger} = createRecordingLogger();
|
|
312
|
+
let caught: unknown;
|
|
313
|
+
try {
|
|
314
|
+
await withApiErrorHandling(
|
|
315
|
+
async () => {
|
|
316
|
+
throw buildAxiosError({data: {message: "patient 12345 not found"}, status: 404});
|
|
317
|
+
},
|
|
318
|
+
{
|
|
319
|
+
...CONTEXT,
|
|
320
|
+
logger,
|
|
321
|
+
redactError: (normalized) => ({...normalized, messages: ["[redacted]"]}),
|
|
322
|
+
rethrowAs: "apiError",
|
|
323
|
+
}
|
|
324
|
+
);
|
|
325
|
+
} catch (error) {
|
|
326
|
+
caught = error;
|
|
327
|
+
}
|
|
328
|
+
const apiError = caught as APIError;
|
|
329
|
+
expect(apiError.detail).toBe("[redacted]");
|
|
330
|
+
expect(apiError.message).not.toContain("patient 12345");
|
|
331
|
+
});
|
|
332
|
+
|
|
333
|
+
it("falls back to a generic detail when redactError strips all messages", async () => {
|
|
334
|
+
const {logger} = createRecordingLogger();
|
|
335
|
+
let caught: unknown;
|
|
336
|
+
try {
|
|
337
|
+
await withApiErrorHandling(
|
|
338
|
+
async () => {
|
|
339
|
+
throw buildAxiosError({data: {message: "sensitive"}, status: 404});
|
|
340
|
+
},
|
|
341
|
+
{
|
|
342
|
+
...CONTEXT,
|
|
343
|
+
logger,
|
|
344
|
+
redactError: (normalized) => ({...normalized, messages: []}),
|
|
345
|
+
rethrowAs: "apiError",
|
|
346
|
+
}
|
|
347
|
+
);
|
|
348
|
+
} catch (error) {
|
|
349
|
+
caught = error;
|
|
350
|
+
}
|
|
351
|
+
expect((caught as APIError).detail).toBe("unknown error");
|
|
352
|
+
});
|
|
353
|
+
});
|
|
354
|
+
|
|
355
|
+
describe("createAuthenticatedClient", () => {
|
|
356
|
+
describe("bearer strategy", () => {
|
|
357
|
+
it("attaches the Authorization header and caches the token across requests", async () => {
|
|
358
|
+
const seenAuthHeaders: (string | undefined)[] = [];
|
|
359
|
+
const server = await startTestServer((app) => {
|
|
360
|
+
app.get("/widgets", (req, res) => {
|
|
361
|
+
seenAuthHeaders.push(req.headers.authorization);
|
|
362
|
+
res.json({ok: true});
|
|
363
|
+
});
|
|
364
|
+
});
|
|
365
|
+
try {
|
|
366
|
+
let tokenFetches = 0;
|
|
367
|
+
const client = createAuthenticatedClient({
|
|
368
|
+
auth: {
|
|
369
|
+
getToken: async () => {
|
|
370
|
+
tokenFetches += 1;
|
|
371
|
+
return "token-abc";
|
|
372
|
+
},
|
|
373
|
+
type: "bearer",
|
|
374
|
+
},
|
|
375
|
+
baseURL: server.baseURL,
|
|
376
|
+
});
|
|
377
|
+
await client.axios.get("/widgets");
|
|
378
|
+
await client.axios.get("/widgets");
|
|
379
|
+
expect(seenAuthHeaders).toEqual(["Bearer token-abc", "Bearer token-abc"]);
|
|
380
|
+
expect(tokenFetches).toBe(1);
|
|
381
|
+
} finally {
|
|
382
|
+
await server.close();
|
|
383
|
+
}
|
|
384
|
+
});
|
|
385
|
+
|
|
386
|
+
it("re-fetches the token after invalidateToken", async () => {
|
|
387
|
+
const server = await startTestServer((app) => {
|
|
388
|
+
app.get("/widgets", (_req, res) => {
|
|
389
|
+
res.json({ok: true});
|
|
390
|
+
});
|
|
391
|
+
});
|
|
392
|
+
try {
|
|
393
|
+
let tokenFetches = 0;
|
|
394
|
+
const client = createAuthenticatedClient({
|
|
395
|
+
auth: {
|
|
396
|
+
getToken: async () => {
|
|
397
|
+
tokenFetches += 1;
|
|
398
|
+
return `token-${tokenFetches}`;
|
|
399
|
+
},
|
|
400
|
+
type: "bearer",
|
|
401
|
+
},
|
|
402
|
+
baseURL: server.baseURL,
|
|
403
|
+
});
|
|
404
|
+
await client.axios.get("/widgets");
|
|
405
|
+
client.invalidateToken();
|
|
406
|
+
await client.axios.get("/widgets");
|
|
407
|
+
expect(tokenFetches).toBe(2);
|
|
408
|
+
} finally {
|
|
409
|
+
await server.close();
|
|
410
|
+
}
|
|
411
|
+
});
|
|
412
|
+
});
|
|
413
|
+
|
|
414
|
+
describe("apiKey strategy", () => {
|
|
415
|
+
it("attaches the key to the configured header", async () => {
|
|
416
|
+
const seenKeys: (string | undefined)[] = [];
|
|
417
|
+
const server = await startTestServer((app) => {
|
|
418
|
+
app.get("/widgets", (req, res) => {
|
|
419
|
+
seenKeys.push(req.headers["x-api-key"] as string | undefined);
|
|
420
|
+
res.json({ok: true});
|
|
421
|
+
});
|
|
422
|
+
});
|
|
423
|
+
try {
|
|
424
|
+
const client = createAuthenticatedClient({
|
|
425
|
+
auth: {getKey: async () => "secret-key", header: "X-Api-Key", type: "apiKey"},
|
|
426
|
+
baseURL: server.baseURL,
|
|
427
|
+
});
|
|
428
|
+
await client.axios.get("/widgets");
|
|
429
|
+
expect(seenKeys).toEqual(["secret-key"]);
|
|
430
|
+
} finally {
|
|
431
|
+
await server.close();
|
|
432
|
+
}
|
|
433
|
+
});
|
|
434
|
+
});
|
|
435
|
+
|
|
436
|
+
describe("oauth2 strategy", () => {
|
|
437
|
+
const configureOauthServer = (
|
|
438
|
+
app: express.Express,
|
|
439
|
+
state: {tokenFetches: number; validToken: string}
|
|
440
|
+
): void => {
|
|
441
|
+
app.post("/oauth/token", (req, res) => {
|
|
442
|
+
state.tokenFetches += 1;
|
|
443
|
+
const authHeader = req.headers.authorization ?? "";
|
|
444
|
+
const decoded = Buffer.from(authHeader.replace("Basic ", ""), "base64").toString();
|
|
445
|
+
if (decoded !== "client-id:client-secret" || req.body.grant_type !== "client_credentials") {
|
|
446
|
+
res.status(400).json({message: "bad token request"});
|
|
447
|
+
return;
|
|
448
|
+
}
|
|
449
|
+
res.json({access_token: state.validToken});
|
|
450
|
+
});
|
|
451
|
+
};
|
|
452
|
+
|
|
453
|
+
it("fetches a client-credentials token and sends it as a bearer", async () => {
|
|
454
|
+
const state = {tokenFetches: 0, validToken: "oauth-token-1"};
|
|
455
|
+
const seenAuthHeaders: (string | undefined)[] = [];
|
|
456
|
+
const server = await startTestServer((app) => {
|
|
457
|
+
configureOauthServer(app, state);
|
|
458
|
+
app.get("/widgets", (req, res) => {
|
|
459
|
+
seenAuthHeaders.push(req.headers.authorization);
|
|
460
|
+
res.json({ok: true});
|
|
461
|
+
});
|
|
462
|
+
});
|
|
463
|
+
try {
|
|
464
|
+
const client = createAuthenticatedClient({
|
|
465
|
+
auth: {
|
|
466
|
+
credentials: {clientId: "client-id", clientSecret: "client-secret"},
|
|
467
|
+
refreshOn401: true,
|
|
468
|
+
tokenUrl: `${server.baseURL}/oauth/token`,
|
|
469
|
+
type: "oauth2",
|
|
470
|
+
},
|
|
471
|
+
baseURL: server.baseURL,
|
|
472
|
+
});
|
|
473
|
+
await client.axios.get("/widgets");
|
|
474
|
+
await client.axios.get("/widgets");
|
|
475
|
+
expect(seenAuthHeaders).toEqual(["Bearer oauth-token-1", "Bearer oauth-token-1"]);
|
|
476
|
+
expect(state.tokenFetches).toBe(1);
|
|
477
|
+
} finally {
|
|
478
|
+
await server.close();
|
|
479
|
+
}
|
|
480
|
+
});
|
|
481
|
+
|
|
482
|
+
it("refreshes the token and retries exactly once on a 401", async () => {
|
|
483
|
+
const state = {tokenFetches: 0, validToken: "stale-token"};
|
|
484
|
+
const server = await startTestServer((app) => {
|
|
485
|
+
configureOauthServer(app, state);
|
|
486
|
+
app.get("/widgets", (req, res) => {
|
|
487
|
+
if (req.headers.authorization === "Bearer fresh-token") {
|
|
488
|
+
res.json({ok: true});
|
|
489
|
+
return;
|
|
490
|
+
}
|
|
491
|
+
// Invalidate the stale token server-side so the refresh fetches a good one.
|
|
492
|
+
state.validToken = "fresh-token";
|
|
493
|
+
res.status(401).json({message: "expired"});
|
|
494
|
+
});
|
|
495
|
+
});
|
|
496
|
+
try {
|
|
497
|
+
const client = createAuthenticatedClient({
|
|
498
|
+
auth: {
|
|
499
|
+
credentials: {clientId: "client-id", clientSecret: "client-secret"},
|
|
500
|
+
refreshOn401: true,
|
|
501
|
+
tokenUrl: `${server.baseURL}/oauth/token`,
|
|
502
|
+
type: "oauth2",
|
|
503
|
+
},
|
|
504
|
+
baseURL: server.baseURL,
|
|
505
|
+
});
|
|
506
|
+
const response = await client.axios.get("/widgets");
|
|
507
|
+
expect(response.data.ok).toBe(true);
|
|
508
|
+
expect(state.tokenFetches).toBe(2);
|
|
509
|
+
} finally {
|
|
510
|
+
await server.close();
|
|
511
|
+
}
|
|
512
|
+
});
|
|
513
|
+
|
|
514
|
+
it("propagates a persistent 401 after a single refresh attempt", async () => {
|
|
515
|
+
const state = {tokenFetches: 0, validToken: "always-stale"};
|
|
516
|
+
let widgetRequests = 0;
|
|
517
|
+
const server = await startTestServer((app) => {
|
|
518
|
+
configureOauthServer(app, state);
|
|
519
|
+
app.get("/widgets", (_req, res) => {
|
|
520
|
+
widgetRequests += 1;
|
|
521
|
+
res.status(401).json({message: "still expired"});
|
|
522
|
+
});
|
|
523
|
+
});
|
|
524
|
+
try {
|
|
525
|
+
const client = createAuthenticatedClient({
|
|
526
|
+
auth: {
|
|
527
|
+
credentials: {clientId: "client-id", clientSecret: "client-secret"},
|
|
528
|
+
refreshOn401: true,
|
|
529
|
+
tokenUrl: `${server.baseURL}/oauth/token`,
|
|
530
|
+
type: "oauth2",
|
|
531
|
+
},
|
|
532
|
+
baseURL: server.baseURL,
|
|
533
|
+
});
|
|
534
|
+
let caught: unknown;
|
|
535
|
+
try {
|
|
536
|
+
await client.axios.get("/widgets");
|
|
537
|
+
} catch (error) {
|
|
538
|
+
caught = error;
|
|
539
|
+
}
|
|
540
|
+
expect(isAxiosError(caught)).toBe(true);
|
|
541
|
+
expect((caught as AxiosError).response?.status).toBe(401);
|
|
542
|
+
expect(widgetRequests).toBe(2);
|
|
543
|
+
expect(state.tokenFetches).toBe(2);
|
|
544
|
+
} finally {
|
|
545
|
+
await server.close();
|
|
546
|
+
}
|
|
547
|
+
});
|
|
548
|
+
});
|
|
549
|
+
|
|
550
|
+
describe("retry policy", () => {
|
|
551
|
+
const NO_AUTH = {getToken: async () => "t", type: "bearer"} as const;
|
|
552
|
+
|
|
553
|
+
it("retries an idempotent GET on 5xx and succeeds within maxAttempts", async () => {
|
|
554
|
+
let attempts = 0;
|
|
555
|
+
const server = await startTestServer((app) => {
|
|
556
|
+
app.get("/flaky", (_req, res) => {
|
|
557
|
+
attempts += 1;
|
|
558
|
+
if (attempts < 3) {
|
|
559
|
+
res.status(500).json({message: "boom"});
|
|
560
|
+
return;
|
|
561
|
+
}
|
|
562
|
+
res.json({ok: true});
|
|
563
|
+
});
|
|
564
|
+
});
|
|
565
|
+
try {
|
|
566
|
+
const client = createAuthenticatedClient({
|
|
567
|
+
auth: NO_AUTH,
|
|
568
|
+
baseURL: server.baseURL,
|
|
569
|
+
retry: FAST_RETRY,
|
|
570
|
+
});
|
|
571
|
+
const response = await client.axios.get("/flaky");
|
|
572
|
+
expect(response.data.ok).toBe(true);
|
|
573
|
+
expect(attempts).toBe(3);
|
|
574
|
+
} finally {
|
|
575
|
+
await server.close();
|
|
576
|
+
}
|
|
577
|
+
});
|
|
578
|
+
|
|
579
|
+
it("retries a GET on 429 rate limiting", async () => {
|
|
580
|
+
let attempts = 0;
|
|
581
|
+
const server = await startTestServer((app) => {
|
|
582
|
+
app.get("/limited", (_req, res) => {
|
|
583
|
+
attempts += 1;
|
|
584
|
+
if (attempts === 1) {
|
|
585
|
+
res.set("Retry-After", "0").status(429).json({message: "slow down"});
|
|
586
|
+
return;
|
|
587
|
+
}
|
|
588
|
+
res.json({ok: true});
|
|
589
|
+
});
|
|
590
|
+
});
|
|
591
|
+
try {
|
|
592
|
+
const client = createAuthenticatedClient({
|
|
593
|
+
auth: NO_AUTH,
|
|
594
|
+
baseURL: server.baseURL,
|
|
595
|
+
retry: FAST_RETRY,
|
|
596
|
+
});
|
|
597
|
+
const response = await client.axios.get("/limited");
|
|
598
|
+
expect(response.data.ok).toBe(true);
|
|
599
|
+
expect(attempts).toBe(2);
|
|
600
|
+
} finally {
|
|
601
|
+
await server.close();
|
|
602
|
+
}
|
|
603
|
+
});
|
|
604
|
+
|
|
605
|
+
it("rejects with the original error once maxAttempts is exhausted", async () => {
|
|
606
|
+
let attempts = 0;
|
|
607
|
+
const server = await startTestServer((app) => {
|
|
608
|
+
app.get("/down", (_req, res) => {
|
|
609
|
+
attempts += 1;
|
|
610
|
+
res.status(503).json({message: "unavailable"});
|
|
611
|
+
});
|
|
612
|
+
});
|
|
613
|
+
try {
|
|
614
|
+
const client = createAuthenticatedClient({
|
|
615
|
+
auth: NO_AUTH,
|
|
616
|
+
baseURL: server.baseURL,
|
|
617
|
+
retry: {...FAST_RETRY, maxAttempts: 2},
|
|
618
|
+
});
|
|
619
|
+
let caught: unknown;
|
|
620
|
+
try {
|
|
621
|
+
await client.axios.get("/down");
|
|
622
|
+
} catch (error) {
|
|
623
|
+
caught = error;
|
|
624
|
+
}
|
|
625
|
+
expect(isAxiosError(caught)).toBe(true);
|
|
626
|
+
expect((caught as AxiosError).response?.status).toBe(503);
|
|
627
|
+
expect(attempts).toBe(2);
|
|
628
|
+
} finally {
|
|
629
|
+
await server.close();
|
|
630
|
+
}
|
|
631
|
+
});
|
|
632
|
+
|
|
633
|
+
it("does not retry a POST by default even on 5xx", async () => {
|
|
634
|
+
let attempts = 0;
|
|
635
|
+
const server = await startTestServer((app) => {
|
|
636
|
+
app.post("/orders", (_req, res) => {
|
|
637
|
+
attempts += 1;
|
|
638
|
+
res.status(500).json({message: "boom"});
|
|
639
|
+
});
|
|
640
|
+
});
|
|
641
|
+
try {
|
|
642
|
+
const client = createAuthenticatedClient({
|
|
643
|
+
auth: NO_AUTH,
|
|
644
|
+
baseURL: server.baseURL,
|
|
645
|
+
retry: FAST_RETRY,
|
|
646
|
+
});
|
|
647
|
+
let caught: unknown;
|
|
648
|
+
try {
|
|
649
|
+
await client.axios.post("/orders", {widget: 1});
|
|
650
|
+
} catch (error) {
|
|
651
|
+
caught = error;
|
|
652
|
+
}
|
|
653
|
+
expect(isAxiosError(caught)).toBe(true);
|
|
654
|
+
expect(attempts).toBe(1);
|
|
655
|
+
} finally {
|
|
656
|
+
await server.close();
|
|
657
|
+
}
|
|
658
|
+
});
|
|
659
|
+
|
|
660
|
+
it("retries a POST when the request opts in via markRetryUnsafe, preserving config", async () => {
|
|
661
|
+
let attempts = 0;
|
|
662
|
+
const seenTestHeaders: (string | undefined)[] = [];
|
|
663
|
+
const server = await startTestServer((app) => {
|
|
664
|
+
app.post("/orders", (req, res) => {
|
|
665
|
+
attempts += 1;
|
|
666
|
+
seenTestHeaders.push(req.headers["x-test"] as string | undefined);
|
|
667
|
+
if (attempts === 1) {
|
|
668
|
+
res.status(500).json({message: "boom"});
|
|
669
|
+
return;
|
|
670
|
+
}
|
|
671
|
+
res.json({ok: true});
|
|
672
|
+
});
|
|
673
|
+
});
|
|
674
|
+
try {
|
|
675
|
+
const client = createAuthenticatedClient({
|
|
676
|
+
auth: NO_AUTH,
|
|
677
|
+
baseURL: server.baseURL,
|
|
678
|
+
retry: FAST_RETRY,
|
|
679
|
+
});
|
|
680
|
+
const response = await client.axios.post(
|
|
681
|
+
"/orders",
|
|
682
|
+
{widget: 1},
|
|
683
|
+
markRetryUnsafe({headers: {"X-Test": "kept"}})
|
|
684
|
+
);
|
|
685
|
+
expect(response.data.ok).toBe(true);
|
|
686
|
+
expect(attempts).toBe(2);
|
|
687
|
+
expect(seenTestHeaders).toEqual(["kept", "kept"]);
|
|
688
|
+
} finally {
|
|
689
|
+
await server.close();
|
|
690
|
+
}
|
|
691
|
+
});
|
|
692
|
+
|
|
693
|
+
it("does not retry non-retryable classifications like validation errors", async () => {
|
|
694
|
+
let attempts = 0;
|
|
695
|
+
const server = await startTestServer((app) => {
|
|
696
|
+
app.get("/bad", (_req, res) => {
|
|
697
|
+
attempts += 1;
|
|
698
|
+
res.status(400).json({message: "bad request"});
|
|
699
|
+
});
|
|
700
|
+
});
|
|
701
|
+
try {
|
|
702
|
+
const client = createAuthenticatedClient({
|
|
703
|
+
auth: NO_AUTH,
|
|
704
|
+
baseURL: server.baseURL,
|
|
705
|
+
retry: FAST_RETRY,
|
|
706
|
+
});
|
|
707
|
+
let caught: unknown;
|
|
708
|
+
try {
|
|
709
|
+
await client.axios.get("/bad");
|
|
710
|
+
} catch (error) {
|
|
711
|
+
caught = error;
|
|
712
|
+
}
|
|
713
|
+
expect((caught as AxiosError).response?.status).toBe(400);
|
|
714
|
+
expect(attempts).toBe(1);
|
|
715
|
+
} finally {
|
|
716
|
+
await server.close();
|
|
717
|
+
}
|
|
718
|
+
});
|
|
719
|
+
});
|
|
720
|
+
});
|
|
721
|
+
|
|
722
|
+
describe("createAuthenticatedClient hardening", () => {
|
|
723
|
+
it("rejects without looping when the oauth2 token endpoint itself returns 401", async () => {
|
|
724
|
+
let tokenRequests = 0;
|
|
725
|
+
const server = await startTestServer((app) => {
|
|
726
|
+
app.post("/oauth/token", (_req, res) => {
|
|
727
|
+
tokenRequests += 1;
|
|
728
|
+
res.status(401).json({message: "invalid client credentials"});
|
|
729
|
+
});
|
|
730
|
+
app.get("/widgets", (_req, res) => {
|
|
731
|
+
res.json({ok: true});
|
|
732
|
+
});
|
|
733
|
+
});
|
|
734
|
+
try {
|
|
735
|
+
const client = createAuthenticatedClient({
|
|
736
|
+
auth: {
|
|
737
|
+
credentials: {clientId: "bad", clientSecret: "creds"},
|
|
738
|
+
refreshOn401: true,
|
|
739
|
+
tokenUrl: `${server.baseURL}/oauth/token`,
|
|
740
|
+
type: "oauth2",
|
|
741
|
+
},
|
|
742
|
+
baseURL: server.baseURL,
|
|
743
|
+
});
|
|
744
|
+
let caught: unknown;
|
|
745
|
+
try {
|
|
746
|
+
await client.axios.get("/widgets");
|
|
747
|
+
} catch (error) {
|
|
748
|
+
caught = error;
|
|
749
|
+
}
|
|
750
|
+
expect(caught).toBeInstanceOf(Error);
|
|
751
|
+
expect((caught as Error).message).toContain("token fetch");
|
|
752
|
+
expect(tokenRequests).toBe(1);
|
|
753
|
+
} finally {
|
|
754
|
+
await server.close();
|
|
755
|
+
}
|
|
756
|
+
});
|
|
757
|
+
|
|
758
|
+
it("rejects clearly when the token response has no access_token", async () => {
|
|
759
|
+
const server = await startTestServer((app) => {
|
|
760
|
+
app.post("/oauth/token", (_req, res) => {
|
|
761
|
+
res.json({unexpected: "shape"});
|
|
762
|
+
});
|
|
763
|
+
});
|
|
764
|
+
try {
|
|
765
|
+
const client = createAuthenticatedClient({
|
|
766
|
+
auth: {
|
|
767
|
+
credentials: {clientId: "client-id", clientSecret: "client-secret"},
|
|
768
|
+
refreshOn401: true,
|
|
769
|
+
tokenUrl: `${server.baseURL}/oauth/token`,
|
|
770
|
+
type: "oauth2",
|
|
771
|
+
},
|
|
772
|
+
baseURL: server.baseURL,
|
|
773
|
+
});
|
|
774
|
+
let caught: unknown;
|
|
775
|
+
try {
|
|
776
|
+
await client.axios.get("/widgets");
|
|
777
|
+
} catch (error) {
|
|
778
|
+
caught = error;
|
|
779
|
+
}
|
|
780
|
+
expect((caught as Error).message).toContain("access_token");
|
|
781
|
+
} finally {
|
|
782
|
+
await server.close();
|
|
783
|
+
}
|
|
784
|
+
});
|
|
785
|
+
|
|
786
|
+
it("shares a single token fetch across concurrent first requests", async () => {
|
|
787
|
+
const server = await startTestServer((app) => {
|
|
788
|
+
app.get("/widgets", (_req, res) => {
|
|
789
|
+
res.json({ok: true});
|
|
790
|
+
});
|
|
791
|
+
});
|
|
792
|
+
try {
|
|
793
|
+
let tokenFetches = 0;
|
|
794
|
+
const client = createAuthenticatedClient({
|
|
795
|
+
auth: {
|
|
796
|
+
getToken: async () => {
|
|
797
|
+
tokenFetches += 1;
|
|
798
|
+
await new Promise((resolve) => setTimeout(resolve, 5));
|
|
799
|
+
return "token-shared";
|
|
800
|
+
},
|
|
801
|
+
type: "bearer",
|
|
802
|
+
},
|
|
803
|
+
baseURL: server.baseURL,
|
|
804
|
+
});
|
|
805
|
+
await Promise.all([client.axios.get("/widgets"), client.axios.get("/widgets")]);
|
|
806
|
+
expect(tokenFetches).toBe(1);
|
|
807
|
+
} finally {
|
|
808
|
+
await server.close();
|
|
809
|
+
}
|
|
810
|
+
});
|
|
811
|
+
|
|
812
|
+
it("retries network errors and logs the retry attempts", async () => {
|
|
813
|
+
const server = await startTestServer(() => {});
|
|
814
|
+
const {baseURL} = server;
|
|
815
|
+
await server.close();
|
|
816
|
+
const {logger, entries} = createRecordingLogger();
|
|
817
|
+
const client = createAuthenticatedClient({
|
|
818
|
+
auth: {getToken: async () => "t", type: "bearer"},
|
|
819
|
+
baseURL,
|
|
820
|
+
logger,
|
|
821
|
+
retry: {baseDelayMs: 1, maxAttempts: 2},
|
|
822
|
+
});
|
|
823
|
+
let caught: unknown;
|
|
824
|
+
try {
|
|
825
|
+
await client.axios.get("/gone");
|
|
826
|
+
} catch (error) {
|
|
827
|
+
caught = error;
|
|
828
|
+
}
|
|
829
|
+
expect(isAxiosError(caught)).toBe(true);
|
|
830
|
+
const retryLogs = entries.filter((entry) => entry.msg.includes("retrying attempt"));
|
|
831
|
+
expect(retryLogs).toHaveLength(1);
|
|
832
|
+
expect(retryLogs[0].msg).toContain("attempt 2/2");
|
|
833
|
+
expect(retryLogs[0].msg).toContain("network");
|
|
834
|
+
});
|
|
835
|
+
|
|
836
|
+
it("prefers a numeric Retry-After header over backoff", async () => {
|
|
837
|
+
let attempts = 0;
|
|
838
|
+
const server = await startTestServer((app) => {
|
|
839
|
+
app.get("/limited", (_req, res) => {
|
|
840
|
+
attempts += 1;
|
|
841
|
+
if (attempts === 1) {
|
|
842
|
+
res.set("Retry-After", "0").status(429).json({message: "slow down"});
|
|
843
|
+
return;
|
|
844
|
+
}
|
|
845
|
+
res.json({ok: true});
|
|
846
|
+
});
|
|
847
|
+
});
|
|
848
|
+
try {
|
|
849
|
+
const {logger, entries} = createRecordingLogger();
|
|
850
|
+
const client = createAuthenticatedClient({
|
|
851
|
+
auth: {getToken: async () => "t", type: "bearer"},
|
|
852
|
+
baseURL: server.baseURL,
|
|
853
|
+
logger,
|
|
854
|
+
// A base delay far above the Retry-After value: if backoff were used the log
|
|
855
|
+
// would show >=100ms, so "in 0ms" proves the header took precedence.
|
|
856
|
+
retry: {baseDelayMs: 100},
|
|
857
|
+
});
|
|
858
|
+
await client.axios.get("/limited");
|
|
859
|
+
const retryLog = entries.find((entry) => entry.msg.includes("retrying attempt"));
|
|
860
|
+
expect(retryLog?.msg).toContain("in 0ms");
|
|
861
|
+
} finally {
|
|
862
|
+
await server.close();
|
|
863
|
+
}
|
|
864
|
+
});
|
|
865
|
+
|
|
866
|
+
it("falls back to backoff for a non-numeric Retry-After header", async () => {
|
|
867
|
+
let attempts = 0;
|
|
868
|
+
const server = await startTestServer((app) => {
|
|
869
|
+
app.get("/limited", (_req, res) => {
|
|
870
|
+
attempts += 1;
|
|
871
|
+
if (attempts === 1) {
|
|
872
|
+
res
|
|
873
|
+
.set("Retry-After", "Wed, 21 Oct 2015 07:28:00 GMT")
|
|
874
|
+
.status(429)
|
|
875
|
+
.json({message: "slow down"});
|
|
876
|
+
return;
|
|
877
|
+
}
|
|
878
|
+
res.json({ok: true});
|
|
879
|
+
});
|
|
880
|
+
});
|
|
881
|
+
try {
|
|
882
|
+
const {logger, entries} = createRecordingLogger();
|
|
883
|
+
const client = createAuthenticatedClient({
|
|
884
|
+
auth: {getToken: async () => "t", type: "bearer"},
|
|
885
|
+
baseURL: server.baseURL,
|
|
886
|
+
logger,
|
|
887
|
+
retry: FAST_RETRY,
|
|
888
|
+
});
|
|
889
|
+
await client.axios.get("/limited");
|
|
890
|
+
const retryLog = entries.find((entry) => entry.msg.includes("retrying attempt"));
|
|
891
|
+
expect(retryLog?.msg).toMatch(/in [1-9]\d*ms/);
|
|
892
|
+
} finally {
|
|
893
|
+
await server.close();
|
|
894
|
+
}
|
|
895
|
+
});
|
|
896
|
+
|
|
897
|
+
it("caps an excessive Retry-After header at the delay ceiling", async () => {
|
|
898
|
+
let attempts = 0;
|
|
899
|
+
const server = await startTestServer((app) => {
|
|
900
|
+
app.get("/limited", (_req, res) => {
|
|
901
|
+
attempts += 1;
|
|
902
|
+
if (attempts === 1) {
|
|
903
|
+
res.set("Retry-After", "3600").status(429).json({message: "slow down"});
|
|
904
|
+
return;
|
|
905
|
+
}
|
|
906
|
+
res.json({ok: true});
|
|
907
|
+
});
|
|
908
|
+
});
|
|
909
|
+
try {
|
|
910
|
+
const {logger, entries} = createRecordingLogger();
|
|
911
|
+
const client = createAuthenticatedClient({
|
|
912
|
+
auth: {getToken: async () => "t", type: "bearer"},
|
|
913
|
+
baseURL: server.baseURL,
|
|
914
|
+
logger,
|
|
915
|
+
retry: {...FAST_RETRY, maxDelayMs: 2},
|
|
916
|
+
});
|
|
917
|
+
await client.axios.get("/limited");
|
|
918
|
+
const retryLog = entries.find((entry) => entry.msg.includes("retrying attempt"));
|
|
919
|
+
expect(retryLog?.msg).toContain("in 2ms");
|
|
920
|
+
} finally {
|
|
921
|
+
await server.close();
|
|
922
|
+
}
|
|
923
|
+
});
|
|
924
|
+
|
|
925
|
+
it("honors a custom retryOn list", async () => {
|
|
926
|
+
let attempts = 0;
|
|
927
|
+
const server = await startTestServer((app) => {
|
|
928
|
+
app.get("/missing", (_req, res) => {
|
|
929
|
+
attempts += 1;
|
|
930
|
+
if (attempts === 1) {
|
|
931
|
+
res.status(404).json({message: "not here yet"});
|
|
932
|
+
return;
|
|
933
|
+
}
|
|
934
|
+
res.json({ok: true});
|
|
935
|
+
});
|
|
936
|
+
});
|
|
937
|
+
try {
|
|
938
|
+
const client = createAuthenticatedClient({
|
|
939
|
+
auth: {getToken: async () => "t", type: "bearer"},
|
|
940
|
+
baseURL: server.baseURL,
|
|
941
|
+
retry: {...FAST_RETRY, retryOn: ["notFound"]},
|
|
942
|
+
});
|
|
943
|
+
const response = await client.axios.get("/missing");
|
|
944
|
+
expect(response.data.ok).toBe(true);
|
|
945
|
+
expect(attempts).toBe(2);
|
|
946
|
+
} finally {
|
|
947
|
+
await server.close();
|
|
948
|
+
}
|
|
949
|
+
});
|
|
950
|
+
|
|
951
|
+
it("uses the apiName option in normalized retry context instead of the baseURL", async () => {
|
|
952
|
+
let attempts = 0;
|
|
953
|
+
const server = await startTestServer((app) => {
|
|
954
|
+
app.get("/flaky", (_req, res) => {
|
|
955
|
+
attempts += 1;
|
|
956
|
+
if (attempts === 1) {
|
|
957
|
+
res.status(500).json({message: "boom"});
|
|
958
|
+
return;
|
|
959
|
+
}
|
|
960
|
+
res.json({ok: true});
|
|
961
|
+
});
|
|
962
|
+
});
|
|
963
|
+
try {
|
|
964
|
+
const {logger, entries} = createRecordingLogger();
|
|
965
|
+
const client = createAuthenticatedClient({
|
|
966
|
+
apiName: "widgetService",
|
|
967
|
+
auth: {getToken: async () => "t", type: "bearer"},
|
|
968
|
+
baseURL: server.baseURL,
|
|
969
|
+
logger,
|
|
970
|
+
retry: FAST_RETRY,
|
|
971
|
+
});
|
|
972
|
+
await client.axios.get("/flaky");
|
|
973
|
+
const retryLog = entries.find((entry) => entry.msg.includes("retrying attempt"));
|
|
974
|
+
expect(retryLog?.msg).toContain("[widgetService]");
|
|
975
|
+
} finally {
|
|
976
|
+
await server.close();
|
|
977
|
+
}
|
|
978
|
+
});
|
|
979
|
+
});
|