@npora/request 1.4.0 → 1.5.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/README.md CHANGED
@@ -115,6 +115,7 @@ api.optionsResponse(url, config)
115
115
  import {
116
116
  authPlugin,
117
117
  cachePlugin,
118
+ circuitBreakerPlugin,
118
119
  createClient,
119
120
  retryPlugin
120
121
  } from '@npora/request'
@@ -127,6 +128,7 @@ const request = createClient()
127
128
  jitter: true,
128
129
  maxElapsedTime: 10000
129
130
  }))
131
+ .use(circuitBreakerPlugin())
130
132
  .use(cache)
131
133
  .use(authPlugin({
132
134
  token: () => accessToken,
@@ -160,6 +162,7 @@ Built-in plugins:
160
162
 
161
163
  - `retryPlugin()`
162
164
  - `cachePlugin()`
165
+ - `circuitBreakerPlugin()`
163
166
  - `authPlugin()`
164
167
  - `loggerPlugin()`
165
168
  - `uploadPlugin()`
@@ -168,6 +171,23 @@ Built-in plugins:
168
171
  Plugin-owned request options belong under `extensions`. Third-party plugins can
169
172
  augment `RequestExtensions` through TypeScript module augmentation.
170
173
 
174
+ Protect a failing upstream after retries are exhausted:
175
+
176
+ ```ts
177
+ const breaker = circuitBreakerPlugin({
178
+ failureThreshold: 5,
179
+ resetTimeout: 30000
180
+ })
181
+
182
+ const request = createClient()
183
+ .use(retryPlugin({ retries: 2 }))
184
+ .use(breaker)
185
+ ```
186
+
187
+ Circuits are isolated by request origin by default. Open circuits reject with
188
+ the stable `CIRCUIT_OPEN` error code and permit a bounded half-open probe after
189
+ the recovery window.
190
+
171
191
  Inject a structured logger when request correlation and timing are needed:
172
192
 
173
193
  ```ts
@@ -242,6 +262,7 @@ Stable request error codes:
242
262
  - `TIMEOUT_ERROR`
243
263
  - `ABORT_ERROR`
244
264
  - `PARSER_ERROR`
265
+ - `CIRCUIT_OPEN`
245
266
 
246
267
  ## Documentation
247
268
 
package/dist/index.cjs CHANGED
@@ -29,6 +29,7 @@ __export(index_exports, {
29
29
  RequestError: () => RequestError,
30
30
  authPlugin: () => authPlugin,
31
31
  cachePlugin: () => cachePlugin,
32
+ circuitBreakerPlugin: () => circuitBreakerPlugin,
32
33
  createClient: () => createClient,
33
34
  downloadPlugin: () => downloadPlugin,
34
35
  loggerPlugin: () => loggerPlugin,
@@ -2236,6 +2237,233 @@ function cloneCacheValue(value) {
2236
2237
  }
2237
2238
  }
2238
2239
 
2240
+ // src/plugins/circuitBreakerPlugin.ts
2241
+ function circuitBreakerPlugin(options = {}) {
2242
+ const normalized = normalizeOptions(options);
2243
+ const circuits = /* @__PURE__ */ new Map();
2244
+ const plugin = {
2245
+ name: "circuit-breaker",
2246
+ getState(key) {
2247
+ return circuits.get(key)?.state ?? "closed";
2248
+ },
2249
+ reset(key) {
2250
+ if (key === void 0) {
2251
+ circuits.clear();
2252
+ return;
2253
+ }
2254
+ circuits.delete(key);
2255
+ },
2256
+ install(context) {
2257
+ const admissions = /* @__PURE__ */ new WeakMap();
2258
+ let active = true;
2259
+ context.hooks.onRequest((requestContext) => {
2260
+ const requestOptions = resolveExtensionConfig(
2261
+ requestContext.config,
2262
+ "circuitBreaker"
2263
+ );
2264
+ if (requestOptions?.enabled === false) {
2265
+ return;
2266
+ }
2267
+ const key = normalizeKey(
2268
+ requestOptions?.key ?? normalized.createKey(requestContext.config)
2269
+ );
2270
+ const record = getCircuit(circuits, key);
2271
+ if (record.state === "open" && Date.now() - record.openedAt >= normalized.resetTimeout) {
2272
+ transition(record, key, "half-open", normalized);
2273
+ }
2274
+ if (record.state === "open") {
2275
+ throw createOpenError(key, requestContext.config);
2276
+ }
2277
+ const probe = record.state === "half-open";
2278
+ if (probe && record.probes >= normalized.halfOpenMaxRequests) {
2279
+ throw createOpenError(key, requestContext.config);
2280
+ }
2281
+ if (probe) {
2282
+ record.probes += 1;
2283
+ }
2284
+ admissions.set(requestContext, {
2285
+ key,
2286
+ generation: record.generation,
2287
+ probe
2288
+ });
2289
+ });
2290
+ context.hooks.onSettled(async (requestContext) => {
2291
+ const admission = admissions.get(requestContext);
2292
+ if (!admission) {
2293
+ return;
2294
+ }
2295
+ admissions.delete(requestContext);
2296
+ if (!active) {
2297
+ return;
2298
+ }
2299
+ const record = circuits.get(admission.key);
2300
+ if (!record || record.generation !== admission.generation) {
2301
+ return;
2302
+ }
2303
+ if (admission.probe) {
2304
+ record.probes = Math.max(0, record.probes - 1);
2305
+ }
2306
+ if (!requestContext.error && requestContext.response) {
2307
+ record.failures = 0;
2308
+ if (admission.probe && record.state === "half-open") {
2309
+ record.successes += 1;
2310
+ if (record.successes >= normalized.successThreshold) {
2311
+ transition(record, admission.key, "closed", normalized);
2312
+ }
2313
+ }
2314
+ return;
2315
+ }
2316
+ const counted = await normalized.shouldCountFailure(
2317
+ requestContext.error,
2318
+ requestContext.config
2319
+ );
2320
+ if (!active || circuits.get(admission.key) !== record || record.generation !== admission.generation || !counted) {
2321
+ return;
2322
+ }
2323
+ if (admission.probe && record.state === "half-open") {
2324
+ transition(record, admission.key, "open", normalized);
2325
+ return;
2326
+ }
2327
+ if (record.state === "closed") {
2328
+ record.failures += 1;
2329
+ if (record.failures >= normalized.failureThreshold) {
2330
+ transition(record, admission.key, "open", normalized);
2331
+ }
2332
+ }
2333
+ });
2334
+ return () => {
2335
+ active = false;
2336
+ circuits.clear();
2337
+ };
2338
+ }
2339
+ };
2340
+ return plugin;
2341
+ }
2342
+ function normalizeOptions(options) {
2343
+ return {
2344
+ failureThreshold: normalizePositiveInteger(
2345
+ options.failureThreshold,
2346
+ 5
2347
+ ),
2348
+ successThreshold: normalizePositiveInteger(
2349
+ options.successThreshold,
2350
+ 1
2351
+ ),
2352
+ resetTimeout: normalizeDuration(options.resetTimeout, 3e4),
2353
+ halfOpenMaxRequests: normalizePositiveInteger(
2354
+ options.halfOpenMaxRequests,
2355
+ 1
2356
+ ),
2357
+ createKey: options.createKey ?? createDefaultKey,
2358
+ shouldCountFailure: options.shouldCountFailure ?? defaultShouldCountFailure,
2359
+ onStateChange: options.onStateChange
2360
+ };
2361
+ }
2362
+ function normalizePositiveInteger(value, fallback) {
2363
+ if (value === void 0) {
2364
+ return fallback;
2365
+ }
2366
+ if (!Number.isFinite(value)) {
2367
+ return fallback;
2368
+ }
2369
+ return Math.max(1, Math.floor(value));
2370
+ }
2371
+ function normalizeDuration(value, fallback) {
2372
+ if (value === void 0) {
2373
+ return fallback;
2374
+ }
2375
+ if (!Number.isFinite(value)) {
2376
+ return value > 0 ? Number.MAX_SAFE_INTEGER : 0;
2377
+ }
2378
+ return Math.max(0, value);
2379
+ }
2380
+ function normalizeKey(key) {
2381
+ return key || "default";
2382
+ }
2383
+ function createDefaultKey(config) {
2384
+ try {
2385
+ return new URL(config.url).origin;
2386
+ } catch {
2387
+ }
2388
+ try {
2389
+ if (config.baseURL) {
2390
+ return new URL(config.url, config.baseURL).origin;
2391
+ }
2392
+ } catch {
2393
+ }
2394
+ return "default";
2395
+ }
2396
+ function getCircuit(circuits, key) {
2397
+ let record = circuits.get(key);
2398
+ if (!record) {
2399
+ record = {
2400
+ state: "closed",
2401
+ failures: 0,
2402
+ successes: 0,
2403
+ openedAt: 0,
2404
+ probes: 0,
2405
+ generation: 0
2406
+ };
2407
+ circuits.set(key, record);
2408
+ }
2409
+ return record;
2410
+ }
2411
+ function transition(record, key, state, options) {
2412
+ if (record.state === state) {
2413
+ if (state === "open") {
2414
+ record.openedAt = Date.now();
2415
+ record.successes = 0;
2416
+ record.probes = 0;
2417
+ record.generation += 1;
2418
+ }
2419
+ return;
2420
+ }
2421
+ const previousState = record.state;
2422
+ record.state = state;
2423
+ record.successes = 0;
2424
+ record.probes = 0;
2425
+ record.generation += 1;
2426
+ if (state === "open") {
2427
+ record.openedAt = Date.now();
2428
+ } else if (state === "closed") {
2429
+ record.failures = 0;
2430
+ record.openedAt = 0;
2431
+ }
2432
+ notifyStateChange(options.onStateChange, {
2433
+ key,
2434
+ previousState,
2435
+ state,
2436
+ timestamp: Date.now(),
2437
+ failures: record.failures
2438
+ });
2439
+ }
2440
+ function notifyStateChange(observer, event) {
2441
+ if (!observer) {
2442
+ return;
2443
+ }
2444
+ try {
2445
+ void Promise.resolve(observer(event)).catch(ignoreObserverError);
2446
+ } catch {
2447
+ }
2448
+ }
2449
+ function ignoreObserverError() {
2450
+ }
2451
+ function createOpenError(key, config) {
2452
+ return new RequestError(`Circuit is open for ${key}`, {
2453
+ code: "CIRCUIT_OPEN",
2454
+ config
2455
+ });
2456
+ }
2457
+ function defaultShouldCountFailure(error) {
2458
+ if (!(error instanceof RequestError)) {
2459
+ return true;
2460
+ }
2461
+ if (error.code === "NETWORK_ERROR" || error.code === "TIMEOUT_ERROR") {
2462
+ return true;
2463
+ }
2464
+ return error.code === "HTTP_ERROR" && (error.status === 429 || error.status !== void 0 && error.status >= 500);
2465
+ }
2466
+
2239
2467
  // src/plugins/xhrTransport.ts
2240
2468
  function xhrRequest(config, options = {}) {
2241
2469
  let request;
@@ -3165,6 +3393,7 @@ function uploadPlugin() {
3165
3393
  RequestError,
3166
3394
  authPlugin,
3167
3395
  cachePlugin,
3396
+ circuitBreakerPlugin,
3168
3397
  createClient,
3169
3398
  downloadPlugin,
3170
3399
  loggerPlugin,
package/dist/index.d.cts CHANGED
@@ -3,6 +3,26 @@
3
3
  */
4
4
  type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS';
5
5
 
6
+ type CircuitState = 'closed' | 'open' | 'half-open';
7
+ interface CircuitBreakerOptions {
8
+ /**
9
+ * Enable circuit-breaker protection for this request.
10
+ *
11
+ * @default true
12
+ */
13
+ enabled?: boolean;
14
+ /**
15
+ * Override the isolation key for this request.
16
+ */
17
+ key?: string;
18
+ }
19
+ interface CircuitBreakerStateChange {
20
+ key: string;
21
+ previousState: CircuitState;
22
+ state: CircuitState;
23
+ timestamp: number;
24
+ failures: number;
25
+ }
6
26
  /**
7
27
  * Per-request retry configuration used by the retry extension.
8
28
  */
@@ -200,6 +220,7 @@ type FetchOptions = Omit<RequestInit, 'method' | 'headers' | 'body' | 'signal'>;
200
220
  interface RequestExtensions {
201
221
  auth?: AuthOptions;
202
222
  cache?: CacheOptions;
223
+ circuitBreaker?: CircuitBreakerOptions;
203
224
  download?: DownloadOptions;
204
225
  logger?: LoggerOptions;
205
226
  retry?: number | RetryOptions;
@@ -495,7 +516,7 @@ declare function createClient(options?: ClientOptions): Client;
495
516
  /**
496
517
  * Public request error codes.
497
518
  */
498
- type RequestErrorCode = 'CONFIG_ERROR' | 'HTTP_ERROR' | 'NETWORK_ERROR' | 'TIMEOUT_ERROR' | 'ABORT_ERROR' | 'PARSER_ERROR';
519
+ type RequestErrorCode = 'CONFIG_ERROR' | 'HTTP_ERROR' | 'NETWORK_ERROR' | 'TIMEOUT_ERROR' | 'ABORT_ERROR' | 'PARSER_ERROR' | 'CIRCUIT_OPEN';
499
520
  interface RequestErrorOptions<T = unknown> {
500
521
  /**
501
522
  * Stable machine-readable error code.
@@ -654,6 +675,54 @@ interface CachePlugin extends Plugin {
654
675
  }
655
676
  declare function cachePlugin(options?: CachePluginOptions): CachePlugin;
656
677
 
678
+ interface CircuitBreakerPluginOptions {
679
+ /**
680
+ * Consecutive counted failures required to open a closed circuit.
681
+ *
682
+ * @default 5
683
+ */
684
+ failureThreshold?: number;
685
+ /**
686
+ * Successful probes required to close a half-open circuit.
687
+ *
688
+ * @default 1
689
+ */
690
+ successThreshold?: number;
691
+ /**
692
+ * Time in milliseconds before an open circuit permits probes.
693
+ *
694
+ * @default 30000
695
+ */
696
+ resetTimeout?: number;
697
+ /**
698
+ * Maximum concurrent probes admitted while a circuit is half-open.
699
+ *
700
+ * @default 1
701
+ */
702
+ halfOpenMaxRequests?: number;
703
+ /**
704
+ * Create the default isolation key for a request.
705
+ *
706
+ * @default the resolved request origin or "default"
707
+ */
708
+ createKey?: (config: RequestConfig) => string;
709
+ /**
710
+ * Decide whether a final request failure affects the circuit.
711
+ *
712
+ * @default network errors, timeouts, HTTP 429, and HTTP 5xx
713
+ */
714
+ shouldCountFailure?: (error: unknown, config: RequestConfig) => boolean | Promise<boolean>;
715
+ /**
716
+ * Observe circuit state changes. Observer failures are isolated.
717
+ */
718
+ onStateChange?: (event: Readonly<CircuitBreakerStateChange>) => void | Promise<void>;
719
+ }
720
+ interface CircuitBreakerPlugin extends Plugin {
721
+ getState(key: string): CircuitState;
722
+ reset(key?: string): void;
723
+ }
724
+ declare function circuitBreakerPlugin(options?: CircuitBreakerPluginOptions): CircuitBreakerPlugin;
725
+
657
726
  type DownloadTransport = 'auto' | 'fetch' | 'xhr';
658
727
  interface DownloadPluginOptions {
659
728
  /**
@@ -674,4 +743,4 @@ declare function retryPlugin(defaultOptions?: RetryOptions): Plugin;
674
743
 
675
744
  declare function uploadPlugin(): Plugin;
676
745
 
677
- export { type Adapter, type AuthOptions, type AuthPluginOptions, type AuthTokenStorage, type CacheEntry, type CacheOptions, type CachePlugin, type CachePluginOptions, type CacheStore, Client, type ClientOptions, type DownloadOptions, type DownloadPluginOptions, type DownloadProgress, type DownloadTransport, type ErrorLogEntry, FetchAdapter, type FetchOptions, type HttpMethod, type Interceptor, InterceptorManager, type InterceptorOptions, type LoggerEntry, type LoggerOptions, MemoryCacheStore, MockAdapter, type MockAdapterOptions, type MockHandler, type MockReply, type MockReplyHandler, type MockRequestMatcher, type MockResponseOptions, type MockRoute, type MockURLMatcher, type NporaResponse, type Plugin, type PluginCleanup, type PluginContext, PluginError, type PluginErrorCode, type PluginErrorOptions, type PluginHookManager, type PluginInterceptorManager, type QueryParams, type QueryValue, type RequestConfig, RequestError, type RequestErrorCode, type RequestErrorOptions, type RequestExtensions, type RequestLogEntry, type RequestLogger, type ResponseLogEntry, type ResponseType, type RetryEvent, type RetryOptions, type UploadData, type UploadOptions, type UploadProgress, authPlugin, cachePlugin, createClient, downloadPlugin, loggerPlugin, retryPlugin, uploadPlugin };
746
+ export { type Adapter, type AuthOptions, type AuthPluginOptions, type AuthTokenStorage, type CacheEntry, type CacheOptions, type CachePlugin, type CachePluginOptions, type CacheStore, type CircuitBreakerOptions, type CircuitBreakerPlugin, type CircuitBreakerPluginOptions, type CircuitBreakerStateChange, type CircuitState, Client, type ClientOptions, type DownloadOptions, type DownloadPluginOptions, type DownloadProgress, type DownloadTransport, type ErrorLogEntry, FetchAdapter, type FetchOptions, type HttpMethod, type Interceptor, InterceptorManager, type InterceptorOptions, type LoggerEntry, type LoggerOptions, MemoryCacheStore, MockAdapter, type MockAdapterOptions, type MockHandler, type MockReply, type MockReplyHandler, type MockRequestMatcher, type MockResponseOptions, type MockRoute, type MockURLMatcher, type NporaResponse, type Plugin, type PluginCleanup, type PluginContext, PluginError, type PluginErrorCode, type PluginErrorOptions, type PluginHookManager, type PluginInterceptorManager, type QueryParams, type QueryValue, type RequestConfig, RequestError, type RequestErrorCode, type RequestErrorOptions, type RequestExtensions, type RequestLogEntry, type RequestLogger, type ResponseLogEntry, type ResponseType, type RetryEvent, type RetryOptions, type UploadData, type UploadOptions, type UploadProgress, authPlugin, cachePlugin, circuitBreakerPlugin, createClient, downloadPlugin, loggerPlugin, retryPlugin, uploadPlugin };
package/dist/index.d.ts CHANGED
@@ -3,6 +3,26 @@
3
3
  */
4
4
  type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS';
5
5
 
6
+ type CircuitState = 'closed' | 'open' | 'half-open';
7
+ interface CircuitBreakerOptions {
8
+ /**
9
+ * Enable circuit-breaker protection for this request.
10
+ *
11
+ * @default true
12
+ */
13
+ enabled?: boolean;
14
+ /**
15
+ * Override the isolation key for this request.
16
+ */
17
+ key?: string;
18
+ }
19
+ interface CircuitBreakerStateChange {
20
+ key: string;
21
+ previousState: CircuitState;
22
+ state: CircuitState;
23
+ timestamp: number;
24
+ failures: number;
25
+ }
6
26
  /**
7
27
  * Per-request retry configuration used by the retry extension.
8
28
  */
@@ -200,6 +220,7 @@ type FetchOptions = Omit<RequestInit, 'method' | 'headers' | 'body' | 'signal'>;
200
220
  interface RequestExtensions {
201
221
  auth?: AuthOptions;
202
222
  cache?: CacheOptions;
223
+ circuitBreaker?: CircuitBreakerOptions;
203
224
  download?: DownloadOptions;
204
225
  logger?: LoggerOptions;
205
226
  retry?: number | RetryOptions;
@@ -495,7 +516,7 @@ declare function createClient(options?: ClientOptions): Client;
495
516
  /**
496
517
  * Public request error codes.
497
518
  */
498
- type RequestErrorCode = 'CONFIG_ERROR' | 'HTTP_ERROR' | 'NETWORK_ERROR' | 'TIMEOUT_ERROR' | 'ABORT_ERROR' | 'PARSER_ERROR';
519
+ type RequestErrorCode = 'CONFIG_ERROR' | 'HTTP_ERROR' | 'NETWORK_ERROR' | 'TIMEOUT_ERROR' | 'ABORT_ERROR' | 'PARSER_ERROR' | 'CIRCUIT_OPEN';
499
520
  interface RequestErrorOptions<T = unknown> {
500
521
  /**
501
522
  * Stable machine-readable error code.
@@ -654,6 +675,54 @@ interface CachePlugin extends Plugin {
654
675
  }
655
676
  declare function cachePlugin(options?: CachePluginOptions): CachePlugin;
656
677
 
678
+ interface CircuitBreakerPluginOptions {
679
+ /**
680
+ * Consecutive counted failures required to open a closed circuit.
681
+ *
682
+ * @default 5
683
+ */
684
+ failureThreshold?: number;
685
+ /**
686
+ * Successful probes required to close a half-open circuit.
687
+ *
688
+ * @default 1
689
+ */
690
+ successThreshold?: number;
691
+ /**
692
+ * Time in milliseconds before an open circuit permits probes.
693
+ *
694
+ * @default 30000
695
+ */
696
+ resetTimeout?: number;
697
+ /**
698
+ * Maximum concurrent probes admitted while a circuit is half-open.
699
+ *
700
+ * @default 1
701
+ */
702
+ halfOpenMaxRequests?: number;
703
+ /**
704
+ * Create the default isolation key for a request.
705
+ *
706
+ * @default the resolved request origin or "default"
707
+ */
708
+ createKey?: (config: RequestConfig) => string;
709
+ /**
710
+ * Decide whether a final request failure affects the circuit.
711
+ *
712
+ * @default network errors, timeouts, HTTP 429, and HTTP 5xx
713
+ */
714
+ shouldCountFailure?: (error: unknown, config: RequestConfig) => boolean | Promise<boolean>;
715
+ /**
716
+ * Observe circuit state changes. Observer failures are isolated.
717
+ */
718
+ onStateChange?: (event: Readonly<CircuitBreakerStateChange>) => void | Promise<void>;
719
+ }
720
+ interface CircuitBreakerPlugin extends Plugin {
721
+ getState(key: string): CircuitState;
722
+ reset(key?: string): void;
723
+ }
724
+ declare function circuitBreakerPlugin(options?: CircuitBreakerPluginOptions): CircuitBreakerPlugin;
725
+
657
726
  type DownloadTransport = 'auto' | 'fetch' | 'xhr';
658
727
  interface DownloadPluginOptions {
659
728
  /**
@@ -674,4 +743,4 @@ declare function retryPlugin(defaultOptions?: RetryOptions): Plugin;
674
743
 
675
744
  declare function uploadPlugin(): Plugin;
676
745
 
677
- export { type Adapter, type AuthOptions, type AuthPluginOptions, type AuthTokenStorage, type CacheEntry, type CacheOptions, type CachePlugin, type CachePluginOptions, type CacheStore, Client, type ClientOptions, type DownloadOptions, type DownloadPluginOptions, type DownloadProgress, type DownloadTransport, type ErrorLogEntry, FetchAdapter, type FetchOptions, type HttpMethod, type Interceptor, InterceptorManager, type InterceptorOptions, type LoggerEntry, type LoggerOptions, MemoryCacheStore, MockAdapter, type MockAdapterOptions, type MockHandler, type MockReply, type MockReplyHandler, type MockRequestMatcher, type MockResponseOptions, type MockRoute, type MockURLMatcher, type NporaResponse, type Plugin, type PluginCleanup, type PluginContext, PluginError, type PluginErrorCode, type PluginErrorOptions, type PluginHookManager, type PluginInterceptorManager, type QueryParams, type QueryValue, type RequestConfig, RequestError, type RequestErrorCode, type RequestErrorOptions, type RequestExtensions, type RequestLogEntry, type RequestLogger, type ResponseLogEntry, type ResponseType, type RetryEvent, type RetryOptions, type UploadData, type UploadOptions, type UploadProgress, authPlugin, cachePlugin, createClient, downloadPlugin, loggerPlugin, retryPlugin, uploadPlugin };
746
+ export { type Adapter, type AuthOptions, type AuthPluginOptions, type AuthTokenStorage, type CacheEntry, type CacheOptions, type CachePlugin, type CachePluginOptions, type CacheStore, type CircuitBreakerOptions, type CircuitBreakerPlugin, type CircuitBreakerPluginOptions, type CircuitBreakerStateChange, type CircuitState, Client, type ClientOptions, type DownloadOptions, type DownloadPluginOptions, type DownloadProgress, type DownloadTransport, type ErrorLogEntry, FetchAdapter, type FetchOptions, type HttpMethod, type Interceptor, InterceptorManager, type InterceptorOptions, type LoggerEntry, type LoggerOptions, MemoryCacheStore, MockAdapter, type MockAdapterOptions, type MockHandler, type MockReply, type MockReplyHandler, type MockRequestMatcher, type MockResponseOptions, type MockRoute, type MockURLMatcher, type NporaResponse, type Plugin, type PluginCleanup, type PluginContext, PluginError, type PluginErrorCode, type PluginErrorOptions, type PluginHookManager, type PluginInterceptorManager, type QueryParams, type QueryValue, type RequestConfig, RequestError, type RequestErrorCode, type RequestErrorOptions, type RequestExtensions, type RequestLogEntry, type RequestLogger, type ResponseLogEntry, type ResponseType, type RetryEvent, type RetryOptions, type UploadData, type UploadOptions, type UploadProgress, authPlugin, cachePlugin, circuitBreakerPlugin, createClient, downloadPlugin, loggerPlugin, retryPlugin, uploadPlugin };
package/dist/index.js CHANGED
@@ -2197,6 +2197,233 @@ function cloneCacheValue(value) {
2197
2197
  }
2198
2198
  }
2199
2199
 
2200
+ // src/plugins/circuitBreakerPlugin.ts
2201
+ function circuitBreakerPlugin(options = {}) {
2202
+ const normalized = normalizeOptions(options);
2203
+ const circuits = /* @__PURE__ */ new Map();
2204
+ const plugin = {
2205
+ name: "circuit-breaker",
2206
+ getState(key) {
2207
+ return circuits.get(key)?.state ?? "closed";
2208
+ },
2209
+ reset(key) {
2210
+ if (key === void 0) {
2211
+ circuits.clear();
2212
+ return;
2213
+ }
2214
+ circuits.delete(key);
2215
+ },
2216
+ install(context) {
2217
+ const admissions = /* @__PURE__ */ new WeakMap();
2218
+ let active = true;
2219
+ context.hooks.onRequest((requestContext) => {
2220
+ const requestOptions = resolveExtensionConfig(
2221
+ requestContext.config,
2222
+ "circuitBreaker"
2223
+ );
2224
+ if (requestOptions?.enabled === false) {
2225
+ return;
2226
+ }
2227
+ const key = normalizeKey(
2228
+ requestOptions?.key ?? normalized.createKey(requestContext.config)
2229
+ );
2230
+ const record = getCircuit(circuits, key);
2231
+ if (record.state === "open" && Date.now() - record.openedAt >= normalized.resetTimeout) {
2232
+ transition(record, key, "half-open", normalized);
2233
+ }
2234
+ if (record.state === "open") {
2235
+ throw createOpenError(key, requestContext.config);
2236
+ }
2237
+ const probe = record.state === "half-open";
2238
+ if (probe && record.probes >= normalized.halfOpenMaxRequests) {
2239
+ throw createOpenError(key, requestContext.config);
2240
+ }
2241
+ if (probe) {
2242
+ record.probes += 1;
2243
+ }
2244
+ admissions.set(requestContext, {
2245
+ key,
2246
+ generation: record.generation,
2247
+ probe
2248
+ });
2249
+ });
2250
+ context.hooks.onSettled(async (requestContext) => {
2251
+ const admission = admissions.get(requestContext);
2252
+ if (!admission) {
2253
+ return;
2254
+ }
2255
+ admissions.delete(requestContext);
2256
+ if (!active) {
2257
+ return;
2258
+ }
2259
+ const record = circuits.get(admission.key);
2260
+ if (!record || record.generation !== admission.generation) {
2261
+ return;
2262
+ }
2263
+ if (admission.probe) {
2264
+ record.probes = Math.max(0, record.probes - 1);
2265
+ }
2266
+ if (!requestContext.error && requestContext.response) {
2267
+ record.failures = 0;
2268
+ if (admission.probe && record.state === "half-open") {
2269
+ record.successes += 1;
2270
+ if (record.successes >= normalized.successThreshold) {
2271
+ transition(record, admission.key, "closed", normalized);
2272
+ }
2273
+ }
2274
+ return;
2275
+ }
2276
+ const counted = await normalized.shouldCountFailure(
2277
+ requestContext.error,
2278
+ requestContext.config
2279
+ );
2280
+ if (!active || circuits.get(admission.key) !== record || record.generation !== admission.generation || !counted) {
2281
+ return;
2282
+ }
2283
+ if (admission.probe && record.state === "half-open") {
2284
+ transition(record, admission.key, "open", normalized);
2285
+ return;
2286
+ }
2287
+ if (record.state === "closed") {
2288
+ record.failures += 1;
2289
+ if (record.failures >= normalized.failureThreshold) {
2290
+ transition(record, admission.key, "open", normalized);
2291
+ }
2292
+ }
2293
+ });
2294
+ return () => {
2295
+ active = false;
2296
+ circuits.clear();
2297
+ };
2298
+ }
2299
+ };
2300
+ return plugin;
2301
+ }
2302
+ function normalizeOptions(options) {
2303
+ return {
2304
+ failureThreshold: normalizePositiveInteger(
2305
+ options.failureThreshold,
2306
+ 5
2307
+ ),
2308
+ successThreshold: normalizePositiveInteger(
2309
+ options.successThreshold,
2310
+ 1
2311
+ ),
2312
+ resetTimeout: normalizeDuration(options.resetTimeout, 3e4),
2313
+ halfOpenMaxRequests: normalizePositiveInteger(
2314
+ options.halfOpenMaxRequests,
2315
+ 1
2316
+ ),
2317
+ createKey: options.createKey ?? createDefaultKey,
2318
+ shouldCountFailure: options.shouldCountFailure ?? defaultShouldCountFailure,
2319
+ onStateChange: options.onStateChange
2320
+ };
2321
+ }
2322
+ function normalizePositiveInteger(value, fallback) {
2323
+ if (value === void 0) {
2324
+ return fallback;
2325
+ }
2326
+ if (!Number.isFinite(value)) {
2327
+ return fallback;
2328
+ }
2329
+ return Math.max(1, Math.floor(value));
2330
+ }
2331
+ function normalizeDuration(value, fallback) {
2332
+ if (value === void 0) {
2333
+ return fallback;
2334
+ }
2335
+ if (!Number.isFinite(value)) {
2336
+ return value > 0 ? Number.MAX_SAFE_INTEGER : 0;
2337
+ }
2338
+ return Math.max(0, value);
2339
+ }
2340
+ function normalizeKey(key) {
2341
+ return key || "default";
2342
+ }
2343
+ function createDefaultKey(config) {
2344
+ try {
2345
+ return new URL(config.url).origin;
2346
+ } catch {
2347
+ }
2348
+ try {
2349
+ if (config.baseURL) {
2350
+ return new URL(config.url, config.baseURL).origin;
2351
+ }
2352
+ } catch {
2353
+ }
2354
+ return "default";
2355
+ }
2356
+ function getCircuit(circuits, key) {
2357
+ let record = circuits.get(key);
2358
+ if (!record) {
2359
+ record = {
2360
+ state: "closed",
2361
+ failures: 0,
2362
+ successes: 0,
2363
+ openedAt: 0,
2364
+ probes: 0,
2365
+ generation: 0
2366
+ };
2367
+ circuits.set(key, record);
2368
+ }
2369
+ return record;
2370
+ }
2371
+ function transition(record, key, state, options) {
2372
+ if (record.state === state) {
2373
+ if (state === "open") {
2374
+ record.openedAt = Date.now();
2375
+ record.successes = 0;
2376
+ record.probes = 0;
2377
+ record.generation += 1;
2378
+ }
2379
+ return;
2380
+ }
2381
+ const previousState = record.state;
2382
+ record.state = state;
2383
+ record.successes = 0;
2384
+ record.probes = 0;
2385
+ record.generation += 1;
2386
+ if (state === "open") {
2387
+ record.openedAt = Date.now();
2388
+ } else if (state === "closed") {
2389
+ record.failures = 0;
2390
+ record.openedAt = 0;
2391
+ }
2392
+ notifyStateChange(options.onStateChange, {
2393
+ key,
2394
+ previousState,
2395
+ state,
2396
+ timestamp: Date.now(),
2397
+ failures: record.failures
2398
+ });
2399
+ }
2400
+ function notifyStateChange(observer, event) {
2401
+ if (!observer) {
2402
+ return;
2403
+ }
2404
+ try {
2405
+ void Promise.resolve(observer(event)).catch(ignoreObserverError);
2406
+ } catch {
2407
+ }
2408
+ }
2409
+ function ignoreObserverError() {
2410
+ }
2411
+ function createOpenError(key, config) {
2412
+ return new RequestError(`Circuit is open for ${key}`, {
2413
+ code: "CIRCUIT_OPEN",
2414
+ config
2415
+ });
2416
+ }
2417
+ function defaultShouldCountFailure(error) {
2418
+ if (!(error instanceof RequestError)) {
2419
+ return true;
2420
+ }
2421
+ if (error.code === "NETWORK_ERROR" || error.code === "TIMEOUT_ERROR") {
2422
+ return true;
2423
+ }
2424
+ return error.code === "HTTP_ERROR" && (error.status === 429 || error.status !== void 0 && error.status >= 500);
2425
+ }
2426
+
2200
2427
  // src/plugins/xhrTransport.ts
2201
2428
  function xhrRequest(config, options = {}) {
2202
2429
  let request;
@@ -3125,6 +3352,7 @@ export {
3125
3352
  RequestError,
3126
3353
  authPlugin,
3127
3354
  cachePlugin,
3355
+ circuitBreakerPlugin,
3128
3356
  createClient,
3129
3357
  downloadPlugin,
3130
3358
  loggerPlugin,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@npora/request",
3
- "version": "1.4.0",
3
+ "version": "1.5.0",
4
4
  "description": "A modern, TypeScript-first HTTP client powered by the Fetch API.",
5
5
  "keywords": [
6
6
  "npora",