Xabaril / AspNetCore.Diagnostics.HealthChecks

Enterprise HealthChecks for ASP.NET Core Diagnostics Package
Apache License 2.0
4.11k stars 800 forks source link

Introduce async factories to Redis health check. #2305

Open mitchdenny opened 1 month ago

mitchdenny commented 1 month ago

What this PR does / why we need it:

This PR introduces variants of the AddRedis(...) method which takes async factories for connection string and connection multiplexer.

On the .NET Aspire team we are using these libraries to implement health check support for orchestrated resources. We use health checks in two scenarios. The first is inside an orchestrated service (e.g. a .NET Web API project) and the second is in the app host that does the orchestrating.

It is this second scenario that motivates this proposed change. Here is our current usage of this API in the Azure.Hosting.Redis package:

https://github.com/dotnet/aspire/blob/4e7e0de000bb83f824cca2773892a22b5da89245/src/Aspire.Hosting.Redis/RedisBuilderExtensions.cs#L36-L62

    public static IResourceBuilder<RedisResource> AddRedis(this IDistributedApplicationBuilder builder, [ResourceName] string name, int? port = null)
    {
        ArgumentNullException.ThrowIfNull(builder);

        var redis = new RedisResource(name);

        string? connectionString = null;

        builder.Eventing.Subscribe<ConnectionStringAvailableEvent>(redis, async (@event, ct) =>
        {
            connectionString = await redis.GetConnectionStringAsync(ct).ConfigureAwait(false);

            if (connectionString == null)
            {
                throw new DistributedApplicationException($"ConnectionStringAvailableEvent was published for the '{redis.Name}' resource but the connection string was null.");
            }
        });

        var healthCheckKey = $"{name}_check";
        builder.Services.AddHealthChecks().AddRedis(sp => connectionString ?? throw new InvalidOperationException("Connection string is unavailable"), name: healthCheckKey);

        return builder.AddResource(redis)
                      .WithEndpoint(port: port, targetPort: 6379, name: RedisResource.PrimaryEndpointName)
                      .WithImage(RedisContainerImageTags.Image, RedisContainerImageTags.Tag)
                      .WithImageRegistry(RedisContainerImageTags.Registry)
                      .WithHealthCheck(healthCheckKey);
    }

Notice that we make use of the existing non-async factory method for AddRedis(...). However for this to work we need to declare a variable in the outer scope called connectionString and then capture that variable in both an event handling callback to get the connection string which is only available AFTER the DI container has been created and is only available via an async call. We do it this way to avoid doing sync over async.

With the change in this PR we might be able to greatly simplify this code, down to the following:

    public static IResourceBuilder<RedisResource> AddRedis(this IDistributedApplicationBuilder builder, [ResourceName] string name, int? port = null)
    {
        ArgumentNullException.ThrowIfNull(builder);

        var redis = new RedisResource(name);

        var healthCheckKey = $"{name}_check";
        builder.Services.AddHealthChecks().AddRedis((sp, ct) => {
          var connectionString = await redis.GetConnectionStringAsync(ct).ConfigureAwait(false);
          return connectionString;
        });

        return builder.AddResource(redis)
                      .WithEndpoint(port: port, targetPort: 6379, name: RedisResource.PrimaryEndpointName)
                      .WithImage(RedisContainerImageTags.Image, RedisContainerImageTags.Tag)
                      .WithImageRegistry(RedisContainerImageTags.Registry)
                      .WithHealthCheck(healthCheckKey);
    }

Which issue(s) this PR fixes:

Please reference the issue this PR will close: #[issue number]

Special notes for your reviewer:

Does this PR introduce a user-facing change?:

Yes.

Please make sure you've completed the relevant tasks for this PR, out of the following list:

mitchdenny commented 1 month ago

@eerhardt @adamsitnik