@baukit/api-runtime 0.31.0 → 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,6 +40,9 @@ 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
 
@@ -43,15 +58,20 @@ interface AttemptState {
43
58
  useOriginalRequest: boolean;
44
59
  retries: number;
45
60
  unauthorizedReplayUsed: boolean;
61
+ timedOut: boolean;
46
62
  }
47
63
 
48
64
  export function fetchSettings(options: ApiRuntimeOptions, baseUrl: string): FetchSettings {
65
+ const now = options.now ?? Date.now;
49
66
  return {
50
67
  baseUrl,
51
68
  requestConstructor: options.requestConstructor ?? globalThis.Request,
52
69
  transport: options.fetch ?? globalThis.fetch.bind(globalThis),
53
70
  requestIdFactory: options.requestIdFactory ?? createUuid,
54
71
  retry: normalizeRetryOptions(options.retry),
72
+ requestTimeoutMs: normalizeRequestTimeout(options.requestTimeoutMs),
73
+ cooldown: options.cooldown === false ? null : new OriginCooldown(options.cooldown ?? {}, now),
74
+ now,
55
75
  options,
56
76
  };
57
77
  }
@@ -73,9 +93,11 @@ export async function runFetch(
73
93
  useOriginalRequest: true,
74
94
  retries: 0,
75
95
  unauthorizedReplayUsed: false,
96
+ timedOut: false,
76
97
  };
77
98
  for (;;) {
78
99
  throwIfAborted(state.request.signal, context.requestId);
100
+ throwIfCoolingDown(context, state);
79
101
  const outcome = await runAttempt(context, state);
80
102
  if (outcome !== RETRY) {
81
103
  return outcome;
@@ -108,15 +130,47 @@ async function runAttempt(context: FetchContext, state: AttemptState): Promise<A
108
130
  }
109
131
  }
110
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
+
111
155
  async function sendAttempt(context: FetchContext, state: AttemptState): Promise<Response> {
112
156
  const attempt = state.useOriginalRequest ? state.request : state.replaySource?.clone();
113
157
  if (attempt === undefined) {
114
158
  throw new TypeError('API request body cannot be replayed');
115
159
  }
116
160
  state.useOriginalRequest = false;
117
- const response = await context.transport(attempt);
118
- throwIfAborted(state.request.signal, context.requestId);
119
- 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
+ }
120
174
  }
121
175
 
122
176
  async function handleResponse(
@@ -124,11 +178,20 @@ async function handleResponse(
124
178
  state: AttemptState,
125
179
  response: Response,
126
180
  ): Promise<AttemptOutcome> {
181
+ const retryAfterMs = retryAfterDelayMs(response, context.retry, context.now());
182
+ if (retryAfterMs !== null) {
183
+ context.cooldown?.coolDown(originOf(state), retryAfterMs);
184
+ }
127
185
  if (
128
186
  state.replaySource !== undefined &&
129
- 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
+ )
130
193
  ) {
131
- await backOff(context, state);
194
+ await backOff(context, state, retryAfterMs);
132
195
  return RETRY;
133
196
  }
134
197
  if (response.ok) {
@@ -237,29 +300,52 @@ async function handleFailure(
237
300
  state: AttemptState,
238
301
  cause: unknown,
239
302
  ): Promise<AttemptOutcome> {
240
- if (cause instanceof ApiError || cause instanceof HttpError) {
303
+ if (
304
+ cause instanceof ApiError ||
305
+ cause instanceof HttpError ||
306
+ cause instanceof ApiUnavailableError
307
+ ) {
241
308
  throw cause;
242
309
  }
243
- 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
+ }
244
314
  if (
245
315
  !aborted &&
246
316
  state.replaySource !== undefined &&
247
317
  shouldRetryMethod(state.request, context.retry) &&
248
318
  state.retries < context.retry.maxRetries
249
319
  ) {
250
- await backOff(context, state);
320
+ await backOff(context, state, null);
251
321
  return RETRY;
252
322
  }
253
323
  throw new NetworkError(
254
- aborted ? 'API request was aborted' : 'API network request failed',
324
+ failureMessage(aborted, state.timedOut),
255
325
  context.requestId,
256
326
  cause,
257
327
  aborted,
258
328
  );
259
329
  }
260
330
 
261
- async function backOff(context: FetchContext, state: AttemptState): Promise<void> {
262
- 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);
263
349
  state.retries += 1;
264
350
  }
265
351
 
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`. */
@@ -132,6 +138,12 @@ export interface ApiRuntimeOptions extends ApiEnvironmentConfig {
132
138
  */
133
139
  readonly sessionSubject?: () => string | undefined;
134
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;
135
147
  }
136
148
 
137
149
  /** A configured runtime that can be handed to a product's generated client. */
@@ -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
+ }