@zero-server/sdk 0.9.1 → 0.9.3
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/LICENSE +21 -21
- package/README.md +460 -443
- package/index.js +414 -412
- package/lib/app.js +1172 -1172
- package/lib/auth/authorize.js +399 -399
- package/lib/auth/enrollment.js +367 -367
- package/lib/auth/index.js +57 -57
- package/lib/auth/jwt.js +731 -731
- package/lib/auth/oauth.js +362 -362
- package/lib/auth/session.js +588 -588
- package/lib/auth/trustedDevice.js +409 -409
- package/lib/auth/twoFactor.js +1150 -1150
- package/lib/auth/webauthn.js +946 -946
- package/lib/body/index.js +14 -14
- package/lib/body/json.js +109 -109
- package/lib/body/multipart.js +440 -440
- package/lib/body/raw.js +71 -71
- package/lib/body/rawBuffer.js +160 -160
- package/lib/body/sendError.js +25 -25
- package/lib/body/text.js +75 -75
- package/lib/body/typeMatch.js +41 -41
- package/lib/body/urlencoded.js +235 -235
- package/lib/cli.js +845 -845
- package/lib/cluster.js +666 -666
- package/lib/debug.js +372 -372
- package/lib/env/index.js +465 -465
- package/lib/errors.js +683 -683
- package/lib/fetch/index.js +256 -256
- package/lib/grpc/balancer.js +378 -378
- package/lib/grpc/call.js +708 -708
- package/lib/grpc/client.js +764 -764
- package/lib/grpc/codec.js +1221 -1221
- package/lib/grpc/credentials.js +398 -398
- package/lib/grpc/frame.js +262 -262
- package/lib/grpc/health.js +287 -287
- package/lib/grpc/index.js +121 -121
- package/lib/grpc/metadata.js +461 -461
- package/lib/grpc/proto.js +821 -821
- package/lib/grpc/reflection.js +590 -590
- package/lib/grpc/server.js +445 -445
- package/lib/grpc/status.js +118 -118
- package/lib/grpc/watch.js +173 -173
- package/lib/http/index.js +10 -10
- package/lib/http/request.js +727 -727
- package/lib/http/response.js +799 -799
- package/lib/lifecycle.js +557 -557
- package/lib/middleware/compress.js +230 -230
- package/lib/middleware/cookieParser.js +237 -237
- package/lib/middleware/cors.js +93 -93
- package/lib/middleware/csrf.js +137 -137
- package/lib/middleware/errorHandler.js +101 -101
- package/lib/middleware/helmet.js +175 -175
- package/lib/middleware/index.js +19 -17
- package/lib/middleware/logger.js +74 -74
- package/lib/middleware/rateLimit.js +88 -88
- package/lib/middleware/requestId.js +53 -53
- package/lib/middleware/static.js +326 -326
- package/lib/middleware/timeout.js +71 -71
- package/lib/middleware/validator.js +255 -255
- package/lib/observe/health.js +326 -326
- package/lib/observe/index.js +50 -50
- package/lib/observe/logger.js +359 -359
- package/lib/observe/metrics.js +805 -805
- package/lib/observe/tracing.js +592 -592
- package/lib/orm/adapters/json.js +290 -290
- package/lib/orm/adapters/memory.js +764 -764
- package/lib/orm/adapters/mongo.js +764 -764
- package/lib/orm/adapters/mysql.js +933 -933
- package/lib/orm/adapters/postgres.js +1144 -1144
- package/lib/orm/adapters/redis.js +1534 -1534
- package/lib/orm/adapters/sql-base.js +212 -212
- package/lib/orm/adapters/sqlite.js +858 -858
- package/lib/orm/audit.js +649 -649
- package/lib/orm/cache.js +394 -394
- package/lib/orm/geo.js +387 -387
- package/lib/orm/index.js +784 -784
- package/lib/orm/migrate.js +432 -432
- package/lib/orm/model.js +1706 -1706
- package/lib/orm/plugin.js +375 -375
- package/lib/orm/procedures.js +836 -836
- package/lib/orm/profiler.js +233 -233
- package/lib/orm/query.js +1772 -1772
- package/lib/orm/replicas.js +241 -241
- package/lib/orm/schema.js +307 -307
- package/lib/orm/search.js +380 -380
- package/lib/orm/seed/data/commerce.js +136 -136
- package/lib/orm/seed/data/internet.js +111 -111
- package/lib/orm/seed/data/locations.js +204 -204
- package/lib/orm/seed/data/names.js +338 -338
- package/lib/orm/seed/data/person.js +128 -128
- package/lib/orm/seed/data/phone.js +211 -211
- package/lib/orm/seed/data/words.js +134 -134
- package/lib/orm/seed/factory.js +178 -178
- package/lib/orm/seed/fake.js +1186 -1186
- package/lib/orm/seed/index.js +18 -18
- package/lib/orm/seed/rng.js +70 -70
- package/lib/orm/seed/seeder.js +124 -124
- package/lib/orm/seed/unique.js +68 -68
- package/lib/orm/snapshot.js +366 -366
- package/lib/orm/tenancy.js +605 -605
- package/lib/orm/views.js +350 -350
- package/lib/router/index.js +436 -436
- package/lib/sse/index.js +8 -8
- package/lib/sse/stream.js +349 -349
- package/lib/ws/connection.js +451 -451
- package/lib/ws/handshake.js +125 -125
- package/lib/ws/index.js +14 -14
- package/lib/ws/room.js +223 -223
- package/package.json +73 -73
- package/types/app.d.ts +223 -223
- package/types/auth.d.ts +520 -520
- package/types/body.d.ts +14 -0
- package/types/cli.d.ts +2 -0
- package/types/cluster.d.ts +75 -75
- package/types/env.d.ts +80 -80
- package/types/errors.d.ts +316 -316
- package/types/fetch.d.ts +43 -43
- package/types/grpc.d.ts +432 -432
- package/types/index.d.ts +384 -384
- package/types/lifecycle.d.ts +60 -60
- package/types/middleware.d.ts +320 -320
- package/types/observe.d.ts +304 -304
- package/types/orm.d.ts +1887 -1887
- package/types/request.d.ts +109 -109
- package/types/response.d.ts +157 -157
- package/types/router.d.ts +78 -78
- package/types/sse.d.ts +78 -78
- package/types/websocket.d.ts +126 -126
package/lib/observe/health.js
CHANGED
|
@@ -1,326 +1,326 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @module observe/health
|
|
3
|
-
* @description Health check middleware with liveness and readiness probes.
|
|
4
|
-
* Kubernetes-compatible `/healthz` and `/readyz` endpoints with
|
|
5
|
-
* composable checks (database ping, memory, event loop lag,
|
|
6
|
-
* disk space) and custom check registration.
|
|
7
|
-
*
|
|
8
|
-
* Returns `200` when healthy, `503` when degraded or during
|
|
9
|
-
* shutdown drain phase, with a JSON body detailing each check.
|
|
10
|
-
*
|
|
11
|
-
* @example
|
|
12
|
-
* const { healthCheck } = require('@zero-server/sdk');
|
|
13
|
-
*
|
|
14
|
-
* app.get('/healthz', healthCheck());
|
|
15
|
-
* app.get('/readyz', healthCheck({
|
|
16
|
-
* checks: {
|
|
17
|
-
* database: () => db.ping(),
|
|
18
|
-
* cache: () => redis.ping(),
|
|
19
|
-
* },
|
|
20
|
-
* }));
|
|
21
|
-
*
|
|
22
|
-
* @example | Using the App Integration
|
|
23
|
-
* app.health('/healthz');
|
|
24
|
-
* app.ready('/readyz', {
|
|
25
|
-
* database: () => db.ping(),
|
|
26
|
-
* });
|
|
27
|
-
*/
|
|
28
|
-
const os = require('os');
|
|
29
|
-
|
|
30
|
-
// -- Built-in Checks -----------------------------------------------
|
|
31
|
-
|
|
32
|
-
/**
|
|
33
|
-
* Check memory usage against a threshold.
|
|
34
|
-
*
|
|
35
|
-
* @param {object} [opts] - Check options.
|
|
36
|
-
* @param {number} [opts.maxHeapUsedPercent=90] - Max heap usage percentage.
|
|
37
|
-
* @param {number} [opts.maxRssBytes] - Max RSS in bytes.
|
|
38
|
-
* @returns {Function} Check function.
|
|
39
|
-
*
|
|
40
|
-
* @example
|
|
41
|
-
* app.get('/healthz', healthCheck({
|
|
42
|
-
* checks: { memory: memoryCheck({ maxHeapUsedPercent: 85 }) },
|
|
43
|
-
* }));
|
|
44
|
-
*/
|
|
45
|
-
function memoryCheck(opts = {})
|
|
46
|
-
{
|
|
47
|
-
const maxPercent = typeof opts.maxHeapUsedPercent === 'number' ? opts.maxHeapUsedPercent : 90;
|
|
48
|
-
const maxRss = opts.maxRssBytes || Infinity;
|
|
49
|
-
|
|
50
|
-
return () =>
|
|
51
|
-
{
|
|
52
|
-
const mem = process.memoryUsage();
|
|
53
|
-
const heapPercent = (mem.heapUsed / mem.heapTotal) * 100;
|
|
54
|
-
const healthy = heapPercent < maxPercent && mem.rss < maxRss;
|
|
55
|
-
|
|
56
|
-
return {
|
|
57
|
-
healthy,
|
|
58
|
-
details: {
|
|
59
|
-
heapUsed: mem.heapUsed,
|
|
60
|
-
heapTotal: mem.heapTotal,
|
|
61
|
-
heapPercent: Math.round(heapPercent * 100) / 100,
|
|
62
|
-
rss: mem.rss,
|
|
63
|
-
external: mem.external,
|
|
64
|
-
},
|
|
65
|
-
};
|
|
66
|
-
};
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
/**
|
|
70
|
-
* Check event loop lag against a threshold.
|
|
71
|
-
*
|
|
72
|
-
* @param {object} [opts] - Check options.
|
|
73
|
-
* @param {number} [opts.maxLagMs=500] - Max acceptable lag in ms.
|
|
74
|
-
* @returns {Function} Check function.
|
|
75
|
-
*
|
|
76
|
-
* @example
|
|
77
|
-
* app.get('/healthz', healthCheck({
|
|
78
|
-
* checks: { eventLoop: eventLoopCheck({ maxLagMs: 200 }) },
|
|
79
|
-
* }));
|
|
80
|
-
*/
|
|
81
|
-
function eventLoopCheck(opts = {})
|
|
82
|
-
{
|
|
83
|
-
const maxLag = opts.maxLagMs || 500;
|
|
84
|
-
let _lastCheck = process.hrtime.bigint();
|
|
85
|
-
let _lag = 0;
|
|
86
|
-
|
|
87
|
-
// Sample event loop lag periodically
|
|
88
|
-
const _check = () =>
|
|
89
|
-
{
|
|
90
|
-
const now = process.hrtime.bigint();
|
|
91
|
-
const expected = 1_000_000_000n; // 1 second in nanoseconds
|
|
92
|
-
const actual = now - _lastCheck;
|
|
93
|
-
_lag = Math.max(0, Number(actual - expected) / 1e6); // ms
|
|
94
|
-
_lastCheck = now;
|
|
95
|
-
};
|
|
96
|
-
|
|
97
|
-
const timer = setInterval(_check, 1000);
|
|
98
|
-
if (timer.unref) timer.unref();
|
|
99
|
-
|
|
100
|
-
const check = () => ({
|
|
101
|
-
healthy: _lag < maxLag,
|
|
102
|
-
details: { lagMs: Math.round(_lag * 100) / 100, maxLagMs: maxLag },
|
|
103
|
-
});
|
|
104
|
-
|
|
105
|
-
// Expose cleanup for testing
|
|
106
|
-
check._cleanup = () => clearInterval(timer);
|
|
107
|
-
return check;
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
/**
|
|
111
|
-
* Check available disk space (simple heuristic using os.freemem).
|
|
112
|
-
*
|
|
113
|
-
* @param {object} [opts] - Check options.
|
|
114
|
-
* @param {number} [opts.minFreeBytes=104857600] - Minimum free memory in bytes (default: 100MB).
|
|
115
|
-
* @returns {Function} Check function.
|
|
116
|
-
*/
|
|
117
|
-
function diskSpaceCheck(opts = {})
|
|
118
|
-
{
|
|
119
|
-
const minFree = opts.minFreeBytes || 104857600; // 100MB
|
|
120
|
-
|
|
121
|
-
return () =>
|
|
122
|
-
{
|
|
123
|
-
const free = os.freemem();
|
|
124
|
-
return {
|
|
125
|
-
healthy: free > minFree,
|
|
126
|
-
details: {
|
|
127
|
-
freeMemory: free,
|
|
128
|
-
totalMemory: os.totalmem(),
|
|
129
|
-
minRequired: minFree,
|
|
130
|
-
},
|
|
131
|
-
};
|
|
132
|
-
};
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
// -- Health Check Handler ------------------------------------------
|
|
136
|
-
|
|
137
|
-
/**
|
|
138
|
-
* Create a health check route handler.
|
|
139
|
-
*
|
|
140
|
-
* Returns a JSON response with the status of all registered checks.
|
|
141
|
-
* Returns `200` when all checks pass, `503` when any check fails
|
|
142
|
-
* or when the application is in drain/shutdown state.
|
|
143
|
-
*
|
|
144
|
-
* Response format:
|
|
145
|
-
* ```json
|
|
146
|
-
* {
|
|
147
|
-
* "status": "healthy",
|
|
148
|
-
* "uptime": 12345,
|
|
149
|
-
* "timestamp": "2026-01-01T00:00:00.000Z",
|
|
150
|
-
* "checks": {
|
|
151
|
-
* "database": { "healthy": true, "duration": 5, "details": {} }
|
|
152
|
-
* }
|
|
153
|
-
* }
|
|
154
|
-
* ```
|
|
155
|
-
*
|
|
156
|
-
* @param {object} [opts] - Options.
|
|
157
|
-
* @param {Object<string, Function>} [opts.checks] - Named check functions. Each returns `{ healthy, details }` or a boolean/Promise.
|
|
158
|
-
* @param {number} [opts.timeout=5000] - Max time to wait for all checks in ms.
|
|
159
|
-
* @param {boolean} [opts.verbose=true] - Include check details in response.
|
|
160
|
-
* @param {Function} [opts.onFailure] - `(results) => void` — called when any check fails.
|
|
161
|
-
* @returns {Function} Route handler `(req, res) => void`.
|
|
162
|
-
*
|
|
163
|
-
* @example
|
|
164
|
-
* app.get('/healthz', healthCheck());
|
|
165
|
-
*
|
|
166
|
-
* @example
|
|
167
|
-
* app.get('/readyz', healthCheck({
|
|
168
|
-
* checks: {
|
|
169
|
-
* database: async () => {
|
|
170
|
-
* await db.ping();
|
|
171
|
-
* return { healthy: true };
|
|
172
|
-
* },
|
|
173
|
-
* cache: () => ({ healthy: cacheClient.isConnected }),
|
|
174
|
-
* },
|
|
175
|
-
* }));
|
|
176
|
-
*
|
|
177
|
-
* @example | Auto-deregister from Load Balancer
|
|
178
|
-
* app.get('/readyz', healthCheck({
|
|
179
|
-
* checks: {
|
|
180
|
-
* lifecycle: () => ({ healthy: app.lifecycleState === 'running' }),
|
|
181
|
-
* },
|
|
182
|
-
* }));
|
|
183
|
-
*/
|
|
184
|
-
function healthCheck(opts = {})
|
|
185
|
-
{
|
|
186
|
-
const checks = opts.checks || {};
|
|
187
|
-
const timeout = opts.timeout || 5000;
|
|
188
|
-
const verbose = opts.verbose !== false;
|
|
189
|
-
const onFailure = typeof opts.onFailure === 'function' ? opts.onFailure : null;
|
|
190
|
-
|
|
191
|
-
return async (req, res) =>
|
|
192
|
-
{
|
|
193
|
-
const start = Date.now();
|
|
194
|
-
|
|
195
|
-
// Check lifecycle state (auto-deregister during shutdown)
|
|
196
|
-
const app = req.app;
|
|
197
|
-
if (app && app.lifecycleState && app.lifecycleState !== 'running')
|
|
198
|
-
{
|
|
199
|
-
res.status(503).json({
|
|
200
|
-
status: 'unavailable',
|
|
201
|
-
reason: 'shutdown',
|
|
202
|
-
lifecycleState: app.lifecycleState,
|
|
203
|
-
timestamp: new Date().toISOString(),
|
|
204
|
-
});
|
|
205
|
-
return;
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
const checkNames = Object.keys(checks);
|
|
209
|
-
const results = {};
|
|
210
|
-
let allHealthy = true;
|
|
211
|
-
|
|
212
|
-
if (checkNames.length > 0)
|
|
213
|
-
{
|
|
214
|
-
// Run all checks concurrently with timeout
|
|
215
|
-
const promises = checkNames.map(async (name) =>
|
|
216
|
-
{
|
|
217
|
-
const checkStart = Date.now();
|
|
218
|
-
try
|
|
219
|
-
{
|
|
220
|
-
const result = await Promise.race([
|
|
221
|
-
Promise.resolve(checks[name]()),
|
|
222
|
-
new Promise((_, reject) =>
|
|
223
|
-
setTimeout(() => reject(new Error('Check timed out')), timeout)
|
|
224
|
-
),
|
|
225
|
-
]);
|
|
226
|
-
|
|
227
|
-
const duration = Date.now() - checkStart;
|
|
228
|
-
|
|
229
|
-
if (typeof result === 'boolean')
|
|
230
|
-
{
|
|
231
|
-
results[name] = { healthy: result, duration };
|
|
232
|
-
}
|
|
233
|
-
else if (result && typeof result === 'object')
|
|
234
|
-
{
|
|
235
|
-
results[name] = { healthy: !!result.healthy, duration };
|
|
236
|
-
if (verbose && result.details) results[name].details = result.details;
|
|
237
|
-
}
|
|
238
|
-
else
|
|
239
|
-
{
|
|
240
|
-
results[name] = { healthy: true, duration };
|
|
241
|
-
}
|
|
242
|
-
}
|
|
243
|
-
catch (err)
|
|
244
|
-
{
|
|
245
|
-
results[name] = {
|
|
246
|
-
healthy: false,
|
|
247
|
-
duration: Date.now() - checkStart,
|
|
248
|
-
error: err.message,
|
|
249
|
-
};
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
if (!results[name].healthy) allHealthy = false;
|
|
253
|
-
});
|
|
254
|
-
|
|
255
|
-
await Promise.all(promises);
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
const body = {
|
|
259
|
-
status: allHealthy ? 'healthy' : 'unhealthy',
|
|
260
|
-
uptime: process.uptime(),
|
|
261
|
-
timestamp: new Date().toISOString(),
|
|
262
|
-
duration: Date.now() - start,
|
|
263
|
-
};
|
|
264
|
-
|
|
265
|
-
if (checkNames.length > 0) body.checks = results;
|
|
266
|
-
|
|
267
|
-
if (!allHealthy && onFailure)
|
|
268
|
-
{
|
|
269
|
-
try { onFailure(results); }
|
|
270
|
-
catch (_) { /* ignore callback errors */ }
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
res.status(allHealthy ? 200 : 503).json(body);
|
|
274
|
-
};
|
|
275
|
-
}
|
|
276
|
-
|
|
277
|
-
// -- Convenience Health & Ready Factory ----------------------------
|
|
278
|
-
|
|
279
|
-
/**
|
|
280
|
-
* Create paired liveness and readiness handlers for an app.
|
|
281
|
-
* Liveness includes basic process checks; readiness includes
|
|
282
|
-
* all registered dependency checks.
|
|
283
|
-
*
|
|
284
|
-
* @param {object} [opts] - Options.
|
|
285
|
-
* @param {Object<string, Function>} [opts.checks] - Named readiness checks.
|
|
286
|
-
* @param {boolean} [opts.includeMemory=false] - Include memory check in liveness.
|
|
287
|
-
* @param {boolean} [opts.includeEventLoop=false] - Include event loop lag check.
|
|
288
|
-
* @param {number} [opts.timeout=5000] - Check timeout.
|
|
289
|
-
* @returns {{ health: Function, ready: Function }} Route handlers.
|
|
290
|
-
*
|
|
291
|
-
* @example
|
|
292
|
-
* const { health, ready } = createHealthHandlers({
|
|
293
|
-
* checks: { database: () => db.ping() },
|
|
294
|
-
* includeMemory: true,
|
|
295
|
-
* });
|
|
296
|
-
* app.get('/healthz', health);
|
|
297
|
-
* app.get('/readyz', ready);
|
|
298
|
-
*/
|
|
299
|
-
function createHealthHandlers(opts = {})
|
|
300
|
-
{
|
|
301
|
-
const livenessChecks = {};
|
|
302
|
-
if (opts.includeMemory) livenessChecks.memory = memoryCheck(opts.memoryOpts);
|
|
303
|
-
if (opts.includeEventLoop) livenessChecks.eventLoop = eventLoopCheck(opts.eventLoopOpts);
|
|
304
|
-
|
|
305
|
-
const readinessChecks = { ...livenessChecks };
|
|
306
|
-
if (opts.checks)
|
|
307
|
-
{
|
|
308
|
-
for (const [name, fn] of Object.entries(opts.checks))
|
|
309
|
-
{
|
|
310
|
-
readinessChecks[name] = fn;
|
|
311
|
-
}
|
|
312
|
-
}
|
|
313
|
-
|
|
314
|
-
return {
|
|
315
|
-
health: healthCheck({ checks: livenessChecks, timeout: opts.timeout }),
|
|
316
|
-
ready: healthCheck({ checks: readinessChecks, timeout: opts.timeout, onFailure: opts.onFailure }),
|
|
317
|
-
};
|
|
318
|
-
}
|
|
319
|
-
|
|
320
|
-
module.exports = {
|
|
321
|
-
healthCheck,
|
|
322
|
-
createHealthHandlers,
|
|
323
|
-
memoryCheck,
|
|
324
|
-
eventLoopCheck,
|
|
325
|
-
diskSpaceCheck,
|
|
326
|
-
};
|
|
1
|
+
/**
|
|
2
|
+
* @module observe/health
|
|
3
|
+
* @description Health check middleware with liveness and readiness probes.
|
|
4
|
+
* Kubernetes-compatible `/healthz` and `/readyz` endpoints with
|
|
5
|
+
* composable checks (database ping, memory, event loop lag,
|
|
6
|
+
* disk space) and custom check registration.
|
|
7
|
+
*
|
|
8
|
+
* Returns `200` when healthy, `503` when degraded or during
|
|
9
|
+
* shutdown drain phase, with a JSON body detailing each check.
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* const { healthCheck } = require('@zero-server/sdk');
|
|
13
|
+
*
|
|
14
|
+
* app.get('/healthz', healthCheck());
|
|
15
|
+
* app.get('/readyz', healthCheck({
|
|
16
|
+
* checks: {
|
|
17
|
+
* database: () => db.ping(),
|
|
18
|
+
* cache: () => redis.ping(),
|
|
19
|
+
* },
|
|
20
|
+
* }));
|
|
21
|
+
*
|
|
22
|
+
* @example | Using the App Integration
|
|
23
|
+
* app.health('/healthz');
|
|
24
|
+
* app.ready('/readyz', {
|
|
25
|
+
* database: () => db.ping(),
|
|
26
|
+
* });
|
|
27
|
+
*/
|
|
28
|
+
const os = require('os');
|
|
29
|
+
|
|
30
|
+
// -- Built-in Checks -----------------------------------------------
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Check memory usage against a threshold.
|
|
34
|
+
*
|
|
35
|
+
* @param {object} [opts] - Check options.
|
|
36
|
+
* @param {number} [opts.maxHeapUsedPercent=90] - Max heap usage percentage.
|
|
37
|
+
* @param {number} [opts.maxRssBytes] - Max RSS in bytes.
|
|
38
|
+
* @returns {Function} Check function.
|
|
39
|
+
*
|
|
40
|
+
* @example
|
|
41
|
+
* app.get('/healthz', healthCheck({
|
|
42
|
+
* checks: { memory: memoryCheck({ maxHeapUsedPercent: 85 }) },
|
|
43
|
+
* }));
|
|
44
|
+
*/
|
|
45
|
+
function memoryCheck(opts = {})
|
|
46
|
+
{
|
|
47
|
+
const maxPercent = typeof opts.maxHeapUsedPercent === 'number' ? opts.maxHeapUsedPercent : 90;
|
|
48
|
+
const maxRss = opts.maxRssBytes || Infinity;
|
|
49
|
+
|
|
50
|
+
return () =>
|
|
51
|
+
{
|
|
52
|
+
const mem = process.memoryUsage();
|
|
53
|
+
const heapPercent = (mem.heapUsed / mem.heapTotal) * 100;
|
|
54
|
+
const healthy = heapPercent < maxPercent && mem.rss < maxRss;
|
|
55
|
+
|
|
56
|
+
return {
|
|
57
|
+
healthy,
|
|
58
|
+
details: {
|
|
59
|
+
heapUsed: mem.heapUsed,
|
|
60
|
+
heapTotal: mem.heapTotal,
|
|
61
|
+
heapPercent: Math.round(heapPercent * 100) / 100,
|
|
62
|
+
rss: mem.rss,
|
|
63
|
+
external: mem.external,
|
|
64
|
+
},
|
|
65
|
+
};
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Check event loop lag against a threshold.
|
|
71
|
+
*
|
|
72
|
+
* @param {object} [opts] - Check options.
|
|
73
|
+
* @param {number} [opts.maxLagMs=500] - Max acceptable lag in ms.
|
|
74
|
+
* @returns {Function} Check function.
|
|
75
|
+
*
|
|
76
|
+
* @example
|
|
77
|
+
* app.get('/healthz', healthCheck({
|
|
78
|
+
* checks: { eventLoop: eventLoopCheck({ maxLagMs: 200 }) },
|
|
79
|
+
* }));
|
|
80
|
+
*/
|
|
81
|
+
function eventLoopCheck(opts = {})
|
|
82
|
+
{
|
|
83
|
+
const maxLag = opts.maxLagMs || 500;
|
|
84
|
+
let _lastCheck = process.hrtime.bigint();
|
|
85
|
+
let _lag = 0;
|
|
86
|
+
|
|
87
|
+
// Sample event loop lag periodically
|
|
88
|
+
const _check = () =>
|
|
89
|
+
{
|
|
90
|
+
const now = process.hrtime.bigint();
|
|
91
|
+
const expected = 1_000_000_000n; // 1 second in nanoseconds
|
|
92
|
+
const actual = now - _lastCheck;
|
|
93
|
+
_lag = Math.max(0, Number(actual - expected) / 1e6); // ms
|
|
94
|
+
_lastCheck = now;
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
const timer = setInterval(_check, 1000);
|
|
98
|
+
if (timer.unref) timer.unref();
|
|
99
|
+
|
|
100
|
+
const check = () => ({
|
|
101
|
+
healthy: _lag < maxLag,
|
|
102
|
+
details: { lagMs: Math.round(_lag * 100) / 100, maxLagMs: maxLag },
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
// Expose cleanup for testing
|
|
106
|
+
check._cleanup = () => clearInterval(timer);
|
|
107
|
+
return check;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Check available disk space (simple heuristic using os.freemem).
|
|
112
|
+
*
|
|
113
|
+
* @param {object} [opts] - Check options.
|
|
114
|
+
* @param {number} [opts.minFreeBytes=104857600] - Minimum free memory in bytes (default: 100MB).
|
|
115
|
+
* @returns {Function} Check function.
|
|
116
|
+
*/
|
|
117
|
+
function diskSpaceCheck(opts = {})
|
|
118
|
+
{
|
|
119
|
+
const minFree = opts.minFreeBytes || 104857600; // 100MB
|
|
120
|
+
|
|
121
|
+
return () =>
|
|
122
|
+
{
|
|
123
|
+
const free = os.freemem();
|
|
124
|
+
return {
|
|
125
|
+
healthy: free > minFree,
|
|
126
|
+
details: {
|
|
127
|
+
freeMemory: free,
|
|
128
|
+
totalMemory: os.totalmem(),
|
|
129
|
+
minRequired: minFree,
|
|
130
|
+
},
|
|
131
|
+
};
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// -- Health Check Handler ------------------------------------------
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Create a health check route handler.
|
|
139
|
+
*
|
|
140
|
+
* Returns a JSON response with the status of all registered checks.
|
|
141
|
+
* Returns `200` when all checks pass, `503` when any check fails
|
|
142
|
+
* or when the application is in drain/shutdown state.
|
|
143
|
+
*
|
|
144
|
+
* Response format:
|
|
145
|
+
* ```json
|
|
146
|
+
* {
|
|
147
|
+
* "status": "healthy",
|
|
148
|
+
* "uptime": 12345,
|
|
149
|
+
* "timestamp": "2026-01-01T00:00:00.000Z",
|
|
150
|
+
* "checks": {
|
|
151
|
+
* "database": { "healthy": true, "duration": 5, "details": {} }
|
|
152
|
+
* }
|
|
153
|
+
* }
|
|
154
|
+
* ```
|
|
155
|
+
*
|
|
156
|
+
* @param {object} [opts] - Options.
|
|
157
|
+
* @param {Object<string, Function>} [opts.checks] - Named check functions. Each returns `{ healthy, details }` or a boolean/Promise.
|
|
158
|
+
* @param {number} [opts.timeout=5000] - Max time to wait for all checks in ms.
|
|
159
|
+
* @param {boolean} [opts.verbose=true] - Include check details in response.
|
|
160
|
+
* @param {Function} [opts.onFailure] - `(results) => void` — called when any check fails.
|
|
161
|
+
* @returns {Function} Route handler `(req, res) => void`.
|
|
162
|
+
*
|
|
163
|
+
* @example
|
|
164
|
+
* app.get('/healthz', healthCheck());
|
|
165
|
+
*
|
|
166
|
+
* @example
|
|
167
|
+
* app.get('/readyz', healthCheck({
|
|
168
|
+
* checks: {
|
|
169
|
+
* database: async () => {
|
|
170
|
+
* await db.ping();
|
|
171
|
+
* return { healthy: true };
|
|
172
|
+
* },
|
|
173
|
+
* cache: () => ({ healthy: cacheClient.isConnected }),
|
|
174
|
+
* },
|
|
175
|
+
* }));
|
|
176
|
+
*
|
|
177
|
+
* @example | Auto-deregister from Load Balancer
|
|
178
|
+
* app.get('/readyz', healthCheck({
|
|
179
|
+
* checks: {
|
|
180
|
+
* lifecycle: () => ({ healthy: app.lifecycleState === 'running' }),
|
|
181
|
+
* },
|
|
182
|
+
* }));
|
|
183
|
+
*/
|
|
184
|
+
function healthCheck(opts = {})
|
|
185
|
+
{
|
|
186
|
+
const checks = opts.checks || {};
|
|
187
|
+
const timeout = opts.timeout || 5000;
|
|
188
|
+
const verbose = opts.verbose !== false;
|
|
189
|
+
const onFailure = typeof opts.onFailure === 'function' ? opts.onFailure : null;
|
|
190
|
+
|
|
191
|
+
return async (req, res) =>
|
|
192
|
+
{
|
|
193
|
+
const start = Date.now();
|
|
194
|
+
|
|
195
|
+
// Check lifecycle state (auto-deregister during shutdown)
|
|
196
|
+
const app = req.app;
|
|
197
|
+
if (app && app.lifecycleState && app.lifecycleState !== 'running')
|
|
198
|
+
{
|
|
199
|
+
res.status(503).json({
|
|
200
|
+
status: 'unavailable',
|
|
201
|
+
reason: 'shutdown',
|
|
202
|
+
lifecycleState: app.lifecycleState,
|
|
203
|
+
timestamp: new Date().toISOString(),
|
|
204
|
+
});
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
const checkNames = Object.keys(checks);
|
|
209
|
+
const results = {};
|
|
210
|
+
let allHealthy = true;
|
|
211
|
+
|
|
212
|
+
if (checkNames.length > 0)
|
|
213
|
+
{
|
|
214
|
+
// Run all checks concurrently with timeout
|
|
215
|
+
const promises = checkNames.map(async (name) =>
|
|
216
|
+
{
|
|
217
|
+
const checkStart = Date.now();
|
|
218
|
+
try
|
|
219
|
+
{
|
|
220
|
+
const result = await Promise.race([
|
|
221
|
+
Promise.resolve(checks[name]()),
|
|
222
|
+
new Promise((_, reject) =>
|
|
223
|
+
setTimeout(() => reject(new Error('Check timed out')), timeout)
|
|
224
|
+
),
|
|
225
|
+
]);
|
|
226
|
+
|
|
227
|
+
const duration = Date.now() - checkStart;
|
|
228
|
+
|
|
229
|
+
if (typeof result === 'boolean')
|
|
230
|
+
{
|
|
231
|
+
results[name] = { healthy: result, duration };
|
|
232
|
+
}
|
|
233
|
+
else if (result && typeof result === 'object')
|
|
234
|
+
{
|
|
235
|
+
results[name] = { healthy: !!result.healthy, duration };
|
|
236
|
+
if (verbose && result.details) results[name].details = result.details;
|
|
237
|
+
}
|
|
238
|
+
else
|
|
239
|
+
{
|
|
240
|
+
results[name] = { healthy: true, duration };
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
catch (err)
|
|
244
|
+
{
|
|
245
|
+
results[name] = {
|
|
246
|
+
healthy: false,
|
|
247
|
+
duration: Date.now() - checkStart,
|
|
248
|
+
error: err.message,
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
if (!results[name].healthy) allHealthy = false;
|
|
253
|
+
});
|
|
254
|
+
|
|
255
|
+
await Promise.all(promises);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
const body = {
|
|
259
|
+
status: allHealthy ? 'healthy' : 'unhealthy',
|
|
260
|
+
uptime: process.uptime(),
|
|
261
|
+
timestamp: new Date().toISOString(),
|
|
262
|
+
duration: Date.now() - start,
|
|
263
|
+
};
|
|
264
|
+
|
|
265
|
+
if (checkNames.length > 0) body.checks = results;
|
|
266
|
+
|
|
267
|
+
if (!allHealthy && onFailure)
|
|
268
|
+
{
|
|
269
|
+
try { onFailure(results); }
|
|
270
|
+
catch (_) { /* ignore callback errors */ }
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
res.status(allHealthy ? 200 : 503).json(body);
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
// -- Convenience Health & Ready Factory ----------------------------
|
|
278
|
+
|
|
279
|
+
/**
|
|
280
|
+
* Create paired liveness and readiness handlers for an app.
|
|
281
|
+
* Liveness includes basic process checks; readiness includes
|
|
282
|
+
* all registered dependency checks.
|
|
283
|
+
*
|
|
284
|
+
* @param {object} [opts] - Options.
|
|
285
|
+
* @param {Object<string, Function>} [opts.checks] - Named readiness checks.
|
|
286
|
+
* @param {boolean} [opts.includeMemory=false] - Include memory check in liveness.
|
|
287
|
+
* @param {boolean} [opts.includeEventLoop=false] - Include event loop lag check.
|
|
288
|
+
* @param {number} [opts.timeout=5000] - Check timeout.
|
|
289
|
+
* @returns {{ health: Function, ready: Function }} Route handlers.
|
|
290
|
+
*
|
|
291
|
+
* @example
|
|
292
|
+
* const { health, ready } = createHealthHandlers({
|
|
293
|
+
* checks: { database: () => db.ping() },
|
|
294
|
+
* includeMemory: true,
|
|
295
|
+
* });
|
|
296
|
+
* app.get('/healthz', health);
|
|
297
|
+
* app.get('/readyz', ready);
|
|
298
|
+
*/
|
|
299
|
+
function createHealthHandlers(opts = {})
|
|
300
|
+
{
|
|
301
|
+
const livenessChecks = {};
|
|
302
|
+
if (opts.includeMemory) livenessChecks.memory = memoryCheck(opts.memoryOpts);
|
|
303
|
+
if (opts.includeEventLoop) livenessChecks.eventLoop = eventLoopCheck(opts.eventLoopOpts);
|
|
304
|
+
|
|
305
|
+
const readinessChecks = { ...livenessChecks };
|
|
306
|
+
if (opts.checks)
|
|
307
|
+
{
|
|
308
|
+
for (const [name, fn] of Object.entries(opts.checks))
|
|
309
|
+
{
|
|
310
|
+
readinessChecks[name] = fn;
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
return {
|
|
315
|
+
health: healthCheck({ checks: livenessChecks, timeout: opts.timeout }),
|
|
316
|
+
ready: healthCheck({ checks: readinessChecks, timeout: opts.timeout, onFailure: opts.onFailure }),
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
module.exports = {
|
|
321
|
+
healthCheck,
|
|
322
|
+
createHealthHandlers,
|
|
323
|
+
memoryCheck,
|
|
324
|
+
eventLoopCheck,
|
|
325
|
+
diskSpaceCheck,
|
|
326
|
+
};
|