using System.Net; using System.Net.Http.Json; using collAnon.Client.Services; using decePubClient.Helpers; using decePubClient.Models; namespace decePubClient.Services { /// /// 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. /// public interface IHttpService { Task Get(string uri, string[] queryParams = default, bool retryOnError = false, CancellationToken cancellationToken = default); Task GetAnon(string uri, string[] queryParams = default, bool retryOnError = false, CancellationToken cancellationToken = default); Task GetTotallyAnon(string uri, string[] queryParams = default, bool retryOnError = false, CancellationToken cancellationToken = default); Task Post(string uri, object payload = default, bool retryOnError = false, CancellationToken cancellationToken = default); Task PostAnon(string uri, object payload = default, bool retryOnError = false, CancellationToken cancellationToken = default); Task PostTotallyAnon(string uri, object payload = default, bool retryOnError = false, CancellationToken cancellationToken = default); Task Delete(string uri, string[] queryParams = default, object payload = default, bool retryOnError = false, CancellationToken cancellationToken = default); Task DeleteTotallyAnon(string uri, string[] queryParams = default, object payload = default, bool retryOnError = false, CancellationToken cancellationToken = default); } public class HttpService(IHttpClientFactory httpClientFactory, TokenAuthStateProvider authStateProvider, AppStatusService statusService, ILoggingService logger, CoalescingStringLocalizer localizer) : IHttpService { 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]; readonly HttpClient httpClient = httpClientFactory.CreateClient("default"); public Task 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 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 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 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); public Task 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 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 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 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 Send(string caller, Func requestFactory, Func> send, bool retryOnError, CancellationToken cancellationToken) { var deadline = DateTime.UtcNow + RetryDeadline; var attempt = 0; while (true) { // 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 { var response = await send(request, cancellationToken); var status = (int)response.StatusCode; if (!retryOnError || !RetryableStatusCodes.Contains(status)) return status > 499 ? ServerError(response) : response; 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); } var delay = attempt < RetryRampUpDelaysMs.Length ? RetryRampUpDelaysMs[attempt] : RetryIndefiniteDelayMs; delay += Random.Shared.Next(0, delay / 4); if (deadline - DateTime.UtcNow <= TimeSpan.FromMilliseconds(delay)) { 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++; } } HttpResponseMessage ServerError(HttpResponseMessage response) { var status = response.StatusCode; response.Dispose(); return SUtility.ClassifiedFailure(FailureCodes.ServerError, localizer["The server reported an internal error (HTTP {0}).", (int)status], status); } /// Why a request got no answer: the device is offline, it timed out, retries ran out, or the server is unreachable. async Task DescribeUnreachable(Exception exception, int attempts, CancellationToken cancellationToken) { if (!await statusService.IsOnline(cancellationToken)) return SUtility.ClassifiedFailure(FailureCodes.DeviceOffline, localizer["This device is offline. Check the connection and try again."], HttpStatusCode.ServiceUnavailable); if (exception is TaskCanceledException { InnerException: TimeoutException }) return SUtility.ClassifiedFailure(FailureCodes.Timeout, localizer["The server took too long to answer. Try again later."], HttpStatusCode.ServiceUnavailable); 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); } async Task SendAuthRequest(HttpRequestMessage request, CancellationToken cancellationToken) { var token = await authStateProvider.GetToken(cancellationToken); if (token is null) { logger.Process($"NO_TOKEN:{request.RequestUri?.OriginalString}", nameof(SendAuthRequest), LogLevel.Warning); return SUtility.DefaultUnauthorized(localizer["Your session has expired. Sign in again."]); } request.Headers.Authorization = new("Bearer", token); var response = await httpClient.SendAsync(request, cancellationToken); if (response.StatusCode is not HttpStatusCode.Unauthorized) return response; response.Dispose(); await authStateProvider.LogoutAsync(cancellationToken: cancellationToken); return SUtility.DefaultUnauthorized(localizer["Your session has expired. Sign in again."]); } async Task 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; } } }