Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 | 30x 30x 30x 29x 29x 29x 29x 29x 29x 29x 29x 29x 25x 4x 29x 29x 29x 29x 29x 29x 29x 2x 27x 29x | /**
* Health Check Service
*
* Provides a lightweight, synchronous-friendly health snapshot for the
* MCP server. The snapshot is designed to be consumed by:
* - Monitoring integrations (CloudWatch, Prometheus, etc.)
* - Future CLI health commands
*
* **Intelligence Perspective:** Operational health metrics are a
* prerequisite for reliable intelligence product delivery—degraded
* connectivity or exhausted rate limits must surface immediately.
*
* **Business Perspective:** Health endpoints support SLA dashboards and
* enable proactive incident response before customers are impacted.
*
* ISMS Policy: MO-001 (Monitoring and Alerting), PE-001 (Performance Standards)
*
* @module services/HealthService
*/
import type { RateLimiter, RateLimiterStatus } from '../utils/rateLimiter.js';
import type { MetricsService } from './MetricsService.js';
import { MetricName } from './MetricsService.js';
// ── Public types ──────────────────────────────────────────────────
/**
* Overall server health verdict.
*
* | Value | Meaning |
* |-------------|---------|
* | `healthy` | All subsystems operating normally |
* | `degraded` | One or more subsystems impaired but functional |
* | `unhealthy` | Critical subsystem failure |
*/
export type HealthStatusLevel = 'healthy' | 'degraded' | 'unhealthy';
/**
* Rate-limiter status snapshot for health reporting.
* Type alias of {@link RateLimiterStatus} to prevent the two from drifting.
*/
export type RateLimiterHealthStatus = RateLimiterStatus;
/**
* Cache status snapshot for health reporting.
*/
export interface CacheHealthStatus {
/** Whether the cache is populated (has at least one entry) */
populated: boolean;
/** Human-readable description of cache state */
description: string;
}
/**
* Full health status returned by {@link HealthService.checkHealth}.
*/
export interface HealthStatus {
/** Overall health verdict */
status: HealthStatusLevel;
/**
* Whether the EP API base URL is reachable (based on recent metrics).
* `null` means no API calls have been recorded yet — reachability is unknown.
*/
epApiReachable: boolean | null;
/** Cache subsystem status */
cache: CacheHealthStatus;
/** Rate-limiter subsystem status */
rateLimiter: RateLimiterHealthStatus;
/** ISO-8601 timestamp of this health snapshot */
timestamp: string;
/** Server uptime in milliseconds */
uptimeMs: number;
}
// ── HealthService implementation ──────────────────────────────────
/**
* Health Check Service
*
* Aggregates status from the rate limiter and metrics service to
* produce a structured {@link HealthStatus} snapshot.
*
* The check is intentionally **synchronous-safe** – it never makes
* network calls. Network reachability is inferred from recent
* metrics (EP API error rate).
*
* @example
* ```typescript
* const healthService = new HealthService(rateLimiter, metricsService);
* const status = healthService.checkHealth();
* console.log(status.status); // 'healthy' | 'degraded' | 'unhealthy'
* ```
*/
export class HealthService {
private readonly startTime: number;
/**
* Creates a new {@link HealthService} instance.
*
* @param rateLimiter - Rate limiter whose token availability is checked as
* part of the degraded-state heuristic
* @param metricsService - Metrics service providing EP API call and error
* counters used to infer reachability
*
* @example
* ```typescript
* const healthService = new HealthService(
* createStandardRateLimiter(),
* new MetricsService()
* );
* ```
*
* @since 0.8.0
*/
constructor(
private readonly rateLimiter: RateLimiter,
private readonly metricsService: MetricsService
) {
this.startTime = Date.now();
}
/**
* Produces a health status snapshot.
*
* Checks:
* 1. Rate-limiter token availability (degraded if < 10 %)
* 2. EP API error counter (unhealthy if recent errors > 0 with no successes)
*
* The check is **synchronous-safe** — it never makes network calls.
* Reachability is inferred from cached metric counters.
*
* @returns Structured {@link HealthStatus} object with `status`,
* `epApiReachable`, `cache`, `rateLimiter`, `timestamp`, and `uptimeMs`
* @throws {Error} If the underlying metrics or rate-limiter service throws
* unexpectedly (should not occur under normal operating conditions)
*
* @example
* ```typescript
* const healthService = new HealthService(rateLimiter, metricsService);
* const status = healthService.checkHealth();
* if (status.status !== 'healthy') {
* console.warn('Server degraded:', status);
* }
* ```
*
* @since 0.8.0
*/
checkHealth(): HealthStatus {
const rateLimiterStatus = this.buildRateLimiterStatus();
const epApiReachable = this.isEpApiReachable();
const cacheStatus = this.buildCacheStatus();
const status = this.deriveOverallStatus(rateLimiterStatus, epApiReachable);
return {
status,
epApiReachable,
cache: cacheStatus,
rateLimiter: rateLimiterStatus,
timestamp: new Date().toISOString(),
uptimeMs: Date.now() - this.startTime,
};
}
// ── Private helpers ─────────────────────────────────────────────
/**
* Build rate-limiter snapshot by delegating to RateLimiter.getStatus().
* Cyclomatic complexity: 1
*/
private buildRateLimiterStatus(): RateLimiterHealthStatus {
return this.rateLimiter.getStatus();
}
/**
* Determine EP API reachability from recorded metrics.
* Cyclomatic complexity: 2
*
* Returns `null` when no API calls have been recorded yet (unknown state),
* `false` when all calls failed (error count >= call count > 0),
* `true` when at least some calls succeeded.
*/
private isEpApiReachable(): boolean | null {
const errorCount = this.metricsService.getMetric(MetricName.EP_API_ERROR_COUNT) ?? 0;
const callCount = this.metricsService.getMetric(MetricName.EP_API_CALL_COUNT) ?? 0;
if (callCount === 0) {
// No calls yet — reachability is unknown
return null;
}
// Reachable if at least some calls succeeded
return errorCount < callCount;
}
/**
* Build a descriptive cache status object.
* Cyclomatic complexity: 2
*/
private buildCacheStatus(): CacheHealthStatus {
const hits = this.metricsService.getMetric(MetricName.EP_CACHE_HIT_COUNT) ?? 0;
const misses = this.metricsService.getMetric(MetricName.EP_CACHE_MISS_COUNT) ?? 0;
const total = hits + misses;
const populated = total > 0;
const description = populated
? `${String(hits)} hits / ${String(misses)} misses (${String(total)} total)`
: 'No cache activity yet';
return { populated, description };
}
/**
* Derive the overall health verdict from sub-system checks.
* Cyclomatic complexity: 3
*/
private deriveOverallStatus(
rateLimiter: RateLimiterHealthStatus,
epApiReachable: boolean | null
): HealthStatusLevel {
// null = unknown (no metrics yet) — treat as not failing
if (epApiReachable === false) {
return 'unhealthy';
}
// Degraded if less than 10 % of tokens remain
const rateLimiterLow =
rateLimiter.maxTokens > 0 &&
rateLimiter.availableTokens / rateLimiter.maxTokens < 0.1;
return rateLimiterLow ? 'degraded' : 'healthy';
}
}
|