| | | 1 | | using Anichron.API.Settings; |
| | | 2 | | using Microsoft.AspNetCore.Diagnostics; |
| | | 3 | | using Npgsql; |
| | | 4 | | using static System.Globalization.CultureInfo; |
| | | 5 | | |
| | | 6 | | namespace 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> |
| | 146 | 13 | | internal 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 |
| | 10 | 18 | | { |
| | 10 | 19 | | if (Unreachable(exception) is not { } cause) |
| | 3 | 20 | | return false; |
| | | 21 | | |
| | 7 | 22 | | Log.DatabaseUnreachable(logger, httpContext.Request.Method, httpContext.Request.Path, cause.Message); |
| | 7 | 23 | | httpContext.Response.Headers.RetryAfter = AppDefaults.Database.RetryAfterSeconds.ToString(InvariantCulture); |
| | 7 | 24 | | await ApiProblems.Problem(StatusCodes.Status503ServiceUnavailable, ErrorCodes.ServiceUnavailable, detail) |
| | 7 | 25 | | .ExecuteAsync(httpContext); |
| | 7 | 26 | | return true; |
| | 10 | 27 | | } |
| | | 28 | | |
| | | 29 | | private static NpgsqlException? Unreachable(Exception? exception) |
| | 10 | 30 | | { |
| | 22 | 31 | | for (; exception is not null; exception = exception.InnerException) |
| | 13 | 32 | | { |
| | 13 | 33 | | if (exception is NpgsqlException { IsTransient: true } transient) |
| | 7 | 34 | | return transient; |
| | 6 | 35 | | } |
| | | 36 | | |
| | 3 | 37 | | return null; |
| | 10 | 38 | | } |
| | | 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 | | } |