Ported from the owner's b2b.next and adapted from MudBlazor to the daisyUI
components:
- LocalizableComponentBase provides CascadingState, Navigation, Toast,
IsLoading/IsDefaultDisabled, WhenOnline/StartOnlinePolling, and after-render
jobs that actually run.
- CascadingState starts with initialised state and polls the online status
with a PeriodicTimer. It reports errors through ILoggingService plus a toast,
and disposes what it holds.
- New pieces:
- ToastService + ToastHost, the snackbar, with AddResponseError/Success/
Warning/Exception in SUtility;
- ErrorViewer, which shows the validation messages plus AdditionalError(s);
- LoggingService, which writes to the console and the IndexedDB client log.
- HttpService is rebuilt and registered:
- auth levels Get/Post/Delete, *Anon and *TotallyAnon;
- retry with backoff;
- classified failures (FailureCodes) instead of exceptions;
- HTTP 410 on cancel;
- the "default" client.
ReadWebResult and DefaultReadFromJsonAsync read its responses.
- ClientJsonContext is source-generated, and SUtility.DefaultSerializer and
Blazored.LocalStorage use it.
- WebResult gains a C# 14 IsInvalid extension property.
The code follows the imported rules:
- Every service and async helper takes a CancellationToken last.
- Primary constructors replace constructor-plus-fields.
- MessagesService and IStorage return Task<WebResult> / Task<List<T>>.
MessagesService is still mock, building its results in memory; the seed
feed and thread moved to Faker.
- Index and ExpandMessage follow the page pattern: an offline guard with
WhenOnline, LoadData, and early returns with toasts on the results they used
to ignore. ExpandMessage reloads on route change and shows "not found"
instead of a null message.
- Model and state collections are [], and the fake identity defaults moved
out of the models.
- Components:
- no ?. chains over initialised state;
- [Inject] instead of @inject;
- IsDefaultDisabled on the actions;
- autocomplete on every text input;
- Localizer[key, args] instead of string.Format;
- the localizer no longer leaks its inner _pLocalizer.
- Settings → General gains a language picker (English/Italiano), and
SetDefaultCulture limits the culture to those two.
Bugs fixed along the way:
- A compose with untouched (null) content passed the empty check.
- File errors were joined with <br/> and rendered as markup.
- ClientLogs.ErrorMessage() threw on warnings.
- CoalescingStringLocalizer[key, args] showed a raw "{0}" for missing keys.
- AppStatusService exposed a call to a JS function that doesn't exist.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LsXgEaXee4GCU1hwYgPJXw
218 lines
11 KiB
C#
218 lines
11 KiB
C#
using System.Net;
|
|
using System.Net.Http.Json;
|
|
|
|
using collAnon.Client.Services;
|
|
|
|
using decePubClient.Helpers;
|
|
using decePubClient.Models;
|
|
|
|
namespace decePubClient.Services
|
|
{
|
|
/// <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>
|
|
public interface IHttpService
|
|
{
|
|
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);
|
|
|
|
Task<HttpResponseMessage> GetTotallyAnon(string uri, string[] queryParams = default, bool retryOnError = false,
|
|
CancellationToken cancellationToken = default);
|
|
|
|
Task<HttpResponseMessage> Post(string uri, object payload = default, bool retryOnError = false, CancellationToken cancellationToken = default);
|
|
|
|
Task<HttpResponseMessage> PostAnon(string uri, object payload = default, bool retryOnError = false, CancellationToken cancellationToken = default);
|
|
|
|
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);
|
|
}
|
|
|
|
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<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);
|
|
|
|
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)
|
|
{
|
|
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);
|
|
}
|
|
|
|
/// <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)
|
|
{
|
|
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<HttpResponseMessage> 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<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;
|
|
}
|
|
}
|
|
}
|