Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce async factories to Redis health check. #2305

Open
wants to merge 3 commits into
base: master
Choose a base branch
from

Conversation

mitchdenny
Copy link

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:

  • Code compiles correctly
  • Created/updated tests
  • Unit tests passing
  • End-to-end tests passing
  • Extended the documentation
  • Provided sample for the feature

@mitchdenny
Copy link
Author

@eerhardt @adamsitnik

Directory.Build.props Outdated Show resolved Hide resolved
src/HealthChecks.Redis/RedisHealthCheck.cs Outdated Show resolved Hide resolved
/// <returns>The specified <paramref name="builder"/>.</returns>
public static IHealthChecksBuilder AddRedis(
this IHealthChecksBuilder builder,
Func<IServiceProvider, CancellationToken, Task<string?>> connectionStringFactory,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This overload feels weird to me. It is too specific to the Aspire use case.

If you need to do something async, I think you should create the IConnectionMultiplexer asynchronously. Getting the connection string asynchronously isn't very common.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure if delayed acquisition of connection strings is Aspire specific. It certainly impacts Aspire, but there are plenty of times that the connection string is not immediately available (particularly in multi-tenant scenarios).

@@ -9,14 +9,19 @@ namespace HealthChecks.Redis;
/// </summary>
public class RedisHealthCheck : IHealthCheck
{
private static readonly ConcurrentDictionary<string, IConnectionMultiplexer> _connections = new();
private readonly string? _redisConnectionString;
private static readonly ConcurrentDictionary<Func<CancellationToken, Task<string?>>, IConnectionMultiplexer> _connections = new();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this caching now broken if I create multiple RedisHealthCheck instances with the same connection string value? They each will get a different delegate instance now, where before it was keyed off the actual string value.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants