src — networking

Module: src-networking Cohesion: 0.80 Members: 0

src — networking

The src/networking module provides robust utilities for building resilient and fault-tolerant network interactions within the Code Buddy application. It encapsulates common patterns like Circuit Breakers and Health Checks, along with re-exporting related utilities for retries and rate limiting.

This module is crucial for ensuring the stability and reliability of services that interact with external APIs or internal microservices, preventing cascading failures and providing insights into endpoint health.

1. Overview

The src/networking module aggregates several key functionalities:

This documentation focuses on the CircuitBreaker and HealthCheckManager components, as they are defined within this module.

2. Circuit Breaker (src/networking/circuit-breaker.ts)

The CircuitBreaker class implements the Circuit Breaker pattern, a critical fault-tolerance mechanism. It prevents an application from repeatedly trying to execute an operation that is likely to fail, thereby saving resources and preventing cascading failures.

2.1 Core Concepts

The circuit breaker operates through three primary states:

2.2 CircuitBreaker Class

The CircuitBreaker class manages the state and logic for a single circuit.

2.2.1 Initialization and Options

A CircuitBreaker instance is created with CircuitBreakerOptions:

interface CircuitBreakerOptions {
  failureThreshold?: number; class="hl-cmt">// Default: 5
  resetTimeout?: number;     class="hl-cmt">// Default: 30000ms (30 seconds)
  successThreshold?: number; class="hl-cmt">// Default: 2
  failureWindow?: number;    class="hl-cmt">// Default: 60000ms (60 seconds)
  isFailure?: (error: unknown) => boolean; class="hl-cmt">// Custom error check
  onStateChange?: (from: CircuitState, to: CircuitState) => void; class="hl-cmt">// Callback
}

const breaker = new CircuitBreaker({
  failureThreshold: 3,
  resetTimeout: 15000,
  isFailure: (err) => err instanceof NetworkError, class="hl-cmt">// Only trip on network errors
});

2.2.2 Executing Operations

The primary way to interact with the circuit breaker is through the execute method:

async execute<T>(fn: () => Promise<T>): Promise<T>

This method wraps an asynchronous function (fn) and applies the circuit breaker logic:

  1. It first calls this.canExecute() to determine if the current state allows the request.

  1. If allowed, it executes fn().
  2. On successful completion of fn(), this.onSuccess() is called, potentially transitioning the circuit from HALF_OPEN to CLOSED.
  3. On failure of fn(), this.onFailure() is called (if options.isFailure returns true for the error), potentially transitioning the circuit from CLOSED or HALF_OPEN to OPEN.

2.2.3 State Management

The internal methods onSuccess(), onFailure(), canExecute(), and transitionTo() manage the circuit's state transitions and failure/success counts.

2.2.4 Utility Methods

2.2.5 Events

The CircuitBreaker extends EventEmitter and emits the following events:

2.2.6 Global Circuit Breaker Registry

The module also provides global functions for managing named circuit breakers:

2.2.7 Circuit Breaker State Diagram

stateDiagram
    direction LR
    [*] --> CLOSED
    CLOSED --> OPEN : Failures > Threshold
    OPEN --> HALF_OPEN : Reset Timeout
    HALF_OPEN --> CLOSED : Successes > Threshold
    HALF_OPEN --> OPEN : Any Failure
    CLOSED --> CLOSED : Success
    OPEN --> OPEN : Blocked

2.3 Usage Example

import { getCircuitBreaker } from &#39;./networking/circuit-breaker.js&#39;;

const myServiceBreaker = getCircuitBreaker(&#39;my-external-service&#39;, {
  failureThreshold: 5,
  resetTimeout: 60000, class="hl-cmt">// 1 minute
  successThreshold: 3,
});

myServiceBreaker.on(&#39;stateChange&#39;, ({ from, to }) => {
  console.log(`Circuit for &#39;my-external-service&#39; changed from ${from} to ${to}`);
});

async function callExternalService(): Promise<string> {
  return myServiceBreaker.execute(async () => {
    console.log(&#39;Attempting to call external service...&#39;);
    class="hl-cmt">// Simulate an API call
    const response = await fetch(&#39;https:class="hl-cmt">//api.example.com/data&#39;);
    if (!response.ok) {
      throw new Error(`Service responded with status: ${response.status}`);
    }
    const data = await response.text();
    console.log(&#39;Service call successful.&#39;);
    return data;
  });
}

class="hl-cmt">// Example usage loop
setInterval(async () => {
  try {
    const result = await callExternalService();
    class="hl-cmt">// console.log(&#39;Received:&#39;, result.substring(0, 20));
  } catch (error: any) {
    console.error(&#39;Service call failed or blocked:&#39;, error.message);
    console.log(&#39;Current breaker state:&#39;, myServiceBreaker.getState());
    if (myServiceBreaker.getState() === &#39;OPEN&#39;) {
      console.log(`Retry in: ${Math.ceil(myServiceBreaker.getTimeUntilRetry() / 1000)}s`);
    }
  }
  console.log(myServiceBreaker.formatStats());
  console.log(&#39;---&#39;);
}, 5000);

3. Health Check (src/networking/health-check.ts)

The HealthCheckManager provides a centralized way to monitor the health and performance of various API endpoints. It tracks status, latency, and failure counts, enabling applications to make informed decisions about routing requests or alerting operators.

3.1 Core Concepts

3.2 HealthCheckManager Class

The HealthCheckManager class is responsible for managing and performing health checks.

3.2.1 Initialization and Options

A HealthCheckManager instance is created with HealthCheckOptions:

interface HealthCheckOptions {
  interval?: number;          class="hl-cmt">// Default: 30000ms (30 seconds)
  timeout?: number;           class="hl-cmt">// Default: 5000ms (5 seconds)
  failureThreshold?: number;  class="hl-cmt">// Default: 3
  degradedThreshold?: number; class="hl-cmt">// Default: 2000ms (2 seconds)
  maxHistory?: number;        class="hl-cmt">// Default: 100
  checkFn?: (url: string) => Promise<boolean>; class="hl-cmt">// Custom check function
}

const manager = new HealthCheckManager({
  interval: 10000, class="hl-cmt">// Check every 10 seconds
  failureThreshold: 2,
  checkFn: async (url) => {
    class="hl-cmt">// Custom logic, e.g., check a specific API endpoint
    const response = await fetch(`${url}/health`);
    return response.status === 200;
  },
});

3.2.2 Endpoint Management

3.2.3 Performing Checks

3.2.4 Reporting and Querying

3.2.5 Events

The HealthCheckManager extends EventEmitter and emits the following events:

3.2.6 Global Health Check Manager

The module provides global functions for managing a singleton HealthCheckManager instance:

3.2.7 Health Status State Diagram

stateDiagram
    direction LR
    [*] --> unknown
    unknown --> healthy : Check Success
    unknown --> degraded : Check Failure (below threshold)
    unknown --> unhealthy : Check Failure (above threshold)
    healthy --> degraded : High Latency
    healthy --> unhealthy : Failures > Threshold
    degraded --> healthy : Low Latency, Success
    degraded --> unhealthy : Failures > Threshold
    unhealthy --> healthy : Recovered

3.3 Usage Example

import { getHealthCheckManager } from &#39;./networking/health-check.js&#39;;

const healthManager = getHealthCheckManager({
  interval: 5000, class="hl-cmt">// Check every 5 seconds
  degradedThreshold: 1000, class="hl-cmt">// Degraded if latency > 1s
  failureThreshold: 2, class="hl-cmt">// Unhealthy after 2 consecutive failures
});

healthManager.addEndpoint(&#39;https:class="hl-cmt">//jsonplaceholder.typicode.com/posts/1&#39;);
healthManager.addEndpoint(&#39;https:class="hl-cmt">//non-existent-service.com/health&#39;); // Will fail
healthManager.addEndpoint(&#39;https:class="hl-cmt">//httpbin.org/delay/1&#39;); // Will be degraded due to latency

healthManager.on(&#39;check&#39;, ({ url, result }) => {
  class="hl-cmt">// console.log(`Checked ${url}: ${result.status} (${result.latency}ms)`);
});

healthManager.on(&#39;unhealthy&#39;, ({ url, result }) => {
  console.warn(`🚨 Endpoint UNHEALTHY: ${url} - ${result.error}`);
});

healthManager.on(&#39;recovered&#39;, ({ url }) => {
  console.info(`✅ Endpoint RECOVERED: ${url}`);
});

class="hl-cmt">// Start continuous monitoring
healthManager.startMonitoring(&#39;https:class="hl-cmt">//jsonplaceholder.typicode.com/posts/1&#39;);
healthManager.startMonitoring(&#39;https:class="hl-cmt">//non-existent-service.com/health&#39;);
healthManager.startMonitoring(&#39;https:class="hl-cmt">//httpbin.org/delay/1&#39;);


class="hl-cmt">// Periodically log summary
setInterval(() => {
  console.log(&#39;\n--- Health Check Report ---&#39;);
  console.log(healthManager.formatHealth());
  const healthiest = healthManager.getHealthiestEndpoint([
    &#39;https:class="hl-cmt">//jsonplaceholder.typicode.com/posts/1&#39;,
    &#39;https:class="hl-cmt">//non-existent-service.com/health&#39;,
    &#39;https:class="hl-cmt">//httpbin.org/delay/1&#39;
  ]);
  console.log(`Healthiest endpoint: ${healthiest || &#39;None&#39;}`);
  console.log(&#39;---------------------------\n&#39;);
}, 15000);

class="hl-cmt">// Clean up after a while
setTimeout(() => {
  console.log(&#39;Disposing health check manager...&#39;);
  healthManager.dispose();
}, 60000);

The src/networking/index.ts file re-exports several related utilities from the src/utils module, centralizing access to common networking patterns:

These are useful for handling transient network errors or temporary service unavailability.

These prevent overwhelming services with too many requests in a short period.

Developers should refer to the documentation for src/utils/retry.ts and src/utils/rate-limiter.ts for detailed usage of these re-exported utilities.

5. Conclusion

The src/networking module provides a robust foundation for building resilient and observable network interactions. By leveraging CircuitBreaker for fault tolerance and HealthCheckManager for proactive monitoring, developers can create more stable and reliable applications that gracefully handle external service dependencies. The re-export of retry and rate-limiting utilities further enhances this capability, offering a comprehensive toolkit for network-aware development.