### Implementing Custom Health Checks with BaseCheck Source: https://context7.com/adonisjs/health/llms.txt Shows how to extend the BaseCheck abstract class to create custom health monitoring logic. Examples include a DatabaseCheck for database connectivity and an ExternalApiCheck for external service availability. It also demonstrates registering these custom checks with the HealthChecks class and running them to generate a report. ```typescript import { BaseCheck, Result, HealthChecks } from '@adonisjs/health' import type { HealthCheckResult } from '@adonisjs/health/types' // Custom database health check class DatabaseCheck extends BaseCheck { name = 'Database connection check' constructor(private connectionPool: any) { super() } async run(): Promise { try { const startTime = Date.now() await this.connectionPool.query('SELECT 1') const responseTime = Date.now() - startTime if (responseTime > 1000) { return Result.warning('Database responding slowly') .setMetaData({ responseTimeMs: responseTime, threshold: 1000 }) } return Result.ok('Database connection is healthy') .setMetaData({ responseTimeMs: responseTime, poolSize: this.connectionPool.totalCount, idleConnections: this.connectionPool.idleCount }) } catch (error) { return Result.failed('Database connection failed', error as Error) } } } // Custom external API health check class ExternalApiCheck extends BaseCheck { name = 'External API check' constructor(private apiUrl: string) { super() } async run(): Promise { try { const response = await fetch(`${this.apiUrl}/health`) if (!response.ok) { return Result.failed(`API returned status ${response.status}`) } return Result.ok('External API is reachable') .setMetaData({ statusCode: response.status }) } catch (error) { return Result.failed('External API unreachable', error as Error) } } } // Register custom checks const healthChecks = new HealthChecks().register([ new DatabaseCheck(dbPool) .as('PostgreSQL database') .cacheFor('30s'), new ExternalApiCheck('https://api.example.com') .as('Payment gateway API') .cacheFor('1 minute') ]) const report = await healthChecks.run() ``` -------------------------------- ### Subscribe to Health Check Tracing Events (TypeScript) Source: https://context7.com/adonisjs/health/llms.txt This snippet demonstrates how to subscribe to health check lifecycle events (start, end, error) using the tracing channels provided by @adonisjs/health. It logs the start and end of checks, measures their duration, and logs any errors encountered. It also shows how to check if there are active subscribers. ```typescript import { tracingChannels } from '@adonisjs/health' const { healthCheck } = tracingChannels // Subscribe to health check execution events healthCheck.subscribe({ start(data) { console.log(`[Health] Starting check: ${data.check.name}`) console.time(`healthCheck:${data.check.name}`) }, end(data, result) { console.timeEnd(`healthCheck:${data.check.name}`) console.log(`[Health] Completed: ${data.check.name} - Status: ${result?.status}`) }, error(data, error) { console.error(`[Health] Check failed: ${data.check.name}`, error) } }) // Check if there are active subscribers if (healthCheck.hasSubscribers) { console.log('Health check tracing is active') } ``` -------------------------------- ### Tracing Channels Source: https://context7.com/adonisjs/health/llms.txt Integrate diagnostic channels to monitor health check execution lifecycle events such as start, end, and error phases. ```APIDOC ## Tracing Channels Diagnostic channel integration for monitoring health check execution. Subscribe to the tracing channel to log, measure, or observe health check lifecycle events including start, end, and error phases. ### Method N/A (This is a code example for subscribing to events) ### Endpoint N/A ### Parameters N/A ### Request Example ```typescript import { tracingChannels } from '@adonisjs/health' const { healthCheck } = tracingChannels // Subscribe to health check execution events healthCheck.subscribe({ start(data) { console.log(`[Health] Starting check: ${data.check.name}`) console.time(`healthCheck:${data.check.name}`) }, end(data, result) { console.timeEnd(`healthCheck:${data.check.name}`) console.log(`[Health] Completed: ${data.check.name} - Status: ${result?.status}`) }, error(data, error) { console.error(`[Health] Check failed: ${data.check.name}`, error) } }) // Check if there are active subscribers if (healthCheck.hasSubscribers) { console.log('Health check tracing is active') } ``` ### Response N/A (This is for event subscription, not a direct API response) ### Response Example ``` [Health] Starting check: Disk space check healthCheck:Disk space check: 15.234ms [Health] Completed: Disk space check - Status: ok [Health] Starting check: Memory heap check healthCheck:Memory heap check: 2.156ms [Health] Completed: Memory heap check - Status: ok ``` ``` -------------------------------- ### Configure and Run HTTP Health Checks (TypeScript) Source: https://context7.com/adonisjs/health/llms.txt This snippet shows how to configure and run health checks using the HealthChecks class from @adonisjs/health. It registers built-in checks like DiskSpaceCheck, MemoryHeapCheck, and MemoryRSSCheck with configurable thresholds and caching. It also provides examples for an Express/Fastify/AdonisJS route handler and Kubernetes-style liveness/readiness probes. ```typescript import { HealthChecks, DiskSpaceCheck, MemoryHeapCheck, MemoryRSSCheck } from '@adonisjs/health' // Configure health checks once at application startup const healthChecks = new HealthChecks().register([ new DiskSpaceCheck() .warnWhenExceeds(70) .failWhenExceeds(85) .cacheFor('1 minute'), new MemoryHeapCheck() .warnWhenExceedsPercentage(80) .failWhenExceedsPercentage(90) .cacheFor('30s'), new MemoryRSSCheck() .warnWhenExceedsPercentage(70) .failWhenExceedsPercentage(85) .cacheFor('30s') ]) // Express/Fastify/AdonisJS route handler example async function healthEndpoint(request: any, response: any) { const report = await healthChecks.run() // Set appropriate HTTP status code const httpStatus = report.isHealthy ? 200 : 503 response.status(httpStatus).json({ status: report.status, timestamp: report.finishedAt.toISOString(), checks: report.checks.map(check => ({ name: check.name, status: check.status, message: check.message, cached: check.isCached })), process: { pid: report.debugInfo.pid, uptime: Math.floor(report.debugInfo.uptime), nodeVersion: report.debugInfo.version } }) } // Kubernetes-style liveness/readiness probes async function livenessProbe(request: any, response: any) { const report = await healthChecks.run() response.status(report.isHealthy ? 200 : 503).send(report.status) } ``` -------------------------------- ### Configure Disk Space Check Source: https://context7.com/adonisjs/health/llms.txt Monitors disk space usage with customizable thresholds and caching. Supports default root filesystem monitoring or custom disk paths. Allows for custom computation logic for testing or specific environments. ```typescript import { DiskSpaceCheck } from '@adonisjs/health' // Basic disk space check with default settings const basicDiskCheck = new DiskSpaceCheck() // Fully configured disk space check const diskCheck = new DiskSpaceCheck() .as('Application data disk') // Custom name .warnWhenExceeds(70) // Warning at 70% usage .failWhenExceeds(85) // Error at 85% usage .cacheFor('2 minutes') // Cache result for 2 minutes // Custom disk path (Windows example) const windowsDiskCheck = new DiskSpaceCheck() .as('Windows C: drive') windowsDiskCheck.diskPath = 'C:\\' // Custom compute function for testing or specialized environments const customDiskCheck = new DiskSpaceCheck() .as('Mock disk check') .compute(async () => ({ free: 200000000000, // 200 GB free size: 500000000000 // 500 GB total })) const result = await diskCheck.run() console.log(result) ``` -------------------------------- ### Register and Run Health Checks with HealthChecks Class Source: https://context7.com/adonisjs/health/llms.txt Orchestrates the registration and execution of multiple health checks. It runs checks in parallel, aggregates results, and provides an overall health report including debug information. Supports registering checks initially and appending more later. ```typescript import { HealthChecks, DiskSpaceCheck, MemoryHeapCheck, MemoryRSSCheck } from '@adonisjs/health' // Create and configure health checks runner const healthChecks = new HealthChecks() // Register multiple health checks healthChecks.register([ new DiskSpaceCheck() .as('Root disk space') .warnWhenExceeds(70) .failWhenExceeds(85) .cacheFor('1 minute'), new MemoryHeapCheck() .as('V8 heap memory') .warnWhenExceeds('200 mb') .failWhenExceeds('500 mb') .cacheFor('30s'), new MemoryRSSCheck() .as('Process RSS memory') .warnWhenExceedsPercentage(70) .failWhenExceedsPercentage(85) .cacheFor('30s') ]) // Execute all checks and get aggregated report const report = await healthChecks.run() console.log(report) // Append additional checks later healthChecks.append([ new DiskSpaceCheck().as('Data disk').compute(async () => ({ free: 500000000, size: 1000000000 })) ]) ``` -------------------------------- ### Constructing Health Check Results with Result Class Source: https://context7.com/adonisjs/health/llms.txt Demonstrates how to use the Result class to create health check outcomes. It covers creating success, warning, and error results, attaching metadata, handling errors, merging metadata, setting custom timestamps, and converting results to JSON. This class provides a fluent API for building comprehensive check results. ```typescript import { Result } from '@adonisjs/health' // Success result const successResult = Result.ok('Database connection is healthy') console.log(successResult) // { status: 'ok', message: 'Database connection is healthy', finishedAt: Date } // Warning result with metadata const warningResult = Result.warning('Memory usage is above 80%') .setMetaData({ currentUsage: '82%', threshold: '80%', recommendation: 'Consider scaling up' }) // Error result with Error object const errorResult = Result.failed('Database connection failed', new Error('Connection timeout')) console.log(errorResult) // { // status: 'error', // message: 'Database connection failed', // finishedAt: Date, // meta: { error: Error('Connection timeout') } // } // Error result from Error object directly const errorFromException = Result.failed(new Error('Critical system failure')) // Merging metadata (shallow merge) const resultWithMergedMeta = Result.ok('Service healthy') .setMetaData({ responseTime: 120 }) .mergeMetaData({ uptime: 86400, connections: 50 }) // meta: { responseTime: 120, uptime: 86400, connections: 50 } // Custom finish timestamp const customTimestamp = Result.ok('Check completed') .setFinishedAt(new Date('2024-01-15T10:30:00.000Z')) // Convert to plain object const jsonResult = Result.ok('Service running') .setMetaData({ version: '1.0.0' }) .toJSON() // { message: 'Service running', status: 'ok', finishedAt: Date, meta: { version: '1.0.0' } } ``` -------------------------------- ### Monitor Process RSS Memory with AdonisJS Health Source: https://context7.com/adonisjs/health/llms.txt This check monitors the Resident Set Size (RSS) of a process, representing its total allocated memory. It supports both absolute byte thresholds and percentage-based thresholds relative to total system memory. Dependencies include the '@adonisjs/health' package. ```typescript import { MemoryRSSCheck } from '@adonisjs/health' // Byte-based thresholds const rssCheckBytes = new MemoryRSSCheck() .as('Process RSS Memory (bytes)') .warnWhenExceeds('300 mb') // Warning at 300 MB .failWhenExceeds('400 mb') // Error at 400 MB .cacheFor('1 minute') // Percentage-based thresholds (relative to total system RAM) const rssCheckPercentage = new MemoryRSSCheck() .as('Process RSS Memory (percentage)') .warnWhenExceedsPercentage(70) // Warning at 70% of system RAM .failWhenExceedsPercentage(85) // Error at 85% of system RAM .cacheFor('1 minute') // Custom compute function const mockRssCheck = new MemoryRSSCheck() .as('Mock RSS check') .compute(() => ({ rss: 250000000, // 250 MB RSS heapTotal: 100000000, heapUsed: 80000000, external: 5000000, arrayBuffers: 2000000 })) const result = await rssCheckBytes.run() console.log(result) // Output: // { // status: 'ok', // message: 'RSS usage is under defined thresholds', // finishedAt: 2024-01-15T10:30:00.000Z, // meta: { // memoryInBytes: { // used: 125829120, // failureThreshold: 419430400, // warningThreshold: 314572800 // } // } // } const resultPercentage = await rssCheckPercentage.run() console.log(resultPercentage) // Output (percentage-based): // { // status: 'ok', // message: 'RSS usage is under defined thresholds', // finishedAt: 2024-01-15T10:30:00.000Z, // meta: { // sizeInPercentage: { used: 2, failureThreshold: 85, warningThreshold: 70 }, // memoryInBytes: { // used: 125829120, // totalSystemMemory: 8589934592, // failureThreshold: 7301444403, // warningThreshold: 6012954214 // } // } // } ``` -------------------------------- ### Monitor V8 Heap Memory Usage with AdonisJS Health Source: https://context7.com/adonisjs/health/llms.txt This check monitors V8 heap memory usage, supporting both absolute byte thresholds and percentage-based thresholds relative to the maximum V8 heap size. It's useful for detecting memory leaks and high memory consumption patterns. Dependencies include the '@adonisjs/health' package. ```typescript import { MemoryHeapCheck } from '@adonisjs/health' // Byte-based thresholds (default approach) const heapCheckBytes = new MemoryHeapCheck() .as('V8 Heap Memory (bytes)') .warnWhenExceeds('200 mb') // Warning at 200 MB .failWhenExceeds('500 mb') // Error at 500 MB .cacheFor('30 seconds') // Percentage-based thresholds (relative to V8 heap limit) const heapCheckPercentage = new MemoryHeapCheck() .as('V8 Heap Memory (percentage)') .warnWhenExceedsPercentage(80) // Warning at 80% of max heap .failWhenExceedsPercentage(90) // Error at 90% of max heap .cacheFor('30s') // Numeric byte values also supported const heapCheckNumeric = new MemoryHeapCheck() .warnWhenExceeds(209715200) // 200 MB in bytes .failWhenExceeds(524288000) // 500 MB in bytes // Custom compute function for testing const mockHeapCheck = new MemoryHeapCheck() .as('Mock heap check') .compute(() => ({ rss: 150000000, heapTotal: 100000000, heapUsed: 80000000, external: 5000000, arrayBuffers: 2000000 })) const resultBytes = await heapCheckBytes.run() console.log(resultBytes) // Output (byte-based): // { // status: 'ok', // message: 'Heap usage is under defined thresholds', // finishedAt: 2024-01-15T10:30:00.000Z, // meta: { // memoryInBytes: { // used: 52428800, // failureThreshold: 524288000, // warningThreshold: 209715200 // } // } // } const resultPercentage = await heapCheckPercentage.run() console.log(resultPercentage) // Output (percentage-based): // { // status: 'ok', // message: 'Heap usage is under defined thresholds', // finishedAt: 2024-01-15T10:30:00.000Z, // meta: { // sizeInPercentage: { used: 15, failureThreshold: 90, warningThreshold: 80 }, // heapInBytes: { // used: 52428800, // maxHeapSize: 2197815296, // failureThreshold: 1978033766, // warningThreshold: 1758252236 // } // } // } ``` -------------------------------- ### HTTP Health Endpoint Integration Source: https://context7.com/adonisjs/health/llms.txt Integrate health checks with an HTTP endpoint to expose application health status for load balancers, container orchestrators, and monitoring systems. ```APIDOC ## HTTP Health Endpoint Integration Integrate health checks with an HTTP endpoint to expose application health status for load balancers, container orchestrators (Kubernetes), and monitoring systems. ### Method GET ### Endpoint `/health` (Example path, can be customized) ### Parameters N/A ### Request Body N/A ### Request Example ```typescript import { HealthChecks, DiskSpaceCheck, MemoryHeapCheck, MemoryRSSCheck } from '@adonisjs/health' // Configure health checks once at application startup const healthChecks = new HealthChecks().register([ new DiskSpaceCheck() .warnWhenExceeds(70) .failWhenExceeds(85) .cacheFor('1 minute'), new MemoryHeapCheck() .warnWhenExceedsPercentage(80) .failWhenExceedsPercentage(90) .cacheFor('30s'), new MemoryRSSCheck() .warnWhenExceedsPercentage(70) .failWhenExceedsPercentage(85) .cacheFor('30s') ]) // Express/Fastify/AdonisJS route handler example async function healthEndpoint(request: any, response: any) { const report = await healthChecks.run() // Set appropriate HTTP status code const httpStatus = report.isHealthy ? 200 : 503 response.status(httpStatus).json({ status: report.status, timestamp: report.finishedAt.toISOString(), checks: report.checks.map(check => ({ name: check.name, status: check.status, message: check.message, cached: check.isCached })), process: { pid: report.debugInfo.pid, uptime: Math.floor(report.debugInfo.uptime), nodeVersion: report.debugInfo.version } }) } // Kubernetes-style liveness/readiness probes async function livenessProbe(request: any, response: any) { const report = await healthChecks.run() response.status(report.isHealthy ? 200 : 503).send(report.status) } ``` ### Response #### Success Response (200) - **status** (string) - Overall health status of the application ('ok' or 'error'). - **timestamp** (string) - ISO 8601 timestamp of when the health check report was generated. - **checks** (array) - An array of objects, each representing a health check. - **name** (string) - The name of the health check. - **status** (string) - The status of the individual check ('ok', 'warn', 'error'). - **message** (string) - A descriptive message about the check's outcome. - **cached** (boolean) - Indicates if the result was served from cache. - **process** (object) - Information about the application process. - **pid** (number) - The process ID. - **uptime** (number) - The uptime of the process in seconds. - **nodeVersion** (string) - The Node.js version. #### Error Response (503) Returns the same structure as the success response, but with an overall status indicating an unhealthy state. ### Response Example ```json { "status": "ok", "timestamp": "2024-01-15T10:30:00.000Z", "checks": [ { "name": "Disk space check", "status": "ok", "message": "Disk usage is under defined thresholds", "cached": false }, { "name": "Memory heap check", "status": "ok", "message": "Heap usage is under defined thresholds", "cached": true }, { "name": "Memory RSS check", "status": "ok", "message": "RSS usage is under defined thresholds", "cached": true } ], "process": { "pid": 12345, "uptime": 3600, "nodeVersion": "v20.10.0" } } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.