< Summary

Information
Class: Anichron.API.Infrastructure.DatabaseUnavailableHandler
Assembly: Anichron.API
File(s): /home/runner/work/anichron/anichron/src/Anichron.API/Infrastructure/DatabaseUnavailableHandler.cs
Tag: 19_45211875487
Line coverage
100%
Covered lines: 18
Uncovered lines: 0
Coverable lines: 18
Total lines: 45
Line coverage: 100%
Branch coverage
100%
Covered branches: 8
Total branches: 8
Branch coverage: 100%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)100%11100%
TryHandleAsync()100%22100%
Unreachable(...)100%66100%

File(s)

/home/runner/work/anichron/anichron/src/Anichron.API/Infrastructure/DatabaseUnavailableHandler.cs

#LineLine coverage
 1using Anichron.API.Settings;
 2using Microsoft.AspNetCore.Diagnostics;
 3using Npgsql;
 4using static System.Globalization.CultureInfo;
 5
 6namespace Anichron.API.Infrastructure;
 7
 8/// <summary>
 9/// Answers a request that failed because the database cannot be reached with a 503 the client can
 10/// retry, and leaves every other exception to the server error.
 11/// </summary>
 12/// <param name="logger">Notes each request answered with the 503.</param>
 14613internal sealed partial class DatabaseUnavailableHandler(ILogger<DatabaseUnavailableHandler> logger) : IExceptionHandler
 14{
 15    private const string detail = "The service is temporarily unavailable. Try again shortly.";
 16
 17    public async ValueTask<bool> TryHandleAsync(HttpContext httpContext, Exception exception, CancellationToken cancella
 1018    {
 1019        if (Unreachable(exception) is not { } cause)
 320            return false;
 21
 722        Log.DatabaseUnreachable(logger, httpContext.Request.Method, httpContext.Request.Path, cause.Message);
 723        httpContext.Response.Headers.RetryAfter = AppDefaults.Database.RetryAfterSeconds.ToString(InvariantCulture);
 724        await ApiProblems.Problem(StatusCodes.Status503ServiceUnavailable, ErrorCodes.ServiceUnavailable, detail)
 725            .ExecuteAsync(httpContext);
 726        return true;
 1027    }
 28
 29    private static NpgsqlException? Unreachable(Exception? exception)
 1030    {
 2231        for (; exception is not null; exception = exception.InnerException)
 1332        {
 1333            if (exception is NpgsqlException { IsTransient: true } transient)
 734                return transient;
 635        }
 36
 337        return null;
 1038    }
 39
 40    private static partial class Log
 41    {
 42        [LoggerMessage(Level = LogLevel.Warning, Message = "{Method} {Path} answered 503: the database is unreachable ({
 43        public static partial void DatabaseUnreachable(ILogger logger, string method, string path, string reason);
 44    }
 45}