axios-retryer
Version:
axios-retryer is an advanced Axios request manager offering intelligent retry logic with token refresh, concurrency control, priority queuing, and a flexible plugin architecture, all built with TypeScript for robust HTTP client integrations.
178 lines (177 loc) • 6.25 kB
TypeScript
import { RetryManager } from '../../core/RetryManager';
import { RetryPlugin } from '../../types';
import { AxiosError } from 'axios';
/**
* Configuration options for the Circuit Breaker behavior.
*/
export interface CircuitBreakerOptions {
/**
* Number of consecutive failures required to trip the circuit.
* Once this threshold is exceeded, the circuit transitions from `CLOSED` to `OPEN`.
*/
failureThreshold: number;
/**
* Duration (in milliseconds) the circuit remains in the `OPEN` state
* before allowing a test request in the `HALF_OPEN` state.
*/
openTimeout: number;
/**
* Maximum number of test requests allowed in `HALF_OPEN` state
* before deciding to either reset (back to `CLOSED`) or trip again to `OPEN`.
*/
halfOpenMax: number;
/**
* Number of successful test requests required in HALF_OPEN state to reset the circuit.
* This allows for more confidence before fully closing the circuit.
* Must be <= halfOpenMax.
*/
successThreshold?: number;
/**
* If true, uses a sliding window approach to count failures over time rather than consecutive failures.
* This provides more accurate failure detection in high-volume systems.
*/
useSlidingWindow?: boolean;
/**
* The duration (in milliseconds) of the sliding window when useSlidingWindow is true.
* Only failures within this time period are counted toward the failure threshold.
*/
slidingWindowSize?: number;
/**
* Callback function to determine which errors should contribute to circuit breaking.
* This allows selective monitoring of specific error types.
* If not provided, all errors count.
*/
shouldCountError?: (error: AxiosError) => boolean;
/**
* Adaptive timeout configuration. When true, the circuit breaker will track response times
* and adjust timeouts accordingly.
*/
adaptiveTimeout?: boolean;
/**
* Percentile (0-1) to use for adaptive timeout calculation. Default is 0.95 (95th percentile).
*/
adaptiveTimeoutPercentile?: number;
/**
* Number of historical response times to track for adaptive timeout calculation.
*/
adaptiveTimeoutSampleSize?: number;
/**
* Timeout multiplier (e.g., 1.5 = 150% of the calculated percentile).
*/
adaptiveTimeoutMultiplier?: number;
/**
* Allow specific endpoints to be excluded from circuit breaking.
* These URLs will always be allowed through regardless of circuit state.
*/
excludeUrls?: (string | RegExp)[];
}
/**
* Enhanced CircuitBreakerPlugin
*
* This plugin implements an advanced Circuit Breaker pattern with:
* - Sliding window failure counting (time-based rather than just consecutive)
* - Selective error monitoring (filter which errors should trip the circuit)
* - Adaptive timeout management (learns from response times)
* - Granular recovery with success threshold
* - URL exclusion capabilities
*
* When enabled, it monitors for failure patterns and temporarily "opens the circuit"
* to prevent further calls to problematic services, with intelligent recovery mechanisms.
*
* @implements {RetryPlugin}
*/
export declare class CircuitBreakerPlugin implements RetryPlugin {
readonly name = "CircuitBreakerPlugin";
readonly version = "2.0.0";
private _options;
private _state;
private _failureCount;
private _successCount;
private _halfOpenCount;
private _nextAttempt;
private _requestInterceptorId?;
private _responseInterceptorId?;
private _manager;
private _recentFailures;
private _responseMetrics;
static STATES: {
CLOSED: string;
OPEN: string;
HALF_OPEN: string;
};
/**
* Creates an instance of CircuitBreakerPlugin with advanced options.
* @param {Partial<CircuitBreakerOptions>} [options] - Configuration options.
*/
constructor(options?: Partial<CircuitBreakerOptions>);
/**
* Initializes the plugin by setting up request and response interceptors.
* Called when the plugin is attached.
*
* @param {RetryManager} manager - The RetryManager instance.
*/
initialize(manager: RetryManager): void;
/**
* Called before the plugin is removed.
* Ejects the interceptors.
*
* @param {RetryManager} manager - The RetryManager instance.
*/
onBeforeDestroyed(manager: RetryManager): void;
/**
* Returns the current state of the circuit breaker.
* Useful for monitoring or metrics collection.
*/
getState(): typeof CircuitBreakerPlugin.STATES[keyof typeof CircuitBreakerPlugin.STATES];
/**
* Returns metrics about the circuit breaker's operation.
* Includes current failure count, state, and time until next attempt.
*/
getMetrics(): Record<string, any>;
/**
* Trips the circuit by transitioning it to OPEN state.
* Sets the next attempt time based on the openTimeout option.
*/
private _trip;
/**
* Resets the circuit by transitioning it back to CLOSED state.
*/
private _reset;
/**
* Transitions the circuit to HALF_OPEN state, allowing test requests.
*/
private _transitionToHalfOpen;
/**
* Adds a failure to the sliding window for time-based failure tracking.
*/
private _addFailureToSlidingWindow;
/**
* Removes failures that are outside the sliding window timeframe.
*/
private _cleanupOldFailures;
/**
* Gets the number of failures in the current sliding window.
*/
private _getFailureCountInWindow;
/**
* Tracks response time for adaptive timeout calculation.
*/
private _trackResponseTime;
/**
* Updates the timeout percentile calculation for a specific URL.
*/
private _updateTimeoutPercentile;
/**
* Normalizes a URL for grouping similar endpoints.
* e.g., /users/123 and /users/456 become /users/:id
*/
private _normalizeUrl;
/**
* Checks if a URL is excluded from circuit breaking.
*/
private _isUrlExcluded;
/**
* Helper method for logging with the appropriate log level.
*/
private _log;
}