Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 | 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 24x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 12x 12x 12x 12x 8x 8x 8x 12x 4x 8x 8x 8x 6x 6x 5x 1x 2x 2x 8x 8x 8x 8x 7x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 24x 2x 2x 2x 24x 3x 2x 2x 2x 2x 2x 2x 24x 1x 2x 2x 2x 2x 2x 2x 24x 8x 2x 2x 2x 8x 8x 8x 14x 5x 7x 1x 8x 2x 2x 8x 5x 2x 3x 2x 2x 2x 2x 2x 2x 2x 2x 2x 24x 2x 2x 4x 2x 4x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 24x 6x 6x 6x 2x 4x 2x 2x 2x 2x 2x 3x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 24x 2x 5x 5x 5x 3x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 24x 2x 2x 2x 5x 5x 5x 5x 2x 5x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 24x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 24x 2x 2x 2x 7x 7x 4x 2x 2x 2x 2x 5x 4x 2x 2x 2x 2x 5x 2x 2x 2x 2x 2x | // src/routes/health.routes.ts /** * @file Health check endpoints implementing ADR-020: Health Checks and Liveness/Readiness Probes. * * Provides endpoints for: * - Liveness probe (/live) - Is the server process running? * - Readiness probe (/ready) - Is the server ready to accept traffic? * - Individual service health checks (db, redis, storage) */ import { Router, Request, Response, NextFunction } from 'express'; import { z } from 'zod'; import { checkTablesExist, getPoolStatus, getPool } from '../services/db/connection.db'; import { connection as redisConnection } from '../services/queueService.server'; import fs from 'node:fs/promises'; import { getSimpleWeekAndYear } from '../utils/dateUtils'; import { validateRequest } from '../middleware/validation.middleware'; import { sendSuccess, sendError, ErrorCode } from '../utils/apiResponse'; const router = Router(); // --- Types for Health Check Response --- interface ServiceHealth { status: 'healthy' | 'degraded' | 'unhealthy'; latency?: number; message?: string; details?: Record<string, unknown>; } interface ReadinessResponse { status: 'healthy' | 'degraded' | 'unhealthy'; timestamp: string; uptime: number; services: { database: ServiceHealth; redis: ServiceHealth; storage: ServiceHealth; }; } // --- Helper Functions --- /** * Checks database connectivity with timing. */ async function checkDatabase(): Promise<ServiceHealth> { const start = Date.now(); try { const pool = getPool(); await pool.query('SELECT 1'); const latency = Date.now() - start; const poolStatus = getPoolStatus(); // Consider degraded if waiting connections > 3 const status = poolStatus.waitingCount > 3 ? 'degraded' : 'healthy'; return { status, latency, details: { totalConnections: poolStatus.totalCount, idleConnections: poolStatus.idleCount, waitingConnections: poolStatus.waitingCount, }, }; } catch (error) { return { status: 'unhealthy', latency: Date.now() - start, message: error instanceof Error ? error.message : 'Database connection failed', }; } } /** * Checks Redis connectivity with timing. */ async function checkRedis(): Promise<ServiceHealth> { const start = Date.now(); try { const reply = await redisConnection.ping(); const latency = Date.now() - start; if (reply === 'PONG') { return { status: 'healthy', latency }; } return { status: 'unhealthy', latency, message: `Unexpected ping response: ${reply}`, }; } catch (error) { return { status: 'unhealthy', latency: Date.now() - start, message: error instanceof Error ? error.message : 'Redis connection failed', }; } } /** * Checks storage accessibility. */ async function checkStorage(): Promise<ServiceHealth> { const storagePath = process.env.STORAGE_PATH || '/var/www/flyer-crawler.projectium.com/flyer-images'; const start = Date.now(); try { await fs.access(storagePath, fs.constants.W_OK); return { status: 'healthy', latency: Date.now() - start, details: { path: storagePath }, }; } catch { return { status: 'unhealthy', latency: Date.now() - start, message: `Storage not accessible: ${storagePath}`, }; } } // --- Zod Schemas for Health Routes (as per ADR-003) --- // These routes do not expect any input, so we define empty schemas // to maintain a consistent validation pattern across the application. const emptySchema = z.object({}); /** * @openapi * /health/ping: * get: * summary: Simple ping endpoint * description: Returns a pong response to verify server is responsive. Use this for basic connectivity checks. * tags: * - Health * responses: * 200: * description: Server is responsive * content: * application/json: * schema: * type: object * properties: * success: * type: boolean * example: true * data: * type: object * properties: * message: * type: string * example: pong */ router.get('/ping', validateRequest(emptySchema), (_req: Request, res: Response) => { return sendSuccess(res, { message: 'pong' }); }); // ============================================================================= // KUBERNETES PROBES (ADR-020) // ============================================================================= /** * @openapi * /health/live: * get: * summary: Liveness probe * description: | * Returns 200 OK if the server process is running. * If this fails, the orchestrator should restart the container. * This endpoint is intentionally simple and has no external dependencies. * tags: * - Health * responses: * 200: * description: Server process is alive * content: * application/json: * schema: * type: object * properties: * success: * type: boolean * example: true * data: * type: object * properties: * status: * type: string * example: ok * timestamp: * type: string * format: date-time */ router.get('/live', validateRequest(emptySchema), (_req: Request, res: Response) => { return sendSuccess(res, { status: 'ok', timestamp: new Date().toISOString(), }); }); /** * @openapi * /health/ready: * get: * summary: Readiness probe * description: | * Returns 200 OK if the server is ready to accept traffic. * Checks all critical dependencies (database, Redis, storage). * If this fails, the orchestrator should remove the container from the load balancer. * tags: * - Health * responses: * 200: * description: Server is ready to accept traffic * content: * application/json: * schema: * type: object * properties: * success: * type: boolean * example: true * data: * type: object * properties: * status: * type: string * enum: [healthy, degraded, unhealthy] * timestamp: * type: string * format: date-time * uptime: * type: number * description: Server uptime in seconds * services: * type: object * properties: * database: * $ref: '#/components/schemas/ServiceHealth' * redis: * $ref: '#/components/schemas/ServiceHealth' * storage: * $ref: '#/components/schemas/ServiceHealth' * 503: * description: Service is unhealthy and should not receive traffic * content: * application/json: * schema: * $ref: '#/components/schemas/ErrorResponse' */ router.get('/ready', validateRequest(emptySchema), async (req: Request, res: Response) => { // Check all services in parallel for speed const [database, redis, storage] = await Promise.all([ checkDatabase(), checkRedis(), checkStorage(), ]); // Determine overall status // - 'healthy' if all critical services (db, redis) are healthy // - 'degraded' if any service is degraded but none unhealthy // - 'unhealthy' if any critical service is unhealthy const criticalServices = [database, redis]; const allServices = [database, redis, storage]; let overallStatus: 'healthy' | 'degraded' | 'unhealthy' = 'healthy'; if (criticalServices.some((s) => s.status === 'unhealthy')) { overallStatus = 'unhealthy'; } else if (allServices.some((s) => s.status === 'degraded')) { overallStatus = 'degraded'; } const response: ReadinessResponse = { status: overallStatus, timestamp: new Date().toISOString(), uptime: process.uptime(), services: { database, redis, storage, }, }; // Return appropriate HTTP status code // 200 = healthy or degraded (can still handle traffic) // 503 = unhealthy (should not receive traffic) if (overallStatus === 'unhealthy') { return sendError(res, ErrorCode.SERVICE_UNAVAILABLE, 'Service unhealthy', 503, response); } return sendSuccess(res, response); }); /** * GET /api/health/startup - Startup probe for container orchestration. * * Similar to readiness but used during container startup. * The orchestrator will not send liveness/readiness probes until this succeeds. * This allows for longer initialization times without triggering restarts. */ router.get('/startup', validateRequest(emptySchema), async (req: Request, res: Response) => { // For startup, we only check database connectivity // Redis and storage can be checked later in readiness const database = await checkDatabase(); if (database.status === 'unhealthy') { return sendError(res, ErrorCode.SERVICE_UNAVAILABLE, 'Waiting for database connection', 503, { status: 'starting', database, }); } return sendSuccess(res, { status: 'started', timestamp: new Date().toISOString(), database, }); }); /** * GET /api/health/db-schema - Checks if all essential database tables exist. * This is a critical check to ensure the database schema is correctly set up. */ router.get('/db-schema', validateRequest(emptySchema), async (req, res, next: NextFunction) => { try { const requiredTables = ['users', 'profiles', 'flyers', 'flyer_items', 'stores']; const missingTables = await checkTablesExist(requiredTables); if (missingTables.length > 0) { // Create a new error to be handled by the global error handler return next( new Error(`Database schema check failed. Missing tables: ${missingTables.join(', ')}.`), ); } return sendSuccess(res, { message: 'All required database tables exist.' }); } catch (error: unknown) { if (error instanceof Error) { return next(error); } const message = (error as { message?: string })?.message || 'An unknown error occurred during DB schema check.'; return next(new Error(message)); } }); /** * GET /api/health/storage - Verifies that the application's file storage path is accessible and writable. * This is important for features like file uploads. */ router.get('/storage', validateRequest(emptySchema), async (req, res, next: NextFunction) => { const storagePath = process.env.STORAGE_PATH || '/var/www/flyer-crawler.projectium.com/flyer-images'; try { await fs.access(storagePath, fs.constants.W_OK); // Use fs.promises return sendSuccess(res, { message: `Storage directory '${storagePath}' is accessible and writable.`, }); } catch { next( new Error( `Storage check failed. Ensure the directory '${storagePath}' exists and is writable by the application.`, ), ); } }); /** * GET /api/health/db-pool - Checks the status of the database connection pool. * This helps diagnose issues related to database connection saturation. */ router.get( '/db-pool', validateRequest(emptySchema), (req: Request, res: Response, next: NextFunction) => { try { const status = getPoolStatus(); const isHealthy = status.waitingCount < 5; const message = `Pool Status: ${status.totalCount} total, ${status.idleCount} idle, ${status.waitingCount} waiting.`; if (isHealthy) { return sendSuccess(res, { message, ...status }); } else { req.log.warn(`Database pool health check shows high waiting count: ${status.waitingCount}`); return sendError( res, ErrorCode.INTERNAL_ERROR, `Pool may be under stress. ${message}`, 500, status, ); } } catch (error: unknown) { if (error instanceof Error) { return next(error); } const message = (error as { message?: string })?.message || 'An unknown error occurred during DB pool check.'; return next(new Error(message)); } }, ); /** * GET /api/health/time - Returns the server's current time, year, and week number. * Useful for verifying time synchronization and for features dependent on week numbers. */ router.get('/time', validateRequest(emptySchema), (req: Request, res: Response) => { const now = new Date(); const { year, week } = getSimpleWeekAndYear(now); return sendSuccess(res, { currentTime: now.toISOString(), year, week, }); }); /** * GET /api/health/redis - Checks the health of the Redis connection. */ router.get( '/redis', validateRequest(emptySchema), async (req: Request, res: Response, next: NextFunction) => { try { const reply = await redisConnection.ping(); if (reply === 'PONG') { return sendSuccess(res, { message: 'Redis connection is healthy.' }); } throw new Error(`Unexpected Redis ping response: ${reply}`); // This will be caught below } catch (error: unknown) { if (error instanceof Error) { return next(error); } const message = (error as { message?: string })?.message || 'An unknown error occurred during Redis health check.'; return next(new Error(message)); } }, ); export default router; |