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

+125 -327
View File
@@ -1,389 +1,187 @@
using decePubClient.Helpers;
using decePubClient.Helpers;
using decePubClient.Models;
using decePubClient.Models.Types;
using Markdig;
using PrivaPub.ClientModels;
namespace decePubClient.Services
{
/// <summary>
/// The IndexedDB database "data" (schema in GenericExtensions.AddIndexedDb): messages and the client log. Lists
/// come back empty on failure, mutations as an invalid WebResult; nothing throws. Failures are logged with ILogger
/// only, because ILoggingService writes its log through this class.
/// </summary>
public interface IStorage
{
ValueTask<List<Message>> GetMessages();
ValueTask<Message> GetMessage(string messageId);
ValueTask<string> AddMessages(List<Message> messages);
ValueTask<string> UpdateMessages(List<Message> messages);
ValueTask<string> RemoveMessage(string messageId);
Task<List<Message>> GetMessages(CancellationToken cancellationToken = default);
ValueTask<ICollection<ClientLogs>> GetClientLogs();
ValueTask AddLog(Exception exception, string where);
ValueTask AddLog(string message, string where);
Task<Message> GetMessage(string messageId, CancellationToken cancellationToken = default);
ValueTask<bool> RemoveAll(bool includeClientLogs = false);
Task<WebResult> AddMessages(List<Message> messages, CancellationToken cancellationToken = default);
Task<WebResult> UpdateMessages(List<Message> messages, CancellationToken cancellationToken = default);
Task<WebResult> RemoveMessage(string messageId, CancellationToken cancellationToken = default);
Task<List<ClientLogs>> GetClientLogs(CancellationToken cancellationToken = default);
Task AddLog(Exception exception, string where, CancellationToken cancellationToken = default);
Task AddLog(string message, string where, CancellationToken cancellationToken = default);
Task<WebResult> RemoveAll(bool includeClientLogs = false, CancellationToken cancellationToken = default);
}
public class Storage : IStorage
public class Storage(IndexedDb db, ILogger<Storage> logger) : IStorage
{
readonly IndexedDb _db;
readonly ILogger<Storage> _logger;
/// <summary>The client log keeps at most this many entries; past it the oldest half is dropped.</summary>
const int MaxLogs = 100;
public Storage(IndexedDb indexedDb, ILogger<Storage> logger)
#region Messages
public async Task<Message> GetMessage(string messageId, CancellationToken cancellationToken = default)
{
_db = indexedDb;
_logger = logger;
}
#region Messagges
public async ValueTask<Message> GetMessage(string messageId)
{
await _db.OpenIndexedDb();
var message = await _db.GetByKey<string, Message>(nameof(Message), messageId);
if (message is null)
try
{
var messages = await GetMessages();
cancellationToken.ThrowIfCancellationRequested();
await db.OpenIndexedDb();
var message = await db.GetByKey<string, Message>(nameof(Message), messageId);
if (message is not null)
return message;
var messages = await GetMessages(cancellationToken);
return messages.FirstOrDefault(m => m.MessageId == messageId);
}
return message;
}
public async ValueTask<List<Message>> GetMessages()
{
await _db.OpenIndexedDb();
var messages = await _db.GetAll<Message>(nameof(Message)) ?? new();
if (messages.Count == 0)
catch (Exception ex)
{
messages.Add(new()
{
RootMessageId = default,
MessageId = "992167EE-8947-4823-B1E2-B4E1019B6974",
User = Faker.GetRandomUser(),
MessageType = (MessageType)Random.Shared.Next(0, 4),
Title = default,
Content = "test di messaggio normale senza titolo",
Medias = new(),
CreatedAt = DateTime.UtcNow.AddMinutes(Random.Shared.Next(-5000, 0)),
IsFavourite = Random.Shared.Next() % 2 == 0,
BoostsCounter = Random.Shared.Next(0, 100),
IsBoostedByCurrentUser = Random.Shared.Next() % 2 == 0,
});
messages.Add(new()
{
RootMessageId = default,
MessageId = "C5307644-4EA8-4B5F-A240-7CFE4DE34741",
User = Faker.GetRandomUser(),
MessageType = (MessageType)Random.Shared.Next(0, 4),
Title = "sopra la panca la capra canta",
Content = Markdown.ToHtml("test di messaggio con titolo"),
Medias = new(),
CreatedAt = DateTime.UtcNow.AddMinutes(Random.Shared.Next(-5000, 0)),
IsFavourite = Random.Shared.Next() % 2 == 0,
BoostsCounter = Random.Shared.Next(0, 100),
IsBoostedByCurrentUser = Random.Shared.Next() % 2 == 0,
});
messages.Add(new()
{
RootMessageId = default,
MessageId = "E473D562-D210-4453-93DA-157D4B90B0D8",
User = Faker.GetRandomUser(),
MessageType = (MessageType)Random.Shared.Next(0, 4),
Title = default,
Content = "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd test di messaggio con overflow del testo",
Medias = new(),
CreatedAt = DateTime.UtcNow.AddMinutes(Random.Shared.Next(-5000, 0)),
IsFavourite = Random.Shared.Next() % 2 == 0,
BoostsCounter = Random.Shared.Next(0, 100),
IsBoostedByCurrentUser = Random.Shared.Next() % 2 == 0,
});
messages.Add(new()
{
RootMessageId = default,
MessageId = "adf89dc6-0484-430e-a7c9-fcb1179b0c28",
User = Faker.GetRandomUser(),
MessageType = (MessageType)Random.Shared.Next(0, 4),
Title = default,
Content = "test video",
Medias = new()
{
new()
{
FileName = "8252d175e714db88beb8ee0349dbac90405d3d5148e96e0cfd7de3b0876dbb1b.mp4",
Url = "https://ihatebeinga.live/media/8252d175e714db88beb8ee0349dbac90405d3d5148e96e0cfd7de3b0876dbb1b.mp4",
AltText = "https://ihatebeinga.live/media/8252d175e714db88beb8ee0349dbac90405d3d5148e96e0cfd7de3b0876dbb1b.mp4",
ContentType = "video/mp4"
}
},
CreatedAt = DateTime.UtcNow.AddMinutes(Random.Shared.Next(-5000, 0)),
IsFavourite = Random.Shared.Next() % 2 == 0,
BoostsCounter = Random.Shared.Next(0, 100),
IsBoostedByCurrentUser = Random.Shared.Next() % 2 == 0,
});
messages.Add(new()
{
RootMessageId = default,
MessageId = "96025b43-5235-44e9-a3fa-98df31edfbfb",
User = Faker.GetRandomUser(),
MessageType = (MessageType)Random.Shared.Next(0, 4),
Title = default,
Content = "test immagine",
Medias = new()
{
new()
{
FileName = "51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
Url = "https://ihatebeinga.live/media/51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
AltText = "51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
ContentType = "image/jpg"
}
},
CreatedAt = DateTime.UtcNow.AddMinutes(Random.Shared.Next(-5000, 0)),
IsFavourite = Random.Shared.Next() % 2 == 0,
BoostsCounter = Random.Shared.Next(0, 100),
IsBoostedByCurrentUser = Random.Shared.Next() % 2 == 0,
});
messages.Add(new()
{
RootMessageId = default,
MessageId = "277ca76b-aaad-4aa6-95fb-25f59e2fddf9",
User = Faker.GetRandomUser(),
MessageType = (MessageType)Random.Shared.Next(0, 4),
Title = default,
Content = "test audio",
Medias = new()
{
new()
{
FileName = "09bfb06d0096975f.mp3",
Url = "https://cdn.masto.host/mastodonuno/media_attachments/files/107/798/288/501/917/857/original/09bfb06d0096975f.mp3",
AltText = "09bfb06d0096975f.mp3",
ContentType = "audio/mp3"
}
},
CreatedAt = DateTime.UtcNow.AddMinutes(Random.Shared.Next(-5000, 0)),
IsFavourite = Random.Shared.Next() % 2 == 0,
BoostsCounter = Random.Shared.Next(0, 100),
IsBoostedByCurrentUser = Random.Shared.Next() % 2 == 0,
});
messages.Add(new()
{
BoostingUser = Faker.GetRandomBoostingUser(),
RootMessageId = default,
MessageId = "de64e520-a7d3-4f31-b5a9-ba236f3b146c",
User = Faker.GetRandomUser(),
MessageType = (MessageType)Random.Shared.Next(0, 4),
Title = default,
Content = "test immagini",
Medias = new()
{
new()
{
FileName = "51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
Url = "https://ihatebeinga.live/media/51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
AltText = "51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
ContentType = "image/jpg"
},
new()
{
FileName = "51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
Url = "https://ihatebeinga.live/media/51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
AltText = "51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
ContentType = "image/jpg"
},
new()
{
FileName = "51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
Url = "https://ihatebeinga.live/media/51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
AltText = "51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
ContentType = "image/jpg"
}
},
CreatedAt = DateTime.UtcNow.AddMinutes(Random.Shared.Next(-5000, 0)),
IsFavourite = Random.Shared.Next() % 2 == 0,
BoostsCounter = Random.Shared.Next(0,100),
IsBoostedByCurrentUser = Random.Shared.Next() % 2 == 0,
});
messages.Add(new()
{
RootMessageId = default,
MessageId = "de64e520-a7d3-4f31-b5a9-ba236f3b146c",
User = Faker.GetRandomUser(),
MessageType = (MessageType)Random.Shared.Next(0, 4),
Title = default,
Content = "test immagini",
Medias = new()
{
new()
{
FileName = "51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
Url = "https://ihatebeinga.live/media/51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
AltText = "51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
ContentType = "image/jpg"
},
new()
{
FileName = "51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
Url = "https://ihatebeinga.live/media/51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
AltText = "51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
ContentType = "image/jpg"
},
new()
{
FileName = "51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
Url = "https://ihatebeinga.live/media/51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
AltText = "51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
ContentType = "image/jpg"
}
},
CreatedAt = DateTime.UtcNow.AddMinutes(Random.Shared.Next(-5000, 0)),
IsFavourite = Random.Shared.Next() % 2 == 0,
BoostsCounter = Random.Shared.Next(0,100),
IsBoostedByCurrentUser = Random.Shared.Next() % 2 == 0,
});
logger.LogError(ex, $"{nameof(Storage)}.{nameof(GetMessage)}");
return default;
}
messages = messages.OrderByDescending(m => m.CreatedAt).ToList();
return messages;
}
public async ValueTask<string> AddMessages(List<Message> messages)
/// <summary>The stored messages, newest first; while none are stored, the mock feed (Faker.SeedMessages).</summary>
public async Task<List<Message>> GetMessages(CancellationToken cancellationToken = default)
{
await _db.OpenIndexedDb();
var result = await _db.AddItems(nameof(Message), messages);
_logger.LogInformation(result);
return result;
try
{
cancellationToken.ThrowIfCancellationRequested();
await db.OpenIndexedDb();
var messages = await db.GetAll<Message>(nameof(Message)) ?? [];
if (messages.Count == 0)
messages = Faker.SeedMessages();
return [.. messages.OrderByDescending(m => m.CreatedAt)];
}
catch (Exception ex)
{
logger.LogError(ex, $"{nameof(Storage)}.{nameof(GetMessages)}");
return [];
}
}
public async ValueTask<string> UpdateMessages(List<Message> messages)
{
await _db.OpenIndexedDb();
var result = await _db.UpdateItems(nameof(Message), messages);
_logger.LogInformation(result);
return result;
public Task<WebResult> AddMessages(List<Message> messages, CancellationToken cancellationToken = default) =>
Run(nameof(AddMessages), async () => await db.AddItems(nameof(Message), messages), cancellationToken);
}
public Task<WebResult> UpdateMessages(List<Message> messages, CancellationToken cancellationToken = default) =>
Run(nameof(UpdateMessages), async () => await db.UpdateItems(nameof(Message), messages), cancellationToken);
public async ValueTask<string> RemoveMessage(string messageId)
{
await _db.OpenIndexedDb();
var result = await _db.DeleteByKey(nameof(Message), messageId);
_logger.LogInformation(result);
return result;
}
public Task<WebResult> RemoveMessage(string messageId, CancellationToken cancellationToken = default) =>
Run(nameof(RemoveMessage), async () => await db.DeleteByKey(nameof(Message), messageId), cancellationToken);
#endregion
#region Logs
public async ValueTask<ICollection<ClientLogs>> GetClientLogs()
public async Task<List<ClientLogs>> GetClientLogs(CancellationToken cancellationToken = default)
{
try
{
_logger.LogInformation($"opening on {nameof(GetClientLogs)}");
await _db.OpenIndexedDb();
return (await _db.GetAll<ClientLogs>(nameof(ClientLogs))).OrderByDescending(cl => cl.TimeStamp).ToArray();
cancellationToken.ThrowIfCancellationRequested();
await db.OpenIndexedDb();
var logs = await db.GetAll<ClientLogs>(nameof(ClientLogs)) ?? [];
return [.. logs.OrderByDescending(log => log.TimeStamp)];
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
return new List<ClientLogs>();
logger.LogError(ex, $"{nameof(Storage)}.{nameof(GetClientLogs)}");
return [];
}
}
public async ValueTask AddLog(Exception exception, string where)
public Task AddLog(Exception exception, string where, CancellationToken cancellationToken = default) =>
AddLog(new ClientLogs
{
Where = where,
Exception = new()
{
Type = exception.GetType().ToString(),
HelpLink = exception.HelpLink,
HResult = exception.HResult.ToString(),
InnerExceptionMessage = exception.InnerException?.Message,
Message = exception.Message,
Source = exception.Source,
StackTrace = exception.StackTrace,
TargetSiteName = exception.TargetSite?.Name
}
}, cancellationToken);
public Task AddLog(string message, string where, CancellationToken cancellationToken = default) =>
AddLog(new ClientLogs { Where = where, WarningMessage = message }, cancellationToken);
/// <summary>Numbers the entry after the newest one and trims the log; never throws.</summary>
async Task AddLog(ClientLogs log, CancellationToken cancellationToken)
{
try
{
await _db.OpenIndexedDb();
cancellationToken.ThrowIfCancellationRequested();
await db.OpenIndexedDb();
var maxKey = await _db.GetMaxKey<long>(nameof(ClientLogs));
var minKey = await _db.GetMinKey<long>(nameof(ClientLogs));
var maxKey = await db.GetMaxKey<long>(nameof(ClientLogs));
var minKey = await db.GetMinKey<long>(nameof(ClientLogs));
if (maxKey - minKey >= MaxLogs)
for (var key = minKey; key < minKey + MaxLogs / 2; key++)
_ = await db.DeleteByKey(nameof(ClientLogs), key);
if (minKey - maxKey <= -100)
for (var i = minKey; i < minKey + 50; i++)
_ = await _db.DeleteByKey(nameof(ClientLogs), i);
maxKey += 1;
var result = await _db.AddItems<ClientLogs>(nameof(ClientLogs), new()
{
new()
{
Id = maxKey,
Where = where,
Exception = new()
{
Type = exception.GetType().ToString(),
HelpLink = exception.HelpLink,
HResult = exception.HResult.ToString(),
InnerExceptionMessage = exception.InnerException?.Message,
Message = exception.Message,
Source = exception.Source,
StackTrace = exception.StackTrace,
TargetSiteName = exception.TargetSite?.Name
}
}
});
_logger.LogDebug($"{nameof(AddLog)}() add logs result = {result}");
log.Id = maxKey + 1;
var result = await db.AddItems<ClientLogs>(nameof(ClientLogs), [log]);
logger.LogDebug($"{nameof(AddLog)}() add logs result = {result}");
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
}
}
public async ValueTask AddLog(string message, string where)
{
try
{
await _db.OpenIndexedDb();
var maxKey = await _db.GetMaxKey<long>(nameof(ClientLogs));
var minKey = await _db.GetMinKey<long>(nameof(ClientLogs));
if (minKey - maxKey <= -100)
for (var i = minKey; i < minKey + 50; i++)
_ = await _db.DeleteByKey(nameof(ClientLogs), i);
maxKey += 1;
var result = await _db.AddItems<ClientLogs>(nameof(ClientLogs), new()
{
new()
{
Id = maxKey,
Where = where,
Exception = null,
WarningMessage = message
}
});
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
logger.LogError(ex, $"{nameof(Storage)}.{nameof(AddLog)}");
}
}
#endregion
public async ValueTask<bool> RemoveAll(bool includeClientLogs = false)
public Task<WebResult> RemoveAll(bool includeClientLogs = false, CancellationToken cancellationToken = default) =>
Run(nameof(RemoveAll), async () =>
{
var result = await db.DeleteAll(nameof(Message));
if (includeClientLogs)
result = await db.DeleteAll(nameof(ClientLogs));
return result;
}, cancellationToken);
/// <summary>Runs a write and turns its outcome into a WebResult.</summary>
async Task<WebResult> Run(string caller, Func<Task<string>> write, CancellationToken cancellationToken)
{
var result = new WebResult();
try
{
_logger.LogInformation($"opening on {nameof(RemoveAll)}");
await _db.OpenIndexedDb();
_ = await _db.DeleteAll(nameof(Message));
if (includeClientLogs)
_ = await _db.DeleteAll(nameof(ClientLogs));
return true;
cancellationToken.ThrowIfCancellationRequested();
await db.OpenIndexedDb();
logger.LogInformation("{Caller}: {Result}", caller, await write());
return result;
}
catch (OperationCanceledException)
{
return SUtility.DefaultTaskCancelledResult;
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
return default;
logger.LogError(ex, $"{nameof(Storage)}.{caller}");
return result.Invalidate(ex.Message, exception: ex);
}
}
}
}