UNPKG

@graphql-hive/core

Version:
370 lines • 16.1 kB
export default CircuitBreaker; /** * Constructs a {@link CircuitBreaker}. * * @class CircuitBreaker * @extends EventEmitter * @param {Function} action The action to fire for this {@link CircuitBreaker} * @param {Object} options Options for the {@link CircuitBreaker} * @param {Status} options.status A {@link Status} object that might * have pre-prime stats * @param {Number} options.timeout The time in milliseconds that action should * be allowed to execute before timing out. Timeout can be disabled by setting * this to `false`. Default 10000 (10 seconds) * @param {Number} options.maxFailures (Deprecated) The number of times the * circuit can fail before opening. Default 10. * @param {Number} options.resetTimeout The time in milliseconds to wait before * setting the breaker to `halfOpen` state, and trying the action again. * Default: 30000 (30 seconds) * @param {Number} options.rollingCountTimeout Sets the duration of the * statistical rolling window, in milliseconds. This is how long Opossum keeps * metrics for the circuit breaker to use and for publishing. Default: 10000 * @param {Number} options.rollingCountBuckets Sets the number of buckets the * rolling statistical window is divided into. So, if * options.rollingCountTimeout is 10000, and options.rollingCountBuckets is 10, * then the statistical window will be 1000/1 second snapshots in the * statistical window. Default: 10 * @param {String} options.name the circuit name to use when reporting stats. * Default: the name of the function this circuit controls. * @param {boolean} options.rollingPercentilesEnabled This property indicates * whether execution latencies should be tracked and calculated as percentiles. * If they are disabled, all summary statistics (mean, percentiles) are * returned as -1. Default: true * @param {Number} options.capacity the number of concurrent requests allowed. * If the number currently executing function calls is equal to * options.capacity, further calls to `fire()` are rejected until at least one * of the current requests completes. Default: `Number.MAX_SAFE_INTEGER`. * @param {Number} options.errorThresholdPercentage the error percentage at * which to open the circuit and start short-circuiting requests to fallback. * Default: 50 * @param {boolean} options.enabled whether this circuit is enabled upon * construction. Default: true * @param {boolean} options.allowWarmUp determines whether to allow failures * without opening the circuit during a brief warmup period (this is the * `rollingCountTimeout` property). Default: false * This can help in situations where no matter what your * `errorThresholdPercentage` is, if the first execution times out or fails, * the circuit immediately opens. * @param {Number} options.volumeThreshold the minimum number of requests within * the rolling statistical window that must exist before the circuit breaker * can open. This is similar to `options.allowWarmUp` in that no matter how many * failures there are, if the number of requests within the statistical window * does not exceed this threshold, the circuit will remain closed. Default: 0 * @param {Function} options.errorFilter an optional function that will be * called when the circuit's function fails (returns a rejected Promise). If * this function returns truthy, the circuit's failPure statistics will not be * incremented. This is useful, for example, when you don't want HTTP 404 to * trip the circuit, but still want to handle it as a failure case. * @param {boolean} options.cache whether the return value of the first * successful execution of the circuit's function will be cached. Once a value * has been cached that value will be returned for every subsequent execution: * the cache can be cleared using `clearCache`. (The metrics `cacheHit` and * `cacheMiss` reflect cache activity.) Default: false * @param {Number} options.cacheTTL the time to live for the cache * in milliseconds. Set 0 for infinity cache. Default: 0 (no TTL) * @param {Number} options.cacheSize the max amount of entries in the internal * cache. Only used when cacheTransport is not defined. * Default: max size of JS map (2^24). * @param {Function} options.cacheGetKey function that returns the key to use * when caching the result of the circuit's fire. * Better to use custom one, because `JSON.stringify` is not good * from performance perspective. * Default: `(...args) => JSON.stringify(args)` * @param {CacheTransport} options.cacheTransport custom cache transport * should implement `get`, `set` and `flush` methods. * @param {boolean} options.coalesce If true, this provides coalescing of * requests to this breaker, in other words: the promise will be cached. * Only one action (with same cache key) is executed at a time, and the other * pending actions wait for the result. Performance will improve when rapidly * firing the circuitbreaker with the same request, especially on a slower * action (e.g. multiple end-users fetching same data from remote). * Will use internal cache only. Can be used in combination with options.cache. * The metrics `coalesceCacheHit` and `coalesceCacheMiss` are available. * Default: false * @param {Number} options.coalesceTTL the time to live for the coalescing * in milliseconds. Set 0 for infinity cache. Default: same as options.timeout * @param {Number} options.coalesceSize the max amount of entries in the * coalescing cache. Default: max size of JS map (2^24). * @param {string[]} options.coalesceResetOn when to reset the coalesce cache. * Options: `error`, `success`, `timeout`. Default: not set, reset using TTL. * @param {AbortController} options.abortController this allows Opossum to * signal upon timeout and properly abort your on going requests instead of * leaving it in the background * @param {boolean} options.enableSnapshots whether to enable the rolling * stats snapshots that opossum emits at the bucketInterval. Disable this * as an optimization if you don't listen to the 'snapshot' event to reduce * the number of timers opossum initiates. * @param {EventEmitter} options.rotateBucketController if you have multiple * breakers in your app, the number of timers across breakers can get costly. * This option allows you to provide an EventEmitter that rotates the buckets * so you can have one global timer in your app. Make sure that you are * emitting a 'rotate' event from this EventEmitter * @param {boolean} options.autoRenewAbortController Automatically recreates * the instance of AbortController whenever the circuit transitions to * 'halfOpen' or 'closed' state. This ensures that new requests are not * impacted by previous signals that were triggered when the circuit was 'open'. * Default: false * * * @fires CircuitBreaker#halfOpen * @fires CircuitBreaker#close * @fires CircuitBreaker#open * @fires CircuitBreaker#fire * @fires CircuitBreaker#cacheHit * @fires CircuitBreaker#cacheMiss * @fires CircuitBreaker#coalesceCacheHit * @fires CircuitBreaker#coalesceCacheMiss * @fires CircuitBreaker#reject * @fires CircuitBreaker#timeout * @fires CircuitBreaker#success * @fires CircuitBreaker#semaphoreLocked * @fires CircuitBreaker#healthCheckFailed * @fires CircuitBreaker#fallback * @fires CircuitBreaker#failure */ declare class CircuitBreaker extends EventEmitter<[never]> { /** * Returns true if the provided error was generated here. It will be false * if the error came from the action itself. * @param {Error} error The Error to check. * @returns {Boolean} true if the error was generated here */ static isOurError(error: Error): boolean; /** * Create a new Status object, * helpful when you need to prime a breaker with stats * @param {Object} options - * @param {Number} options.rollingCountBuckets number of buckets in the window * @param {Number} options.rollingCountTimeout the duration of the window * @param {Boolean} options.rollingPercentilesEnabled whether to calculate * @param {Object} options.stats user supplied stats * @returns {Status} a new {@link Status} object */ static newStatus(options: { rollingCountBuckets: number; rollingCountTimeout: number; rollingPercentilesEnabled: boolean; stats: Object; }): Status; constructor(action: any, options?: {}); options: {}; semaphore: any; action: any; /** * Renews the abort controller if needed * @private * @returns {void} */ private _renewAbortControllerIfNeeded; /** * Closes the breaker, allowing the action to execute again * @fires CircuitBreaker#close * @returns {void} */ close(): void; /** * Opens the breaker. Each time the breaker is fired while the circuit is * opened, a failed Promise is returned, or if any fallback function * has been provided, it is invoked. * * If the breaker is already open this call does nothing. * @fires CircuitBreaker#open * @returns {void} */ open(): void; /** * Shuts down this circuit breaker. All subsequent calls to the * circuit will fail, returning a rejected promise. * @returns {void} */ shutdown(): void; /** * Determines if the circuit has been shutdown. * @type {Boolean} */ get isShutdown(): boolean; /** * Gets the name of this circuit * @type {String} */ get name(): string; /** * Gets the name of this circuit group * @type {String} */ get group(): string; /** * Gets whether this circuit is in the `pendingClosed` state * @type {Boolean} */ get pendingClose(): boolean; /** * True if the circuit is currently closed. False otherwise. * @type {Boolean} */ get closed(): boolean; /** * True if the circuit is currently opened. False otherwise. * @type {Boolean} */ get opened(): boolean; /** * True if the circuit is currently half opened. False otherwise. * @type {Boolean} */ get halfOpen(): boolean; /** * The current {@link Status} of this {@link CircuitBreaker} * @type {Status} */ get status(): Status; /** * Get the current stats for the circuit. * @see Status#stats * @type {Object} */ get stats(): Object; toJSON(): { state: { name: string; enabled: boolean; closed: boolean; open: boolean; halfOpen: boolean; warmUp: boolean; shutdown: boolean; lastTimerAt: any; }; status: Object; }; /** * Gets whether the circuit is enabled or not * @type {Boolean} */ get enabled(): boolean; /** * Gets whether the circuit is currently in warm up phase * @type {Boolean} */ get warmUp(): boolean; /** * Gets the volume threshold for this circuit * @type {Boolean} */ get volumeThreshold(): boolean; /** * Provide a fallback function for this {@link CircuitBreaker}. This * function will be executed when the circuit is `fire`d and fails. * It will always be preceded by a `failure` event, and `breaker.fire` returns * a rejected Promise. * @param {Function | CircuitBreaker} func the fallback function to execute * when the breaker has opened or when a timeout or error occurs. * @return {CircuitBreaker} this */ fallback(func: Function | CircuitBreaker): CircuitBreaker; /** * Execute the action for this circuit. If the action fails or times out, the * returned promise will be rejected. If the action succeeds, the promise will * resolve with the resolved value from action. If a fallback function was * provided, it will be invoked in the event of any failure or timeout. * * Any parameters passed to this function will be proxied to the circuit * function. * * @return {Promise<any>} promise resolves with the circuit function's return * value on success or is rejected on failure of the action. Use isOurError() * to determine if a rejection was a result of the circuit breaker or the * action. * * @fires CircuitBreaker#failure * @fires CircuitBreaker#fallback * @fires CircuitBreaker#fire * @fires CircuitBreaker#reject * @fires CircuitBreaker#success * @fires CircuitBreaker#timeout * @fires CircuitBreaker#semaphoreLocked */ fire(...args: any[]): Promise<any>; /** * Execute the action for this circuit using `context` as `this`. * If the action fails or times out, the * returned promise will be rejected. If the action succeeds, the promise will * resolve with the resolved value from action. If a fallback function was * provided, it will be invoked in the event of any failure or timeout. * * Any parameters in addition to `context will be passed to the * circuit function. * * @param {any} context the `this` context used for function execution * @param {any} rest the arguments passed to the action * * @return {Promise<any>} promise resolves with the circuit function's return * value on success or is rejected on failure of the action. * * @fires CircuitBreaker#failure * @fires CircuitBreaker#fallback * @fires CircuitBreaker#fire * @fires CircuitBreaker#reject * @fires CircuitBreaker#success * @fires CircuitBreaker#timeout * @fires CircuitBreaker#semaphoreLocked */ call(context: any, ...rest: any): Promise<any>; /** * Clears the cache of this {@link CircuitBreaker} * @returns {void} */ clearCache(): void; /** * Provide a health check function to be called periodically. The function * should return a Promise. If the promise is rejected the circuit will open. * This is in addition to the existing circuit behavior as defined by * `options.errorThresholdPercentage` in the constructor. For example, if the * health check function provided here always returns a resolved promise, the * circuit can still trip and open if there are failures exceeding the * configured threshold. The health check function is executed within the * circuit breaker's execution context, so `this` within the function is the * circuit breaker itself. * * @param {Function} func a health check function which returns a promise. * @param {Number} [interval] the amount of time between calls to the health * check function. Default: 5000 (5 seconds) * * @returns {void} * * @fires CircuitBreaker#healthCheckFailed * @throws {TypeError} if `interval` is supplied but not a number */ healthCheck(func: Function, interval?: number): void; /** * Enables this circuit. If the circuit is the disabled * state, it will be re-enabled. If not, this is essentially * a noop. * @returns {void} */ enable(): void; /** * Disables this circuit, causing all calls to the circuit's function * to be executed without circuit or fallback protection. * @returns {void} */ disable(): void; /** * Retrieves the current AbortSignal from the abortController, if available. * This signal can be used to monitor ongoing requests. * @returns {AbortSignal|undefined} The AbortSignal if present, * otherwise undefined. */ getSignal(): AbortSignal | undefined; /** * Retrieves the current AbortController instance. * This controller can be used to manually abort ongoing requests or create * a new signal. * @returns {AbortController|undefined} The AbortController if present, * otherwise undefined. */ getAbortController(): AbortController | undefined; } import EventEmitter from 'events'; import Status from './status.js'; //# sourceMappingURL=circuit.d.ts.map