@npora/request 1.4.0 → 1.6.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,
@@ -156,10 +158,15 @@ const cache = cachePlugin({
156
158
  })
157
159
  ```
158
160
 
161
+ The default memory store keeps up to 1,000 entries using LRU eviction and
162
+ removes expired entries when read. Set `maxEntries` to tune the bound, use `0`
163
+ to disable storage, or use `Infinity` for an explicitly unbounded store.
164
+
159
165
  Built-in plugins:
160
166
 
161
167
  - `retryPlugin()`
162
168
  - `cachePlugin()`
169
+ - `circuitBreakerPlugin()`
163
170
  - `authPlugin()`
164
171
  - `loggerPlugin()`
165
172
  - `uploadPlugin()`
@@ -168,6 +175,25 @@ Built-in plugins:
168
175
  Plugin-owned request options belong under `extensions`. Third-party plugins can
169
176
  augment `RequestExtensions` through TypeScript module augmentation.
170
177
 
178
+ Protect a failing upstream after retries are exhausted:
179
+
180
+ ```ts
181
+ const breaker = circuitBreakerPlugin({
182
+ failureThreshold: 5,
183
+ resetTimeout: 30000,
184
+ maxCircuits: 1000
185
+ })
186
+
187
+ const request = createClient()
188
+ .use(retryPlugin({ retries: 2 }))
189
+ .use(breaker)
190
+ ```
191
+
192
+ Circuits are isolated by request origin by default. Open circuits reject with
193
+ the stable `CIRCUIT_OPEN` error code and permit a bounded half-open probe after
194
+ the recovery window. Inactive circuit state is retained with LRU eviction;
195
+ active requests are never evicted and can temporarily exceed `maxCircuits`.
196
+
171
197
  Inject a structured logger when request correlation and timing are needed:
172
198
 
173
199
  ```ts
@@ -242,6 +268,7 @@ Stable request error codes:
242
268
  - `TIMEOUT_ERROR`
243
269
  - `ABORT_ERROR`
244
270
  - `PARSER_ERROR`
271
+ - `CIRCUIT_OPEN`
245
272
 
246
273
  ## Documentation
247
274
 
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,
@@ -1868,13 +1869,35 @@ function defaultShouldRefresh(error) {
1868
1869
 
1869
1870
  // src/plugins/cachePlugin.ts
1870
1871
  var MemoryCacheStore = class {
1871
- constructor() {
1872
+ constructor(options = {}) {
1872
1873
  this.entries = /* @__PURE__ */ new Map();
1874
+ this.maxEntries = normalizeMaxEntries(options.maxEntries);
1873
1875
  }
1874
1876
  get(key) {
1875
- return this.entries.get(key);
1877
+ const entry = this.entries.get(key);
1878
+ if (!entry) {
1879
+ return void 0;
1880
+ }
1881
+ if (!Number.isFinite(entry.expiresAt) || Date.now() > entry.expiresAt) {
1882
+ this.entries.delete(key);
1883
+ return void 0;
1884
+ }
1885
+ this.entries.delete(key);
1886
+ this.entries.set(key, entry);
1887
+ return entry;
1876
1888
  }
1877
1889
  set(key, entry) {
1890
+ if (this.maxEntries === 0) {
1891
+ return;
1892
+ }
1893
+ this.entries.delete(key);
1894
+ while (this.entries.size >= this.maxEntries) {
1895
+ const oldestKey = this.entries.keys().next().value;
1896
+ if (oldestKey === void 0) {
1897
+ break;
1898
+ }
1899
+ this.entries.delete(oldestKey);
1900
+ }
1878
1901
  this.entries.set(key, entry);
1879
1902
  }
1880
1903
  delete(key) {
@@ -1895,7 +1918,9 @@ var DEFAULT_VARY_HEADERS = [
1895
1918
  "accept-language"
1896
1919
  ];
1897
1920
  function cachePlugin(options = {}) {
1898
- const store = options.store ?? new MemoryCacheStore();
1921
+ const store = options.store ?? new MemoryCacheStore({
1922
+ maxEntries: options.maxEntries
1923
+ });
1899
1924
  const cacheHits = /* @__PURE__ */ new WeakSet();
1900
1925
  const leaders = /* @__PURE__ */ new WeakMap();
1901
1926
  const completedRecords = /* @__PURE__ */ new WeakMap();
@@ -2235,6 +2260,275 @@ function cloneCacheValue(value) {
2235
2260
  return value;
2236
2261
  }
2237
2262
  }
2263
+ function normalizeMaxEntries(value) {
2264
+ if (value === void 0) {
2265
+ return 1e3;
2266
+ }
2267
+ if (!Number.isFinite(value)) {
2268
+ return value > 0 ? Number.POSITIVE_INFINITY : 0;
2269
+ }
2270
+ return Math.max(0, Math.floor(value));
2271
+ }
2272
+
2273
+ // src/plugins/circuitBreakerPlugin.ts
2274
+ function circuitBreakerPlugin(options = {}) {
2275
+ const normalized = normalizeOptions(options);
2276
+ const circuits = /* @__PURE__ */ new Map();
2277
+ const plugin = {
2278
+ name: "circuit-breaker",
2279
+ getState(key) {
2280
+ return circuits.get(key)?.state ?? "closed";
2281
+ },
2282
+ reset(key) {
2283
+ if (key === void 0) {
2284
+ circuits.clear();
2285
+ return;
2286
+ }
2287
+ circuits.delete(key);
2288
+ },
2289
+ install(context) {
2290
+ const admissions = /* @__PURE__ */ new WeakMap();
2291
+ let active = true;
2292
+ context.hooks.onRequest((requestContext) => {
2293
+ const requestOptions = resolveExtensionConfig(
2294
+ requestContext.config,
2295
+ "circuitBreaker"
2296
+ );
2297
+ if (requestOptions?.enabled === false) {
2298
+ return;
2299
+ }
2300
+ const key = normalizeKey(
2301
+ requestOptions?.key ?? normalized.createKey(requestContext.config)
2302
+ );
2303
+ const record = getCircuit(
2304
+ circuits,
2305
+ key,
2306
+ normalized.maxCircuits
2307
+ );
2308
+ if (record.state === "open" && Date.now() - record.openedAt >= normalized.resetTimeout) {
2309
+ transition(record, key, "half-open", normalized);
2310
+ }
2311
+ if (record.state === "open") {
2312
+ throw createOpenError(key, requestContext.config);
2313
+ }
2314
+ const probe = record.state === "half-open";
2315
+ if (probe && record.probes >= normalized.halfOpenMaxRequests) {
2316
+ throw createOpenError(key, requestContext.config);
2317
+ }
2318
+ if (probe) {
2319
+ record.probes += 1;
2320
+ }
2321
+ record.activeRequests += 1;
2322
+ admissions.set(requestContext, {
2323
+ key,
2324
+ generation: record.generation,
2325
+ probe,
2326
+ record
2327
+ });
2328
+ });
2329
+ context.hooks.onSettled(async (requestContext) => {
2330
+ const admission = admissions.get(requestContext);
2331
+ if (!admission) {
2332
+ return;
2333
+ }
2334
+ admissions.delete(requestContext);
2335
+ const record = admission.record;
2336
+ if (!active) {
2337
+ record.activeRequests = Math.max(0, record.activeRequests - 1);
2338
+ return;
2339
+ }
2340
+ try {
2341
+ if (circuits.get(admission.key) !== record || record.generation !== admission.generation) {
2342
+ return;
2343
+ }
2344
+ if (admission.probe) {
2345
+ record.probes = Math.max(0, record.probes - 1);
2346
+ }
2347
+ if (!requestContext.error && requestContext.response) {
2348
+ record.failures = 0;
2349
+ if (admission.probe && record.state === "half-open") {
2350
+ record.successes += 1;
2351
+ if (record.successes >= normalized.successThreshold) {
2352
+ transition(record, admission.key, "closed", normalized);
2353
+ }
2354
+ }
2355
+ return;
2356
+ }
2357
+ const counted = await normalized.shouldCountFailure(
2358
+ requestContext.error,
2359
+ requestContext.config
2360
+ );
2361
+ if (!active || circuits.get(admission.key) !== record || record.generation !== admission.generation || !counted) {
2362
+ return;
2363
+ }
2364
+ if (admission.probe && record.state === "half-open") {
2365
+ transition(record, admission.key, "open", normalized);
2366
+ return;
2367
+ }
2368
+ if (record.state === "closed") {
2369
+ record.failures += 1;
2370
+ if (record.failures >= normalized.failureThreshold) {
2371
+ transition(record, admission.key, "open", normalized);
2372
+ }
2373
+ }
2374
+ } finally {
2375
+ record.activeRequests = Math.max(0, record.activeRequests - 1);
2376
+ trimCircuits(circuits, normalized.maxCircuits);
2377
+ }
2378
+ });
2379
+ return () => {
2380
+ active = false;
2381
+ circuits.clear();
2382
+ };
2383
+ }
2384
+ };
2385
+ return plugin;
2386
+ }
2387
+ function normalizeOptions(options) {
2388
+ return {
2389
+ failureThreshold: normalizePositiveInteger(
2390
+ options.failureThreshold,
2391
+ 5
2392
+ ),
2393
+ successThreshold: normalizePositiveInteger(
2394
+ options.successThreshold,
2395
+ 1
2396
+ ),
2397
+ resetTimeout: normalizeDuration(options.resetTimeout, 3e4),
2398
+ halfOpenMaxRequests: normalizePositiveInteger(
2399
+ options.halfOpenMaxRequests,
2400
+ 1
2401
+ ),
2402
+ maxCircuits: normalizePositiveInteger(options.maxCircuits, 1e3),
2403
+ createKey: options.createKey ?? createDefaultKey,
2404
+ shouldCountFailure: options.shouldCountFailure ?? defaultShouldCountFailure,
2405
+ onStateChange: options.onStateChange
2406
+ };
2407
+ }
2408
+ function normalizePositiveInteger(value, fallback) {
2409
+ if (value === void 0) {
2410
+ return fallback;
2411
+ }
2412
+ if (!Number.isFinite(value)) {
2413
+ return fallback;
2414
+ }
2415
+ return Math.max(1, Math.floor(value));
2416
+ }
2417
+ function normalizeDuration(value, fallback) {
2418
+ if (value === void 0) {
2419
+ return fallback;
2420
+ }
2421
+ if (!Number.isFinite(value)) {
2422
+ return value > 0 ? Number.MAX_SAFE_INTEGER : 0;
2423
+ }
2424
+ return Math.max(0, value);
2425
+ }
2426
+ function normalizeKey(key) {
2427
+ return key || "default";
2428
+ }
2429
+ function createDefaultKey(config) {
2430
+ try {
2431
+ return new URL(config.url).origin;
2432
+ } catch {
2433
+ }
2434
+ try {
2435
+ if (config.baseURL) {
2436
+ return new URL(config.url, config.baseURL).origin;
2437
+ }
2438
+ } catch {
2439
+ }
2440
+ return "default";
2441
+ }
2442
+ function getCircuit(circuits, key, maxCircuits) {
2443
+ let record = circuits.get(key);
2444
+ if (record) {
2445
+ circuits.delete(key);
2446
+ circuits.set(key, record);
2447
+ return record;
2448
+ }
2449
+ trimCircuits(circuits, maxCircuits - 1);
2450
+ record = {
2451
+ state: "closed",
2452
+ failures: 0,
2453
+ successes: 0,
2454
+ openedAt: 0,
2455
+ probes: 0,
2456
+ generation: 0,
2457
+ activeRequests: 0
2458
+ };
2459
+ circuits.set(key, record);
2460
+ return record;
2461
+ }
2462
+ function trimCircuits(circuits, maxCircuits) {
2463
+ while (circuits.size > maxCircuits) {
2464
+ let removableKey;
2465
+ for (const [key, record] of circuits) {
2466
+ if (record.activeRequests === 0) {
2467
+ removableKey = key;
2468
+ break;
2469
+ }
2470
+ }
2471
+ if (removableKey === void 0) {
2472
+ return;
2473
+ }
2474
+ circuits.delete(removableKey);
2475
+ }
2476
+ }
2477
+ function transition(record, key, state, options) {
2478
+ if (record.state === state) {
2479
+ if (state === "open") {
2480
+ record.openedAt = Date.now();
2481
+ record.successes = 0;
2482
+ record.probes = 0;
2483
+ record.generation += 1;
2484
+ }
2485
+ return;
2486
+ }
2487
+ const previousState = record.state;
2488
+ record.state = state;
2489
+ record.successes = 0;
2490
+ record.probes = 0;
2491
+ record.generation += 1;
2492
+ if (state === "open") {
2493
+ record.openedAt = Date.now();
2494
+ } else if (state === "closed") {
2495
+ record.failures = 0;
2496
+ record.openedAt = 0;
2497
+ }
2498
+ notifyStateChange(options.onStateChange, {
2499
+ key,
2500
+ previousState,
2501
+ state,
2502
+ timestamp: Date.now(),
2503
+ failures: record.failures
2504
+ });
2505
+ }
2506
+ function notifyStateChange(observer, event) {
2507
+ if (!observer) {
2508
+ return;
2509
+ }
2510
+ try {
2511
+ void Promise.resolve(observer(event)).catch(ignoreObserverError);
2512
+ } catch {
2513
+ }
2514
+ }
2515
+ function ignoreObserverError() {
2516
+ }
2517
+ function createOpenError(key, config) {
2518
+ return new RequestError(`Circuit is open for ${key}`, {
2519
+ code: "CIRCUIT_OPEN",
2520
+ config
2521
+ });
2522
+ }
2523
+ function defaultShouldCountFailure(error) {
2524
+ if (!(error instanceof RequestError)) {
2525
+ return true;
2526
+ }
2527
+ if (error.code === "NETWORK_ERROR" || error.code === "TIMEOUT_ERROR") {
2528
+ return true;
2529
+ }
2530
+ return error.code === "HTTP_ERROR" && (error.status === 429 || error.status !== void 0 && error.status >= 500);
2531
+ }
2238
2532
 
2239
2533
  // src/plugins/xhrTransport.ts
2240
2534
  function xhrRequest(config, options = {}) {
@@ -3165,6 +3459,7 @@ function uploadPlugin() {
3165
3459
  RequestError,
3166
3460
  authPlugin,
3167
3461
  cachePlugin,
3462
+ circuitBreakerPlugin,
3168
3463
  createClient,
3169
3464
  downloadPlugin,
3170
3465
  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.
@@ -616,8 +637,19 @@ interface CacheStore {
616
637
  delete(key: string): MaybePromise<void>;
617
638
  clear(): MaybePromise<void>;
618
639
  }
640
+ interface MemoryCacheStoreOptions {
641
+ /**
642
+ * Maximum entries retained by the in-memory LRU store.
643
+ * Use `Infinity` for no practical limit.
644
+ *
645
+ * @default 1000
646
+ */
647
+ maxEntries?: number;
648
+ }
619
649
  declare class MemoryCacheStore implements CacheStore {
620
650
  private readonly entries;
651
+ private readonly maxEntries;
652
+ constructor(options?: MemoryCacheStoreOptions);
621
653
  get(key: string): CacheEntry | undefined;
622
654
  set(key: string, entry: CacheEntry): void;
623
655
  delete(key: string): void;
@@ -642,6 +674,13 @@ interface CachePluginOptions {
642
674
  * @default an isolated MemoryCacheStore
643
675
  */
644
676
  store?: CacheStore;
677
+ /**
678
+ * Maximum entries retained by the default MemoryCacheStore.
679
+ * Ignored when `store` is provided.
680
+ *
681
+ * @default 1000
682
+ */
683
+ maxEntries?: number;
645
684
  /**
646
685
  * Share one network operation between concurrent equivalent requests.
647
686
  *
@@ -654,6 +693,61 @@ interface CachePlugin extends Plugin {
654
693
  }
655
694
  declare function cachePlugin(options?: CachePluginOptions): CachePlugin;
656
695
 
696
+ interface CircuitBreakerPluginOptions {
697
+ /**
698
+ * Consecutive counted failures required to open a closed circuit.
699
+ *
700
+ * @default 5
701
+ */
702
+ failureThreshold?: number;
703
+ /**
704
+ * Successful probes required to close a half-open circuit.
705
+ *
706
+ * @default 1
707
+ */
708
+ successThreshold?: number;
709
+ /**
710
+ * Time in milliseconds before an open circuit permits probes.
711
+ *
712
+ * @default 30000
713
+ */
714
+ resetTimeout?: number;
715
+ /**
716
+ * Maximum concurrent probes admitted while a circuit is half-open.
717
+ *
718
+ * @default 1
719
+ */
720
+ halfOpenMaxRequests?: number;
721
+ /**
722
+ * Maximum inactive isolation states retained by this plugin instance.
723
+ * Active requests are never evicted and may temporarily exceed the limit.
724
+ *
725
+ * @default 1000
726
+ */
727
+ maxCircuits?: number;
728
+ /**
729
+ * Create the default isolation key for a request.
730
+ *
731
+ * @default the resolved request origin or "default"
732
+ */
733
+ createKey?: (config: RequestConfig) => string;
734
+ /**
735
+ * Decide whether a final request failure affects the circuit.
736
+ *
737
+ * @default network errors, timeouts, HTTP 429, and HTTP 5xx
738
+ */
739
+ shouldCountFailure?: (error: unknown, config: RequestConfig) => boolean | Promise<boolean>;
740
+ /**
741
+ * Observe circuit state changes. Observer failures are isolated.
742
+ */
743
+ onStateChange?: (event: Readonly<CircuitBreakerStateChange>) => void | Promise<void>;
744
+ }
745
+ interface CircuitBreakerPlugin extends Plugin {
746
+ getState(key: string): CircuitState;
747
+ reset(key?: string): void;
748
+ }
749
+ declare function circuitBreakerPlugin(options?: CircuitBreakerPluginOptions): CircuitBreakerPlugin;
750
+
657
751
  type DownloadTransport = 'auto' | 'fetch' | 'xhr';
658
752
  interface DownloadPluginOptions {
659
753
  /**
@@ -674,4 +768,4 @@ declare function retryPlugin(defaultOptions?: RetryOptions): Plugin;
674
768
 
675
769
  declare function uploadPlugin(): Plugin;
676
770
 
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 };
771
+ 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, type MemoryCacheStoreOptions, 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.
@@ -616,8 +637,19 @@ interface CacheStore {
616
637
  delete(key: string): MaybePromise<void>;
617
638
  clear(): MaybePromise<void>;
618
639
  }
640
+ interface MemoryCacheStoreOptions {
641
+ /**
642
+ * Maximum entries retained by the in-memory LRU store.
643
+ * Use `Infinity` for no practical limit.
644
+ *
645
+ * @default 1000
646
+ */
647
+ maxEntries?: number;
648
+ }
619
649
  declare class MemoryCacheStore implements CacheStore {
620
650
  private readonly entries;
651
+ private readonly maxEntries;
652
+ constructor(options?: MemoryCacheStoreOptions);
621
653
  get(key: string): CacheEntry | undefined;
622
654
  set(key: string, entry: CacheEntry): void;
623
655
  delete(key: string): void;
@@ -642,6 +674,13 @@ interface CachePluginOptions {
642
674
  * @default an isolated MemoryCacheStore
643
675
  */
644
676
  store?: CacheStore;
677
+ /**
678
+ * Maximum entries retained by the default MemoryCacheStore.
679
+ * Ignored when `store` is provided.
680
+ *
681
+ * @default 1000
682
+ */
683
+ maxEntries?: number;
645
684
  /**
646
685
  * Share one network operation between concurrent equivalent requests.
647
686
  *
@@ -654,6 +693,61 @@ interface CachePlugin extends Plugin {
654
693
  }
655
694
  declare function cachePlugin(options?: CachePluginOptions): CachePlugin;
656
695
 
696
+ interface CircuitBreakerPluginOptions {
697
+ /**
698
+ * Consecutive counted failures required to open a closed circuit.
699
+ *
700
+ * @default 5
701
+ */
702
+ failureThreshold?: number;
703
+ /**
704
+ * Successful probes required to close a half-open circuit.
705
+ *
706
+ * @default 1
707
+ */
708
+ successThreshold?: number;
709
+ /**
710
+ * Time in milliseconds before an open circuit permits probes.
711
+ *
712
+ * @default 30000
713
+ */
714
+ resetTimeout?: number;
715
+ /**
716
+ * Maximum concurrent probes admitted while a circuit is half-open.
717
+ *
718
+ * @default 1
719
+ */
720
+ halfOpenMaxRequests?: number;
721
+ /**
722
+ * Maximum inactive isolation states retained by this plugin instance.
723
+ * Active requests are never evicted and may temporarily exceed the limit.
724
+ *
725
+ * @default 1000
726
+ */
727
+ maxCircuits?: number;
728
+ /**
729
+ * Create the default isolation key for a request.
730
+ *
731
+ * @default the resolved request origin or "default"
732
+ */
733
+ createKey?: (config: RequestConfig) => string;
734
+ /**
735
+ * Decide whether a final request failure affects the circuit.
736
+ *
737
+ * @default network errors, timeouts, HTTP 429, and HTTP 5xx
738
+ */
739
+ shouldCountFailure?: (error: unknown, config: RequestConfig) => boolean | Promise<boolean>;
740
+ /**
741
+ * Observe circuit state changes. Observer failures are isolated.
742
+ */
743
+ onStateChange?: (event: Readonly<CircuitBreakerStateChange>) => void | Promise<void>;
744
+ }
745
+ interface CircuitBreakerPlugin extends Plugin {
746
+ getState(key: string): CircuitState;
747
+ reset(key?: string): void;
748
+ }
749
+ declare function circuitBreakerPlugin(options?: CircuitBreakerPluginOptions): CircuitBreakerPlugin;
750
+
657
751
  type DownloadTransport = 'auto' | 'fetch' | 'xhr';
658
752
  interface DownloadPluginOptions {
659
753
  /**
@@ -674,4 +768,4 @@ declare function retryPlugin(defaultOptions?: RetryOptions): Plugin;
674
768
 
675
769
  declare function uploadPlugin(): Plugin;
676
770
 
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 };
771
+ 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, type MemoryCacheStoreOptions, 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
@@ -1829,13 +1829,35 @@ function defaultShouldRefresh(error) {
1829
1829
 
1830
1830
  // src/plugins/cachePlugin.ts
1831
1831
  var MemoryCacheStore = class {
1832
- constructor() {
1832
+ constructor(options = {}) {
1833
1833
  this.entries = /* @__PURE__ */ new Map();
1834
+ this.maxEntries = normalizeMaxEntries(options.maxEntries);
1834
1835
  }
1835
1836
  get(key) {
1836
- return this.entries.get(key);
1837
+ const entry = this.entries.get(key);
1838
+ if (!entry) {
1839
+ return void 0;
1840
+ }
1841
+ if (!Number.isFinite(entry.expiresAt) || Date.now() > entry.expiresAt) {
1842
+ this.entries.delete(key);
1843
+ return void 0;
1844
+ }
1845
+ this.entries.delete(key);
1846
+ this.entries.set(key, entry);
1847
+ return entry;
1837
1848
  }
1838
1849
  set(key, entry) {
1850
+ if (this.maxEntries === 0) {
1851
+ return;
1852
+ }
1853
+ this.entries.delete(key);
1854
+ while (this.entries.size >= this.maxEntries) {
1855
+ const oldestKey = this.entries.keys().next().value;
1856
+ if (oldestKey === void 0) {
1857
+ break;
1858
+ }
1859
+ this.entries.delete(oldestKey);
1860
+ }
1839
1861
  this.entries.set(key, entry);
1840
1862
  }
1841
1863
  delete(key) {
@@ -1856,7 +1878,9 @@ var DEFAULT_VARY_HEADERS = [
1856
1878
  "accept-language"
1857
1879
  ];
1858
1880
  function cachePlugin(options = {}) {
1859
- const store = options.store ?? new MemoryCacheStore();
1881
+ const store = options.store ?? new MemoryCacheStore({
1882
+ maxEntries: options.maxEntries
1883
+ });
1860
1884
  const cacheHits = /* @__PURE__ */ new WeakSet();
1861
1885
  const leaders = /* @__PURE__ */ new WeakMap();
1862
1886
  const completedRecords = /* @__PURE__ */ new WeakMap();
@@ -2196,6 +2220,275 @@ function cloneCacheValue(value) {
2196
2220
  return value;
2197
2221
  }
2198
2222
  }
2223
+ function normalizeMaxEntries(value) {
2224
+ if (value === void 0) {
2225
+ return 1e3;
2226
+ }
2227
+ if (!Number.isFinite(value)) {
2228
+ return value > 0 ? Number.POSITIVE_INFINITY : 0;
2229
+ }
2230
+ return Math.max(0, Math.floor(value));
2231
+ }
2232
+
2233
+ // src/plugins/circuitBreakerPlugin.ts
2234
+ function circuitBreakerPlugin(options = {}) {
2235
+ const normalized = normalizeOptions(options);
2236
+ const circuits = /* @__PURE__ */ new Map();
2237
+ const plugin = {
2238
+ name: "circuit-breaker",
2239
+ getState(key) {
2240
+ return circuits.get(key)?.state ?? "closed";
2241
+ },
2242
+ reset(key) {
2243
+ if (key === void 0) {
2244
+ circuits.clear();
2245
+ return;
2246
+ }
2247
+ circuits.delete(key);
2248
+ },
2249
+ install(context) {
2250
+ const admissions = /* @__PURE__ */ new WeakMap();
2251
+ let active = true;
2252
+ context.hooks.onRequest((requestContext) => {
2253
+ const requestOptions = resolveExtensionConfig(
2254
+ requestContext.config,
2255
+ "circuitBreaker"
2256
+ );
2257
+ if (requestOptions?.enabled === false) {
2258
+ return;
2259
+ }
2260
+ const key = normalizeKey(
2261
+ requestOptions?.key ?? normalized.createKey(requestContext.config)
2262
+ );
2263
+ const record = getCircuit(
2264
+ circuits,
2265
+ key,
2266
+ normalized.maxCircuits
2267
+ );
2268
+ if (record.state === "open" && Date.now() - record.openedAt >= normalized.resetTimeout) {
2269
+ transition(record, key, "half-open", normalized);
2270
+ }
2271
+ if (record.state === "open") {
2272
+ throw createOpenError(key, requestContext.config);
2273
+ }
2274
+ const probe = record.state === "half-open";
2275
+ if (probe && record.probes >= normalized.halfOpenMaxRequests) {
2276
+ throw createOpenError(key, requestContext.config);
2277
+ }
2278
+ if (probe) {
2279
+ record.probes += 1;
2280
+ }
2281
+ record.activeRequests += 1;
2282
+ admissions.set(requestContext, {
2283
+ key,
2284
+ generation: record.generation,
2285
+ probe,
2286
+ record
2287
+ });
2288
+ });
2289
+ context.hooks.onSettled(async (requestContext) => {
2290
+ const admission = admissions.get(requestContext);
2291
+ if (!admission) {
2292
+ return;
2293
+ }
2294
+ admissions.delete(requestContext);
2295
+ const record = admission.record;
2296
+ if (!active) {
2297
+ record.activeRequests = Math.max(0, record.activeRequests - 1);
2298
+ return;
2299
+ }
2300
+ try {
2301
+ if (circuits.get(admission.key) !== record || record.generation !== admission.generation) {
2302
+ return;
2303
+ }
2304
+ if (admission.probe) {
2305
+ record.probes = Math.max(0, record.probes - 1);
2306
+ }
2307
+ if (!requestContext.error && requestContext.response) {
2308
+ record.failures = 0;
2309
+ if (admission.probe && record.state === "half-open") {
2310
+ record.successes += 1;
2311
+ if (record.successes >= normalized.successThreshold) {
2312
+ transition(record, admission.key, "closed", normalized);
2313
+ }
2314
+ }
2315
+ return;
2316
+ }
2317
+ const counted = await normalized.shouldCountFailure(
2318
+ requestContext.error,
2319
+ requestContext.config
2320
+ );
2321
+ if (!active || circuits.get(admission.key) !== record || record.generation !== admission.generation || !counted) {
2322
+ return;
2323
+ }
2324
+ if (admission.probe && record.state === "half-open") {
2325
+ transition(record, admission.key, "open", normalized);
2326
+ return;
2327
+ }
2328
+ if (record.state === "closed") {
2329
+ record.failures += 1;
2330
+ if (record.failures >= normalized.failureThreshold) {
2331
+ transition(record, admission.key, "open", normalized);
2332
+ }
2333
+ }
2334
+ } finally {
2335
+ record.activeRequests = Math.max(0, record.activeRequests - 1);
2336
+ trimCircuits(circuits, normalized.maxCircuits);
2337
+ }
2338
+ });
2339
+ return () => {
2340
+ active = false;
2341
+ circuits.clear();
2342
+ };
2343
+ }
2344
+ };
2345
+ return plugin;
2346
+ }
2347
+ function normalizeOptions(options) {
2348
+ return {
2349
+ failureThreshold: normalizePositiveInteger(
2350
+ options.failureThreshold,
2351
+ 5
2352
+ ),
2353
+ successThreshold: normalizePositiveInteger(
2354
+ options.successThreshold,
2355
+ 1
2356
+ ),
2357
+ resetTimeout: normalizeDuration(options.resetTimeout, 3e4),
2358
+ halfOpenMaxRequests: normalizePositiveInteger(
2359
+ options.halfOpenMaxRequests,
2360
+ 1
2361
+ ),
2362
+ maxCircuits: normalizePositiveInteger(options.maxCircuits, 1e3),
2363
+ createKey: options.createKey ?? createDefaultKey,
2364
+ shouldCountFailure: options.shouldCountFailure ?? defaultShouldCountFailure,
2365
+ onStateChange: options.onStateChange
2366
+ };
2367
+ }
2368
+ function normalizePositiveInteger(value, fallback) {
2369
+ if (value === void 0) {
2370
+ return fallback;
2371
+ }
2372
+ if (!Number.isFinite(value)) {
2373
+ return fallback;
2374
+ }
2375
+ return Math.max(1, Math.floor(value));
2376
+ }
2377
+ function normalizeDuration(value, fallback) {
2378
+ if (value === void 0) {
2379
+ return fallback;
2380
+ }
2381
+ if (!Number.isFinite(value)) {
2382
+ return value > 0 ? Number.MAX_SAFE_INTEGER : 0;
2383
+ }
2384
+ return Math.max(0, value);
2385
+ }
2386
+ function normalizeKey(key) {
2387
+ return key || "default";
2388
+ }
2389
+ function createDefaultKey(config) {
2390
+ try {
2391
+ return new URL(config.url).origin;
2392
+ } catch {
2393
+ }
2394
+ try {
2395
+ if (config.baseURL) {
2396
+ return new URL(config.url, config.baseURL).origin;
2397
+ }
2398
+ } catch {
2399
+ }
2400
+ return "default";
2401
+ }
2402
+ function getCircuit(circuits, key, maxCircuits) {
2403
+ let record = circuits.get(key);
2404
+ if (record) {
2405
+ circuits.delete(key);
2406
+ circuits.set(key, record);
2407
+ return record;
2408
+ }
2409
+ trimCircuits(circuits, maxCircuits - 1);
2410
+ record = {
2411
+ state: "closed",
2412
+ failures: 0,
2413
+ successes: 0,
2414
+ openedAt: 0,
2415
+ probes: 0,
2416
+ generation: 0,
2417
+ activeRequests: 0
2418
+ };
2419
+ circuits.set(key, record);
2420
+ return record;
2421
+ }
2422
+ function trimCircuits(circuits, maxCircuits) {
2423
+ while (circuits.size > maxCircuits) {
2424
+ let removableKey;
2425
+ for (const [key, record] of circuits) {
2426
+ if (record.activeRequests === 0) {
2427
+ removableKey = key;
2428
+ break;
2429
+ }
2430
+ }
2431
+ if (removableKey === void 0) {
2432
+ return;
2433
+ }
2434
+ circuits.delete(removableKey);
2435
+ }
2436
+ }
2437
+ function transition(record, key, state, options) {
2438
+ if (record.state === state) {
2439
+ if (state === "open") {
2440
+ record.openedAt = Date.now();
2441
+ record.successes = 0;
2442
+ record.probes = 0;
2443
+ record.generation += 1;
2444
+ }
2445
+ return;
2446
+ }
2447
+ const previousState = record.state;
2448
+ record.state = state;
2449
+ record.successes = 0;
2450
+ record.probes = 0;
2451
+ record.generation += 1;
2452
+ if (state === "open") {
2453
+ record.openedAt = Date.now();
2454
+ } else if (state === "closed") {
2455
+ record.failures = 0;
2456
+ record.openedAt = 0;
2457
+ }
2458
+ notifyStateChange(options.onStateChange, {
2459
+ key,
2460
+ previousState,
2461
+ state,
2462
+ timestamp: Date.now(),
2463
+ failures: record.failures
2464
+ });
2465
+ }
2466
+ function notifyStateChange(observer, event) {
2467
+ if (!observer) {
2468
+ return;
2469
+ }
2470
+ try {
2471
+ void Promise.resolve(observer(event)).catch(ignoreObserverError);
2472
+ } catch {
2473
+ }
2474
+ }
2475
+ function ignoreObserverError() {
2476
+ }
2477
+ function createOpenError(key, config) {
2478
+ return new RequestError(`Circuit is open for ${key}`, {
2479
+ code: "CIRCUIT_OPEN",
2480
+ config
2481
+ });
2482
+ }
2483
+ function defaultShouldCountFailure(error) {
2484
+ if (!(error instanceof RequestError)) {
2485
+ return true;
2486
+ }
2487
+ if (error.code === "NETWORK_ERROR" || error.code === "TIMEOUT_ERROR") {
2488
+ return true;
2489
+ }
2490
+ return error.code === "HTTP_ERROR" && (error.status === 429 || error.status !== void 0 && error.status >= 500);
2491
+ }
2199
2492
 
2200
2493
  // src/plugins/xhrTransport.ts
2201
2494
  function xhrRequest(config, options = {}) {
@@ -3125,6 +3418,7 @@ export {
3125
3418
  RequestError,
3126
3419
  authPlugin,
3127
3420
  cachePlugin,
3421
+ circuitBreakerPlugin,
3128
3422
  createClient,
3129
3423
  downloadPlugin,
3130
3424
  loggerPlugin,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@npora/request",
3
- "version": "1.4.0",
3
+ "version": "1.6.0",
4
4
  "description": "A modern, TypeScript-first HTTP client powered by the Fetch API.",
5
5
  "keywords": [
6
6
  "npora",