Adopt b2b.next's client patterns: services, page state, feedback

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
This commit is contained in:
thepraandClaude Opus 5.5 committed 2026-10-03 15:26:21 +02:00
1 parent ca060f25fb
commit 95428430c0
55 files changed
+1844 -1337

No files matched your search

+182 -161
View File
@@ -1,196 +1,217 @@
using Blazored.LocalStorage;
using System.Globalization;
using System.Net.Http.Json;
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, object payload = default, string[] queryParams = default);
Task<HttpResponseMessage> Get(string uri, string[] queryParams = default, bool retryOnError = false, CancellationToken cancellationToken = default);
Task<HttpResponseMessage> GetAnon(string uri, object payload = default, string[] queryParams = default);
Task<HttpResponseMessage> GetAnon(string uri, string[] queryParams = default, bool retryOnError = false, CancellationToken cancellationToken = default);
Task<HttpResponseMessage> Post(string uri, object payload = default);
Task<HttpResponseMessage> GetTotallyAnon(string uri, string[] queryParams = default, bool retryOnError = false,
CancellationToken cancellationToken = default);
Task<HttpResponseMessage> PostAnon(string uri, object payload = default);
Task<HttpResponseMessage> Post(string uri, object payload = default, bool retryOnError = false, CancellationToken cancellationToken = default);
Task<HttpResponseMessage> Delete(string uri, string[] queryParams = default, object payload = 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 : IHttpService
public class HttpService(IHttpClientFactory httpClientFactory, TokenAuthStateProvider authStateProvider, AppStatusService statusService,
ILoggingService logger, CoalescingStringLocalizer localizer) : IHttpService
{
readonly IHttpClientFactory HttpClientFactory;
readonly TokenAuthStateProvider AuthStateProvider;
readonly ILogger<HttpService> Logger;
readonly ILocalStorageService Storage;
readonly IStorage DbStorage;
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];
public HttpService(
IHttpClientFactory httpClientFactory,
TokenAuthStateProvider authStateProvider,
ILogger<HttpService> logger,
ILocalStorageService storage,
IStorage dbStorage)
{
HttpClientFactory = httpClientFactory;
AuthStateProvider = authStateProvider;
Logger = logger;
Storage = storage;
DbStorage = dbStorage;
}
readonly HttpClient httpClient = httpClientFactory.CreateClient("default");
public async Task<HttpResponseMessage> Get(string uri, object payload = default, string[] queryParams = default)
{
try
{
uri = $"{CultureInfo.DefaultThreadCurrentCulture.TwoLetterISOLanguageName}/{uri}";
var request = default(HttpRequestMessage);
if (queryParams != null)
request = new(HttpMethod.Get, string.Join('?', uri, string.Join('&', queryParams)));
else
request = new(HttpMethod.Get, uri);
if (payload != null)
request.Content = JsonContent.Create(payload);
return await SendRequest(request);
}
catch (Exception ex)
{
Logger.LogError(ex, $"{nameof(Get)}:{uri}");
await DbStorage.AddLog(ex, $"{nameof(Get)}:{uri}");
return new(HttpStatusCode.ServiceUnavailable);
}
}
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 async Task<HttpResponseMessage> Post(string uri, object payload = default)
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)
{
try
var deadline = DateTime.UtcNow + RetryDeadline;
var attempt = 0;
while (true)
{
uri = $"{CultureInfo.DefaultThreadCurrentCulture.TwoLetterISOLanguageName}/{uri}";
var request = new HttpRequestMessage(HttpMethod.Post, uri)
// 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
{
Content = JsonContent.Create(payload)
};
return await SendRequest(request);
}
catch (Exception ex)
{
Logger.LogError(ex, $"{nameof(Post)}:{uri}");
await DbStorage.AddLog(ex, $"{nameof(Post)}:{uri}");
return new(HttpStatusCode.ServiceUnavailable);
}
}
var response = await send(request, cancellationToken);
var status = (int)response.StatusCode;
if (!retryOnError || !RetryableStatusCodes.Contains(status))
return status > 499 ? ServerError(response) : response;
public async Task<HttpResponseMessage> GetAnon(string uri, object payload = default, string[] queryParams = default)
{
try
{
uri = $"{CultureInfo.DefaultThreadCurrentCulture.TwoLetterISOLanguageName}/{uri}";
var request = default(HttpRequestMessage);
if (queryParams != null)
request = new(HttpMethod.Get, string.Join('?', uri, string.Join('&', queryParams)));
else
request = new(HttpMethod.Get, uri);
if (payload != null)
request.Content = JsonContent.Create(payload);
return await SendAnonRequest(request);
}
catch (Exception ex)
{
Logger.LogError(ex, $"{nameof(GetAnon)}:{uri}");
await DbStorage.AddLog(ex, $"{nameof(GetAnon)}:{uri}");
return new(HttpStatusCode.ServiceUnavailable);
}
}
public async Task<HttpResponseMessage> PostAnon(string uri, object payload = default)
{
try
{
uri = $"{CultureInfo.DefaultThreadCurrentCulture.TwoLetterISOLanguageName}/{uri}";
var request = new HttpRequestMessage(HttpMethod.Post, uri)
failure = $"HTTP {status}";
response.Dispose();
}
catch (Exception) when (cancellationToken.IsCancellationRequested)
{
Content = JsonContent.Create(payload)
};
return await SendAnonRequest(request);
}
catch (Exception ex)
{
Logger.LogError(ex, $"{nameof(PostAnon)}:{uri}");
await DbStorage.AddLog(ex, $"{nameof(PostAnon)}:{uri}");
return new(HttpStatusCode.ServiceUnavailable);
}
}
public async Task<HttpResponseMessage> Delete(string uri, string[] queryParams = default, object payload = default)
{
try
{
uri = $"{CultureInfo.DefaultThreadCurrentCulture.TwoLetterISOLanguageName}/{uri}";
var request = default(HttpRequestMessage);
if (queryParams != null)
request = new(HttpMethod.Delete, string.Join('?', uri, string.Join('&', queryParams)));
else
request = new(HttpMethod.Delete, uri);
if (payload != null)
request.Content = JsonContent.Create(payload);
return await SendRequest(request);
}
catch (Exception ex)
{
Logger.LogError(ex, $"{nameof(Delete)}:{uri}");
await DbStorage.AddLog(ex, $"{nameof(Delete)}:{uri}");
return new(HttpStatusCode.ServiceUnavailable);
}
}
// helper methods
async Task<HttpResponseMessage> SendRequest(HttpRequestMessage request)
{
try
{
var authData = await Storage.GetItemAsync<AuthData>(nameof(AuthData));
var isApiUrl = !request.RequestUri?.IsAbsoluteUri;
if (isApiUrl.HasValue && isApiUrl.Value)
request.Headers.Authorization = new("Bearer", authData.Token);
var response = await HttpClientFactory.CreateClient().SendAsync(request);
if (response.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden)
return SUtility.DefaultTaskCancelled();
}
catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException)
{
Logger.LogWarning($"{nameof(SendRequest)}:401/403:{request.RequestUri?.OriginalString}:{await response.Content.ReadAsStringAsync()}");
await DbStorage.AddLog($"{nameof(SendRequest)}:401/403:{request.RequestUri?.OriginalString}:{await response.Content.ReadAsStringAsync()}", $"{nameof(SendRequest)}:{request.RequestUri?.OriginalString}");
await AuthStateProvider.LogoutAsync();
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);
}
return response;
}
catch (Exception ex)
{
Logger.LogError(ex, $"{nameof(SendRequest)}:{request.RequestUri?.OriginalString}");
await DbStorage.AddLog(ex, $"{nameof(SendRequest)}:{request.RequestUri?.OriginalString}");
return new(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++;
}
}
async Task<HttpResponseMessage> SendAnonRequest(HttpRequestMessage request)
HttpResponseMessage ServerError(HttpResponseMessage response)
{
try
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)
{
var authData = await Storage.GetItemAsync<AuthData>(nameof(AuthData));
if (!string.IsNullOrEmpty(authData?.Token))
request.Headers.Authorization = new("Bearer", authData.Token);
var response = await HttpClientFactory.CreateClient().SendAsync(request);
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;
}
catch (Exception ex)
{
Logger.LogError(ex, $"{nameof(SendAnonRequest)}:{request.RequestUri?.OriginalString}");
await DbStorage.AddLog(ex, $"{nameof(SendAnonRequest)}:{request.RequestUri?.OriginalString}");
return new(HttpStatusCode.ServiceUnavailable);
}
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;
}
}
}