Skip to content
Merged
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
2 changes: 2 additions & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
<PackageVersion Include="DuckDB.NET.Data" Version="1.4.1" />
<PackageVersion Include="Elastic.Clients.Elasticsearch" Version="9.2.0" />
<PackageVersion Include="FirebirdSql.Data.FirebirdClient" Version="10.3.3" />
<PackageVersion Include="Google.Cloud.Firestore" Version="3.10.0" />
<PackageVersion Include="Keycloak.Net.Core" Version="1.0.37" />
<PackageVersion Include="LiteDB" Version="5.0.21" />
<PackageVersion Include="Microsoft.ApplicationInsights" Version="2.23.0" />
Expand Down Expand Up @@ -84,6 +85,7 @@
<PackageVersion Include="Testcontainers.Db2" Version="$(VersionTestContainers)" />
<PackageVersion Include="Testcontainers.Elasticsearch" Version="$(VersionTestContainers)" />
<PackageVersion Include="Testcontainers.FirebirdSql" Version="$(VersionTestContainers)" />
<PackageVersion Include="Testcontainers.Firestore" Version="$(VersionTestContainers)" />
<PackageVersion Include="Testcontainers.Kafka" Version="$(VersionTestContainers)" />
<PackageVersion Include="Testcontainers.Keycloak" Version="$(VersionTestContainers)" />
<PackageVersion Include="Testcontainers.LocalStack" Version="$(VersionTestContainers)" />
Expand Down
1 change: 1 addition & 0 deletions HealthChecks.slnx
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
<Project Path="src/NetEvolve.HealthChecks.DuckDB/NetEvolve.HealthChecks.DuckDB.csproj" />
<Project Path="src/NetEvolve.HealthChecks.Elasticsearch/NetEvolve.HealthChecks.Elasticsearch.csproj" />
<Project Path="src/NetEvolve.HealthChecks.Firebird/NetEvolve.HealthChecks.Firebird.csproj" />
<Project Path="src/NetEvolve.HealthChecks.GCP.Firestore/NetEvolve.HealthChecks.GCP.Firestore.csproj" />
<Project Path="src/NetEvolve.HealthChecks.Http/NetEvolve.HealthChecks.Http.csproj" />
<Project Path="src/NetEvolve.HealthChecks.Keycloak/NetEvolve.HealthChecks.Keycloak.csproj" />
<Project Path="src/NetEvolve.HealthChecks.LiteDB/NetEvolve.HealthChecks.LiteDB.csproj" />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
namespace NetEvolve.HealthChecks.GCP.Firestore;

using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using NetEvolve.HealthChecks.Abstractions;

/// <summary>
/// Extension methods for registering Firestore health checks.
/// </summary>
public static class DependencyInjectionExtensions
{
private static readonly string[] _defaultTags = ["firestore", "gcp"];

/// <summary>
/// Adds a health check for Google Cloud Firestore.
/// </summary>
/// <param name="builder">The <see cref="IHealthChecksBuilder"/>.</param>
/// <param name="name">The name of the health check.</param>
/// <param name="options">An optional action to configure the <see cref="FirestoreOptions"/>.</param>
/// <param name="tags">An optional list of tags to associate with the health check.</param>
/// <returns>The <see cref="IHealthChecksBuilder"/> so that additional calls can be chained.</returns>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="builder"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="name"/> is <see langword="null"/> or empty.</exception>
/// <exception cref="ArgumentException">Thrown when <paramref name="name"/> is already in use.</exception>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="tags"/> is <see langword="null"/>.</exception>
public static IHealthChecksBuilder AddFirestore(
[NotNull] this IHealthChecksBuilder builder,
[NotNull] string name,
Action<FirestoreOptions>? options = null,
params string[] tags
)
{
ArgumentNullException.ThrowIfNull(builder);
ArgumentException.ThrowIfNullOrEmpty(name);
ArgumentNullException.ThrowIfNull(tags);

if (!builder.IsServiceTypeRegistered<FirestoreHealthCheckMarker>())
{
_ = builder
.Services.AddSingleton<FirestoreHealthCheckMarker>()
.AddSingleton<FirestoreHealthCheck>()
.ConfigureOptions<FirestoreOptionsConfigure>();
}

builder.ThrowIfNameIsAlreadyUsed<FirestoreHealthCheck>(name);

if (options is not null)
{
_ = builder.Services.Configure(name, options);
}

return builder.AddCheck<FirestoreHealthCheck>(
name,
HealthStatus.Unhealthy,
_defaultTags.Union(tags, StringComparer.OrdinalIgnoreCase)
);
}

private sealed partial class FirestoreHealthCheckMarker;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
namespace NetEvolve.HealthChecks.GCP.Firestore;

using System;
using System.Threading;
using System.Threading.Tasks;
using global::Google.Cloud.Firestore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Options;
using NetEvolve.Extensions.Tasks;
using NetEvolve.HealthChecks.Abstractions;

internal sealed class FirestoreHealthCheck : ConfigurableHealthCheckBase<FirestoreOptions>
{
private readonly IServiceProvider _serviceProvider;

public FirestoreHealthCheck(IOptionsMonitor<FirestoreOptions> optionsMonitor, IServiceProvider serviceProvider)
: base(optionsMonitor) => _serviceProvider = serviceProvider;

protected override async ValueTask<HealthCheckResult> ExecuteHealthCheckAsync(
string name,
HealthStatus failureStatus,
FirestoreOptions options,
CancellationToken cancellationToken
)
{
var client = string.IsNullOrWhiteSpace(options.KeyedService)
? _serviceProvider.GetRequiredService<FirestoreDb>()
: _serviceProvider.GetRequiredKeyedService<FirestoreDb>(options.KeyedService);

// Use a simple operation to check if the database is accessible
// Creating a document reference is a local operation that validates the client is configured
var testCollection = client.Collection("healthcheck");
var testDoc = testCollection.Document("test");

// Attempt a lightweight operation with timeout
var (isValid, _) = await testDoc
.GetSnapshotAsync(cancellationToken)
.WithTimeoutAsync(options.Timeout, cancellationToken)
.ConfigureAwait(false);

return HealthCheckState(isValid, name);
}
}
23 changes: 23 additions & 0 deletions src/NetEvolve.HealthChecks.GCP.Firestore/FirestoreOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
namespace NetEvolve.HealthChecks.GCP.Firestore;

/// <summary>
/// Options for <see cref="FirestoreHealthCheck"/>
/// </summary>
public sealed record FirestoreOptions
{
/// <summary>
/// Gets or sets the timeout in milliseconds to use when executing tasks against the Firestore database.
/// </summary>
/// <value>
/// The timeout in milliseconds. Default value is 100 milliseconds.
/// </value>
public int Timeout { get; set; } = 100;

/// <summary>
/// Gets or sets the keyed service name for retrieving the <see cref="Google.Cloud.Firestore.FirestoreDb"/> instance.
/// </summary>
/// <value>
/// The keyed service name, or <c>null</c> if using the default service registration.
/// </value>
public string? KeyedService { get; set; }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
namespace NetEvolve.HealthChecks.GCP.Firestore;

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using static Microsoft.Extensions.Options.ValidateOptionsResult;

internal sealed class FirestoreOptionsConfigure
: IConfigureNamedOptions<FirestoreOptions>,
IValidateOptions<FirestoreOptions>
{
private readonly IConfiguration _configuration;

public FirestoreOptionsConfigure(IConfiguration configuration) => _configuration = configuration;

public void Configure(string? name, FirestoreOptions options)
{
ArgumentNullException.ThrowIfNull(name);

_configuration.Bind($"HealthChecks:GCP:Firestore:{name}", options);
}

public void Configure(FirestoreOptions options) => Configure(Options.DefaultName, options);

public ValidateOptionsResult Validate(string? name, FirestoreOptions options)
{
if (string.IsNullOrWhiteSpace(name))
{
return Fail("The name cannot be null or whitespace.");
}

if (options is null)
{
return Fail("The option cannot be null.");
}

if (options.Timeout < Timeout.Infinite)
{
return Fail("The timeout value must be a positive number in milliseconds or -1 for an infinite timeout.");
}

return Success;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>$(_ProjectTargetFrameworks)</TargetFrameworks>
<Description>Contains HealthChecks for Google Cloud Platform Firestore, based on the nuget package `Google.Cloud.Firestore`.</Description>
<PackageTags>$(PackageTags);gcp;google;firestore</PackageTags>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Google.Cloud.Firestore" />
<PackageReference Include="NetEvolve.Extensions.Tasks" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\NetEvolve.HealthChecks.Abstractions\NetEvolve.HealthChecks.Abstractions.csproj" />
</ItemGroup>
</Project>
78 changes: 78 additions & 0 deletions src/NetEvolve.HealthChecks.GCP.Firestore/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
# NetEvolve.HealthChecks.GCP.Firestore

[![NuGet](https://img.shields.io/nuget/v/NetEvolve.HealthChecks.GCP.Firestore?logo=nuget)](https://www.nuget.org/packages/NetEvolve.HealthChecks.GCP.Firestore/)
[![NuGet](https://img.shields.io/nuget/dt/NetEvolve.HealthChecks.GCP.Firestore?logo=nuget)](https://www.nuget.org/packages/NetEvolve.HealthChecks.GCP.Firestore/)

This package provides a health check for Google Cloud Platform Firestore, based on the [Google.Cloud.Firestore](https://www.nuget.org/packages/Google.Cloud.Firestore/) package. The main purpose is to check if the Firestore database is available and accessible.

:bulb: This package is available for .NET 8.0 and later.

## Installation
To use this package, you need to add the package to your project. You can do this by using the NuGet package manager or by using the dotnet CLI.
```powershell
dotnet add package NetEvolve.HealthChecks.GCP.Firestore
```

## Health Check - Firestore Liveness
The health check is a liveness check. It checks if the Firestore database is available and accessible.
If the query needs longer than the configured timeout, the health check will return `Degraded`.
If the query fails, for whatever reason, the health check will return `Unhealthy`.

### Usage
After adding the package, you need to import the namespace and add the health check to the health check builder.
```csharp
using NetEvolve.HealthChecks.GCP.Firestore;
```
Therefore, you can use two different approaches. In both approaches you have to provide a name for the health check.

### Parameters
- `name`: The name of the health check. The name is used to identify the configuration object. It is required and must be unique within the application.
- `options`: The configuration options for the health check. If you don't provide any options, the health check will use the configuration based approach.
- `tags`: The tags for the health check. The tags `firestore` and `gcp` are always used as default and combined with the user input. You can provide additional tags to group or filter the health checks.

### Variant 1: Configuration based
The first one is to use the configuration based approach. This approach is recommended if you have multiple Firestore instances to check.
```csharp
var builder = services.AddHealthChecks();

builder.AddFirestore("<name>");
```

The configuration looks like this:
```json
{
..., // other configuration
"HealthChecks": {
"GCP": {
"Firestore": {
"<name>": {
"Timeout": <timeout> // optional, default is 100 milliseconds
}
}
}
}
}
```

### Variant 2: Builder based
The second approach is to use the builder based approach. This approach is recommended if you only have one Firestore instance to check or dynamic programmatic values.
```csharp
var builder = services.AddHealthChecks();

builder.AddFirestore("<name>", options =>
{
options.Timeout = <timeout>; // optional, default is 100 milliseconds
});
```

### :bulb: You can always provide tags to all health checks, for grouping or filtering.

```csharp
var builder = services.AddHealthChecks();

builder.AddFirestore("<name>", options => ..., "firestore", "gcp");
```

## License

This project is licensed under the MIT License - see the [LICENSE](https://raw.githubusercontent.com/dailydevops/healthchecks/refs/heads/main/LICENSE) file for details.
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ private static Architecture LoadArchitecture()
typeof(Azure.Queues.QueueClientAvailableHealthCheck).Assembly,
typeof(Azure.ServiceBus.ServiceBusQueueHealthCheck).Assembly,
typeof(Azure.Tables.TableClientAvailableHealthCheck).Assembly,
// GCP
typeof(GCP.Firestore.FirestoreHealthCheck).Assembly,
// others
typeof(Abstractions.HealthCheckBase).Assembly,
typeof(ArangoDb.ArangoDbHealthCheck).Assembly,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
<ProjectReference Include="..\..\src\NetEvolve.HealthChecks.DuckDB\NetEvolve.HealthChecks.DuckDB.csproj" />
<ProjectReference Include="..\..\src\NetEvolve.HealthChecks.Elasticsearch\NetEvolve.HealthChecks.Elasticsearch.csproj" />
<ProjectReference Include="..\..\src\NetEvolve.HealthChecks.Firebird\NetEvolve.HealthChecks.Firebird.csproj" />
<ProjectReference Include="..\..\src\NetEvolve.HealthChecks.GCP.Firestore\NetEvolve.HealthChecks.GCP.Firestore.csproj" />
<ProjectReference Include="..\..\src\NetEvolve.HealthChecks.Http\NetEvolve.HealthChecks.Http.csproj" />
<ProjectReference Include="..\..\src\NetEvolve.HealthChecks.Keycloak\NetEvolve.HealthChecks.Keycloak.csproj" />
<ProjectReference Include="..\..\src\NetEvolve.HealthChecks.LiteDB\NetEvolve.HealthChecks.LiteDB.csproj" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ await RunAndVerify(
options.TopicName = topicName;
options.Subscription = subcription.SubscriptionArn;
options.Mode = CreationMode.BasicAuthentication;
options.Timeout = 10000; // Set a reasonable timeout
}
);
},
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
namespace NetEvolve.HealthChecks.Tests.Integration.GCP.Firestore;

using System;
using System.Threading.Tasks;
using global::Google.Cloud.Firestore;
using global::Google.Cloud.Firestore.V1;
using global::Grpc.Core;
using Microsoft.Extensions.Logging.Abstractions;
using Testcontainers.Firestore;
using TUnit.Core.Interfaces;

public sealed class FirestoreDatabase : IAsyncInitializer, IAsyncDisposable
{
private readonly FirestoreContainer _container = new FirestoreBuilder().WithLogger(NullLogger.Instance).Build();

private FirestoreDb? _database;

public const string ProjectId = "test-project";

public FirestoreDb Database => _database ?? throw new InvalidOperationException("Database not initialized");

public async ValueTask DisposeAsync() => await _container.DisposeAsync().ConfigureAwait(false);

public async Task InitializeAsync()
{
await _container.StartAsync().ConfigureAwait(false);

// Parse endpoint to get host:port
var fullEndpoint = _container.GetEmulatorEndpoint();
var uri = new Uri(fullEndpoint);
var hostPort = $"{uri.Host}:{uri.Port}";

// Create Firestore client configured for emulator
var clientBuilder = new FirestoreClientBuilder
{
Endpoint = hostPort,
ChannelCredentials = ChannelCredentials.Insecure,
};

var client = await clientBuilder.BuildAsync().ConfigureAwait(false);
_database = await FirestoreDb.CreateAsync(ProjectId, client).ConfigureAwait(false);
}
}
Loading
Loading