@sebspark/health-check 3.0.15 → 3.1.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/CHANGELOG.md +11 -0
- package/README.md +33 -14
- package/dist/index.d.mts +22 -2
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +96 -19
- package/dist/index.mjs.map +1 -1
- package/package.json +4 -5
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,16 @@
|
|
|
1
1
|
# @sebspark/health-check
|
|
2
2
|
|
|
3
|
+
## 3.1.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 1b464d1: `liveness()`'s `system` block now reads the container's cgroup limits (v2, with a v1 fallback) for memory and CPU when available, instead of always reporting host/node metrics from `os.*`. This fixes misleading `totalmem`/`freemem`/`memUsedRatio`/`cpus.count` values in containerized environments (e.g. Kubernetes) where the container's resource allocation is smaller than the node's.
|
|
8
|
+
|
|
9
|
+
- Added `system.resourceSource: 'cgroup' | 'host'` so consumers know which source the figures come from.
|
|
10
|
+
- `system.uptime` and `system.loadavg` are now only present when `resourceSource` is `'host'` — they have no meaningful cgroup equivalent and the node's load/uptime is not representative of this container. `process.uptime` (unaffected) remains the accurate uptime for this process.
|
|
11
|
+
- `system.cpus.count` can now be fractional (e.g. `0.5`) when `resourceSource` is `'cgroup'`, reflecting the container's actual vCPU allotment rather than the host's physical core count.
|
|
12
|
+
- Falls back to the previous `os.*`-based host behavior when no cgroup limits are found.
|
|
13
|
+
|
|
3
14
|
## 3.0.15
|
|
4
15
|
|
|
5
16
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -11,6 +11,7 @@ An easy way to add health check routes to your API.
|
|
|
11
11
|
- `/health` – combined view
|
|
12
12
|
- Supports critical and non-critical dependencies
|
|
13
13
|
- Throttled dependency checks to avoid overload
|
|
14
|
+
- `system` metrics are container-aware: when running under a cgroup (e.g. Kubernetes), memory and CPU figures reflect the container's own limit/usage rather than the host node's, so `system.resourceSource` tells you which one you're looking at (`"cgroup"` or `"host"`)
|
|
14
15
|
|
|
15
16
|
## Usage
|
|
16
17
|
|
|
@@ -266,9 +267,17 @@ app.listen(3000, () => {
|
|
|
266
267
|
"HealthCheck_System": {
|
|
267
268
|
"type": "object",
|
|
268
269
|
"properties": {
|
|
270
|
+
"resourceSource": {
|
|
271
|
+
"type": "string",
|
|
272
|
+
"enum": [
|
|
273
|
+
"cgroup",
|
|
274
|
+
"host"
|
|
275
|
+
],
|
|
276
|
+
"description": "Whether memory/CPU figures come from the container's cgroup limits or the host node (os.*). 'host' only when no cgroup limits are found."
|
|
277
|
+
},
|
|
269
278
|
"uptime": {
|
|
270
279
|
"type": "number",
|
|
271
|
-
"description": "
|
|
280
|
+
"description": "Host node uptime in seconds. Only present when resourceSource is 'host'; has no meaningful cgroup equivalent. See process.uptime for the process's own uptime."
|
|
272
281
|
},
|
|
273
282
|
"loadavg": {
|
|
274
283
|
"type": "array",
|
|
@@ -277,13 +286,15 @@ app.listen(3000, () => {
|
|
|
277
286
|
},
|
|
278
287
|
"minItems": 3,
|
|
279
288
|
"maxItems": 3,
|
|
280
|
-
"description": "
|
|
289
|
+
"description": "Host node load averages for 1, 5, 15 minutes, across all containers on the node. Only present when resourceSource is 'host'."
|
|
281
290
|
},
|
|
282
291
|
"totalmem": {
|
|
283
|
-
"type": "number"
|
|
292
|
+
"type": "number",
|
|
293
|
+
"description": "Container memory limit in bytes when resourceSource is 'cgroup'; host total memory otherwise."
|
|
284
294
|
},
|
|
285
295
|
"freemem": {
|
|
286
|
-
"type": "number"
|
|
296
|
+
"type": "number",
|
|
297
|
+
"description": "Container memory headroom (limit - usage) in bytes when resourceSource is 'cgroup'; host free memory otherwise."
|
|
287
298
|
},
|
|
288
299
|
"memUsedRatio": {
|
|
289
300
|
"type": "number",
|
|
@@ -294,8 +305,10 @@ app.listen(3000, () => {
|
|
|
294
305
|
"type": "object",
|
|
295
306
|
"properties": {
|
|
296
307
|
"count": {
|
|
297
|
-
"type": "
|
|
298
|
-
"minimum":
|
|
308
|
+
"type": "number",
|
|
309
|
+
"minimum": 0,
|
|
310
|
+
"exclusiveMinimum": true,
|
|
311
|
+
"description": "Container's allotted vCPU share (can be fractional, e.g. 0.5) when resourceSource is 'cgroup'; host physical core count otherwise."
|
|
299
312
|
}
|
|
300
313
|
},
|
|
301
314
|
"required": [
|
|
@@ -304,8 +317,7 @@ app.listen(3000, () => {
|
|
|
304
317
|
}
|
|
305
318
|
},
|
|
306
319
|
"required": [
|
|
307
|
-
"
|
|
308
|
-
"loadavg",
|
|
320
|
+
"resourceSource",
|
|
309
321
|
"totalmem",
|
|
310
322
|
"freemem",
|
|
311
323
|
"memUsedRatio",
|
|
@@ -881,20 +893,26 @@ components:
|
|
|
881
893
|
arch:
|
|
882
894
|
type: string
|
|
883
895
|
description: e.g., x64, arm64
|
|
896
|
+
resourceSource:
|
|
897
|
+
type: string
|
|
898
|
+
enum: [cgroup, host]
|
|
899
|
+
description: Whether memory/CPU figures come from the container's cgroup limits or the host node (os.*). 'host' only when no cgroup limits are found.
|
|
884
900
|
uptime:
|
|
885
901
|
type: number
|
|
886
|
-
description:
|
|
902
|
+
description: Host node uptime in seconds. Only present when resourceSource is 'host'; has no meaningful cgroup equivalent. See process.uptime for the process's own uptime.
|
|
887
903
|
loadavg:
|
|
888
904
|
type: array
|
|
889
905
|
items:
|
|
890
906
|
type: number
|
|
891
907
|
minItems: 3
|
|
892
908
|
maxItems: 3
|
|
893
|
-
description:
|
|
909
|
+
description: Host node load averages for 1, 5, 15 minutes, across all containers on the node. Only present when resourceSource is 'host'.
|
|
894
910
|
totalmem:
|
|
895
911
|
type: number
|
|
912
|
+
description: Container memory limit in bytes when resourceSource is 'cgroup'; host total memory otherwise.
|
|
896
913
|
freemem:
|
|
897
914
|
type: number
|
|
915
|
+
description: Container memory headroom (limit - usage) in bytes when resourceSource is 'cgroup'; host free memory otherwise.
|
|
898
916
|
memUsedRatio:
|
|
899
917
|
type: number
|
|
900
918
|
minimum: 0
|
|
@@ -903,8 +921,10 @@ components:
|
|
|
903
921
|
type: object
|
|
904
922
|
properties:
|
|
905
923
|
count:
|
|
906
|
-
type:
|
|
907
|
-
minimum:
|
|
924
|
+
type: number
|
|
925
|
+
minimum: 0
|
|
926
|
+
exclusiveMinimum: true
|
|
927
|
+
description: Container's allotted vCPU share (can be fractional, e.g. 0.5) when resourceSource is 'cgroup'; host physical core count otherwise.
|
|
908
928
|
model:
|
|
909
929
|
type: string
|
|
910
930
|
speedMHz:
|
|
@@ -915,8 +935,7 @@ components:
|
|
|
915
935
|
- platform
|
|
916
936
|
- release
|
|
917
937
|
- arch
|
|
918
|
-
-
|
|
919
|
-
- loadavg
|
|
938
|
+
- resourceSource
|
|
920
939
|
- totalmem
|
|
921
940
|
- freemem
|
|
922
941
|
- memUsedRatio
|
package/dist/index.d.mts
CHANGED
|
@@ -20,12 +20,32 @@ export type Status = {
|
|
|
20
20
|
status: StatusValue;
|
|
21
21
|
};
|
|
22
22
|
export type System = {
|
|
23
|
-
|
|
24
|
-
|
|
23
|
+
/**
|
|
24
|
+
* Whether memory/CPU figures come from the container's cgroup limits or
|
|
25
|
+
* the host node (`os.*`). `'host'` only when no cgroup limits are found.
|
|
26
|
+
*/
|
|
27
|
+
resourceSource: 'cgroup' | 'host';
|
|
28
|
+
/**
|
|
29
|
+
* Host node uptime in seconds. Only present when `resourceSource` is
|
|
30
|
+
* `'host'`; has no meaningful cgroup equivalent. See `process.uptime` for
|
|
31
|
+
* the process's own uptime.
|
|
32
|
+
*/
|
|
33
|
+
uptime?: number;
|
|
34
|
+
/**
|
|
35
|
+
* Host node load averages for 1, 5, 15 minutes, across all containers on
|
|
36
|
+
* the node. Only present when `resourceSource` is `'host'`.
|
|
37
|
+
*/
|
|
38
|
+
loadavg?: [number, number, number];
|
|
39
|
+
/** Container memory limit in bytes when `resourceSource` is `'cgroup'`; host total memory otherwise. */
|
|
25
40
|
totalmem: number;
|
|
41
|
+
/** Container memory headroom (limit - usage) in bytes when `resourceSource` is `'cgroup'`; host free memory otherwise. */
|
|
26
42
|
freemem: number;
|
|
27
43
|
memUsedRatio: number;
|
|
28
44
|
cpus: {
|
|
45
|
+
/**
|
|
46
|
+
* Container's allotted vCPU share (can be fractional, e.g. `0.5`) when
|
|
47
|
+
* `resourceSource` is `'cgroup'`; host physical core count otherwise.
|
|
48
|
+
*/
|
|
29
49
|
count: number;
|
|
30
50
|
};
|
|
31
51
|
};
|
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;
|
|
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;;;;;EAKV;;;;;;EAMA;;;;;EAKA;;EAEA;;EAEA;EACA;EACA;;;;;IAKE;;;YAIQ;EACV;EACA,QAAQ,OAAO;;YAGL,WAAW;EACrB;EACA,QAAQ;EACR,SAAS;;YAGC;;EAEV;;EAEA;;YAGU;EACV;GACC;;YAGS;EACV;EACA;;YAGU,kBAAkB;EAC5B,QAAQ;EACR,MAAM;EACN,WAAW;EACX,WAAW;EACX,UAAU;EACV,QAAQ;EACR;;YAGU;EACV;IAAY;IAAY;IAAkB;;EAC1C;IAAe;IAAY;IA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spark/promise-cache";
|
|
4
4
|
import { Router } from "express";
|
|
5
5
|
import os from "node:os";
|
|
6
|
+
import { readFileSync } from "node:fs";
|
|
6
7
|
// src/types.ts
|
|
7
8
|
var TimeoutError = class extends Error {
|
|
8
9
|
constructor() {
|
|
@@ -257,9 +258,66 @@ var DependencyMonitor = class {
|
|
|
257
258
|
if (this.timeout) clearTimeout(this.timeout);
|
|
258
259
|
}
|
|
259
260
|
};
|
|
261
|
+
// src/cgroup.ts
|
|
262
|
+
/** cgroup v1's sentinel for "no memory limit set" (close to 2^63, in practice 9223372036854771712). */
|
|
263
|
+
const CGROUP_V1_UNLIMITED_MEMORY = 0xde0b6b3a7640000;
|
|
264
|
+
const readFile = (path) => {
|
|
265
|
+
try {
|
|
266
|
+
return readFileSync(path, "utf8").trim();
|
|
267
|
+
} catch {
|
|
268
|
+
return null;
|
|
269
|
+
}
|
|
270
|
+
};
|
|
271
|
+
/**
|
|
272
|
+
* Reads the container's memory limit and current usage from the cgroup
|
|
273
|
+
* filesystem, preferring cgroup v2 and falling back to cgroup v1.
|
|
274
|
+
* Returns `null` when neither is available (e.g. not running in a container).
|
|
275
|
+
*/
|
|
276
|
+
const readCgroupMemory = () => {
|
|
277
|
+
const maxV2 = readFile("/sys/fs/cgroup/memory.max");
|
|
278
|
+
const currentV2 = readFile("/sys/fs/cgroup/memory.current");
|
|
279
|
+
if (maxV2 !== null && currentV2 !== null) return {
|
|
280
|
+
limit: maxV2 === "max" ? null : Number(maxV2),
|
|
281
|
+
usage: Number(currentV2)
|
|
282
|
+
};
|
|
283
|
+
const limitV1 = readFile("/sys/fs/cgroup/memory/memory.limit_in_bytes");
|
|
284
|
+
const usageV1 = readFile("/sys/fs/cgroup/memory/memory.usage_in_bytes");
|
|
285
|
+
if (limitV1 !== null && usageV1 !== null) {
|
|
286
|
+
const limit = Number(limitV1);
|
|
287
|
+
return {
|
|
288
|
+
limit: limit >= CGROUP_V1_UNLIMITED_MEMORY ? null : limit,
|
|
289
|
+
usage: Number(usageV1)
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
return null;
|
|
293
|
+
};
|
|
294
|
+
/**
|
|
295
|
+
* Reads the container's allotted vCPU share from the cgroup filesystem,
|
|
296
|
+
* preferring cgroup v2 and falling back to cgroup v1. Returns `null` when
|
|
297
|
+
* neither is available (e.g. not running in a container).
|
|
298
|
+
*/
|
|
299
|
+
const readCgroupCpu = () => {
|
|
300
|
+
const maxV2 = readFile("/sys/fs/cgroup/cpu.max");
|
|
301
|
+
if (maxV2 !== null) {
|
|
302
|
+
const [quotaRaw, periodRaw] = maxV2.split(" ");
|
|
303
|
+
if (quotaRaw === "max") return { quota: null };
|
|
304
|
+
const quota = Number(quotaRaw);
|
|
305
|
+
const period = Number(periodRaw);
|
|
306
|
+
return period > 0 ? { quota: quota / period } : null;
|
|
307
|
+
}
|
|
308
|
+
const quotaV1 = readFile("/sys/fs/cgroup/cpu/cpu.cfs_quota_us");
|
|
309
|
+
const periodV1 = readFile("/sys/fs/cgroup/cpu/cpu.cfs_period_us");
|
|
310
|
+
if (quotaV1 !== null && periodV1 !== null) {
|
|
311
|
+
const quota = Number(quotaV1);
|
|
312
|
+
const period = Number(periodV1);
|
|
313
|
+
if (quota <= 0) return { quota: null };
|
|
314
|
+
return period > 0 ? { quota: quota / period } : null;
|
|
315
|
+
}
|
|
316
|
+
return null;
|
|
317
|
+
};
|
|
260
318
|
// src/static-checks.ts
|
|
261
319
|
const ping = () => ({ status: "ok" });
|
|
262
|
-
const
|
|
320
|
+
const hostSystem = () => {
|
|
263
321
|
const cpus = os.cpus();
|
|
264
322
|
const total = os.totalmem();
|
|
265
323
|
const free = os.freemem();
|
|
@@ -269,26 +327,45 @@ const liveness = () => {
|
|
|
269
327
|
if (total > 0) memUsedRatio = (total - free) / total;
|
|
270
328
|
else memUsedRatio = 0;
|
|
271
329
|
return {
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
memUsedRatio,
|
|
284
|
-
cpus: { count: cpus.length }
|
|
285
|
-
},
|
|
286
|
-
process: {
|
|
287
|
-
uptime: process.uptime(),
|
|
288
|
-
memory: process.memoryUsage()
|
|
289
|
-
}
|
|
330
|
+
resourceSource: "host",
|
|
331
|
+
uptime: os.uptime(),
|
|
332
|
+
loadavg: [
|
|
333
|
+
load1,
|
|
334
|
+
load5,
|
|
335
|
+
load15
|
|
336
|
+
],
|
|
337
|
+
totalmem: total,
|
|
338
|
+
freemem: free,
|
|
339
|
+
memUsedRatio,
|
|
340
|
+
cpus: { count: cpus.length }
|
|
290
341
|
};
|
|
291
342
|
};
|
|
343
|
+
const cgroupSystem = (memory, cpu) => {
|
|
344
|
+
const limit = memory?.limit ?? os.totalmem();
|
|
345
|
+
const usage = memory?.usage ?? os.totalmem() - os.freemem();
|
|
346
|
+
const memUsedRatio = limit > 0 ? usage / limit : 0;
|
|
347
|
+
return {
|
|
348
|
+
resourceSource: "cgroup",
|
|
349
|
+
totalmem: limit,
|
|
350
|
+
freemem: limit - usage,
|
|
351
|
+
memUsedRatio,
|
|
352
|
+
cpus: { count: cpu?.quota ?? os.cpus().length }
|
|
353
|
+
};
|
|
354
|
+
};
|
|
355
|
+
const getSystem = () => {
|
|
356
|
+
const memory = readCgroupMemory();
|
|
357
|
+
const cpu = readCgroupCpu();
|
|
358
|
+
return memory?.limit != null || cpu?.quota != null ? cgroupSystem(memory, cpu) : hostSystem();
|
|
359
|
+
};
|
|
360
|
+
const liveness = () => ({
|
|
361
|
+
status: "ok",
|
|
362
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
363
|
+
system: getSystem(),
|
|
364
|
+
process: {
|
|
365
|
+
uptime: process.uptime(),
|
|
366
|
+
memory: process.memoryUsage()
|
|
367
|
+
}
|
|
368
|
+
});
|
|
292
369
|
// src/health-monitor.ts
|
|
293
370
|
/**
|
|
294
371
|
* HealthMonitor wires up standard health check endpoints for an Express app.
|
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 /** `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;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;;;;;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/cgroup.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 /**\n * Whether memory/CPU figures come from the container's cgroup limits or\n * the host node (`os.*`). `'host'` only when no cgroup limits are found.\n */\n resourceSource: 'cgroup' | 'host'\n /**\n * Host node uptime in seconds. Only present when `resourceSource` is\n * `'host'`; has no meaningful cgroup equivalent. See `process.uptime` for\n * the process's own uptime.\n */\n uptime?: number\n /**\n * Host node load averages for 1, 5, 15 minutes, across all containers on\n * the node. Only present when `resourceSource` is `'host'`.\n */\n loadavg?: [number, number, number]\n /** Container memory limit in bytes when `resourceSource` is `'cgroup'`; host total memory otherwise. */\n totalmem: number\n /** Container memory headroom (limit - usage) in bytes when `resourceSource` is `'cgroup'`; host free memory otherwise. */\n freemem: number\n memUsedRatio: number // 0..1\n cpus: {\n /**\n * Container's allotted vCPU share (can be fractional, e.g. `0.5`) when\n * `resourceSource` is `'cgroup'`; host physical core count otherwise.\n */\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 { readFileSync } from 'node:fs'\n\n/** Memory limit/usage as reported by the container's cgroup. */\nexport type CgroupMemory = {\n /** Bytes, or `null` when the cgroup has no memory limit (unbounded). */\n limit: number | null\n /** Bytes currently in use. */\n usage: number\n}\n\n/** CPU allotment as reported by the container's cgroup. */\nexport type CgroupCpu = {\n /** Allotted vCPU share (can be fractional, e.g. `0.5`), or `null` when unbounded. */\n quota: number | null\n}\n\n/** cgroup v1's sentinel for \"no memory limit set\" (close to 2^63, in practice 9223372036854771712). */\nconst CGROUP_V1_UNLIMITED_MEMORY = 1e18\n\nconst readFile = (path: string): string | null => {\n try {\n return readFileSync(path, 'utf8').trim()\n } catch {\n return null\n }\n}\n\n/**\n * Reads the container's memory limit and current usage from the cgroup\n * filesystem, preferring cgroup v2 and falling back to cgroup v1.\n * Returns `null` when neither is available (e.g. not running in a container).\n */\nexport const readCgroupMemory = (): CgroupMemory | null => {\n const maxV2 = readFile('/sys/fs/cgroup/memory.max')\n const currentV2 = readFile('/sys/fs/cgroup/memory.current')\n if (maxV2 !== null && currentV2 !== null) {\n return {\n limit: maxV2 === 'max' ? null : Number(maxV2),\n usage: Number(currentV2),\n }\n }\n\n const limitV1 = readFile('/sys/fs/cgroup/memory/memory.limit_in_bytes')\n const usageV1 = readFile('/sys/fs/cgroup/memory/memory.usage_in_bytes')\n if (limitV1 !== null && usageV1 !== null) {\n const limit = Number(limitV1)\n return {\n limit: limit >= CGROUP_V1_UNLIMITED_MEMORY ? null : limit,\n usage: Number(usageV1),\n }\n }\n\n return null\n}\n\n/**\n * Reads the container's allotted vCPU share from the cgroup filesystem,\n * preferring cgroup v2 and falling back to cgroup v1. Returns `null` when\n * neither is available (e.g. not running in a container).\n */\nexport const readCgroupCpu = (): CgroupCpu | null => {\n const maxV2 = readFile('/sys/fs/cgroup/cpu.max')\n if (maxV2 !== null) {\n const [quotaRaw, periodRaw] = maxV2.split(' ')\n if (quotaRaw === 'max') return { quota: null }\n const quota = Number(quotaRaw)\n const period = Number(periodRaw)\n return period > 0 ? { quota: quota / period } : null\n }\n\n const quotaV1 = readFile('/sys/fs/cgroup/cpu/cpu.cfs_quota_us')\n const periodV1 = readFile('/sys/fs/cgroup/cpu/cpu.cfs_period_us')\n if (quotaV1 !== null && periodV1 !== null) {\n const quota = Number(quotaV1)\n const period = Number(periodV1)\n if (quota <= 0) return { quota: null }\n return period > 0 ? { quota: quota / period } : null\n }\n\n return null\n}\n","import os from 'node:os'\nimport { readCgroupCpu, readCgroupMemory } from './cgroup'\nimport type { Liveness, Status, System } from './types'\n\nexport const ping = (): Status => ({ status: 'ok' })\n\nconst hostSystem = (): System => {\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 resourceSource: 'host',\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}\n\nconst cgroupSystem = (\n memory: ReturnType<typeof readCgroupMemory>,\n cpu: ReturnType<typeof readCgroupCpu>\n): System => {\n const limit = memory?.limit ?? os.totalmem()\n const usage = memory?.usage ?? os.totalmem() - os.freemem()\n const memUsedRatio = limit > 0 ? usage / limit : 0\n\n return {\n resourceSource: 'cgroup',\n totalmem: limit,\n freemem: limit - usage,\n memUsedRatio,\n cpus: {\n count: cpu?.quota ?? os.cpus().length,\n },\n }\n}\n\nconst getSystem = (): System => {\n const memory = readCgroupMemory()\n const cpu = readCgroupCpu()\n const isCgroupBound = memory?.limit != null || cpu?.quota != null\n\n return isCgroupBound ? cgroupSystem(memory, cpu) : hostSystem()\n}\n\nexport const liveness = (): Liveness => ({\n status: 'ok',\n timestamp: new Date().toISOString(),\n system: getSystem(),\n process: {\n uptime: process.uptime(),\n memory: process.memoryUsage(),\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"],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,EAAE,WAAW,cAAc,EAAE,WAAW,OACjD;EACA,MAAM,sBAAsB,OAAO,MAChC,MAAM,EAAE,WAAW,cAAc,EAAE,WAAW,UACjD;EAEA,IAAI,kBAAkB,SAAS;OAC1B,IAAI,uBAAuB,oBAAoB,SAAS;EAW7D,OAAO;GAPL;GACA,4BAAW,IAAI,KAAK,EAAA,CAAE,YAAY;GAElC;GACA;EAGW;CACf;CAEA,MAAa,SAAiC;EAC5C,MAAM,EAAE,QAAQ,QAAQ,YAAY,MAAM,KAAK,MAAM;EACrD,MAAM,EAAE,WAAW,QAAQ,YAAY,KAAK,KAAK;EAEjD,OAAO;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.1.0",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.mjs",
|
|
@@ -17,10 +17,10 @@
|
|
|
17
17
|
"scripts": {
|
|
18
18
|
"build": "spark-build src/index.ts",
|
|
19
19
|
"dev": "tsc --watch --noEmit",
|
|
20
|
-
"lint": "biome check .",
|
|
20
|
+
"lint": "biome check --write .",
|
|
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": "tsc --noEmit -p . && vitest --typecheck.only --passWithNoTests --run"
|
|
23
|
+
"typecheck": "tsc --noEmit -p . && vitest --typecheck.only --passWithNoTests --run --fsModuleCachePath node_modules/.vitest-cache"
|
|
24
24
|
},
|
|
25
25
|
"dependencies": {
|
|
26
26
|
"@sebspark/hyper-media": "0.1.8",
|
|
@@ -30,11 +30,10 @@
|
|
|
30
30
|
"devDependencies": {
|
|
31
31
|
"@biomejs/biome": "2.6.4",
|
|
32
32
|
"@google-cloud/pubsub": "6.3.2",
|
|
33
|
-
"@sebspark/tsconfig": "3.0.
|
|
33
|
+
"@sebspark/tsconfig": "3.0.29",
|
|
34
34
|
"@testcontainers/gcloud": "12.2.1",
|
|
35
35
|
"@testcontainers/mockserver": "12.2.1",
|
|
36
36
|
"@testcontainers/redis": "12.2.1",
|
|
37
|
-
"mockserver-client": "9.2.0",
|
|
38
37
|
"supertest": "7.3.1",
|
|
39
38
|
"typescript": "7.0.2",
|
|
40
39
|
"vite": "8.3.5",
|