2022-02-14 01:51:37 +01:00
|
|
|
using System.Net;
|
2026-10-03 15:26:21 +02:00
|
|
|
using System.Net.Http.Json;
|
|
|
|
|
|
|
|
|
|
using collAnon.Client.Services;
|
|
|
|
|
|
|
|
|
|
using decePubClient.Helpers;
|
2022-02-14 01:51:37 +01:00
|
|
|
using decePubClient.Models;
|
|
|
|
|
|
|
|
|
|
namespace decePubClient.Services
|
|
|
|
|
{
|
2026-10-03 15:26:21 +02:00
|
|
|
/// <summary>
|
|
|
|
|
/// Requests to the PrivaPub API through the "default" HttpClient (AppConfiguration.ApiBaseAddress), at three
|
|
|
|
|
/// authentication levels: Get/Post/Delete need a valid token and sign out on 401, *Anon add the token when there is
|
|
|
|
|
/// one, *TotallyAnon never send it. Nothing throws: a failure comes back as a response carrying an invalid WebResult
|
|
|
|
|
/// (SUtility.ClassifiedFailure, read with ExtensionMethods.ReadWebResult), a cancelled request as HTTP 410.
|
|
|
|
|
/// With retryOnError, 408/429/502/503/504 and transport errors are retried after 1, 2, 4, 8, 16 and 29 seconds, then
|
|
|
|
|
/// every 60, plus jitter, for at most 10 minutes.
|
|
|
|
|
/// </summary>
|
2022-02-14 01:51:37 +01:00
|
|
|
public interface IHttpService
|
|
|
|
|
{
|
2026-10-03 15:26:21 +02:00
|
|
|
Task<HttpResponseMessage> Get(string uri, string[] queryParams = default, bool retryOnError = false, CancellationToken cancellationToken = default);
|
|
|
|
|
|
|
|
|
|
Task<HttpResponseMessage> GetAnon(string uri, string[] queryParams = default, bool retryOnError = false, CancellationToken cancellationToken = default);
|
2022-02-14 01:51:37 +01:00
|
|
|
|
2026-10-03 15:26:21 +02:00
|
|
|
Task<HttpResponseMessage> GetTotallyAnon(string uri, string[] queryParams = default, bool retryOnError = false,
|
|
|
|
|
CancellationToken cancellationToken = default);
|
2022-02-14 01:51:37 +01:00
|
|
|
|
2026-10-03 15:26:21 +02:00
|
|
|
Task<HttpResponseMessage> Post(string uri, object payload = default, bool retryOnError = false, CancellationToken cancellationToken = default);
|
2022-02-14 01:51:37 +01:00
|
|
|
|
2026-10-03 15:26:21 +02:00
|
|
|
Task<HttpResponseMessage> PostAnon(string uri, object payload = default, bool retryOnError = false, CancellationToken cancellationToken = default);
|
2022-02-14 01:51:37 +01:00
|
|
|
|
2026-10-03 15:26:21 +02:00
|
|
|
Task<HttpResponseMessage> PostTotallyAnon(string uri, object payload = default, bool retryOnError = false,
|
|
|
|
|
CancellationToken cancellationToken = default);
|
|
|
|
|
|
|
|
|
|
Task<HttpResponseMessage> Delete(string uri, string[] queryParams = default, object payload = default, bool retryOnError = false,
|
|
|
|
|
CancellationToken cancellationToken = default);
|
|
|
|
|
|
|
|
|
|
Task<HttpResponseMessage> DeleteTotallyAnon(string uri, string[] queryParams = default, object payload = default, bool retryOnError = false,
|
|
|
|
|
CancellationToken cancellationToken = default);
|
2022-02-14 01:51:37 +01:00
|
|
|
}
|
|
|
|
|
|
2026-10-03 15:26:21 +02:00
|
|
|
public class HttpService(IHttpClientFactory httpClientFactory, TokenAuthStateProvider authStateProvider, AppStatusService statusService,
|
|
|
|
|
ILoggingService logger, CoalescingStringLocalizer localizer) : IHttpService
|
2022-02-14 01:51:37 +01:00
|
|
|
{
|
2026-10-03 15:26:21 +02:00
|
|
|
static readonly int[] RetryRampUpDelaysMs = [1_000, 2_000, 4_000, 8_000, 16_000, 29_000];
|
|
|
|
|
const int RetryIndefiniteDelayMs = 60_000;
|
|
|
|
|
static readonly TimeSpan RetryDeadline = TimeSpan.FromMinutes(10);
|
|
|
|
|
static readonly int[] RetryableStatusCodes = [408, 429, 502, 503, 504];
|
2022-02-14 01:51:37 +01:00
|
|
|
|
2026-10-03 15:26:21 +02:00
|
|
|
readonly HttpClient httpClient = httpClientFactory.CreateClient("default");
|
|
|
|
|
|
|
|
|
|
public Task<HttpResponseMessage> Get(string uri, string[] queryParams = default, bool retryOnError = false, CancellationToken cancellationToken = default) =>
|
|
|
|
|
Send(nameof(Get), () => BuildRequest(HttpMethod.Get, uri, queryParams: queryParams), SendAuthRequest, retryOnError, cancellationToken);
|
|
|
|
|
|
|
|
|
|
public Task<HttpResponseMessage> GetAnon(string uri, string[] queryParams = default, bool retryOnError = false, CancellationToken cancellationToken = default) =>
|
|
|
|
|
Send(nameof(GetAnon), () => BuildRequest(HttpMethod.Get, uri, queryParams: queryParams), SendAuthIfAvailableRequest, retryOnError,
|
|
|
|
|
cancellationToken);
|
|
|
|
|
|
|
|
|
|
public Task<HttpResponseMessage> GetTotallyAnon(string uri, string[] queryParams = default, bool retryOnError = false,
|
|
|
|
|
CancellationToken cancellationToken = default) =>
|
|
|
|
|
Send(nameof(GetTotallyAnon), () => BuildRequest(HttpMethod.Get, uri, queryParams: queryParams), httpClient.SendAsync, retryOnError,
|
|
|
|
|
cancellationToken);
|
|
|
|
|
|
|
|
|
|
public Task<HttpResponseMessage> Post(string uri, object payload = default, bool retryOnError = false, CancellationToken cancellationToken = default) =>
|
|
|
|
|
Send(nameof(Post), () => BuildRequest(HttpMethod.Post, uri, payload, forceContent: true), SendAuthRequest, retryOnError, cancellationToken);
|
2022-02-14 01:51:37 +01:00
|
|
|
|
2026-10-03 15:26:21 +02:00
|
|
|
public Task<HttpResponseMessage> PostAnon(string uri, object payload = default, bool retryOnError = false, CancellationToken cancellationToken = default) =>
|
|
|
|
|
Send(nameof(PostAnon), () => BuildRequest(HttpMethod.Post, uri, payload, forceContent: true), SendAuthIfAvailableRequest, retryOnError,
|
|
|
|
|
cancellationToken);
|
|
|
|
|
|
|
|
|
|
public Task<HttpResponseMessage> PostTotallyAnon(string uri, object payload = default, bool retryOnError = false,
|
|
|
|
|
CancellationToken cancellationToken = default) =>
|
|
|
|
|
Send(nameof(PostTotallyAnon), () => BuildRequest(HttpMethod.Post, uri, payload, forceContent: true), httpClient.SendAsync, retryOnError,
|
|
|
|
|
cancellationToken);
|
|
|
|
|
|
|
|
|
|
public Task<HttpResponseMessage> Delete(string uri, string[] queryParams = default, object payload = default, bool retryOnError = false,
|
|
|
|
|
CancellationToken cancellationToken = default) =>
|
|
|
|
|
Send(nameof(Delete), () => BuildRequest(HttpMethod.Delete, uri, payload, queryParams), SendAuthRequest, retryOnError, cancellationToken);
|
|
|
|
|
|
|
|
|
|
public Task<HttpResponseMessage> DeleteTotallyAnon(string uri, string[] queryParams = default, object payload = default, bool retryOnError = false,
|
|
|
|
|
CancellationToken cancellationToken = default) =>
|
|
|
|
|
Send(nameof(DeleteTotallyAnon), () => BuildRequest(HttpMethod.Delete, uri, payload, queryParams), httpClient.SendAsync, retryOnError,
|
|
|
|
|
cancellationToken);
|
|
|
|
|
|
|
|
|
|
async Task<HttpResponseMessage> Send(string caller, Func<HttpRequestMessage> requestFactory,
|
|
|
|
|
Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> send, bool retryOnError, CancellationToken cancellationToken)
|
2022-02-14 01:51:37 +01:00
|
|
|
{
|
2026-10-03 15:26:21 +02:00
|
|
|
var deadline = DateTime.UtcNow + RetryDeadline;
|
|
|
|
|
var attempt = 0;
|
|
|
|
|
while (true)
|
2022-02-14 01:51:37 +01:00
|
|
|
{
|
2026-10-03 15:26:21 +02:00
|
|
|
// A request message can be sent once, so every attempt builds its own.
|
|
|
|
|
var request = requestFactory();
|
|
|
|
|
var where = $"{nameof(HttpService)}.{caller}:{request.RequestUri?.OriginalString}";
|
|
|
|
|
var failure = default(string);
|
|
|
|
|
var transportException = default(Exception);
|
|
|
|
|
try
|
2022-02-14 01:51:37 +01:00
|
|
|
{
|
2026-10-03 15:26:21 +02:00
|
|
|
var response = await send(request, cancellationToken);
|
|
|
|
|
var status = (int)response.StatusCode;
|
|
|
|
|
if (!retryOnError || !RetryableStatusCodes.Contains(status))
|
|
|
|
|
return status > 499 ? ServerError(response) : response;
|
2022-02-14 01:51:37 +01:00
|
|
|
|
2026-10-03 15:26:21 +02:00
|
|
|
failure = $"HTTP {status}";
|
|
|
|
|
response.Dispose();
|
|
|
|
|
}
|
|
|
|
|
catch (Exception) when (cancellationToken.IsCancellationRequested)
|
|
|
|
|
{
|
|
|
|
|
return SUtility.DefaultTaskCancelled();
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException)
|
|
|
|
|
{
|
|
|
|
|
if (!retryOnError)
|
|
|
|
|
{
|
|
|
|
|
await logger.ProcessError(ex, where, cancellationToken);
|
|
|
|
|
return await DescribeUnreachable(ex, 1, cancellationToken);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
failure = ex.Message;
|
|
|
|
|
transportException = ex;
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
|
|
|
|
await logger.ProcessError(ex, where, cancellationToken);
|
|
|
|
|
return SUtility.ClassifiedFailure(FailureCodes.ClientError,
|
|
|
|
|
localizer["The request could not be prepared. Reload the page and try again."], HttpStatusCode.ServiceUnavailable);
|
|
|
|
|
}
|
2022-02-14 01:51:37 +01:00
|
|
|
|
2026-10-03 15:26:21 +02:00
|
|
|
var delay = attempt < RetryRampUpDelaysMs.Length ? RetryRampUpDelaysMs[attempt] : RetryIndefiniteDelayMs;
|
|
|
|
|
delay += Random.Shared.Next(0, delay / 4);
|
|
|
|
|
if (deadline - DateTime.UtcNow <= TimeSpan.FromMilliseconds(delay))
|
2022-02-14 01:51:37 +01:00
|
|
|
{
|
2026-10-03 15:26:21 +02:00
|
|
|
await logger.ProcessError($"Gave up after {attempt + 1} attempts. {failure}", where, cancellationToken);
|
|
|
|
|
if (transportException is not null)
|
|
|
|
|
return await DescribeUnreachable(transportException, attempt + 1, cancellationToken);
|
|
|
|
|
return SUtility.ClassifiedFailure(FailureCodes.RetriesExhausted,
|
|
|
|
|
localizer["The server is still not answering after {0} attempts. Try again later.", attempt + 1], HttpStatusCode.ServiceUnavailable);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
await logger.ProcessWarning($"Attempt {attempt + 1} failed, retrying in {delay}ms. {failure}", where, cancellationToken);
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
await Task.Delay(delay, cancellationToken);
|
|
|
|
|
}
|
|
|
|
|
catch (OperationCanceledException)
|
|
|
|
|
{
|
|
|
|
|
return SUtility.DefaultTaskCancelled();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
attempt++;
|
2022-02-14 01:51:37 +01:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-03 15:26:21 +02:00
|
|
|
HttpResponseMessage ServerError(HttpResponseMessage response)
|
2022-02-14 01:51:37 +01:00
|
|
|
{
|
2026-10-03 15:26:21 +02:00
|
|
|
var status = response.StatusCode;
|
|
|
|
|
response.Dispose();
|
|
|
|
|
return SUtility.ClassifiedFailure(FailureCodes.ServerError, localizer["The server reported an internal error (HTTP {0}).", (int)status], status);
|
2022-02-14 01:51:37 +01:00
|
|
|
}
|
|
|
|
|
|
2026-10-03 15:26:21 +02:00
|
|
|
/// <summary>Why a request got no answer: the device is offline, it timed out, retries ran out, or the server is unreachable.</summary>
|
|
|
|
|
async Task<HttpResponseMessage> DescribeUnreachable(Exception exception, int attempts, CancellationToken cancellationToken)
|
2022-02-14 01:51:37 +01:00
|
|
|
{
|
2026-10-03 15:26:21 +02:00
|
|
|
if (!await statusService.IsOnline(cancellationToken))
|
|
|
|
|
return SUtility.ClassifiedFailure(FailureCodes.DeviceOffline,
|
|
|
|
|
localizer["This device is offline. Check the connection and try again."], HttpStatusCode.ServiceUnavailable);
|
2022-02-14 01:51:37 +01:00
|
|
|
|
2026-10-03 15:26:21 +02:00
|
|
|
if (exception is TaskCanceledException { InnerException: TimeoutException })
|
|
|
|
|
return SUtility.ClassifiedFailure(FailureCodes.Timeout,
|
|
|
|
|
localizer["The server took too long to answer. Try again later."], HttpStatusCode.ServiceUnavailable);
|
2022-02-14 01:51:37 +01:00
|
|
|
|
2026-10-03 15:26:21 +02:00
|
|
|
if (attempts > 1)
|
|
|
|
|
return SUtility.ClassifiedFailure(FailureCodes.RetriesExhausted,
|
|
|
|
|
localizer["The server is still not answering after {0} attempts. Try again later.", attempts], HttpStatusCode.ServiceUnavailable);
|
|
|
|
|
|
|
|
|
|
return SUtility.ClassifiedFailure(FailureCodes.ApiUnreachable,
|
|
|
|
|
localizer["The server can't be reached. Try again later."], HttpStatusCode.ServiceUnavailable);
|
2022-02-14 01:51:37 +01:00
|
|
|
}
|
|
|
|
|
|
2026-10-03 15:26:21 +02:00
|
|
|
async Task<HttpResponseMessage> SendAuthRequest(HttpRequestMessage request, CancellationToken cancellationToken)
|
2022-02-14 01:51:37 +01:00
|
|
|
{
|
2026-10-03 15:26:21 +02:00
|
|
|
var token = await authStateProvider.GetToken(cancellationToken);
|
|
|
|
|
if (token is null)
|
2022-02-14 01:51:37 +01:00
|
|
|
{
|
2026-10-03 15:26:21 +02:00
|
|
|
logger.Process($"NO_TOKEN:{request.RequestUri?.OriginalString}", nameof(SendAuthRequest), LogLevel.Warning);
|
|
|
|
|
return SUtility.DefaultUnauthorized(localizer["Your session has expired. Sign in again."]);
|
|
|
|
|
}
|
2022-02-14 01:51:37 +01:00
|
|
|
|
2026-10-03 15:26:21 +02:00
|
|
|
request.Headers.Authorization = new("Bearer", token);
|
|
|
|
|
var response = await httpClient.SendAsync(request, cancellationToken);
|
|
|
|
|
if (response.StatusCode is not HttpStatusCode.Unauthorized)
|
2022-02-14 01:51:37 +01:00
|
|
|
return response;
|
2026-10-03 15:26:21 +02:00
|
|
|
|
|
|
|
|
response.Dispose();
|
|
|
|
|
await authStateProvider.LogoutAsync(cancellationToken: cancellationToken);
|
|
|
|
|
return SUtility.DefaultUnauthorized(localizer["Your session has expired. Sign in again."]);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async Task<HttpResponseMessage> SendAuthIfAvailableRequest(HttpRequestMessage request, CancellationToken cancellationToken)
|
|
|
|
|
{
|
|
|
|
|
var token = await authStateProvider.GetToken(cancellationToken);
|
|
|
|
|
if (token is not null)
|
|
|
|
|
request.Headers.Authorization = new("Bearer", token);
|
|
|
|
|
return await httpClient.SendAsync(request, cancellationToken);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
static HttpRequestMessage BuildRequest(HttpMethod method, string uri, object payload = default, string[] queryParams = default,
|
|
|
|
|
bool forceContent = false)
|
|
|
|
|
{
|
|
|
|
|
var target = queryParams is { Length: > 0 } ? $"{uri}?{string.Join('&', queryParams)}" : uri;
|
|
|
|
|
var request = new HttpRequestMessage(method, target);
|
|
|
|
|
if (payload is not null || forceContent)
|
|
|
|
|
request.Content = JsonContent.Create(payload, payload?.GetType() ?? typeof(object), options: SUtility.DefaultSerializer);
|
|
|
|
|
return request;
|
2022-02-14 01:51:37 +01:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|