Skip to content

CircuitBreaker

CircuitBreaker: object

Defined in: Core/CircuitBreaker.ts:39

is: object

Type guards for checking circuit breaker states and errors.

closed: (state) => state is ClosedState = isClosedState

Checks whether a circuit breaker state is Closed.

State<unknown>

state is ClosedState

  • CircuitBreaker.is.open for checking if the circuit is tripped Open.
  • CircuitBreaker.is.halfOpen for checking if the circuit is in trial recovery HalfOpen.
const state = breaker.state();
if (CircuitBreaker.is.closed(state)) {
  console.log("Downstream dependency is healthy");
}

halfOpen: (state) => state is HalfOpenState = isHalfOpenState

Checks whether a circuit breaker state is HalfOpen.

State<unknown>

state is HalfOpenState

  • CircuitBreaker.is.closed for checking if the circuit is healthy Closed.
  • CircuitBreaker.is.open for checking if the circuit is tripped Open.
const state = breaker.state();
if (CircuitBreaker.is.halfOpen(state)) {
  console.log("Testing downstream recovery with trial probes");
}

open: <E>(state) => state is OpenState<E> = isOpenState

Checks whether a circuit breaker state is Open.

E = unknown

State<E>

state is OpenState<E>

  • CircuitBreaker.is.closed for checking if the circuit is healthy Closed.
  • CircuitBreaker.is.halfOpen for checking if the circuit is in trial recovery HalfOpen.
const state = breaker.state();
if (CircuitBreaker.is.open(state)) {
  console.log(`Downstream cooling down. Last error:`, state.lastError);
}

openError: <E>(value) => value is OpenError<E> = isCircuitOpenError

Checks whether a value is a CircuitOpenError.

E = unknown

unknown

value is OpenError<E>

if (CircuitBreaker.is.openError(error)) {
  console.warn(`Circuit is open. Retry after ${error.retryAfterMs}ms`);
}

make: <E>(config) => CircuitBreaker<E> = makeCircuitBreaker

Creates a stateful CircuitBreaker with the provided configuration options.

E = unknown

Config<E>

CircuitBreaker<E>

const breaker = CircuitBreaker.make<NetworkError>({
  failureThreshold: 5,
  resetTimeout: Duration.seconds(30),
  successThreshold: 2,
  shouldTrip: (err) => err.isTimeout || err.status >= 500,
});