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
188 lines
6.4 KiB
C#
188 lines
6.4 KiB
C#
using decePubClient.Helpers;
|
|
using decePubClient.Models;
|
|
|
|
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
|
|
{
|
|
Task<List<Message>> GetMessages(CancellationToken cancellationToken = default);
|
|
|
|
Task<Message> GetMessage(string messageId, CancellationToken cancellationToken = default);
|
|
|
|
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(IndexedDb db, ILogger<Storage> logger) : IStorage
|
|
{
|
|
/// <summary>The client log keeps at most this many entries; past it the oldest half is dropped.</summary>
|
|
const int MaxLogs = 100;
|
|
|
|
#region Messages
|
|
|
|
public async Task<Message> GetMessage(string messageId, CancellationToken cancellationToken = default)
|
|
{
|
|
try
|
|
{
|
|
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);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
logger.LogError(ex, $"{nameof(Storage)}.{nameof(GetMessage)}");
|
|
return default;
|
|
}
|
|
}
|
|
|
|
/// <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)
|
|
{
|
|
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 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 Task<WebResult> RemoveMessage(string messageId, CancellationToken cancellationToken = default) =>
|
|
Run(nameof(RemoveMessage), async () => await db.DeleteByKey(nameof(Message), messageId), cancellationToken);
|
|
|
|
#endregion
|
|
|
|
#region Logs
|
|
|
|
public async Task<List<ClientLogs>> GetClientLogs(CancellationToken cancellationToken = default)
|
|
{
|
|
try
|
|
{
|
|
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, $"{nameof(Storage)}.{nameof(GetClientLogs)}");
|
|
return [];
|
|
}
|
|
}
|
|
|
|
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
|
|
{
|
|
cancellationToken.ThrowIfCancellationRequested();
|
|
await db.OpenIndexedDb();
|
|
|
|
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);
|
|
|
|
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, $"{nameof(Storage)}.{nameof(AddLog)}");
|
|
}
|
|
}
|
|
|
|
#endregion
|
|
|
|
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
|
|
{
|
|
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, $"{nameof(Storage)}.{caller}");
|
|
return result.Invalidate(ex.Message, exception: ex);
|
|
}
|
|
}
|
|
}
|
|
}
|