@metamask-previews/controller-utils 11.4.5-preview-e05b7d3e → 11.4.5-preview-6244b7be

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/CHANGELOG.md CHANGED
@@ -9,7 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
9
9
 
10
10
  ### Added
11
11
 
12
- - Add `createServicePolicy` function to assist with reducing boilerplate for service classes ([#5053](https://github.com/MetaMask/core/pull/5053))
12
+ - Add `createServicePolicy` function to assist with reducing boilerplate for service classes ([#5154](https://github.com/MetaMask/core/pull/5154), [#5143](https://github.com/MetaMask/core/pull/5143))
13
13
 
14
14
  ## [11.4.5]
15
15
 
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createServicePolicy = exports.DEFAULT_CIRCUIT_BREAK_DURATION = exports.DEFAULT_MAX_CONSECUTIVE_FAILURES = exports.DEFAULT_MAX_RETRIES = void 0;
3
+ exports.createServicePolicy = exports.DEFAULT_DEGRADED_THRESHOLD = exports.DEFAULT_CIRCUIT_BREAK_DURATION = exports.DEFAULT_MAX_CONSECUTIVE_FAILURES = exports.DEFAULT_MAX_RETRIES = void 0;
4
4
  const cockatiel_1 = require("cockatiel");
5
5
  /**
6
6
  * The maximum number of times that a failing service should be re-run before
@@ -17,6 +17,11 @@ exports.DEFAULT_MAX_CONSECUTIVE_FAILURES = (1 + exports.DEFAULT_MAX_RETRIES) * 3
17
17
  * the service after enough consecutive failures.
18
18
  */
19
19
  exports.DEFAULT_CIRCUIT_BREAK_DURATION = 30 * 60 * 1000;
20
+ /**
21
+ * The default length of time (in milliseconds) that governs when the service is
22
+ * regarded as degraded (affecting when `onDegraded` is called).
23
+ */
24
+ exports.DEFAULT_DEGRADED_THRESHOLD = 5000;
20
25
  /**
21
26
  * Constructs an object exposing an `execute` method which, given a function —
22
27
  * hereafter called the "service" — will retry that service with ever increasing
@@ -35,8 +40,17 @@ exports.DEFAULT_CIRCUIT_BREAK_DURATION = 30 * 60 * 1000;
35
40
  * @param options - The options to this function.
36
41
  * @param options.maxConsecutiveFailures - The maximum number of times that the
37
42
  * service is allowed to fail before pausing further retries. Defaults to 12.
43
+ * @param options.circuitBreakDuration - The length of time (in milliseconds) to
44
+ * pause retries of the action after the number of failures reaches
45
+ * `maxConsecutiveFailures`.
46
+ * @param options.degradedThreshold - The length of time (in milliseconds) that
47
+ * governs when the service is regarded as degraded (affecting when `onDegraded`
48
+ * is called). Defaults to 5 seconds.
38
49
  * @param options.onBreak - A function which is called when the service fails
39
50
  * too many times in a row (specifically, more than `maxConsecutiveFailures`).
51
+ * @param options.onDegraded - A function which is called when the service
52
+ * succeeds before `maxConsecutiveFailures` is reached, but takes more time than
53
+ * the `degradedThreshold` to run.
40
54
  * @param options.onRetry - A function which will be called the moment the
41
55
  * policy kicks off a timer to re-run the function passed to the policy. This is
42
56
  * primarily useful in tests where we are mocking timers.
@@ -49,9 +63,14 @@ exports.DEFAULT_CIRCUIT_BREAK_DURATION = 30 * 60 * 1000;
49
63
  * constructor() {
50
64
  * this.#policy = createServicePolicy({
51
65
  * maxConsecutiveFailures: 3,
66
+ * circuitBreakDuration: 5000,
67
+ * degradedThreshold: 2000,
52
68
  * onBreak: () => {
53
69
  * console.log('Circuit broke');
54
70
  * },
71
+ * onDegraded: () => {
72
+ * console.log('Service is degraded');
73
+ * },
55
74
  * });
56
75
  * }
57
76
  *
@@ -64,7 +83,9 @@ exports.DEFAULT_CIRCUIT_BREAK_DURATION = 30 * 60 * 1000;
64
83
  * }
65
84
  * ```
66
85
  */
67
- function createServicePolicy({ maxConsecutiveFailures = exports.DEFAULT_MAX_CONSECUTIVE_FAILURES, onBreak = () => {
86
+ function createServicePolicy({ maxConsecutiveFailures = exports.DEFAULT_MAX_CONSECUTIVE_FAILURES, circuitBreakDuration = exports.DEFAULT_CIRCUIT_BREAK_DURATION, degradedThreshold = exports.DEFAULT_DEGRADED_THRESHOLD, onBreak = () => {
87
+ // do nothing
88
+ }, onDegraded = () => {
68
89
  // do nothing
69
90
  }, onRetry = () => {
70
91
  // do nothing
@@ -81,10 +102,10 @@ function createServicePolicy({ maxConsecutiveFailures = exports.DEFAULT_MAX_CONS
81
102
  // While the circuit is open, any additional invocations of the service
82
103
  // passed to the policy (either via automatic retries or by manually
83
104
  // executing the policy again) will result in a BrokenCircuitError. This
84
- // will remain the case until the default circuit break duration passes,
85
- // after which the service will be allowed to run again. If the service
86
- // succeeds, the circuit will close, otherwise it will remain open.
87
- halfOpenAfter: exports.DEFAULT_CIRCUIT_BREAK_DURATION,
105
+ // will remain the case until `circuitBreakDuration` passes, after which the
106
+ // service will be allowed to run again. If the service succeeds, the
107
+ // circuit will close, otherwise it will remain open.
108
+ halfOpenAfter: circuitBreakDuration,
88
109
  breaker: new cockatiel_1.ConsecutiveBreaker(maxConsecutiveFailures),
89
110
  });
90
111
  // The `onBreak` callback will be called if the service consistently throws
@@ -99,6 +120,23 @@ function createServicePolicy({ maxConsecutiveFailures = exports.DEFAULT_MAX_CONS
99
120
  // The `onRetryPolicy` callback will be called each time the service is
100
121
  // invoked (including retries).
101
122
  retryPolicy.onRetry(onRetry);
123
+ retryPolicy.onGiveUp(() => {
124
+ if (circuitBreakerPolicy.state === cockatiel_1.CircuitState.Closed) {
125
+ // The `onDegraded` callback will be called if the number of retries is
126
+ // exceeded and the maximum number of consecutive failures has not been
127
+ // reached yet (whether the policy is called once or multiple times).
128
+ onDegraded();
129
+ }
130
+ });
131
+ retryPolicy.onSuccess(({ duration }) => {
132
+ if (circuitBreakerPolicy.state === cockatiel_1.CircuitState.Closed &&
133
+ duration > degradedThreshold) {
134
+ // The `onDegraded` callback will also be called if the service does not
135
+ // throw, but the time it takes for the service to run exceeds the
136
+ // `degradedThreshold`.
137
+ onDegraded();
138
+ }
139
+ });
102
140
  // The retry policy really retries the circuit breaker policy, which invokes
103
141
  // the service.
104
142
  return (0, cockatiel_1.wrap)(retryPolicy, circuitBreakerPolicy);
@@ -1 +1 @@
1
- {"version":3,"file":"create-service-policy.cjs","sourceRoot":"","sources":["../src/create-service-policy.ts"],"names":[],"mappings":";;;AAAA,yCAOmB;AAKnB;;;GAGG;AACU,QAAA,mBAAmB,GAAG,CAAC,CAAC;AAErC;;;GAGG;AACU,QAAA,gCAAgC,GAAG,CAAC,CAAC,GAAG,2BAAmB,CAAC,GAAG,CAAC,CAAC;AAE9E;;;GAGG;AACU,QAAA,8BAA8B,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAE7D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8CG;AACH,SAAgB,mBAAmB,CAAC,EAClC,sBAAsB,GAAG,wCAAgC,EACzD,OAAO,GAAG,GAAG,EAAE;IACb,aAAa;AACf,CAAC,EACD,OAAO,GAAG,GAAG,EAAE;IACb,aAAa;AACf,CAAC,MAKC,EAAE;IACJ,MAAM,WAAW,GAAG,IAAA,iBAAK,EAAC,qBAAS,EAAE;QACnC,2EAA2E;QAC3E,mEAAmE;QACnE,WAAW,EAAE,2BAAmB;QAChC,4EAA4E;QAC5E,mCAAmC;QACnC,OAAO,EAAE,IAAI,8BAAkB,EAAE;KAClC,CAAC,CAAC;IAEH,MAAM,oBAAoB,GAAG,IAAA,0BAAc,EAAC,qBAAS,EAAE;QACrD,uEAAuE;QACvE,oEAAoE;QACpE,wEAAwE;QACxE,wEAAwE;QACxE,uEAAuE;QACvE,mEAAmE;QACnE,aAAa,EAAE,sCAA8B;QAC7C,OAAO,EAAE,IAAI,8BAAkB,CAAC,sBAAsB,CAAC;KACxD,CAAC,CAAC;IAEH,2EAA2E;IAC3E,2EAA2E;IAC3E,sDAAsD;IACtD,6EAA6E;IAC7E,gBAAgB;IAChB,8EAA8E;IAC9E,8EAA8E;IAC9E,6BAA6B;IAC7B,oBAAoB,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;IAEtC,uEAAuE;IACvE,+BAA+B;IAC/B,WAAW,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;IAE7B,4EAA4E;IAC5E,eAAe;IACf,OAAO,IAAA,gBAAI,EAAC,WAAW,EAAE,oBAAoB,CAAC,CAAC;AACjD,CAAC;AAlDD,kDAkDC","sourcesContent":["import {\n circuitBreaker,\n ConsecutiveBreaker,\n ExponentialBackoff,\n handleAll,\n retry,\n wrap,\n} from 'cockatiel';\nimport type { IPolicy } from 'cockatiel';\n\nexport type { IPolicy as IServicePolicy };\n\n/**\n * The maximum number of times that a failing service should be re-run before\n * giving up.\n */\nexport const DEFAULT_MAX_RETRIES = 3;\n\n/**\n * The maximum number of times that the service is allowed to fail before\n * pausing further retries.\n */\nexport const DEFAULT_MAX_CONSECUTIVE_FAILURES = (1 + DEFAULT_MAX_RETRIES) * 3;\n\n/**\n * The default length of time (in milliseconds) to temporarily pause retries of\n * the service after enough consecutive failures.\n */\nexport const DEFAULT_CIRCUIT_BREAK_DURATION = 30 * 60 * 1000;\n\n/**\n * Constructs an object exposing an `execute` method which, given a function —\n * hereafter called the \"service\" — will retry that service with ever increasing\n * delays until it succeeds. If the policy detects too many consecutive\n * failures, it will block further retries until a designated time period has\n * passed; this particular behavior is primarily designed for services that wrap\n * API calls so as not to make needless HTTP requests when the API is down and\n * to be able to recover when the API comes back up. In addition, hooks allow\n * for responding to certain events, one of which can be used to detect when an\n * HTTP request is performing slowly.\n *\n * Internally, this function makes use of the retry and circuit breaker policies\n * from the [Cockatiel](https://www.npmjs.com/package/cockatiel) library; see\n * there for more.\n *\n * @param options - The options to this function.\n * @param options.maxConsecutiveFailures - The maximum number of times that the\n * service is allowed to fail before pausing further retries. Defaults to 12.\n * @param options.onBreak - A function which is called when the service fails\n * too many times in a row (specifically, more than `maxConsecutiveFailures`).\n * @param options.onRetry - A function which will be called the moment the\n * policy kicks off a timer to re-run the function passed to the policy. This is\n * primarily useful in tests where we are mocking timers.\n * @returns The service policy.\n * @example\n * This function is designed to be used in the context of a service class like\n * this:\n * ``` ts\n * class Service {\n * constructor() {\n * this.#policy = createServicePolicy({\n * maxConsecutiveFailures: 3,\n * onBreak: () => {\n * console.log('Circuit broke');\n * },\n * });\n * }\n *\n * async fetch() {\n * return await this.#policy.execute(async () => {\n * const response = await fetch('https://some/url');\n * return await response.json();\n * });\n * }\n * }\n * ```\n */\nexport function createServicePolicy({\n maxConsecutiveFailures = DEFAULT_MAX_CONSECUTIVE_FAILURES,\n onBreak = () => {\n // do nothing\n },\n onRetry = () => {\n // do nothing\n },\n}: {\n maxConsecutiveFailures?: number;\n onBreak?: () => void;\n onRetry?: () => void;\n} = {}): IPolicy {\n const retryPolicy = retry(handleAll, {\n // Note that although the option here is called \"max attempts\", it's really\n // maximum number of *retries* (attempts past the initial attempt).\n maxAttempts: DEFAULT_MAX_RETRIES,\n // Retries of the service will be executed following ever increasing delays,\n // determined by a backoff formula.\n backoff: new ExponentialBackoff(),\n });\n\n const circuitBreakerPolicy = circuitBreaker(handleAll, {\n // While the circuit is open, any additional invocations of the service\n // passed to the policy (either via automatic retries or by manually\n // executing the policy again) will result in a BrokenCircuitError. This\n // will remain the case until the default circuit break duration passes,\n // after which the service will be allowed to run again. If the service\n // succeeds, the circuit will close, otherwise it will remain open.\n halfOpenAfter: DEFAULT_CIRCUIT_BREAK_DURATION,\n breaker: new ConsecutiveBreaker(maxConsecutiveFailures),\n });\n\n // The `onBreak` callback will be called if the service consistently throws\n // for as many times as exceeds the maximum consecutive number of failures.\n // Combined with the retry policy, this can happen if:\n // - `maxConsecutiveFailures` < the default max retries (3) and the policy is\n // executed once\n // - `maxConsecutiveFailures` >= the default max retries (3) but the policy is\n // executed multiple times, enough for the total number of retries to exceed\n // `maxConsecutiveFailures`\n circuitBreakerPolicy.onBreak(onBreak);\n\n // The `onRetryPolicy` callback will be called each time the service is\n // invoked (including retries).\n retryPolicy.onRetry(onRetry);\n\n // The retry policy really retries the circuit breaker policy, which invokes\n // the service.\n return wrap(retryPolicy, circuitBreakerPolicy);\n}\n"]}
1
+ {"version":3,"file":"create-service-policy.cjs","sourceRoot":"","sources":["../src/create-service-policy.ts"],"names":[],"mappings":";;;AAAA,yCAQmB;AAKnB;;;GAGG;AACU,QAAA,mBAAmB,GAAG,CAAC,CAAC;AAErC;;;GAGG;AACU,QAAA,gCAAgC,GAAG,CAAC,CAAC,GAAG,2BAAmB,CAAC,GAAG,CAAC,CAAC;AAE9E;;;GAGG;AACU,QAAA,8BAA8B,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAE7D;;;GAGG;AACU,QAAA,0BAA0B,GAAG,IAAK,CAAC;AAEhD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4DG;AACH,SAAgB,mBAAmB,CAAC,EAClC,sBAAsB,GAAG,wCAAgC,EACzD,oBAAoB,GAAG,sCAA8B,EACrD,iBAAiB,GAAG,kCAA0B,EAC9C,OAAO,GAAG,GAAG,EAAE;IACb,aAAa;AACf,CAAC,EACD,UAAU,GAAG,GAAG,EAAE;IAChB,aAAa;AACf,CAAC,EACD,OAAO,GAAG,GAAG,EAAE;IACb,aAAa;AACf,CAAC,MAQC,EAAE;IACJ,MAAM,WAAW,GAAG,IAAA,iBAAK,EAAC,qBAAS,EAAE;QACnC,2EAA2E;QAC3E,mEAAmE;QACnE,WAAW,EAAE,2BAAmB;QAChC,4EAA4E;QAC5E,mCAAmC;QACnC,OAAO,EAAE,IAAI,8BAAkB,EAAE;KAClC,CAAC,CAAC;IAEH,MAAM,oBAAoB,GAAG,IAAA,0BAAc,EAAC,qBAAS,EAAE;QACrD,uEAAuE;QACvE,oEAAoE;QACpE,wEAAwE;QACxE,4EAA4E;QAC5E,qEAAqE;QACrE,qDAAqD;QACrD,aAAa,EAAE,oBAAoB;QACnC,OAAO,EAAE,IAAI,8BAAkB,CAAC,sBAAsB,CAAC;KACxD,CAAC,CAAC;IAEH,2EAA2E;IAC3E,2EAA2E;IAC3E,sDAAsD;IACtD,6EAA6E;IAC7E,gBAAgB;IAChB,8EAA8E;IAC9E,8EAA8E;IAC9E,6BAA6B;IAC7B,oBAAoB,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;IAEtC,uEAAuE;IACvE,+BAA+B;IAC/B,WAAW,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;IAE7B,WAAW,CAAC,QAAQ,CAAC,GAAG,EAAE;QACxB,IAAI,oBAAoB,CAAC,KAAK,KAAK,wBAAY,CAAC,MAAM,EAAE;YACtD,uEAAuE;YACvE,uEAAuE;YACvE,qEAAqE;YACrE,UAAU,EAAE,CAAC;SACd;IACH,CAAC,CAAC,CAAC;IACH,WAAW,CAAC,SAAS,CAAC,CAAC,EAAE,QAAQ,EAAE,EAAE,EAAE;QACrC,IACE,oBAAoB,CAAC,KAAK,KAAK,wBAAY,CAAC,MAAM;YAClD,QAAQ,GAAG,iBAAiB,EAC5B;YACA,wEAAwE;YACxE,kEAAkE;YAClE,uBAAuB;YACvB,UAAU,EAAE,CAAC;SACd;IACH,CAAC,CAAC,CAAC;IAEH,4EAA4E;IAC5E,eAAe;IACf,OAAO,IAAA,gBAAI,EAAC,WAAW,EAAE,oBAAoB,CAAC,CAAC;AACjD,CAAC;AA9ED,kDA8EC","sourcesContent":["import {\n circuitBreaker,\n ConsecutiveBreaker,\n ExponentialBackoff,\n handleAll,\n retry,\n wrap,\n CircuitState,\n} from 'cockatiel';\nimport type { IPolicy } from 'cockatiel';\n\nexport type { IPolicy as IServicePolicy };\n\n/**\n * The maximum number of times that a failing service should be re-run before\n * giving up.\n */\nexport const DEFAULT_MAX_RETRIES = 3;\n\n/**\n * The maximum number of times that the service is allowed to fail before\n * pausing further retries.\n */\nexport const DEFAULT_MAX_CONSECUTIVE_FAILURES = (1 + DEFAULT_MAX_RETRIES) * 3;\n\n/**\n * The default length of time (in milliseconds) to temporarily pause retries of\n * the service after enough consecutive failures.\n */\nexport const DEFAULT_CIRCUIT_BREAK_DURATION = 30 * 60 * 1000;\n\n/**\n * The default length of time (in milliseconds) that governs when the service is\n * regarded as degraded (affecting when `onDegraded` is called).\n */\nexport const DEFAULT_DEGRADED_THRESHOLD = 5_000;\n\n/**\n * Constructs an object exposing an `execute` method which, given a function —\n * hereafter called the \"service\" — will retry that service with ever increasing\n * delays until it succeeds. If the policy detects too many consecutive\n * failures, it will block further retries until a designated time period has\n * passed; this particular behavior is primarily designed for services that wrap\n * API calls so as not to make needless HTTP requests when the API is down and\n * to be able to recover when the API comes back up. In addition, hooks allow\n * for responding to certain events, one of which can be used to detect when an\n * HTTP request is performing slowly.\n *\n * Internally, this function makes use of the retry and circuit breaker policies\n * from the [Cockatiel](https://www.npmjs.com/package/cockatiel) library; see\n * there for more.\n *\n * @param options - The options to this function.\n * @param options.maxConsecutiveFailures - The maximum number of times that the\n * service is allowed to fail before pausing further retries. Defaults to 12.\n * @param options.circuitBreakDuration - The length of time (in milliseconds) to\n * pause retries of the action after the number of failures reaches\n * `maxConsecutiveFailures`.\n * @param options.degradedThreshold - The length of time (in milliseconds) that\n * governs when the service is regarded as degraded (affecting when `onDegraded`\n * is called). Defaults to 5 seconds.\n * @param options.onBreak - A function which is called when the service fails\n * too many times in a row (specifically, more than `maxConsecutiveFailures`).\n * @param options.onDegraded - A function which is called when the service\n * succeeds before `maxConsecutiveFailures` is reached, but takes more time than\n * the `degradedThreshold` to run.\n * @param options.onRetry - A function which will be called the moment the\n * policy kicks off a timer to re-run the function passed to the policy. This is\n * primarily useful in tests where we are mocking timers.\n * @returns The service policy.\n * @example\n * This function is designed to be used in the context of a service class like\n * this:\n * ``` ts\n * class Service {\n * constructor() {\n * this.#policy = createServicePolicy({\n * maxConsecutiveFailures: 3,\n * circuitBreakDuration: 5000,\n * degradedThreshold: 2000,\n * onBreak: () => {\n * console.log('Circuit broke');\n * },\n * onDegraded: () => {\n * console.log('Service is degraded');\n * },\n * });\n * }\n *\n * async fetch() {\n * return await this.#policy.execute(async () => {\n * const response = await fetch('https://some/url');\n * return await response.json();\n * });\n * }\n * }\n * ```\n */\nexport function createServicePolicy({\n maxConsecutiveFailures = DEFAULT_MAX_CONSECUTIVE_FAILURES,\n circuitBreakDuration = DEFAULT_CIRCUIT_BREAK_DURATION,\n degradedThreshold = DEFAULT_DEGRADED_THRESHOLD,\n onBreak = () => {\n // do nothing\n },\n onDegraded = () => {\n // do nothing\n },\n onRetry = () => {\n // do nothing\n },\n}: {\n maxConsecutiveFailures?: number;\n circuitBreakDuration?: number;\n degradedThreshold?: number;\n onBreak?: () => void;\n onDegraded?: () => void;\n onRetry?: () => void;\n} = {}): IPolicy {\n const retryPolicy = retry(handleAll, {\n // Note that although the option here is called \"max attempts\", it's really\n // maximum number of *retries* (attempts past the initial attempt).\n maxAttempts: DEFAULT_MAX_RETRIES,\n // Retries of the service will be executed following ever increasing delays,\n // determined by a backoff formula.\n backoff: new ExponentialBackoff(),\n });\n\n const circuitBreakerPolicy = circuitBreaker(handleAll, {\n // While the circuit is open, any additional invocations of the service\n // passed to the policy (either via automatic retries or by manually\n // executing the policy again) will result in a BrokenCircuitError. This\n // will remain the case until `circuitBreakDuration` passes, after which the\n // service will be allowed to run again. If the service succeeds, the\n // circuit will close, otherwise it will remain open.\n halfOpenAfter: circuitBreakDuration,\n breaker: new ConsecutiveBreaker(maxConsecutiveFailures),\n });\n\n // The `onBreak` callback will be called if the service consistently throws\n // for as many times as exceeds the maximum consecutive number of failures.\n // Combined with the retry policy, this can happen if:\n // - `maxConsecutiveFailures` < the default max retries (3) and the policy is\n // executed once\n // - `maxConsecutiveFailures` >= the default max retries (3) but the policy is\n // executed multiple times, enough for the total number of retries to exceed\n // `maxConsecutiveFailures`\n circuitBreakerPolicy.onBreak(onBreak);\n\n // The `onRetryPolicy` callback will be called each time the service is\n // invoked (including retries).\n retryPolicy.onRetry(onRetry);\n\n retryPolicy.onGiveUp(() => {\n if (circuitBreakerPolicy.state === CircuitState.Closed) {\n // The `onDegraded` callback will be called if the number of retries is\n // exceeded and the maximum number of consecutive failures has not been\n // reached yet (whether the policy is called once or multiple times).\n onDegraded();\n }\n });\n retryPolicy.onSuccess(({ duration }) => {\n if (\n circuitBreakerPolicy.state === CircuitState.Closed &&\n duration > degradedThreshold\n ) {\n // The `onDegraded` callback will also be called if the service does not\n // throw, but the time it takes for the service to run exceeds the\n // `degradedThreshold`.\n onDegraded();\n }\n });\n\n // The retry policy really retries the circuit breaker policy, which invokes\n // the service.\n return wrap(retryPolicy, circuitBreakerPolicy);\n}\n"]}
@@ -15,6 +15,11 @@ export declare const DEFAULT_MAX_CONSECUTIVE_FAILURES: number;
15
15
  * the service after enough consecutive failures.
16
16
  */
17
17
  export declare const DEFAULT_CIRCUIT_BREAK_DURATION: number;
18
+ /**
19
+ * The default length of time (in milliseconds) that governs when the service is
20
+ * regarded as degraded (affecting when `onDegraded` is called).
21
+ */
22
+ export declare const DEFAULT_DEGRADED_THRESHOLD = 5000;
18
23
  /**
19
24
  * Constructs an object exposing an `execute` method which, given a function —
20
25
  * hereafter called the "service" — will retry that service with ever increasing
@@ -33,8 +38,17 @@ export declare const DEFAULT_CIRCUIT_BREAK_DURATION: number;
33
38
  * @param options - The options to this function.
34
39
  * @param options.maxConsecutiveFailures - The maximum number of times that the
35
40
  * service is allowed to fail before pausing further retries. Defaults to 12.
41
+ * @param options.circuitBreakDuration - The length of time (in milliseconds) to
42
+ * pause retries of the action after the number of failures reaches
43
+ * `maxConsecutiveFailures`.
44
+ * @param options.degradedThreshold - The length of time (in milliseconds) that
45
+ * governs when the service is regarded as degraded (affecting when `onDegraded`
46
+ * is called). Defaults to 5 seconds.
36
47
  * @param options.onBreak - A function which is called when the service fails
37
48
  * too many times in a row (specifically, more than `maxConsecutiveFailures`).
49
+ * @param options.onDegraded - A function which is called when the service
50
+ * succeeds before `maxConsecutiveFailures` is reached, but takes more time than
51
+ * the `degradedThreshold` to run.
38
52
  * @param options.onRetry - A function which will be called the moment the
39
53
  * policy kicks off a timer to re-run the function passed to the policy. This is
40
54
  * primarily useful in tests where we are mocking timers.
@@ -47,9 +61,14 @@ export declare const DEFAULT_CIRCUIT_BREAK_DURATION: number;
47
61
  * constructor() {
48
62
  * this.#policy = createServicePolicy({
49
63
  * maxConsecutiveFailures: 3,
64
+ * circuitBreakDuration: 5000,
65
+ * degradedThreshold: 2000,
50
66
  * onBreak: () => {
51
67
  * console.log('Circuit broke');
52
68
  * },
69
+ * onDegraded: () => {
70
+ * console.log('Service is degraded');
71
+ * },
53
72
  * });
54
73
  * }
55
74
  *
@@ -62,9 +81,12 @@ export declare const DEFAULT_CIRCUIT_BREAK_DURATION: number;
62
81
  * }
63
82
  * ```
64
83
  */
65
- export declare function createServicePolicy({ maxConsecutiveFailures, onBreak, onRetry, }?: {
84
+ export declare function createServicePolicy({ maxConsecutiveFailures, circuitBreakDuration, degradedThreshold, onBreak, onDegraded, onRetry, }?: {
66
85
  maxConsecutiveFailures?: number;
86
+ circuitBreakDuration?: number;
87
+ degradedThreshold?: number;
67
88
  onBreak?: () => void;
89
+ onDegraded?: () => void;
68
90
  onRetry?: () => void;
69
91
  }): IPolicy;
70
92
  //# sourceMappingURL=create-service-policy.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"create-service-policy.d.cts","sourceRoot":"","sources":["../src/create-service-policy.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,OAAO,EAAE,kBAAkB;AAEzC,YAAY,EAAE,OAAO,IAAI,cAAc,EAAE,CAAC;AAE1C;;;GAGG;AACH,eAAO,MAAM,mBAAmB,IAAI,CAAC;AAErC;;;GAGG;AACH,eAAO,MAAM,gCAAgC,QAAgC,CAAC;AAE9E;;;GAGG;AACH,eAAO,MAAM,8BAA8B,QAAiB,CAAC;AAE7D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8CG;AACH,wBAAgB,mBAAmB,CAAC,EAClC,sBAAyD,EACzD,OAEC,EACD,OAEC,GACF,GAAE;IACD,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IACrB,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;CACjB,GAAG,OAAO,CAsCf"}
1
+ {"version":3,"file":"create-service-policy.d.cts","sourceRoot":"","sources":["../src/create-service-policy.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,OAAO,EAAE,kBAAkB;AAEzC,YAAY,EAAE,OAAO,IAAI,cAAc,EAAE,CAAC;AAE1C;;;GAGG;AACH,eAAO,MAAM,mBAAmB,IAAI,CAAC;AAErC;;;GAGG;AACH,eAAO,MAAM,gCAAgC,QAAgC,CAAC;AAE9E;;;GAGG;AACH,eAAO,MAAM,8BAA8B,QAAiB,CAAC;AAE7D;;;GAGG;AACH,eAAO,MAAM,0BAA0B,OAAQ,CAAC;AAEhD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4DG;AACH,wBAAgB,mBAAmB,CAAC,EAClC,sBAAyD,EACzD,oBAAqD,EACrD,iBAA8C,EAC9C,OAEC,EACD,UAEC,EACD,OAEC,GACF,GAAE;IACD,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IACrB,UAAU,CAAC,EAAE,MAAM,IAAI,CAAC;IACxB,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;CACjB,GAAG,OAAO,CA0Df"}
@@ -15,6 +15,11 @@ export declare const DEFAULT_MAX_CONSECUTIVE_FAILURES: number;
15
15
  * the service after enough consecutive failures.
16
16
  */
17
17
  export declare const DEFAULT_CIRCUIT_BREAK_DURATION: number;
18
+ /**
19
+ * The default length of time (in milliseconds) that governs when the service is
20
+ * regarded as degraded (affecting when `onDegraded` is called).
21
+ */
22
+ export declare const DEFAULT_DEGRADED_THRESHOLD = 5000;
18
23
  /**
19
24
  * Constructs an object exposing an `execute` method which, given a function —
20
25
  * hereafter called the "service" — will retry that service with ever increasing
@@ -33,8 +38,17 @@ export declare const DEFAULT_CIRCUIT_BREAK_DURATION: number;
33
38
  * @param options - The options to this function.
34
39
  * @param options.maxConsecutiveFailures - The maximum number of times that the
35
40
  * service is allowed to fail before pausing further retries. Defaults to 12.
41
+ * @param options.circuitBreakDuration - The length of time (in milliseconds) to
42
+ * pause retries of the action after the number of failures reaches
43
+ * `maxConsecutiveFailures`.
44
+ * @param options.degradedThreshold - The length of time (in milliseconds) that
45
+ * governs when the service is regarded as degraded (affecting when `onDegraded`
46
+ * is called). Defaults to 5 seconds.
36
47
  * @param options.onBreak - A function which is called when the service fails
37
48
  * too many times in a row (specifically, more than `maxConsecutiveFailures`).
49
+ * @param options.onDegraded - A function which is called when the service
50
+ * succeeds before `maxConsecutiveFailures` is reached, but takes more time than
51
+ * the `degradedThreshold` to run.
38
52
  * @param options.onRetry - A function which will be called the moment the
39
53
  * policy kicks off a timer to re-run the function passed to the policy. This is
40
54
  * primarily useful in tests where we are mocking timers.
@@ -47,9 +61,14 @@ export declare const DEFAULT_CIRCUIT_BREAK_DURATION: number;
47
61
  * constructor() {
48
62
  * this.#policy = createServicePolicy({
49
63
  * maxConsecutiveFailures: 3,
64
+ * circuitBreakDuration: 5000,
65
+ * degradedThreshold: 2000,
50
66
  * onBreak: () => {
51
67
  * console.log('Circuit broke');
52
68
  * },
69
+ * onDegraded: () => {
70
+ * console.log('Service is degraded');
71
+ * },
53
72
  * });
54
73
  * }
55
74
  *
@@ -62,9 +81,12 @@ export declare const DEFAULT_CIRCUIT_BREAK_DURATION: number;
62
81
  * }
63
82
  * ```
64
83
  */
65
- export declare function createServicePolicy({ maxConsecutiveFailures, onBreak, onRetry, }?: {
84
+ export declare function createServicePolicy({ maxConsecutiveFailures, circuitBreakDuration, degradedThreshold, onBreak, onDegraded, onRetry, }?: {
66
85
  maxConsecutiveFailures?: number;
86
+ circuitBreakDuration?: number;
87
+ degradedThreshold?: number;
67
88
  onBreak?: () => void;
89
+ onDegraded?: () => void;
68
90
  onRetry?: () => void;
69
91
  }): IPolicy;
70
92
  //# sourceMappingURL=create-service-policy.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"create-service-policy.d.mts","sourceRoot":"","sources":["../src/create-service-policy.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,OAAO,EAAE,kBAAkB;AAEzC,YAAY,EAAE,OAAO,IAAI,cAAc,EAAE,CAAC;AAE1C;;;GAGG;AACH,eAAO,MAAM,mBAAmB,IAAI,CAAC;AAErC;;;GAGG;AACH,eAAO,MAAM,gCAAgC,QAAgC,CAAC;AAE9E;;;GAGG;AACH,eAAO,MAAM,8BAA8B,QAAiB,CAAC;AAE7D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8CG;AACH,wBAAgB,mBAAmB,CAAC,EAClC,sBAAyD,EACzD,OAEC,EACD,OAEC,GACF,GAAE;IACD,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IACrB,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;CACjB,GAAG,OAAO,CAsCf"}
1
+ {"version":3,"file":"create-service-policy.d.mts","sourceRoot":"","sources":["../src/create-service-policy.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,OAAO,EAAE,kBAAkB;AAEzC,YAAY,EAAE,OAAO,IAAI,cAAc,EAAE,CAAC;AAE1C;;;GAGG;AACH,eAAO,MAAM,mBAAmB,IAAI,CAAC;AAErC;;;GAGG;AACH,eAAO,MAAM,gCAAgC,QAAgC,CAAC;AAE9E;;;GAGG;AACH,eAAO,MAAM,8BAA8B,QAAiB,CAAC;AAE7D;;;GAGG;AACH,eAAO,MAAM,0BAA0B,OAAQ,CAAC;AAEhD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4DG;AACH,wBAAgB,mBAAmB,CAAC,EAClC,sBAAyD,EACzD,oBAAqD,EACrD,iBAA8C,EAC9C,OAEC,EACD,UAEC,EACD,OAEC,GACF,GAAE;IACD,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IACrB,UAAU,CAAC,EAAE,MAAM,IAAI,CAAC;IACxB,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;CACjB,GAAG,OAAO,CA0Df"}
@@ -1,4 +1,4 @@
1
- import { circuitBreaker, ConsecutiveBreaker, ExponentialBackoff, handleAll, retry, wrap } from "cockatiel";
1
+ import { circuitBreaker, ConsecutiveBreaker, ExponentialBackoff, handleAll, retry, wrap, CircuitState } from "cockatiel";
2
2
  /**
3
3
  * The maximum number of times that a failing service should be re-run before
4
4
  * giving up.
@@ -14,6 +14,11 @@ export const DEFAULT_MAX_CONSECUTIVE_FAILURES = (1 + DEFAULT_MAX_RETRIES) * 3;
14
14
  * the service after enough consecutive failures.
15
15
  */
16
16
  export const DEFAULT_CIRCUIT_BREAK_DURATION = 30 * 60 * 1000;
17
+ /**
18
+ * The default length of time (in milliseconds) that governs when the service is
19
+ * regarded as degraded (affecting when `onDegraded` is called).
20
+ */
21
+ export const DEFAULT_DEGRADED_THRESHOLD = 5000;
17
22
  /**
18
23
  * Constructs an object exposing an `execute` method which, given a function —
19
24
  * hereafter called the "service" — will retry that service with ever increasing
@@ -32,8 +37,17 @@ export const DEFAULT_CIRCUIT_BREAK_DURATION = 30 * 60 * 1000;
32
37
  * @param options - The options to this function.
33
38
  * @param options.maxConsecutiveFailures - The maximum number of times that the
34
39
  * service is allowed to fail before pausing further retries. Defaults to 12.
40
+ * @param options.circuitBreakDuration - The length of time (in milliseconds) to
41
+ * pause retries of the action after the number of failures reaches
42
+ * `maxConsecutiveFailures`.
43
+ * @param options.degradedThreshold - The length of time (in milliseconds) that
44
+ * governs when the service is regarded as degraded (affecting when `onDegraded`
45
+ * is called). Defaults to 5 seconds.
35
46
  * @param options.onBreak - A function which is called when the service fails
36
47
  * too many times in a row (specifically, more than `maxConsecutiveFailures`).
48
+ * @param options.onDegraded - A function which is called when the service
49
+ * succeeds before `maxConsecutiveFailures` is reached, but takes more time than
50
+ * the `degradedThreshold` to run.
37
51
  * @param options.onRetry - A function which will be called the moment the
38
52
  * policy kicks off a timer to re-run the function passed to the policy. This is
39
53
  * primarily useful in tests where we are mocking timers.
@@ -46,9 +60,14 @@ export const DEFAULT_CIRCUIT_BREAK_DURATION = 30 * 60 * 1000;
46
60
  * constructor() {
47
61
  * this.#policy = createServicePolicy({
48
62
  * maxConsecutiveFailures: 3,
63
+ * circuitBreakDuration: 5000,
64
+ * degradedThreshold: 2000,
49
65
  * onBreak: () => {
50
66
  * console.log('Circuit broke');
51
67
  * },
68
+ * onDegraded: () => {
69
+ * console.log('Service is degraded');
70
+ * },
52
71
  * });
53
72
  * }
54
73
  *
@@ -61,7 +80,9 @@ export const DEFAULT_CIRCUIT_BREAK_DURATION = 30 * 60 * 1000;
61
80
  * }
62
81
  * ```
63
82
  */
64
- export function createServicePolicy({ maxConsecutiveFailures = DEFAULT_MAX_CONSECUTIVE_FAILURES, onBreak = () => {
83
+ export function createServicePolicy({ maxConsecutiveFailures = DEFAULT_MAX_CONSECUTIVE_FAILURES, circuitBreakDuration = DEFAULT_CIRCUIT_BREAK_DURATION, degradedThreshold = DEFAULT_DEGRADED_THRESHOLD, onBreak = () => {
84
+ // do nothing
85
+ }, onDegraded = () => {
65
86
  // do nothing
66
87
  }, onRetry = () => {
67
88
  // do nothing
@@ -78,10 +99,10 @@ export function createServicePolicy({ maxConsecutiveFailures = DEFAULT_MAX_CONSE
78
99
  // While the circuit is open, any additional invocations of the service
79
100
  // passed to the policy (either via automatic retries or by manually
80
101
  // executing the policy again) will result in a BrokenCircuitError. This
81
- // will remain the case until the default circuit break duration passes,
82
- // after which the service will be allowed to run again. If the service
83
- // succeeds, the circuit will close, otherwise it will remain open.
84
- halfOpenAfter: DEFAULT_CIRCUIT_BREAK_DURATION,
102
+ // will remain the case until `circuitBreakDuration` passes, after which the
103
+ // service will be allowed to run again. If the service succeeds, the
104
+ // circuit will close, otherwise it will remain open.
105
+ halfOpenAfter: circuitBreakDuration,
85
106
  breaker: new ConsecutiveBreaker(maxConsecutiveFailures),
86
107
  });
87
108
  // The `onBreak` callback will be called if the service consistently throws
@@ -96,6 +117,23 @@ export function createServicePolicy({ maxConsecutiveFailures = DEFAULT_MAX_CONSE
96
117
  // The `onRetryPolicy` callback will be called each time the service is
97
118
  // invoked (including retries).
98
119
  retryPolicy.onRetry(onRetry);
120
+ retryPolicy.onGiveUp(() => {
121
+ if (circuitBreakerPolicy.state === CircuitState.Closed) {
122
+ // The `onDegraded` callback will be called if the number of retries is
123
+ // exceeded and the maximum number of consecutive failures has not been
124
+ // reached yet (whether the policy is called once or multiple times).
125
+ onDegraded();
126
+ }
127
+ });
128
+ retryPolicy.onSuccess(({ duration }) => {
129
+ if (circuitBreakerPolicy.state === CircuitState.Closed &&
130
+ duration > degradedThreshold) {
131
+ // The `onDegraded` callback will also be called if the service does not
132
+ // throw, but the time it takes for the service to run exceeds the
133
+ // `degradedThreshold`.
134
+ onDegraded();
135
+ }
136
+ });
99
137
  // The retry policy really retries the circuit breaker policy, which invokes
100
138
  // the service.
101
139
  return wrap(retryPolicy, circuitBreakerPolicy);
@@ -1 +1 @@
1
- {"version":3,"file":"create-service-policy.mjs","sourceRoot":"","sources":["../src/create-service-policy.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,EACd,kBAAkB,EAClB,kBAAkB,EAClB,SAAS,EACT,KAAK,EACL,IAAI,EACL,kBAAkB;AAKnB;;;GAGG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAC,CAAC;AAErC;;;GAGG;AACH,MAAM,CAAC,MAAM,gCAAgC,GAAG,CAAC,CAAC,GAAG,mBAAmB,CAAC,GAAG,CAAC,CAAC;AAE9E;;;GAGG;AACH,MAAM,CAAC,MAAM,8BAA8B,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAE7D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8CG;AACH,MAAM,UAAU,mBAAmB,CAAC,EAClC,sBAAsB,GAAG,gCAAgC,EACzD,OAAO,GAAG,GAAG,EAAE;IACb,aAAa;AACf,CAAC,EACD,OAAO,GAAG,GAAG,EAAE;IACb,aAAa;AACf,CAAC,MAKC,EAAE;IACJ,MAAM,WAAW,GAAG,KAAK,CAAC,SAAS,EAAE;QACnC,2EAA2E;QAC3E,mEAAmE;QACnE,WAAW,EAAE,mBAAmB;QAChC,4EAA4E;QAC5E,mCAAmC;QACnC,OAAO,EAAE,IAAI,kBAAkB,EAAE;KAClC,CAAC,CAAC;IAEH,MAAM,oBAAoB,GAAG,cAAc,CAAC,SAAS,EAAE;QACrD,uEAAuE;QACvE,oEAAoE;QACpE,wEAAwE;QACxE,wEAAwE;QACxE,uEAAuE;QACvE,mEAAmE;QACnE,aAAa,EAAE,8BAA8B;QAC7C,OAAO,EAAE,IAAI,kBAAkB,CAAC,sBAAsB,CAAC;KACxD,CAAC,CAAC;IAEH,2EAA2E;IAC3E,2EAA2E;IAC3E,sDAAsD;IACtD,6EAA6E;IAC7E,gBAAgB;IAChB,8EAA8E;IAC9E,8EAA8E;IAC9E,6BAA6B;IAC7B,oBAAoB,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;IAEtC,uEAAuE;IACvE,+BAA+B;IAC/B,WAAW,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;IAE7B,4EAA4E;IAC5E,eAAe;IACf,OAAO,IAAI,CAAC,WAAW,EAAE,oBAAoB,CAAC,CAAC;AACjD,CAAC","sourcesContent":["import {\n circuitBreaker,\n ConsecutiveBreaker,\n ExponentialBackoff,\n handleAll,\n retry,\n wrap,\n} from 'cockatiel';\nimport type { IPolicy } from 'cockatiel';\n\nexport type { IPolicy as IServicePolicy };\n\n/**\n * The maximum number of times that a failing service should be re-run before\n * giving up.\n */\nexport const DEFAULT_MAX_RETRIES = 3;\n\n/**\n * The maximum number of times that the service is allowed to fail before\n * pausing further retries.\n */\nexport const DEFAULT_MAX_CONSECUTIVE_FAILURES = (1 + DEFAULT_MAX_RETRIES) * 3;\n\n/**\n * The default length of time (in milliseconds) to temporarily pause retries of\n * the service after enough consecutive failures.\n */\nexport const DEFAULT_CIRCUIT_BREAK_DURATION = 30 * 60 * 1000;\n\n/**\n * Constructs an object exposing an `execute` method which, given a function —\n * hereafter called the \"service\" — will retry that service with ever increasing\n * delays until it succeeds. If the policy detects too many consecutive\n * failures, it will block further retries until a designated time period has\n * passed; this particular behavior is primarily designed for services that wrap\n * API calls so as not to make needless HTTP requests when the API is down and\n * to be able to recover when the API comes back up. In addition, hooks allow\n * for responding to certain events, one of which can be used to detect when an\n * HTTP request is performing slowly.\n *\n * Internally, this function makes use of the retry and circuit breaker policies\n * from the [Cockatiel](https://www.npmjs.com/package/cockatiel) library; see\n * there for more.\n *\n * @param options - The options to this function.\n * @param options.maxConsecutiveFailures - The maximum number of times that the\n * service is allowed to fail before pausing further retries. Defaults to 12.\n * @param options.onBreak - A function which is called when the service fails\n * too many times in a row (specifically, more than `maxConsecutiveFailures`).\n * @param options.onRetry - A function which will be called the moment the\n * policy kicks off a timer to re-run the function passed to the policy. This is\n * primarily useful in tests where we are mocking timers.\n * @returns The service policy.\n * @example\n * This function is designed to be used in the context of a service class like\n * this:\n * ``` ts\n * class Service {\n * constructor() {\n * this.#policy = createServicePolicy({\n * maxConsecutiveFailures: 3,\n * onBreak: () => {\n * console.log('Circuit broke');\n * },\n * });\n * }\n *\n * async fetch() {\n * return await this.#policy.execute(async () => {\n * const response = await fetch('https://some/url');\n * return await response.json();\n * });\n * }\n * }\n * ```\n */\nexport function createServicePolicy({\n maxConsecutiveFailures = DEFAULT_MAX_CONSECUTIVE_FAILURES,\n onBreak = () => {\n // do nothing\n },\n onRetry = () => {\n // do nothing\n },\n}: {\n maxConsecutiveFailures?: number;\n onBreak?: () => void;\n onRetry?: () => void;\n} = {}): IPolicy {\n const retryPolicy = retry(handleAll, {\n // Note that although the option here is called \"max attempts\", it's really\n // maximum number of *retries* (attempts past the initial attempt).\n maxAttempts: DEFAULT_MAX_RETRIES,\n // Retries of the service will be executed following ever increasing delays,\n // determined by a backoff formula.\n backoff: new ExponentialBackoff(),\n });\n\n const circuitBreakerPolicy = circuitBreaker(handleAll, {\n // While the circuit is open, any additional invocations of the service\n // passed to the policy (either via automatic retries or by manually\n // executing the policy again) will result in a BrokenCircuitError. This\n // will remain the case until the default circuit break duration passes,\n // after which the service will be allowed to run again. If the service\n // succeeds, the circuit will close, otherwise it will remain open.\n halfOpenAfter: DEFAULT_CIRCUIT_BREAK_DURATION,\n breaker: new ConsecutiveBreaker(maxConsecutiveFailures),\n });\n\n // The `onBreak` callback will be called if the service consistently throws\n // for as many times as exceeds the maximum consecutive number of failures.\n // Combined with the retry policy, this can happen if:\n // - `maxConsecutiveFailures` < the default max retries (3) and the policy is\n // executed once\n // - `maxConsecutiveFailures` >= the default max retries (3) but the policy is\n // executed multiple times, enough for the total number of retries to exceed\n // `maxConsecutiveFailures`\n circuitBreakerPolicy.onBreak(onBreak);\n\n // The `onRetryPolicy` callback will be called each time the service is\n // invoked (including retries).\n retryPolicy.onRetry(onRetry);\n\n // The retry policy really retries the circuit breaker policy, which invokes\n // the service.\n return wrap(retryPolicy, circuitBreakerPolicy);\n}\n"]}
1
+ {"version":3,"file":"create-service-policy.mjs","sourceRoot":"","sources":["../src/create-service-policy.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,EACd,kBAAkB,EAClB,kBAAkB,EAClB,SAAS,EACT,KAAK,EACL,IAAI,EACJ,YAAY,EACb,kBAAkB;AAKnB;;;GAGG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAC,CAAC;AAErC;;;GAGG;AACH,MAAM,CAAC,MAAM,gCAAgC,GAAG,CAAC,CAAC,GAAG,mBAAmB,CAAC,GAAG,CAAC,CAAC;AAE9E;;;GAGG;AACH,MAAM,CAAC,MAAM,8BAA8B,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAE7D;;;GAGG;AACH,MAAM,CAAC,MAAM,0BAA0B,GAAG,IAAK,CAAC;AAEhD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4DG;AACH,MAAM,UAAU,mBAAmB,CAAC,EAClC,sBAAsB,GAAG,gCAAgC,EACzD,oBAAoB,GAAG,8BAA8B,EACrD,iBAAiB,GAAG,0BAA0B,EAC9C,OAAO,GAAG,GAAG,EAAE;IACb,aAAa;AACf,CAAC,EACD,UAAU,GAAG,GAAG,EAAE;IAChB,aAAa;AACf,CAAC,EACD,OAAO,GAAG,GAAG,EAAE;IACb,aAAa;AACf,CAAC,MAQC,EAAE;IACJ,MAAM,WAAW,GAAG,KAAK,CAAC,SAAS,EAAE;QACnC,2EAA2E;QAC3E,mEAAmE;QACnE,WAAW,EAAE,mBAAmB;QAChC,4EAA4E;QAC5E,mCAAmC;QACnC,OAAO,EAAE,IAAI,kBAAkB,EAAE;KAClC,CAAC,CAAC;IAEH,MAAM,oBAAoB,GAAG,cAAc,CAAC,SAAS,EAAE;QACrD,uEAAuE;QACvE,oEAAoE;QACpE,wEAAwE;QACxE,4EAA4E;QAC5E,qEAAqE;QACrE,qDAAqD;QACrD,aAAa,EAAE,oBAAoB;QACnC,OAAO,EAAE,IAAI,kBAAkB,CAAC,sBAAsB,CAAC;KACxD,CAAC,CAAC;IAEH,2EAA2E;IAC3E,2EAA2E;IAC3E,sDAAsD;IACtD,6EAA6E;IAC7E,gBAAgB;IAChB,8EAA8E;IAC9E,8EAA8E;IAC9E,6BAA6B;IAC7B,oBAAoB,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;IAEtC,uEAAuE;IACvE,+BAA+B;IAC/B,WAAW,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;IAE7B,WAAW,CAAC,QAAQ,CAAC,GAAG,EAAE;QACxB,IAAI,oBAAoB,CAAC,KAAK,KAAK,YAAY,CAAC,MAAM,EAAE;YACtD,uEAAuE;YACvE,uEAAuE;YACvE,qEAAqE;YACrE,UAAU,EAAE,CAAC;SACd;IACH,CAAC,CAAC,CAAC;IACH,WAAW,CAAC,SAAS,CAAC,CAAC,EAAE,QAAQ,EAAE,EAAE,EAAE;QACrC,IACE,oBAAoB,CAAC,KAAK,KAAK,YAAY,CAAC,MAAM;YAClD,QAAQ,GAAG,iBAAiB,EAC5B;YACA,wEAAwE;YACxE,kEAAkE;YAClE,uBAAuB;YACvB,UAAU,EAAE,CAAC;SACd;IACH,CAAC,CAAC,CAAC;IAEH,4EAA4E;IAC5E,eAAe;IACf,OAAO,IAAI,CAAC,WAAW,EAAE,oBAAoB,CAAC,CAAC;AACjD,CAAC","sourcesContent":["import {\n circuitBreaker,\n ConsecutiveBreaker,\n ExponentialBackoff,\n handleAll,\n retry,\n wrap,\n CircuitState,\n} from 'cockatiel';\nimport type { IPolicy } from 'cockatiel';\n\nexport type { IPolicy as IServicePolicy };\n\n/**\n * The maximum number of times that a failing service should be re-run before\n * giving up.\n */\nexport const DEFAULT_MAX_RETRIES = 3;\n\n/**\n * The maximum number of times that the service is allowed to fail before\n * pausing further retries.\n */\nexport const DEFAULT_MAX_CONSECUTIVE_FAILURES = (1 + DEFAULT_MAX_RETRIES) * 3;\n\n/**\n * The default length of time (in milliseconds) to temporarily pause retries of\n * the service after enough consecutive failures.\n */\nexport const DEFAULT_CIRCUIT_BREAK_DURATION = 30 * 60 * 1000;\n\n/**\n * The default length of time (in milliseconds) that governs when the service is\n * regarded as degraded (affecting when `onDegraded` is called).\n */\nexport const DEFAULT_DEGRADED_THRESHOLD = 5_000;\n\n/**\n * Constructs an object exposing an `execute` method which, given a function —\n * hereafter called the \"service\" — will retry that service with ever increasing\n * delays until it succeeds. If the policy detects too many consecutive\n * failures, it will block further retries until a designated time period has\n * passed; this particular behavior is primarily designed for services that wrap\n * API calls so as not to make needless HTTP requests when the API is down and\n * to be able to recover when the API comes back up. In addition, hooks allow\n * for responding to certain events, one of which can be used to detect when an\n * HTTP request is performing slowly.\n *\n * Internally, this function makes use of the retry and circuit breaker policies\n * from the [Cockatiel](https://www.npmjs.com/package/cockatiel) library; see\n * there for more.\n *\n * @param options - The options to this function.\n * @param options.maxConsecutiveFailures - The maximum number of times that the\n * service is allowed to fail before pausing further retries. Defaults to 12.\n * @param options.circuitBreakDuration - The length of time (in milliseconds) to\n * pause retries of the action after the number of failures reaches\n * `maxConsecutiveFailures`.\n * @param options.degradedThreshold - The length of time (in milliseconds) that\n * governs when the service is regarded as degraded (affecting when `onDegraded`\n * is called). Defaults to 5 seconds.\n * @param options.onBreak - A function which is called when the service fails\n * too many times in a row (specifically, more than `maxConsecutiveFailures`).\n * @param options.onDegraded - A function which is called when the service\n * succeeds before `maxConsecutiveFailures` is reached, but takes more time than\n * the `degradedThreshold` to run.\n * @param options.onRetry - A function which will be called the moment the\n * policy kicks off a timer to re-run the function passed to the policy. This is\n * primarily useful in tests where we are mocking timers.\n * @returns The service policy.\n * @example\n * This function is designed to be used in the context of a service class like\n * this:\n * ``` ts\n * class Service {\n * constructor() {\n * this.#policy = createServicePolicy({\n * maxConsecutiveFailures: 3,\n * circuitBreakDuration: 5000,\n * degradedThreshold: 2000,\n * onBreak: () => {\n * console.log('Circuit broke');\n * },\n * onDegraded: () => {\n * console.log('Service is degraded');\n * },\n * });\n * }\n *\n * async fetch() {\n * return await this.#policy.execute(async () => {\n * const response = await fetch('https://some/url');\n * return await response.json();\n * });\n * }\n * }\n * ```\n */\nexport function createServicePolicy({\n maxConsecutiveFailures = DEFAULT_MAX_CONSECUTIVE_FAILURES,\n circuitBreakDuration = DEFAULT_CIRCUIT_BREAK_DURATION,\n degradedThreshold = DEFAULT_DEGRADED_THRESHOLD,\n onBreak = () => {\n // do nothing\n },\n onDegraded = () => {\n // do nothing\n },\n onRetry = () => {\n // do nothing\n },\n}: {\n maxConsecutiveFailures?: number;\n circuitBreakDuration?: number;\n degradedThreshold?: number;\n onBreak?: () => void;\n onDegraded?: () => void;\n onRetry?: () => void;\n} = {}): IPolicy {\n const retryPolicy = retry(handleAll, {\n // Note that although the option here is called \"max attempts\", it's really\n // maximum number of *retries* (attempts past the initial attempt).\n maxAttempts: DEFAULT_MAX_RETRIES,\n // Retries of the service will be executed following ever increasing delays,\n // determined by a backoff formula.\n backoff: new ExponentialBackoff(),\n });\n\n const circuitBreakerPolicy = circuitBreaker(handleAll, {\n // While the circuit is open, any additional invocations of the service\n // passed to the policy (either via automatic retries or by manually\n // executing the policy again) will result in a BrokenCircuitError. This\n // will remain the case until `circuitBreakDuration` passes, after which the\n // service will be allowed to run again. If the service succeeds, the\n // circuit will close, otherwise it will remain open.\n halfOpenAfter: circuitBreakDuration,\n breaker: new ConsecutiveBreaker(maxConsecutiveFailures),\n });\n\n // The `onBreak` callback will be called if the service consistently throws\n // for as many times as exceeds the maximum consecutive number of failures.\n // Combined with the retry policy, this can happen if:\n // - `maxConsecutiveFailures` < the default max retries (3) and the policy is\n // executed once\n // - `maxConsecutiveFailures` >= the default max retries (3) but the policy is\n // executed multiple times, enough for the total number of retries to exceed\n // `maxConsecutiveFailures`\n circuitBreakerPolicy.onBreak(onBreak);\n\n // The `onRetryPolicy` callback will be called each time the service is\n // invoked (including retries).\n retryPolicy.onRetry(onRetry);\n\n retryPolicy.onGiveUp(() => {\n if (circuitBreakerPolicy.state === CircuitState.Closed) {\n // The `onDegraded` callback will be called if the number of retries is\n // exceeded and the maximum number of consecutive failures has not been\n // reached yet (whether the policy is called once or multiple times).\n onDegraded();\n }\n });\n retryPolicy.onSuccess(({ duration }) => {\n if (\n circuitBreakerPolicy.state === CircuitState.Closed &&\n duration > degradedThreshold\n ) {\n // The `onDegraded` callback will also be called if the service does not\n // throw, but the time it takes for the service to run exceeds the\n // `degradedThreshold`.\n onDegraded();\n }\n });\n\n // The retry policy really retries the circuit breaker policy, which invokes\n // the service.\n return wrap(retryPolicy, circuitBreakerPolicy);\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask-previews/controller-utils",
3
- "version": "11.4.5-preview-e05b7d3e",
3
+ "version": "11.4.5-preview-6244b7be",
4
4
  "description": "Data and convenience functions shared by multiple packages",
5
5
  "keywords": [
6
6
  "MetaMask",