@sebspark/health-check 3.0.14 → 3.0.15
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/CHANGELOG.md +13 -0
- package/README.md +5 -2
- package/dist/index.d.mts +4 -2
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +23 -19
- package/dist/index.mjs.map +1 -1
- package/package.json +4 -4
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,18 @@
|
|
|
1
1
|
# @sebspark/health-check
|
|
2
2
|
|
|
3
|
+
## 3.0.15
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 176ea40: - Polled and async dependency checks now always report `freshness`. Before the first result it is `{ lastChecked: null, lastSuccess: null }`. Previously the field was missing, even though both the `DependencyCheck` type and the OpenAPI schema mark it as required. `Freshness.lastChecked` is now typed `string | null`, and the README schema is updated to match.
|
|
8
|
+
- A failed check no longer mutates the `freshness` object of a result that was already returned.
|
|
9
|
+
- When a dependency throws a non-`Error` value, the error is now reported with its message (for example `'connection refused'`) instead of `message: undefined`.
|
|
10
|
+
- Internal type assertions were removed.
|
|
11
|
+
- Updated dependencies [176ea40]
|
|
12
|
+
- Updated dependencies [176ea40]
|
|
13
|
+
- @sebspark/hyper-media@0.1.8
|
|
14
|
+
- @sebspark/promise-cache@8.1.10
|
|
15
|
+
|
|
3
16
|
## 3.0.14
|
|
4
17
|
|
|
5
18
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -383,7 +383,10 @@ app.listen(3000, () => {
|
|
|
383
383
|
"type": "object",
|
|
384
384
|
"properties": {
|
|
385
385
|
"lastChecked": {
|
|
386
|
-
"type":
|
|
386
|
+
"type": [
|
|
387
|
+
"string",
|
|
388
|
+
"null"
|
|
389
|
+
],
|
|
387
390
|
"format": "date-time"
|
|
388
391
|
},
|
|
389
392
|
"lastSuccess": {
|
|
@@ -969,7 +972,7 @@ components:
|
|
|
969
972
|
type: object
|
|
970
973
|
properties:
|
|
971
974
|
lastChecked:
|
|
972
|
-
type: string
|
|
975
|
+
type: [string, "null"]
|
|
973
976
|
format: date-time
|
|
974
977
|
lastSuccess:
|
|
975
978
|
type: [string, "null"]
|
package/dist/index.d.mts
CHANGED
|
@@ -39,7 +39,9 @@ export type Liveness = Status & {
|
|
|
39
39
|
process: Process;
|
|
40
40
|
};
|
|
41
41
|
export type Freshness = {
|
|
42
|
-
|
|
42
|
+
/** `null` until the first check has completed. */
|
|
43
|
+
lastChecked: string | null;
|
|
44
|
+
/** `null` until a check has succeeded. */
|
|
43
45
|
lastSuccess: string | null;
|
|
44
46
|
};
|
|
45
47
|
export type Observed = {
|
|
@@ -200,7 +202,7 @@ export declare class DependencyMonitor {
|
|
|
200
202
|
/** Last observed metrics (e.g., latency). */
|
|
201
203
|
private observed?;
|
|
202
204
|
/** Freshness timestamps for last check/success. */
|
|
203
|
-
private freshness
|
|
205
|
+
private freshness;
|
|
204
206
|
/** Optional details returned by the helth check call. */
|
|
205
207
|
private details?;
|
|
206
208
|
/** Indicates whether this monitor has been disposed. */
|
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":["_$__types0.Status","_$__types0.Liveness"],"sources":["../src/types.ts","../src/dependency-monitor.ts","../src/health-monitor.ts"],"mappings":";YAAY;YACA;EACV,QAAQ;EACR,UAAU;;YAEA,cAAc;YACd;YACA;YAEA;YAEA;EACV,QAAQ;EACR;;iBAGe,OAAO;EACtB,MAAM;EACN,OAAO,eAAe;;YAGZ;EACV,QAAQ;;YAGE;EACV;EACA;EACA;EACA;EACA;EACA;IACE;;;YAIQ;EACV;EACA,QAAQ,OAAO;;YAGL,WAAW;EACrB;EACA,QAAQ;EACR,SAAS;;YAGC
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":["_$__types0.Status","_$__types0.Liveness"],"sources":["../src/types.ts","../src/dependency-monitor.ts","../src/health-monitor.ts"],"mappings":";YAAY;YACA;EAC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OAAO;;;;;;EASR;;iBCnWQ;EACf;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAmCW;mBACM;mBACA;UACT;;;;EAKR,YAAY,SAAS;;;;;;;;;;;;;;;;;EA0Bd,cAAc,cAAc,YAAY;;;;UAQvC;;;;EAmGD,QA3GwCA;;;;EAkHxC,QAPIC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAwCE,SAAS,QAAQ;EAkHjB,UAAU,QAAQ;;;;MAiBpB,UAAM;;;;GAOT,OAAO;;;;;;EASR"}
|
package/dist/index.mjs
CHANGED
|
@@ -23,7 +23,7 @@ const runTimeoutTimer = async (ms) => {
|
|
|
23
23
|
throw new TimeoutError();
|
|
24
24
|
};
|
|
25
25
|
const runAgainstTimeout = (promise, ms) => {
|
|
26
|
-
if (ms > 0) return Promise.race([promise, runTimeoutTimer(ms)]);
|
|
26
|
+
if (ms !== void 0 && ms > 0) return Promise.race([promise, runTimeoutTimer(ms)]);
|
|
27
27
|
return promise;
|
|
28
28
|
};
|
|
29
29
|
/**
|
|
@@ -37,7 +37,7 @@ const runAgainstTimeout = (promise, ms) => {
|
|
|
37
37
|
const throttle = (fn, ms) => {
|
|
38
38
|
let current = null;
|
|
39
39
|
let clearHandle = null;
|
|
40
|
-
|
|
40
|
+
return (...args) => {
|
|
41
41
|
if (!current) {
|
|
42
42
|
current = fn(...args);
|
|
43
43
|
/* istanbul ignore next */
|
|
@@ -60,7 +60,6 @@ const throttle = (fn, ms) => {
|
|
|
60
60
|
}
|
|
61
61
|
return current;
|
|
62
62
|
};
|
|
63
|
-
return wrapped;
|
|
64
63
|
};
|
|
65
64
|
/**
|
|
66
65
|
* Wraps an async function so that concurrent invocations share the same in-flight Promise.
|
|
@@ -99,7 +98,10 @@ var DependencyMonitor = class {
|
|
|
99
98
|
/** Last observed metrics (e.g., latency). */
|
|
100
99
|
observed;
|
|
101
100
|
/** Freshness timestamps for last check/success. */
|
|
102
|
-
freshness
|
|
101
|
+
freshness = {
|
|
102
|
+
lastChecked: null,
|
|
103
|
+
lastSuccess: null
|
|
104
|
+
};
|
|
103
105
|
/** Optional details returned by the helth check call. */
|
|
104
106
|
details;
|
|
105
107
|
/** Indicates whether this monitor has been disposed. */
|
|
@@ -129,8 +131,9 @@ var DependencyMonitor = class {
|
|
|
129
131
|
async doCheck() {
|
|
130
132
|
if (this.timeout) clearTimeout(this.timeout);
|
|
131
133
|
if (this.isDisposed) return;
|
|
132
|
-
|
|
133
|
-
|
|
134
|
+
const { config } = this;
|
|
135
|
+
if (config.syncCall) await this.doSyncCheck(config);
|
|
136
|
+
else this.doAsyncCheck(config);
|
|
134
137
|
}
|
|
135
138
|
/**
|
|
136
139
|
* Execute a synchronous (inline/polled) check and update internal state.
|
|
@@ -139,15 +142,14 @@ var DependencyMonitor = class {
|
|
|
139
142
|
* - Degraded if `"degraded"` or latency between `(healthyLimitMs, timeoutLimitMs]`
|
|
140
143
|
* - Error if `"error"`, `Error`, or timeout exceeded
|
|
141
144
|
*/
|
|
142
|
-
async doSyncCheck() {
|
|
145
|
+
async doSyncCheck({ syncCall, timeoutLimitMs }) {
|
|
143
146
|
const start = performance.now();
|
|
144
|
-
const { syncCall, timeoutLimitMs } = this.config;
|
|
145
147
|
try {
|
|
146
148
|
const response = await runAgainstTimeout(syncCall(), timeoutLimitMs);
|
|
147
149
|
const duration = performance.now() - start;
|
|
148
150
|
this.handleDependencyResponse(response, duration);
|
|
149
151
|
} catch (err) {
|
|
150
|
-
this.handleDependencyError(err);
|
|
152
|
+
this.handleDependencyError(err instanceof Error ? err : new Error(String(err)));
|
|
151
153
|
}
|
|
152
154
|
}
|
|
153
155
|
/**
|
|
@@ -156,8 +158,7 @@ var DependencyMonitor = class {
|
|
|
156
158
|
* if no callback result arrives within the thresholds.
|
|
157
159
|
* - On callback, clears timers and classifies the result with latency.
|
|
158
160
|
*/
|
|
159
|
-
async doAsyncCheck() {
|
|
160
|
-
const { asyncCall, healthyLimitMs, timeoutLimitMs } = this.config;
|
|
161
|
+
async doAsyncCheck({ asyncCall, healthyLimitMs, timeoutLimitMs }) {
|
|
161
162
|
const start = performance.now();
|
|
162
163
|
let callActive = true;
|
|
163
164
|
let healthTimeout;
|
|
@@ -214,11 +215,9 @@ var DependencyMonitor = class {
|
|
|
214
215
|
code: error.code || "UNKNOWN",
|
|
215
216
|
message: error.message
|
|
216
217
|
};
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
lastChecked: end.toISOString(),
|
|
221
|
-
lastSuccess: null
|
|
218
|
+
this.freshness = {
|
|
219
|
+
...this.freshness,
|
|
220
|
+
lastChecked: (/* @__PURE__ */ new Date()).toISOString()
|
|
222
221
|
};
|
|
223
222
|
if ((this.config.retryRate || this.config.pollRate) && !this.isDisposed) {
|
|
224
223
|
const delay = this.config.retryRate || this.config.pollRate;
|
|
@@ -264,6 +263,7 @@ const liveness = () => {
|
|
|
264
263
|
const cpus = os.cpus();
|
|
265
264
|
const total = os.totalmem();
|
|
266
265
|
const free = os.freemem();
|
|
266
|
+
const [load1 = 0, load5 = 0, load15 = 0] = os.loadavg();
|
|
267
267
|
let memUsedRatio;
|
|
268
268
|
/* istanbul ignore else */
|
|
269
269
|
if (total > 0) memUsedRatio = (total - free) / total;
|
|
@@ -273,7 +273,11 @@ const liveness = () => {
|
|
|
273
273
|
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
274
274
|
system: {
|
|
275
275
|
uptime: os.uptime(),
|
|
276
|
-
loadavg:
|
|
276
|
+
loadavg: [
|
|
277
|
+
load1,
|
|
278
|
+
load5,
|
|
279
|
+
load15
|
|
280
|
+
],
|
|
277
281
|
totalmem: total,
|
|
278
282
|
freemem: free,
|
|
279
283
|
memUsedRatio,
|
|
@@ -469,13 +473,13 @@ var HealthMonitor = class {
|
|
|
469
473
|
const checks = {};
|
|
470
474
|
for (let i = 0; i < settled.length; i++) {
|
|
471
475
|
const s = settled[i];
|
|
472
|
-
const [name] = entries[i];
|
|
476
|
+
const [name, monitor] = entries[i];
|
|
473
477
|
if (s.status === "fulfilled") {
|
|
474
478
|
const [, check] = s.value;
|
|
475
479
|
checks[name] = check;
|
|
476
480
|
} else checks[name] = {
|
|
477
481
|
status: "error",
|
|
478
|
-
impact:
|
|
482
|
+
impact: monitor.impact,
|
|
479
483
|
mode: "polled",
|
|
480
484
|
freshness: {
|
|
481
485
|
lastChecked: (/* @__PURE__ */ new Date()).toISOString(),
|
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 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 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 }\n}\n\nexport type Process = {\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; degraded: 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 /* istanbul ignore next */\n if (clearHandle) {\n clearTimeout(clearHandle)\n clearHandle = null\n }\n\n const schedule = () => {\n if (ms > 0) {\n clearHandle = setTimeout(\n /* istanbul ignore next */ () => {\n current = null\n clearHandle = null\n },\n ms\n )\n } else {\n current = null\n }\n }\n current.then(schedule, schedule)\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 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 let memUsedRatio: number\n /* istanbul ignore else */\n if (total > 0) {\n memUsedRatio = (total - free) / total\n } else {\n memUsedRatio = 0\n }\n\n return {\n status: 'ok',\n timestamp: new Date().toISOString(),\n system: {\n uptime: os.uptime(),\n loadavg: os.loadavg() as [number, number, number],\n totalmem: total,\n freemem: free,\n memUsedRatio,\n cpus: {\n count: cpus.length,\n },\n },\n process: {\n uptime: process.uptime(),\n memory: process.memoryUsage(),\n },\n }\n}\n","import { toEntity } from '@sebspark/hyper-media'\nimport { createCache, InMemoryPersistor } from '@sebspark/promise-cache'\nimport { type ErrorRequestHandler, type RequestHandler, 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 const persistor = new InMemoryPersistor()\n const cache = createCache(persistor)\n\n // Health\n const cachedHealth = cache.wrap(() => this.health(), {\n key: '/health',\n expiry: 1000,\n })\n const healthHandler: RequestHandler = async (\n req,\n res,\n next\n ): Promise<void> => {\n try {\n const health = await cachedHealth()\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 router.get('/health', healthHandler)\n\n // Ping (no cache handler for ping since that woul actually increase the cost of the call)\n const pingHandler: RequestHandler = (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 router.get('/health/ping', pingHandler)\n\n // Liveness\n const cachedLiveness = cache.wrap(() => this.live(), {\n key: 'health/live',\n expiry: 1000,\n })\n const livenessHandler: RequestHandler = async (req, res, next) => {\n try {\n const liveness = await cachedLiveness()\n res.status(200).json(\n toEntity(req, liveness, {\n health: '/health',\n })\n )\n } catch (err) {\n next?.(err)\n }\n }\n router.get('/health/live', livenessHandler)\n\n // Readiness\n const cachedReadiness = cache.wrap(() => this.ready(), {\n key: '/health/ready',\n expiry: 1000,\n })\n const readinessHandler: RequestHandler = async (req, res, next) => {\n try {\n const readiness = await cachedReadiness()\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 router.get('/health/ready', readinessHandler)\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 criticalDegraded = 0\n let criticalFailing = 0\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) criticalDegraded++\n else nonCritDegraded++\n degradedReasons.push(`${name}:degraded`)\n } else {\n // 'error'\n if (isCritical) criticalFailing++\n else nonCritFailing++\n /* istanbul ignore else */\n if (c.error?.code) {\n degradedReasons.push(`${name}:${c.error.code}`)\n } else {\n degradedReasons.push(`${name}:error`)\n }\n }\n }\n\n const summary: ReadinessSummary = {\n critical: {\n ok: criticalOk,\n degraded: criticalDegraded,\n failing: criticalFailing,\n },\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 if (this.isDisposed) {\n return\n }\n this.isDisposed = true\n for (const dependency of this.dependencies.values()) {\n dependency.dispose()\n }\n }\n}\n"],"mappings":";;;;;;AAyFA,IAAa,eAAb,cAAkC,MAAM;CACtC,cAAc;EACZ,MAAM,SAAS;EACf,KAAK,OAAO;CACd;AACF;AAEA,IAAa,eAAb,cAAkC,MAAM;CACtC,cAAc;EACZ,MAAM,SAAS;EACf,KAAK,OAAO;CACd;AACF;;ACnGA,MAAa,QAAQ,OACnB,IAAI,SAAe,YAAY,WAAW,SAAS,EAAE,CAAC;AAExD,MAAa,kBAAkB,OAAO,OAAe;CACnD,MAAM,KAAK,EAAE;CACb,MAAM,IAAI,aAAa;AACzB;AAEA,MAAa,qBACX,SACA,OACe;CACf,IAAK,KAAgB,GACnB,OAAO,QAAQ,KAAK,CAAC,SAAS,gBAAgB,EAAY,CAAC,CAAC;CAG9D,OAAO;AACT;;;;;;;;;AAUA,MAAa,YACX,IACA,OACG;CAGH,IAAI,UAAoB;CACxB,IAAI,cAAqC;CAEzC,MAAM,WAAW,GAAG,SAA2B;EAC7C,IAAI,CAAC,SAAS;GACZ,UAAU,GAAG,GAAG,IAAI;;GAGpB,IAAI,aAAa;IACf,aAAa,WAAW;IACxB,cAAc;GAChB;GAEA,MAAM,iBAAiB;IACrB,IAAI,KAAK,GACP,cAAc;;WACqB;MAC/B,UAAU;MACV,cAAc;KAChB;KACA;IACF;SAEA,UAAU;GAEd;GACA,QAAQ,KAAK,UAAU,QAAQ;EACjC;EAEA,OAAO;CACT;CAGA,OAAO;AACT;;;;;;AAOA,MAAa,gBAGX,OACG,SAAY,IAAI,CAAC;;;;;;;;;;;;;;;;;;;;ACiDtB,IAAa,oBAAb,MAA+B;;CAE7B;;CAEA;;CAGA;;CAEA;;CAEA;;CAEA;;CAEA;;CAGA,aAAqB;;CAErB;;;;;CAMA,YAAY,QAAiC;EAC3C,KAAK,SAAS;EAEd,KAAK,OAAO,OAAO,YACf,UAC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AKA,IAAW,SAAS;EAClB,OAAO,KAAK;CACd;;;;CAKA,CAAQ,OAAO,WAAW;EACxB,KAAK,QAAQ;CACf;;;;;;CAOA,UAAiB;EACf,IAAI,KAAK,YACP;EAEF,KAAK,aAAa;EAClB,KAAK,MAAM,cAAc,KAAK,aAAa,OAAO,GAChD,WAAW,QAAQ;CAEvB;AACF"}
|
|
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 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 }\n}\n\nexport type Process = {\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 /** `null` until the first check has completed. */\n lastChecked: string | null\n /** `null` until a check has succeeded. */\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; degraded: 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\n// Global setTimeout on purpose: node:timers/promises is not controlled by\n// vi.useFakeTimers(), so switching would change timing for consumers' tests.\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 !== undefined && ms > 0) {\n return Promise.race([promise, runTimeoutTimer(ms)])\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 = <A extends unknown[], T>(\n fn: (...args: A) => Promise<T>,\n ms: number\n): ((...args: A) => Promise<T>) => {\n let current: Promise<T> | null = null\n let clearHandle: NodeJS.Timeout | null = null\n\n return (...args: A): Promise<T> => {\n if (!current) {\n current = fn(...args)\n\n /* istanbul ignore next */\n if (clearHandle) {\n clearTimeout(clearHandle)\n clearHandle = null\n }\n\n const schedule = () => {\n if (ms > 0) {\n clearHandle = setTimeout(\n /* istanbul ignore next */ () => {\n current = null\n clearHandle = null\n },\n ms\n )\n } else {\n current = null\n }\n }\n current.then(schedule, schedule)\n }\n\n return current\n }\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 = <A extends unknown[], T>(\n fn: (...args: A) => Promise<T>\n) => throttle(fn, 0)\n","import { performance } from 'node:perf_hooks'\nimport { runAgainstTimeout, singleFlight } from './timing'\nimport {\n type CheckError,\n type DependencyCheck,\n type 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 = { lastChecked: null, lastSuccess: null }\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 const { config } = this\n if (config.syncCall) {\n await this.doSyncCheck(config)\n } else {\n this.doAsyncCheck(config)\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 syncCall,\n timeoutLimitMs,\n }: SyncInlineConfig | SyncPolledConfig) {\n const start = performance.now()\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(\n err instanceof Error ? err : new Error(String(err))\n )\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 asyncCall,\n healthyLimitMs,\n timeoutLimitMs,\n }: AsyncConfig) {\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 this.freshness = {\n ...this.freshness,\n lastChecked: new Date().toISOString(),\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,\n impact: this.config.impact,\n mode: this.mode,\n freshness: this.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 const [load1 = 0, load5 = 0, load15 = 0] = os.loadavg()\n let memUsedRatio: number\n /* istanbul ignore else */\n if (total > 0) {\n memUsedRatio = (total - free) / total\n } else {\n memUsedRatio = 0\n }\n\n return {\n status: 'ok',\n timestamp: new Date().toISOString(),\n system: {\n uptime: os.uptime(),\n loadavg: [load1, load5, load15],\n totalmem: total,\n freemem: free,\n memUsedRatio,\n cpus: {\n count: cpus.length,\n },\n },\n process: {\n uptime: process.uptime(),\n memory: process.memoryUsage(),\n },\n }\n}\n","import { toEntity } from '@sebspark/hyper-media'\nimport { createCache, InMemoryPersistor } from '@sebspark/promise-cache'\nimport { type ErrorRequestHandler, type RequestHandler, 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 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 const persistor = new InMemoryPersistor()\n const cache = createCache(persistor)\n\n // Health\n const cachedHealth = cache.wrap(() => this.health(), {\n key: '/health',\n expiry: 1000,\n })\n const healthHandler: RequestHandler = async (\n req,\n res,\n next\n ): Promise<void> => {\n try {\n const health = await cachedHealth()\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 router.get('/health', healthHandler)\n\n // Ping (no cache handler for ping since that woul actually increase the cost of the call)\n const pingHandler: RequestHandler = (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 router.get('/health/ping', pingHandler)\n\n // Liveness\n const cachedLiveness = cache.wrap(() => this.live(), {\n key: 'health/live',\n expiry: 1000,\n })\n const livenessHandler: RequestHandler = async (req, res, next) => {\n try {\n const liveness = await cachedLiveness()\n res.status(200).json(\n toEntity(req, liveness, {\n health: '/health',\n })\n )\n } catch (err) {\n next?.(err)\n }\n }\n router.get('/health/live', livenessHandler)\n\n // Readiness\n const cachedReadiness = cache.wrap(() => this.ready(), {\n key: '/health/ready',\n expiry: 1000,\n })\n const readinessHandler: RequestHandler = async (req, res, next) => {\n try {\n const readiness = await cachedReadiness()\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 router.get('/health/ready', readinessHandler)\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, monitor] = 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: monitor.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 criticalDegraded = 0\n let criticalFailing = 0\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) criticalDegraded++\n else nonCritDegraded++\n degradedReasons.push(`${name}:degraded`)\n } else {\n // 'error'\n if (isCritical) criticalFailing++\n else nonCritFailing++\n /* istanbul ignore else */\n if (c.error?.code) {\n degradedReasons.push(`${name}:${c.error.code}`)\n } else {\n degradedReasons.push(`${name}:error`)\n }\n }\n }\n\n const summary: ReadinessSummary = {\n critical: {\n ok: criticalOk,\n degraded: criticalDegraded,\n failing: criticalFailing,\n },\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(): Promise<HealthSummary> {\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 }\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 if (this.isDisposed) {\n return\n }\n this.isDisposed = true\n for (const dependency of this.dependencies.values()) {\n dependency.dispose()\n }\n }\n}\n"],"mappings":";;;;;;AA2FA,IAAa,eAAb,cAAkC,MAAM;CACtC,cAAc;EACZ,MAAM,SAAS;EACf,KAAK,OAAO;CACd;AACF;AAEA,IAAa,eAAb,cAAkC,MAAM;CACtC,cAAc;EACZ,MAAM,SAAS;EACf,KAAK,OAAO;CACd;AACF;;ACnGA,MAAa,QAAQ,OACnB,IAAI,SAAe,YAAY,WAAW,SAAS,EAAE,CAAC;AAExD,MAAa,kBAAkB,OAAO,OAAe;CACnD,MAAM,KAAK,EAAE;CACb,MAAM,IAAI,aAAa;AACzB;AAEA,MAAa,qBACX,SACA,OACe;CACf,IAAI,OAAO,KAAA,KAAa,KAAK,GAC3B,OAAO,QAAQ,KAAK,CAAC,SAAS,gBAAgB,EAAE,CAAC,CAAC;CAGpD,OAAO;AACT;;;;;;;;;AAUA,MAAa,YACX,IACA,OACiC;CACjC,IAAI,UAA6B;CACjC,IAAI,cAAqC;CAEzC,QAAQ,GAAG,SAAwB;EACjC,IAAI,CAAC,SAAS;GACZ,UAAU,GAAG,GAAG,IAAI;;GAGpB,IAAI,aAAa;IACf,aAAa,WAAW;IACxB,cAAc;GAChB;GAEA,MAAM,iBAAiB;IACrB,IAAI,KAAK,GACP,cAAc;;WACqB;MAC/B,UAAU;MACV,cAAc;KAChB;KACA;IACF;SAEA,UAAU;GAEd;GACA,QAAQ,KAAK,UAAU,QAAQ;EACjC;EAEA,OAAO;CACT;AACF;;;;;;AAOA,MAAa,gBACX,OACG,SAAS,IAAI,CAAC;;;;;;;;;;;;;;;;;;;;ACsDnB,IAAa,oBAAb,MAA+B;;CAE7B;;CAEA;;CAGA;;CAEA;;CAEA;;CAEA,YAA+B;EAAE,aAAa;EAAM,aAAa;CAAK;;CAEtE;;CAGA,aAAqB;;CAErB;;;;;CAMA,YAAY,QAAiC;EAC3C,KAAK,SAAS;EAEd,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AAO;GACL;GACA;GACA;GACA;GACA;GACA;EACF;CACF;;;;CAKA,IAAW,SAAS;EAClB,OAAO,KAAK;CACd;;;;CAKA,CAAQ,OAAO,WAAW;EACxB,KAAK,QAAQ;CACf;;;;;;CAOA,UAAiB;EACf,IAAI,KAAK,YACP;EAEF,KAAK,aAAa;EAClB,KAAK,MAAM,cAAc,KAAK,aAAa,OAAO,GAChD,WAAW,QAAQ;CAEvB;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sebspark/health-check",
|
|
3
|
-
"version": "3.0.
|
|
3
|
+
"version": "3.0.15",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.mjs",
|
|
@@ -20,11 +20,11 @@
|
|
|
20
20
|
"lint": "biome check .",
|
|
21
21
|
"test": "vitest run --passWithNoTests --coverage --fsModuleCachePath node_modules/.vitest-cache",
|
|
22
22
|
"test:e2e": "vitest run --config ../../vitest.e2e.config.mts --fsModuleCachePath node_modules/.vitest-cache",
|
|
23
|
-
"typecheck": "vitest --typecheck.only --passWithNoTests --run"
|
|
23
|
+
"typecheck": "tsc --noEmit -p . && vitest --typecheck.only --passWithNoTests --run"
|
|
24
24
|
},
|
|
25
25
|
"dependencies": {
|
|
26
|
-
"@sebspark/hyper-media": "0.1.
|
|
27
|
-
"@sebspark/promise-cache": "8.1.
|
|
26
|
+
"@sebspark/hyper-media": "0.1.8",
|
|
27
|
+
"@sebspark/promise-cache": "8.1.10",
|
|
28
28
|
"express": "5.3.0"
|
|
29
29
|
},
|
|
30
30
|
"devDependencies": {
|