@baukit/api-runtime 0.30.6 → 0.32.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/src/fetch.ts CHANGED
@@ -1,4 +1,12 @@
1
- import { ApiError, HttpError, isApiError, NetworkError, normalizeResponseError } from './errors.js';
1
+ import { OriginCooldown } from './cooldown.js';
2
+ import {
3
+ ApiError,
4
+ ApiUnavailableError,
5
+ HttpError,
6
+ isApiError,
7
+ NetworkError,
8
+ normalizeResponseError,
9
+ } from './errors.js';
2
10
  import { REQUEST_ID_HEADER } from './headers.js';
3
11
  import type {
4
12
  ApiRuntimeOptions,
@@ -10,15 +18,19 @@ import type {
10
18
  import {
11
19
  isAbortError,
12
20
  networkError,
21
+ nextRetryDelayMs,
13
22
  normalizeRetryOptions,
23
+ retryAfterDelayMs,
14
24
  retryDelay,
15
25
  shouldRetryMethod,
16
26
  shouldRetryResponse,
17
27
  throwIfAborted,
18
28
  type NormalizedRetryOptions,
19
29
  } from './retry.js';
30
+ import { attemptSignal } from './timeout.js';
20
31
 
21
32
  const UNAUTHORIZED_STATUS = 401;
33
+ const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
22
34
  const RETRY = Symbol('retry');
23
35
  type AttemptOutcome = Response | typeof RETRY;
24
36
 
@@ -28,11 +40,16 @@ export interface FetchSettings {
28
40
  readonly transport: FetchImplementation;
29
41
  readonly requestIdFactory: () => string;
30
42
  readonly retry: NormalizedRetryOptions;
43
+ readonly requestTimeoutMs: number | null;
44
+ readonly cooldown: OriginCooldown | null;
45
+ readonly now: () => number;
31
46
  readonly options: ApiRuntimeOptions;
32
47
  }
33
48
 
34
49
  interface FetchContext extends FetchSettings {
35
50
  readonly requestId: string;
51
+ /** Session subject at send time; 401 signals from an older session are dropped. */
52
+ readonly sessionSubject: string | undefined;
36
53
  }
37
54
 
38
55
  interface AttemptState {
@@ -41,15 +58,20 @@ interface AttemptState {
41
58
  useOriginalRequest: boolean;
42
59
  retries: number;
43
60
  unauthorizedReplayUsed: boolean;
61
+ timedOut: boolean;
44
62
  }
45
63
 
46
64
  export function fetchSettings(options: ApiRuntimeOptions, baseUrl: string): FetchSettings {
65
+ const now = options.now ?? Date.now;
47
66
  return {
48
67
  baseUrl,
49
68
  requestConstructor: options.requestConstructor ?? globalThis.Request,
50
69
  transport: options.fetch ?? globalThis.fetch.bind(globalThis),
51
70
  requestIdFactory: options.requestIdFactory ?? createUuid,
52
71
  retry: normalizeRetryOptions(options.retry),
72
+ requestTimeoutMs: normalizeRequestTimeout(options.requestTimeoutMs),
73
+ cooldown: options.cooldown === false ? null : new OriginCooldown(options.cooldown ?? {}, now),
74
+ now,
53
75
  options,
54
76
  };
55
77
  }
@@ -59,7 +81,11 @@ export async function runFetch(
59
81
  input: RequestInfo | URL,
60
82
  init: RequestInit | undefined,
61
83
  ): Promise<Response> {
62
- const context: FetchContext = { ...settings, requestId: settings.requestIdFactory() };
84
+ const context: FetchContext = {
85
+ ...settings,
86
+ requestId: settings.requestIdFactory(),
87
+ sessionSubject: settings.options.sessionSubject?.(),
88
+ };
63
89
  const request = await prepareRequest(context, input, init);
64
90
  const state: AttemptState = {
65
91
  request,
@@ -67,9 +93,11 @@ export async function runFetch(
67
93
  useOriginalRequest: true,
68
94
  retries: 0,
69
95
  unauthorizedReplayUsed: false,
96
+ timedOut: false,
70
97
  };
71
98
  for (;;) {
72
99
  throwIfAborted(state.request.signal, context.requestId);
100
+ throwIfCoolingDown(context, state);
73
101
  const outcome = await runAttempt(context, state);
74
102
  if (outcome !== RETRY) {
75
103
  return outcome;
@@ -102,15 +130,47 @@ async function runAttempt(context: FetchContext, state: AttemptState): Promise<A
102
130
  }
103
131
  }
104
132
 
133
+ function normalizeRequestTimeout(timeoutMs: number | false | undefined): number | null {
134
+ if (timeoutMs === false) {
135
+ return null;
136
+ }
137
+ const value = timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
138
+ if (!Number.isFinite(value) || value <= 0) {
139
+ throw new Error('requestTimeoutMs must be a finite positive number');
140
+ }
141
+ return value;
142
+ }
143
+
144
+ function originOf(state: AttemptState): string {
145
+ return new URL(state.request.url).origin;
146
+ }
147
+
148
+ function throwIfCoolingDown(context: FetchContext, state: AttemptState): void {
149
+ const retryAt = context.cooldown?.blockedUntil(originOf(state)) ?? null;
150
+ if (retryAt !== null) {
151
+ throw new ApiUnavailableError(context.requestId, retryAt);
152
+ }
153
+ }
154
+
105
155
  async function sendAttempt(context: FetchContext, state: AttemptState): Promise<Response> {
106
156
  const attempt = state.useOriginalRequest ? state.request : state.replaySource?.clone();
107
157
  if (attempt === undefined) {
108
158
  throw new TypeError('API request body cannot be replayed');
109
159
  }
110
160
  state.useOriginalRequest = false;
111
- const response = await context.transport(attempt);
112
- throwIfAborted(state.request.signal, context.requestId);
113
- return response;
161
+ state.timedOut = false;
162
+ const scope = attemptSignal(state.request.signal, context.requestTimeoutMs);
163
+ try {
164
+ const response = await context.transport(attempt, { signal: scope.signal });
165
+ throwIfAborted(state.request.signal, context.requestId);
166
+ context.cooldown?.recordResponse(originOf(state));
167
+ return response;
168
+ } catch (cause) {
169
+ state.timedOut = scope.timedOut();
170
+ throw cause;
171
+ } finally {
172
+ scope.dispose();
173
+ }
114
174
  }
115
175
 
116
176
  async function handleResponse(
@@ -118,18 +178,27 @@ async function handleResponse(
118
178
  state: AttemptState,
119
179
  response: Response,
120
180
  ): Promise<AttemptOutcome> {
181
+ const retryAfterMs = retryAfterDelayMs(response, context.retry, context.now());
182
+ if (retryAfterMs !== null) {
183
+ context.cooldown?.coolDown(originOf(state), retryAfterMs);
184
+ }
121
185
  if (
122
186
  state.replaySource !== undefined &&
123
- shouldRetryResponse(state.request, response.status, state.retries, context.retry)
187
+ shouldRetryResponse(
188
+ state.request,
189
+ { status: response.status, retryAfterMs },
190
+ state.retries,
191
+ context.retry,
192
+ )
124
193
  ) {
125
- await backOff(context, state);
194
+ await backOff(context, state, retryAfterMs);
126
195
  return RETRY;
127
196
  }
128
197
  if (response.ok) {
129
198
  return response;
130
199
  }
131
200
  const error = await normalizeResponseError(response);
132
- if (response.status !== UNAUTHORIZED_STATUS) {
201
+ if (response.status !== UNAUTHORIZED_STATUS || !acceptsSessionSignals(context, state.request)) {
133
202
  throw error;
134
203
  }
135
204
  return handleUnauthorized(context, state, { response, error });
@@ -151,6 +220,7 @@ async function handleUnauthorized(
151
220
  ...failure,
152
221
  request: state.replaySource?.clone() ?? state.request,
153
222
  canRetry,
223
+ ...(context.sessionSubject === undefined ? {} : { subject: context.sessionSubject }),
154
224
  });
155
225
  if (isApiError(error, 'profile_erased')) {
156
226
  await notifyObserver(() => options.onProfileErased?.(unauthorizedContext(false)));
@@ -230,29 +300,52 @@ async function handleFailure(
230
300
  state: AttemptState,
231
301
  cause: unknown,
232
302
  ): Promise<AttemptOutcome> {
233
- if (cause instanceof ApiError || cause instanceof HttpError) {
303
+ if (
304
+ cause instanceof ApiError ||
305
+ cause instanceof HttpError ||
306
+ cause instanceof ApiUnavailableError
307
+ ) {
234
308
  throw cause;
235
309
  }
236
- const aborted = state.request.signal.aborted || isAbortError(cause);
310
+ const aborted = state.request.signal.aborted || (!state.timedOut && isAbortError(cause));
311
+ if (!aborted) {
312
+ context.cooldown?.recordNetworkFailure(originOf(state));
313
+ }
237
314
  if (
238
315
  !aborted &&
239
316
  state.replaySource !== undefined &&
240
317
  shouldRetryMethod(state.request, context.retry) &&
241
318
  state.retries < context.retry.maxRetries
242
319
  ) {
243
- await backOff(context, state);
320
+ await backOff(context, state, null);
244
321
  return RETRY;
245
322
  }
246
323
  throw new NetworkError(
247
- aborted ? 'API request was aborted' : 'API network request failed',
324
+ failureMessage(aborted, state.timedOut),
248
325
  context.requestId,
249
326
  cause,
250
327
  aborted,
251
328
  );
252
329
  }
253
330
 
254
- async function backOff(context: FetchContext, state: AttemptState): Promise<void> {
255
- await retryDelay(state.retries, context.retry, state.request.signal, context.requestId);
331
+ function failureMessage(aborted: boolean, timedOut: boolean): string {
332
+ if (aborted) {
333
+ return 'API request was aborted';
334
+ }
335
+ return timedOut ? 'API request timed out' : 'API network request failed';
336
+ }
337
+
338
+ async function backOff(
339
+ context: FetchContext,
340
+ state: AttemptState,
341
+ retryAfterMs: number | null,
342
+ ): Promise<void> {
343
+ const delayMs = nextRetryDelayMs(state.retries, context.retry, retryAfterMs);
344
+ const retryAt = context.cooldown?.blockedUntil(originOf(state)) ?? null;
345
+ if (retryAt !== null && retryAt > context.now() + delayMs) {
346
+ throw new ApiUnavailableError(context.requestId, retryAt);
347
+ }
348
+ await retryDelay(delayMs, context.retry, state.request.signal, context.requestId);
256
349
  state.retries += 1;
257
350
  }
258
351
 
@@ -262,7 +355,7 @@ async function decorateRequest(context: FetchContext, request: Request): Promise
262
355
  const headers = new Headers(request.headers);
263
356
  headers.set(REQUEST_ID_HEADER, requestId);
264
357
 
265
- if (options.tokenProvider !== undefined) {
358
+ if (options.tokenProvider !== undefined && isApiRequest(request.url, context.baseUrl)) {
266
359
  const token = await options.tokenProvider();
267
360
  throwIfAborted(request.signal, requestId);
268
361
  headers.delete('authorization');
@@ -297,11 +390,42 @@ function createRequest(
297
390
  requestConstructor: typeof Request,
298
391
  ): Request {
299
392
  if (typeof input === 'string' || input instanceof URL) {
300
- return new requestConstructor(new URL(input.toString(), `${baseUrl}/`), init);
393
+ return new requestConstructor(resolveApiUrl(input, baseUrl), init);
301
394
  }
302
395
  return new requestConstructor(input, init);
303
396
  }
304
397
 
398
+ const BASE_RELATIVE_PATH = /^\/(?![/\\])/u;
399
+
400
+ /** Paths starting with a single `/` stay under the base path; `//host` and `/\host` do not. */
401
+ export function resolveApiUrl(input: string | URL, baseUrl: string): URL {
402
+ if (input instanceof URL) return input;
403
+ if (BASE_RELATIVE_PATH.test(input)) return new URL(`${baseUrl}${input}`);
404
+ return new URL(input, `${baseUrl}/`);
405
+ }
406
+
407
+ /** True when `url` has the base origin and sits at or under the base path. */
408
+ export function isApiRequest(url: string, baseUrl: string): boolean {
409
+ let target: URL;
410
+ try {
411
+ target = new URL(url);
412
+ } catch {
413
+ return false;
414
+ }
415
+ const base = new URL(baseUrl);
416
+ if (target.origin !== base.origin) return false;
417
+ const basePath = base.pathname.replace(/\/$/u, '');
418
+ return (
419
+ basePath === '' || target.pathname === basePath || target.pathname.startsWith(`${basePath}/`)
420
+ );
421
+ }
422
+
423
+ function acceptsSessionSignals(context: FetchContext, request: Request): boolean {
424
+ if (!isApiRequest(request.url, context.baseUrl)) return false;
425
+ const currentSubject = context.options.sessionSubject;
426
+ return currentSubject === undefined || currentSubject() === context.sessionSubject;
427
+ }
428
+
305
429
  function createUuid(): string {
306
430
  // Runtime probe: React Native and older runtimes may lack `crypto` despite the DOM lib typing.
307
431
  const runtime: { readonly crypto?: Crypto } = globalThis;
package/src/index.ts CHANGED
@@ -3,6 +3,7 @@
3
3
  import createClient from 'openapi-fetch';
4
4
  import type { Client, ClientOptions } from 'openapi-fetch';
5
5
 
6
+ import type { CooldownOptions } from './cooldown.js';
6
7
  import type { ApiError, HttpError } from './errors.js';
7
8
  import { fetchSettings, runFetch } from './fetch.js';
8
9
 
@@ -19,10 +20,13 @@ export {
19
20
  } from './sign-in-session.js';
20
21
 
21
22
  export { IDEMPOTENCY_KEY_HEADER, REQUEST_ID_HEADER } from './headers.js';
23
+ export type { CooldownOptions } from './cooldown.js';
22
24
  export {
23
25
  ApiError,
26
+ ApiUnavailableError,
24
27
  HttpError,
25
28
  isApiError,
29
+ isApiUnavailableError,
26
30
  isHttpError,
27
31
  isNetworkError,
28
32
  NetworkError,
@@ -75,6 +79,8 @@ export interface RetryOptions {
75
79
  readonly baseDelayMs?: number;
76
80
  /** Maximum backoff ceiling in milliseconds. Defaults to 2,000. */
77
81
  readonly maxDelayMs?: number;
82
+ /** Upper bound for a honoured `Retry-After` delay in milliseconds. Defaults to 30,000. */
83
+ readonly maxRetryAfterMs?: number;
78
84
  /** Methods eligible for retries. Defaults to GET and HEAD. */
79
85
  readonly methods?: readonly RetryableMethod[];
80
86
  /** Random source used for full jitter. Defaults to `Math.random`. */
@@ -96,6 +102,8 @@ export interface UnauthorizedContext {
96
102
  readonly response: Response;
97
103
  /** False when the request body cannot be cloned safely for replay. */
98
104
  readonly canRetry: boolean;
105
+ /** `sessionSubject()` when the request was sent, if the option is configured. */
106
+ readonly subject?: string;
99
107
  }
100
108
 
101
109
  /** Explicit outcome of a 401 hook. `handled` preserves the original normalized rejection. */
@@ -124,7 +132,18 @@ export interface ApiRuntimeOptions extends ApiEnvironmentConfig {
124
132
  readonly onUnauthorized?: UnauthorizedHandler;
125
133
  readonly onUnauthorizedExhausted?: UnauthorizedExhaustedHandler;
126
134
  readonly onProfileErased?: ProfileErasedHandler;
135
+ /**
136
+ * Current session subject, read at send time and again on a 401. A 401 whose
137
+ * subject changed in between fires no signal, so it cannot affect a newer session.
138
+ */
139
+ readonly sessionSubject?: () => string | undefined;
127
140
  readonly retry?: RetryOptions | false;
141
+ /** Per-attempt timeout in milliseconds, combined with the caller's signal. Defaults to 30,000. */
142
+ readonly requestTimeoutMs?: number | false;
143
+ /** Per-origin fail-fast cooldown. On by default; `false` disables it. */
144
+ readonly cooldown?: CooldownOptions | false;
145
+ /** Epoch-millisecond clock for cooldowns and `Retry-After` dates. Defaults to `Date.now`. */
146
+ readonly now?: () => number;
128
147
  }
129
148
 
130
149
  /** A configured runtime that can be handed to a product's generated client. */
@@ -0,0 +1,122 @@
1
+ import fc from 'fast-check';
2
+ import { describe, expect, it, vi } from 'vitest';
3
+
4
+ import { MockFetch, createApiFetch } from './index.js';
5
+
6
+ const baseUrl = 'https://api.example.test/v1';
7
+ const base = new URL(baseUrl);
8
+
9
+ const segment = fc.constantFrom('items', 'v1', 'v10', '..', '.', '%2F', '%2e%2e', 'a b', '');
10
+ const host = fc.constantFrom('api.example.test', 'evil.example', 'api.example.test:8443');
11
+ const path = fc.array(segment, { maxLength: 4 }).map((parts) => parts.join('/'));
12
+ const input = fc.oneof(
13
+ path.map((value) => `/${value}`),
14
+ path,
15
+ fc.tuple(host, path).map(([name, value]) => `//${name}/${value}`),
16
+ fc.tuple(host, path).map(([name, value]) => `/\\${name}/${value}`),
17
+ fc.tuple(host, path).map(([name, value]) => `\\\\${name}/${value}`),
18
+ fc
19
+ .tuple(fc.constantFrom('https', 'http'), host, path)
20
+ .map(([scheme, name, value]) => `${scheme}://${name}/${value}`),
21
+ );
22
+ const requestInput = fc.oneof(
23
+ input,
24
+ input
25
+ .filter((value) => URL.canParse(value, `${baseUrl}/`))
26
+ .map((value) => new Request(new URL(value, `${baseUrl}/`))),
27
+ );
28
+
29
+ function underBase(url: string): boolean {
30
+ const target = new URL(url);
31
+ return (
32
+ target.origin === base.origin &&
33
+ (target.pathname === base.pathname || target.pathname.startsWith(`${base.pathname}/`))
34
+ );
35
+ }
36
+
37
+ function erasedResponse(): Response {
38
+ return new Response(
39
+ JSON.stringify({
40
+ error: { code: 'profile_erased', message: 'x', requestId: 'r', details: {} },
41
+ }),
42
+ { status: 401, headers: { 'content-type': 'application/json' } },
43
+ );
44
+ }
45
+
46
+ describe('C-01 api-runtime origin property', () => {
47
+ it('attaches Authorization iff the request is under the base origin and path', async () => {
48
+ await fc.assert(
49
+ fc.asyncProperty(requestInput, async (value) => {
50
+ const transport = new MockFetch().enqueue(new Response('{}'));
51
+ const fetch = createApiFetch({
52
+ baseUrl,
53
+ environment: 'test',
54
+ fetch: transport.fetch,
55
+ tokenProvider: () => Promise.resolve('t'),
56
+ });
57
+ const outcome = await fetch(value).catch((cause: unknown) => cause);
58
+ if (transport.requests.length === 0) {
59
+ expect(outcome).toBeInstanceOf(Error);
60
+ return;
61
+ }
62
+ const sent = transport.request(0);
63
+ expect(sent.headers.get('authorization') !== null).toBe(underBase(sent.url));
64
+ }),
65
+ );
66
+ });
67
+
68
+ it('fires 401 hooks only for base requests and replays at most once', async () => {
69
+ await fc.assert(
70
+ fc.asyncProperty(requestInput, fc.boolean(), async (value, erased) => {
71
+ const onProfileErased = vi.fn();
72
+ const onUnauthorized = vi.fn().mockReturnValue('retry-once');
73
+ const transport = new MockFetch();
74
+ const sent: string[] = [];
75
+ for (let index = 0; index < 3; index += 1) {
76
+ transport.enqueue((request) => {
77
+ sent.push(request.url);
78
+ return erased ? erasedResponse() : new Response(null, { status: 401 });
79
+ });
80
+ }
81
+ const fetch = createApiFetch({
82
+ baseUrl,
83
+ environment: 'test',
84
+ fetch: transport.fetch,
85
+ tokenProvider: () => Promise.resolve('t'),
86
+ onProfileErased,
87
+ onUnauthorized,
88
+ });
89
+ await expect(fetch(value)).rejects.toThrow();
90
+ if (sent.length === 0) return;
91
+ const trusted = underBase(sent[0] ?? '');
92
+ expect(onProfileErased.mock.calls.length).toBe(trusted && erased ? 1 : 0);
93
+ expect(onUnauthorized.mock.calls.length).toBe(trusted && !erased ? 1 : 0);
94
+ expect(sent.length).toBeLessThanOrEqual(2);
95
+ if (!trusted || erased) expect(sent.length).toBe(1);
96
+ }),
97
+ );
98
+ });
99
+
100
+ it('sends POST and PATCH without an idempotency key exactly once on 5xx', async () => {
101
+ await fc.assert(
102
+ fc.asyncProperty(
103
+ fc.constantFrom('POST', 'PATCH'),
104
+ fc.integer({ min: 500, max: 599 }),
105
+ async (method, status) => {
106
+ const transport = new MockFetch();
107
+ for (let index = 0; index < 4; index += 1) {
108
+ transport.enqueue(new Response(null, { status }));
109
+ }
110
+ const fetch = createApiFetch({
111
+ baseUrl,
112
+ environment: 'test',
113
+ fetch: transport.fetch,
114
+ retry: { methods: ['POST', 'PATCH'], sleep: () => Promise.resolve() },
115
+ });
116
+ await expect(fetch('/items', { method, body: '{}' })).rejects.toThrow();
117
+ expect(transport.requests).toHaveLength(1);
118
+ },
119
+ ),
120
+ );
121
+ });
122
+ });
@@ -0,0 +1,87 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+
3
+ import { ApiError, MockFetch, createApiFetch } from './index.js';
4
+
5
+ const baseUrl = 'https://api.example.test/v1';
6
+ const erased = () =>
7
+ new Response(
8
+ JSON.stringify({
9
+ error: { code: 'profile_erased', message: 'gone', requestId: 'r', details: {} },
10
+ }),
11
+ { status: 401, headers: { 'content-type': 'application/json' } },
12
+ );
13
+
14
+ function setup(sessionSubject?: () => string | undefined) {
15
+ const transport = new MockFetch();
16
+ const onProfileErased = vi.fn();
17
+ const onUnauthorized = vi.fn().mockReturnValue('retry-once');
18
+ const fetch = createApiFetch({
19
+ baseUrl,
20
+ environment: 'test',
21
+ fetch: transport.fetch,
22
+ tokenProvider: () => Promise.resolve('secret'),
23
+ onProfileErased,
24
+ onUnauthorized,
25
+ ...(sessionSubject === undefined ? {} : { sessionSubject }),
26
+ });
27
+ return { transport, fetch, onProfileErased, onUnauthorized };
28
+ }
29
+
30
+ describe('base origin and path scoping', () => {
31
+ it.each([
32
+ ['/items', 'https://api.example.test/v1/items', true],
33
+ ['items', 'https://api.example.test/v1/items', true],
34
+ ['//evil.example/x', 'https://evil.example/x', false],
35
+ ['/\\evil.example/x', 'https://evil.example/x', false],
36
+ ['https://evil.example/v1/x', 'https://evil.example/v1/x', false],
37
+ ['https://api.example.test/v2/x', 'https://api.example.test/v2/x', false],
38
+ ['https://api.example.test/v10', 'https://api.example.test/v10', false],
39
+ ['/../admin', 'https://api.example.test/admin', false],
40
+ ])('resolves %s and attaches the token only under the base', async (input, url, trusted) => {
41
+ const { transport, fetch } = setup();
42
+ transport.enqueue(new Response('{}'));
43
+ await fetch(input);
44
+ const request = transport.request(0);
45
+ expect(request.url).toBe(url);
46
+ expect(request.headers.get('authorization')).toBe(trusted ? 'Bearer secret' : null);
47
+ });
48
+
49
+ it('applies the same rule to Request inputs', async () => {
50
+ const { transport, fetch } = setup();
51
+ transport.enqueue(new Response('{}')).enqueue(new Response('{}'));
52
+ await fetch(new Request('https://evil.example/v1/x'));
53
+ await fetch(new Request(`${baseUrl}/x`));
54
+ expect(transport.request(0).headers.get('authorization')).toBeNull();
55
+ expect(transport.request(1).headers.get('authorization')).toBe('Bearer secret');
56
+ });
57
+
58
+ it('ignores 401 signals from another origin', async () => {
59
+ const { transport, fetch, onProfileErased, onUnauthorized } = setup();
60
+ transport.enqueue(erased()).enqueue(new Response(null, { status: 401 }));
61
+ await expect(fetch('https://evil.example/x')).rejects.toBeInstanceOf(ApiError);
62
+ await expect(fetch('//evil.example/x')).rejects.toThrow();
63
+ expect(onProfileErased).not.toHaveBeenCalled();
64
+ expect(onUnauthorized).not.toHaveBeenCalled();
65
+ transport.assertQueueEmpty();
66
+ });
67
+ });
68
+
69
+ describe('session generation', () => {
70
+ it('drops a profile_erased signal stamped with an older subject', async () => {
71
+ let subject = 'account-a';
72
+ const { transport, fetch, onProfileErased } = setup(() => subject);
73
+ transport.enqueue(() => {
74
+ subject = 'account-b';
75
+ return erased();
76
+ });
77
+ await expect(fetch('/items')).rejects.toBeInstanceOf(ApiError);
78
+ expect(onProfileErased).not.toHaveBeenCalled();
79
+ });
80
+
81
+ it('passes the stamped subject to onProfileErased', async () => {
82
+ const { transport, fetch, onProfileErased } = setup(() => 'account-a');
83
+ transport.enqueue(erased());
84
+ await expect(fetch('/items')).rejects.toBeInstanceOf(ApiError);
85
+ expect(onProfileErased).toHaveBeenCalledWith(expect.objectContaining({ subject: 'account-a' }));
86
+ });
87
+ });
@@ -0,0 +1,128 @@
1
+ import { readFileSync } from 'node:fs';
2
+
3
+ import { isNonNegativeSafeInteger, isRecord, isString } from '@baukit/type-guards';
4
+ import { describe, expect, it } from 'vitest';
5
+
6
+ import { fullJitterBackoffMs } from './backoff.js';
7
+ import { OriginCooldown } from './cooldown.js';
8
+
9
+ const fixtureRoot = new URL('../../../../fixtures/resilience/', import.meta.url);
10
+ const ORIGIN = 'https://api.example.test';
11
+
12
+ /** Scenarios whose closed and open phases the cooldown models; it has no half-open probe. */
13
+ const COOLDOWN_SCENARIOS = [
14
+ 'consecutive timeouts open the breaker',
15
+ 'retry-after holds the breaker without counting a failure',
16
+ ];
17
+
18
+ function readFixture(name: string): Record<string, unknown> {
19
+ const parsed: unknown = JSON.parse(readFileSync(new URL(name, fixtureRoot), 'utf8'));
20
+ if (!isRecord(parsed) || parsed['version'] !== 1) {
21
+ throw new Error(`${name} is not a version 1 fixture`);
22
+ }
23
+ return parsed;
24
+ }
25
+
26
+ function records(value: unknown): Record<string, unknown>[] {
27
+ if (!Array.isArray(value) || !value.every(isRecord)) {
28
+ throw new Error('expected a list of objects');
29
+ }
30
+ return value;
31
+ }
32
+
33
+ function integer(record: Record<string, unknown>, key: string): number {
34
+ const value = record[key];
35
+ if (!isNonNegativeSafeInteger(value)) {
36
+ throw new Error(`${key} must be a non-negative integer`);
37
+ }
38
+ return value;
39
+ }
40
+
41
+ function fraction(record: Record<string, unknown>): number {
42
+ const value = record['fraction'];
43
+ if (typeof value !== 'number' || value < 0 || value > 1) {
44
+ throw new Error('fraction must be in [0, 1]');
45
+ }
46
+ return value;
47
+ }
48
+
49
+ function text(record: Record<string, unknown>, key: string): string {
50
+ const value = record[key];
51
+ if (!isString(value)) {
52
+ throw new Error(`${key} must be a string`);
53
+ }
54
+ return value;
55
+ }
56
+
57
+ describe('backoff-v1.json', () => {
58
+ const cases = records(readFixture('backoff-v1.json')['cases']).filter(
59
+ (vector) => vector['strategy'] === 'full_jitter',
60
+ );
61
+
62
+ it.each(cases)('full jitter case %#', (vector) => {
63
+ const delay = fullJitterBackoffMs(integer(vector, 'attempt'), {
64
+ baseDelayMs: integer(vector, 'initial_ms'),
65
+ maxDelayMs: integer(vector, 'max_ms'),
66
+ random: () => fraction(vector),
67
+ });
68
+
69
+ expect(delay).toBe(integer(vector, 'expected_delay_ms'));
70
+ });
71
+ });
72
+
73
+ describe('breaker-v1.json against the origin cooldown', () => {
74
+ const fixture = readFixture('breaker-v1.json');
75
+ const policy = isRecord(fixture['policy']) ? fixture['policy'] : {};
76
+ const scenarios = records(fixture['scenarios']).filter((scenario) =>
77
+ COOLDOWN_SCENARIOS.includes(text(scenario, 'name')),
78
+ );
79
+
80
+ it('finds every scenario it replays', () => {
81
+ expect(scenarios).toHaveLength(COOLDOWN_SCENARIOS.length);
82
+ });
83
+
84
+ it.each(scenarios)('$name', (scenario) => {
85
+ let nowMs = 0;
86
+ let jitter = 0;
87
+ const cooldown = new OriginCooldown(
88
+ {
89
+ networkFailureThreshold: integer(policy, 'consecutive_timeouts'),
90
+ networkFailureCooldownMs: integer(policy, 'open_base_ms'),
91
+ maxCooldownMs: integer(policy, 'open_max_ms'),
92
+ jitterPercent: integer(policy, 'jitter_percent'),
93
+ random: () => jitter,
94
+ },
95
+ () => nowMs,
96
+ );
97
+
98
+ for (const event of records(scenario['events'])) {
99
+ nowMs = integer(event, 'at_ms');
100
+ if (event['op'] === 'record') {
101
+ jitter = fraction(event);
102
+ applyOutcome(cooldown, event);
103
+ }
104
+ const blockedUntil = cooldown.blockedUntil(ORIGIN);
105
+ if (text(event, 'expect_state') !== 'open') {
106
+ expect(blockedUntil, `at ${String(nowMs)}`).toBeNull();
107
+ continue;
108
+ }
109
+ expect(blockedUntil, `at ${String(nowMs)}`).not.toBeNull();
110
+ if (event['expect_retry_after_ms'] !== undefined) {
111
+ expect((blockedUntil ?? 0) - nowMs).toBe(integer(event, 'expect_retry_after_ms'));
112
+ }
113
+ }
114
+ });
115
+ });
116
+
117
+ function applyOutcome(cooldown: OriginCooldown, event: Record<string, unknown>): void {
118
+ const outcome = text(event, 'outcome');
119
+ if (outcome === 'timeout') {
120
+ cooldown.recordNetworkFailure(ORIGIN);
121
+ } else if (outcome === 'success') {
122
+ cooldown.recordResponse(ORIGIN);
123
+ } else if (outcome === 'hold_for') {
124
+ cooldown.coolDown(ORIGIN, integer(event, 'hold_for_ms'));
125
+ } else if (outcome !== 'ignored') {
126
+ throw new Error(`outcome ${outcome} is outside the cooldown model`);
127
+ }
128
+ }