### Circuit Breaker State Object Example Source: https://nodeshift.dev/opossum An example of the object returned by the `toJSON` method, representing the current state and status of a circuit breaker. ```javascript { state: { enabled: true, name: 'functionName' closed: true, open: false, halfOpen: false, warmUp: false, shutdown: false }, status: { ... } }; ``` -------------------------------- ### Browser Usage Example Source: https://nodeshift.dev/opossum Demonstrates how to access and use the CircuitBreaker constructor in a browser environment, typically after bundling with tools like webpack. This allows guarding AJAX calls against network failures. ```javascript In the browser's global scope will be a `CircuitBreaker` constructor. Use it to create circuit breakers, guarding against network failures in your REST API calls. ``` -------------------------------- ### Circuit Breaker Fires and Failures Example Source: https://nodeshift.dev/opossum Illustrates the rolling count of fires and failures over a 10-second window with 10 buckets. This helps in understanding how the error rate is calculated for the circuit breaker. ```markdown | fires: 2 | fires: 1 | fires: 3 | fires: 0 | fires: 9 | fires: 3 | fires: 2 | fires: 0 | fires: 4 | fires: 0 | | fails: 0 | fails: 0 | fails: 0 | fails: 0 | fails: 0 | fails: 3 | fails: 0 | fails: 0 | fails: 0 | fails: 0 | ``` -------------------------------- ### Circuit Breaker Stats Object Structure Source: https://nodeshift.dev/opossum An example structure of the statistics object returned by `breaker.stats`. This object contains detailed metrics about the circuit breaker's operation. ```json { "failures": 11, "fallbacks": 0, "successes": 5, "rejects": 0, "fires": 16, "timeouts": 0, "cacheHits": 0, "cacheMisses": 0, "semaphoreRejections": 0, "percentiles": { "0": 0, "1": 0, "0.25": 0, "0.5": 0, "0.75": 0, "0.9": 0, "0.95": 0, "0.99": 0, "0.995": 0 }, "latencyTimes": [ 0 ], "latencyMean": 0 } ``` -------------------------------- ### volumeThreshold Source: https://nodeshift.dev/opossum Gets the volume threshold configured for this circuit breaker. ```APIDOC ## volumeThreshold ### Description Gets the volume threshold for this circuit. ### Type - **Boolean** ``` -------------------------------- ### name Source: https://nodeshift.dev/opossum Gets the name of the circuit breaker. ```APIDOC ## name ### Description Gets the name of this circuit. ### Type - **String** ``` -------------------------------- ### MemoryCache Get Operation Source: https://nodeshift.dev/opossum Retrieves a value from the cache using its key. Returns the cached value if found and not expired, otherwise returns undefined. ```javascript get(key: string): any ``` -------------------------------- ### group Source: https://nodeshift.dev/opossum Gets the name of the circuit breaker's group. ```APIDOC ## group ### Description Gets the name of this circuit group. ### Type - **String** ``` -------------------------------- ### Get Circuit Breaker State Source: https://nodeshift.dev/opossum Retrieve the current state and status of a circuit breaker. The output can be used to initialize a new breaker with the same state. ```javascript const breakerState = breaker.toJSON(); ``` -------------------------------- ### Get Circuit Breaker Stats Source: https://nodeshift.dev/opossum Retrieve the current cumulative statistics of a circuit breaker. This is useful for pre-populating stats in ephemeral environments. ```javascript const stats = breaker.stats; ``` -------------------------------- ### Create and Use Circuit Breaker with Status Source: https://nodeshift.dev/opossum Demonstrates creating a circuit breaker with specific rolling count options and accessing its cumulative statistics and time-sliced window. ```javascript const circuit = circuitBreaker(fs.readFile, { rollingCountBuckets: 10, rollingCountTimeout: 1000 }); // get the cumulative statistics for the last second circuit.status.stats; // get the array of 10, 1 second time slices for the last second circuit.status.window; ``` -------------------------------- ### Initialize MemoryCache Source: https://nodeshift.dev/opossum Instantiates a new in-memory cache. This cache can be used to store key-value pairs with a specified time-to-live. ```javascript new MemoryCache() ``` -------------------------------- ### Re-import Circuit Breaker Stats Source: https://nodeshift.dev/opossum Initialize a new circuit breaker with previously saved statistics. This is particularly useful for serverless or containerized environments where instances are ephemeral. ```javascript const statusOptions = { stats: {....} }; const newStatus = CircuitBreaker.newStatus(statusOptions); const breaker = new CircuitBreaker({status: newStatus}); ``` -------------------------------- ### newStatus Source: https://nodeshift.dev/opossum Creates a new Status object, useful for initializing a breaker with specific statistics. ```APIDOC ## newStatus(options) ### Description Create a new Status object, helpful when you need to prime a breaker with stats. ### Parameters - **options** (Object) - **options.rollingCountBuckets** (Number) - number of buckets in the window - **options.rollingCountTimeout** (Number) - the duration of the window - **options.rollingPercentilesEnabled** (Boolean) - whether to calculate - **options.stats** (Object) - user supplied stats ### Returns - **Status**: a new Status object ``` -------------------------------- ### open Source: https://nodeshift.dev/opossum Opens the circuit breaker, causing subsequent calls to fail or invoke a fallback function. ```APIDOC ## open() ### Description 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. ### Returns - **void** ``` -------------------------------- ### call Source: https://nodeshift.dev/opossum Executes the action with a specified 'this' context and arguments, handling circuit breaker logic. ```APIDOC ## call(context, rest) ### Description 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. ### Parameters - **context** (any) - the `this` context used for function execution. - **rest** (any) - the arguments passed to the action. ### Returns - **Promise**: promise resolves with the circuit function's return value on success or is rejected on failure of the action. ``` -------------------------------- ### enable() Source: https://nodeshift.dev/opossum Enables the circuit breaker. If the circuit is currently disabled, it will be re-enabled. Otherwise, this operation has no effect. ```APIDOC ## enable() ### Description Enables this circuit. If the circuit is the disabled state, it will be re-enabled. If not, this is essentially a noop. ### Method `enable(): void` ### Returns `void` ``` -------------------------------- ### Circuit Breaker Fires and Failures with Reduced Window Source: https://nodeshift.dev/opossum Demonstrates the rolling count of fires and failures with a reduced window of 3 seconds and 3 buckets. This scenario highlights how a lower `rollingCountTimeout` and `rollingCountBuckets` can increase the error rate. ```markdown | fires: 3 | fires: 2 | fires: 0 | | fails: 3 | fails: 0 | fails: 0 | ``` -------------------------------- ### Promisify Callback Functions Source: https://nodeshift.dev/opossum Convert Node.js style callback functions into Promises using `util.promisify()`. This allows circuit actions that use callbacks to be seamlessly integrated with Opossum's Promise-based API. ```javascript The `opossum` API returns a `Promise` from `CircuitBreaker.fire()`. But your circuit action - the async function that might fail - doesn't have to return a promise. You can easily turn Node.js style callback functions into something `opossum` understands by using the built in Node core utility function `util.promisify()` . ``` -------------------------------- ### Shutdown Circuit Breaker Source: https://nodeshift.dev/opossum Demonstrates how to properly shut down a CircuitBreaker instance to clean up all listeners, which is particularly useful in test suites where CircuitBreakers are created and destroyed frequently. ```javascript breaker.shutdown(); ``` -------------------------------- ### Initialize Circuit Breaker with State Source: https://nodeshift.dev/opossum Create a new circuit breaker instance using a previously saved state object. This is useful for serverless or containerized environments where ephemeral instances need to retain state. ```javascript const breaker = new CircuitBreaker({state: state}); ``` -------------------------------- ### warmUp Source: https://nodeshift.dev/opossum Indicates if the circuit breaker is currently in its warm-up phase. ```APIDOC ## warmUp ### Description Gets whether the circuit is currently in warm up phase. ### Type - **Boolean** ``` -------------------------------- ### MemoryCache Class Source: https://nodeshift.dev/opossum A simple in-memory cache implementation for storing key-value pairs with optional time-to-live (TTL). ```APIDOC ## MemoryCache Class Simple in-memory cache implementation ### new MemoryCache() **Properties** - cache `(Map)`: Cache map ### Instance Members - **get(key)** Get cache value by key get(key: string): any **Parameters** - key `(string)`: Cache key **Returns** - `any`: Response from cache - **set(key, value, ttl)** Set cache key with value and ttl set(key: string, value: any, ttl: number): void **Parameters** - key `(string)`: Cache key - value `(any)`: Value to cache - ttl `(number)`: Time to live in milliseconds **Returns** - `void`: - **flush()** Clear cache flush(): void **Returns** - `void`: ``` -------------------------------- ### fire Source: https://nodeshift.dev/opossum Executes the action protected by the circuit breaker. Handles success, failure, and timeouts, optionally invoking a fallback function. ```APIDOC ## fire(args) ### Description 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. ### Parameters - **args** (...any) - Arguments to be passed to the circuit function. ### Returns - **Promise**: 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. ``` -------------------------------- ### fallback Source: https://nodeshift.dev/opossum Provides a fallback function to be executed when the circuit is tripped or the action fails. ```APIDOC ## fallback(func) ### Description Provide a fallback function for this 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. ### Parameters - **func** (Function | CircuitBreaker) - the fallback function to execute when the breaker has opened or when a timeout or error occurs. ### Returns - **CircuitBreaker**: this ``` -------------------------------- ### opened Source: https://nodeshift.dev/opossum Indicates if the circuit breaker is currently in the 'opened' state. ```APIDOC ## opened ### Description True if the circuit is currently opened. False otherwise. ### Type - **Boolean** ``` -------------------------------- ### enabled Source: https://nodeshift.dev/opossum Indicates whether the circuit breaker is currently enabled. ```APIDOC ## enabled ### Description Gets whether the circuit is enabled or not. ### Type - **Boolean** ``` -------------------------------- ### stats Source: https://nodeshift.dev/opossum Retrieves the current statistics for the circuit breaker. ```APIDOC ## stats ### Description Get the current stats for the circuit. ### Type - **Object** ### Related - Status#stats ``` -------------------------------- ### close Source: https://nodeshift.dev/opossum Closes the circuit breaker, allowing the protected action to be executed again. ```APIDOC ## close() ### Description Closes the breaker, allowing the action to execute again. ### Returns - **void** ``` -------------------------------- ### MemoryCache Set Operation Source: https://nodeshift.dev/opossum Sets a value in the cache with a specified key and time-to-live (TTL). If the key already exists, its value and TTL will be updated. ```javascript set(key: string, value: any, ttl: number): void ``` -------------------------------- ### halfOpen Source: https://nodeshift.dev/opossum Indicates if the circuit breaker is currently in the 'halfOpen' state. ```APIDOC ## halfOpen ### Description True if the circuit is currently half opened. False otherwise. ### Type - **Boolean** ``` -------------------------------- ### healthCheck Source: https://nodeshift.dev/opossum Provides a health check function that is periodically executed to monitor the circuit's health. ```APIDOC ## healthCheck(func, interval?) ### Description 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. ### Parameters - **func** (Function) - The health check function to execute. - **interval** (Number?) - The interval in milliseconds at which to execute the health check. ``` -------------------------------- ### MemoryCache Flush Operation Source: https://nodeshift.dev/opossum Clears all entries from the cache, effectively resetting it to an empty state. ```javascript flush(): void ``` -------------------------------- ### CircuitBreaker Constructor Source: https://nodeshift.dev/opossum Constructs a new CircuitBreaker instance. This class extends EventEmitter. ```APIDOC ## new CircuitBreaker(action: Function, options: Object) ### Description Constructs a CircuitBreaker. ### Parameters - **action** (Function) - The action to fire for this CircuitBreaker. - **options** (Object) - Options for the CircuitBreaker. #### Options - **options.status** (Status) - A Status object that might have pre-prime stats. - **options.timeout** (Number) - 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). - **options.maxFailures** (Number) - (Deprecated) The number of times the circuit can fail before opening. Default: 10. - **options.resetTimeout** (Number) - The time in milliseconds to wait before setting the breaker to `halfOpen` state, and trying the action again. Default: 30000 (30 seconds). - **options.rollingCountTimeout** (Number) - 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. - **options.rollingCountBuckets** (Number) - Sets the number of buckets the rolling statistical window is divided into. Default: 10. - **options.name** (String) - The circuit name to use when reporting stats. Default: the name of the function this circuit controls. - **options.rollingPercentilesEnabled** (boolean) - Whether execution latencies should be tracked and calculated as percentiles. Default: true. - **options.capacity** (Number) - The number of concurrent requests allowed. Default: `Number.MAX_SAFE_INTEGER`. - **options.errorThresholdPercentage** (Number) - The error percentage at which to open the circuit. Default: 50. - **options.enabled** (boolean) - Whether this circuit is enabled upon construction. Default: true. - **options.allowWarmUp** (boolean) - Determines whether to allow failures without opening the circuit during a brief warmup period. Default: false. - **options.volumeThreshold** (Number) - The minimum number of requests within the rolling statistical window that must exist before the circuit breaker can open. Default: 0. - **options.errorFilter** (Function) - An optional function that will be called when the circuit's function fails. If this function returns truthy, the circuit's failPure statistics will not be incremented. - **options.cache** (boolean) - Whether the return value of the first successful execution of the circuit's function will be cached. Default: false. - **options.cacheTTL** (Number) - The time to live for the cache in milliseconds. Set 0 for infinity cache. Default: 0 (no TTL). - **options.cacheGetKey** (Function) - Function that returns the key to use when caching the result of the circuit's fire. Default: `(...args) => JSON.stringify(args)`. - **options.cacheTransport** (CacheTransport) - Custom cache transport should implement `get`, `set`, and `flush` methods. - **options.abortController** (AbortController) - Allows Opossum to signal upon timeout and properly abort ongoing requests. - **options.enableSnapshots** (boolean) - Whether to enable the rolling stats snapshots that opossum emits at the bucketInterval. Default: true. - **options.rotateBucketController** (EventEmitter) - Allows for a global timer for bucket rotation across multiple breakers. ``` -------------------------------- ### Increase EventEmitter Listeners Source: https://nodeshift.dev/opossum Shows how to increase the maximum number of listeners for an EventEmitter to resolve issues related to too many listeners, often encountered when creating many CircuitBreaker instances. ```javascript const EventEmitter = require('events'); const MAX_LISTENERS = 100; EventEmitter.defaultMaxListeners = MAX_LISTENERS; ``` -------------------------------- ### clearCache Source: https://nodeshift.dev/opossum Clears the internal cache of the circuit breaker. ```APIDOC ## clearCache() ### Description Clears the cache of this CircuitBreaker. ### Returns - **void** ``` -------------------------------- ### pendingClose Source: https://nodeshift.dev/opossum Indicates if the circuit breaker is in the 'pendingClosed' state. ```APIDOC ## pendingClose ### Description Gets whether this circuit is in the `pendingClosed` state. ### Type - **Boolean** ``` -------------------------------- ### status Source: https://nodeshift.dev/opossum Retrieves the current status of the circuit breaker. ```APIDOC ## status ### Description The current Status of this CircuitBreaker. ### Type - **Status** ``` -------------------------------- ### Status Class Source: https://nodeshift.dev/opossum The Status class tracks execution statistics for a CircuitBreaker instance within a rolling time window. It aggregates event counts and provides insights into the circuit's performance. ```APIDOC ## Status Class Tracks execution status for a given CircuitBreaker. A Status instance is created for every CircuitBreaker and does not typically need to be created by a user. A Status instance will listen for all events on the CircuitBreaker and track them in a rolling statistical window. The window duration is determined by the `rollingCountTimeout` option provided to the CircuitBreaker. The window consists of an array of Objects, each representing the counts for a CircuitBreaker's events. The array's length is determined by the CircuitBreaker's `rollingCountBuckets` option. The duration of each slice of the window is determined by dividing the `rollingCountTimeout` by `rollingCountBuckets`. ### new Status(options: Object) Extends EventEmitter **Parameters** - options `(Object)`: for the status window - options.rollingCountBuckets `Number`: number of buckets in the window - options.rollingCountTimeout `Number`: the duration of the window - options.rollingPercentilesEnabled `Boolean`: whether to calculate percentiles - options.stats `Object`: object of previous stats **Related** - CircuitBreaker#status **Example** ```javascript // Creates a 1 second window consisting of ten time slices, // each 100ms long. const circuit = circuitBreaker(fs.readFile, { rollingCountBuckets: 10, rollingCountTimeout: 1000}); // get the cumulative statistics for the last second circuit.status.stats; // get the array of 10, 1 second time slices for the last second circuit.status.window; ``` ### Instance Members - **stats** Get the cumulative stats for the current window Type: Object - **window** Gets the stats window as an array of time-sliced objects. Type: Array ### Status#snapshot Emitted at each time-slice. Listeners for this event will receive a cumulative snapshot of the current status window. Type: Object ``` -------------------------------- ### CircuitBreaker Configuration Source: https://nodeshift.dev/opossum Configuration options for the CircuitBreaker, including the health check function and interval. ```APIDOC ## CircuitBreaker Configuration ### Parameters - `healthCheckFn` (Function) - A health check function which returns a promise. - `interval` (Number?) - The amount of time between calls to the health check function. Default: 5000 (5 seconds) ### Returns `void` ### Throws * `TypeError`: if `interval` is supplied but not a number ``` -------------------------------- ### closed Source: https://nodeshift.dev/opossum Indicates if the circuit breaker is currently in the 'closed' state. ```APIDOC ## closed ### Description True if the circuit is currently closed. False otherwise. ### Type - **Boolean** ``` -------------------------------- ### shutdown Source: https://nodeshift.dev/opossum Shuts down the circuit breaker, causing all future calls to fail. ```APIDOC ## shutdown() ### Description Shuts down this circuit breaker. All subsequent calls to the circuit will fail, returning a rejected promise. ### Returns - **void** ``` -------------------------------- ### isOurError Source: https://nodeshift.dev/opossum Checks if an error originated from the CircuitBreaker itself or from the executed action. ```APIDOC ## isOurError(error) ### Description Returns true if the provided error was generated here. It will be false if the error came from the action itself. ### Parameters - **error** (Error) - The Error to check. ### Returns - **Boolean**: true if the error was generated here ``` -------------------------------- ### disable() Source: https://nodeshift.dev/opossum Disables the circuit breaker, causing all calls to the circuit's function to be executed without circuit or fallback protection. ```APIDOC ## disable() ### Description Disables this circuit, causing all calls to the circuit's function to be executed without circuit or fallback protection. ### Method `disable(): void` ### Returns `void` ``` -------------------------------- ### isShutdown Source: https://nodeshift.dev/opossum Determines if the circuit breaker has been shut down. ```APIDOC ## isShutdown ### Description Determines if the circuit has been shutdown. ### Type - **Boolean** ``` -------------------------------- ### CircuitBreaker Events Source: https://nodeshift.dev/opossum The CircuitBreaker class emits various events to signal its state and operation outcomes. These events can be listened to for monitoring and control. ```APIDOC ## CircuitBreaker Events ### halfOpen Emitted after `options.resetTimeout` has elapsed, allowing for a single attempt to call the service again. If that attempt is successful, the circuit will be closed. Otherwise it remains open. ### close Emitted when the breaker is reset allowing the action to execute again. ### open Emitted when the breaker opens because the action has failure percentage greater than `options.errorThresholdPercentage`. ### shutdown Emitted when the circuit breaker has been shut down. ### fire Emitted when the circuit breaker action is executed. ### cacheHit Emitted when the circuit breaker is using the cache and finds a value. ### cacheMiss Emitted when the circuit breaker does not find a value in the cache, but the cache option is enabled. ### reject Emitted when the circuit breaker is open and failing fast. ### timeout Emitted when the circuit breaker action takes longer than `options.timeout`. ### success Emitted when the circuit breaker action succeeds. ### semaphoreLocked Emitted when the rate limit has been reached and there are no more locks to be obtained. ### healthCheckFailed Emitted with the user-supplied health check function returns a rejected promise. ### fallback Emitted when the circuit breaker executes a fallback function. ### failure Emitted when the circuit breaker action fails. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.