@metamask-previews/controller-utils 12.3.0-preview-aa4ef4666 → 12.3.0-preview-186382c0a

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
@@ -11,6 +11,31 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
11
11
 
12
12
  - Add optional `startTime` to `TraceRequest` to allow backdating a span's start time ([#9315](https://github.com/MetaMask/core/pull/9315))
13
13
 
14
+ ### Deprecated
15
+
16
+ - Deprecate `createServicePolicy` and related symbols ([#9418](https://github.com/MetaMask/core/pull/9418))
17
+ - Deprecated functions:
18
+ `createServicePolicy`
19
+ - Deprecated constants:
20
+ - `DEFAULT_CIRCUIT_BREAK_DURATION`
21
+ - `DEFAULT_DEGRADED_THRESHOLD`
22
+ - `DEFAULT_MAX_CONSECUTIVE_FAILURES`
23
+ - `DEFAULT_MAX_RETRIES`
24
+ - Deprecated types:
25
+ - `CreateServicePolicyOptions`
26
+ - `ServicePolicy`
27
+ - Deprecated re-exports from `cockatiel`:
28
+ - `BrokenCircuitError`
29
+ - `CircuitState`
30
+ - `CockatielEventEmitter`
31
+ - `CockatielEvent`
32
+ - `CockatielFailureReason`
33
+ - `ConstantBackoff`
34
+ - `ExponentialBackoff`
35
+ - `handleAll`
36
+ - `handleWhen`
37
+ - These symbols will be removed in a future major version. Please use equivalent implementations from `@metamask/base-data-service` going forward.
38
+
14
39
  ## [12.3.0]
15
40
 
16
41
  ### Added
@@ -23,6 +23,9 @@ const AVAILABILITY_STATUSES = {
23
23
  /**
24
24
  * The maximum number of times that a failing service should be re-run before
25
25
  * giving up.
26
+ *
27
+ * @deprecated This is deprecated and will be removed in a future major version.
28
+ * Please use the equivalent variable from `@metamask/base-data-service`.
26
29
  */
27
30
  exports.DEFAULT_MAX_RETRIES = 3;
28
31
  /**
@@ -30,16 +33,25 @@ exports.DEFAULT_MAX_RETRIES = 3;
30
33
  * pausing further retries. This is set to a value such that if given a
31
34
  * service that continually fails, the policy needs to be executed 3 times
32
35
  * before further retries are paused.
36
+ *
37
+ * @deprecated This is deprecated and will be removed in a future major version.
38
+ * Please use the equivalent variable from `@metamask/base-data-service`.
33
39
  */
34
40
  exports.DEFAULT_MAX_CONSECUTIVE_FAILURES = (1 + exports.DEFAULT_MAX_RETRIES) * 3;
35
41
  /**
36
42
  * The default length of time (in milliseconds) to temporarily pause retries of
37
43
  * the service after enough consecutive failures.
44
+ *
45
+ * @deprecated This is deprecated and will be removed in a future major version.
46
+ * Please use the equivalent variable from `@metamask/base-data-service`.
38
47
  */
39
48
  exports.DEFAULT_CIRCUIT_BREAK_DURATION = 30 * 60 * 1000;
40
49
  /**
41
50
  * The default length of time (in milliseconds) that governs when the service is
42
51
  * regarded as degraded (affecting when `onDegraded` is called).
52
+ *
53
+ * @deprecated This is deprecated and will be removed in a future major version.
54
+ * Please use the equivalent variable from `@metamask/base-data-service`.
43
55
  */
44
56
  exports.DEFAULT_DEGRADED_THRESHOLD = 5000;
45
57
  const defaultIsServiceFailure = (error) => {
@@ -121,6 +133,9 @@ function getInternalCircuitState(state) {
121
133
  * }
122
134
  * }
123
135
  * ```
136
+ *
137
+ * @deprecated This is deprecated and will be removed in a future major version.
138
+ * Please use the equivalent function from `@metamask/base-data-service`.
124
139
  */
125
140
  function createServicePolicy(options = {}) {
126
141
  const { maxRetries = exports.DEFAULT_MAX_RETRIES, retryFilterPolicy = cockatiel_1.handleAll, maxConsecutiveFailures = exports.DEFAULT_MAX_CONSECUTIVE_FAILURES, circuitBreakDuration = exports.DEFAULT_CIRCUIT_BREAK_DURATION, degradedThreshold = exports.DEFAULT_DEGRADED_THRESHOLD, backoff = new cockatiel_1.ExponentialBackoff(), isServiceFailure = defaultIsServiceFailure, } = options;
@@ -1 +1 @@
1
- {"version":3,"file":"create-service-policy.cjs","sourceRoot":"","sources":["../src/create-service-policy.ts"],"names":[],"mappings":";;;AAAA,yCAYmB;AAYjB,mGAvBA,8BAAkB,O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AAgC;IAChC,2CAA2C;IAC3C,oCAAoC;IACpC,UAAU;IACV,QAAQ;IACR,EAAE;IACF,8EAA8E;IAC9E,8EAA8E;IAC9E,6EAA6E;IAC7E,qCAAqC;IACrC,MAAM,MAAM,GAAG,IAAA,gBAAI,EAAC,WAAW,EAAE,oBAAoB,CAAC,CAAC;IAEvD,MAAM,+BAA+B,GAAG,GAAkB,EAAE;QAC1D,IAAI,oBAAoB,CAAC,KAAK,KAAK,wBAAY,CAAC,IAAI,EAAE,CAAC;YACrD,OAAO,oBAAoB,CAAC,QAAQ,GAAG,oBAAoB,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QAC3E,CAAC;QACD,OAAO,IAAI,CAAC;IACd,CAAC,CAAC;IAEF,MAAM,eAAe,GAAG,GAAiB,EAAE;QACzC,OAAO,oBAAoB,CAAC,KAAK,CAAC;IACpC,CAAC,CAAC;IAEF,MAAM,KAAK,GAAG,GAAS,EAAE;QACvB,4EAA4E;QAC5E,MAAM,EAAE,OAAO,EAAE,GAAG,oBAAoB,CAAC,OAAO,EAAE,CAAC;QACnD,8BAA8B;QAC9B,OAAO,EAAE,CAAC;QAEV,2CAA2C;QAC3C,kBAAkB,CAAC,OAAO,EAAE,CAAC;QAE7B,2EAA2E;QAC3E,2DAA2D;QAC3D,kBAAkB,GAAG,qBAAqB,CAAC,OAAO,CAAC;IACrD,CAAC,CAAC;IAEF,OAAO;QACL,GAAG,MAAM;QACT,oBAAoB;QACpB,oBAAoB;QACpB,eAAe;QACf,+BAA+B;QAC/B,KAAK;QACL,WAAW;QACX,OAAO;QACP,UAAU;QACV,WAAW;QACX,OAAO;KACR,CAAC;AACJ,CAAC;AAxID,kDAwIC","sourcesContent":["import {\n BrokenCircuitError,\n CircuitState,\n EventEmitter as CockatielEventEmitter,\n ConsecutiveBreaker,\n ExponentialBackoff,\n ConstantBackoff,\n circuitBreaker,\n handleAll,\n handleWhen,\n retry,\n wrap,\n} from 'cockatiel';\nimport type {\n CircuitBreakerPolicy,\n Event as CockatielEvent,\n FailureReason,\n IBackoffFactory,\n IPolicy,\n Policy,\n RetryPolicy,\n} from 'cockatiel';\n\nexport {\n BrokenCircuitError,\n CockatielEventEmitter,\n CircuitState,\n ConstantBackoff,\n ExponentialBackoff,\n handleAll,\n handleWhen,\n};\n\nexport type { CockatielEvent, FailureReason as CockatielFailureReason };\n\n/**\n * The options for `createServicePolicy`.\n */\nexport type CreateServicePolicyOptions = {\n /**\n * The backoff strategy to use. Mainly useful for testing so that a constant\n * backoff can be used when mocking timers. Defaults to an instance of\n * ExponentialBackoff.\n */\n backoff?: IBackoffFactory<unknown>;\n /**\n * The length of time (in milliseconds) to pause retries of the action after\n * the number of failures reaches `maxConsecutiveFailures`.\n */\n circuitBreakDuration?: number;\n /**\n * The length of time (in milliseconds) that governs when the service is\n * regarded as degraded (affecting when `onDegraded` is called).\n */\n degradedThreshold?: number;\n /**\n * Predicate function for when an error should be considered a service failure.\n */\n isServiceFailure?: (error: unknown) => boolean;\n /**\n * The maximum number of times that the service is allowed to fail before\n * pausing further retries.\n */\n maxConsecutiveFailures?: number;\n /**\n * The maximum number of times that a failing service should be re-invoked\n * before giving up.\n */\n maxRetries?: number;\n /**\n * The policy used to control when the service should be retried based on\n * either the result of the service or an error that it throws. For instance,\n * you could use this to retry only certain errors. See `handleWhen` and\n * friends from Cockatiel for more.\n */\n retryFilterPolicy?: Policy;\n};\n\n/**\n * The service policy object.\n */\nexport type ServicePolicy = IPolicy & {\n /**\n * The Cockatiel circuit breaker policy that the service policy uses\n * internally.\n */\n circuitBreakerPolicy: CircuitBreakerPolicy;\n /**\n * The amount of time to pause requests to the service if the number of\n * maximum consecutive failures is reached.\n */\n circuitBreakDuration: number;\n /**\n * @returns The state of the underlying circuit.\n */\n getCircuitState: () => CircuitState;\n /**\n * If the circuit is open and ongoing requests are paused, returns the number\n * of milliseconds before the requests will be attempted again. If the circuit\n * is not open, returns null.\n */\n getRemainingCircuitOpenDuration: () => number | null;\n /**\n * Resets the internal circuit breaker policy (if it is open, it will now be\n * closed).\n */\n reset: () => void;\n /**\n * The Cockatiel retry policy that the service policy uses internally.\n */\n retryPolicy: RetryPolicy;\n /**\n * A function which is called when the number of times that the service fails\n * in a row meets the set maximum number of consecutive failures.\n */\n onBreak: CircuitBreakerPolicy['onBreak'];\n /**\n * A function which is called in two circumstances: 1) when the service\n * succeeds before the maximum number of consecutive failures is reached, but\n * takes more time than the `degradedThreshold` to run, or 2) if the service\n * never succeeds before the retry policy gives up and before the maximum\n * number of consecutive failures has been reached.\n */\n onDegraded: CockatielEvent<FailureReason<unknown> | { duration: number }>;\n /**\n * A function which is called when the service succeeds for the first time,\n * or when the service fails enough times to cause the circuit to break and\n * then recovers.\n */\n onAvailable: CockatielEvent<void>;\n /**\n * A function which will be called by the retry policy each time the service\n * fails and the policy kicks off a timer to re-run the service. This is\n * primarily useful in tests where we are mocking timers.\n */\n onRetry: RetryPolicy['onRetry'];\n};\n\n/**\n * Parts of the circuit breaker's internal and external state as necessary in\n * order to compute the time remaining before the circuit will reopen.\n */\ntype InternalCircuitState =\n | {\n state: CircuitState.Open;\n openedAt: number;\n }\n | { state: Exclude<CircuitState, CircuitState.Open> };\n\n/**\n * Availability statuses that the service can be in.\n *\n * Used to keep track of whether the `onAvailable` event should be fired.\n */\nconst AVAILABILITY_STATUSES = {\n Available: 'available',\n Degraded: 'degraded',\n Unavailable: 'unavailable',\n Unknown: 'unknown',\n} as const;\n\n/**\n * Availability statuses that the service can be in.\n *\n * Used to keep track of whether the `onAvailable` event should be fired.\n */\ntype AvailabilityStatus =\n (typeof AVAILABILITY_STATUSES)[keyof typeof AVAILABILITY_STATUSES];\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. This is set to a value such that if given a\n * service that continually fails, the policy needs to be executed 3 times\n * before further retries are paused.\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\nconst defaultIsServiceFailure = (error: unknown): boolean => {\n if (\n typeof error === 'object' &&\n error !== null &&\n 'httpStatus' in error &&\n typeof error.httpStatus === 'number'\n ) {\n return error.httpStatus >= 500;\n }\n\n // If the error is not an object, or doesn't have a numeric httpStatus\n // property, consider it a service failure (e.g., network errors, timeouts,\n // etc.)\n return true;\n};\n\n/**\n * The circuit breaker policy inside of the Cockatiel library exposes some of\n * its state, but not all of it. Notably, the time that the circuit opened is\n * not publicly accessible. So we have to record this ourselves.\n *\n * This function therefore allows us to obtain the circuit breaker state that we\n * wish we could access.\n *\n * @param state - The public state of a circuit breaker policy.\n * @returns if the circuit is open, the state of the circuit breaker policy plus\n * the time that it opened, otherwise just the circuit state.\n */\nfunction getInternalCircuitState(state: CircuitState): InternalCircuitState {\n if (state === CircuitState.Open) {\n return { state, openedAt: Date.now() };\n }\n return { state };\n}\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. See\n * {@link CreateServicePolicyOptions}.\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 * maxRetries: 3,\n * retryFilterPolicy: handleWhen((error) => {\n * return error.message.includes('oops');\n * }),\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 options: CreateServicePolicyOptions = {},\n): ServicePolicy {\n const {\n maxRetries = DEFAULT_MAX_RETRIES,\n retryFilterPolicy = handleAll,\n maxConsecutiveFailures = DEFAULT_MAX_CONSECUTIVE_FAILURES,\n circuitBreakDuration = DEFAULT_CIRCUIT_BREAK_DURATION,\n degradedThreshold = DEFAULT_DEGRADED_THRESHOLD,\n backoff = new ExponentialBackoff(),\n isServiceFailure = defaultIsServiceFailure,\n } = options;\n\n let availabilityStatus: AvailabilityStatus = AVAILABILITY_STATUSES.Unknown;\n\n const retryPolicy = retry(retryFilterPolicy, {\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: maxRetries,\n // Retries of the service will be executed following ever increasing delays,\n // determined by a backoff formula.\n backoff,\n });\n const onRetry = retryPolicy.onRetry.bind(retryPolicy);\n\n const consecutiveBreaker = new ConsecutiveBreaker(maxConsecutiveFailures);\n const circuitBreakerPolicy = circuitBreaker(handleWhen(isServiceFailure), {\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: consecutiveBreaker,\n });\n\n let internalCircuitState: InternalCircuitState = getInternalCircuitState(\n circuitBreakerPolicy.state,\n );\n circuitBreakerPolicy.onStateChange((state) => {\n internalCircuitState = getInternalCircuitState(state);\n });\n\n circuitBreakerPolicy.onBreak(() => {\n availabilityStatus = AVAILABILITY_STATUSES.Unavailable;\n });\n const onBreak = circuitBreakerPolicy.onBreak.bind(circuitBreakerPolicy);\n\n const onDegradedEventEmitter = new CockatielEventEmitter<\n FailureReason<unknown> | { duration: number }\n >();\n const onDegraded = onDegradedEventEmitter.addListener;\n\n const onAvailableEventEmitter = new CockatielEventEmitter<void>();\n const onAvailable = onAvailableEventEmitter.addListener;\n\n retryPolicy.onGiveUp((data) => {\n if (circuitBreakerPolicy.state === CircuitState.Closed) {\n availabilityStatus = AVAILABILITY_STATUSES.Degraded;\n onDegradedEventEmitter.emit(data);\n }\n });\n retryPolicy.onSuccess(({ duration }) => {\n if (circuitBreakerPolicy.state === CircuitState.Closed) {\n if (duration > degradedThreshold) {\n availabilityStatus = AVAILABILITY_STATUSES.Degraded;\n onDegradedEventEmitter.emit({ duration });\n } else if (availabilityStatus !== AVAILABILITY_STATUSES.Available) {\n availabilityStatus = AVAILABILITY_STATUSES.Available;\n onAvailableEventEmitter.emit();\n }\n }\n });\n\n // Every time the retry policy makes an attempt, it executes the circuit\n // breaker policy, which executes the service.\n //\n // Calling:\n //\n // policy.execute(() => {\n // // do what the service does\n // })\n //\n // is equivalent to:\n //\n // retryPolicy.execute(() => {\n // circuitBreakerPolicy.execute(() => {\n // // do what the service does\n // });\n // });\n //\n // So if the retry policy succeeds or fails, it is because the circuit breaker\n // policy succeeded or failed. And if there are any event listeners registered\n // on the retry policy, by the time they are called, the state of the circuit\n // breaker will have already changed.\n const policy = wrap(retryPolicy, circuitBreakerPolicy);\n\n const getRemainingCircuitOpenDuration = (): number | null => {\n if (internalCircuitState.state === CircuitState.Open) {\n return internalCircuitState.openedAt + circuitBreakDuration - Date.now();\n }\n return null;\n };\n\n const getCircuitState = (): CircuitState => {\n return circuitBreakerPolicy.state;\n };\n\n const reset = (): void => {\n // Set the state of the policy to \"isolated\" regardless of its current state\n const { dispose } = circuitBreakerPolicy.isolate();\n // Reset the state to \"closed\"\n dispose();\n\n // Reset the counter on the breaker as well\n consecutiveBreaker.success();\n\n // Re-initialize the availability status so that if the service is executed\n // successfully, onAvailable listeners will be called again\n availabilityStatus = AVAILABILITY_STATUSES.Unknown;\n };\n\n return {\n ...policy,\n circuitBreakerPolicy,\n circuitBreakDuration,\n getCircuitState,\n getRemainingCircuitOpenDuration,\n reset,\n retryPolicy,\n onBreak,\n onDegraded,\n onAvailable,\n onRetry,\n };\n}\n"]}
1
+ {"version":3,"file":"create-service-policy.cjs","sourceRoot":"","sources":["../src/create-service-policy.ts"],"names":[],"mappings":";;;AAAA,yCAYmB;AAgBjB,mGA3BA,8BAAkB,OA2BA;AAUlB,6FApCA,wBAAY,OAoCA;AALZ,sGA9BgB,wBAAqB,OA8BhB;AAerB,mGA3CA,8BAAkB,OA2CA;AALlB,gGArCA,2BAAe,OAqCA;AAWf,0FA9CA,qBAAS,OA8CA;AAMT,2FAnDA,sBAAU,OAmDA;AAwIZ;;;;GAIG;AACH,MAAM,qBAAqB,GAAG;IAC5B,SAAS,EAAE,WAAW;IACtB,QAAQ,EAAE,UAAU;IACpB,WAAW,EAAE,aAAa;IAC1B,OAAO,EAAE,SAAS;CACV,CAAC;AAUX;;;;;;GAMG;AACU,QAAA,mBAAmB,GAAG,CAAC,CAAC;AAErC;;;;;;;;GAQG;AACU,QAAA,gCAAgC,GAAG,CAAC,CAAC,GAAG,2BAAmB,CAAC,GAAG,CAAC,CAAC;AAE9E;;;;;;GAMG;AACU,QAAA,8BAA8B,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAE7D;;;;;;GAMG;AACU,QAAA,0BAA0B,GAAG,IAAK,CAAC;AAEhD,MAAM,uBAAuB,GAAG,CAAC,KAAc,EAAW,EAAE;IAC1D,IACE,OAAO,KAAK,KAAK,QAAQ;QACzB,KAAK,KAAK,IAAI;QACd,YAAY,IAA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BAAkB,CAAC,OAAO,EAAE,CAAC;QAE7B,2EAA2E;QAC3E,2DAA2D;QAC3D,kBAAkB,GAAG,qBAAqB,CAAC,OAAO,CAAC;IACrD,CAAC,CAAC;IAEF,OAAO;QACL,GAAG,MAAM;QACT,oBAAoB;QACpB,oBAAoB;QACpB,eAAe;QACf,+BAA+B;QAC/B,KAAK;QACL,WAAW;QACX,OAAO;QACP,UAAU;QACV,WAAW;QACX,OAAO;KACR,CAAC;AACJ,CAAC;AAxID,kDAwIC","sourcesContent":["import {\n BrokenCircuitError,\n CircuitState,\n EventEmitter as CockatielEventEmitter,\n ConsecutiveBreaker,\n ExponentialBackoff,\n ConstantBackoff,\n circuitBreaker,\n handleAll,\n handleWhen,\n retry,\n wrap,\n} from 'cockatiel';\nimport type {\n CircuitBreakerPolicy,\n Event as CockatielEvent,\n FailureReason,\n IBackoffFactory,\n IPolicy,\n Policy,\n RetryPolicy,\n} from 'cockatiel';\n\nexport {\n /**\n * @deprecated This is deprecated and will be removed in a future major\n * version. Please use the equivalent type from `@metamask/base-data-service`.\n */\n BrokenCircuitError,\n /**\n * @deprecated This is deprecated and will be removed in a future major\n * version. Please use the equivalent type from `@metamask/base-data-service`.\n */\n CockatielEventEmitter,\n /**\n * @deprecated This is deprecated and will be removed in a future major\n * version. Please use the equivalent type from `@metamask/base-data-service`.\n */\n CircuitState,\n /**\n * @deprecated This is deprecated and will be removed in a future major\n * version. Please use the equivalent type from `@metamask/base-data-service`.\n */\n ConstantBackoff,\n /**\n * @deprecated This is deprecated and will be removed in a future major\n * version. Please use the equivalent type from `@metamask/base-data-service`.\n */\n ExponentialBackoff,\n /**\n * @deprecated This is deprecated and will be removed in a future major\n * version. Please use the equivalent function from\n * `@metamask/base-data-service`.\n */\n handleAll,\n /**\n * @deprecated This is deprecated and will be removed in a future major\n * version. Please use the equivalent function from\n * `@metamask/base-data-service`.\n */\n handleWhen,\n};\n\nexport type {\n /**\n * @deprecated This is deprecated and will be removed in a future major\n * version. Please use the equivalent type from `@metamask/base-data-service`.\n */\n CockatielEvent,\n /**\n * @deprecated This is deprecated and will be removed in a future major\n * version. Please use the equivalent type from `@metamask/base-data-service`.\n */\n FailureReason as CockatielFailureReason,\n};\n\n/**\n * The options for `createServicePolicy`.\n *\n * @deprecated This is deprecated and will be removed in a future major version.\n * Please use the equivalent type from `@metamask/base-data-service`.\n */\nexport type CreateServicePolicyOptions = {\n /**\n * The backoff strategy to use. Mainly useful for testing so that a constant\n * backoff can be used when mocking timers. Defaults to an instance of\n * ExponentialBackoff.\n */\n backoff?: IBackoffFactory<unknown>;\n /**\n * The length of time (in milliseconds) to pause retries of the action after\n * the number of failures reaches `maxConsecutiveFailures`.\n */\n circuitBreakDuration?: number;\n /**\n * The length of time (in milliseconds) that governs when the service is\n * regarded as degraded (affecting when `onDegraded` is called).\n */\n degradedThreshold?: number;\n /**\n * Predicate function for when an error should be considered a service failure.\n */\n isServiceFailure?: (error: unknown) => boolean;\n /**\n * The maximum number of times that the service is allowed to fail before\n * pausing further retries.\n */\n maxConsecutiveFailures?: number;\n /**\n * The maximum number of times that a failing service should be re-invoked\n * before giving up.\n */\n maxRetries?: number;\n /**\n * The policy used to control when the service should be retried based on\n * either the result of the service or an error that it throws. For instance,\n * you could use this to retry only certain errors. See `handleWhen` and\n * friends from Cockatiel for more.\n */\n retryFilterPolicy?: Policy;\n};\n\n/**\n * The service policy object.\n *\n * @deprecated This is deprecated and will be removed in a future major\n * version. Please use the equivalent type from `@metamask/base-data-service`.\n */\nexport type ServicePolicy = IPolicy & {\n /**\n * The Cockatiel circuit breaker policy that the service policy uses\n * internally.\n */\n circuitBreakerPolicy: CircuitBreakerPolicy;\n /**\n * The amount of time to pause requests to the service if the number of\n * maximum consecutive failures is reached.\n */\n circuitBreakDuration: number;\n /**\n * @returns The state of the underlying circuit.\n */\n getCircuitState: () => CircuitState;\n /**\n * If the circuit is open and ongoing requests are paused, returns the number\n * of milliseconds before the requests will be attempted again. If the circuit\n * is not open, returns null.\n */\n getRemainingCircuitOpenDuration: () => number | null;\n /**\n * Resets the internal circuit breaker policy (if it is open, it will now be\n * closed).\n */\n reset: () => void;\n /**\n * The Cockatiel retry policy that the service policy uses internally.\n */\n retryPolicy: RetryPolicy;\n /**\n * A function which is called when the number of times that the service fails\n * in a row meets the set maximum number of consecutive failures.\n */\n onBreak: CircuitBreakerPolicy['onBreak'];\n /**\n * A function which is called in two circumstances: 1) when the service\n * succeeds before the maximum number of consecutive failures is reached, but\n * takes more time than the `degradedThreshold` to run, or 2) if the service\n * never succeeds before the retry policy gives up and before the maximum\n * number of consecutive failures has been reached.\n */\n onDegraded: CockatielEvent<FailureReason<unknown> | { duration: number }>;\n /**\n * A function which is called when the service succeeds for the first time,\n * or when the service fails enough times to cause the circuit to break and\n * then recovers.\n */\n onAvailable: CockatielEvent<void>;\n /**\n * A function which will be called by the retry policy each time the service\n * fails and the policy kicks off a timer to re-run the service. This is\n * primarily useful in tests where we are mocking timers.\n */\n onRetry: RetryPolicy['onRetry'];\n};\n\n/**\n * Parts of the circuit breaker's internal and external state as necessary in\n * order to compute the time remaining before the circuit will reopen.\n */\ntype InternalCircuitState =\n | {\n state: CircuitState.Open;\n openedAt: number;\n }\n | { state: Exclude<CircuitState, CircuitState.Open> };\n\n/**\n * Availability statuses that the service can be in.\n *\n * Used to keep track of whether the `onAvailable` event should be fired.\n */\nconst AVAILABILITY_STATUSES = {\n Available: 'available',\n Degraded: 'degraded',\n Unavailable: 'unavailable',\n Unknown: 'unknown',\n} as const;\n\n/**\n * Availability statuses that the service can be in.\n *\n * Used to keep track of whether the `onAvailable` event should be fired.\n */\ntype AvailabilityStatus =\n (typeof AVAILABILITY_STATUSES)[keyof typeof AVAILABILITY_STATUSES];\n\n/**\n * The maximum number of times that a failing service should be re-run before\n * giving up.\n *\n * @deprecated This is deprecated and will be removed in a future major version.\n * Please use the equivalent variable from `@metamask/base-data-service`.\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. This is set to a value such that if given a\n * service that continually fails, the policy needs to be executed 3 times\n * before further retries are paused.\n *\n * @deprecated This is deprecated and will be removed in a future major version.\n * Please use the equivalent variable from `@metamask/base-data-service`.\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 *\n * @deprecated This is deprecated and will be removed in a future major version.\n * Please use the equivalent variable from `@metamask/base-data-service`.\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 *\n * @deprecated This is deprecated and will be removed in a future major version.\n * Please use the equivalent variable from `@metamask/base-data-service`.\n */\nexport const DEFAULT_DEGRADED_THRESHOLD = 5_000;\n\nconst defaultIsServiceFailure = (error: unknown): boolean => {\n if (\n typeof error === 'object' &&\n error !== null &&\n 'httpStatus' in error &&\n typeof error.httpStatus === 'number'\n ) {\n return error.httpStatus >= 500;\n }\n\n // If the error is not an object, or doesn't have a numeric httpStatus\n // property, consider it a service failure (e.g., network errors, timeouts,\n // etc.)\n return true;\n};\n\n/**\n * The circuit breaker policy inside of the Cockatiel library exposes some of\n * its state, but not all of it. Notably, the time that the circuit opened is\n * not publicly accessible. So we have to record this ourselves.\n *\n * This function therefore allows us to obtain the circuit breaker state that we\n * wish we could access.\n *\n * @param state - The public state of a circuit breaker policy.\n * @returns if the circuit is open, the state of the circuit breaker policy plus\n * the time that it opened, otherwise just the circuit state.\n */\nfunction getInternalCircuitState(state: CircuitState): InternalCircuitState {\n if (state === CircuitState.Open) {\n return { state, openedAt: Date.now() };\n }\n return { state };\n}\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. See\n * {@link CreateServicePolicyOptions}.\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 * maxRetries: 3,\n * retryFilterPolicy: handleWhen((error) => {\n * return error.message.includes('oops');\n * }),\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 *\n * @deprecated This is deprecated and will be removed in a future major version.\n * Please use the equivalent function from `@metamask/base-data-service`.\n */\nexport function createServicePolicy(\n options: CreateServicePolicyOptions = {},\n): ServicePolicy {\n const {\n maxRetries = DEFAULT_MAX_RETRIES,\n retryFilterPolicy = handleAll,\n maxConsecutiveFailures = DEFAULT_MAX_CONSECUTIVE_FAILURES,\n circuitBreakDuration = DEFAULT_CIRCUIT_BREAK_DURATION,\n degradedThreshold = DEFAULT_DEGRADED_THRESHOLD,\n backoff = new ExponentialBackoff(),\n isServiceFailure = defaultIsServiceFailure,\n } = options;\n\n let availabilityStatus: AvailabilityStatus = AVAILABILITY_STATUSES.Unknown;\n\n const retryPolicy = retry(retryFilterPolicy, {\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: maxRetries,\n // Retries of the service will be executed following ever increasing delays,\n // determined by a backoff formula.\n backoff,\n });\n const onRetry = retryPolicy.onRetry.bind(retryPolicy);\n\n const consecutiveBreaker = new ConsecutiveBreaker(maxConsecutiveFailures);\n const circuitBreakerPolicy = circuitBreaker(handleWhen(isServiceFailure), {\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: consecutiveBreaker,\n });\n\n let internalCircuitState: InternalCircuitState = getInternalCircuitState(\n circuitBreakerPolicy.state,\n );\n circuitBreakerPolicy.onStateChange((state) => {\n internalCircuitState = getInternalCircuitState(state);\n });\n\n circuitBreakerPolicy.onBreak(() => {\n availabilityStatus = AVAILABILITY_STATUSES.Unavailable;\n });\n const onBreak = circuitBreakerPolicy.onBreak.bind(circuitBreakerPolicy);\n\n const onDegradedEventEmitter = new CockatielEventEmitter<\n FailureReason<unknown> | { duration: number }\n >();\n const onDegraded = onDegradedEventEmitter.addListener;\n\n const onAvailableEventEmitter = new CockatielEventEmitter<void>();\n const onAvailable = onAvailableEventEmitter.addListener;\n\n retryPolicy.onGiveUp((data) => {\n if (circuitBreakerPolicy.state === CircuitState.Closed) {\n availabilityStatus = AVAILABILITY_STATUSES.Degraded;\n onDegradedEventEmitter.emit(data);\n }\n });\n retryPolicy.onSuccess(({ duration }) => {\n if (circuitBreakerPolicy.state === CircuitState.Closed) {\n if (duration > degradedThreshold) {\n availabilityStatus = AVAILABILITY_STATUSES.Degraded;\n onDegradedEventEmitter.emit({ duration });\n } else if (availabilityStatus !== AVAILABILITY_STATUSES.Available) {\n availabilityStatus = AVAILABILITY_STATUSES.Available;\n onAvailableEventEmitter.emit();\n }\n }\n });\n\n // Every time the retry policy makes an attempt, it executes the circuit\n // breaker policy, which executes the service.\n //\n // Calling:\n //\n // policy.execute(() => {\n // // do what the service does\n // })\n //\n // is equivalent to:\n //\n // retryPolicy.execute(() => {\n // circuitBreakerPolicy.execute(() => {\n // // do what the service does\n // });\n // });\n //\n // So if the retry policy succeeds or fails, it is because the circuit breaker\n // policy succeeded or failed. And if there are any event listeners registered\n // on the retry policy, by the time they are called, the state of the circuit\n // breaker will have already changed.\n const policy = wrap(retryPolicy, circuitBreakerPolicy);\n\n const getRemainingCircuitOpenDuration = (): number | null => {\n if (internalCircuitState.state === CircuitState.Open) {\n return internalCircuitState.openedAt + circuitBreakDuration - Date.now();\n }\n return null;\n };\n\n const getCircuitState = (): CircuitState => {\n return circuitBreakerPolicy.state;\n };\n\n const reset = (): void => {\n // Set the state of the policy to \"isolated\" regardless of its current state\n const { dispose } = circuitBreakerPolicy.isolate();\n // Reset the state to \"closed\"\n dispose();\n\n // Reset the counter on the breaker as well\n consecutiveBreaker.success();\n\n // Re-initialize the availability status so that if the service is executed\n // successfully, onAvailable listeners will be called again\n availabilityStatus = AVAILABILITY_STATUSES.Unknown;\n };\n\n return {\n ...policy,\n circuitBreakerPolicy,\n circuitBreakDuration,\n getCircuitState,\n getRemainingCircuitOpenDuration,\n reset,\n retryPolicy,\n onBreak,\n onDegraded,\n onAvailable,\n onRetry,\n };\n}\n"]}
@@ -1,9 +1,59 @@
1
1
  import { BrokenCircuitError, CircuitState, EventEmitter as CockatielEventEmitter, ExponentialBackoff, ConstantBackoff, handleAll, handleWhen } from "cockatiel";
2
2
  import type { CircuitBreakerPolicy, Event as CockatielEvent, FailureReason, IBackoffFactory, IPolicy, Policy, RetryPolicy } from "cockatiel";
3
- export { BrokenCircuitError, CockatielEventEmitter, CircuitState, ConstantBackoff, ExponentialBackoff, handleAll, handleWhen, };
4
- export type { CockatielEvent, FailureReason as CockatielFailureReason };
3
+ export {
4
+ /**
5
+ * @deprecated This is deprecated and will be removed in a future major
6
+ * version. Please use the equivalent type from `@metamask/base-data-service`.
7
+ */
8
+ BrokenCircuitError,
9
+ /**
10
+ * @deprecated This is deprecated and will be removed in a future major
11
+ * version. Please use the equivalent type from `@metamask/base-data-service`.
12
+ */
13
+ CockatielEventEmitter,
14
+ /**
15
+ * @deprecated This is deprecated and will be removed in a future major
16
+ * version. Please use the equivalent type from `@metamask/base-data-service`.
17
+ */
18
+ CircuitState,
19
+ /**
20
+ * @deprecated This is deprecated and will be removed in a future major
21
+ * version. Please use the equivalent type from `@metamask/base-data-service`.
22
+ */
23
+ ConstantBackoff,
24
+ /**
25
+ * @deprecated This is deprecated and will be removed in a future major
26
+ * version. Please use the equivalent type from `@metamask/base-data-service`.
27
+ */
28
+ ExponentialBackoff,
29
+ /**
30
+ * @deprecated This is deprecated and will be removed in a future major
31
+ * version. Please use the equivalent function from
32
+ * `@metamask/base-data-service`.
33
+ */
34
+ handleAll,
35
+ /**
36
+ * @deprecated This is deprecated and will be removed in a future major
37
+ * version. Please use the equivalent function from
38
+ * `@metamask/base-data-service`.
39
+ */
40
+ handleWhen, };
41
+ export type {
42
+ /**
43
+ * @deprecated This is deprecated and will be removed in a future major
44
+ * version. Please use the equivalent type from `@metamask/base-data-service`.
45
+ */
46
+ CockatielEvent,
47
+ /**
48
+ * @deprecated This is deprecated and will be removed in a future major
49
+ * version. Please use the equivalent type from `@metamask/base-data-service`.
50
+ */
51
+ FailureReason as CockatielFailureReason, };
5
52
  /**
6
53
  * The options for `createServicePolicy`.
54
+ *
55
+ * @deprecated This is deprecated and will be removed in a future major version.
56
+ * Please use the equivalent type from `@metamask/base-data-service`.
7
57
  */
8
58
  export type CreateServicePolicyOptions = {
9
59
  /**
@@ -46,6 +96,9 @@ export type CreateServicePolicyOptions = {
46
96
  };
47
97
  /**
48
98
  * The service policy object.
99
+ *
100
+ * @deprecated This is deprecated and will be removed in a future major
101
+ * version. Please use the equivalent type from `@metamask/base-data-service`.
49
102
  */
50
103
  export type ServicePolicy = IPolicy & {
51
104
  /**
@@ -108,6 +161,9 @@ export type ServicePolicy = IPolicy & {
108
161
  /**
109
162
  * The maximum number of times that a failing service should be re-run before
110
163
  * giving up.
164
+ *
165
+ * @deprecated This is deprecated and will be removed in a future major version.
166
+ * Please use the equivalent variable from `@metamask/base-data-service`.
111
167
  */
112
168
  export declare const DEFAULT_MAX_RETRIES = 3;
113
169
  /**
@@ -115,16 +171,25 @@ export declare const DEFAULT_MAX_RETRIES = 3;
115
171
  * pausing further retries. This is set to a value such that if given a
116
172
  * service that continually fails, the policy needs to be executed 3 times
117
173
  * before further retries are paused.
174
+ *
175
+ * @deprecated This is deprecated and will be removed in a future major version.
176
+ * Please use the equivalent variable from `@metamask/base-data-service`.
118
177
  */
119
178
  export declare const DEFAULT_MAX_CONSECUTIVE_FAILURES: number;
120
179
  /**
121
180
  * The default length of time (in milliseconds) to temporarily pause retries of
122
181
  * the service after enough consecutive failures.
182
+ *
183
+ * @deprecated This is deprecated and will be removed in a future major version.
184
+ * Please use the equivalent variable from `@metamask/base-data-service`.
123
185
  */
124
186
  export declare const DEFAULT_CIRCUIT_BREAK_DURATION: number;
125
187
  /**
126
188
  * The default length of time (in milliseconds) that governs when the service is
127
189
  * regarded as degraded (affecting when `onDegraded` is called).
190
+ *
191
+ * @deprecated This is deprecated and will be removed in a future major version.
192
+ * Please use the equivalent variable from `@metamask/base-data-service`.
128
193
  */
129
194
  export declare const DEFAULT_DEGRADED_THRESHOLD = 5000;
130
195
  /**
@@ -176,6 +241,9 @@ export declare const DEFAULT_DEGRADED_THRESHOLD = 5000;
176
241
  * }
177
242
  * }
178
243
  * ```
244
+ *
245
+ * @deprecated This is deprecated and will be removed in a future major version.
246
+ * Please use the equivalent function from `@metamask/base-data-service`.
179
247
  */
180
248
  export declare function createServicePolicy(options?: CreateServicePolicyOptions): ServicePolicy;
181
249
  //# 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":"AAAA,OAAO,EACL,kBAAkB,EAClB,YAAY,EACZ,YAAY,IAAI,qBAAqB,EAErC,kBAAkB,EAClB,eAAe,EAEf,SAAS,EAC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,UAAU,EAAE,cAAc,CAAC,aAAa,CAAC,OAAO,CAAC,GAAG;QAAE,QAAQ,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAC1E;;;;OAIG;IACH,WAAW,EAAE,cAAc,CAAC,IAAI,CAAC,CAAC;IAClC;;;;OAIG;IACH,OAAO,EAAE,WAAW,CAAC,SAAS,CAAC,CAAC;CACjC,CAAC;AAiCF;;;GAGG;AACH,eAAO,MAAM,mBAAmB,IAAI,CAAC;AAErC;;;;;GAKG;AACH,eAAO,MAAM,gCAAgC,QAAgC,CAAC;AAE9E;;;GAGG;AACH,eAAO,MAAM,8BAA8B,QAAiB,CAAC;AAE7D;;;GAGG;AACH,eAAO,MAAM,0BAA0B,OAAQ,CAAC;AAqChD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiDG;AACH,wBAAgB,mBAAmB,CACjC,OAAO,GAAE,0BAA+B,GACvC,aAAa,CAsIf"}
1
+ {"version":3,"file":"create-service-policy.d.cts","sourceRoot":"","sources":["../src/create-service-policy.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,YAAY,EACZ,YAAY,IAAI,qBAAqB,EAErC,kBAAkB,EAClB,eAAe,EAEf,SAAS,EACT,UAAU,EAGX,kBAAkB;AACnB,OAAO,KAAK,EACV,oBAAoB,EACpB,KAAK,IAAI,cAAc,EACvB,aAAa,EACb,eAAe,EACf,OAAO,EACP,MAAM,EACN,WAAW,EACZ,kBAAkB;AAEnB,OAAO;AACL;;;GAGG;AACH,kBAAkB;AAClB;;;GAGG;AACH,qBAAqB;AACrB;;;GAGG;AACH,YAAY;AACZ;;;GAGG;AACH,eAAe;AACf;;;GAGG;AACH,kBAAkB;AAClB;;;;GAIG;AACH,SAAS;AACT;;;;GAIG;AACH,UAAU,GACX,CAAC;AAEF,YAAY;AACV;;;GAGG;AACH,cAAc;AACd;;;GAGG;AACH,aAAa,IAAI,sBAAsB,GACxC,CAAC;AAEF;;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H,eAAO,MAAM,gCAAgC,QAAgC,CAAC;AAE9E;;;;;;GAMG;AACH,eAAO,MAAM,8BAA8B,QAAiB,CAAC;AAE7D;;;;;;GAMG;AACH,eAAO,MAAM,0BAA0B,OAAQ,CAAC;AAqChD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoDG;AACH,wBAAgB,mBAAmB,CACjC,OAAO,GAAE,0BAA+B,GACvC,aAAa,CAsIf"}
@@ -1,9 +1,59 @@
1
1
  import { BrokenCircuitError, CircuitState, EventEmitter as CockatielEventEmitter, ExponentialBackoff, ConstantBackoff, handleAll, handleWhen } from "cockatiel";
2
2
  import type { CircuitBreakerPolicy, Event as CockatielEvent, FailureReason, IBackoffFactory, IPolicy, Policy, RetryPolicy } from "cockatiel";
3
- export { BrokenCircuitError, CockatielEventEmitter, CircuitState, ConstantBackoff, ExponentialBackoff, handleAll, handleWhen, };
4
- export type { CockatielEvent, FailureReason as CockatielFailureReason };
3
+ export {
4
+ /**
5
+ * @deprecated This is deprecated and will be removed in a future major
6
+ * version. Please use the equivalent type from `@metamask/base-data-service`.
7
+ */
8
+ BrokenCircuitError,
9
+ /**
10
+ * @deprecated This is deprecated and will be removed in a future major
11
+ * version. Please use the equivalent type from `@metamask/base-data-service`.
12
+ */
13
+ CockatielEventEmitter,
14
+ /**
15
+ * @deprecated This is deprecated and will be removed in a future major
16
+ * version. Please use the equivalent type from `@metamask/base-data-service`.
17
+ */
18
+ CircuitState,
19
+ /**
20
+ * @deprecated This is deprecated and will be removed in a future major
21
+ * version. Please use the equivalent type from `@metamask/base-data-service`.
22
+ */
23
+ ConstantBackoff,
24
+ /**
25
+ * @deprecated This is deprecated and will be removed in a future major
26
+ * version. Please use the equivalent type from `@metamask/base-data-service`.
27
+ */
28
+ ExponentialBackoff,
29
+ /**
30
+ * @deprecated This is deprecated and will be removed in a future major
31
+ * version. Please use the equivalent function from
32
+ * `@metamask/base-data-service`.
33
+ */
34
+ handleAll,
35
+ /**
36
+ * @deprecated This is deprecated and will be removed in a future major
37
+ * version. Please use the equivalent function from
38
+ * `@metamask/base-data-service`.
39
+ */
40
+ handleWhen, };
41
+ export type {
42
+ /**
43
+ * @deprecated This is deprecated and will be removed in a future major
44
+ * version. Please use the equivalent type from `@metamask/base-data-service`.
45
+ */
46
+ CockatielEvent,
47
+ /**
48
+ * @deprecated This is deprecated and will be removed in a future major
49
+ * version. Please use the equivalent type from `@metamask/base-data-service`.
50
+ */
51
+ FailureReason as CockatielFailureReason, };
5
52
  /**
6
53
  * The options for `createServicePolicy`.
54
+ *
55
+ * @deprecated This is deprecated and will be removed in a future major version.
56
+ * Please use the equivalent type from `@metamask/base-data-service`.
7
57
  */
8
58
  export type CreateServicePolicyOptions = {
9
59
  /**
@@ -46,6 +96,9 @@ export type CreateServicePolicyOptions = {
46
96
  };
47
97
  /**
48
98
  * The service policy object.
99
+ *
100
+ * @deprecated This is deprecated and will be removed in a future major
101
+ * version. Please use the equivalent type from `@metamask/base-data-service`.
49
102
  */
50
103
  export type ServicePolicy = IPolicy & {
51
104
  /**
@@ -108,6 +161,9 @@ export type ServicePolicy = IPolicy & {
108
161
  /**
109
162
  * The maximum number of times that a failing service should be re-run before
110
163
  * giving up.
164
+ *
165
+ * @deprecated This is deprecated and will be removed in a future major version.
166
+ * Please use the equivalent variable from `@metamask/base-data-service`.
111
167
  */
112
168
  export declare const DEFAULT_MAX_RETRIES = 3;
113
169
  /**
@@ -115,16 +171,25 @@ export declare const DEFAULT_MAX_RETRIES = 3;
115
171
  * pausing further retries. This is set to a value such that if given a
116
172
  * service that continually fails, the policy needs to be executed 3 times
117
173
  * before further retries are paused.
174
+ *
175
+ * @deprecated This is deprecated and will be removed in a future major version.
176
+ * Please use the equivalent variable from `@metamask/base-data-service`.
118
177
  */
119
178
  export declare const DEFAULT_MAX_CONSECUTIVE_FAILURES: number;
120
179
  /**
121
180
  * The default length of time (in milliseconds) to temporarily pause retries of
122
181
  * the service after enough consecutive failures.
182
+ *
183
+ * @deprecated This is deprecated and will be removed in a future major version.
184
+ * Please use the equivalent variable from `@metamask/base-data-service`.
123
185
  */
124
186
  export declare const DEFAULT_CIRCUIT_BREAK_DURATION: number;
125
187
  /**
126
188
  * The default length of time (in milliseconds) that governs when the service is
127
189
  * regarded as degraded (affecting when `onDegraded` is called).
190
+ *
191
+ * @deprecated This is deprecated and will be removed in a future major version.
192
+ * Please use the equivalent variable from `@metamask/base-data-service`.
128
193
  */
129
194
  export declare const DEFAULT_DEGRADED_THRESHOLD = 5000;
130
195
  /**
@@ -176,6 +241,9 @@ export declare const DEFAULT_DEGRADED_THRESHOLD = 5000;
176
241
  * }
177
242
  * }
178
243
  * ```
244
+ *
245
+ * @deprecated This is deprecated and will be removed in a future major version.
246
+ * Please use the equivalent function from `@metamask/base-data-service`.
179
247
  */
180
248
  export declare function createServicePolicy(options?: CreateServicePolicyOptions): ServicePolicy;
181
249
  //# 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":"AAAA,OAAO,EACL,kBAAkB,EAClB,YAAY,EACZ,YAAY,IAAI,qBAAqB,EAErC,kBAAkB,EAClB,eAAe,EAEf,SAAS,EACT,UAAU,EAGX,kBAAkB;AACnB,OAAO,KAAK,EACV,oBAAoB,EACpB,KAAK,IAAI,cAAc,EACvB,aAAa,EACb,eAAe,EACf,OAAO,EACP,MAAM,EACN,WAAW,EACZ,kBAAkB;AAEnB,OAAO,EACL,kBAAkB,EAClB,qBAAqB,EACrB,YAAY,EACZ,eAAe,EACf,kBAAkB,EAClB,SAAS,EACT,UAAU,GACX,CAAC;AAEF,YAAY,EAAE,cAAc,EAAE,aAAa,IAAI,sBAAsB,EAAE,CAAC;AAExE;;GAEG;AACH,MAAM,MAAM,0BAA0B,GAAG;IACvC;;;;OAIG;IACH,OAAO,CAAC,EAAE,eAAe,CAAC,OAAO,CAAC,CAA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AAM,0BAA0B,OAAQ,CAAC;AAqChD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiDG;AACH,wBAAgB,mBAAmB,CACjC,OAAO,GAAE,0BAA+B,GACvC,aAAa,CAsIf"}
1
+ {"version":3,"file":"create-service-policy.d.mts","sourceRoot":"","sources":["../src/create-service-policy.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,YAAY,EACZ,YAAY,IAAI,qBAAqB,EAErC,kBAAkB,EAClB,eAAe,EAEf,SAAS,EACT,UAAU,EAGX,kBAAkB;AACnB,OAAO,KAAK,EACV,oBAAoB,EACpB,KAAK,IAAI,cAAc,EACvB,aAAa,EACb,eAAe,EACf,OAAO,EACP,MAAM,EACN,WAAW,EACZ,kBAAkB;AAEnB,OAAO;AACL;;;GAGG;AACH,kBAAkB;AAClB;;;GAGG;AACH,qBAAqB;AACrB;;;GAGG;AACH,YAAY;AACZ;;;GAGG;AACH,eAAe;AACf;;;GAGG;AACH,kBAAkB;AAClB;;;;GAIG;AACH,SAAS;AACT;;;;GAIG;AACH,UAAU,GACX,CAAC;AAEF,YAAY;AACV;;;GAGG;AACH,cAAc;AACd;;;GAGG;AACH,aAAa,IAAI,sBAAsB,GACxC,CAAC;AAEF;;;;;GAKG;AACH,MAAM,MAAM,0BAA0B,GAAG;IACvC;;;;OAIG;IACH,OAAO,CAAC,EAAE,eAAe,CAAC,OAAO,CAAC,CAAC;IACnC;;;OAGG;IACH,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B;;;OAGG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B;;OAEG;IACH,gBAAgB,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,OAAO,CAAC;IAC/C;;;OAGG;IACH,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;;;OAKG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC5B,CAAC;AAEF;;;;;GAKG;AACH,MAAM,MAAM,aAAa,GAAG,OAAO,GAAG;IACpC;;;OAGG;IACH,oBAAoB,EAAE,oBAAoB,CAAC;IAC3C;;;OAGG;IACH,oBAAoB,EAAE,MAAM,CAAC;IAC7B;;OAEG;IACH,eAAe,EAAE,MAAM,YAAY,CAAC;IACpC;;;;OAIG;IACH,+BAA+B,EAAE,MAAM,MAAM,GAAG,IAAI,CAAC;IACrD;;;OAGG;IACH,KAAK,EAAE,MAAM,IAAI,CAAC;IAClB;;OAEG;IACH,WAAW,EAAE,WAAW,CAAC;IACzB;;;OAGG;IACH,OAAO,EAAE,oBAAoB,CAAC,SAAS,CAAC,CAAC;IACzC;;;;;;OAMG;IACH,UAAU,EAAE,cAAc,CAAC,aAAa,CAAC,OAAO,CAAC,GAAG;QAAE,QAAQ,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAC1E;;;;OAIG;IACH,WAAW,EAAE,cAAc,CAAC,IAAI,CAAC,CAAC;IAClC;;;;OAIG;IACH,OAAO,EAAE,WAAW,CAAC,SAAS,CAAC,CAAC;CACjC,CAAC;AAiCF;;;;;;GAMG;AACH,eAAO,MAAM,mBAAmB,IAAI,CAAC;AAErC;;;;;;;;GAQG;AACH,eAAO,MAAM,gCAAgC,QAAgC,CAAC;AAE9E;;;;;;GAMG;AACH,eAAO,MAAM,8BAA8B,QAAiB,CAAC;AAE7D;;;;;;GAMG;AACH,eAAO,MAAM,0BAA0B,OAAQ,CAAC;AAqChD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoDG;AACH,wBAAgB,mBAAmB,CACjC,OAAO,GAAE,0BAA+B,GACvC,aAAa,CAsIf"}
@@ -1,5 +1,42 @@
1
1
  import { BrokenCircuitError, CircuitState, EventEmitter as CockatielEventEmitter, ConsecutiveBreaker, ExponentialBackoff, ConstantBackoff, circuitBreaker, handleAll, handleWhen, retry, wrap } from "cockatiel";
2
- export { BrokenCircuitError, CockatielEventEmitter, CircuitState, ConstantBackoff, ExponentialBackoff, handleAll, handleWhen };
2
+ export {
3
+ /**
4
+ * @deprecated This is deprecated and will be removed in a future major
5
+ * version. Please use the equivalent type from `@metamask/base-data-service`.
6
+ */
7
+ BrokenCircuitError,
8
+ /**
9
+ * @deprecated This is deprecated and will be removed in a future major
10
+ * version. Please use the equivalent type from `@metamask/base-data-service`.
11
+ */
12
+ CockatielEventEmitter,
13
+ /**
14
+ * @deprecated This is deprecated and will be removed in a future major
15
+ * version. Please use the equivalent type from `@metamask/base-data-service`.
16
+ */
17
+ CircuitState,
18
+ /**
19
+ * @deprecated This is deprecated and will be removed in a future major
20
+ * version. Please use the equivalent type from `@metamask/base-data-service`.
21
+ */
22
+ ConstantBackoff,
23
+ /**
24
+ * @deprecated This is deprecated and will be removed in a future major
25
+ * version. Please use the equivalent type from `@metamask/base-data-service`.
26
+ */
27
+ ExponentialBackoff,
28
+ /**
29
+ * @deprecated This is deprecated and will be removed in a future major
30
+ * version. Please use the equivalent function from
31
+ * `@metamask/base-data-service`.
32
+ */
33
+ handleAll,
34
+ /**
35
+ * @deprecated This is deprecated and will be removed in a future major
36
+ * version. Please use the equivalent function from
37
+ * `@metamask/base-data-service`.
38
+ */
39
+ handleWhen };
3
40
  /**
4
41
  * Availability statuses that the service can be in.
5
42
  *
@@ -14,6 +51,9 @@ const AVAILABILITY_STATUSES = {
14
51
  /**
15
52
  * The maximum number of times that a failing service should be re-run before
16
53
  * giving up.
54
+ *
55
+ * @deprecated This is deprecated and will be removed in a future major version.
56
+ * Please use the equivalent variable from `@metamask/base-data-service`.
17
57
  */
18
58
  export const DEFAULT_MAX_RETRIES = 3;
19
59
  /**
@@ -21,16 +61,25 @@ export const DEFAULT_MAX_RETRIES = 3;
21
61
  * pausing further retries. This is set to a value such that if given a
22
62
  * service that continually fails, the policy needs to be executed 3 times
23
63
  * before further retries are paused.
64
+ *
65
+ * @deprecated This is deprecated and will be removed in a future major version.
66
+ * Please use the equivalent variable from `@metamask/base-data-service`.
24
67
  */
25
68
  export const DEFAULT_MAX_CONSECUTIVE_FAILURES = (1 + DEFAULT_MAX_RETRIES) * 3;
26
69
  /**
27
70
  * The default length of time (in milliseconds) to temporarily pause retries of
28
71
  * the service after enough consecutive failures.
72
+ *
73
+ * @deprecated This is deprecated and will be removed in a future major version.
74
+ * Please use the equivalent variable from `@metamask/base-data-service`.
29
75
  */
30
76
  export const DEFAULT_CIRCUIT_BREAK_DURATION = 30 * 60 * 1000;
31
77
  /**
32
78
  * The default length of time (in milliseconds) that governs when the service is
33
79
  * regarded as degraded (affecting when `onDegraded` is called).
80
+ *
81
+ * @deprecated This is deprecated and will be removed in a future major version.
82
+ * Please use the equivalent variable from `@metamask/base-data-service`.
34
83
  */
35
84
  export const DEFAULT_DEGRADED_THRESHOLD = 5000;
36
85
  const defaultIsServiceFailure = (error) => {
@@ -112,6 +161,9 @@ function getInternalCircuitState(state) {
112
161
  * }
113
162
  * }
114
163
  * ```
164
+ *
165
+ * @deprecated This is deprecated and will be removed in a future major version.
166
+ * Please use the equivalent function from `@metamask/base-data-service`.
115
167
  */
116
168
  export function createServicePolicy(options = {}) {
117
169
  const { maxRetries = DEFAULT_MAX_RETRIES, retryFilterPolicy = handleAll, maxConsecutiveFailures = DEFAULT_MAX_CONSECUTIVE_FAILURES, circuitBreakDuration = DEFAULT_CIRCUIT_BREAK_DURATION, degradedThreshold = DEFAULT_DEGRADED_THRESHOLD, backoff = new ExponentialBackoff(), isServiceFailure = defaultIsServiceFailure, } = options;
@@ -1 +1 @@
1
- {"version":3,"file":"create-service-policy.mjs","sourceRoot":"","sources":["../src/create-service-policy.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,YAAY,EACZ,YAAY,IAAI,qBAAqB,EACrC,kBAAkB,EAClB,kBAAkB,EAClB,eAAe,EACf,cAAc,EACd,SAAS,EACT,UAAU,EACV,KAAK,EACL,IAAI,EACL,kBA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pC,UAAU;IACV,QAAQ;IACR,EAAE;IACF,8EAA8E;IAC9E,8EAA8E;IAC9E,6EAA6E;IAC7E,qCAAqC;IACrC,MAAM,MAAM,GAAG,IAAI,CAAC,WAAW,EAAE,oBAAoB,CAAC,CAAC;IAEvD,MAAM,+BAA+B,GAAG,GAAkB,EAAE;QAC1D,IAAI,oBAAoB,CAAC,KAAK,KAAK,YAAY,CAAC,IAAI,EAAE,CAAC;YACrD,OAAO,oBAAoB,CAAC,QAAQ,GAAG,oBAAoB,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QAC3E,CAAC;QACD,OAAO,IAAI,CAAC;IACd,CAAC,CAAC;IAEF,MAAM,eAAe,GAAG,GAAiB,EAAE;QACzC,OAAO,oBAAoB,CAAC,KAAK,CAAC;IACpC,CAAC,CAAC;IAEF,MAAM,KAAK,GAAG,GAAS,EAAE;QACvB,4EAA4E;QAC5E,MAAM,EAAE,OAAO,EAAE,GAAG,oBAAoB,CAAC,OAAO,EAAE,CAAC;QACnD,8BAA8B;QAC9B,OAAO,EAAE,CAAC;QAEV,2CAA2C;QAC3C,kBAAkB,CAAC,OAAO,EAAE,CAAC;QAE7B,2EAA2E;QAC3E,2DAA2D;QAC3D,kBAAkB,GAAG,qBAAqB,CAAC,OAAO,CAAC;IACrD,CAAC,CAAC;IAEF,OAAO;QACL,GAAG,MAAM;QACT,oBAAoB;QACpB,oBAAoB;QACpB,eAAe;QACf,+BAA+B;QAC/B,KAAK;QACL,WAAW;QACX,OAAO;QACP,UAAU;QACV,WAAW;QACX,OAAO;KACR,CAAC;AACJ,CAAC","sourcesContent":["import {\n BrokenCircuitError,\n CircuitState,\n EventEmitter as CockatielEventEmitter,\n ConsecutiveBreaker,\n ExponentialBackoff,\n ConstantBackoff,\n circuitBreaker,\n handleAll,\n handleWhen,\n retry,\n wrap,\n} from 'cockatiel';\nimport type {\n CircuitBreakerPolicy,\n Event as CockatielEvent,\n FailureReason,\n IBackoffFactory,\n IPolicy,\n Policy,\n RetryPolicy,\n} from 'cockatiel';\n\nexport {\n BrokenCircuitError,\n CockatielEventEmitter,\n CircuitState,\n ConstantBackoff,\n ExponentialBackoff,\n handleAll,\n handleWhen,\n};\n\nexport type { CockatielEvent, FailureReason as CockatielFailureReason };\n\n/**\n * The options for `createServicePolicy`.\n */\nexport type CreateServicePolicyOptions = {\n /**\n * The backoff strategy to use. Mainly useful for testing so that a constant\n * backoff can be used when mocking timers. Defaults to an instance of\n * ExponentialBackoff.\n */\n backoff?: IBackoffFactory<unknown>;\n /**\n * The length of time (in milliseconds) to pause retries of the action after\n * the number of failures reaches `maxConsecutiveFailures`.\n */\n circuitBreakDuration?: number;\n /**\n * The length of time (in milliseconds) that governs when the service is\n * regarded as degraded (affecting when `onDegraded` is called).\n */\n degradedThreshold?: number;\n /**\n * Predicate function for when an error should be considered a service failure.\n */\n isServiceFailure?: (error: unknown) => boolean;\n /**\n * The maximum number of times that the service is allowed to fail before\n * pausing further retries.\n */\n maxConsecutiveFailures?: number;\n /**\n * The maximum number of times that a failing service should be re-invoked\n * before giving up.\n */\n maxRetries?: number;\n /**\n * The policy used to control when the service should be retried based on\n * either the result of the service or an error that it throws. For instance,\n * you could use this to retry only certain errors. See `handleWhen` and\n * friends from Cockatiel for more.\n */\n retryFilterPolicy?: Policy;\n};\n\n/**\n * The service policy object.\n */\nexport type ServicePolicy = IPolicy & {\n /**\n * The Cockatiel circuit breaker policy that the service policy uses\n * internally.\n */\n circuitBreakerPolicy: CircuitBreakerPolicy;\n /**\n * The amount of time to pause requests to the service if the number of\n * maximum consecutive failures is reached.\n */\n circuitBreakDuration: number;\n /**\n * @returns The state of the underlying circuit.\n */\n getCircuitState: () => CircuitState;\n /**\n * If the circuit is open and ongoing requests are paused, returns the number\n * of milliseconds before the requests will be attempted again. If the circuit\n * is not open, returns null.\n */\n getRemainingCircuitOpenDuration: () => number | null;\n /**\n * Resets the internal circuit breaker policy (if it is open, it will now be\n * closed).\n */\n reset: () => void;\n /**\n * The Cockatiel retry policy that the service policy uses internally.\n */\n retryPolicy: RetryPolicy;\n /**\n * A function which is called when the number of times that the service fails\n * in a row meets the set maximum number of consecutive failures.\n */\n onBreak: CircuitBreakerPolicy['onBreak'];\n /**\n * A function which is called in two circumstances: 1) when the service\n * succeeds before the maximum number of consecutive failures is reached, but\n * takes more time than the `degradedThreshold` to run, or 2) if the service\n * never succeeds before the retry policy gives up and before the maximum\n * number of consecutive failures has been reached.\n */\n onDegraded: CockatielEvent<FailureReason<unknown> | { duration: number }>;\n /**\n * A function which is called when the service succeeds for the first time,\n * or when the service fails enough times to cause the circuit to break and\n * then recovers.\n */\n onAvailable: CockatielEvent<void>;\n /**\n * A function which will be called by the retry policy each time the service\n * fails and the policy kicks off a timer to re-run the service. This is\n * primarily useful in tests where we are mocking timers.\n */\n onRetry: RetryPolicy['onRetry'];\n};\n\n/**\n * Parts of the circuit breaker's internal and external state as necessary in\n * order to compute the time remaining before the circuit will reopen.\n */\ntype InternalCircuitState =\n | {\n state: CircuitState.Open;\n openedAt: number;\n }\n | { state: Exclude<CircuitState, CircuitState.Open> };\n\n/**\n * Availability statuses that the service can be in.\n *\n * Used to keep track of whether the `onAvailable` event should be fired.\n */\nconst AVAILABILITY_STATUSES = {\n Available: 'available',\n Degraded: 'degraded',\n Unavailable: 'unavailable',\n Unknown: 'unknown',\n} as const;\n\n/**\n * Availability statuses that the service can be in.\n *\n * Used to keep track of whether the `onAvailable` event should be fired.\n */\ntype AvailabilityStatus =\n (typeof AVAILABILITY_STATUSES)[keyof typeof AVAILABILITY_STATUSES];\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. This is set to a value such that if given a\n * service that continually fails, the policy needs to be executed 3 times\n * before further retries are paused.\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\nconst defaultIsServiceFailure = (error: unknown): boolean => {\n if (\n typeof error === 'object' &&\n error !== null &&\n 'httpStatus' in error &&\n typeof error.httpStatus === 'number'\n ) {\n return error.httpStatus >= 500;\n }\n\n // If the error is not an object, or doesn't have a numeric httpStatus\n // property, consider it a service failure (e.g., network errors, timeouts,\n // etc.)\n return true;\n};\n\n/**\n * The circuit breaker policy inside of the Cockatiel library exposes some of\n * its state, but not all of it. Notably, the time that the circuit opened is\n * not publicly accessible. So we have to record this ourselves.\n *\n * This function therefore allows us to obtain the circuit breaker state that we\n * wish we could access.\n *\n * @param state - The public state of a circuit breaker policy.\n * @returns if the circuit is open, the state of the circuit breaker policy plus\n * the time that it opened, otherwise just the circuit state.\n */\nfunction getInternalCircuitState(state: CircuitState): InternalCircuitState {\n if (state === CircuitState.Open) {\n return { state, openedAt: Date.now() };\n }\n return { state };\n}\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. See\n * {@link CreateServicePolicyOptions}.\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 * maxRetries: 3,\n * retryFilterPolicy: handleWhen((error) => {\n * return error.message.includes('oops');\n * }),\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 options: CreateServicePolicyOptions = {},\n): ServicePolicy {\n const {\n maxRetries = DEFAULT_MAX_RETRIES,\n retryFilterPolicy = handleAll,\n maxConsecutiveFailures = DEFAULT_MAX_CONSECUTIVE_FAILURES,\n circuitBreakDuration = DEFAULT_CIRCUIT_BREAK_DURATION,\n degradedThreshold = DEFAULT_DEGRADED_THRESHOLD,\n backoff = new ExponentialBackoff(),\n isServiceFailure = defaultIsServiceFailure,\n } = options;\n\n let availabilityStatus: AvailabilityStatus = AVAILABILITY_STATUSES.Unknown;\n\n const retryPolicy = retry(retryFilterPolicy, {\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: maxRetries,\n // Retries of the service will be executed following ever increasing delays,\n // determined by a backoff formula.\n backoff,\n });\n const onRetry = retryPolicy.onRetry.bind(retryPolicy);\n\n const consecutiveBreaker = new ConsecutiveBreaker(maxConsecutiveFailures);\n const circuitBreakerPolicy = circuitBreaker(handleWhen(isServiceFailure), {\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: consecutiveBreaker,\n });\n\n let internalCircuitState: InternalCircuitState = getInternalCircuitState(\n circuitBreakerPolicy.state,\n );\n circuitBreakerPolicy.onStateChange((state) => {\n internalCircuitState = getInternalCircuitState(state);\n });\n\n circuitBreakerPolicy.onBreak(() => {\n availabilityStatus = AVAILABILITY_STATUSES.Unavailable;\n });\n const onBreak = circuitBreakerPolicy.onBreak.bind(circuitBreakerPolicy);\n\n const onDegradedEventEmitter = new CockatielEventEmitter<\n FailureReason<unknown> | { duration: number }\n >();\n const onDegraded = onDegradedEventEmitter.addListener;\n\n const onAvailableEventEmitter = new CockatielEventEmitter<void>();\n const onAvailable = onAvailableEventEmitter.addListener;\n\n retryPolicy.onGiveUp((data) => {\n if (circuitBreakerPolicy.state === CircuitState.Closed) {\n availabilityStatus = AVAILABILITY_STATUSES.Degraded;\n onDegradedEventEmitter.emit(data);\n }\n });\n retryPolicy.onSuccess(({ duration }) => {\n if (circuitBreakerPolicy.state === CircuitState.Closed) {\n if (duration > degradedThreshold) {\n availabilityStatus = AVAILABILITY_STATUSES.Degraded;\n onDegradedEventEmitter.emit({ duration });\n } else if (availabilityStatus !== AVAILABILITY_STATUSES.Available) {\n availabilityStatus = AVAILABILITY_STATUSES.Available;\n onAvailableEventEmitter.emit();\n }\n }\n });\n\n // Every time the retry policy makes an attempt, it executes the circuit\n // breaker policy, which executes the service.\n //\n // Calling:\n //\n // policy.execute(() => {\n // // do what the service does\n // })\n //\n // is equivalent to:\n //\n // retryPolicy.execute(() => {\n // circuitBreakerPolicy.execute(() => {\n // // do what the service does\n // });\n // });\n //\n // So if the retry policy succeeds or fails, it is because the circuit breaker\n // policy succeeded or failed. And if there are any event listeners registered\n // on the retry policy, by the time they are called, the state of the circuit\n // breaker will have already changed.\n const policy = wrap(retryPolicy, circuitBreakerPolicy);\n\n const getRemainingCircuitOpenDuration = (): number | null => {\n if (internalCircuitState.state === CircuitState.Open) {\n return internalCircuitState.openedAt + circuitBreakDuration - Date.now();\n }\n return null;\n };\n\n const getCircuitState = (): CircuitState => {\n return circuitBreakerPolicy.state;\n };\n\n const reset = (): void => {\n // Set the state of the policy to \"isolated\" regardless of its current state\n const { dispose } = circuitBreakerPolicy.isolate();\n // Reset the state to \"closed\"\n dispose();\n\n // Reset the counter on the breaker as well\n consecutiveBreaker.success();\n\n // Re-initialize the availability status so that if the service is executed\n // successfully, onAvailable listeners will be called again\n availabilityStatus = AVAILABILITY_STATUSES.Unknown;\n };\n\n return {\n ...policy,\n circuitBreakerPolicy,\n circuitBreakDuration,\n getCircuitState,\n getRemainingCircuitOpenDuration,\n reset,\n retryPolicy,\n onBreak,\n onDegraded,\n onAvailable,\n onRetry,\n };\n}\n"]}
1
+ {"version":3,"file":"create-service-policy.mjs","sourceRoot":"","sources":["../src/create-service-policy.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,YAAY,EACZ,YAAY,IAAI,qBAAqB,EACrC,kBAAkB,EAClB,kBAAkB,EAClB,eAAe,EACf,cAAc,EACd,SAAS,EACT,UAAU,EACV,KAAK,EACL,IAAI,EACL,kBAAkB;AAWnB,OAAO;AACL;;;GAGG;AACH,kBAAkB;AAClB;;;GAGG;AACH,qBAAqB;AACrB;;;GAGG;AACH,YAAY;AACZ;;;GAGG;AACH,eAAe;AACf;;;GAGG;AACH,kBAAkB;AAClB;;;;GAIG;AACH,SAAS;AACT;;;;GAIG;AACH,UAAU,EACX,CAAC;AAuIF;;;;GAIG;AACH,MAAM,qBAAqB,GAAG;IAC5B,SAAS,EAAE,WAAW;IACtB,QAAQ,EAAE,UAAU;IACpB,WAAW,EAAE,aAAa;IAC1B,OAAO,EAAE,SAAS;CACV,CAAC;AAUX;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAC,CAAC;AAErC;;;;;;;;GAQG;AACH,MAAM,CAAC,MAAM,gCAAgC,GAAG,CAAC,CAAC,GAAG,mBAAmB,CAAC,GAAG,CAAC,CAAC;AAE9E;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,8BAA8B,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAE7D;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,0BAA0B,GAAG,I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,EAAE,GAAG,oBAAoB,CAAC,OAAO,EAAE,CAAC;QACnD,8BAA8B;QAC9B,OAAO,EAAE,CAAC;QAEV,2CAA2C;QAC3C,kBAAkB,CAAC,OAAO,EAAE,CAAC;QAE7B,2EAA2E;QAC3E,2DAA2D;QAC3D,kBAAkB,GAAG,qBAAqB,CAAC,OAAO,CAAC;IACrD,CAAC,CAAC;IAEF,OAAO;QACL,GAAG,MAAM;QACT,oBAAoB;QACpB,oBAAoB;QACpB,eAAe;QACf,+BAA+B;QAC/B,KAAK;QACL,WAAW;QACX,OAAO;QACP,UAAU;QACV,WAAW;QACX,OAAO;KACR,CAAC;AACJ,CAAC","sourcesContent":["import {\n BrokenCircuitError,\n CircuitState,\n EventEmitter as CockatielEventEmitter,\n ConsecutiveBreaker,\n ExponentialBackoff,\n ConstantBackoff,\n circuitBreaker,\n handleAll,\n handleWhen,\n retry,\n wrap,\n} from 'cockatiel';\nimport type {\n CircuitBreakerPolicy,\n Event as CockatielEvent,\n FailureReason,\n IBackoffFactory,\n IPolicy,\n Policy,\n RetryPolicy,\n} from 'cockatiel';\n\nexport {\n /**\n * @deprecated This is deprecated and will be removed in a future major\n * version. Please use the equivalent type from `@metamask/base-data-service`.\n */\n BrokenCircuitError,\n /**\n * @deprecated This is deprecated and will be removed in a future major\n * version. Please use the equivalent type from `@metamask/base-data-service`.\n */\n CockatielEventEmitter,\n /**\n * @deprecated This is deprecated and will be removed in a future major\n * version. Please use the equivalent type from `@metamask/base-data-service`.\n */\n CircuitState,\n /**\n * @deprecated This is deprecated and will be removed in a future major\n * version. Please use the equivalent type from `@metamask/base-data-service`.\n */\n ConstantBackoff,\n /**\n * @deprecated This is deprecated and will be removed in a future major\n * version. Please use the equivalent type from `@metamask/base-data-service`.\n */\n ExponentialBackoff,\n /**\n * @deprecated This is deprecated and will be removed in a future major\n * version. Please use the equivalent function from\n * `@metamask/base-data-service`.\n */\n handleAll,\n /**\n * @deprecated This is deprecated and will be removed in a future major\n * version. Please use the equivalent function from\n * `@metamask/base-data-service`.\n */\n handleWhen,\n};\n\nexport type {\n /**\n * @deprecated This is deprecated and will be removed in a future major\n * version. Please use the equivalent type from `@metamask/base-data-service`.\n */\n CockatielEvent,\n /**\n * @deprecated This is deprecated and will be removed in a future major\n * version. Please use the equivalent type from `@metamask/base-data-service`.\n */\n FailureReason as CockatielFailureReason,\n};\n\n/**\n * The options for `createServicePolicy`.\n *\n * @deprecated This is deprecated and will be removed in a future major version.\n * Please use the equivalent type from `@metamask/base-data-service`.\n */\nexport type CreateServicePolicyOptions = {\n /**\n * The backoff strategy to use. Mainly useful for testing so that a constant\n * backoff can be used when mocking timers. Defaults to an instance of\n * ExponentialBackoff.\n */\n backoff?: IBackoffFactory<unknown>;\n /**\n * The length of time (in milliseconds) to pause retries of the action after\n * the number of failures reaches `maxConsecutiveFailures`.\n */\n circuitBreakDuration?: number;\n /**\n * The length of time (in milliseconds) that governs when the service is\n * regarded as degraded (affecting when `onDegraded` is called).\n */\n degradedThreshold?: number;\n /**\n * Predicate function for when an error should be considered a service failure.\n */\n isServiceFailure?: (error: unknown) => boolean;\n /**\n * The maximum number of times that the service is allowed to fail before\n * pausing further retries.\n */\n maxConsecutiveFailures?: number;\n /**\n * The maximum number of times that a failing service should be re-invoked\n * before giving up.\n */\n maxRetries?: number;\n /**\n * The policy used to control when the service should be retried based on\n * either the result of the service or an error that it throws. For instance,\n * you could use this to retry only certain errors. See `handleWhen` and\n * friends from Cockatiel for more.\n */\n retryFilterPolicy?: Policy;\n};\n\n/**\n * The service policy object.\n *\n * @deprecated This is deprecated and will be removed in a future major\n * version. Please use the equivalent type from `@metamask/base-data-service`.\n */\nexport type ServicePolicy = IPolicy & {\n /**\n * The Cockatiel circuit breaker policy that the service policy uses\n * internally.\n */\n circuitBreakerPolicy: CircuitBreakerPolicy;\n /**\n * The amount of time to pause requests to the service if the number of\n * maximum consecutive failures is reached.\n */\n circuitBreakDuration: number;\n /**\n * @returns The state of the underlying circuit.\n */\n getCircuitState: () => CircuitState;\n /**\n * If the circuit is open and ongoing requests are paused, returns the number\n * of milliseconds before the requests will be attempted again. If the circuit\n * is not open, returns null.\n */\n getRemainingCircuitOpenDuration: () => number | null;\n /**\n * Resets the internal circuit breaker policy (if it is open, it will now be\n * closed).\n */\n reset: () => void;\n /**\n * The Cockatiel retry policy that the service policy uses internally.\n */\n retryPolicy: RetryPolicy;\n /**\n * A function which is called when the number of times that the service fails\n * in a row meets the set maximum number of consecutive failures.\n */\n onBreak: CircuitBreakerPolicy['onBreak'];\n /**\n * A function which is called in two circumstances: 1) when the service\n * succeeds before the maximum number of consecutive failures is reached, but\n * takes more time than the `degradedThreshold` to run, or 2) if the service\n * never succeeds before the retry policy gives up and before the maximum\n * number of consecutive failures has been reached.\n */\n onDegraded: CockatielEvent<FailureReason<unknown> | { duration: number }>;\n /**\n * A function which is called when the service succeeds for the first time,\n * or when the service fails enough times to cause the circuit to break and\n * then recovers.\n */\n onAvailable: CockatielEvent<void>;\n /**\n * A function which will be called by the retry policy each time the service\n * fails and the policy kicks off a timer to re-run the service. This is\n * primarily useful in tests where we are mocking timers.\n */\n onRetry: RetryPolicy['onRetry'];\n};\n\n/**\n * Parts of the circuit breaker's internal and external state as necessary in\n * order to compute the time remaining before the circuit will reopen.\n */\ntype InternalCircuitState =\n | {\n state: CircuitState.Open;\n openedAt: number;\n }\n | { state: Exclude<CircuitState, CircuitState.Open> };\n\n/**\n * Availability statuses that the service can be in.\n *\n * Used to keep track of whether the `onAvailable` event should be fired.\n */\nconst AVAILABILITY_STATUSES = {\n Available: 'available',\n Degraded: 'degraded',\n Unavailable: 'unavailable',\n Unknown: 'unknown',\n} as const;\n\n/**\n * Availability statuses that the service can be in.\n *\n * Used to keep track of whether the `onAvailable` event should be fired.\n */\ntype AvailabilityStatus =\n (typeof AVAILABILITY_STATUSES)[keyof typeof AVAILABILITY_STATUSES];\n\n/**\n * The maximum number of times that a failing service should be re-run before\n * giving up.\n *\n * @deprecated This is deprecated and will be removed in a future major version.\n * Please use the equivalent variable from `@metamask/base-data-service`.\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. This is set to a value such that if given a\n * service that continually fails, the policy needs to be executed 3 times\n * before further retries are paused.\n *\n * @deprecated This is deprecated and will be removed in a future major version.\n * Please use the equivalent variable from `@metamask/base-data-service`.\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 *\n * @deprecated This is deprecated and will be removed in a future major version.\n * Please use the equivalent variable from `@metamask/base-data-service`.\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 *\n * @deprecated This is deprecated and will be removed in a future major version.\n * Please use the equivalent variable from `@metamask/base-data-service`.\n */\nexport const DEFAULT_DEGRADED_THRESHOLD = 5_000;\n\nconst defaultIsServiceFailure = (error: unknown): boolean => {\n if (\n typeof error === 'object' &&\n error !== null &&\n 'httpStatus' in error &&\n typeof error.httpStatus === 'number'\n ) {\n return error.httpStatus >= 500;\n }\n\n // If the error is not an object, or doesn't have a numeric httpStatus\n // property, consider it a service failure (e.g., network errors, timeouts,\n // etc.)\n return true;\n};\n\n/**\n * The circuit breaker policy inside of the Cockatiel library exposes some of\n * its state, but not all of it. Notably, the time that the circuit opened is\n * not publicly accessible. So we have to record this ourselves.\n *\n * This function therefore allows us to obtain the circuit breaker state that we\n * wish we could access.\n *\n * @param state - The public state of a circuit breaker policy.\n * @returns if the circuit is open, the state of the circuit breaker policy plus\n * the time that it opened, otherwise just the circuit state.\n */\nfunction getInternalCircuitState(state: CircuitState): InternalCircuitState {\n if (state === CircuitState.Open) {\n return { state, openedAt: Date.now() };\n }\n return { state };\n}\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. See\n * {@link CreateServicePolicyOptions}.\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 * maxRetries: 3,\n * retryFilterPolicy: handleWhen((error) => {\n * return error.message.includes('oops');\n * }),\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 *\n * @deprecated This is deprecated and will be removed in a future major version.\n * Please use the equivalent function from `@metamask/base-data-service`.\n */\nexport function createServicePolicy(\n options: CreateServicePolicyOptions = {},\n): ServicePolicy {\n const {\n maxRetries = DEFAULT_MAX_RETRIES,\n retryFilterPolicy = handleAll,\n maxConsecutiveFailures = DEFAULT_MAX_CONSECUTIVE_FAILURES,\n circuitBreakDuration = DEFAULT_CIRCUIT_BREAK_DURATION,\n degradedThreshold = DEFAULT_DEGRADED_THRESHOLD,\n backoff = new ExponentialBackoff(),\n isServiceFailure = defaultIsServiceFailure,\n } = options;\n\n let availabilityStatus: AvailabilityStatus = AVAILABILITY_STATUSES.Unknown;\n\n const retryPolicy = retry(retryFilterPolicy, {\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: maxRetries,\n // Retries of the service will be executed following ever increasing delays,\n // determined by a backoff formula.\n backoff,\n });\n const onRetry = retryPolicy.onRetry.bind(retryPolicy);\n\n const consecutiveBreaker = new ConsecutiveBreaker(maxConsecutiveFailures);\n const circuitBreakerPolicy = circuitBreaker(handleWhen(isServiceFailure), {\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: consecutiveBreaker,\n });\n\n let internalCircuitState: InternalCircuitState = getInternalCircuitState(\n circuitBreakerPolicy.state,\n );\n circuitBreakerPolicy.onStateChange((state) => {\n internalCircuitState = getInternalCircuitState(state);\n });\n\n circuitBreakerPolicy.onBreak(() => {\n availabilityStatus = AVAILABILITY_STATUSES.Unavailable;\n });\n const onBreak = circuitBreakerPolicy.onBreak.bind(circuitBreakerPolicy);\n\n const onDegradedEventEmitter = new CockatielEventEmitter<\n FailureReason<unknown> | { duration: number }\n >();\n const onDegraded = onDegradedEventEmitter.addListener;\n\n const onAvailableEventEmitter = new CockatielEventEmitter<void>();\n const onAvailable = onAvailableEventEmitter.addListener;\n\n retryPolicy.onGiveUp((data) => {\n if (circuitBreakerPolicy.state === CircuitState.Closed) {\n availabilityStatus = AVAILABILITY_STATUSES.Degraded;\n onDegradedEventEmitter.emit(data);\n }\n });\n retryPolicy.onSuccess(({ duration }) => {\n if (circuitBreakerPolicy.state === CircuitState.Closed) {\n if (duration > degradedThreshold) {\n availabilityStatus = AVAILABILITY_STATUSES.Degraded;\n onDegradedEventEmitter.emit({ duration });\n } else if (availabilityStatus !== AVAILABILITY_STATUSES.Available) {\n availabilityStatus = AVAILABILITY_STATUSES.Available;\n onAvailableEventEmitter.emit();\n }\n }\n });\n\n // Every time the retry policy makes an attempt, it executes the circuit\n // breaker policy, which executes the service.\n //\n // Calling:\n //\n // policy.execute(() => {\n // // do what the service does\n // })\n //\n // is equivalent to:\n //\n // retryPolicy.execute(() => {\n // circuitBreakerPolicy.execute(() => {\n // // do what the service does\n // });\n // });\n //\n // So if the retry policy succeeds or fails, it is because the circuit breaker\n // policy succeeded or failed. And if there are any event listeners registered\n // on the retry policy, by the time they are called, the state of the circuit\n // breaker will have already changed.\n const policy = wrap(retryPolicy, circuitBreakerPolicy);\n\n const getRemainingCircuitOpenDuration = (): number | null => {\n if (internalCircuitState.state === CircuitState.Open) {\n return internalCircuitState.openedAt + circuitBreakDuration - Date.now();\n }\n return null;\n };\n\n const getCircuitState = (): CircuitState => {\n return circuitBreakerPolicy.state;\n };\n\n const reset = (): void => {\n // Set the state of the policy to \"isolated\" regardless of its current state\n const { dispose } = circuitBreakerPolicy.isolate();\n // Reset the state to \"closed\"\n dispose();\n\n // Reset the counter on the breaker as well\n consecutiveBreaker.success();\n\n // Re-initialize the availability status so that if the service is executed\n // successfully, onAvailable listeners will be called again\n availabilityStatus = AVAILABILITY_STATUSES.Unknown;\n };\n\n return {\n ...policy,\n circuitBreakerPolicy,\n circuitBreakDuration,\n getCircuitState,\n getRemainingCircuitOpenDuration,\n reset,\n retryPolicy,\n onBreak,\n onDegraded,\n onAvailable,\n onRetry,\n };\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask-previews/controller-utils",
3
- "version": "12.3.0-preview-aa4ef4666",
3
+ "version": "12.3.0-preview-186382c0a",
4
4
  "description": "Data and convenience functions shared by multiple packages",
5
5
  "keywords": [
6
6
  "Ethereum",