HbarSuite Docs
  • Welcome to HbarSuite
  • HbarSuite Developer Documentation
    • HbarSuite Smart Engine Applications
      • @hsuite/cross-chain-exchange
      • @hsuite/dao
      • @hsuite/exchange
      • @hsuite/launchpad
      • @hsuite/multisig
      • @hsuite/nft-exchange
    • HSuite Libraries
      • @hsuite/api-key
      • @hsuite/auth-types
      • @hsuite/auth
      • @hsuite/client-types
      • @hsuite/client
      • @hsuite/dkg-types
      • @hsuite/hashgraph-types
      • @hsuite/health
      • @hsuite/helpers
      • @hsuite/ipfs
      • @hsuite/smart-config
      • @hsuite/smart-network-types
      • @hsuite/smart-transaction-types
      • @hsuite/smartnode-sdk
      • @hsuite/snapshots
      • @hsuite/subscriptions-types
      • @hsuite/subscriptions
      • @hsuite/throttler-types
      • @hsuite/throttler
      • @hsuite/users-types
      • @hsuite/users
      • @hsuite/validators-types
  • General Documentation
    • Tokenomics
      • Tokenomics v1
      • Tokenomics V2
    • Smart Apps and Interaction
      • Subscription-Based Model
      • Token-Gate Model
    • The Smart Node Network
      • security-layer
        • Security Layer Integration
        • Setting Up Secure Clusters
        • Generating and Sharing Keys Collaboratively
        • Protecting Secrets with Shamir's Method
        • Managing Cluster Membership
        • Handling Node Expulsion and Replacement
        • Automating Responses to Network Changes & Key Rotation
        • Ensuring Continuous Operation and Recovery
      • Understanding Validators in Our System
        • Type of Validators Explained
    • What is a Smart Node?
  • Restful APIs Documentation
Powered by GitBook
On this page
  • Features
  • Installation
  • Peer Dependencies
  • Quick Start
  • API Reference
  • Health Check Endpoint
  • System Information Endpoint
  • Advanced Usage
  • Custom Health Checks
  • Monitoring Service Integration
  • Configuration Options
  • Performance Considerations
  • License
  1. HbarSuite Developer Documentation
  2. HSuite Libraries

@hsuite/health

A comprehensive health monitoring and system diagnostics library for NestJS applications. This library provides real-time monitoring of system resources, service health checks, and detailed performance metrics.

Features

  • System Health Monitoring

    • Real-time health status checks

    • Service availability verification

    • Resource utilization tracking

    • Performance metrics collection

  • Resource Metrics

    • CPU utilization and performance

    • Memory allocation and availability

    • Storage capacity and usage

    • Network traffic and bandwidth

  • Service Integration

    • MongoDB connection health

    • Redis cache monitoring

    • DAG network status

    • Microservice connectivity

  • Performance Optimization

    • Response caching

    • Threshold-based monitoring

    • Efficient resource usage

    • Real-time metrics updates

Installation

npm install @hsuite/health

Peer Dependencies

{
  "@nestjs/common": "^10.4.2",
  "@nestjs/core": "^10.4.2"
}

Quick Start

  1. Import the HealthModule in your application:

import { HealthModule } from '@hsuite/health';

@Module({
  imports: [
    HealthModule.forRoot({
      host: 'localhost',
      port: 6379,
      password: 'your-redis-password',
      db: 0
    })
  ]
})
export class AppModule {}
  1. Access health endpoints:

// Health check endpoint
GET /health/check

// Detailed system metrics
GET /health/infos

API Reference

Health Check Endpoint

GET /health/check

Performs a comprehensive system health check.

Response:

{
  status: 'ok' | 'error',
  info: {
    // Component-specific health information
    redis: { status: 'up' | 'down' },
    mongodb: { status: 'up' | 'down' },
    disk: { status: 'up' | 'down' }
  },
  error: {
    // Error details if any component is unhealthy
  },
  details: {
    // Detailed health metrics for each component
  }
}

System Information Endpoint

GET /health/infos

Retrieves detailed system metrics and resource utilization data.

Response:

{
  platform: string,    // Operating system platform
  release: string,     // OS version
  machine: string,     // Hardware identifier
  arch: string,        // CPU architecture
  uptime: number,      // System uptime in seconds
  cpu: {
    usage: number,     // CPU utilization percentage
    cpus: number,      // Number of CPU cores
    speed: number      // CPU clock speed in MHz
  },
  memory: {
    totalMemMb: number,        // Total memory in MB
    usedMemMb: number,         // Used memory in MB
    freeMemMb: number,         // Free memory in MB
    usedMemPercentage: number, // Memory usage percentage
    freeMemPercentage: number  // Free memory percentage
  },
  drive: {
    totalGb: string,        // Total storage in GB
    usedGb: string,         // Used storage in GB
    freeGb: string,         // Free storage in GB
    usedPercentage: string, // Storage usage percentage
    freePercentage: string  // Free storage percentage
  },
  network: {
    inputBytes: number,  // Total bytes received
    outputBytes: number  // Total bytes transmitted
  }
}

Advanced Usage

Custom Health Checks

The library supports custom health indicators for specialized monitoring needs:

@Injectable()
class CustomHealthIndicator extends HealthIndicator {
  async isHealthy(key: string): Promise<HealthIndicatorResult> {
    const isHealthy = // Your health check logic
    return this.getStatus(key, isHealthy);
  }
}

Monitoring Service Integration

Example of integrating health monitoring in a service:

@Injectable()
class MonitoringService {
  constructor(private healthService: HealthService) {}

  async monitorSystemHealth() {
    try {
      const health = await this.healthService.check();
      
      if (health.status === 'ok') {
        console.log('All systems operational');
        
        // Check individual components
        const { redis, mongodb, disk } = health.details;
        
        if (redis.status === 'up') {
          console.log('Cache service healthy');
        }
        
        if (mongodb.status === 'up') {
          console.log('Database connection stable');
        }
        
        if (disk.status === 'up') {
          console.log('Storage system normal');
        }
      }
    } catch (error) {
      console.error('Health check failed:', error.message);
      // Implement error handling and alerts
    }
  }

  async trackResourceUsage() {
    try {
      const metrics = await this.healthService.infos();
      
      // Monitor system resources
      if (metrics.cpu.usage > 90) {
        console.warn('High CPU utilization detected');
      }
      
      if (metrics.memory.freeMemPercentage < 10) {
        console.warn('Critical memory shortage');
      }
      
      if (parseInt(metrics.drive.freePercentage) < 15) {
        console.warn('Low disk space warning');
      }
      
      // Log system status
      console.log('System Metrics:', {
        platform: metrics.platform,
        uptime: this.formatUptime(metrics.uptime),
        cpu: `${metrics.cpu.usage}% (${metrics.cpu.cpus} cores)`,
        memory: `${metrics.memory.usedMemPercentage}% used`,
        disk: `${metrics.drive.freeGb}GB free`
      });
    } catch (error) {
      console.error('Metrics collection failed:', error.message);
      // Implement fallback mechanisms
    }
  }
}

Configuration Options

The HealthModule.forRoot() method accepts Redis configuration options:

interface RedisOptions {
  host: string;      // Redis server hostname
  port: number;      // Redis server port
  password?: string; // Redis authentication password
  db?: number;       // Redis database index
  tls?: boolean;     // Enable TLS/SSL encryption
  connectTimeout?: number;  // Connection timeout in ms
  enableReadyCheck?: boolean; // Enable Redis ready check
}

Performance Considerations

  • Health check responses are cached for 1 second to prevent excessive system load

  • Resource metrics are collected efficiently to minimize impact

  • Custom health indicators should implement appropriate caching

  • Consider implementing rate limiting for public endpoints

License

This library is part of the HSuite Enterprise platform and is subject to the HSuite Enterprise license agreement.


Built with ❤️ by the HbarSuite Team Copyright © 2024 HbarSuite. All rights reserved.

Previous@hsuite/hashgraph-typesNext@hsuite/helpers

Last updated 3 months ago