@sebspark/health-check 3.0.14 → 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 CHANGED
@@ -1,5 +1,29 @@
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
+
14
+ ## 3.0.15
15
+
16
+ ### Patch Changes
17
+
18
+ - 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.
19
+ - A failed check no longer mutates the `freshness` object of a result that was already returned.
20
+ - When a dependency throws a non-`Error` value, the error is now reported with its message (for example `'connection refused'`) instead of `message: undefined`.
21
+ - Internal type assertions were removed.
22
+ - Updated dependencies [176ea40]
23
+ - Updated dependencies [176ea40]
24
+ - @sebspark/hyper-media@0.1.8
25
+ - @sebspark/promise-cache@8.1.10
26
+
3
27
  ## 3.0.14
4
28
 
5
29
  ### 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": "Seconds."
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": "Load averages for 1, 5, 15 minutes."
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": "integer",
298
- "minimum": 1
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
- "uptime",
308
- "loadavg",
320
+ "resourceSource",
309
321
  "totalmem",
310
322
  "freemem",
311
323
  "memUsedRatio",
@@ -383,7 +395,10 @@ app.listen(3000, () => {
383
395
  "type": "object",
384
396
  "properties": {
385
397
  "lastChecked": {
386
- "type": "string",
398
+ "type": [
399
+ "string",
400
+ "null"
401
+ ],
387
402
  "format": "date-time"
388
403
  },
389
404
  "lastSuccess": {
@@ -878,20 +893,26 @@ components:
878
893
  arch:
879
894
  type: string
880
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.
881
900
  uptime:
882
901
  type: number
883
- description: Seconds.
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.
884
903
  loadavg:
885
904
  type: array
886
905
  items:
887
906
  type: number
888
907
  minItems: 3
889
908
  maxItems: 3
890
- description: Load averages for 1, 5, 15 minutes.
909
+ description: Host node load averages for 1, 5, 15 minutes, across all containers on the node. Only present when resourceSource is 'host'.
891
910
  totalmem:
892
911
  type: number
912
+ description: Container memory limit in bytes when resourceSource is 'cgroup'; host total memory otherwise.
893
913
  freemem:
894
914
  type: number
915
+ description: Container memory headroom (limit - usage) in bytes when resourceSource is 'cgroup'; host free memory otherwise.
895
916
  memUsedRatio:
896
917
  type: number
897
918
  minimum: 0
@@ -900,8 +921,10 @@ components:
900
921
  type: object
901
922
  properties:
902
923
  count:
903
- type: integer
904
- minimum: 1
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.
905
928
  model:
906
929
  type: string
907
930
  speedMHz:
@@ -912,8 +935,7 @@ components:
912
935
  - platform
913
936
  - release
914
937
  - arch
915
- - uptime
916
- - loadavg
938
+ - resourceSource
917
939
  - totalmem
918
940
  - freemem
919
941
  - memUsedRatio
@@ -969,7 +991,7 @@ components:
969
991
  type: object
970
992
  properties:
971
993
  lastChecked:
972
- type: string
994
+ type: [string, "null"]
973
995
  format: date-time
974
996
  lastSuccess:
975
997
  type: [string, "null"]
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
- uptime: number;
24
- loadavg: [number, number, number];
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
  };
@@ -39,7 +59,9 @@ export type Liveness = Status & {
39
59
  process: Process;
40
60
  };
41
61
  export type Freshness = {
42
- lastChecked: string;
62
+ /** `null` until the first check has completed. */
63
+ lastChecked: string | null;
64
+ /** `null` until a check has succeeded. */
43
65
  lastSuccess: string | null;
44
66
  };
45
67
  export type Observed = {
@@ -200,7 +222,7 @@ export declare class DependencyMonitor {
200
222
  /** Last observed metrics (e.g., latency). */
201
223
  private observed?;
202
224
  /** Freshness timestamps for last check/success. */
203
- private freshness?;
225
+ private freshness;
204
226
  /** Optional details returned by the helth check call. */
205
227
  private details?;
206
228
  /** Indicates whether this monitor has been disposed. */
@@ -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;EACV;EACA;;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;IAAkB;;EAC7C;;YAGU,mBAAmB;EAC7B;EACA;IAAY;IAAe;IAAkB;;EAC7C,SAAS;EACT,QAAQ,eAAe;;YAGb,gBAAgB,SAC1B,KAAK,0CACL,KAAK;EAAoC;;qBAE9B,qBAAqB;EAChC;;qBAMW,qBAAqB;EAChC;;;;;KC9EG;;;;;;EAMH,QAAQ;;;;;;EAOR;;;;;;EAOA;;;;;;EAOA;;;;;;;EAQA;;;;;;YAOU,mBAAmB;;EAE7B,gBAAgB,QAAQ,mBAAmB,wBAAwB;EACnE;EACA;EACA;;;;;;YAOU,mBAAmB;;EAE7B,gBAAgB,QAAQ,mBAAmB,wBAAwB;;EAEnE;EACA;;;;;;YAOU,cAAc;;;;;EAKxB,YACE,iBACE,QAAQ,mBAAmB,wBAAwB,iBACzC,yBACF;;EAEZ;EACA;;;;;;;;YASU,0BACR,mBACA,mBACA;;;;;;;;;;;;;;;;;;;qBAoBS;;mBAEM;;mBAEA;;UAGT;;UAEA;;UAEA;;UAEA;;UAEA;;UAGA;;UAEA;;;;;EAMR,YAAY,QAAQ;;MAuBT,UAAM;;;;;;UASH;;;;;;;;UAsBA;;;;;;;UAqBA;;;;;;UAsCN;;;;;UAyCA;;;;;;;EA4BK,SAAS,QAAQ;;GAuBtB,OAAO;;;;;;EASR;;iBC/VQ;EACf;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAmCW;mBACM;mBACA;UACT;;;;EAKR,YAAY,SAAS;;;;;;;;;;;;;;;;;EA0Bd,cAAc,cAAc,YAAY;;;;UAQvC;;;;EAmGD,QA3GwCA;;;;EAkHxC,QAPIC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAwCE,SAAS,QAAQ;EAkHjB,UAAM,QAAA;;;;MAiBR,UAAM;;;;GAOT,OAAO;;;;;;EASR"}
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,Q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} from "@sebspark/hyper-media";
3
3
  import { InMemoryPersistor, createCache } from "@sebspark/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() {
@@ -23,7 +24,7 @@ const runTimeoutTimer = async (ms) => {
23
24
  throw new TimeoutError();
24
25
  };
25
26
  const runAgainstTimeout = (promise, ms) => {
26
- if (ms > 0) return Promise.race([promise, runTimeoutTimer(ms)]);
27
+ if (ms !== void 0 && ms > 0) return Promise.race([promise, runTimeoutTimer(ms)]);
27
28
  return promise;
28
29
  };
29
30
  /**
@@ -37,7 +38,7 @@ const runAgainstTimeout = (promise, ms) => {
37
38
  const throttle = (fn, ms) => {
38
39
  let current = null;
39
40
  let clearHandle = null;
40
- const wrapped = (...args) => {
41
+ return (...args) => {
41
42
  if (!current) {
42
43
  current = fn(...args);
43
44
  /* istanbul ignore next */
@@ -60,7 +61,6 @@ const throttle = (fn, ms) => {
60
61
  }
61
62
  return current;
62
63
  };
63
- return wrapped;
64
64
  };
65
65
  /**
66
66
  * Wraps an async function so that concurrent invocations share the same in-flight Promise.
@@ -99,7 +99,10 @@ var DependencyMonitor = class {
99
99
  /** Last observed metrics (e.g., latency). */
100
100
  observed;
101
101
  /** Freshness timestamps for last check/success. */
102
- freshness;
102
+ freshness = {
103
+ lastChecked: null,
104
+ lastSuccess: null
105
+ };
103
106
  /** Optional details returned by the helth check call. */
104
107
  details;
105
108
  /** Indicates whether this monitor has been disposed. */
@@ -129,8 +132,9 @@ var DependencyMonitor = class {
129
132
  async doCheck() {
130
133
  if (this.timeout) clearTimeout(this.timeout);
131
134
  if (this.isDisposed) return;
132
- if (this.config.syncCall) await this.doSyncCheck();
133
- else this.doAsyncCheck();
135
+ const { config } = this;
136
+ if (config.syncCall) await this.doSyncCheck(config);
137
+ else this.doAsyncCheck(config);
134
138
  }
135
139
  /**
136
140
  * Execute a synchronous (inline/polled) check and update internal state.
@@ -139,15 +143,14 @@ var DependencyMonitor = class {
139
143
  * - Degraded if `"degraded"` or latency between `(healthyLimitMs, timeoutLimitMs]`
140
144
  * - Error if `"error"`, `Error`, or timeout exceeded
141
145
  */
142
- async doSyncCheck() {
146
+ async doSyncCheck({ syncCall, timeoutLimitMs }) {
143
147
  const start = performance.now();
144
- const { syncCall, timeoutLimitMs } = this.config;
145
148
  try {
146
149
  const response = await runAgainstTimeout(syncCall(), timeoutLimitMs);
147
150
  const duration = performance.now() - start;
148
151
  this.handleDependencyResponse(response, duration);
149
152
  } catch (err) {
150
- this.handleDependencyError(err);
153
+ this.handleDependencyError(err instanceof Error ? err : new Error(String(err)));
151
154
  }
152
155
  }
153
156
  /**
@@ -156,8 +159,7 @@ var DependencyMonitor = class {
156
159
  * if no callback result arrives within the thresholds.
157
160
  * - On callback, clears timers and classifies the result with latency.
158
161
  */
159
- async doAsyncCheck() {
160
- const { asyncCall, healthyLimitMs, timeoutLimitMs } = this.config;
162
+ async doAsyncCheck({ asyncCall, healthyLimitMs, timeoutLimitMs }) {
161
163
  const start = performance.now();
162
164
  let callActive = true;
163
165
  let healthTimeout;
@@ -214,11 +216,9 @@ var DependencyMonitor = class {
214
216
  code: error.code || "UNKNOWN",
215
217
  message: error.message
216
218
  };
217
- const end = /* @__PURE__ */ new Date();
218
- if (this.freshness) this.freshness.lastChecked = end.toISOString();
219
- else this.freshness = {
220
- lastChecked: end.toISOString(),
221
- lastSuccess: null
219
+ this.freshness = {
220
+ ...this.freshness,
221
+ lastChecked: (/* @__PURE__ */ new Date()).toISOString()
222
222
  };
223
223
  if ((this.config.retryRate || this.config.pollRate) && !this.isDisposed) {
224
224
  const delay = this.config.retryRate || this.config.pollRate;
@@ -258,33 +258,114 @@ var DependencyMonitor = class {
258
258
  if (this.timeout) clearTimeout(this.timeout);
259
259
  }
260
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
+ };
261
318
  // src/static-checks.ts
262
319
  const ping = () => ({ status: "ok" });
263
- const liveness = () => {
320
+ const hostSystem = () => {
264
321
  const cpus = os.cpus();
265
322
  const total = os.totalmem();
266
323
  const free = os.freemem();
324
+ const [load1 = 0, load5 = 0, load15 = 0] = os.loadavg();
267
325
  let memUsedRatio;
268
326
  /* istanbul ignore else */
269
327
  if (total > 0) memUsedRatio = (total - free) / total;
270
328
  else memUsedRatio = 0;
271
329
  return {
272
- status: "ok",
273
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
274
- system: {
275
- uptime: os.uptime(),
276
- loadavg: os.loadavg(),
277
- totalmem: total,
278
- freemem: free,
279
- memUsedRatio,
280
- cpus: { count: cpus.length }
281
- },
282
- process: {
283
- uptime: process.uptime(),
284
- memory: process.memoryUsage()
285
- }
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 }
341
+ };
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 }
286
353
  };
287
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
+ });
288
369
  // src/health-monitor.ts
289
370
  /**
290
371
  * HealthMonitor wires up standard health check endpoints for an Express app.
@@ -469,13 +550,13 @@ var HealthMonitor = class {
469
550
  const checks = {};
470
551
  for (let i = 0; i < settled.length; i++) {
471
552
  const s = settled[i];
472
- const [name] = entries[i];
553
+ const [name, monitor] = entries[i];
473
554
  if (s.status === "fulfilled") {
474
555
  const [, check] = s.value;
475
556
  checks[name] = check;
476
557
  } else checks[name] = {
477
558
  status: "error",
478
- impact: this.dependencies.get(name)?.impact,
559
+ impact: monitor.impact,
479
560
  mode: "polled",
480
561
  freshness: {
481
562
  lastChecked: (/* @__PURE__ */ new Date()).toISOString(),
@@ -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;;;;;;;;;;;;;;;;;;;;ACiDt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a,SAAS;EACpB,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"}
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"],"mappings":";;;;;;;AA+GA,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;;ACvHA,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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IACJ,UAAU;IACV,SAAS;GACX;GACA,aAAa;IACX,IAAI;IACJ,UAAU;IACV,SAAS;GACX;GACA;EACF;EAGA,IAAI,SAAsB;EAC1B,MAAM,SAAS,OAAO,OAAO,MAAM;EACnC,MAAM,mBAAmB,OAAO,MAC7B,MAAM,EAAE,WAAW,cAAc,EAAE,WAAW,OACjD;EACA,MAAM,qBAAqB,OAAO,MAC/B,MAAM,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.14",
3
+ "version": "3.1.0",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "main": "dist/index.mjs",
@@ -17,24 +17,23 @@
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": "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
- "@sebspark/hyper-media": "0.1.7",
27
- "@sebspark/promise-cache": "8.1.9",
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": {
31
31
  "@biomejs/biome": "2.6.4",
32
32
  "@google-cloud/pubsub": "6.3.2",
33
- "@sebspark/tsconfig": "3.0.28",
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",