Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
namespace HealthChecks.Azure.Messaging.EventGrid;

public sealed class AzureEventGridHealthCheck : IHealthCheck
{
private readonly EventGridPublisherClient _client;

public AzureEventGridHealthCheck(EventGridPublisherClient client)
{
_client = Guard.ThrowIfNull(client);
}

/// <inheritdoc />
public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
{
try
{
// Send a ping event to verify connectivity
var healthCheckEvent = new EventGridEvent(
"HealthCheck",
"HealthCheck.Ping",
"1.0",
new { Timestamp = DateTimeOffset.UtcNow });

await _client.SendEventAsync(healthCheckEvent, cancellationToken).ConfigureAwait(false);

return HealthCheckResult.Healthy();
}
catch (Exception ex)
{
return new HealthCheckResult(context.Registration.FailureStatus, exception: ex);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
namespace Microsoft.Extensions.DependencyInjection;

/// <summary>
/// Extension methods to configure <see cref="AzureEventGridHealthCheck"/>.
/// </summary>
public static class AzureEventGridHealthChecksBuilderExtensions
{
private const string NAME = "azure_event_grid";

/// <summary>
/// Add a health check for Azure Event Grid by registering <see cref="AzureEventGridHealthCheck"/> for given <paramref name="builder"/>.
/// </summary>
/// <param name="builder">The <see cref="IHealthChecksBuilder"/> to add <see cref="HealthCheckRegistration"/> to.</param>
/// <param name="clientFactory">
/// An optional factory to obtain <see cref="EventGridPublisherClient" /> instance.
/// When not provided, <see cref="EventGridPublisherClient" /> is simply resolved from <see cref="IServiceProvider"/>.
/// </param>
/// <param name="name">The health check name. Optional. If <c>null</c> the name 'azure_event_grid' will be used.</param>
/// <param name="failureStatus">
/// The <see cref="HealthStatus"/> that should be reported when the health check fails. Optional. If <c>null</c> then
/// the default status of <see cref="HealthStatus.Unhealthy"/> will be reported.
/// </param>
/// <param name="tags">A list of tags that can be used to filter sets of health checks. Optional.</param>
/// <param name="timeout">An optional <see cref="TimeSpan"/> representing the timeout of the check.</param>
/// <returns>The specified <paramref name="builder"/>.</returns>
public static IHealthChecksBuilder AddAzureEventGrid(
this IHealthChecksBuilder builder,
Func<IServiceProvider, EventGridPublisherClient>? clientFactory = default,
string? name = NAME,
HealthStatus? failureStatus = default,
IEnumerable<string>? tags = default,
TimeSpan? timeout = default)
{
return builder.Add(new HealthCheckRegistration(
name ?? NAME,
sp => new AzureEventGridHealthCheck(clientFactory?.Invoke(sp) ?? sp.GetRequiredService<EventGridPublisherClient>()),
failureStatus,
tags,
timeout));
}
}
9 changes: 9 additions & 0 deletions src/HealthChecks.Azure.Messaging.EventGrid/GlobalUsings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
global using System;
global using System.Threading;
global using System.Threading.Tasks;
global using System.Runtime.CompilerServices;

global using Azure.Messaging.EventGrid;

global using Microsoft.Extensions.DependencyInjection;
global using Microsoft.Extensions.Diagnostics.HealthChecks;
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<![CDATA[<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks>
<PackageTags>$(PackageTags);Azure;EventGrid</PackageTags>
<Description>HealthChecks.Azure.Messaging.EventGrid is the health check package for Azure Event Grid.</Description>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Azure.Messaging.EventGrid" />
<PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks" />
</ItemGroup>

</Project>]]>
51 changes: 51 additions & 0 deletions src/HealthChecks.Azure.Messaging.EventGrid/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# Azure Event Grid Health Check

This health check verifies the ability to communicate with [Azure Event Grid](https://azure.microsoft.com/services/event-grid/). It uses the provided [EventGridPublisherClient](https://learn.microsoft.com/dotnet/api/azure.messaging.eventgrid.eventgridpublisherclient) to send a ping event to verify connectivity.

## Implementation

The health check makes an actual call to Event Grid by sending a simple ping event. This verifies that:
1. The client is properly configured
2. The connection to Event Grid service is working
3. The topic exists and is accessible
4. The credentials are valid and not expired

## Setup

```csharp
public void ConfigureServices(IServiceCollection services)
{
// Register the EventGridPublisherClient
services.AddSingleton(sp =>
{
return new EventGridPublisherClient(
new Uri("https://<your-topic-endpoint>"),
new AzureKeyCredential("<your-access-key>"));
});

services
.AddHealthChecks()
.AddAzureEventGrid();
}
```

You can also register the health check by providing a factory method for the client:

```csharp
services
.AddHealthChecks()
.AddAzureEventGrid(sp =>
{
return new EventGridPublisherClient(
new Uri("https://<your-topic-endpoint>"),
new AzureKeyCredential("<your-access-key>"));
});
```

## Parameters

- `clientFactory`: An optional factory to obtain the EventGridPublisherClient instance. When not provided, EventGridPublisherClient is resolved from IServiceProvider.
- `name`: The health check name. Optional. If null the name 'azure_event_grid' will be used.
- `failureStatus`: The HealthStatus that should be reported when the health check fails. Optional. If null then the default status of HealthStatus.Unhealthy will be reported.
- `tags`: A list of tags that can be used to filter sets of health checks.
- `timeout`: An optional TimeSpan representing the timeout of the check.
15 changes: 15 additions & 0 deletions src/HealthChecks.Azure.Messaging.EventGrid/Utils/Guard.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
namespace HealthChecks.Azure.Messaging.EventGrid;

internal static class Guard
{
public static T ThrowIfNull<T>(T value, [CallerArgumentExpression(nameof(value))] string? parameterName = null)
where T : class
{
if (value is null)
{
throw new ArgumentNullException(parameterName);
}

return value;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
using Azure.Identity;
using Azure.Messaging.EventGrid;

namespace HealthChecks.Azure.Messaging.EventGrid.Tests;

public class EventGridConformanceTests : ConformanceTests<EventGridPublisherClient, AzureEventGridHealthCheck, UnusedOptions>
{
protected override IHealthChecksBuilder AddHealthCheck(IHealthChecksBuilder builder, Func<IServiceProvider, EventGridPublisherClient>? clientFactory = null, Func<IServiceProvider, UnusedOptions>? optionsFactory = null, string? healthCheckName = null, HealthStatus? failureStatus = null, IEnumerable<string>? tags = null, TimeSpan? timeout = null)
=> builder.AddAzureEventGrid(clientFactory, healthCheckName, failureStatus, tags, timeout);

protected override EventGridPublisherClient CreateClientForNonExistingEndpoint()
=> new(new Uri("https://non-existing-topic.region.eventgrid.azure.net"), new AzureCliCredential());

protected override AzureEventGridHealthCheck CreateHealthCheck(EventGridPublisherClient client, UnusedOptions? options)
=> new(client);

protected override UnusedOptions CreateHealthCheckOptions()
=> new();
}

// AzureEventGridHealthCheck does not use any options, the type exists only to meet ConformanceTests<,,> criteria
public sealed class UnusedOptions
{
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
global using System;
global using System.Threading;
global using System.Threading.Tasks;
global using System.Collections.Generic;

global using Microsoft.Extensions.DependencyInjection;
global using Microsoft.Extensions.Diagnostics.HealthChecks;

global using HealthChecks.Tests.Common;
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<![CDATA[<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<IsPackable>false</IsPackable>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Azure.Identity" />
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="PublicApiGenerator" />
<PackageReference Include="Shouldly" />
<PackageReference Include="xunit" />
<PackageReference Include="xunit.runner.visualstudio">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\src\HealthChecks.Azure.Messaging.EventGrid\HealthChecks.Azure.Messaging.EventGrid.csproj" />
<ProjectReference Include="..\HealthChecks.Tests.Common\HealthChecks.Tests.Common.csproj" />
</ItemGroup>

</Project>]]>
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
namespace HealthChecks.Azure.Messaging.EventGrid
{
public sealed class AzureEventGridHealthCheck : Microsoft.Extensions.Diagnostics.HealthChecks.IHealthCheck
{
public AzureEventGridHealthCheck(Azure.Messaging.EventGrid.EventGridPublisherClient client) { }
public System.Threading.Tasks.Task<Microsoft.Extensions.Diagnostics.HealthChecks.HealthCheckResult> CheckHealthAsync(Microsoft.Extensions.Diagnostics.HealthChecks.HealthCheckContext context, System.Threading.CancellationToken cancellationToken = default) { }
}
}
namespace Microsoft.Extensions.DependencyInjection
{
public static class AzureEventGridHealthChecksBuilderExtensions
{
public static Microsoft.Extensions.DependencyInjection.IHealthChecksBuilder AddAzureEventGrid(this Microsoft.Extensions.DependencyInjection.IHealthChecksBuilder builder, System.Func<System.IServiceProvider, Azure.Messaging.EventGrid.EventGridPublisherClient>? clientFactory = null, string? name = "azure_event_grid", Microsoft.Extensions.Diagnostics.HealthChecks.HealthStatus? failureStatus = default, System.Collections.Generic.IEnumerable<string>? tags = null, System.TimeSpan? timeout = default) { }
}
}