Skip to content

Custom Health Checks

Eduardo Fonseca edited this page Jul 25, 2024 · 2 revisions

FairPlayTube Health Check Tutorial

This tutorial explains how to implement a health check class for the FairPlayTube component of the FairPlayCombined application. The health check ensures certain tables in the database have entries, indicating the system is functioning properly.

FairPlayTubeHealthCheck Class

using FairPlayCombined.DataAccess.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Diagnostics.HealthChecks;

namespace FairPlayTube.HealthChecks
{
    public class FairPlayTubeHealthCheck(IDbContextFactory<FairPlayCombinedDbContext> dbContextFactory,
        ILogger<FairPlayTubeHealthCheck> logger) : IHealthCheck
    {
        public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
        {
            try
            {
                logger.LogInformation("Running health checks for: {HealthCheckName}",
                    nameof(FairPlayTubeHealthCheck));
                var dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
                var roles = await dbContext.AspNetRoles.ToArrayAsync(cancellationToken);
                if (roles?.Length == 0)
                {
                    return HealthCheckResult.Unhealthy(description: "Missing roles");
                }
                var videoIndexStatuses = await dbContext.VideoIndexStatus.ToArrayAsync(cancellationToken);
                if (videoIndexStatuses?.Length == 0)
                {
                    return HealthCheckResult.Unhealthy(description: "Missing video index statuses");
                }
                var videoVisibilities = await dbContext.VideoVisibility.ToArrayAsync(cancellationToken);
                if (videoVisibilities?.Length == 0)
                {
                    return HealthCheckResult.Unhealthy(description: "Missing video visibilities");
                }
                var data = new Dictionary<string, object>()
                {
                    {nameof(roles), roles! },
                    {nameof(videoIndexStatuses), videoIndexStatuses! },
                    {nameof(videoVisibilities), videoVisibilities! }
                };
                return HealthCheckResult.Healthy(data: data.AsReadOnly());
            }
            catch (Exception ex)
            {
                return HealthCheckResult.Unhealthy(context.Registration.FailureStatus.ToString(),
                    exception: ex);
            }
        }
    }
}

Explanation

Namespaces

The using statements include necessary namespaces:

  • FairPlayCombined.DataAccess.Data: Contains the FairPlayCombinedDbContext which is the database context for FairPlayCombined.
  • Microsoft.EntityFrameworkCore: Provides APIs for working with the Entity Framework Core, an ORM for database interactions.
  • Microsoft.Extensions.Diagnostics.HealthChecks: Provides interfaces and classes for implementing health checks.

Namespace Declaration

namespace FairPlayTube.HealthChecks

Defines a namespace for organizing classes related to health checks within the FairPlayTube application.

Class Declaration

public class FairPlayTubeHealthCheck(IDbContextFactory<FairPlayCombinedDbContext> dbContextFactory,
    ILogger<FairPlayTubeHealthCheck> logger) : IHealthCheck

Defines a public class FairPlayTubeHealthCheck that implements the IHealthCheck interface. It has a constructor that takes two parameters:

  • IDbContextFactory<FairPlayCombinedDbContext> dbContextFactory: A factory for creating instances of FairPlayCombinedDbContext.
  • ILogger<FairPlayTubeHealthCheck> logger: A logger for logging information.

Health Check Method

public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)

Implements the CheckHealthAsync method required by the IHealthCheck interface. This method performs the health check logic and returns a HealthCheckResult.

Health Check Logic

The method performs the following steps:

  1. Logs the start of the health check.
  2. Creates a FairPlayCombinedDbContext instance using the factory.
  3. Queries the AspNetRoles table and checks if it has any entries. If not, returns HealthCheckResult.Unhealthy with a description.
  4. Queries the VideoIndexStatus table and checks if it has any entries. If not, returns HealthCheckResult.Unhealthy with a description.
  5. Queries the VideoVisibility table and checks if it has any entries. If not, returns HealthCheckResult.Unhealthy with a description.
  6. If all checks pass, it creates a dictionary with the retrieved data and returns HealthCheckResult.Healthy with this data.
  7. If an exception occurs, it catches the exception and returns HealthCheckResult.Unhealthy with the failure status and exception details.

Class Closing

This closes the class and the namespace.


By following this tutorial, you can implement a health check class to monitor the health of your FairPlayTube component by ensuring that essential tables in your database have entries.
Clone this wiki locally