@sebspark/health-check 2.1.0 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +11 -5
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +8 -3
- package/dist/index.mjs.map +1 -1
- package/package.json +5 -5
package/dist/index.d.mts
CHANGED
|
@@ -2,6 +2,10 @@ import { Router } from "express";
|
|
|
2
2
|
|
|
3
3
|
//#region src/types.d.ts
|
|
4
4
|
type DependencyStatusValue = 'ok' | 'degraded' | 'error';
|
|
5
|
+
type DependencyStatus = {
|
|
6
|
+
status: DependencyStatusValue;
|
|
7
|
+
details?: Record<string, unknown> | undefined;
|
|
8
|
+
};
|
|
5
9
|
type StatusValue = DependencyStatusValue | 'unknown' | 'draining';
|
|
6
10
|
type Impact = 'critical' | 'non_critical';
|
|
7
11
|
type Mode = 'inline' | 'polled' | 'async';
|
|
@@ -139,7 +143,7 @@ type BaseConfig = {
|
|
|
139
143
|
* `syncCall` runs **only** when {@link DependencyMonitor.check} is invoked.
|
|
140
144
|
*/
|
|
141
145
|
type SyncInlineConfig = BaseConfig & {
|
|
142
|
-
/** Performs the check immediately when {@link DependencyMonitor.check} is called. */syncCall: () => Promise<DependencyStatusValue | Error>;
|
|
146
|
+
/** Performs the check immediately when {@link DependencyMonitor.check} is called. */syncCall: () => Promise<DependencyStatus | DependencyStatusValue | Error>;
|
|
143
147
|
asyncCall?: never;
|
|
144
148
|
pollRate?: undefined;
|
|
145
149
|
retryRate?: undefined;
|
|
@@ -149,7 +153,7 @@ type SyncInlineConfig = BaseConfig & {
|
|
|
149
153
|
* `syncCall` runs on an interval (`pollRate`) and results are cached.
|
|
150
154
|
*/
|
|
151
155
|
type SyncPolledConfig = BaseConfig & {
|
|
152
|
-
/** Performs the check at each poll interval. */syncCall: () => Promise<DependencyStatusValue | Error>; /** Polling interval in milliseconds. */
|
|
156
|
+
/** Performs the check at each poll interval. */syncCall: () => Promise<DependencyStatus | DependencyStatusValue | Error>; /** Polling interval in milliseconds. */
|
|
153
157
|
pollRate: number;
|
|
154
158
|
asyncCall?: never;
|
|
155
159
|
};
|
|
@@ -160,9 +164,9 @@ type SyncPolledConfig = BaseConfig & {
|
|
|
160
164
|
type AsyncConfig = BaseConfig & {
|
|
161
165
|
/**
|
|
162
166
|
* Starts an asynchronous check. Must call `reportResponse` once a result is available.
|
|
163
|
-
* The callback may be invoked with a `DependencyStatusValue` or an `Error`.
|
|
167
|
+
* The callback may be invoked with a `DependencyStatus | DependencyStatusValue` or an `Error`.
|
|
164
168
|
*/
|
|
165
|
-
asyncCall: (reportResponse: (status: DependencyStatusValue | Error) => void | Promise<void>) => void | Promise<void>; /** Polling interval in milliseconds. */
|
|
169
|
+
asyncCall: (reportResponse: (status: DependencyStatus | DependencyStatusValue | Error) => void | Promise<void>) => void | Promise<void>; /** Polling interval in milliseconds. */
|
|
166
170
|
pollRate: number;
|
|
167
171
|
syncCall?: never;
|
|
168
172
|
};
|
|
@@ -204,6 +208,8 @@ declare class DependencyMonitor {
|
|
|
204
208
|
private observed?;
|
|
205
209
|
/** Freshness timestamps for last check/success. */
|
|
206
210
|
private freshness?;
|
|
211
|
+
/** Optional details returned by the helth check call. */
|
|
212
|
+
private details?;
|
|
207
213
|
/** Indicates whether this monitor has been disposed. */
|
|
208
214
|
private isDisposed;
|
|
209
215
|
/** Internal timer handle for polling/retry. */
|
|
@@ -383,5 +389,5 @@ declare class HealthMonitor {
|
|
|
383
389
|
dispose(): void;
|
|
384
390
|
}
|
|
385
391
|
//#endregion
|
|
386
|
-
export { AsyncConfig, CheckError, DependencyCheck, DependencyMonitor, DependencyMonitorConfig, DependencyStatusValue, Entity, Freshness, HealthMonitor, HealthMonitorConfig, HealthSummary, Impact, Link, Liveness, Mode, Observed, Process, ReadinessPayload, ReadinessSummary, Status, StatusValue, SyncInlineConfig, SyncPolledConfig, System, TimeoutError, UnknownError, Verb };
|
|
392
|
+
export { AsyncConfig, CheckError, DependencyCheck, DependencyMonitor, DependencyMonitorConfig, DependencyStatus, DependencyStatusValue, Entity, Freshness, HealthMonitor, HealthMonitorConfig, HealthSummary, Impact, Link, Liveness, Mode, Observed, Process, ReadinessPayload, ReadinessSummary, Status, StatusValue, SyncInlineConfig, SyncPolledConfig, System, TimeoutError, UnknownError, Verb };
|
|
387
393
|
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/types.ts","../src/dependency-monitor.ts","../src/health-monitor.ts"],"mappings":";;;KAAY,qBAAA;AAAA,KACA,WAAA,GAAc,qBAAA;AAAA,KACd,MAAA;AAAA,KACA,IAAA;AAAA,KAEA,IAAA;AAAA,KAEA,IAAA;EACV,MAAA,EAAQ,IAAA;EACR,IAAA;AAAA;AAAA,UAGe,MAAA;EACf,IAAA,EAAM,CAAA;EACN,KAAA,EAAO,MAAA,SAAe,IAAA;AAAA;AAAA,KAGZ,MAAA;EACV,MAAA,EAAQ,WAAA;AAAA;AAAA,KAGE,MAAA;EACV,QAAA;EACA,QAAA,EAAU,MAAA,CAAO,QAAA;EACjB,OAAA;EACA,IAAA;EACA,MAAA;EACA,OAAA;EACA,QAAA;EACA,OAAA;EACA,YAAA;EACA,IAAA;IACE,KAAA;IACA,KAAA;IACA,QAAA;EAAA;AAAA;AAAA,KAIQ,OAAA;EACV,GAAA;EACA,IAAA;EACA,MAAA;EACA,MAAA,EAAQ,MAAA,CAAO,WAAA;AAAA;AAAA,KAGL,QAAA,GAAW,MAAA;EACrB,SAAA;EACA,MAAA,EAAQ,MAAA;EACR,OAAA,EAAS,OAAA;AAAA;AAAA,KAGC,SAAA;EACV,WAAA;EACA,WAAA;AAAA;AAAA,KAGU,QAAA;EACV,SAAA;EAAA,CACC,CAAA;AAAA;AAAA,KAGS,UAAA;EACV,IAAA;EACA,OAAA;AAAA;AAAA,KAGU,eAAA,GAAkB,MAAA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;EAAA,CCwRlB,MAAA,CAAO,OAAA;EDvRH;;;;;ECgSL,OAAA,CAAA;AAAA;;;UChWQ,mBAAA;EACf,QAAA;AAAA;;;AFjBF;;;;;;;;;;AAIA;;;;;AACA;;;;;AACA;;;;;AAEA;;;;;cE4Ca,aAAA;EAAA,iBACM,OAAA;EAAA,iBACA,YAAA;EF3CL;;;cEiDA,MAAA,GAAS,mBAAA;EFhDjB;;AAGN;;;;;;;;;;;;;;EEuES,aAAA,CAAc,IAAA,UAAc,UAAA,EAAY,iBAAA;EFrErB;AAG5B;;EAH4B,QE6ElB,YAAA;EFzER;;AAGF;EEkJS,IAAA,CAAA,GApFyD,MAAA;;;;EA2FzD,IAAA,CAAA,GAPI,QAAA;EFhJD;;;;;;;;;;;;;;;AAeZ;;;;;;;;;;;;AAOA;;EEkKe,KAAA,CAAA,GAAS,OAAA,CAAQ,gBAAA;EAyGjB,MAAA,CAAA,GAAM,OAAA,CAAA,aAAA;EFzQX;;;EAAA,IE0RG,MAAA,CAAA,GAAM,MAAA;EF5RI;;;EAAA,CEmSb,MAAA,CAAO,OAAA;EFhSf;;;;AAGF;EEsSS,OAAA,CAAA;AAAA"}
|
package/dist/index.mjs
CHANGED
|
@@ -95,6 +95,8 @@ var DependencyMonitor = class {
|
|
|
95
95
|
observed;
|
|
96
96
|
/** Freshness timestamps for last check/success. */
|
|
97
97
|
freshness;
|
|
98
|
+
/** Optional details returned by the helth check call. */
|
|
99
|
+
details;
|
|
98
100
|
/** Indicates whether this monitor has been disposed. */
|
|
99
101
|
isDisposed = false;
|
|
100
102
|
/** Internal timer handle for polling/retry. */
|
|
@@ -180,9 +182,11 @@ var DependencyMonitor = class {
|
|
|
180
182
|
*/
|
|
181
183
|
handleDependencyResponse(response, duration) {
|
|
182
184
|
if (response instanceof Error) return this.handleDependencyError(response);
|
|
183
|
-
|
|
185
|
+
const normalized = typeof response === "string" ? { status: response } : response;
|
|
186
|
+
if (normalized.status === "error") return this.handleDependencyError(new UnknownError());
|
|
184
187
|
this.error = void 0;
|
|
185
|
-
this.
|
|
188
|
+
this.details = normalized.details;
|
|
189
|
+
this.status = normalized.status === "ok" && duration <= this.config.healthyLimitMs ? "ok" : "degraded";
|
|
186
190
|
const end = /* @__PURE__ */ new Date();
|
|
187
191
|
this.freshness = {
|
|
188
192
|
lastChecked: end.toISOString(),
|
|
@@ -230,6 +234,7 @@ var DependencyMonitor = class {
|
|
|
230
234
|
impact: this.config.impact,
|
|
231
235
|
mode: this.mode,
|
|
232
236
|
freshness: this.freshness,
|
|
237
|
+
details: this.details,
|
|
233
238
|
observed: this.observed,
|
|
234
239
|
error: this.error
|
|
235
240
|
};
|
|
@@ -474,7 +479,7 @@ var HealthMonitor = class {
|
|
|
474
479
|
const degradedReasons = [];
|
|
475
480
|
for (const [name, c] of Object.entries(checks)) {
|
|
476
481
|
const isCritical = c.impact === "critical";
|
|
477
|
-
if (c.status === "ok") if (isCritical) criticalOk++;
|
|
482
|
+
if (c.status === "unknown") {} else if (c.status === "ok") if (isCritical) criticalOk++;
|
|
478
483
|
else nonCritOk++;
|
|
479
484
|
else if (c.status === "degraded") {
|
|
480
485
|
if (isCritical) criticalFailing++;
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../src/types.ts","../src/timing.ts","../src/dependency-monitor.ts","../src/static-checks.ts","../src/health-monitor.ts"],"sourcesContent":["export type DependencyStatusValue = 'ok' | 'degraded' | 'error'\nexport type StatusValue = DependencyStatusValue | 'unknown' | 'draining'\nexport type Impact = 'critical' | 'non_critical'\nexport type Mode = 'inline' | 'polled' | 'async'\n\nexport type Verb = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'\n\nexport type Link = {\n method: Verb\n href: string\n}\n\nexport interface Entity<T> {\n data: T\n links: Record<string, Link>\n}\n\nexport type Status = {\n status: StatusValue\n}\n\nexport type System = {\n hostname: string\n platform: NodeJS.Platform\n release: string\n arch: string\n uptime: number\n loadavg: [number, number, number] // 1, 5, 15 min\n totalmem: number\n freemem: number\n memUsedRatio: number // 0..1\n cpus: {\n count: number\n model?: string\n speedMHz?: number\n }\n}\n\nexport type Process = {\n pid: number\n node: string\n uptime: number\n memory: NodeJS.MemoryUsage\n}\n\nexport type Liveness = Status & {\n timestamp: string\n system: System\n process: Process\n}\n\nexport type Freshness = {\n lastChecked: string\n lastSuccess: string | null\n}\n\nexport type Observed = {\n latencyMs: number | null\n [k: string]: unknown\n}\n\nexport type CheckError = {\n code: string\n message: string\n}\n\nexport type DependencyCheck = Status & {\n impact: Impact\n mode: Mode\n freshness: Freshness\n observed?: Observed\n details?: Record<string, unknown>\n error?: CheckError | null\n since?: string | null\n}\n\nexport type ReadinessSummary = {\n critical: { ok: number; failing: number }\n nonCritical: { ok: number; degraded: number; failing: number }\n degradedReasons: string[]\n}\n\nexport type ReadinessPayload = Status & {\n timestamp: string\n service?: { name?: string; version?: string; instanceId?: string }\n summary: ReadinessSummary\n checks: Record<string, DependencyCheck>\n}\n\nexport type HealthSummary = Status &\n Pick<ReadinessPayload, 'summary' | 'checks'> &\n Pick<Liveness, 'system' | 'process'> & { timestamp: string }\n\nexport class TimeoutError extends Error {\n constructor() {\n super('timeout')\n this.name = 'TimeoutError'\n }\n}\n\nexport class UnknownError extends Error {\n constructor() {\n super('unknown')\n this.name = 'UnknownError'\n }\n}\n","import { TimeoutError } from './types'\n\nexport const wait = (ms: number) =>\n new Promise<void>((resolve) => setTimeout(resolve, ms))\n\nexport const runTimeoutTimer = async (ms: number) => {\n await wait(ms)\n throw new TimeoutError()\n}\n\nexport const runAgainstTimeout = <T>(\n promise: Promise<T>,\n ms?: number | undefined\n): Promise<T> => {\n if ((ms as number) > 0) {\n return Promise.race([promise, runTimeoutTimer(ms as number)])\n }\n\n return promise\n}\n\n/**\n * Throttles an async function:\n * - coalesces concurrent calls into a single in-flight Promise,\n * - after it settles, reuses that settled Promise for `ms` ms,\n * - then clears so the next call invokes `fn` again.\n *\n * Fully preserves the original function signature.\n */\nexport const throttle = <F extends (...args: unknown[]) => Promise<unknown>>(\n fn: F,\n ms: number\n) => {\n type R = ReturnType<F> // a Promise<T>\n\n let current: R | null = null\n let clearHandle: NodeJS.Timeout | null = null\n\n const wrapped = (...args: Parameters<F>): R => {\n if (!current) {\n current = fn(...args) as R\n\n if (clearHandle) {\n clearTimeout(clearHandle)\n clearHandle = null\n }\n\n current.finally(() => {\n if (ms > 0) {\n clearHandle = setTimeout(() => {\n current = null\n clearHandle = null\n }, ms)\n } else {\n current = null\n }\n })\n }\n\n return current\n }\n\n // Cast to F so the returned function has the *identical* callable type\n return wrapped as unknown as F\n}\n\n/**\n * Wraps an async function so that concurrent invocations share the same in-flight Promise.\n * After the Promise settles (resolve or reject), the next call will invoke the function again.\n * Essentially just throttled with timeout 0\n */\nexport const singleFlight = <\n F extends (...args: unknown[]) => Promise<unknown>,\n>(\n fn: F\n) => throttle<F>(fn, 0)\n","import { performance } from 'node:perf_hooks'\nimport { runAgainstTimeout, singleFlight } from './timing'\nimport {\n type CheckError,\n type DependencyCheck,\n type DependencyStatusValue,\n type Freshness,\n type Impact,\n type Mode,\n type Observed,\n type StatusValue,\n TimeoutError,\n UnknownError,\n} from './types'\n\n/**\n * Base configuration shared by all dependency monitor modes.\n */\ntype BaseConfig = {\n /**\n * Importance of the dependency:\n * - `'critical'` → service cannot run without it\n * - `'non_critical'` → service is degraded but still functional if it fails\n */\n impact: Impact\n\n /**\n * Polling interval in milliseconds.\n * - Required for polled and async modes\n * - Must not be set for inline mode\n */\n pollRate?: number\n\n /**\n * Polling interval in milliseconds for failed calls.\n * - Defaults to pollRate for polled and async modes\n * - Must not be set for inline mode\n */\n retryRate?: number\n\n /**\n * Maximum response time in milliseconds considered healthy.\n * - A call resolving within this time window **and** returning `\"ok\"` → status `\"ok\"`\n * - A call resolving after this but **before** `timeoutLimitMs` → status `\"degraded\"`\n */\n healthyLimitMs: number\n\n /**\n * Absolute upper bound in milliseconds; beyond this a call is considered `\"error\"`.\n * - Inline: the awaited call is raced with a timeout and rejected past this limit\n * - Polled/Async: escalate `unknown` → `degraded` at `healthyLimitMs`, then `\"error\"` at `timeoutLimitMs`\n * - Any late `\"ok\"` result after this limit is ignored\n */\n timeoutLimitMs: number\n}\n\n/**\n * Inline mode configuration (no polling).\n * `syncCall` runs **only** when {@link DependencyMonitor.check} is invoked.\n */\nexport type SyncInlineConfig = BaseConfig & {\n /** Performs the check immediately when {@link DependencyMonitor.check} is called. */\n syncCall: () => Promise<DependencyStatusValue | Error>\n asyncCall?: never\n pollRate?: undefined\n retryRate?: undefined\n}\n\n/**\n * Polled mode configuration.\n * `syncCall` runs on an interval (`pollRate`) and results are cached.\n */\nexport type SyncPolledConfig = BaseConfig & {\n /** Performs the check at each poll interval. */\n syncCall: () => Promise<DependencyStatusValue | Error>\n /** Polling interval in milliseconds. */\n pollRate: number\n asyncCall?: never\n}\n\n/**\n * Async mode configuration.\n * `asyncCall` starts a check and must report via the provided callback.\n */\nexport type AsyncConfig = BaseConfig & {\n /**\n * Starts an asynchronous check. Must call `reportResponse` once a result is available.\n * The callback may be invoked with a `DependencyStatusValue` or an `Error`.\n */\n asyncCall: (\n reportResponse: (\n status: DependencyStatusValue | Error\n ) => void | Promise<void>\n ) => void | Promise<void>\n /** Polling interval in milliseconds. */\n pollRate: number\n syncCall?: never\n}\n\n/**\n * Discriminated configuration for a dependency monitor.\n * - {@link SyncInlineConfig} → inline checks on demand\n * - {@link SyncPolledConfig} → synchronous checks on a fixed interval\n * - {@link AsyncConfig} → asynchronous checks that report back via callback\n */\nexport type DependencyMonitorConfig =\n | SyncInlineConfig\n | SyncPolledConfig\n | AsyncConfig\n\n/**\n * Tracks the health of a single dependency in one of three modes:\n *\n * - **inline**: `syncCall` executed only when {@link check} is called\n * - **polled**: `syncCall` executed on `pollRate`; latest result cached\n * - **async**: `asyncCall` executed on `pollRate`, result returned via callback\n *\n * The monitor:\n * - classifies results using `healthyLimitMs` and `timeoutLimitMs`\n * - records freshness (`lastChecked`, `lastSuccess`)\n * - records observed latency (ms) when applicable\n *\n * Status interpretation:\n * - `\"ok\"` only if returned `\"ok\"` **and** latency ≤ `healthyLimitMs`\n * - `\"degraded\"` if returned `\"degraded\"` **or** latency > `healthyLimitMs` but ≤ `timeoutLimitMs`\n * - `\"error\"` if returned `\"error\"`, an `Error`, or exceeded `timeoutLimitMs`\n * - `\"unknown\"` is the initial state before first successful/failed result (polled/async)\n */\nexport class DependencyMonitor {\n /** Immutable configuration for this monitor. */\n private readonly config: DependencyMonitorConfig\n /** Operational mode determined from the configuration. */\n private readonly mode: Mode\n\n /** Last computed status (starts as `\"unknown\"` until first result). */\n private status: StatusValue\n /** Optional error details from the last failure. */\n private error?: CheckError\n /** Last observed metrics (e.g., latency). */\n private observed?: Observed\n /** Freshness timestamps for last check/success. */\n private freshness?: Freshness\n\n /** Indicates whether this monitor has been disposed. */\n private isDisposed = false\n /** Internal timer handle for polling/retry. */\n private timeout?: NodeJS.Timeout\n\n /**\n * Create a new {@link DependencyMonitor}.\n * @param config Monitor configuration (inline, polled, or async).\n */\n constructor(config: DependencyMonitorConfig) {\n this.config = config\n\n this.mode = config.asyncCall\n ? 'async'\n : config.pollRate\n ? 'polled'\n : 'inline'\n\n this.status = 'unknown'\n\n // Deduplicate concurrent inline checks (single-flight).\n if (this.mode === 'inline') {\n this.check = singleFlight(this.check.bind(this))\n }\n\n // Kick off the first cycle for polled/async.\n if (this.mode !== 'inline') {\n this.doCheck()\n }\n }\n\n /** Impact of this dependency (critical/non_critical). */\n public get impact() {\n return this.config.impact\n }\n\n /**\n * Run one check cycle depending on the configured mode.\n * - Inline: no-op here (runs in {@link check})\n * - Polled/Async: invoked automatically and re-scheduled as needed\n */\n private async doCheck() {\n if (this.timeout) {\n clearTimeout(this.timeout)\n }\n if (this.isDisposed) {\n return\n }\n\n if (this.config.syncCall) {\n await this.doSyncCheck()\n } else {\n this.doAsyncCheck()\n }\n }\n\n /**\n * Execute a synchronous (inline/polled) check and update internal state.\n * Classification:\n * - OK if `\"ok\"` and latency ≤ `healthyLimitMs`\n * - Degraded if `\"degraded\"` or latency between `(healthyLimitMs, timeoutLimitMs]`\n * - Error if `\"error\"`, `Error`, or timeout exceeded\n */\n private async doSyncCheck() {\n const start = performance.now()\n\n const { syncCall, timeoutLimitMs } = this.config as SyncInlineConfig\n\n try {\n const response = await runAgainstTimeout(syncCall(), timeoutLimitMs)\n const duration = performance.now() - start\n\n this.handleDependencyResponse(response, duration)\n } catch (err) {\n this.handleDependencyError(err as Error)\n }\n }\n\n /**\n * Execute an asynchronous check (async mode).\n * - Initializes timers to escalate `unknown` → `degraded` → `error`\n * if no callback result arrives within the thresholds.\n * - On callback, clears timers and classifies the result with latency.\n */\n private async doAsyncCheck() {\n const { asyncCall, healthyLimitMs, timeoutLimitMs } = this\n .config as AsyncConfig\n\n const start = performance.now()\n let callActive = true\n let healthTimeout: NodeJS.Timeout | undefined\n let serviceTimeout: NodeJS.Timeout | undefined\n\n asyncCall((response) => {\n if (!callActive) return\n callActive = false\n clearTimeout(healthTimeout)\n clearTimeout(serviceTimeout)\n\n const duration = performance.now() - start\n this.handleDependencyResponse(response, duration)\n })\n\n // Escalate to degraded after healthy limit if still waiting.\n healthTimeout = setTimeout(() => {\n if (callActive) this.status = 'degraded'\n }, healthyLimitMs)\n\n // Escalate to error after timeout limit if still waiting.\n serviceTimeout = setTimeout(() => {\n if (!callActive) return\n callActive = false\n clearTimeout(healthTimeout)\n this.handleDependencyError(new TimeoutError())\n }, timeoutLimitMs)\n }\n\n /**\n * Normalize a successful dependency response into status + metadata.\n * @param response Returned status value or Error from the dependency\n * @param duration Measured latency in milliseconds\n */\n private handleDependencyResponse(\n response: DependencyStatusValue | Error,\n duration: number\n ) {\n if (response instanceof Error) {\n return this.handleDependencyError(response)\n }\n if (response === 'error') {\n return this.handleDependencyError(new UnknownError())\n }\n\n this.error = undefined\n this.status =\n response === 'ok' && duration <= this.config.healthyLimitMs\n ? 'ok'\n : 'degraded'\n\n const end = new Date()\n this.freshness = {\n lastChecked: end.toISOString(),\n lastSuccess: end.toISOString(),\n }\n\n this.observed = { latencyMs: duration }\n\n // Schedule next poll if applicable.\n if (this.config.pollRate && !this.isDisposed) {\n const delay = this.config.pollRate\n this.timeout = setTimeout(() => this.doCheck(), delay)\n }\n }\n\n /**\n * Normalize a failed dependency result into `\"error\"` and update metadata.\n * @param error Error thrown/returned or synthesized (e.g., timeout)\n */\n private handleDependencyError(error: Error & { code?: string }) {\n this.status = 'error'\n this.observed = undefined\n this.error = {\n code: error.code || 'UNKNOWN',\n message: error.message,\n }\n\n const end = new Date()\n if (this.freshness) {\n this.freshness.lastChecked = end.toISOString()\n } else {\n this.freshness = { lastChecked: end.toISOString(), lastSuccess: null }\n }\n\n // Schedule retry/poll if configured.\n if ((this.config.retryRate || this.config.pollRate) && !this.isDisposed) {\n const delay = this.config.retryRate || this.config.pollRate\n this.timeout = setTimeout(() => this.doCheck(), delay)\n }\n }\n\n /**\n * Get a snapshot of the dependency’s current health.\n * - Inline mode: executes the `syncCall` (single-flight guarded)\n * - Polled/Async: returns the cached result\n * @throws if the monitor has been disposed\n */\n public async check(): Promise<DependencyCheck> {\n if (this.isDisposed) {\n throw new Error('DependencyMonitor has been disposed')\n }\n\n if (this.mode === 'inline') {\n await this.doCheck()\n }\n\n const result: DependencyCheck = {\n status: this.status as StatusValue,\n impact: this.config.impact,\n mode: this.mode,\n freshness: this.freshness as Freshness,\n observed: this.observed,\n error: this.error,\n }\n\n return result\n }\n\n /** Symbol-based disposer for use with `using`. */\n public [Symbol.dispose]() {\n this.dispose()\n }\n\n /**\n * Dispose the monitor:\n * - Clears any scheduled timers\n * - Prevents further checks from running\n */\n public dispose() {\n this.isDisposed = true\n if (this.timeout) {\n clearTimeout(this.timeout)\n }\n }\n}\n","import os from 'node:os'\nimport type { Liveness, Status } from './types'\n\nexport const ping = (): Status => ({ status: 'ok' })\nexport const liveness = (): Liveness => {\n const cpus = os.cpus()\n const total = os.totalmem()\n const free = os.freemem()\n\n return {\n status: 'ok',\n timestamp: new Date().toISOString(),\n system: {\n hostname: os.hostname(),\n platform: os.platform(),\n release: os.release(),\n arch: os.arch(),\n uptime: os.uptime(),\n loadavg: os.loadavg() as [number, number, number],\n totalmem: total,\n freemem: free,\n memUsedRatio: total > 0 ? (total - free) / total : 0,\n cpus: {\n count: cpus.length,\n model: cpus[0]?.model,\n speedMHz: cpus[0]?.speed,\n },\n },\n process: {\n pid: process.pid,\n node: process.versions.node,\n uptime: process.uptime(),\n memory: process.memoryUsage(), // rss, heapTotal, heapUsed, external, arrayBuffers\n },\n }\n}\n","import { toEntity } from '@sebspark/hyper-media'\nimport { type ErrorRequestHandler, Router } from 'express'\nimport type {\n DependencyMonitor,\n DependencyMonitorConfig,\n} from './dependency-monitor'\nimport { liveness, ping } from './static-checks'\nimport { throttle } from './timing'\nimport type {\n DependencyCheck,\n HealthSummary,\n Impact,\n ReadinessPayload,\n ReadinessSummary,\n} from './types'\n\nexport interface HealthMonitorConfig {\n throttle: number\n}\n\n/**\n * HealthMonitor wires up standard health check endpoints for an Express app.\n *\n * It provides three endpoints under `/health`:\n * - /ping → lightweight always-OK response (`{ status: \"ok\" }`)\n * - /live → liveness probe (`{ status, uptime, timestamp }`)\n * - /ready → readiness probe with dependency checks (`{ status, checks }`)\n *\n * Dependencies can be added via {@link addDependency} with a {@link DependencyMonitorConfig}.\n * Each dependency is wrapped in a {@link DependencyMonitor} and tracked for readiness.\n *\n * ### Example\n *\n * ```ts\n * import express from 'express'\n * import { HealthMonitor } from './health-monitor'\n *\n * const app = express()\n * const monitor = new HealthMonitor()\n *\n * monitor.addDependency('db', {\n * impact: 'critical',\n * syncCall: async () => {\n * await db.ping()\n * return 'ok'\n * }\n * })\n *\n * app.use(monitor.router)\n * app.listen(3000)\n * ```\n */\nexport class HealthMonitor {\n private readonly _router: Router\n private readonly dependencies: Map<string, DependencyMonitor>\n // private isDisposed = false\n\n /**\n * Create a new HealthMonitor instance with its own router and dependency map.\n */\n constructor(config?: HealthMonitorConfig) {\n this._router = this.createRouter()\n this.dependencies = new Map()\n\n const thr = config ? config.throttle : 10\n if (thr > 0) {\n this.ready = throttle(this.ready.bind(this), thr)\n }\n }\n\n /**\n * Register a named dependency to be checked as part of readiness.\n *\n * @param name - Identifier for the dependency (e.g. \"postgres\", \"redis\").\n * @param dependency - DependencyMonitor\n * @returns this for chaining\n *\n * @example\n * ```ts\n * monitor.addDependency('redis', new DependencyMonitor({\n * impact: 'critical',\n * pollRate: 5000,\n * syncCall: async () => redis.ping() ? 'ok' : 'error'\n * }))\n * ```\n */\n public addDependency(name: string, dependency: DependencyMonitor) {\n this.dependencies.set(name, dependency)\n return this\n }\n\n /**\n * Internal: create the Express router with /health routes.\n */\n private createRouter() {\n const router = Router()\n\n // Health\n router.get('/health', async (req, res, next) => {\n try {\n const health = await this.health()\n res.status(200).json(\n toEntity(req, health, {\n ping: '/health/ping',\n live: '/health/live',\n ready: '/health/ready',\n })\n )\n } catch (err) {\n next?.(err)\n }\n })\n\n // Ping\n router.get('/health/ping', (req, res, next) => {\n try {\n res.status(200).json(\n toEntity(req, this.ping(), {\n health: '/health',\n })\n )\n } catch (err) {\n next?.(err)\n }\n })\n\n // Liveness\n router.get('/health/live', (req, res, next) => {\n try {\n res.status(200).json(\n toEntity(req, this.live(), {\n health: '/health',\n })\n )\n } catch (err) {\n next?.(err)\n }\n })\n\n // Readiness\n router.get('/health/ready', async (req, res, next) => {\n try {\n const readiness = await this.ready()\n const status = readiness.summary.critical.failing > 0 ? 503 : 200\n res.status(status).json(\n toEntity(req, readiness, {\n health: '/health',\n })\n )\n } catch (err) {\n next?.(err)\n }\n })\n\n // Error handler\n const errorHandler: ErrorRequestHandler = (err, _req, res, _next) => {\n const message = err instanceof Error ? err.message : String(err)\n res.status(500).json({\n status: 'error',\n error: { message },\n })\n }\n router.use(errorHandler)\n\n return router\n }\n\n /**\n * Static ping check — always returns `{ status: \"ok\" }`.\n */\n public ping() {\n return ping()\n }\n\n /**\n * Liveness probe: reports uptime and current timestamp.\n */\n public live() {\n return liveness()\n }\n\n /**\n * Readiness probe: runs all registered dependencies in parallel\n * and aggregates their results into an overall status.\n *\n * - Any **critical error** → `\"error\"`\n * - Else any **critical degraded** or any non-critical degraded/error → `\"degraded\"`\n * - Else → `\"ok\"`\n *\n * @returns Object with overall `status` and per-dependency `checks`\n *\n * @example\n * ```json\n * {\n * \"status\": \"ok\",\n * \"checks\": {\n * \"postgres\": {\n * \"status\": \"ok\",\n * \"impact\": \"critical\",\n * \"mode\": \"inline\",\n * \"freshness\": {\n * \"lastChecked\": \"2025-08-19T12:00:00Z\",\n * \"lastSuccess\": \"2025-08-19T12:00:00Z\"\n * },\n * \"observed\": { \"latencyMs\": 12 }\n * }\n * }\n * }\n * ```\n */\n public async ready(): Promise<ReadinessPayload> {\n const entries = Array.from(this.dependencies.entries())\n\n const settled = await Promise.allSettled(\n entries.map(async ([name, monitor]) => {\n const check = await monitor.check()\n return [name, check] as const\n })\n )\n\n const checks: Record<string, DependencyCheck> = {}\n\n for (let i = 0; i < settled.length; i++) {\n const s = settled[i]\n const [name] = entries[i]\n\n if (s.status === 'fulfilled') {\n const [, check] = s.value\n checks[name] = check\n } else {\n checks[name] = {\n status: 'error',\n impact: this.dependencies.get(name)?.impact as Impact,\n mode: 'polled',\n freshness: {\n lastChecked: new Date().toISOString(),\n lastSuccess: null,\n },\n observed: undefined,\n error: {\n code: 'CHECK_FAILED',\n message: String(s.reason ?? 'unknown error'),\n },\n }\n }\n }\n\n // ----- summary -------------------------------------------------------------\n let criticalOk = 0\n let criticalFailing = 0 // counts any non-ok critical (degraded OR error)\n\n let nonCritOk = 0\n let nonCritDegraded = 0\n let nonCritFailing = 0 // non-critical with status === 'error'\n\n const degradedReasons: string[] = []\n\n for (const [name, c] of Object.entries(checks)) {\n const isCritical = c.impact === 'critical'\n if (c.status === 'ok') {\n if (isCritical) criticalOk++\n else nonCritOk++\n } else if (c.status === 'degraded') {\n if (isCritical)\n criticalFailing++ // critical degraded counts as failing\n else nonCritDegraded++\n degradedReasons.push(`${name}:degraded`)\n } else {\n // 'error'\n if (isCritical) criticalFailing++\n else nonCritFailing++\n degradedReasons.push(`${name}:${c.error?.code ?? 'error'}`)\n }\n }\n\n const summary: ReadinessSummary = {\n critical: { ok: criticalOk, failing: criticalFailing },\n nonCritical: {\n ok: nonCritOk,\n degraded: nonCritDegraded,\n failing: nonCritFailing,\n },\n degradedReasons,\n }\n\n // ----- overall status (same rules as before) -------------------------------\n let status: import('./types').StatusValue = 'ok'\n const values = Object.values(checks)\n const anyCriticalError = values.some(\n (c) => c.impact === 'critical' && c.status === 'error'\n )\n const anyDegradedOrError = values.some(\n (c) => c.status === 'degraded' || c.status === 'error'\n )\n const anyCriticalDegraded = values.some(\n (c) => c.impact === 'critical' && c.status === 'degraded'\n )\n\n if (anyCriticalError) status = 'error'\n else if (anyCriticalDegraded || anyDegradedOrError) status = 'degraded'\n\n // ----- payload -------------------------------------------------------------\n const payload: ReadinessPayload = {\n status,\n timestamp: new Date().toISOString(),\n // service: { name, version, instanceId } // (optional; if you add config later)\n summary,\n checks,\n }\n\n return payload\n }\n\n public async health() {\n const { status, checks, summary } = await this.ready()\n const { timestamp, system, process } = this.live()\n\n return {\n status,\n timestamp,\n system,\n process,\n checks,\n summary,\n } as HealthSummary\n }\n\n /**\n * Accessor for the Express router that exposes /health endpoints.\n */\n public get router() {\n return this._router\n }\n\n /**\n * Symbol-based disposer for use with `using`.\n */\n public [Symbol.dispose]() {\n this.dispose()\n }\n\n /**\n * Dispose of the monitor:\n * - marks as disposed\n * - (future: could also stop all dependency monitors)\n */\n public dispose() {\n // this.isDisposed = true\n for (const dependency of this.dependencies.values()) {\n dependency.dispose()\n }\n }\n}\n"],"mappings":";;;;;AA6FA,IAAa,eAAb,cAAkC,MAAM;CACtC,cAAc;AACZ,QAAM,UAAU;AAChB,OAAK,OAAO;;;AAIhB,IAAa,eAAb,cAAkC,MAAM;CACtC,cAAc;A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,YAAY,MAAM,KAAK,OAAO;EACtD,MAAM,EAAE,WAAW,QAAQ,YAAY,KAAK,MAAM;AAElD,SAAO;GACL;GACA;GACA;GACA;GACA;GACA;GACD;;;;;CAMH,IAAW,SAAS;AAClB,SAAO,KAAK;;;;;CAMd,CAAQ,OAAO,WAAW;AACxB,OAAK,SAAS;;;;;;;CAQhB,UAAiB;AAEf,OAAK,MAAM,cAAc,KAAK,aAAa,QAAQ,CACjD,YAAW,SAAS"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/types.ts","../src/timing.ts","../src/dependency-monitor.ts","../src/static-checks.ts","../src/health-monitor.ts"],"sourcesContent":["export type DependencyStatusValue = 'ok' | 'degraded' | 'error'\nexport type DependencyStatus = {\n status: DependencyStatusValue\n details?: Record<string, unknown> | undefined\n}\nexport type StatusValue = DependencyStatusValue | 'unknown' | 'draining'\nexport type Impact = 'critical' | 'non_critical'\nexport type Mode = 'inline' | 'polled' | 'async'\n\nexport type Verb = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'\n\nexport type Link = {\n method: Verb\n href: string\n}\n\nexport interface Entity<T> {\n data: T\n links: Record<string, Link>\n}\n\nexport type Status = {\n status: StatusValue\n}\n\nexport type System = {\n hostname: string\n platform: NodeJS.Platform\n release: string\n arch: string\n uptime: number\n loadavg: [number, number, number] // 1, 5, 15 min\n totalmem: number\n freemem: number\n memUsedRatio: number // 0..1\n cpus: {\n count: number\n model?: string\n speedMHz?: number\n }\n}\n\nexport type Process = {\n pid: number\n node: string\n uptime: number\n memory: NodeJS.MemoryUsage\n}\n\nexport type Liveness = Status & {\n timestamp: string\n system: System\n process: Process\n}\n\nexport type Freshness = {\n lastChecked: string\n lastSuccess: string | null\n}\n\nexport type Observed = {\n latencyMs: number | null\n [k: string]: unknown\n}\n\nexport type CheckError = {\n code: string\n message: string\n}\n\nexport type DependencyCheck = Status & {\n impact: Impact\n mode: Mode\n freshness: Freshness\n observed?: Observed\n details?: Record<string, unknown>\n error?: CheckError | null\n since?: string | null\n}\n\nexport type ReadinessSummary = {\n critical: { ok: number; failing: number }\n nonCritical: { ok: number; degraded: number; failing: number }\n degradedReasons: string[]\n}\n\nexport type ReadinessPayload = Status & {\n timestamp: string\n service?: { name?: string; version?: string; instanceId?: string }\n summary: ReadinessSummary\n checks: Record<string, DependencyCheck>\n}\n\nexport type HealthSummary = Status &\n Pick<ReadinessPayload, 'summary' | 'checks'> &\n Pick<Liveness, 'system' | 'process'> & { timestamp: string }\n\nexport class TimeoutError extends Error {\n constructor() {\n super('timeout')\n this.name = 'TimeoutError'\n }\n}\n\nexport class UnknownError extends Error {\n constructor() {\n super('unknown')\n this.name = 'UnknownError'\n }\n}\n","import { TimeoutError } from './types'\n\nexport const wait = (ms: number) =>\n new Promise<void>((resolve) => setTimeout(resolve, ms))\n\nexport const runTimeoutTimer = async (ms: number) => {\n await wait(ms)\n throw new TimeoutError()\n}\n\nexport const runAgainstTimeout = <T>(\n promise: Promise<T>,\n ms?: number | undefined\n): Promise<T> => {\n if ((ms as number) > 0) {\n return Promise.race([promise, runTimeoutTimer(ms as number)])\n }\n\n return promise\n}\n\n/**\n * Throttles an async function:\n * - coalesces concurrent calls into a single in-flight Promise,\n * - after it settles, reuses that settled Promise for `ms` ms,\n * - then clears so the next call invokes `fn` again.\n *\n * Fully preserves the original function signature.\n */\nexport const throttle = <F extends (...args: unknown[]) => Promise<unknown>>(\n fn: F,\n ms: number\n) => {\n type R = ReturnType<F> // a Promise<T>\n\n let current: R | null = null\n let clearHandle: NodeJS.Timeout | null = null\n\n const wrapped = (...args: Parameters<F>): R => {\n if (!current) {\n current = fn(...args) as R\n\n if (clearHandle) {\n clearTimeout(clearHandle)\n clearHandle = null\n }\n\n current.finally(() => {\n if (ms > 0) {\n clearHandle = setTimeout(() => {\n current = null\n clearHandle = null\n }, ms)\n } else {\n current = null\n }\n })\n }\n\n return current\n }\n\n // Cast to F so the returned function has the *identical* callable type\n return wrapped as unknown as F\n}\n\n/**\n * Wraps an async function so that concurrent invocations share the same in-flight Promise.\n * After the Promise settles (resolve or reject), the next call will invoke the function again.\n * Essentially just throttled with timeout 0\n */\nexport const singleFlight = <\n F extends (...args: unknown[]) => Promise<unknown>,\n>(\n fn: F\n) => throttle<F>(fn, 0)\n","import { performance } from 'node:perf_hooks'\nimport { runAgainstTimeout, singleFlight } from './timing'\nimport {\n type CheckError,\n type DependencyCheck,\n DependencyStatus,\n type DependencyStatusValue,\n type Freshness,\n type Impact,\n type Mode,\n type Observed,\n type StatusValue,\n TimeoutError,\n UnknownError,\n} from './types'\n\n/**\n * Base configuration shared by all dependency monitor modes.\n */\ntype BaseConfig = {\n /**\n * Importance of the dependency:\n * - `'critical'` → service cannot run without it\n * - `'non_critical'` → service is degraded but still functional if it fails\n */\n impact: Impact\n\n /**\n * Polling interval in milliseconds.\n * - Required for polled and async modes\n * - Must not be set for inline mode\n */\n pollRate?: number\n\n /**\n * Polling interval in milliseconds for failed calls.\n * - Defaults to pollRate for polled and async modes\n * - Must not be set for inline mode\n */\n retryRate?: number\n\n /**\n * Maximum response time in milliseconds considered healthy.\n * - A call resolving within this time window **and** returning `\"ok\"` → status `\"ok\"`\n * - A call resolving after this but **before** `timeoutLimitMs` → status `\"degraded\"`\n */\n healthyLimitMs: number\n\n /**\n * Absolute upper bound in milliseconds; beyond this a call is considered `\"error\"`.\n * - Inline: the awaited call is raced with a timeout and rejected past this limit\n * - Polled/Async: escalate `unknown` → `degraded` at `healthyLimitMs`, then `\"error\"` at `timeoutLimitMs`\n * - Any late `\"ok\"` result after this limit is ignored\n */\n timeoutLimitMs: number\n}\n\n/**\n * Inline mode configuration (no polling).\n * `syncCall` runs **only** when {@link DependencyMonitor.check} is invoked.\n */\nexport type SyncInlineConfig = BaseConfig & {\n /** Performs the check immediately when {@link DependencyMonitor.check} is called. */\n syncCall: () => Promise<DependencyStatus | DependencyStatusValue | Error>\n asyncCall?: never\n pollRate?: undefined\n retryRate?: undefined\n}\n\n/**\n * Polled mode configuration.\n * `syncCall` runs on an interval (`pollRate`) and results are cached.\n */\nexport type SyncPolledConfig = BaseConfig & {\n /** Performs the check at each poll interval. */\n syncCall: () => Promise<DependencyStatus | DependencyStatusValue | Error>\n /** Polling interval in milliseconds. */\n pollRate: number\n asyncCall?: never\n}\n\n/**\n * Async mode configuration.\n * `asyncCall` starts a check and must report via the provided callback.\n */\nexport type AsyncConfig = BaseConfig & {\n /**\n * Starts an asynchronous check. Must call `reportResponse` once a result is available.\n * The callback may be invoked with a `DependencyStatus | DependencyStatusValue` or an `Error`.\n */\n asyncCall: (\n reportResponse: (\n status: DependencyStatus | DependencyStatusValue | Error\n ) => void | Promise<void>\n ) => void | Promise<void>\n /** Polling interval in milliseconds. */\n pollRate: number\n syncCall?: never\n}\n\n/**\n * Discriminated configuration for a dependency monitor.\n * - {@link SyncInlineConfig} → inline checks on demand\n * - {@link SyncPolledConfig} → synchronous checks on a fixed interval\n * - {@link AsyncConfig} → asynchronous checks that report back via callback\n */\nexport type DependencyMonitorConfig =\n | SyncInlineConfig\n | SyncPolledConfig\n | AsyncConfig\n\n/**\n * Tracks the health of a single dependency in one of three modes:\n *\n * - **inline**: `syncCall` executed only when {@link check} is called\n * - **polled**: `syncCall` executed on `pollRate`; latest result cached\n * - **async**: `asyncCall` executed on `pollRate`, result returned via callback\n *\n * The monitor:\n * - classifies results using `healthyLimitMs` and `timeoutLimitMs`\n * - records freshness (`lastChecked`, `lastSuccess`)\n * - records observed latency (ms) when applicable\n *\n * Status interpretation:\n * - `\"ok\"` only if returned `\"ok\"` **and** latency ≤ `healthyLimitMs`\n * - `\"degraded\"` if returned `\"degraded\"` **or** latency > `healthyLimitMs` but ≤ `timeoutLimitMs`\n * - `\"error\"` if returned `\"error\"`, an `Error`, or exceeded `timeoutLimitMs`\n * - `\"unknown\"` is the initial state before first successful/failed result (polled/async)\n */\nexport class DependencyMonitor {\n /** Immutable configuration for this monitor. */\n private readonly config: DependencyMonitorConfig\n /** Operational mode determined from the configuration. */\n private readonly mode: Mode\n\n /** Last computed status (starts as `\"unknown\"` until first result). */\n private status: StatusValue\n /** Optional error details from the last failure. */\n private error?: CheckError\n /** Last observed metrics (e.g., latency). */\n private observed?: Observed\n /** Freshness timestamps for last check/success. */\n private freshness?: Freshness\n /** Optional details returned by the helth check call. */\n private details?: Record<string, unknown>\n\n /** Indicates whether this monitor has been disposed. */\n private isDisposed = false\n /** Internal timer handle for polling/retry. */\n private timeout?: NodeJS.Timeout\n\n /**\n * Create a new {@link DependencyMonitor}.\n * @param config Monitor configuration (inline, polled, or async).\n */\n constructor(config: DependencyMonitorConfig) {\n this.config = config\n\n this.mode = config.asyncCall\n ? 'async'\n : config.pollRate\n ? 'polled'\n : 'inline'\n\n this.status = 'unknown'\n\n // Deduplicate concurrent inline checks (single-flight).\n if (this.mode === 'inline') {\n this.check = singleFlight(this.check.bind(this))\n }\n\n // Kick off the first cycle for polled/async.\n if (this.mode !== 'inline') {\n this.doCheck()\n }\n }\n\n /** Impact of this dependency (critical/non_critical). */\n public get impact() {\n return this.config.impact\n }\n\n /**\n * Run one check cycle depending on the configured mode.\n * - Inline: no-op here (runs in {@link check})\n * - Polled/Async: invoked automatically and re-scheduled as needed\n */\n private async doCheck() {\n if (this.timeout) {\n clearTimeout(this.timeout)\n }\n if (this.isDisposed) {\n return\n }\n\n if (this.config.syncCall) {\n await this.doSyncCheck()\n } else {\n this.doAsyncCheck()\n }\n }\n\n /**\n * Execute a synchronous (inline/polled) check and update internal state.\n * Classification:\n * - OK if `\"ok\"` and latency ≤ `healthyLimitMs`\n * - Degraded if `\"degraded\"` or latency between `(healthyLimitMs, timeoutLimitMs]`\n * - Error if `\"error\"`, `Error`, or timeout exceeded\n */\n private async doSyncCheck() {\n const start = performance.now()\n\n const { syncCall, timeoutLimitMs } = this.config as SyncInlineConfig\n\n try {\n const response = await runAgainstTimeout(syncCall(), timeoutLimitMs)\n const duration = performance.now() - start\n\n this.handleDependencyResponse(response, duration)\n } catch (err) {\n this.handleDependencyError(err as Error)\n }\n }\n\n /**\n * Execute an asynchronous check (async mode).\n * - Initializes timers to escalate `unknown` → `degraded` → `error`\n * if no callback result arrives within the thresholds.\n * - On callback, clears timers and classifies the result with latency.\n */\n private async doAsyncCheck() {\n const { asyncCall, healthyLimitMs, timeoutLimitMs } = this\n .config as AsyncConfig\n\n const start = performance.now()\n let callActive = true\n let healthTimeout: NodeJS.Timeout | undefined\n let serviceTimeout: NodeJS.Timeout | undefined\n\n asyncCall((response) => {\n if (!callActive) return\n callActive = false\n clearTimeout(healthTimeout)\n clearTimeout(serviceTimeout)\n\n const duration = performance.now() - start\n this.handleDependencyResponse(response, duration)\n })\n\n // Escalate to degraded after healthy limit if still waiting.\n healthTimeout = setTimeout(() => {\n if (callActive) this.status = 'degraded'\n }, healthyLimitMs)\n\n // Escalate to error after timeout limit if still waiting.\n serviceTimeout = setTimeout(() => {\n if (!callActive) return\n callActive = false\n clearTimeout(healthTimeout)\n this.handleDependencyError(new TimeoutError())\n }, timeoutLimitMs)\n }\n\n /**\n * Normalize a successful dependency response into status + metadata.\n * @param response Returned status value or Error from the dependency\n * @param duration Measured latency in milliseconds\n */\n private handleDependencyResponse(\n response: DependencyStatus | DependencyStatusValue | Error,\n duration: number\n ) {\n if (response instanceof Error) {\n return this.handleDependencyError(response)\n }\n\n const normalized: DependencyStatus =\n typeof response === 'string' ? { status: response } : response\n\n if (normalized.status === 'error') {\n return this.handleDependencyError(new UnknownError())\n }\n\n this.error = undefined\n this.details = normalized.details\n this.status =\n normalized.status === 'ok' && duration <= this.config.healthyLimitMs\n ? 'ok'\n : 'degraded'\n\n const end = new Date()\n this.freshness = {\n lastChecked: end.toISOString(),\n lastSuccess: end.toISOString(),\n }\n\n this.observed = { latencyMs: duration }\n\n // Schedule next poll if applicable.\n if (this.config.pollRate && !this.isDisposed) {\n const delay = this.config.pollRate\n this.timeout = setTimeout(() => this.doCheck(), delay)\n }\n }\n\n /**\n * Normalize a failed dependency result into `\"error\"` and update metadata.\n * @param error Error thrown/returned or synthesized (e.g., timeout)\n */\n private handleDependencyError(error: Error & { code?: string }) {\n this.status = 'error'\n this.observed = undefined\n this.error = {\n code: error.code || 'UNKNOWN',\n message: error.message,\n }\n\n const end = new Date()\n if (this.freshness) {\n this.freshness.lastChecked = end.toISOString()\n } else {\n this.freshness = { lastChecked: end.toISOString(), lastSuccess: null }\n }\n\n // Schedule retry/poll if configured.\n if ((this.config.retryRate || this.config.pollRate) && !this.isDisposed) {\n const delay = this.config.retryRate || this.config.pollRate\n this.timeout = setTimeout(() => this.doCheck(), delay)\n }\n }\n\n /**\n * Get a snapshot of the dependency’s current health.\n * - Inline mode: executes the `syncCall` (single-flight guarded)\n * - Polled/Async: returns the cached result\n * @throws if the monitor has been disposed\n */\n public async check(): Promise<DependencyCheck> {\n if (this.isDisposed) {\n throw new Error('DependencyMonitor has been disposed')\n }\n\n if (this.mode === 'inline') {\n await this.doCheck()\n }\n\n const result: DependencyCheck = {\n status: this.status as StatusValue,\n impact: this.config.impact,\n mode: this.mode,\n freshness: this.freshness as Freshness,\n details: this.details,\n observed: this.observed,\n error: this.error,\n }\n\n return result\n }\n\n /** Symbol-based disposer for use with `using`. */\n public [Symbol.dispose]() {\n this.dispose()\n }\n\n /**\n * Dispose the monitor:\n * - Clears any scheduled timers\n * - Prevents further checks from running\n */\n public dispose() {\n this.isDisposed = true\n if (this.timeout) {\n clearTimeout(this.timeout)\n }\n }\n}\n","import os from 'node:os'\nimport type { Liveness, Status } from './types'\n\nexport const ping = (): Status => ({ status: 'ok' })\nexport const liveness = (): Liveness => {\n const cpus = os.cpus()\n const total = os.totalmem()\n const free = os.freemem()\n\n return {\n status: 'ok',\n timestamp: new Date().toISOString(),\n system: {\n hostname: os.hostname(),\n platform: os.platform(),\n release: os.release(),\n arch: os.arch(),\n uptime: os.uptime(),\n loadavg: os.loadavg() as [number, number, number],\n totalmem: total,\n freemem: free,\n memUsedRatio: total > 0 ? (total - free) / total : 0,\n cpus: {\n count: cpus.length,\n model: cpus[0]?.model,\n speedMHz: cpus[0]?.speed,\n },\n },\n process: {\n pid: process.pid,\n node: process.versions.node,\n uptime: process.uptime(),\n memory: process.memoryUsage(), // rss, heapTotal, heapUsed, external, arrayBuffers\n },\n }\n}\n","import { toEntity } from '@sebspark/hyper-media'\nimport { type ErrorRequestHandler, Router } from 'express'\nimport type {\n DependencyMonitor,\n DependencyMonitorConfig,\n} from './dependency-monitor'\nimport { liveness, ping } from './static-checks'\nimport { throttle } from './timing'\nimport type {\n DependencyCheck,\n HealthSummary,\n Impact,\n ReadinessPayload,\n ReadinessSummary,\n StatusValue,\n} from './types'\n\nexport interface HealthMonitorConfig {\n throttle: number\n}\n\n/**\n * HealthMonitor wires up standard health check endpoints for an Express app.\n *\n * It provides three endpoints under `/health`:\n * - /ping → lightweight always-OK response (`{ status: \"ok\" }`)\n * - /live → liveness probe (`{ status, uptime, timestamp }`)\n * - /ready → readiness probe with dependency checks (`{ status, checks }`)\n *\n * Dependencies can be added via {@link addDependency} with a {@link DependencyMonitorConfig}.\n * Each dependency is wrapped in a {@link DependencyMonitor} and tracked for readiness.\n *\n * ### Example\n *\n * ```ts\n * import express from 'express'\n * import { HealthMonitor } from './health-monitor'\n *\n * const app = express()\n * const monitor = new HealthMonitor()\n *\n * monitor.addDependency('db', {\n * impact: 'critical',\n * syncCall: async () => {\n * await db.ping()\n * return 'ok'\n * }\n * })\n *\n * app.use(monitor.router)\n * app.listen(3000)\n * ```\n */\nexport class HealthMonitor {\n private readonly _router: Router\n private readonly dependencies: Map<string, DependencyMonitor>\n // private isDisposed = false\n\n /**\n * Create a new HealthMonitor instance with its own router and dependency map.\n */\n constructor(config?: HealthMonitorConfig) {\n this._router = this.createRouter()\n this.dependencies = new Map()\n\n const thr = config ? config.throttle : 10\n if (thr > 0) {\n this.ready = throttle(this.ready.bind(this), thr)\n }\n }\n\n /**\n * Register a named dependency to be checked as part of readiness.\n *\n * @param name - Identifier for the dependency (e.g. \"postgres\", \"redis\").\n * @param dependency - DependencyMonitor\n * @returns this for chaining\n *\n * @example\n * ```ts\n * monitor.addDependency('redis', new DependencyMonitor({\n * impact: 'critical',\n * pollRate: 5000,\n * syncCall: async () => redis.ping() ? 'ok' : 'error'\n * }))\n * ```\n */\n public addDependency(name: string, dependency: DependencyMonitor) {\n this.dependencies.set(name, dependency)\n return this\n }\n\n /**\n * Internal: create the Express router with /health routes.\n */\n private createRouter() {\n const router = Router()\n\n // Health\n router.get('/health', async (req, res, next) => {\n try {\n const health = await this.health()\n res.status(200).json(\n toEntity(req, health, {\n ping: '/health/ping',\n live: '/health/live',\n ready: '/health/ready',\n })\n )\n } catch (err) {\n next?.(err)\n }\n })\n\n // Ping\n router.get('/health/ping', (req, res, next) => {\n try {\n res.status(200).json(\n toEntity(req, this.ping(), {\n health: '/health',\n })\n )\n } catch (err) {\n next?.(err)\n }\n })\n\n // Liveness\n router.get('/health/live', (req, res, next) => {\n try {\n res.status(200).json(\n toEntity(req, this.live(), {\n health: '/health',\n })\n )\n } catch (err) {\n next?.(err)\n }\n })\n\n // Readiness\n router.get('/health/ready', async (req, res, next) => {\n try {\n const readiness = await this.ready()\n const status = readiness.summary.critical.failing > 0 ? 503 : 200\n res.status(status).json(\n toEntity(req, readiness, {\n health: '/health',\n })\n )\n } catch (err) {\n next?.(err)\n }\n })\n\n // Error handler\n const errorHandler: ErrorRequestHandler = (err, _req, res, _next) => {\n const message = err instanceof Error ? err.message : String(err)\n res.status(500).json({\n status: 'error',\n error: { message },\n })\n }\n router.use(errorHandler)\n\n return router\n }\n\n /**\n * Static ping check — always returns `{ status: \"ok\" }`.\n */\n public ping() {\n return ping()\n }\n\n /**\n * Liveness probe: reports uptime and current timestamp.\n */\n public live() {\n return liveness()\n }\n\n /**\n * Readiness probe: runs all registered dependencies in parallel\n * and aggregates their results into an overall status.\n *\n * - Any **critical error** → `\"error\"`\n * - Else any **critical degraded** or any non-critical degraded/error → `\"degraded\"`\n * - Else → `\"ok\"`\n *\n * @returns Object with overall `status` and per-dependency `checks`\n *\n * @example\n * ```json\n * {\n * \"status\": \"ok\",\n * \"checks\": {\n * \"postgres\": {\n * \"status\": \"ok\",\n * \"impact\": \"critical\",\n * \"mode\": \"inline\",\n * \"freshness\": {\n * \"lastChecked\": \"2025-08-19T12:00:00Z\",\n * \"lastSuccess\": \"2025-08-19T12:00:00Z\"\n * },\n * \"observed\": { \"latencyMs\": 12 }\n * }\n * }\n * }\n * ```\n */\n public async ready(): Promise<ReadinessPayload> {\n const entries = Array.from(this.dependencies.entries())\n\n const settled = await Promise.allSettled(\n entries.map(async ([name, monitor]) => {\n const check = await monitor.check()\n return [name, check] as const\n })\n )\n\n const checks: Record<string, DependencyCheck> = {}\n\n for (let i = 0; i < settled.length; i++) {\n const s = settled[i]\n const [name] = entries[i]\n\n if (s.status === 'fulfilled') {\n const [, check] = s.value\n checks[name] = check\n } else {\n checks[name] = {\n status: 'error',\n impact: this.dependencies.get(name)?.impact as Impact,\n mode: 'polled',\n freshness: {\n lastChecked: new Date().toISOString(),\n lastSuccess: null,\n },\n observed: undefined,\n error: {\n code: 'CHECK_FAILED',\n message: String(s.reason ?? 'unknown error'),\n },\n }\n }\n }\n\n // ----- summary -------------------------------------------------------------\n let criticalOk = 0\n let criticalFailing = 0 // counts any non-ok critical (degraded OR error)\n\n let nonCritOk = 0\n let nonCritDegraded = 0\n let nonCritFailing = 0 // non-critical with status === 'error'\n\n const degradedReasons: string[] = []\n\n for (const [name, c] of Object.entries(checks)) {\n const isCritical = c.impact === 'critical'\n if (c.status === 'unknown') {\n // not yet checked — don't count as ok or failing\n } else if (c.status === 'ok') {\n if (isCritical) criticalOk++\n else nonCritOk++\n } else if (c.status === 'degraded') {\n if (isCritical)\n criticalFailing++ // critical degraded counts as failing\n else nonCritDegraded++\n degradedReasons.push(`${name}:degraded`)\n } else {\n // 'error'\n if (isCritical) criticalFailing++\n else nonCritFailing++\n degradedReasons.push(`${name}:${c.error?.code ?? 'error'}`)\n }\n }\n\n const summary: ReadinessSummary = {\n critical: { ok: criticalOk, failing: criticalFailing },\n nonCritical: {\n ok: nonCritOk,\n degraded: nonCritDegraded,\n failing: nonCritFailing,\n },\n degradedReasons,\n }\n\n // ----- overall status (same rules as before) -------------------------------\n let status: StatusValue = 'ok'\n const values = Object.values(checks)\n const anyCriticalError = values.some(\n (c) => c.impact === 'critical' && c.status === 'error'\n )\n const anyDegradedOrError = values.some(\n (c) => c.status === 'degraded' || c.status === 'error'\n )\n const anyCriticalDegraded = values.some(\n (c) => c.impact === 'critical' && c.status === 'degraded'\n )\n\n if (anyCriticalError) status = 'error'\n else if (anyCriticalDegraded || anyDegradedOrError) status = 'degraded'\n\n // ----- payload -------------------------------------------------------------\n const payload: ReadinessPayload = {\n status,\n timestamp: new Date().toISOString(),\n // service: { name, version, instanceId } // (optional; if you add config later)\n summary,\n checks,\n }\n\n return payload\n }\n\n public async health() {\n const { status, checks, summary } = await this.ready()\n const { timestamp, system, process } = this.live()\n\n return {\n status,\n timestamp,\n system,\n process,\n checks,\n summary,\n } as HealthSummary\n }\n\n /**\n * Accessor for the Express router that exposes /health endpoints.\n */\n public get router() {\n return this._router\n }\n\n /**\n * Symbol-based disposer for use with `using`.\n */\n public [Symbol.dispose]() {\n this.dispose()\n }\n\n /**\n * Dispose of the monitor:\n * - marks as disposed\n * - (future: could also stop all dependency monitors)\n */\n public dispose() {\n // this.isDisposed = true\n for (const dependency of this.dependencies.values()) {\n dependency.dispose()\n }\n }\n}\n"],"mappings":";;;;;AAiGA,IAAa,eAAb,cAAkC,MAAM;CACtC,cAAc;AACZ,QAAM,UAAU;AAChB,OAAK,OAAO;;;AAIhB,IAAa,eAAb,cAAkC,MAAM;CACtC,cAAc;AACZ,QAAM,UAAU;AAChB,OAAK,OAAO;;;;;ACzGhB,MAAa,QAAQ,OACnB,IAAI,SAAe,YAAY,WAAW,SAAS,GAAG,CAAC;AAEzD,MAAa,kBAAkB,OAAO,OAAe;AACnD,OAAM,KAAK,GAAG;AACd,OAAM,IAAI,cAAc;;AA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,WAAW,QAAQ,YAAY,KAAK,MAAM;AAElD,SAAO;GACL;GACA;GACA;GACA;GACA;GACA;GACD;;;;;CAMH,IAAW,SAAS;AAClB,SAAO,KAAK;;;;;CAMd,CAAQ,OAAO,WAAW;AACxB,OAAK,SAAS;;;;;;;CAQhB,UAAiB;AAEf,OAAK,MAAM,cAAc,KAAK,aAAa,QAAQ,CACjD,YAAW,SAAS"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sebspark/health-check",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.2.0",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.mjs",
|
|
@@ -23,14 +23,14 @@
|
|
|
23
23
|
"typecheck": "vitest --typecheck.only --passWithNoTests"
|
|
24
24
|
},
|
|
25
25
|
"dependencies": {
|
|
26
|
-
"@sebspark/hyper-media": "0.1.
|
|
26
|
+
"@sebspark/hyper-media": "0.1.3",
|
|
27
27
|
"express": "5.2.1"
|
|
28
28
|
},
|
|
29
29
|
"devDependencies": {
|
|
30
30
|
"@google-cloud/pubsub": "5.3.0",
|
|
31
|
-
"@testcontainers/gcloud": "11.
|
|
32
|
-
"@testcontainers/mockserver": "11.
|
|
33
|
-
"@testcontainers/redis": "11.
|
|
31
|
+
"@testcontainers/gcloud": "11.13.0",
|
|
32
|
+
"@testcontainers/mockserver": "11.13.0",
|
|
33
|
+
"@testcontainers/redis": "11.13.0",
|
|
34
34
|
"mockserver-client": "5.15.0",
|
|
35
35
|
"supertest": "7.2.2"
|
|
36
36
|
},
|