@adalo/metrics 0.1.122 → 0.1.124
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/lib/health/healthCheckCache.d.ts +57 -0
- package/lib/health/healthCheckCache.d.ts.map +1 -0
- package/lib/health/healthCheckCache.js +200 -0
- package/lib/health/healthCheckCache.js.map +1 -0
- package/lib/{healthCheckClient.d.ts → health/healthCheckClient.d.ts} +59 -15
- package/lib/health/healthCheckClient.d.ts.map +1 -0
- package/lib/{healthCheckClient.js → health/healthCheckClient.js} +232 -49
- package/lib/health/healthCheckClient.js.map +1 -0
- package/lib/health/healthCheckUtils.d.ts +54 -0
- package/lib/health/healthCheckUtils.d.ts.map +1 -0
- package/lib/health/healthCheckUtils.js +142 -0
- package/lib/health/healthCheckUtils.js.map +1 -0
- package/lib/health/healthCheckWorker.d.ts +2 -0
- package/lib/health/healthCheckWorker.d.ts.map +1 -0
- package/lib/health/healthCheckWorker.js +64 -0
- package/lib/health/healthCheckWorker.js.map +1 -0
- package/lib/index.d.ts +8 -6
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +28 -6
- package/lib/index.js.map +1 -1
- package/lib/metrics/baseMetricsClient.d.ts.map +1 -0
- package/lib/metrics/baseMetricsClient.js.map +1 -0
- package/lib/metrics/metricsClient.d.ts.map +1 -0
- package/lib/metrics/metricsClient.js.map +1 -0
- package/lib/metrics/metricsDatabaseClient.d.ts.map +1 -0
- package/lib/metrics/metricsDatabaseClient.js.map +1 -0
- package/lib/metrics/metricsQueueRedisClient.d.ts.map +1 -0
- package/lib/{metricsQueueRedisClient.js → metrics/metricsQueueRedisClient.js} +2 -2
- package/lib/metrics/metricsQueueRedisClient.js.map +1 -0
- package/lib/metrics/metricsRedisClient.d.ts.map +1 -0
- package/lib/{metricsRedisClient.js → metrics/metricsRedisClient.js} +1 -1
- package/lib/metrics/metricsRedisClient.js.map +1 -0
- package/package.json +1 -1
- package/src/health/healthCheckCache.js +237 -0
- package/src/{healthCheckClient.js → health/healthCheckClient.js} +226 -49
- package/src/health/healthCheckUtils.js +143 -0
- package/src/health/healthCheckWorker.js +61 -0
- package/src/index.ts +8 -6
- package/src/{metricsQueueRedisClient.js → metrics/metricsQueueRedisClient.js} +2 -2
- package/src/{metricsRedisClient.js → metrics/metricsRedisClient.js} +1 -1
- package/lib/baseMetricsClient.d.ts.map +0 -1
- package/lib/baseMetricsClient.js.map +0 -1
- package/lib/healthCheckClient.d.ts.map +0 -1
- package/lib/healthCheckClient.js.map +0 -1
- package/lib/metricsClient.d.ts.map +0 -1
- package/lib/metricsClient.js.map +0 -1
- package/lib/metricsDatabaseClient.d.ts.map +0 -1
- package/lib/metricsDatabaseClient.js.map +0 -1
- package/lib/metricsQueueRedisClient.d.ts.map +0 -1
- package/lib/metricsQueueRedisClient.js.map +0 -1
- package/lib/metricsRedisClient.d.ts.map +0 -1
- package/lib/metricsRedisClient.js.map +0 -1
- /package/lib/{baseMetricsClient.d.ts → metrics/baseMetricsClient.d.ts} +0 -0
- /package/lib/{baseMetricsClient.js → metrics/baseMetricsClient.js} +0 -0
- /package/lib/{metricsClient.d.ts → metrics/metricsClient.d.ts} +0 -0
- /package/lib/{metricsClient.js → metrics/metricsClient.js} +0 -0
- /package/lib/{metricsDatabaseClient.d.ts → metrics/metricsDatabaseClient.d.ts} +0 -0
- /package/lib/{metricsDatabaseClient.js → metrics/metricsDatabaseClient.js} +0 -0
- /package/lib/{metricsQueueRedisClient.d.ts → metrics/metricsQueueRedisClient.d.ts} +0 -0
- /package/lib/{metricsRedisClient.d.ts → metrics/metricsRedisClient.d.ts} +0 -0
- /package/src/{baseMetricsClient.js → metrics/baseMetricsClient.js} +0 -0
- /package/src/{metricsClient.js → metrics/metricsClient.js} +0 -0
- /package/src/{metricsDatabaseClient.js → metrics/metricsDatabaseClient.js} +0 -0
|
@@ -8,7 +8,10 @@ const {
|
|
|
8
8
|
REDIS_V4,
|
|
9
9
|
IOREDIS,
|
|
10
10
|
REDIS_V3
|
|
11
|
-
} = require('
|
|
11
|
+
} = require('../redisUtils');
|
|
12
|
+
const {
|
|
13
|
+
HealthCheckCache
|
|
14
|
+
} = require('./healthCheckCache');
|
|
12
15
|
const HEALTH_CHECK_CACHE_TTL_MS = 60 * 1000;
|
|
13
16
|
|
|
14
17
|
/**
|
|
@@ -72,7 +75,8 @@ function maskSensitiveData(text) {
|
|
|
72
75
|
/**
|
|
73
76
|
* @typedef {Object} ComponentHealth
|
|
74
77
|
* @property {HealthStatus} status - Component health status
|
|
75
|
-
* @property {string} [
|
|
78
|
+
* @property {string} [error] - Error message if status is unhealthy
|
|
79
|
+
* @property {string} [message] - Optional status message (deprecated, use error)
|
|
76
80
|
* @property {number} [latencyMs] - Connection latency in milliseconds
|
|
77
81
|
*/
|
|
78
82
|
|
|
@@ -86,8 +90,8 @@ function maskSensitiveData(text) {
|
|
|
86
90
|
* @typedef {Object} HealthCheckResult
|
|
87
91
|
* @property {HealthStatus} status - Overall health status
|
|
88
92
|
* @property {string} timestamp - ISO timestamp of the check
|
|
89
|
-
* @property {
|
|
90
|
-
* @property {
|
|
93
|
+
* @property {Object<string, ComponentHealth | DatabaseClusterHealth>} checks - Individual service health checks
|
|
94
|
+
* @property {string[]} [errors] - Top-level error messages (not related to specific services)
|
|
91
95
|
*/
|
|
92
96
|
|
|
93
97
|
/**
|
|
@@ -120,12 +124,14 @@ class HealthCheckClient {
|
|
|
120
124
|
* @param {string} [options.databaseUrl] - Main PostgreSQL connection URL
|
|
121
125
|
* @param {string} [options.databaseName='main'] - Name for the main database
|
|
122
126
|
* @param {Object<string, string>} [options.additionalDatabaseUrls] - Additional DB clusters (name -> URL)
|
|
123
|
-
* @param {any} [options.redisClient] - Redis client instance (ioredis or node-redis)
|
|
127
|
+
* @param {any} [options.redisClient] - Redis client instance (ioredis or node-redis) - used for cache
|
|
128
|
+
* @param {boolean} [options.includeRedisCheck=false] - Include Redis health check in results (for backend)
|
|
124
129
|
* @param {number} [options.cacheTtlMs=60000] - Cache TTL in milliseconds (default: 60s)
|
|
125
130
|
* @param {string} [options.appName] - Application name for logging
|
|
126
131
|
*/
|
|
127
132
|
constructor(options = {}) {
|
|
128
133
|
this.redisClient = options.redisClient || null;
|
|
134
|
+
this.includeRedisCheck = options.includeRedisCheck || false;
|
|
129
135
|
this.cacheTtlMs = options.cacheTtlMs ?? HEALTH_CHECK_CACHE_TTL_MS;
|
|
130
136
|
this.appName = options.appName || process.env.BUILD_APP_NAME || 'unknown-app';
|
|
131
137
|
this.prefixLogs = `[${this.appName}] [HealthCheck]`;
|
|
@@ -133,15 +139,26 @@ class HealthCheckClient {
|
|
|
133
139
|
/** @type {CachedHealthResult | null} */
|
|
134
140
|
this._cachedResult = null;
|
|
135
141
|
|
|
142
|
+
/** @type {Promise<HealthCheckResult> | null} */
|
|
143
|
+
this._refreshPromise = null;
|
|
144
|
+
|
|
136
145
|
/** @type {Map<string, Pool>} */
|
|
137
146
|
this._databasePools = new Map();
|
|
138
147
|
|
|
148
|
+
/** @type {DatabaseConfig | null} */
|
|
149
|
+
this._mainDatabaseConfig = null;
|
|
150
|
+
|
|
139
151
|
/** @type {DatabaseConfig[]} */
|
|
140
|
-
this.
|
|
152
|
+
this._clusterConfigs = [];
|
|
141
153
|
this._initDatabases(options);
|
|
142
154
|
if (this.redisClient) {
|
|
143
155
|
this._redisClientType = getRedisClientType(this.redisClient);
|
|
144
156
|
}
|
|
157
|
+
this._cache = new HealthCheckCache({
|
|
158
|
+
redisClient: this.redisClient,
|
|
159
|
+
appName: this.appName,
|
|
160
|
+
cacheTtlMs: this.cacheTtlMs
|
|
161
|
+
});
|
|
145
162
|
}
|
|
146
163
|
|
|
147
164
|
/**
|
|
@@ -151,17 +168,17 @@ class HealthCheckClient {
|
|
|
151
168
|
*/
|
|
152
169
|
_initDatabases(options) {
|
|
153
170
|
const mainUrl = options.databaseUrl || process.env.DATABASE_URL || '';
|
|
154
|
-
const mainName = options.databaseName ||
|
|
171
|
+
const mainName = options.databaseName || `${this.appName}_db`;
|
|
155
172
|
if (mainUrl) {
|
|
156
|
-
this.
|
|
173
|
+
this._mainDatabaseConfig = {
|
|
157
174
|
name: mainName,
|
|
158
175
|
url: mainUrl
|
|
159
|
-
}
|
|
176
|
+
};
|
|
160
177
|
}
|
|
161
178
|
const additionalUrls = options.additionalDatabaseUrls || {};
|
|
162
179
|
for (const [name, url] of Object.entries(additionalUrls)) {
|
|
163
180
|
if (url) {
|
|
164
|
-
this.
|
|
181
|
+
this._clusterConfigs.push({
|
|
165
182
|
name,
|
|
166
183
|
url
|
|
167
184
|
});
|
|
@@ -215,43 +232,71 @@ class HealthCheckClient {
|
|
|
215
232
|
} catch (err) {
|
|
216
233
|
return {
|
|
217
234
|
status: 'unhealthy',
|
|
218
|
-
|
|
235
|
+
error: maskSensitiveData(err.message),
|
|
219
236
|
latencyMs: Date.now() - start
|
|
220
237
|
};
|
|
221
238
|
}
|
|
222
239
|
}
|
|
223
240
|
|
|
224
241
|
/**
|
|
225
|
-
* Tests all PostgreSQL
|
|
226
|
-
* @returns {Promise<
|
|
242
|
+
* Tests all PostgreSQL databases (main + clusters) in parallel.
|
|
243
|
+
* @returns {Promise<Object | null>} Database health with optional clusters
|
|
227
244
|
* @private
|
|
228
245
|
*/
|
|
229
246
|
async _checkAllDatabases() {
|
|
230
|
-
if (this.
|
|
247
|
+
if (!this._mainDatabaseConfig && this._clusterConfigs.length === 0) {
|
|
231
248
|
return null;
|
|
232
249
|
}
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
250
|
+
|
|
251
|
+
// Check main database
|
|
252
|
+
let mainHealth = null;
|
|
253
|
+
if (this._mainDatabaseConfig) {
|
|
254
|
+
mainHealth = await this._checkSingleDatabase(this._mainDatabaseConfig);
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// Check clusters in parallel
|
|
258
|
+
let clusters = null;
|
|
259
|
+
if (this._clusterConfigs.length > 0) {
|
|
260
|
+
const clusterResults = await Promise.all(this._clusterConfigs.map(async config => ({
|
|
261
|
+
name: config.name,
|
|
262
|
+
health: await this._checkSingleDatabase(config)
|
|
263
|
+
})));
|
|
264
|
+
clusters = {};
|
|
265
|
+
for (const {
|
|
266
|
+
name,
|
|
267
|
+
health
|
|
268
|
+
} of clusterResults) {
|
|
269
|
+
clusters[name] = health;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
// Calculate overall status
|
|
274
|
+
const allStatuses = [];
|
|
275
|
+
if (mainHealth) allStatuses.push(mainHealth.status);
|
|
276
|
+
if (clusters) {
|
|
277
|
+
allStatuses.push(...Object.values(clusters).map(c => c.status));
|
|
243
278
|
}
|
|
244
|
-
const statuses = Object.values(clusters).map(c => c.status);
|
|
245
279
|
let overallStatus = 'healthy';
|
|
246
|
-
if (
|
|
280
|
+
if (allStatuses.some(s => s === 'unhealthy')) {
|
|
247
281
|
overallStatus = 'unhealthy';
|
|
248
|
-
} else if (
|
|
282
|
+
} else if (allStatuses.some(s => s === 'degraded')) {
|
|
249
283
|
overallStatus = 'degraded';
|
|
250
284
|
}
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
285
|
+
|
|
286
|
+
// Build result
|
|
287
|
+
const result = {
|
|
288
|
+
status: overallStatus
|
|
254
289
|
};
|
|
290
|
+
if (mainHealth) {
|
|
291
|
+
result.latencyMs = mainHealth.latencyMs;
|
|
292
|
+
if (mainHealth.error) result.error = mainHealth.error;
|
|
293
|
+
// Keep message for backward compatibility
|
|
294
|
+
if (mainHealth.message) result.message = mainHealth.message;
|
|
295
|
+
}
|
|
296
|
+
if (clusters) {
|
|
297
|
+
result.clusters = clusters;
|
|
298
|
+
}
|
|
299
|
+
return result;
|
|
255
300
|
}
|
|
256
301
|
|
|
257
302
|
/**
|
|
@@ -306,21 +351,76 @@ class HealthCheckClient {
|
|
|
306
351
|
/**
|
|
307
352
|
* Performs a full health check on all configured components.
|
|
308
353
|
* Results are cached for the configured TTL to prevent excessive load.
|
|
354
|
+
* Uses a mutex pattern to prevent concurrent health checks when cache expires.
|
|
355
|
+
* If cache is expired but a refresh is in progress, returns stale cache (if available).
|
|
309
356
|
*
|
|
310
357
|
* @returns {Promise<HealthCheckResult>}
|
|
311
358
|
*/
|
|
312
359
|
async performHealthCheck() {
|
|
360
|
+
// If cache is valid, return immediately
|
|
313
361
|
if (this._isCacheValid()) {
|
|
314
362
|
return {
|
|
315
363
|
...this._cachedResult.result,
|
|
316
364
|
cached: true
|
|
317
365
|
};
|
|
318
366
|
}
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
if (
|
|
322
|
-
|
|
323
|
-
|
|
367
|
+
|
|
368
|
+
// If a refresh is already in progress, return stale cache (if available) or wait for refresh
|
|
369
|
+
if (this._refreshPromise) {
|
|
370
|
+
// Return stale cache immediately if available, otherwise wait for refresh
|
|
371
|
+
if (this._cachedResult) {
|
|
372
|
+
return {
|
|
373
|
+
...this._cachedResult.result,
|
|
374
|
+
cached: true
|
|
375
|
+
};
|
|
376
|
+
}
|
|
377
|
+
// Wait for the in-progress refresh
|
|
378
|
+
return this._refreshPromise;
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
// Start a new refresh
|
|
382
|
+
this._refreshPromise = this._performHealthCheckInternal().then(result => {
|
|
383
|
+
this._refreshPromise = null;
|
|
384
|
+
return result;
|
|
385
|
+
}).catch(err => {
|
|
386
|
+
this._refreshPromise = null;
|
|
387
|
+
throw err;
|
|
388
|
+
});
|
|
389
|
+
|
|
390
|
+
// Return stale cache if available while refresh is happening, otherwise wait
|
|
391
|
+
if (this._cachedResult) {
|
|
392
|
+
// Return stale cache immediately, refresh will happen in background
|
|
393
|
+
return {
|
|
394
|
+
...this._cachedResult.result,
|
|
395
|
+
cached: true
|
|
396
|
+
};
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
// No stale cache available, wait for refresh
|
|
400
|
+
return this._refreshPromise;
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/**
|
|
404
|
+
* Internal method that actually performs the health check.
|
|
405
|
+
* This is separated to allow the mutex pattern in performHealthCheck.
|
|
406
|
+
* Only checks database - Redis is used only for cache, not health check.
|
|
407
|
+
*
|
|
408
|
+
* @returns {Promise<HealthCheckResult>}
|
|
409
|
+
* @private
|
|
410
|
+
*/
|
|
411
|
+
async _performHealthCheckInternal() {
|
|
412
|
+
// Check database
|
|
413
|
+
const dbHealth = await this._checkAllDatabases();
|
|
414
|
+
|
|
415
|
+
// Optionally check Redis (for backend)
|
|
416
|
+
let redisHealth = null;
|
|
417
|
+
if (this.includeRedisCheck && this.redisClient) {
|
|
418
|
+
redisHealth = await this._checkRedis();
|
|
419
|
+
}
|
|
420
|
+
const checks = {};
|
|
421
|
+
if (dbHealth) checks.database = dbHealth;
|
|
422
|
+
if (redisHealth) checks.redis = redisHealth;
|
|
423
|
+
const statuses = Object.values(checks).map(c => c.status);
|
|
324
424
|
let overallStatus = 'healthy';
|
|
325
425
|
if (statuses.some(s => s === 'unhealthy')) {
|
|
326
426
|
overallStatus = 'unhealthy';
|
|
@@ -332,8 +432,7 @@ class HealthCheckClient {
|
|
|
332
432
|
const result = {
|
|
333
433
|
status: overallStatus,
|
|
334
434
|
timestamp: new Date().toISOString(),
|
|
335
|
-
|
|
336
|
-
components
|
|
435
|
+
checks
|
|
337
436
|
};
|
|
338
437
|
this._cachedResult = {
|
|
339
438
|
result,
|
|
@@ -342,11 +441,58 @@ class HealthCheckClient {
|
|
|
342
441
|
return result;
|
|
343
442
|
}
|
|
344
443
|
|
|
444
|
+
/**
|
|
445
|
+
* Gets cached result from shared cache (Redis if available, otherwise in-memory).
|
|
446
|
+
* Returns null if no cache is available. This is used by endpoints to read-only access.
|
|
447
|
+
* If Redis fails, returns error result with proper format.
|
|
448
|
+
*
|
|
449
|
+
* @returns {Promise<HealthCheckResult | null>} Cached result, error result if Redis fails, or null if not available
|
|
450
|
+
*/
|
|
451
|
+
async getCachedResult() {
|
|
452
|
+
try {
|
|
453
|
+
const cached = await this._cache.get();
|
|
454
|
+
if (cached) {
|
|
455
|
+
return cached;
|
|
456
|
+
}
|
|
457
|
+
// No cache available - worker may not have run yet
|
|
458
|
+
return null;
|
|
459
|
+
} catch (err) {
|
|
460
|
+
// Redis read failed - return error result with proper format
|
|
461
|
+
console.error(`${this.prefixLogs} Failed to read from cache:`, err);
|
|
462
|
+
const errorMessage = maskSensitiveData(err.message || 'Cache read failed');
|
|
463
|
+
return {
|
|
464
|
+
status: 'unhealthy',
|
|
465
|
+
timestamp: new Date().toISOString(),
|
|
466
|
+
checks: {
|
|
467
|
+
redis: {
|
|
468
|
+
status: 'unhealthy',
|
|
469
|
+
error: errorMessage
|
|
470
|
+
}
|
|
471
|
+
},
|
|
472
|
+
errors: [errorMessage]
|
|
473
|
+
};
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
/**
|
|
478
|
+
* Forces a refresh of the health check cache.
|
|
479
|
+
* This is used by background workers to periodically update the cache.
|
|
480
|
+
* Updates shared cache (Redis if available, otherwise in-memory).
|
|
481
|
+
*
|
|
482
|
+
* @returns {Promise<HealthCheckResult>}
|
|
483
|
+
*/
|
|
484
|
+
async refreshCache() {
|
|
485
|
+
const result = await this._performHealthCheckInternal();
|
|
486
|
+
await this._cache.set(result);
|
|
487
|
+
return result;
|
|
488
|
+
}
|
|
489
|
+
|
|
345
490
|
/**
|
|
346
491
|
* Clears the cached health check result, forcing the next check to be fresh.
|
|
347
492
|
*/
|
|
348
493
|
clearCache() {
|
|
349
494
|
this._cachedResult = null;
|
|
495
|
+
this._refreshPromise = null;
|
|
350
496
|
}
|
|
351
497
|
|
|
352
498
|
/**
|
|
@@ -358,19 +504,28 @@ class HealthCheckClient {
|
|
|
358
504
|
*/
|
|
359
505
|
_getErrorMessages(result) {
|
|
360
506
|
const errors = [];
|
|
361
|
-
if (result.
|
|
362
|
-
const db = result.
|
|
507
|
+
if (result.checks.database) {
|
|
508
|
+
const db = result.checks.database;
|
|
509
|
+
|
|
510
|
+
// Check main database status
|
|
511
|
+
if (db.status === 'unhealthy' && (db.message || db.error)) {
|
|
512
|
+
const dbName = this._mainDatabaseConfig?.name || 'main';
|
|
513
|
+
const errorMsg = db.error || db.message;
|
|
514
|
+
errors.push(`DB ${dbName}: ${maskSensitiveData(errorMsg)}`);
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
// Check clusters
|
|
363
518
|
if (db.clusters) {
|
|
364
519
|
for (const [name, health] of Object.entries(db.clusters)) {
|
|
365
520
|
if (health.status === 'unhealthy') {
|
|
366
|
-
const message = health.message || 'connection failed';
|
|
521
|
+
const message = health.error || health.message || 'connection failed';
|
|
367
522
|
errors.push(`DB ${name}: ${maskSensitiveData(message)}`);
|
|
368
523
|
}
|
|
369
524
|
}
|
|
370
525
|
}
|
|
371
526
|
}
|
|
372
|
-
if (result.
|
|
373
|
-
const message = result.
|
|
527
|
+
if (result.checks.redis && result.checks.redis.status === 'unhealthy') {
|
|
528
|
+
const message = result.checks.redis.error || result.checks.redis.message || 'connection failed';
|
|
374
529
|
errors.push(`Redis: ${maskSensitiveData(message)}`);
|
|
375
530
|
}
|
|
376
531
|
return errors;
|
|
@@ -382,19 +537,41 @@ class HealthCheckClient {
|
|
|
382
537
|
* Response includes errors array when status is not healthy.
|
|
383
538
|
* All sensitive data (passwords, connection strings, etc.) is masked.
|
|
384
539
|
*
|
|
540
|
+
* This handler only reads from cache and never triggers database queries.
|
|
541
|
+
* Use a background worker to periodically refresh the cache.
|
|
542
|
+
*
|
|
385
543
|
* @returns {(req: any, res: any) => Promise<void>} Express request handler
|
|
386
544
|
*/
|
|
387
545
|
healthHandler() {
|
|
388
546
|
return async (req, res) => {
|
|
389
547
|
try {
|
|
390
|
-
|
|
548
|
+
// Only read from cache, never trigger DB queries
|
|
549
|
+
const result = await this.getCachedResult();
|
|
550
|
+
if (!result) {
|
|
551
|
+
// No cache available - return unhealthy status with proper format
|
|
552
|
+
const errorMsg = 'Health check cache not available. Worker may not be running.';
|
|
553
|
+
res.status(503).json({
|
|
554
|
+
status: 'unhealthy',
|
|
555
|
+
timestamp: new Date().toISOString(),
|
|
556
|
+
checks: {
|
|
557
|
+
redis: {
|
|
558
|
+
status: 'unhealthy',
|
|
559
|
+
error: errorMsg
|
|
560
|
+
}
|
|
561
|
+
},
|
|
562
|
+
errors: [errorMsg]
|
|
563
|
+
});
|
|
564
|
+
return;
|
|
565
|
+
}
|
|
391
566
|
const statusCode = result.status === 'unhealthy' ? 503 : 200;
|
|
392
567
|
|
|
393
|
-
// Build response
|
|
568
|
+
// Build response - errors are already in result if present
|
|
394
569
|
const response = {
|
|
395
570
|
...result
|
|
396
571
|
};
|
|
397
|
-
|
|
572
|
+
|
|
573
|
+
// Add top-level errors array if not healthy and errors not already present
|
|
574
|
+
if (result.status !== 'healthy' && !result.errors) {
|
|
398
575
|
const errors = this._getErrorMessages(result);
|
|
399
576
|
if (errors.length > 0) {
|
|
400
577
|
response.errors = errors;
|
|
@@ -403,11 +580,17 @@ class HealthCheckClient {
|
|
|
403
580
|
res.status(statusCode).json(response);
|
|
404
581
|
} catch (err) {
|
|
405
582
|
console.error(`${this.prefixLogs} Health check failed:`, err);
|
|
583
|
+
const errorMsg = maskSensitiveData(err.message);
|
|
406
584
|
res.status(503).json({
|
|
407
585
|
status: 'unhealthy',
|
|
408
586
|
timestamp: new Date().toISOString(),
|
|
409
|
-
|
|
410
|
-
|
|
587
|
+
checks: {
|
|
588
|
+
redis: {
|
|
589
|
+
status: 'unhealthy',
|
|
590
|
+
error: errorMsg
|
|
591
|
+
}
|
|
592
|
+
},
|
|
593
|
+
errors: [errorMsg]
|
|
411
594
|
});
|
|
412
595
|
}
|
|
413
596
|
};
|
|
@@ -417,9 +600,9 @@ class HealthCheckClient {
|
|
|
417
600
|
* Register health check endpoint on an Express app.
|
|
418
601
|
*
|
|
419
602
|
* @param {import('express').Application} app - Express application
|
|
420
|
-
* @param {string} [path='/health'] - Path for the health endpoint
|
|
603
|
+
* @param {string} [path='/health-status'] - Path for the health endpoint
|
|
421
604
|
*/
|
|
422
|
-
registerHealthEndpoint(app, path = '/health') {
|
|
605
|
+
registerHealthEndpoint(app, path = '/health-status') {
|
|
423
606
|
app.get(path, this.healthHandler());
|
|
424
607
|
console.info(`${this.prefixLogs} Registered health endpoint at ${path}`);
|
|
425
608
|
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"healthCheckClient.js","names":["Pool","require","getRedisClientType","REDIS_V4","IOREDIS","REDIS_V3","HealthCheckCache","HEALTH_CHECK_CACHE_TTL_MS","SENSITIVE_PATTERNS","pattern","replacement","maskSensitiveData","text","masked","replace","HealthCheckClient","constructor","options","redisClient","includeRedisCheck","cacheTtlMs","appName","process","env","BUILD_APP_NAME","prefixLogs","_cachedResult","_refreshPromise","_databasePools","Map","_mainDatabaseConfig","_clusterConfigs","_initDatabases","_redisClientType","_cache","mainUrl","databaseUrl","DATABASE_URL","mainName","databaseName","name","url","additionalUrls","additionalDatabaseUrls","Object","entries","push","_getPool","config","has","set","connectionString","max","idleTimeoutMillis","connectionTimeoutMillis","get","_isCacheValid","Date","now","timestamp","_checkSingleDatabase","start","pool","query","status","latencyMs","err","error","message","_checkAllDatabases","length","mainHealth","clusters","clusterResults","Promise","all","map","health","allStatuses","values","c","overallStatus","some","s","result","_checkRedis","pong","resolve","reject","ping","performHealthCheck","cached","_performHealthCheckInternal","then","catch","dbHealth","redisHealth","checks","database","redis","statuses","toISOString","getCachedResult","console","errorMessage","errors","refreshCache","clearCache","_getErrorMessages","db","dbName","errorMsg","healthHandler","req","res","json","statusCode","response","registerHealthEndpoint","app","path","info","cleanup","end","clear","module","exports"],"sources":["../../src/health/healthCheckClient.js"],"sourcesContent":["const { Pool } = require('pg')\nconst {\n getRedisClientType,\n REDIS_V4,\n IOREDIS,\n REDIS_V3,\n} = require('../redisUtils')\nconst { HealthCheckCache } = require('./healthCheckCache')\n\nconst HEALTH_CHECK_CACHE_TTL_MS = 60 * 1000\n\n/**\n * Patterns to detect and mask sensitive information in error messages\n */\nconst SENSITIVE_PATTERNS = [\n // Database connection strings: postgres://user:password@host:port/database\n {\n pattern: /(postgres(?:ql)?|mysql|mongodb|redis|amqp):\\/\\/([^:]+):([^@]+)@([^:/]+)(:\\d+)?\\/([^\\s?]+)/gi,\n replacement: '$1://***:***@***$5/***',\n },\n // Generic URLs with credentials: protocol://user:password@host\n {\n pattern: /(\\w+):\\/\\/([^:]+):([^@]+)@([^\\s/]+)/gi,\n replacement: '$1://***:***@***',\n },\n // Password fields in JSON or key=value format\n {\n pattern: /(password|passwd|pwd|secret|token|api[_-]?key|auth[_-]?token)[\"\\s]*[:=][\"\\s]*([^\\s,}\"]+)/gi,\n replacement: '$1=***',\n },\n // Database/table/schema/role/user names in error messages: database \"name\", table \"name\", etc.\n {\n pattern: /(database|table|schema|role|user|relation|column|index)\\s*[\"']([^\"']+)[\"']/gi,\n replacement: '$1 \"***\"',\n },\n // IP addresses (to hide internal network structure)\n {\n pattern: /\\b(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})(:\\d+)?\\b/g,\n replacement: '***$2',\n },\n // Host names that might reveal internal infrastructure\n {\n pattern: /\\b(host|hostname|server)[\"\\s]*[:=][\"\\s]*([^\\s,}\"]+)/gi,\n replacement: '$1=***',\n },\n]\n\n/**\n * Masks sensitive information in a string\n * @param {string} text - Text that might contain sensitive data\n * @returns {string} - Text with sensitive data masked\n */\nfunction maskSensitiveData(text) {\n if (!text || typeof text !== 'string') {\n return text\n }\n\n let masked = text\n for (const { pattern, replacement } of SENSITIVE_PATTERNS) {\n masked = masked.replace(pattern, replacement)\n }\n return masked\n}\n\n/**\n * @typedef {'healthy' | 'unhealthy' | 'degraded'} HealthStatus\n */\n\n/**\n * @typedef {Object} ComponentHealth\n * @property {HealthStatus} status - Component health status\n * @property {string} [error] - Error message if status is unhealthy\n * @property {string} [message] - Optional status message (deprecated, use error)\n * @property {number} [latencyMs] - Connection latency in milliseconds\n */\n\n/**\n * @typedef {Object} DatabaseClusterHealth\n * @property {HealthStatus} status - Overall databases status\n * @property {Object<string, ComponentHealth>} clusters - Individual cluster health\n */\n\n/**\n * @typedef {Object} HealthCheckResult\n * @property {HealthStatus} status - Overall health status\n * @property {string} timestamp - ISO timestamp of the check\n * @property {Object<string, ComponentHealth | DatabaseClusterHealth>} checks - Individual service health checks\n * @property {string[]} [errors] - Top-level error messages (not related to specific services)\n */\n\n/**\n * @typedef {Object} CachedHealthResult\n * @property {HealthCheckResult} result - The cached health check result\n * @property {number} timestamp - Unix timestamp when cached\n */\n\n/**\n * @typedef {Object} DatabaseConfig\n * @property {string} name - Database/cluster name\n * @property {string} url - Connection URL\n */\n\n/**\n * HealthCheckClient provides a health check middleware for external monitoring services\n * like BetterStack. It validates database and Redis connections with rate limiting\n * to prevent excessive load on backend services.\n *\n * Features:\n * - Multi-cluster DB validation (PostgreSQL)\n * - Redis connection validation (supports ioredis, node-redis v3/v4)\n * - Result caching (default: 60 seconds) to prevent overloading services\n * - Express middleware support\n * - BetterStack-compatible JSON response format\n */\nclass HealthCheckClient {\n /**\n * @param {Object} options\n * @param {string} [options.databaseUrl] - Main PostgreSQL connection URL\n * @param {string} [options.databaseName='main'] - Name for the main database\n * @param {Object<string, string>} [options.additionalDatabaseUrls] - Additional DB clusters (name -> URL)\n * @param {any} [options.redisClient] - Redis client instance (ioredis or node-redis) - used for cache\n * @param {boolean} [options.includeRedisCheck=false] - Include Redis health check in results (for backend)\n * @param {number} [options.cacheTtlMs=60000] - Cache TTL in milliseconds (default: 60s)\n * @param {string} [options.appName] - Application name for logging\n */\n constructor(options = {}) {\n this.redisClient = options.redisClient || null\n this.includeRedisCheck = options.includeRedisCheck || false\n this.cacheTtlMs = options.cacheTtlMs ?? HEALTH_CHECK_CACHE_TTL_MS\n this.appName =\n options.appName || process.env.BUILD_APP_NAME || 'unknown-app'\n\n this.prefixLogs = `[${this.appName}] [HealthCheck]`\n\n /** @type {CachedHealthResult | null} */\n this._cachedResult = null\n\n /** @type {Promise<HealthCheckResult> | null} */\n this._refreshPromise = null\n\n /** @type {Map<string, Pool>} */\n this._databasePools = new Map()\n\n /** @type {DatabaseConfig | null} */\n this._mainDatabaseConfig = null\n\n /** @type {DatabaseConfig[]} */\n this._clusterConfigs = []\n\n this._initDatabases(options)\n\n if (this.redisClient) {\n this._redisClientType = getRedisClientType(this.redisClient)\n }\n\n this._cache = new HealthCheckCache({\n redisClient: this.redisClient,\n appName: this.appName,\n cacheTtlMs: this.cacheTtlMs,\n })\n }\n\n /**\n * Initialize database configurations from options.\n * @param {Object} options - Constructor options\n * @private\n */\n _initDatabases(options) {\n const mainUrl = options.databaseUrl || process.env.DATABASE_URL || ''\n const mainName = options.databaseName || `${this.appName}_db`\n\n if (mainUrl) {\n this._mainDatabaseConfig = { name: mainName, url: mainUrl }\n }\n\n const additionalUrls = options.additionalDatabaseUrls || {}\n for (const [name, url] of Object.entries(additionalUrls)) {\n if (url) {\n this._clusterConfigs.push({ name, url })\n }\n }\n }\n\n /**\n * Get or create a database pool for a given config.\n * @param {DatabaseConfig} config - Database configuration\n * @returns {Pool}\n * @private\n */\n _getPool(config) {\n if (!this._databasePools.has(config.name)) {\n this._databasePools.set(\n config.name,\n new Pool({\n connectionString: config.url,\n max: 1,\n idleTimeoutMillis: 30000,\n connectionTimeoutMillis: 5000,\n })\n )\n }\n return this._databasePools.get(config.name)\n }\n\n /**\n * Checks if cached result is still valid based on TTL.\n * @returns {boolean}\n * @private\n */\n _isCacheValid() {\n if (!this._cachedResult) return false\n return Date.now() - this._cachedResult.timestamp < this.cacheTtlMs\n }\n\n /**\n * Tests a single database cluster connectivity.\n * @param {DatabaseConfig} config - Database configuration\n * @returns {Promise<ComponentHealth>}\n * @private\n */\n async _checkSingleDatabase(config) {\n const start = Date.now()\n\n try {\n const pool = this._getPool(config)\n await pool.query('SELECT 1')\n return {\n status: 'healthy',\n latencyMs: Date.now() - start,\n }\n } catch (err) {\n return {\n status: 'unhealthy',\n error: maskSensitiveData(err.message),\n latencyMs: Date.now() - start,\n }\n }\n }\n\n /**\n * Tests all PostgreSQL databases (main + clusters) in parallel.\n * @returns {Promise<Object | null>} Database health with optional clusters\n * @private\n */\n async _checkAllDatabases() {\n if (!this._mainDatabaseConfig && this._clusterConfigs.length === 0) {\n return null\n }\n\n // Check main database\n let mainHealth = null\n if (this._mainDatabaseConfig) {\n mainHealth = await this._checkSingleDatabase(this._mainDatabaseConfig)\n }\n\n // Check clusters in parallel\n let clusters = null\n if (this._clusterConfigs.length > 0) {\n const clusterResults = await Promise.all(\n this._clusterConfigs.map(async config => ({\n name: config.name,\n health: await this._checkSingleDatabase(config),\n }))\n )\n\n clusters = {}\n for (const { name, health } of clusterResults) {\n clusters[name] = health\n }\n }\n\n // Calculate overall status\n const allStatuses = []\n if (mainHealth) allStatuses.push(mainHealth.status)\n if (clusters) {\n allStatuses.push(...Object.values(clusters).map(c => c.status))\n }\n\n let overallStatus = 'healthy'\n if (allStatuses.some(s => s === 'unhealthy')) {\n overallStatus = 'unhealthy'\n } else if (allStatuses.some(s => s === 'degraded')) {\n overallStatus = 'degraded'\n }\n\n // Build result\n const result = { status: overallStatus }\n if (mainHealth) {\n result.latencyMs = mainHealth.latencyMs\n if (mainHealth.error) result.error = mainHealth.error\n // Keep message for backward compatibility\n if (mainHealth.message) result.message = mainHealth.message\n }\n if (clusters) {\n result.clusters = clusters\n }\n\n return result\n }\n\n /**\n * Tests Redis connectivity using PING command.\n * @returns {Promise<ComponentHealth>}\n * @private\n */\n async _checkRedis() {\n if (!this.redisClient) {\n return { status: 'healthy', message: 'Not configured' }\n }\n\n const start = Date.now()\n\n try {\n let pong\n\n if (this._redisClientType === REDIS_V3) {\n pong = await new Promise((resolve, reject) => {\n this.redisClient.ping((err, result) => {\n if (err) reject(err)\n else resolve(result)\n })\n })\n } else if (\n this._redisClientType === REDIS_V4 ||\n this._redisClientType === IOREDIS\n ) {\n pong = await this.redisClient.ping()\n } else {\n return { status: 'unhealthy', message: 'Unknown Redis client type' }\n }\n\n if (pong === 'PONG') {\n return {\n status: 'healthy',\n latencyMs: Date.now() - start,\n }\n }\n\n return {\n status: 'unhealthy',\n message: maskSensitiveData(`Unexpected PING response: ${pong}`),\n latencyMs: Date.now() - start,\n }\n } catch (err) {\n return {\n status: 'unhealthy',\n message: maskSensitiveData(err.message),\n latencyMs: Date.now() - start,\n }\n }\n }\n\n /**\n * Performs a full health check on all configured components.\n * Results are cached for the configured TTL to prevent excessive load.\n * Uses a mutex pattern to prevent concurrent health checks when cache expires.\n * If cache is expired but a refresh is in progress, returns stale cache (if available).\n *\n * @returns {Promise<HealthCheckResult>}\n */\n async performHealthCheck() {\n // If cache is valid, return immediately\n if (this._isCacheValid()) {\n return { ...this._cachedResult.result, cached: true }\n }\n\n // If a refresh is already in progress, return stale cache (if available) or wait for refresh\n if (this._refreshPromise) {\n // Return stale cache immediately if available, otherwise wait for refresh\n if (this._cachedResult) {\n return { ...this._cachedResult.result, cached: true }\n }\n // Wait for the in-progress refresh\n return this._refreshPromise\n }\n\n // Start a new refresh\n this._refreshPromise = this._performHealthCheckInternal()\n .then(result => {\n this._refreshPromise = null\n return result\n })\n .catch(err => {\n this._refreshPromise = null\n throw err\n })\n\n // Return stale cache if available while refresh is happening, otherwise wait\n if (this._cachedResult) {\n // Return stale cache immediately, refresh will happen in background\n return { ...this._cachedResult.result, cached: true }\n }\n\n // No stale cache available, wait for refresh\n return this._refreshPromise\n }\n\n /**\n * Internal method that actually performs the health check.\n * This is separated to allow the mutex pattern in performHealthCheck.\n * Only checks database - Redis is used only for cache, not health check.\n *\n * @returns {Promise<HealthCheckResult>}\n * @private\n */\n async _performHealthCheckInternal() {\n // Check database\n const dbHealth = await this._checkAllDatabases()\n\n // Optionally check Redis (for backend)\n let redisHealth = null\n if (this.includeRedisCheck && this.redisClient) {\n redisHealth = await this._checkRedis()\n }\n\n const checks = {}\n if (dbHealth) checks.database = dbHealth\n if (redisHealth) checks.redis = redisHealth\n\n const statuses = Object.values(checks).map(c => c.status)\n let overallStatus = 'healthy'\n\n if (statuses.some(s => s === 'unhealthy')) {\n overallStatus = 'unhealthy'\n } else if (statuses.some(s => s === 'degraded')) {\n overallStatus = 'degraded'\n }\n\n /** @type {HealthCheckResult} */\n const result = {\n status: overallStatus,\n timestamp: new Date().toISOString(),\n checks,\n }\n\n this._cachedResult = {\n result,\n timestamp: Date.now(),\n }\n\n return result\n }\n\n /**\n * Gets cached result from shared cache (Redis if available, otherwise in-memory).\n * Returns null if no cache is available. This is used by endpoints to read-only access.\n * If Redis fails, returns error result with proper format.\n *\n * @returns {Promise<HealthCheckResult | null>} Cached result, error result if Redis fails, or null if not available\n */\n async getCachedResult() {\n try {\n const cached = await this._cache.get()\n if (cached) {\n return cached\n }\n // No cache available - worker may not have run yet\n return null\n } catch (err) {\n // Redis read failed - return error result with proper format\n console.error(`${this.prefixLogs} Failed to read from cache:`, err)\n const errorMessage = maskSensitiveData(err.message || 'Cache read failed')\n return {\n status: 'unhealthy',\n timestamp: new Date().toISOString(),\n checks: {\n redis: {\n status: 'unhealthy',\n error: errorMessage,\n },\n },\n errors: [errorMessage],\n }\n }\n }\n\n /**\n * Forces a refresh of the health check cache.\n * This is used by background workers to periodically update the cache.\n * Updates shared cache (Redis if available, otherwise in-memory).\n *\n * @returns {Promise<HealthCheckResult>}\n */\n async refreshCache() {\n const result = await this._performHealthCheckInternal()\n await this._cache.set(result)\n\n return result\n }\n\n /**\n * Clears the cached health check result, forcing the next check to be fresh.\n */\n clearCache() {\n this._cachedResult = null\n this._refreshPromise = null\n }\n\n /**\n * Builds a list of error messages from health check result.\n * All error messages are sanitized to remove sensitive information.\n * @param {HealthCheckResult} result - Health check result\n * @returns {string[]} Array of sanitized error messages\n * @private\n */\n _getErrorMessages(result) {\n const errors = []\n\n if (result.checks.database) {\n const db = result.checks.database\n\n // Check main database status\n if (db.status === 'unhealthy' && (db.message || db.error)) {\n const dbName = this._mainDatabaseConfig?.name || 'main'\n const errorMsg = db.error || db.message\n errors.push(`DB ${dbName}: ${maskSensitiveData(errorMsg)}`)\n }\n\n // Check clusters\n if (db.clusters) {\n for (const [name, health] of Object.entries(db.clusters)) {\n if (health.status === 'unhealthy') {\n const message = health.error || health.message || 'connection failed'\n errors.push(`DB ${name}: ${maskSensitiveData(message)}`)\n }\n }\n }\n }\n\n if (result.checks.redis && result.checks.redis.status === 'unhealthy') {\n const message = result.checks.redis.error || result.checks.redis.message || 'connection failed'\n errors.push(`Redis: ${maskSensitiveData(message)}`)\n }\n\n return errors\n }\n\n /**\n * Express middleware handler for health check endpoint.\n * Returns 200 for healthy/degraded, 503 for unhealthy.\n * Response includes errors array when status is not healthy.\n * All sensitive data (passwords, connection strings, etc.) is masked.\n *\n * This handler only reads from cache and never triggers database queries.\n * Use a background worker to periodically refresh the cache.\n *\n * @returns {(req: any, res: any) => Promise<void>} Express request handler\n */\n healthHandler() {\n return async (req, res) => {\n try {\n // Only read from cache, never trigger DB queries\n const result = await this.getCachedResult()\n\n if (!result) {\n // No cache available - return unhealthy status with proper format\n const errorMsg = 'Health check cache not available. Worker may not be running.'\n res.status(503).json({\n status: 'unhealthy',\n timestamp: new Date().toISOString(),\n checks: {\n redis: {\n status: 'unhealthy',\n error: errorMsg,\n },\n },\n errors: [errorMsg],\n })\n return\n }\n\n const statusCode = result.status === 'unhealthy' ? 503 : 200\n\n // Build response - errors are already in result if present\n const response = { ...result }\n \n // Add top-level errors array if not healthy and errors not already present\n if (result.status !== 'healthy' && !result.errors) {\n const errors = this._getErrorMessages(result)\n if (errors.length > 0) {\n response.errors = errors\n }\n }\n\n res.status(statusCode).json(response)\n } catch (err) {\n console.error(`${this.prefixLogs} Health check failed:`, err)\n const errorMsg = maskSensitiveData(err.message)\n res.status(503).json({\n status: 'unhealthy',\n timestamp: new Date().toISOString(),\n checks: {\n redis: {\n status: 'unhealthy',\n error: errorMsg,\n },\n },\n errors: [errorMsg],\n })\n }\n }\n }\n\n /**\n * Register health check endpoint on an Express app.\n *\n * @param {import('express').Application} app - Express application\n * @param {string} [path='/health-status'] - Path for the health endpoint\n */\n registerHealthEndpoint(app, path = '/health-status') {\n app.get(path, this.healthHandler())\n console.info(`${this.prefixLogs} Registered health endpoint at ${path}`)\n }\n\n /**\n * Cleanup resources (database pools).\n * @returns {Promise<void>}\n */\n async cleanup() {\n for (const [name, pool] of this._databasePools) {\n try {\n await pool.end()\n } catch (err) {\n console.error(`${this.prefixLogs} Error closing database pool ${name}:`, err)\n }\n }\n this._databasePools.clear()\n }\n}\n\nmodule.exports = { HealthCheckClient }\n"],"mappings":";;AAAA,MAAM;EAAEA;AAAK,CAAC,GAAGC,OAAO,CAAC,IAAI,CAAC;AAC9B,MAAM;EACJC,kBAAkB;EAClBC,QAAQ;EACRC,OAAO;EACPC;AACF,CAAC,GAAGJ,OAAO,CAAC,eAAe,CAAC;AAC5B,MAAM;EAAEK;AAAiB,CAAC,GAAGL,OAAO,CAAC,oBAAoB,CAAC;AAE1D,MAAMM,yBAAyB,GAAG,EAAE,GAAG,IAAI;;AAE3C;AACA;AACA;AACA,MAAMC,kBAAkB,GAAG;AACzB;AACA;EACEC,OAAO,EAAE,6FAA6F;EACtGC,WAAW,EAAE;AACf,CAAC;AACD;AACA;EACED,OAAO,EAAE,uCAAuC;EAChDC,WAAW,EAAE;AACf,CAAC;AACD;AACA;EACED,OAAO,EAAE,4FAA4F;EACrGC,WAAW,EAAE;AACf,CAAC;AACD;AACA;EACED,OAAO,EAAE,8EAA8E;EACvFC,WAAW,EAAE;AACf,CAAC;AACD;AACA;EACED,OAAO,EAAE,kDAAkD;EAC3DC,WAAW,EAAE;AACf,CAAC;AACD;AACA;EACED,OAAO,EAAE,uDAAuD;EAChEC,WAAW,EAAE;AACf,CAAC,CACF;;AAED;AACA;AACA;AACA;AACA;AACA,SAASC,iBAAiBA,CAACC,IAAI,EAAE;EAC/B,IAAI,CAACA,IAAI,IAAI,OAAOA,I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}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Creates a Redis client for health check cache with a specific client name.
|
|
3
|
+
* This allows the cache to be shared across worker and web processes.
|
|
4
|
+
*
|
|
5
|
+
* @param {Object} options
|
|
6
|
+
* @param {string} [options.redisUrl] - Redis URL (defaults to process.env.REDIS_URL)
|
|
7
|
+
* @param {string} [options.appName] - Application name for client name
|
|
8
|
+
* @param {string} [options.clientName='healthcheck'] - Client name suffix
|
|
9
|
+
* @returns {any | null} Redis client instance or null if REDIS_URL not available
|
|
10
|
+
*/
|
|
11
|
+
export function createHealthCheckRedisClient(options?: {
|
|
12
|
+
redisUrl?: string | undefined;
|
|
13
|
+
appName?: string | undefined;
|
|
14
|
+
clientName?: string | undefined;
|
|
15
|
+
}): any | null;
|
|
16
|
+
/**
|
|
17
|
+
* Creates a health check client for worker process.
|
|
18
|
+
* Worker needs database config to perform health checks and store results in Redis.
|
|
19
|
+
*
|
|
20
|
+
* @param {Object} options
|
|
21
|
+
* @param {string} options.databaseUrl - Main database URL
|
|
22
|
+
* @param {string} options.databaseName - Database name
|
|
23
|
+
* @param {string} [options.appName] - Application name (defaults to BUILD_APP_NAME)
|
|
24
|
+
* @param {Object<string, string>} [options.additionalDatabaseUrls] - Additional database clusters (for database service)
|
|
25
|
+
* @param {string} [options.redisUrl] - Redis URL (defaults to process.env.REDIS_URL)
|
|
26
|
+
* @param {number} [options.cacheTtlMs=60000] - Cache TTL in milliseconds
|
|
27
|
+
* @returns {HealthCheckClient} Configured health check client instance for worker
|
|
28
|
+
*/
|
|
29
|
+
export function createHealthCheckWorkerClient(options: {
|
|
30
|
+
databaseUrl: string;
|
|
31
|
+
databaseName: string;
|
|
32
|
+
appName?: string | undefined;
|
|
33
|
+
additionalDatabaseUrls?: {
|
|
34
|
+
[x: string]: string;
|
|
35
|
+
} | undefined;
|
|
36
|
+
redisUrl?: string | undefined;
|
|
37
|
+
cacheTtlMs?: number | undefined;
|
|
38
|
+
}): import("./healthCheckClient").HealthCheckClient;
|
|
39
|
+
/**
|
|
40
|
+
* Creates a health check client for endpoint handlers.
|
|
41
|
+
* Endpoints only read from cache, so they only need Redis client (no database config).
|
|
42
|
+
*
|
|
43
|
+
* @param {Object} options
|
|
44
|
+
* @param {any} options.redisClient - Existing Redis client instance (from system) - REQUIRED
|
|
45
|
+
* @param {boolean} [options.includeRedisCheck=false] - Include Redis health check in response (for backend)
|
|
46
|
+
* @param {number} [options.cacheTtlMs=60000] - Cache TTL in milliseconds
|
|
47
|
+
* @returns {HealthCheckClient} Configured health check client instance for endpoints
|
|
48
|
+
*/
|
|
49
|
+
export function createHealthCheckEndpointClient(options: {
|
|
50
|
+
redisClient: any;
|
|
51
|
+
includeRedisCheck?: boolean | undefined;
|
|
52
|
+
cacheTtlMs?: number | undefined;
|
|
53
|
+
}): import("./healthCheckClient").HealthCheckClient;
|
|
54
|
+
//# sourceMappingURL=healthCheckUtils.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"healthCheckUtils.d.ts","sourceRoot":"","sources":["../../src/health/healthCheckUtils.js"],"names":[],"mappings":"AAGA;;;;;;;;;GASG;AACH;IAL4B,QAAQ;IACR,OAAO;IACP,UAAU;IACzB,GAAG,GAAG,IAAI,CAmDtB;AAED;;;;;;;;;;;;GAYG;AACH;IAR2B,WAAW,EAA3B,MAAM;IACU,YAAY,EAA5B,MAAM;IACW,OAAO;IACS,sBAAsB;;;IACtC,QAAQ;IACR,UAAU;oDAmCrC;AAED;;;;;;;;;GASG;AACH;IALwB,WAAW,EAAxB,GAAG;IACe,iBAAiB;IAClB,UAAU;oDAiBrC"}
|