Bundle: redb-tsak / src/redb.Tsak.Web (src.redb.Tsak.Web.txt), 70 files Snapshot: development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Index: https://redbase.app/src/dev-2026-12-06/redb-tsak/_index.txt ==== Path: redb-tsak/src/redb.Tsak.Web/Components/App.razor Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Components/App.razor ---- redb.Tsak — Dashboard @* Self-hosted (review 4.10): no runtime CDN dependency (works air-gapped) and no third-party script loaded without integrity checking. Pinned to Chart.js v4.4.7. *@ Path: redb-tsak/src/redb.Tsak.Web/Components/Layout/BlankLayout.razor Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Components/Layout/BlankLayout.razor ---- @inherits LayoutComponentBase @* Chromeless layout for pages rendered outside the authenticated shell (e.g. /login). *@ @Body Path: redb-tsak/src/redb.Tsak.Web/Components/Layout/TsakShell.razor Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Components/Layout/TsakShell.razor ---- @inherits LayoutComponentBase @inject ToastService Toast @inject NavigationManager Nav @inject INodeClientProvider NodeProvider @implements IDisposable @* Anonymous access is blocked by the [Authorize] attribute every page inherits from _Imports.razor (AuthorizeRouteView enforces the PAGE's own authorize metadata and redirects to /login), so the shell only ever renders for an authenticated principal from the auth cookie. *@
@* Keyed by the node of the address: a change of node in the address (the node switcher, a link) disposes the page and builds a new one for the new node. Without the key Blazor reuses the page instance, and the page kept showing the previous node's data until its next poll, or for good on the pages that load once. *@
@if (_nodeNotice is { } notice) {
@notice
} @Body
@code { private TsakToast? _toast; private string _nodeKey = string.Empty; private string? _nodeNotice; protected override void OnInitialized() { Toast.OnShow += OnToast; } // The router hands the layout a new Body on every navigation, so the key is taken in the same render pass // that builds the new page. protected override void OnParametersSet() { _nodeKey = NodePath.NodeIdOf(Nav.ToBaseRelativePath(Nav.Uri)) ?? string.Empty; _nodeNotice = NoticeFor(_nodeKey); } // A page of a node that is down, or that the cluster does not know, says so above its content: its calls // fail or time out, and the switcher lets one land there on purpose. From the topology last loaded; no call. private string? NoticeFor(string nodeId) { if (nodeId.Length == 0 || NodeProvider.Topology is not { } topology) return null; var node = topology.Nodes.FirstOrDefault(n => n.NodeId == nodeId); if (node is null) return $"Node {nodeId} is not in the cluster topology."; return node.IsAlive ? null : $"Node {nodeId} is down (last heartbeat {NodeSwitch.Ago(node.LastHeartbeat, DateTimeOffset.UtcNow)}); the data below may be missing."; } private void OnToast(string message, string level, int durationMs) { _toast?.Show(message, level, durationMs); } public void Dispose() { Toast.OnShow -= OnToast; } } Path: redb-tsak/src/redb.Tsak.Web/Components/Layout/TsakShell.razor.css Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Components/Layout/TsakShell.razor.css ---- /* Styles moved to wwwroot/css/app.css */ Path: redb-tsak/src/redb.Tsak.Web/Components/Layout/TsakSidebar.razor Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Components/Layout/TsakSidebar.razor ---- @inject NavigationManager Nav @inject INodeClientProvider NodeProvider @using System.Reflection @implements IDisposable @code { // Same source as the About page and the startup banner: informational version with the // +metadata suffix cut, falling back to the four-part assembly version. private static readonly string DashboardVersion = typeof(TsakSidebar).Assembly.GetCustomAttribute() ?.InformationalVersion?.Split('+')[0] ?? typeof(TsakSidebar).Assembly.GetName().Version?.ToString() ?? "?"; private string? _activeNodeId; protected override void OnInitialized() { Nav.LocationChanged += OnLocationChanged; UpdateActiveNode(); } private void OnLocationChanged(object? sender, Microsoft.AspNetCore.Components.Routing.LocationChangedEventArgs e) { UpdateActiveNode(); InvokeAsync(StateHasChanged); } private void UpdateActiveNode() => _activeNodeId = NodePath.NodeIdOf(Nav.ToBaseRelativePath(Nav.Uri)); public void Dispose() { Nav.LocationChanged -= OnLocationChanged; } } Path: redb-tsak/src/redb.Tsak.Web/Components/Layout/TsakSidebar.razor.css Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Components/Layout/TsakSidebar.razor.css ---- /* Styles moved to wwwroot/css/app.css */ Path: redb-tsak/src/redb.Tsak.Web/Components/Layout/TsakTopBar.razor Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Components/Layout/TsakTopBar.razor ---- @using Microsoft.AspNetCore.Components.Authorization @inject INodeClientProvider NodeProvider @inject IJSRuntime JS

@GetPageTitle()

@if (NodeProvider.Topology is { } topo) {
@topo.ClusterName n.IsAlive)} / {topo.Nodes.Count}")" Variant="online" />
} @_displayName
@code { [CascadingParameter] private Task? AuthState { get; set; } private string _themeIcon = "sun"; private string? _displayName; private string? _role; private bool _isAdmin; protected override async Task OnParametersSetAsync() { if (AuthState is null) return; var user = (await AuthState).User; _displayName = user.FindFirst("display_name")?.Value ?? user.Identity?.Name; _role = user.FindFirst(System.Security.Claims.ClaimTypes.Role)?.Value; _isAdmin = user.IsInRole("admin"); } protected override async Task OnAfterRenderAsync(bool firstRender) { if (firstRender) { var theme = await JS.InvokeAsync("tsakTheme.get"); _themeIcon = theme == "dark" ? "sun" : "moon"; StateHasChanged(); } } private async Task ToggleTheme() { var newTheme = await JS.InvokeAsync("tsakTheme.toggle"); _themeIcon = newTheme == "dark" ? "sun" : "moon"; } private string GetPageTitle() { // Simple page title from URL return "Dashboard"; } } Path: redb-tsak/src/redb.Tsak.Web/Components/Layout/TsakTopBar.razor.css Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Components/Layout/TsakTopBar.razor.css ---- /* Styles moved to wwwroot/css/app.css */ Path: redb-tsak/src/redb.Tsak.Web/Components/Pages/About.razor Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Components/Pages/About.razor ---- @page "/about" @inject INodeClientProvider NodeProvider @using System.Reflection @using redb.Tsak.Client @using redb.Tsak.Contracts
@* Product *@
redb.Tsak
Dashboard version@DashboardVersion
DescriptionRuntime container for redb.Route contexts with management API
LicenseApache-2.0 (open source). Pro components are free and require no license key.
@* Links *@
@* Node *@
Node @if (_aliveNodes.Count > 1) { }
@if (_infoError is not null) {

Failed to load node info: @_infoError

} else if (_info is null) {

@(_loading ? "Loading…" : "No live node available.")

} else {
Node@_selectedNodeId
Node version@(_info.InformationalVersion ?? _info.Version)
Machine@_info.MachineName
Started@_info.StartedAt.ToString("yyyy-MM-dd HH:mm:ss")
Uptime@_info.Uptime
Contexts / Modules@_info.ContextCount / @_info.ModuleCount
}
@* Which redb is REALLY running — admin only (the API refuses non-admins anyway) *@
Loaded redb assemblies @if (_assemblies is not null) { @_assemblies.RedbCount of @_assemblies.Count loaded }
@if (_assembliesError is not null) {

Failed to load assemblies: @_assembliesError

} else if (_assemblies is null) {

@(_loading ? "Loading…" : "No live node available.")

} else { Assembly Version Source @context.Name @(context.Version ?? "—") @context.Source }
@code { // Same source as the startup banner: informational version ("3.7.2") with the +metadata // suffix cut, falling back to the four-part assembly version. private static readonly string DashboardVersion = typeof(About).Assembly.GetCustomAttribute() ?.InformationalVersion?.Split('+')[0] ?? typeof(About).Assembly.GetName().Version?.ToString() ?? "unknown"; [CascadingParameter] private Task? AuthState { get; set; } private bool _loading = true; private bool _isAdmin; private List _aliveNodes = []; private string _selectedNodeId = ""; private SystemInfoResponse? _info; private string? _infoError; private AssembliesResponse? _assemblies; private string? _assembliesError; private string SelectedNodeId { get => _selectedNodeId; set { if (_selectedNodeId == value) return; _selectedNodeId = value; _ = InvokeAsync(async () => { await LoadNodeAsync(); StateHasChanged(); }); } } protected override async Task OnInitializedAsync() { var state = AuthState is null ? null : await AuthState; _isAdmin = state?.User?.IsInRole("admin") ?? false; var topology = await NodeProvider.LoadTopologyAsync(); _aliveNodes = topology.Nodes.Where(n => n.IsAlive).ToList(); _selectedNodeId = _aliveNodes.FirstOrDefault()?.NodeId ?? ""; await LoadNodeAsync(); _loading = false; } private async Task LoadNodeAsync() { _info = null; _infoError = null; _assemblies = null; _assembliesError = null; var client = string.IsNullOrEmpty(_selectedNodeId) ? null : NodeProvider.GetClient(_selectedNodeId); if (client is null) return; try { _info = await client.GetInfoAsync(); } catch (Exception ex) { _infoError = ex.Message; // surfaced in the UI, deliberately not swallowed } // Admin-only fetch: the endpoint requires the admin role, a call from a lower tier // would just burn a request to get a 403. if (_isAdmin) { try { _assemblies = await client.GetAssembliesAsync(); } catch (Exception ex) { _assembliesError = ex.Message; // surfaced in the UI, deliberately not swallowed } } } } Path: redb-tsak/src/redb.Tsak.Web/Components/Pages/Audit.razor Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Components/Pages/Audit.razor ---- @page "/node/{NodeId}/audit" @* Admin tier: matches the worker API (AuditController is Admin-only — the trail enumerates who did what; review 2026-09-02 В13). *@ @attribute [Authorize(Policy = "Admin")] @inject INodeClientProvider NodeProvider @inject NavigationManager Nav @inject ToastService Toast @using redb.Tsak.Client @using redb.Tsak.Contracts @using redb.Tsak.Web.Components.Shared @* All filtering and paging is server-side — the audit table can be very large, so nothing is pulled into the browser and filtered there. *@
@if (HasAnyFilter) { }
@if (_loading) {

Loading…

} else if (_unavailable) {

@(_error ?? "The audit trail is not available — this node runs without a database. " + "Admin actions are written to the log instead (grep for the [tsak-audit] anchor).")

} else {
@if (_entries.Length == 0) { } else { @foreach (var e in _entries) { @if (e.ExceptionType is not null) { } } }
Time Actor Action Target Status Duration IP

No audit entries match the current filters.

@e.Timestamp.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss") @(e.ActorPrincipal ?? e.ActorKeyId ?? "—") @e.Action @(e.TargetResource ?? "—") @e.DurationMs.ToString("F0") ms @(e.RemoteIp ?? "—")
@e.ExceptionType: @e.ExceptionMessage
@* Pagination — offset/limit driven, next enabled only when the page came back full. *@
Page @(_page + 1) · showing @_entries.Length (offset @(_page * _pageSize))
} @code { [Parameter] public string NodeId { get; set; } = ""; private string _actor = ""; private string _action = ""; private string _target = ""; private DateTime? _since; private DateTime? _until; private int _pageSize = 50; private int _page; private AuditEntry[] _entries = []; private bool _hasNextPage; private bool _loading = true; private bool _unavailable; private string? _error; private bool HasAnyFilter => !string.IsNullOrEmpty(_actor) || !string.IsNullOrEmpty(_action) || !string.IsNullOrEmpty(_target) || _since is not null || _until is not null; // The text filters travel in the address (?actor=..&action=..&target=..), written when a search runs, so a reload, // a shared link and the node switcher keep them. [SupplyParameterFromQuery(Name = "actor")] public string? ActorQuery { get; set; } [SupplyParameterFromQuery(Name = "action")] public string? ActionQuery { get; set; } [SupplyParameterFromQuery(Name = "target")] public string? TargetQuery { get; set; } protected override Task OnInitializedAsync() { _actor = ActorQuery ?? ""; _action = ActionQuery ?? ""; _target = TargetQuery ?? ""; return LoadAsync(resetPage: true); } private async Task LoadAsync(bool resetPage) { if (resetPage) { _page = 0; QueryState.Set(Nav, new Dictionary { ["actor"] = _actor, ["action"] = _action, ["target"] = _target }); } _loading = true; _error = null; StateHasChanged(); try { // Null-guard like Dlq's (review 2026-09-02, С26): a stale bookmark to a removed node // showed a raw NullReferenceException text instead of a clean unavailable state. var client = NodeProvider.GetClient(NodeId); if (client is null) { _unavailable = true; _error = $"Node '{NodeId}' is not available."; _entries = []; return; } var result = await client.GetAuditAsync( actor: NullIfBlank(_actor), action: NullIfBlank(_action), target: NullIfBlank(_target), since: _since is { } s ? new DateTimeOffset(DateTime.SpecifyKind(s, DateTimeKind.Utc)) : null, until: _until is { } u ? new DateTimeOffset(DateTime.SpecifyKind(u, DateTimeKind.Utc)) : null, limit: _pageSize, offset: _page * _pageSize); if (!result.Available) { _unavailable = true; _error = result.Error; _entries = []; } else { _unavailable = false; _entries = result.Entries; // A full page implies there may be more; a short page is the last one. _hasNextPage = _entries.Length == _pageSize; } } catch (Exception ex) { _unavailable = true; _error = ex.Message; Toast.Error($"Failed to load audit: {ex.Message}"); } finally { _loading = false; StateHasChanged(); } } private async Task NextPage() { if (!_hasNextPage) return; _page++; await LoadAsync(resetPage: false); } private async Task PrevPage() { if (_page == 0) return; _page--; await LoadAsync(resetPage: false); } private async Task ClearFilters() { _actor = _action = _target = ""; _since = _until = null; await LoadAsync(resetPage: true); } private async Task OnFilterKeyDown(KeyboardEventArgs e) { if (e.Key == "Enter") await LoadAsync(resetPage: true); } private static string? NullIfBlank(string s) => string.IsNullOrWhiteSpace(s) ? null : s.Trim(); private static string StatusVariant(int status) => status switch { >= 500 => "error", >= 400 => "warning", _ => "online" }; } Path: redb-tsak/src/redb.Tsak.Web/Components/Pages/Auth.razor Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Components/Pages/Auth.razor ---- @page "/auth" @* Admin tier: matches the worker API (AuthController is Admin-only — key inventory and user management; review 2026-09-02 В13). *@ @attribute [Authorize(Policy = "Admin")] @inject INodeClientProvider NodeProvider @inject ToastService Toast @using redb.Tsak.Contracts @using Microsoft.AspNetCore.Components.Authorization @if (_showCreate) {
Create new API key
@if (_createdKey is not null) {

Key created — copy it now, it won't be shown again:

@_createdKey
}
} @if (_loading) {

Loading keys…

} else if (_keys.Count == 0) {

No API keys

No running nodes returned API key data.

} else { @foreach (var (nodeId, keys) in _keys) {
@nodeId
@keys.Length keys
ID Name Roles Created Valid Actions @context.Id[..Math.Min(8, context.Id.Length)]… @context.Name @context.Roles @context.CreatedAt.ToString("yyyy-MM-dd HH:mm") @if (context.IsValid) { }
} } @* ── Users section (admin only) ────────────────────────────────── *@

Users

@if (_showUserForm) {
@(_editingUser is null ? "Create user" : $"Edit {_editingUser.Login}")
@if (_editingUser is null) {
}
} @if (_users.Length > 0) {
Login Name Role Enabled Registered Actions @context.Login @context.Name @(context.DateRegister?.ToString("yyyy-MM-dd") ?? "—") @if (context.Id > 1 && context.Login != _currentLogin) { }
} else if (!_loading) {

No users

Create the first user account.

}
@code { private readonly Dictionary _keys = new(); private TsakUserInfo[] _users = []; private bool _loading = true; private bool _showCreate; private string _newKeyName = ""; private string _newKeyRoles = ""; private string? _createdKey; private TsakConfirmDialog? _confirm; [CascadingParameter] private Task? AuthState { get; set; } private string? _currentLogin; // User form private bool _showUserForm; private TsakUserInfo? _editingUser; private string _userLogin = ""; private string _userName = ""; private string _userPassword = ""; private string _userRole = "viewer"; protected override async Task OnInitializedAsync() { if (AuthState is not null) _currentLogin = (await AuthState).User.Identity?.Name; await LoadData(); } private async Task LoadData() { _loading = true; _keys.Clear(); _users = []; StateHasChanged(); var topology = await NodeProvider.LoadTopologyAsync(); foreach (var node in topology.Nodes.Where(n => n.IsAlive)) { var client = NodeProvider.GetClient(node.NodeId); if (client is null) continue; var keys = await client.ListApiKeysAsync(); if (keys.Length > 0) _keys[node.NodeId] = keys; if (_users.Length == 0) { try { _users = await client.ListUsersAsync(); } catch { /* node may not support users API yet */ } } } _loading = false; } // ── API Keys ───────────────────────────────────────────────────── private void ShowCreateForm() { _showCreate = true; _createdKey = null; _newKeyName = ""; _newKeyRoles = ""; } private async Task CreateKey() { if (string.IsNullOrWhiteSpace(_newKeyName)) return; var topology = await NodeProvider.LoadTopologyAsync(); var node = topology.Nodes.FirstOrDefault(n => n.IsAlive); if (node is null) return; var client = NodeProvider.GetClient(node.NodeId); if (client is null) return; var roles = string.IsNullOrWhiteSpace(_newKeyRoles) ? null : _newKeyRoles.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); var result = await client.CreateApiKeyAsync(_newKeyName, roles); _createdKey = result.Key; Toast.Success($"API key '{_newKeyName}' created"); await LoadData(); } private async Task RevokeKey(string nodeId, string keyId) { if (_confirm is not null) { var confirmed = await _confirm.ShowAsync( $"Revoke API key {keyId[..Math.Min(8, keyId.Length)]}…? This cannot be undone.", "Revoke API key"); if (!confirmed) return; } var client = NodeProvider.GetClient(nodeId); if (client is null) return; await client.RevokeApiKeyAsync(keyId); Toast.Success("API key revoked"); await LoadData(); } // ── Users ──────────────────────────────────────────────────────── private void ShowUserForm(TsakUserInfo? user) { _editingUser = user; _showUserForm = true; _userLogin = user?.Login ?? ""; _userName = user?.Name ?? ""; _userPassword = ""; _userRole = user?.Role ?? "viewer"; } private async Task SaveUser() { var client = await GetFirstAliveClientAsync(); if (client is null) return; try { if (_editingUser is null) { var request = new TsakCreateUserRequest { Login = _userLogin, Password = _userPassword, Name = _userName, Role = _userRole }; await client.CreateUserAsync(request); Toast.Success($"User '{_userLogin}' created"); } else { var request = new TsakUpdateUserRequest { Name = _userName != _editingUser.Name ? _userName : null, Role = _userRole != _editingUser.Role ? _userRole : null, Password = string.IsNullOrWhiteSpace(_userPassword) ? null : _userPassword }; await client.UpdateUserAsync(_editingUser.Login, request); Toast.Success($"User '{_editingUser.Login}' updated"); } _showUserForm = false; await LoadData(); } catch (Exception ex) { Toast.Error(ex.Message); } } private async Task DeleteUser(string login) { if (_confirm is not null) { var confirmed = await _confirm.ShowAsync( $"Delete user '{login}'? This cannot be undone.", "Delete user"); if (!confirmed) return; } var client = await GetFirstAliveClientAsync(); if (client is null) return; try { await client.DeleteUserAsync(login); Toast.Success($"User '{login}' deleted"); await LoadData(); } catch (Exception ex) { Toast.Error(ex.Message); } } private async Task GetFirstAliveClientAsync() { var topology = await NodeProvider.LoadTopologyAsync(); var node = topology.Nodes.FirstOrDefault(n => n.IsAlive); return node is null ? null : NodeProvider.GetClient(node.NodeId); } } Path: redb-tsak/src/redb.Tsak.Web/Components/Pages/Cluster.razor Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Components/Pages/Cluster.razor ---- @page "/cluster" @inject INodeClientProvider NodeProvider @inject ILogger Log @inject NavigationManager Nav @inject ToastService Toast @implements IDisposable @if (!NodeProvider.IsCluster) {

Cluster mode is not enabled

Configure Tsak:Web:Mode = "cluster" to enable cluster management.

} else if (_topology is null) {

Loading topology…

} else { @foreach (var group in _topology.Groups) { var groupNodes = _topology.Nodes.Where(n => n.GroupName == group.GroupName).ToList(); // Leadership is per group (review 2026-09-02, С14): the old single Leader field showed an // arbitrary group's leader star on every section. var leader = _topology.Leaders.GetValueOrDefault(group.GroupName);
@group.GroupName @if (!string.IsNullOrEmpty(group.Description)) { — @group.Description }
@groupNodes.Count(n => n.IsAlive) / @groupNodes.Count online

No nodes in this group

Node ID Hostname Status Endpoint Started Heartbeat Capabilities @if (leader?.NodeId == context.NodeId) { ★ } @context.NodeId @context.Hostname @if (context.Cordoned) { } @(string.IsNullOrEmpty(context.ApiEndpoint) ? "—" : context.ApiEndpoint) @context.StartedAt.ToString("yyyy-MM-dd HH:mm") @FormatAgo(context.LastHeartbeat) @(string.IsNullOrEmpty(context.Capabilities) ? "—" : context.Capabilities) @if (context.Status == NodeStatus.Online) { @if (context.Cordoned) { } else { } } else if (context.Status is NodeStatus.Dead or NodeStatus.Offline) { }
} @if (_topology.Assignments.Count > 0) {
Module assignments
Module Node Group State Assigned @context.ModuleName @context.NodeId @context.GroupName @context.State @context.AssignedAt.ToString("yyyy-MM-dd HH:mm")
} } @code { private ClusterTopology? _topology; private TsakConfirmDialog? _confirm; private PeriodicTimer? _timer; private CancellationTokenSource? _cts; protected override async Task OnInitializedAsync() { // _cts BEFORE the initial load — a component disposed mid-load must not start an // unstoppable orphan poll loop afterwards (review 2026-09-02, С19). _cts = new CancellationTokenSource(); _topology = await NodeProvider.LoadTopologyAsync(); if (!_cts.IsCancellationRequested) _ = PollLoop(_cts.Token); } private Task PollLoop(CancellationToken ct) { _timer = new PeriodicTimer(TimeSpan.FromSeconds(30)); return PollLoops.RunAsync(_timer, ct, Log, async () => { _topology = await NodeProvider.LoadTopologyAsync(forceRefresh: true); await InvokeAsync(StateHasChanged); }); } private async Task Refresh() { _topology = await NodeProvider.LoadTopologyAsync(forceRefresh: true); } private void NavigateToNode(string nodeId) => Nav.NavigateTo($"node/{nodeId}"); public void Dispose() { _cts?.Cancel(); _cts?.Dispose(); _timer?.Dispose(); } private static string GetBadgeClass(NodeInfo node) => node.Status switch { NodeStatus.Online when node.IsAlive => "online", NodeStatus.Online => "warning", NodeStatus.Offline => "offline", NodeStatus.Dead => "error", _ => "offline" }; private static string FormatAgo(DateTimeOffset timestamp) { var diff = DateTimeOffset.UtcNow - timestamp; if (diff.TotalSeconds < 60) return $"{(int)diff.TotalSeconds}s ago"; if (diff.TotalMinutes < 60) return $"{(int)diff.TotalMinutes}m ago"; if (diff.TotalHours < 24) return $"{(int)diff.TotalHours}h ago"; return $"{(int)diff.TotalDays}d ago"; } private async Task SetCordon(string nodeId, bool cordon) { try { var ok = await NodeProvider.SetCordonedAsync(nodeId, cordon); if (ok) { Toast.Success(cordon ? $"Node '{nodeId}' cordoned — draining, takes no new work" : $"Node '{nodeId}' uncordoned"); _topology = await NodeProvider.LoadTopologyAsync(forceRefresh: true); } else { Toast.Error($"Node '{nodeId}' not found"); } } catch (Exception ex) { Toast.Error($"Failed: {ex.Message}"); } } private async Task RemoveNode(string nodeId) { if (_confirm is not null) { var confirmed = await _confirm.ShowAsync( $"Remove node '{nodeId}' from the cluster? This cannot be undone.", "Remove node"); if (!confirmed) return; } try { var removed = await NodeProvider.RemoveNodeAsync(nodeId); if (removed) { Toast.Success($"Node '{nodeId}' removed"); _topology = await NodeProvider.LoadTopologyAsync(forceRefresh: true); } else { Toast.Error($"Cannot remove node '{nodeId}' — not found or still online"); } } catch (Exception ex) { Toast.Error(ex.Message); } } } Path: redb-tsak/src/redb.Tsak.Web/Components/Pages/Dashboard.razor Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Components/Pages/Dashboard.razor ---- @page "/" @inject INodeClientProvider NodeProvider @inject ILogger Log @inject NavigationManager Nav @using redb.Tsak.Client @using redb.Tsak.Contracts @implements IDisposable @if (_loading) {

Loading cluster data…

} else if (_topology is not null) {
@_onlineCount @if (_onlineHistory.Count > 1) { }
@if (_topology.Leader is { } leader) {
Node @leader.NodeId
Epoch @leader.Epoch
Acquired @leader.AcquiredAt.ToString("yyyy-MM-dd HH:mm:ss")
Expires @leader.ExpiresAt.ToString("yyyy-MM-dd HH:mm:ss")
}
Node Status
Nodes
Node Hostname Group Status Heartbeat Version @context.NodeId @context.Hostname @context.GroupName @FormatAgo(context.LastHeartbeat) @context.Version
@* ── Route & Watchdog Section (per-node) ───────────────── *@ @if (_topology.Nodes.Any(n => n.IsAlive)) {

Node Dashboard

@if (_dashboard is not null) {
@_dashboard.ActiveAlerts.Count @if (_dashboard.ActiveAlerts.Count > 0) { }
@if (_dashboard.SystemMetrics is { } sm) { @($"{sm.CpuPercent:F0}%") / @($"{sm.MemoryMB:F0}MB") }
@* Top Busiest Routes *@ @if (_dashboard.BusiestRoutes.Count > 0) {
Top Busiest Routes — @_selectedNodeId
Route Status Messages Throughput Inflight Rejected Refused @context.RouteId @context.MessagesProcessed @($"{context.ThroughputPerSecond:F1}/s") @context.InflightCount @context.Rejected @context.Refused
} @* Top Error Routes *@ @if (_dashboard.ErrorProneRoutes.Count > 0) {
Error-Prone Routes — @_selectedNodeId
Route Errors Last Error Last Error Time @context.RouteId @context.Errors @(context.LastError ?? "—") @(context.LastErrorTime?.ToString("HH:mm:ss") ?? "—")
} @* Shedding Routes — turned away by admission limits; healthy but under-provisioned, so not folded into Error-Prone *@ @if (_dashboard.SheddingRoutes.Count > 0) {
Shedding Routes — @_selectedNodeId
Route Rejected Throughput Inflight @context.RouteId @context.Rejected @($"{context.ThroughputPerSecond:F1}/s") @context.InflightCount
} } @* Watchdog & Lifecycle panels *@
} } @code { private ClusterTopology? _topology; private bool _loading = true; private int _onlineCount; private TsakChart? _donutChart; private bool _donutDrawn; private PeriodicTimer? _timer; private CancellationTokenSource? _cts; // Component-scoped token: API calls abort when the component is disposed (navigated away) (4.9). // Guard the disposed state — reading _cts.Token after Dispose throws ObjectDisposedException; a call // that started before Dispose already holds the (now-cancelled) token, so returning None here is safe. private CancellationToken Ct { get { try { return _cts?.Token ?? default; } catch (ObjectDisposedException) { return default; } } } private readonly List _onlineHistory = new(); // Per-node dashboard private string _selectedNodeId = ""; private TsakApiClient? _selectedClient; private DashboardSnapshot? _dashboard; private WatchdogPanel? _watchdogPanel; private LifecyclePanel? _lifecyclePanel; private string SelectedNodeId { get => _selectedNodeId; set { if (_selectedNodeId == value) return; _selectedNodeId = value; _selectedClient = string.IsNullOrEmpty(value) ? null : NodeProvider.GetClient(value); // Drop the previous node's snapshot immediately and re-render when the new one lands — // otherwise the cards showed the OLD node's numbers under the NEW node's label for up // to a poll interval (review 2026-09-02, С26). _dashboard = null; _ = InvokeAsync(async () => { await LoadNodeDashboard(); StateHasChanged(); }); } } protected override async Task OnInitializedAsync() { // _cts BEFORE the initial load — a component disposed mid-load must not start an // unstoppable orphan poll loop afterwards (review 2026-09-02, С19). _cts = new CancellationTokenSource(); await LoadData(); if (!_cts.IsCancellationRequested) _ = PollLoop(_cts.Token); } protected override async Task OnAfterRenderAsync(bool firstRender) { // Not firstRender: in interactive mode the first render is the loading spinner, and the // chart component only exists from the render after the initial load completes. if (!_donutDrawn && _donutChart is not null && _topology is not null) { _donutDrawn = true; await UpdateDonutChart(); } } private Task PollLoop(CancellationToken ct) { _timer = new PeriodicTimer(TimeSpan.FromSeconds(10)); // The tick must run on the Blazor dispatcher: PollLoops continues on the thread pool, and // this body refreshes child panels whose StateHasChanged throws off the dispatcher — that // exception killed every tick (no status donut, no auto-refresh) until 2026-09-14. return PollLoops.RunAsync(_timer, ct, Log, () => InvokeAsync(async () => { await LoadData(); await UpdateDonutChart(); StateHasChanged(); })); } private async Task LoadData() { // The spinner belongs to the initial load only (_loading starts true). Re-entering it on // a reload swapped the whole topology block out and destroyed the donut's canvas. _topology = await NodeProvider.LoadTopologyAsync(forceRefresh: true); _onlineCount = _topology.Nodes.Count(n => n.IsAlive); _onlineHistory.Add(_onlineCount); if (_onlineHistory.Count > 20) _onlineHistory.RemoveAt(0); // Auto-select first online node if none selected if (string.IsNullOrEmpty(_selectedNodeId)) { var firstAlive = _topology.Nodes.FirstOrDefault(n => n.IsAlive); if (firstAlive is not null) { _selectedNodeId = firstAlive.NodeId; _selectedClient = NodeProvider.GetClient(firstAlive.NodeId); } } await LoadNodeDashboard(); _loading = false; } private async Task LoadNodeDashboard() { if (_selectedClient is null) { _dashboard = null; return; } try { _dashboard = await _selectedClient.GetDashboardAsync(Ct); } catch { _dashboard = null; } if (_watchdogPanel is not null) await _watchdogPanel.RefreshAsync(); if (_lifecyclePanel is not null) await _lifecyclePanel.RefreshAsync(); } private async Task Refresh() { await LoadData(); await UpdateDonutChart(); } private async Task UpdateDonutChart() { if (_donutChart is null || _topology is null) return; var online = _topology.Nodes.Count(n => n.IsAlive); var offline = _topology.Nodes.Count(n => n.Status == NodeStatus.Offline); var dead = _topology.Nodes.Count(n => n.Status == NodeStatus.Dead); var stale = _topology.Nodes.Count(n => n.Status == NodeStatus.Online && !n.IsAlive); await _donutChart.CreateDonutAsync( ["Online", "Stale", "Offline", "Dead"], [(double)online, (double)stale, (double)offline, (double)dead], ["#22c55e", "#f59e0b", "#6b7280", "#ef4444"]); } private static string GetStatusBadge(NodeInfo node) => node.Status switch { NodeStatus.Online when node.IsAlive => "online", NodeStatus.Online => "warning", NodeStatus.Offline => "offline", NodeStatus.Dead => "error", _ => "offline" }; private static string FormatAgo(DateTimeOffset timestamp) { var diff = DateTimeOffset.UtcNow - timestamp; if (diff.TotalSeconds < 60) return $"{(int)diff.TotalSeconds}s ago"; if (diff.TotalMinutes < 60) return $"{(int)diff.TotalMinutes}m ago"; if (diff.TotalHours < 24) return $"{(int)diff.TotalHours}h ago"; return $"{(int)diff.TotalDays}d ago"; } public void Dispose() { _cts?.Cancel(); _cts?.Dispose(); _timer?.Dispose(); } private void NavigateToNode(string nodeId) => Nav.NavigateTo($"node/{nodeId}"); private static string GetRouteBadge(string status) => status switch { "Started" => "online", "Stopped" => "offline", "Suspended" => "warning", _ => "offline" }; } Path: redb-tsak/src/redb.Tsak.Web/Components/Pages/Denied.razor Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Components/Pages/Denied.razor ---- @page "/denied" @* Where the auth cookie sends a signed-in user whose role does not open the page they asked for (CookieAuthenticationOptions.AccessDeniedPath). An anonymous visitor never gets here: this page requires a signed-in user like every other one. *@ Path: redb-tsak/src/redb.Tsak.Web/Components/Pages/Dlq.razor Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Components/Pages/Dlq.razor ---- @page "/node/{NodeId}/dlq" @* Operator tier: matches the worker API (ExchangesController — listing exposes payload details, replay re-executes business code; review 2026-09-02 В13). *@ @attribute [Authorize(Policy = "Operator")] @inject INodeClientProvider NodeProvider @inject NavigationManager Nav @inject ToastService Toast @using redb.Tsak.Client @using redb.Tsak.Contracts @using redb.Tsak.Web.Components.Shared @* Server-side filters + paging — the DLQ can be large, nothing is pulled into the browser. *@
@if (_loading) {

Loading…

} else if (_unavailable) {

@(_error ?? "The dead-letter store is not available — this node runs without a database.")

} else {
@if (_entries.Length == 0) { } else { @foreach (var e in _entries) { } }
Time Route Marker Status Error

No dead-lettered exchanges.

@e.OccurredAt.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss") @e.RouteId @e.MarkerName @(e.ExceptionType ?? "—") @if (!e.Replayable) { not replayable }
Page @(_page + 1) · showing @_entries.Length
} @code { [Parameter] public string NodeId { get; set; } = ""; private string _route = ""; private string _context = ""; private string _status = ""; private int _pageSize = 50; private int _page; private FailedExchangeEntry[] _entries = []; private bool _hasNext; private bool _loading = true; private bool _unavailable; private string? _error; private string? _busy; // The filters travel in the address (?context=..&route=..&status=..), written when a search runs, so a reload, a // shared link and the node switcher keep them. [SupplyParameterFromQuery(Name = "context")] public string? ContextQuery { get; set; } [SupplyParameterFromQuery(Name = "route")] public string? RouteQuery { get; set; } [SupplyParameterFromQuery(Name = "status")] public string? StatusQuery { get; set; } protected override Task OnInitializedAsync() { _context = ContextQuery ?? ""; _route = RouteQuery ?? ""; _status = StatusQuery ?? ""; return LoadAsync(resetPage: true); } private async Task LoadAsync(bool resetPage) { if (resetPage) { _page = 0; QueryState.Set(Nav, new Dictionary { ["context"] = _context, ["route"] = _route, ["status"] = _status }); } _loading = true; StateHasChanged(); try { var client = NodeProvider.GetClient(NodeId); if (client is null) { // Node not in the current topology (removed, or not yet discovered) — show a clean // empty/unavailable state instead of throwing a NullReferenceException (review 4.8). _unavailable = true; _error = $"Node '{NodeId}' is not available."; _entries = []; return; } var result = await client.GetFailedExchangesAsync( context: NullIfBlank(_context), route: NullIfBlank(_route), status: NullIfBlank(_status), limit: _pageSize, offset: _page * _pageSize); if (!result.Available) { _unavailable = true; _error = result.Error; _entries = []; } else { _unavailable = false; _entries = result.Entries; _hasNext = _entries.Length == _pageSize; } } catch (Exception ex) { _unavailable = true; _error = ex.Message; Toast.Error($"Failed to load DLQ: {ex.Message}"); } finally { _loading = false; StateHasChanged(); } } private async Task Replay(string id) { var client = NodeProvider.GetClient(NodeId); if (client is null) { Toast.Error($"Node '{NodeId}' is not available."); return; } _busy = id; try { var result = await client.ReplayExchangeAsync(id); if (result.Success) Toast.Success("Replayed"); else Toast.Warning(result.Message); await LoadAsync(resetPage: false); } catch (Exception ex) { Toast.Error($"Replay failed: {ex.Message}"); } finally { _busy = null; } } private async Task Discard(string id) { var client = NodeProvider.GetClient(NodeId); if (client is null) { Toast.Error($"Node '{NodeId}' is not available."); return; } _busy = id; try { var result = await client.DiscardExchangeAsync(id); if (result.Success) Toast.Success("Discarded"); else Toast.Warning(result.Message); await LoadAsync(resetPage: false); } catch (Exception ex) { Toast.Error($"Discard failed: {ex.Message}"); } finally { _busy = null; } } private async Task NextPage() { if (_hasNext) { _page++; await LoadAsync(resetPage: false); } } private async Task PrevPage() { if (_page > 0) { _page--; await LoadAsync(resetPage: false); } } private async Task OnKeyDown(KeyboardEventArgs e) { if (e.Key == "Enter") await LoadAsync(resetPage: true); } private static string? NullIfBlank(string s) => string.IsNullOrWhiteSpace(s) ? null : s.Trim(); private static string StatusVariant(string status) => status switch { "pending" => "warning", "replayed" => "online", "discarded" => "offline", _ => "info" }; } Path: redb-tsak/src/redb.Tsak.Web/Components/Pages/Endpoints.razor Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Components/Pages/Endpoints.razor ---- @page "/node/{NodeId}/endpoints" @inject INodeClientProvider NodeProvider @inject ILogger Log @inject NavigationManager Nav @inject ToastService Toast @using redb.Tsak.Client @using redb.Tsak.Contracts @using redb.Tsak.Web.Components.Shared @implements IDisposable @if (_loading) {

Loading endpoints…

} else if (_contexts is { Length: > 0 }) { @* Stat cards *@
@ConsumerCount / @ProducerCount
@* Context groups *@ @* Show every context (incl. anonymous _dyn_ modules) so the list matches the stat cards and the other pages, which never hid them. *@ @foreach (var ctx in _contexts.OrderBy(c => c.Name)) { var filteredEndpoints = FilterEndpoints(ctx.Endpoints); if (_typeFilter != "All" && filteredEndpoints.Length == 0) { continue; }
@ctx.Name (@filteredEndpoints.Length endpoints)
@if (!_collapsed.Contains(ctx.Name)) {
@if (filteredEndpoints.Length > 0) {

Endpoints

URI Type Role In / Out Errors Rejected Refused Throughput Health Last Activity Uptime @context.Uri @GetRoleLabel(context) @FormatNumber(context.MessagesIn) / @FormatNumber(context.MessagesOut) @context.Errors @context.Rejected @context.Refused @($"{context.ThroughputPerSecond:F1}/s") @FormatTimeAgo(context.LastActivity) @FormatUptime(context.Uptime) } else if (_typeFilter != "All") {

No endpoints matching filter "@_typeFilter"

}
}
} } else {

No endpoints on this node

} @* Detail modal *@ @if (_selectedEndpoint is not null) { } @code { [Parameter] public string NodeId { get; set; } = ""; private bool _loading = true; private ContextDetail[]? _contexts; // The type filter travels in the address (?type=Http), so a reload, a shared link and the node switcher keep it. [SupplyParameterFromQuery(Name = "type")] public string? TypeQuery { get; set; } private string _typeValue = "All"; private string _typeFilter { get => _typeValue; set { _typeValue = string.IsNullOrEmpty(value) ? "All" : value; QueryState.Set(Nav, "type", _typeValue, "All"); } } private readonly HashSet _collapsed = new(); // Modal private TsakEndpointInfo? _selectedEndpoint; private string? _selectedContext; // Polling private PeriodicTimer? _timer; private CancellationTokenSource? _cts; // Component-scoped token: API calls abort when the component is disposed (navigated away) (4.9). // Guard the disposed state — reading _cts.Token after Dispose throws ObjectDisposedException; a call // that started before Dispose already holds the (now-cancelled) token, so returning None here is safe. private CancellationToken Ct { get { try { return _cts?.Token ?? default; } catch (ObjectDisposedException) { return default; } } } // Computed stats private int TotalEndpoints => _contexts?.Sum(c => c.Endpoints.Length) ?? 0; private int ActiveEndpoints => _contexts? .Where(c => c.Status is "Running" or "Started") .Sum(c => c.Endpoints.Length) ?? 0; private int ErrorEndpoints => _contexts?.Sum(c => c.Endpoints.Count(e => e.Errors > 0)) ?? 0; private long TotalMessages => _contexts?.Sum(c => c.Endpoints.Sum(e => e.MessagesIn + e.MessagesOut)) ?? 0; private double TotalThroughput => _contexts?.Sum(c => c.Endpoints.Sum(e => e.ThroughputPerSecond)) ?? 0; private int ConsumerCount => _contexts?.Sum(c => c.Endpoints.Count(e => e.IsConsumer)) ?? 0; private int ProducerCount => _contexts?.Sum(c => c.Endpoints.Count(e => e.IsProducer)) ?? 0; private string[] AvailableTypes => _contexts? .SelectMany(c => c.Endpoints.Select(e => GetEndpointType(e.Scheme))) .Distinct().OrderBy(t => t).ToArray() ?? []; protected override async Task OnInitializedAsync() { _typeValue = string.IsNullOrEmpty(TypeQuery) ? "All" : TypeQuery; // _cts BEFORE the initial load — a component disposed mid-load must not start an // unstoppable orphan poll loop afterwards (review 2026-09-02, С19). _cts = new CancellationTokenSource(); await LoadData(); if (!_cts.IsCancellationRequested) _ = PollLoop(_cts.Token); } private Task PollLoop(CancellationToken ct) { _timer = new PeriodicTimer(TimeSpan.FromSeconds(10)); return PollLoops.RunAsync(_timer, ct, Log, async () => { await LoadData(); await InvokeAsync(StateHasChanged); }); } private async Task LoadData() { var client = NodeProvider.GetClient(NodeId); if (client is null) { _loading = false; return; } try { var summaries = await client.ListContextsAsync(Ct); var details = new List(summaries.Length); foreach (var s in summaries) { try { details.Add(await client.GetContextAsync(s.Name, Ct)); } catch { /* skip failing contexts */ } } _contexts = details.ToArray(); } catch { /* retain previous data on error */ } _loading = false; } private async Task Refresh() { await LoadData(); } private TsakEndpointInfo[] FilterEndpoints(TsakEndpointInfo[] endpoints) { if (_typeFilter == "All") return endpoints; return endpoints.Where(e => GetEndpointType(e.Scheme) == _typeFilter).ToArray(); } private void ToggleCollapse(string name) { if (!_collapsed.Remove(name)) _collapsed.Add(name); } private void OnEndpointClick(TsakEndpointInfo endpoint) { _selectedEndpoint = endpoint; // Find context for this endpoint _selectedContext = _contexts? .FirstOrDefault(c => c.Endpoints.Any(e => e.Uri == endpoint.Uri))?.Name; } private void CloseModal() { _selectedEndpoint = null; _selectedContext = null; } // Type classification (from lt.tsak pattern, extended for redb.Route types) private static string GetEndpointType(string? scheme) => scheme?.ToLowerInvariant() switch { "direct" => "Direct", "rabbitmq" => "RabbitMQ", "kafka" => "Kafka", "cron" => "Cron", "timer" => "Timer", "http" or "https" => "HTTP", "redis" => "Redis", "mqtt" => "MQTT", "grpc" => "gRPC", "seda" => "SEDA", "file" => "File", "sql" or "mssql" or "postgres" => "SQL", "tcp" => "TCP", "validator" => "Validator", null or "" => "Unknown", var s => char.ToUpper(s[0]) + s[1..] }; private static string GetTypeBadgeVariant(string? scheme) => scheme?.ToLowerInvariant() switch { "direct" or "seda" => "info", "rabbitmq" => "warning", "kafka" => "info", "cron" or "timer" => "online", "http" or "https" or "grpc" => "error", "redis" or "mqtt" => "warning", "sql" or "mssql" or "postgres" => "info", "tcp" => "error", _ => "offline" }; private static string GetContextBadge(string status) => status switch { "Started" or "Running" => "online", "Stopped" => "offline", "Faulted" => "error", _ => "warning" }; private static string GetHealthBadge(string status) => status switch { "Healthy" => "online", "Warning" => "warning", "Critical" or "Failed" => "error", _ => "offline" }; private static string GetRoleLabel(TsakEndpointInfo ep) => ep.IsConsumer && ep.IsProducer ? "Both" : ep.IsConsumer ? "Consumer" : "Producer"; private static string FormatUptime(TimeSpan uptime) { if (uptime == TimeSpan.Zero) return "—"; if (uptime.TotalDays >= 1) return $"{(int)uptime.TotalDays}d {uptime.Hours}h"; if (uptime.TotalHours >= 1) return $"{(int)uptime.TotalHours}h {uptime.Minutes}m"; if (uptime.TotalMinutes >= 1) return $"{(int)uptime.TotalMinutes}m {uptime.Seconds}s"; return $"{uptime.Seconds}s"; } private static string FormatTimeAgo(DateTimeOffset? timestamp) { if (timestamp is null) return "—"; var diff = DateTimeOffset.UtcNow - timestamp.Value; if (diff.TotalSeconds < 60) return $"{(int)diff.TotalSeconds}s ago"; if (diff.TotalMinutes < 60) return $"{(int)diff.TotalMinutes}m ago"; if (diff.TotalHours < 24) return $"{(int)diff.TotalHours}h ago"; return $"{(int)diff.TotalDays}d ago"; } private static string FormatNumber(long num) { if (num == 0) return "0"; if (num < 1_000) return num.ToString(); if (num < 1_000_000) return $"{num / 1_000.0:F1}K"; if (num < 1_000_000_000) return $"{num / 1_000_000.0:F1}M"; return $"{num / 1_000_000_000.0:F1}B"; } private static string FormatBytes(long bytes) { if (bytes == 0) return "0 B"; if (bytes < 1024) return $"{bytes} B"; if (bytes < 1024 * 1024) return $"{bytes / 1024.0:F1} KB"; if (bytes < 1024 * 1024 * 1024) return $"{bytes / (1024.0 * 1024):F1} MB"; return $"{bytes / (1024.0 * 1024 * 1024):F1} GB"; } private static string FormatDuration(TimeSpan duration) { if (duration == TimeSpan.Zero) return "—"; if (duration.TotalMilliseconds < 1) return $"{duration.TotalMicroseconds:F0}µs"; if (duration.TotalSeconds < 1) return $"{duration.TotalMilliseconds:F1}ms"; if (duration.TotalMinutes < 1) return $"{duration.TotalSeconds:F1}s"; return $"{(int)duration.TotalMinutes}m {duration.Seconds}s"; } public void Dispose() { _cts?.Cancel(); _cts?.Dispose(); _timer?.Dispose(); } } Path: redb-tsak/src/redb.Tsak.Web/Components/Pages/Login.razor Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Components/Pages/Login.razor ---- @page "/login" @layout BlankLayout @attribute [Microsoft.AspNetCore.Authorization.AllowAnonymous] @code { [SupplyParameterFromQuery] private string? Error { get; set; } [SupplyParameterFromQuery] private string? ReturnUrl { get; set; } private string ErrorMessage => Error switch { "locked" => "Too many failed attempts. Try again later.", "stale" => "The form expired. Please try signing in again.", _ => "Invalid login or password." }; } Path: redb-tsak/src/redb.Tsak.Web/Components/Pages/Login.razor.css Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Components/Pages/Login.razor.css ---- /* Styles moved to wwwroot/css/app.css */ Path: redb-tsak/src/redb.Tsak.Web/Components/Pages/Logs.razor Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Components/Pages/Logs.razor ---- @page "/node/{NodeId}/logs" @* Operator tier: matches the worker API (LogsController — log bodies may carry payload fragments; review 2026-09-02 В13). *@ @attribute [Authorize(Policy = "Operator")] @inject INodeClientProvider NodeProvider @inject ILogger Log @inject ToastService Toast @inject NavigationManager Nav @inject IJSRuntime JS @inject LogTailCache Tails @using redb.Tsak.Client @using redb.Tsak.Contracts @using Microsoft.AspNetCore.Components.Web.Virtualization @implements IDisposable
@if (_activeTab == "live") { @* Filters *@
@(_tail?.LineCount ?? 0) shown / @(_tail?.BufferCapacity ?? 0) in the node's buffer
@if (_tail is { Unavailable: true }) {
This node keeps no log buffer.
} @* Log entries: the rows the page holds, filtered here; only the ones on screen are rendered. *@
@if (_tail is { HasOlder: true }) {
} @{ var view = FilteredRows; } @if (view.Count == 0) {

No log entries

} else { @if (row.Entry is { } entry) { } else { }
@LogTime.Header Level Message Source
@LogTime.Format(entry.Timestamp) @entry.Message @if (!string.IsNullOrEmpty(entry.Exception)) {
@entry.Exception
}
@(ShortenSource(entry.Source))
@row.Marker
}
} else { @* Files tab *@ @if (_filesLoading) {

Loading log files…

} else if (_logFiles is { Length: > 0 }) {
Log Files
Filename Size Last Modified (UTC) Download @context.Name @FormatSize(context.Size) @context.LastModified.ToString("yyyy-MM-dd HH:mm:ss") ZIP
} else {

No log files available on this node

} }
@code { [Parameter] public string NodeId { get; set; } = ""; private string _activeTab = "live"; private string _levelFilter = ""; private string _searchText = ""; private bool _autoScroll = true; // The tab, the level and the search travel in the address (?tab=files, ?level=ERR, ?q=..), so a reload, a shared // link and the node switcher keep them. The search is written when the field is left, not on every key. private static readonly string[] Tabs = ["live", "files"]; private static readonly string[] Levels = ["", "VRB", "DBG", "INF", "WRN", "ERR", "FTL"]; [SupplyParameterFromQuery(Name = "tab")] public string? TabQuery { get; set; } [SupplyParameterFromQuery(Name = "level")] public string? LevelQuery { get; set; } [SupplyParameterFromQuery(Name = "q")] public string? SearchQuery { get; set; } private void WriteFilters() => QueryState.Set(Nav, new Dictionary { ["level"] = _levelFilter, ["q"] = _searchText }); private void SwitchToLive() { _activeTab = "live"; QueryState.Set(Nav, "tab", _activeTab, "live"); } // Live state: the node's tail, kept by the circuit (LogTailCache), so a return to this page shows what was seen and // reads only what is new. private LogTail? _tail; private bool _shouldScroll; private bool _loadingOlder; private bool _jumpToBottom; // Files state private LogFileInfo[]? _logFiles; private bool _filesLoading; private PeriodicTimer? _timer; private CancellationTokenSource? _cts; // Component-scoped token: API calls abort when the component is disposed (navigated away) (4.9). // Guard the disposed state — reading _cts.Token after Dispose throws ObjectDisposedException; a call // that started before Dispose already holds the (now-cancelled) token, so returning None here is safe. private CancellationToken Ct { get { try { return _cts?.Token ?? default; } catch (ObjectDisposedException) { return default; } } } // The rows the page holds, filtered here (no request to the node); markers always stay. private List FilteredRows => LogFilter.Apply(_tail?.Rows ?? [], _levelFilter, _searchText); protected override async Task OnInitializedAsync() { // _cts BEFORE the initial load — a component disposed mid-load must not start an // unstoppable orphan poll loop afterwards (review 2026-09-02, С19). _cts = new CancellationTokenSource(); _activeTab = QueryState.OneOf(TabQuery, Tabs, "live"); _levelFilter = QueryState.OneOf(LevelQuery, Levels, ""); _searchText = SearchQuery ?? ""; _tail = Tails.Get(NodeId); if (_activeTab == "files") await LoadFiles(); await FetchIncremental(poll: false); // Opening the page shows the newest lines, wherever the page was scrolled last time. _jumpToBottom = true; if (!_cts.IsCancellationRequested) _ = PollLoop(_cts.Token); } protected override async Task OnAfterRenderAsync(bool firstRender) { if (_jumpToBottom) { _jumpToBottom = false; _shouldScroll = false; await JS.InvokeVoidAsync("tsakLogs.scrollToBottom", "logScrollContainer"); } else if (_shouldScroll) { _shouldScroll = false; await JS.InvokeVoidAsync("tsakLogs.autoScroll", "logScrollContainer"); } } private Task PollLoop(CancellationToken ct) { _timer = new PeriodicTimer(TimeSpan.FromSeconds(3)); return PollLoops.RunAsync(_timer, ct, Log, async () => { if (_activeTab == "live") { await FetchIncremental(poll: true); await InvokeAsync(StateHasChanged); } }); } private async Task FetchIncremental(bool poll) { if (_tail is null || NodeProvider.GetClient(NodeId) is not { } client) return; // The node's start time from the topology tells a restart apart; a poll reads the cached topology only. var topology = poll ? NodeProvider.Topology : NodeProvider.Topology ?? await NodeProvider.LoadTopologyAsync(); var started = topology?.Nodes.FirstOrDefault(n => n.NodeId == NodeId)?.StartedAt; var startedAt = started is { } s && s != default ? s : (DateTimeOffset?)null; var before = _tail.LastId; try { await _tail.SyncAsync(new ClientLogSource(client), startedAt, poll, Ct); } catch (OperationCanceledException) when (Ct.IsCancellationRequested) { } catch (Exception ex) { // A node that does not answer leaves the lines on screen; the next poll tries again. Log.LogDebug(ex, "Reading the log of node {Node} failed", NodeId); } if (_tail.LastId != before) _shouldScroll = _autoScroll; } private async Task LoadOlder() { if (_tail is null || NodeProvider.GetClient(NodeId) is not { } client) return; _loadingOlder = true; try { await _tail.LoadOlderAsync(new ClientLogSource(client), Ct); } catch (OperationCanceledException) when (Ct.IsCancellationRequested) { } catch (Exception ex) { Toast.Error($"Could not load older lines: {ex.Message}"); } finally { _loadingOlder = false; } } private async Task RefreshLive() { if (_activeTab == "live") await FetchIncremental(poll: false); else await LoadFiles(); } // Clears the view; new lines keep coming, and "load older" brings the cleared ones back. private void ClearLive() => _tail?.Clear(); private async Task SwitchToFiles() { _activeTab = "files"; QueryState.Set(Nav, "tab", _activeTab, "live"); await LoadFiles(); } private async Task LoadFiles() { var client = NodeProvider.GetClient(NodeId); if (client is null) return; _filesLoading = true; try { var response = await client.GetLogFilesAsync(Ct); _logFiles = response is { Available: true } ? response.Files : []; } catch { _logFiles = []; } _filesLoading = false; } private static string GetLevelVariant(string level) => level switch { "VRB" => "muted", "DBG" => "muted", "INF" => "online", "WRN" => "warning", "ERR" => "error", "FTL" => "error", _ => "muted" }; private static string GetRowStyle(string level) => level switch { "WRN" => "background: rgba(var(--warning-rgb, 255,171,0), 0.06);", "ERR" or "FTL" => "background: rgba(var(--error-rgb, 255,68,68), 0.08);", _ => "" }; private static string ShortenSource(string? source) { if (string.IsNullOrEmpty(source)) return "—"; // Show last two segments: "redb.Tsak.Core.Services.TsakCoordinator" → "Services.TsakCoordinator" var parts = source.Split('.'); return parts.Length > 2 ? string.Join('.', parts[^2..]) : source; } private static string FormatSize(long bytes) { if (bytes < 1024) return $"{bytes} B"; if (bytes < 1024 * 1024) return $"{bytes / 1024.0:F1} KB"; return $"{bytes / (1024.0 * 1024.0):F1} MB"; } public void Dispose() { _cts?.Cancel(); _cts?.Dispose(); _timer?.Dispose(); } } Path: redb-tsak/src/redb.Tsak.Web/Components/Pages/NodeDetail.razor Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Components/Pages/NodeDetail.razor ---- @page "/node/{NodeId}" @page "/node/{NodeId}/{Tab}" @inject INodeClientProvider NodeProvider @inject NavigationManager Nav @inject ILogger Log @inject ToastService Toast @inject IJSRuntime JS @using Microsoft.JSInterop @using redb.Tsak.Client @using redb.Tsak.Contracts @using redb.Tsak.Web.Components.Shared @implements IAsyncDisposable @if (_node is null) {
@if (_loading) {

Loading node…

} else {

Node not found

Node "@NodeId" was not found in the cluster topology.

}
} else {
@* Overview cards *@
@* Module contexts in memory / the ones that stay after their modules went; the hotreload health card says what to do *@ @if (_metrics is { Available: true, Latest: { } snap }) { }
@* What the checks that are not healthy found (schema problems of a redb database, say) *@ @if (_health is { Details.Count: > 0 } health) { @foreach (var (check, detail) in health.Details.Where(d => health.Checks.GetValueOrDefault(d.Key) != HealthStatus.Healthy)) {
Health: @check @health.Checks.GetValueOrDefault(check)

@detail

} } @* Tabs *@
@foreach (var tab in _tabs) { var href = $"node/{NodeId}/{tab.ToLower()}"; @tab }
@* Tab content *@
@switch (_activeTab) { case "Overview":
Needs attention
@if (_dashboard is null) {
} else if (_attention.Count == 0) {

Nothing needs attention on this node

} else { @foreach (var item in _attention) {
@item.Title
@item.Detail
@if (item.ContextName is { Length: > 0 } ctxName && item.RouteId is { Length: > 0 } routeKey) { }
} }
Busiest routes

No route has processed anything yet

Route Context Status Msg/s Avg In-flight Errors @context.RouteId @(context.ContextName is { Length: > 0 } ctxCell ? ctxCell : "—") @context.ThroughputPerSecond.ToString("F2") @context.AvgProcessingMs.ToString("F1") ms @context.InflightCount @context.Errors
Recent events

No lifecycle events recorded yet

When Event Context / Route Details @context.Timestamp.ToString("MM-dd HH:mm:ss") @context.ContextName@(context.RouteId is { Length: > 0 } evRoute ? " / " + evRoute : "") @(context.Details ?? "—")
break; case "Contexts":

No route contexts on this node

Name Status Endpoints Actions @context.Name @context.EndpointCount @if (context.Status is "Started" or "Running") { } else { }
break; case "Scheduler": @if (_scheduler is null) {
} else {
@_scheduler.Status.TotalJobs jobs · @_scheduler.Status.RunningJobs running @if (_scheduler.Status.IsStarted && !_scheduler.Status.InStandbyMode) { } else if (!_scheduler.Status.IsShutdown) { }
@* Every route context owns its Quartz scheduler; the header above sums them up. *@ @if (_scheduler.Status.Schedulers.Length > 0) {
Context Scheduler Status Jobs Running Actions @context.Context @context.SchedulerName @context.TotalJobs @context.RunningJobs @if (context.IsStarted && !context.InStandbyMode) { } else if (!context.IsShutdown) { }
}

No scheduled jobs on this node.

Context Job Group Cron State Next Fire Actions @(context.Context ?? "—") @context.JobName @context.JobGroup @(context.CronExpression ?? "—") @(context.NextFireTime?.ToString("HH:mm:ss") ?? "—") @if (context.TriggerState == "Normal") { } else if (context.TriggerState == "Paused") { }
} break; case "Modules":

No modules on this node

Name Version Status Dependencies Description @context.ModuleName @(context.Version ?? "—") @(context.Dependencies.Length > 0 ? string.Join(", ", context.Dependencies) : "—") @(context.Description ?? "—")
break; case "Monitoring":
Range:
@if (_monHistory is null) {
} else {
CPU Usage
Memory
Thread Count
GC Collections
} break; case "Logs": @* Operator tier, matching the worker's LogsController and the Logs page: log bodies may carry payload fragments (review 2026-09-02, В13). *@

No log entries from this node

@LogTime.Header Level Message Source @LogTime.Format(context.Timestamp) @context.Message @if (!string.IsNullOrEmpty(context.Exception)) {
@context.Exception
} @(context.Source ?? "—")
break; }
} @code { [Parameter] public string NodeId { get; set; } = ""; [Parameter] public string? Tab { get; set; } private static readonly string[] _tabs = NodeTabs.All; private TsakConfirmDialog? _confirm; private string _activeTab = NodeTabs.Default; private bool _loading = true; // Topology private NodeInfo? _node; private bool _isLeader; // Runtime data private HealthCheckResult? _health; private SystemInfoResponse? _sysInfo; private MetricsResponse? _metrics; private ContextSummary[]? _contexts; private record SchedulerData(SchedulerStatusResponse Status, ScheduledJobsResponse Jobs); private SchedulerData? _scheduler; private ModuleInfo[]? _modules; private LogEntry[]? _logs; // Overview tab data private DashboardSnapshot? _dashboard; private LifecycleEvent[]? _lifecycle; private IReadOnlyList _attention = []; /// Green when the node is clean, red as soon as one item is an error — the card is read at a glance. private string AttentionValueStyle => _attention.Any(i => i.Level == NodeAttention.Error) ? "color: var(--status-error)" : _attention.Count > 0 ? "color: var(--status-warning)" : "color: var(--status-online)"; /// /// Opens a route's detail page. The id travels in the query string: a route that was never given an id /// gets one derived from its from-URI, and the slashes in it cannot be a path segment. /// private void OpenRoute(string contextName, string routeId) { if (string.IsNullOrEmpty(contextName) || string.IsNullOrEmpty(routeId)) return; Nav.NavigateTo($"node/{NodeId}/routes/{Uri.EscapeDataString(contextName)}?route={Uri.EscapeDataString(routeId)}"); } private static string GetEventBadge(LifecycleEventType type) => type switch { LifecycleEventType.ContextStarted or LifecycleEventType.RouteStarted => "online", LifecycleEventType.ContextStopped or LifecycleEventType.RouteStopped => "offline", LifecycleEventType.RouteSuspended or LifecycleEventType.ContextRemoved => "warning", LifecycleEventType.WatchdogAutoRestart => "warning", LifecycleEventType.RouteErrored or LifecycleEventType.ExchangeTimedOut or LifecycleEventType.ExchangeHung => "error", _ => "info" }; // Monitoring tab data private MetricsHistoryResponse? _monHistory; private TsakChart? _cpuChart; private TsakChart? _memChart; private TsakChart? _threadChart; private TsakChart? _gcChart; private bool _monChartsCreated; private int _monMinutes = 60; private static readonly int[] MonRanges = [15, 60, 180, 720]; // The monitoring time range travels in the address (?range=180), so a reload, a shared link and the node switcher keep it. [SupplyParameterFromQuery(Name = "range")] public string? RangeQuery { get; set; } // Polling private PeriodicTimer? _timer; private CancellationTokenSource? _cts; // Component-scoped token: API calls abort when the component is disposed (navigated away) (4.9). // Guard the disposed state — reading _cts.Token after Dispose throws ObjectDisposedException; a call // that started before Dispose already holds the (now-cancelled) token, so returning None here is safe. private CancellationToken Ct { get { try { return _cts?.Token ?? default; } catch (ObjectDisposedException) { return default; } } } protected override async Task OnInitializedAsync() { SyncTab(); _monMinutes = QueryState.OneOf(RangeQuery, MonRanges, 60); // _cts BEFORE the (possibly slow) initial load: a component disposed mid-load used to // start an unstoppable orphan poll loop afterwards (review 2026-09-02, С19). _cts = new CancellationTokenSource(); await LoadAll(); if (!_cts.IsCancellationRequested) _ = PollLoop(_cts.Token); } protected override async Task OnAfterRenderAsync(bool firstRender) { if (_activeTab == "Monitoring" && !_monChartsCreated && _monHistory is { Available: true, Points.Length: > 0 }) { await UpdateMonitoringChartsAsync(); } } protected override async Task OnParametersSetAsync() { var prev = _activeTab; SyncTab(); if (prev != _activeTab) { // Charts are destroyed when leaving Monitoring tab — force recreation on return if (prev == "Monitoring") _monChartsCreated = false; var client = NodeProvider.GetClient(NodeId); if (client is not null) await LoadTabData(client); } } private void SyncTab() => _activeTab = NodeTabs.Resolve(Tab); private async Task PollLoop(CancellationToken ct) { _timer = new PeriodicTimer(TimeSpan.FromSeconds(10)); try { while (await _timer.WaitForNextTickAsync(ct)) { try { await InvokeAsync(async () => { await LoadAll(); StateHasChanged(); }); } catch (OperationCanceledException) { break; } catch (Exception ex) { // One transient failure (node timeout, DB blip, JS disconnect) must not kill // auto-refresh for the rest of the circuit (review 2026-09-02, С18). Log.LogDebug(ex, "[NodeDetail] poll tick failed; retrying next tick"); } } } catch (OperationCanceledException) { /* disposed */ } } private async Task LoadAll() { _loading = _node is null; var topology = await NodeProvider.LoadTopologyAsync(forceRefresh: true); _node = topology.Nodes.FirstOrDefault(n => n.NodeId == NodeId); // Leadership is per group (review 2026-09-02, С14) — judge by THIS node's group. _isLeader = _node is not null && topology.Leaders.TryGetValue(_node.GroupName, out var groupLeader) && groupLeader.NodeId == NodeId; if (_node is null) { Log.LogWarning("[NodeDetail] Node {NodeId} not found in topology ({Count} nodes)", LogValue.Of(NodeId), topology.Nodes.Count); _loading = false; return; } var client = NodeProvider.GetClient(NodeId); if (client is null) { Log.LogWarning("[NodeDetail] GetClient returned null for {NodeId}", LogValue.Of(NodeId)); _loading = false; return; } if (!_node.IsAlive) { Log.LogWarning("[NodeDetail] Node {NodeId} is not alive, skipping API calls", LogValue.Of(NodeId)); _loading = false; return; } // Load overview data _health = await client.GetHealthAsync(Ct); _sysInfo = await client.GetInfoAsync(Ct); _metrics = await client.GetMetricsAsync(Ct); // Load tab data for active tab await LoadTabData(client); _loading = false; } private async Task LoadTabData(TsakApiClient client) { switch (_activeTab) { case "Overview": // One aggregated call carries the alerts, the problem routes and the counters; the other two // bring the event feed and the module states. Everything else the overview shows is already // loaded for the cards above the tabs. _dashboard = await client.GetDashboardAsync(Ct); _lifecycle = await client.GetLifecycleEventsAsync(limit: 15, ct: Ct); _modules = await client.ListModulesAsync(Ct); _attention = NodeAttention.Collect(_dashboard, _modules); break; case "Contexts": _contexts = await client.ListContextsAsync(Ct); break; case "Scheduler": var status = await client.GetSchedulerStatusAsync(Ct); var jobs = await client.ListScheduledJobsAsync(Ct); _scheduler = new SchedulerData(status, jobs); break; case "Modules": _modules = await client.ListModulesAsync(Ct); break; case "Monitoring": _monHistory = await client.GetMetricsHistoryAsync(_monMinutes, Ct); await UpdateMonitoringChartsAsync(); break; case "Logs": var response = await client.GetLogsAsync(limit: 200, ct: Ct); _logs = response is { Available: true, Entries: { } entries } ? entries : []; break; } } private async Task SetTimeRange(int minutes) { if (_monMinutes == minutes) return; _monMinutes = minutes; QueryState.Set(Nav, "range", minutes.ToString(System.Globalization.CultureInfo.InvariantCulture), "60"); _monChartsCreated = false; var client = NodeProvider.GetClient(NodeId); if (client is null) return; _monHistory = await client.GetMetricsHistoryAsync(_monMinutes, Ct); await UpdateMonitoringChartsAsync(); StateHasChanged(); } private static string FormatNumber(int num) { if (num < 1_000) return num.ToString(); if (num < 1_000_000) return $"{num / 1_000.0:F1}K"; if (num < 1_000_000_000) return $"{num / 1_000_000.0:F1}M"; return $"{num / 1_000_000_000.0:F1}B"; } private static string FormatUptime(string? uptime) { if (uptime is null) return "—"; var dot = uptime.LastIndexOf('.'); return dot >= 0 && uptime.Length > dot + 3 ? uptime[..(dot + 3)] : uptime; } private static string GetTabIcon(string tab) => tab switch { "Contexts" => "route", "Endpoints" => "zap", "Scheduler" => "clock", "Modules" => "package", "Monitoring" => "activity", "Overview" => "dashboard", "Logs" => "terminal", _ => "info" }; private async Task ContextAction(Func action, string actionName) { try { // Control client (review 2026-09-02, С12): a context stop/restart drains longer than // the 5s polling timeout — a false client-side timeout made operators retry an // operation that had already succeeded server-side. var client = NodeProvider.GetControlClient(NodeId) ?? throw new InvalidOperationException($"No API client for node {NodeId}"); await action(client); _contexts = await client.ListContextsAsync(Ct); Toast.Success($"Context {actionName}"); } catch (Exception ex) { Toast.Error($"Context action failed: {ex.Message}"); } } private async Task StopContext(string name) { if (_confirm is not null) { var message = name == "_system" ? "WARNING: Stopping '_system' will shut down the management API. You will lose remote access to this node until Worker restart. Continue?" : $"Stop context '{name}'?"; var confirmed = await _confirm.ShowAsync(message, "Stop Context"); if (!confirmed) return; } await ContextAction(c => c.StopContextAsync(name), $"'{name}' stopped"); } private async Task SchedulerAction(Func> action, string actionName) { try { var client = NodeProvider.GetClient(NodeId) ?? throw new InvalidOperationException($"No API client for node {NodeId}"); var result = await action(client); _scheduler = new SchedulerData( await client.GetSchedulerStatusAsync(Ct), await client.ListScheduledJobsAsync(Ct)); if (result.Success) Toast.Success($"Scheduler {actionName}"); else Toast.Error($"Scheduler action failed: {result.Message}"); } catch (Exception ex) { Toast.Error($"Scheduler action failed: {ex.Message}"); } } private void GoBack() => Nav.NavigateTo("cluster"); private static string GetNodeBadge(NodeInfo node) => node.Status switch { NodeStatus.Online when node.IsAlive => "online", NodeStatus.Online => "warning", NodeStatus.Offline => "offline", NodeStatus.Dead => "error", _ => "offline" }; private static string GetContextBadge(string status) => status switch { "Started" or "Running" => "online", "Stopped" => "offline", "Faulted" => "error", _ => "warning" }; // Blocked is a job that does not run concurrently while it executes (Quartz 3.17+ reports it so instead of // Complete): nothing is wrong. Error is the state of a trigger Quartz gave up on. private static string GetTriggerBadge(string state) => state switch { "Normal" => "online", "Paused" => "warning", "Complete" or "Blocked" => "info", "Error" => "error", _ => "offline" }; private static string GetModuleBadge(string status) => status switch { "Initialized" or "Loaded" => "online", "NotLoaded" => "offline", "Error" => "error", _ => "warning" }; private static string GetHealthBadge(string status) => status switch { "Healthy" => "online", "Warning" => "warning", "Critical" or "Failed" => "error", _ => "offline" }; private static string GetLevelBadge(string level) => level switch { "Error" or "Critical" => "error", "Warning" => "warning", "Information" => "info", "Debug" or "Trace" => "offline", _ => "offline" }; private async Task UpdateMonitoringChartsAsync() { if (_monHistory is not { Available: true, Points.Length: > 0 }) return; // All 4 chart refs must be available (rendered) before we can create if (_cpuChart is null || _memChart is null || _threadChart is null || _gcChart is null) return; var labels = _monHistory.Points.Select(p => DateTimeOffset.FromUnixTimeMilliseconds(p.TimestampMs).LocalDateTime.ToString("HH:mm:ss")).ToArray(); var cpuDatasets = new[] { new TsakChart.ChartDataset("Process %", _monHistory.Points.Select(p => p.Cpu.ProcessUsage).ToArray(), "rgb(59,130,246)", null), new TsakChart.ChartDataset("System %", _monHistory.Points.Select(p => p.Cpu.SystemUsage).ToArray(), "rgb(244,63,94)", null) }; var memDatasets = new[] { new TsakChart.ChartDataset("Working Set MB", _monHistory.Points.Select(p => p.Memory.WorkingSetMB).ToArray(), "rgb(16,185,129)", "rgba(16,185,129,0.15)"), new TsakChart.ChartDataset("Private MB", _monHistory.Points.Select(p => p.Memory.PrivateMemoryMB).ToArray(), "rgb(244,63,94)", "rgba(244,63,94,0.15)"), new TsakChart.ChartDataset("GC Memory MB", _monHistory.Points.Select(p => p.Memory.GCMemoryMB).ToArray(), "rgb(139,92,246)", "rgba(139,92,246,0.15)") }; var threadDatasets = new[] { new TsakChart.ChartDataset("Active Threads", _monHistory.Points.Select(p => (double)p.Threading.ActiveThreads).ToArray(), "rgb(245,158,11)", null), new TsakChart.ChartDataset("Pending Work", _monHistory.Points.Select(p => (double)p.Threading.ThreadPoolPendingWork).ToArray(), "rgb(168,85,247)", null) }; var gcDatasets = new[] { new TsakChart.ChartDataset("Gen 0", _monHistory.Points.Select(p => (double)p.GarbageCollector.Gen0Collections).ToArray(), "rgb(59,130,246)", "rgb(59,130,246)"), new TsakChart.ChartDataset("Gen 1", _monHistory.Points.Select(p => (double)p.GarbageCollector.Gen1Collections).ToArray(), "rgb(16,185,129)", "rgb(16,185,129)"), new TsakChart.ChartDataset("Gen 2", _monHistory.Points.Select(p => (double)p.GarbageCollector.Gen2Collections).ToArray(), "rgb(244,63,94)", "rgb(244,63,94)") }; if (!_monChartsCreated) { await _cpuChart.CreateLineAsync(labels, cpuDatasets, "%"); await _memChart.CreateAreaAsync(labels, memDatasets, "MB"); await _threadChart.CreateLineAsync(labels, threadDatasets); await _gcChart.CreateBarAsync(labels, gcDatasets); _monChartsCreated = true; // Size charts container to fill remaining viewport await JS.InvokeVoidAsync("tsakCharts.fitToViewport", ".monitoring-charts"); } else { await _cpuChart.UpdateAsync(labels, cpuDatasets); await _memChart.UpdateAsync(labels, memDatasets); await _threadChart.UpdateAsync(labels, threadDatasets); await _gcChart.UpdateAsync(labels, gcDatasets); } } public async ValueTask DisposeAsync() { _cts?.Cancel(); _cts?.Dispose(); _timer?.Dispose(); try { await JS.InvokeVoidAsync("tsakCharts.disconnectResize"); } catch (JSDisconnectedException) { } catch (JSException) { } catch (InvalidOperationException) { } if (_cpuChart is not null) await _cpuChart.DisposeAsync(); if (_memChart is not null) await _memChart.DisposeAsync(); if (_threadChart is not null) await _threadChart.DisposeAsync(); if (_gcChart is not null) await _gcChart.DisposeAsync(); } } Path: redb-tsak/src/redb.Tsak.Web/Components/Pages/RouteView.razor Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Components/Pages/RouteView.razor ---- @* A route id is free-form: a module that does not call .RouteId(...) gets one derived from its URI, slashes, '?' and '&' included. Such an id cannot be a path segment — the router matched nothing and the page read "Page not found" — so the id travels in the query string. The path form stays for ids that are plain words, and for links made before this change. *@ @page "/node/{NodeId}/routes/{ContextName}" @page "/node/{NodeId}/routes/{ContextName}/{RouteId}" @inject INodeClientProvider NodeProvider @inject ILogger Log @inject NavigationManager Nav @inject ToastService Toast @using redb.Tsak.Client @using redb.Tsak.Contracts @implements IDisposable @if (_detail is not null) { @if (_detail.Status is "Started") { } else { } } @if (_loading) {

Loading route details…

} else if (_detail is not null) { @* Status header *@
@if (IsClusterRoute()) { @GetLeaderDisplay() }
@* Metrics *@ @if (_metrics is not null) {
@if (_metrics.LastActivity.HasValue) { }
@if (_metrics.LastError is not null) {
Last Error @(_metrics.LastErrorTime?.ToString("yyyy-MM-dd HH:mm:ss") ?? "")

@_metrics.LastError

} @if (_metrics.LastWarning is not null) {
Last Warning @(_metrics.LastWarningTime?.ToString("yyyy-MM-dd HH:mm:ss") ?? "")

@_metrics.LastWarning

} } @* In-Flight Exchanges *@ @if (_inflight is { Length: > 0 }) {
In-Flight Exchanges
Exchange ID Elapsed Thread From @context.ExchangeId @($"{context.ElapsedMs:F0}ms") @context.ThreadId @(context.FromEndpoint ?? "—")
} @* Endpoint Statistics *@ @if (_detail.Endpoints is { Length: > 0 }) {
Endpoints
URI In / Out Errors Rejected Refused Throughput Health @context.Uri @FormatNumber(context.MessagesIn) / @FormatNumber(context.MessagesOut) @context.Errors @context.Rejected @context.Refused @($"{context.ThroughputPerSecond:F1}/s") @if (!string.IsNullOrEmpty(context.HealthReason) && context.HealthStatus != "Healthy") { @context.HealthReason }
} @* Lifecycle History *@ @if (_lifecycle is { Length: > 0 }) {
Lifecycle History
Timestamp Event Details @context.Timestamp.ToString("yyyy-MM-dd HH:mm:ss") @(context.Details ?? "—")
} } else { @* Reached as well by switching node on a route page: the route may run on one node only. *@

Route @RouteKey of context @ContextName is not on node @NodeId.

Routes of @NodeId
} @code { [Parameter] public string NodeId { get; set; } = ""; [Parameter] public string ContextName { get; set; } = ""; [Parameter] public string RouteId { get; set; } = ""; /// The route id when it cannot be a path segment — see the note above the page directives. [SupplyParameterFromQuery(Name = "route")] public string? RouteFromQuery { get; set; } /// The id this page works with: the query form wins, the path form is the fallback. private string RouteKey => string.IsNullOrEmpty(RouteFromQuery) ? RouteId : RouteFromQuery; private bool _loading = true; private RouteDetail? _detail; private RouteMetricsSummary? _metrics; private InflightExchangeDto[]? _inflight; private LifecycleEvent[]? _lifecycle; private TsakConfirmDialog _confirmDialog = null!; private PeriodicTimer? _timer; private CancellationTokenSource? _cts; // Component-scoped token: API calls abort when the component is disposed (navigated away) (4.9). // Guard the disposed state — reading _cts.Token after Dispose throws ObjectDisposedException; a call // that started before Dispose already holds the (now-cancelled) token, so returning None here is safe. private CancellationToken Ct { get { try { return _cts?.Token ?? default; } catch (ObjectDisposedException) { return default; } } } protected override async Task OnInitializedAsync() { // _cts BEFORE the initial load — a component disposed mid-load must not start an // unstoppable orphan poll loop afterwards (review 2026-09-02, С19). _cts = new CancellationTokenSource(); await LoadData(); if (!_cts.IsCancellationRequested) _ = PollLoop(_cts.Token); } private Task PollLoop(CancellationToken ct) { _timer = new PeriodicTimer(TimeSpan.FromSeconds(5)); return PollLoops.RunAsync(_timer, ct, Log, async () => { await LoadData(); await InvokeAsync(StateHasChanged); }); } private async Task LoadData() { var client = NodeProvider.GetClient(NodeId); if (client is null) { _loading = false; return; } try { _detail = await client.GetRouteAsync(ContextName, RouteKey, Ct); try { _metrics = await client.GetRouteMetricsAsync(ContextName, RouteKey, Ct); } catch { } try { _inflight = await client.GetRouteInflightAsync(ContextName, RouteKey, Ct); } catch { } try { _lifecycle = await client.GetLifecycleEventsAsync(context: ContextName, route: RouteKey, limit: 20, ct: Ct); } catch { } } catch { /* retain previous data */ } _loading = false; } private async Task Refresh() => await LoadData(); private async Task RouteAction(bool start) { try { var client = NodeProvider.GetClient(NodeId) ?? throw new InvalidOperationException($"No API client for node {NodeId}"); if (start) await client.StartRouteAsync(ContextName, RouteKey, Ct); else await client.StopRouteAsync(ContextName, RouteKey, ct: Ct); await LoadData(); Toast.Success($"Route '{RouteKey}' {(start ? "started" : "stopped")}"); } catch (Exception ex) { Toast.Error($"Route action failed: {ex.Message}"); } } private async Task ForceStop() { var confirmed = await _confirmDialog.ShowAsync( $"Force-stop route '{RouteKey}'? This will immediately cancel all in-flight exchanges.", "Force-Stop Route"); if (!confirmed) return; try { // Control timeout: force-stop drains longer than the 5s polling default (С12). var client = NodeProvider.GetControlClient(NodeId) ?? throw new InvalidOperationException($"No API client for node {NodeId}"); await client.ForceStopRouteAsync(ContextName, RouteKey, Ct); await LoadData(); Toast.Success($"Route '{RouteKey}' force-stopped"); } catch (Exception ex) { Toast.Error($"Force-stop failed: {ex.Message}"); } } private void GoBack() => Nav.NavigateTo($"node/{NodeId}/routes"); private static string GetStatusBadge(string status) => status switch { "Started" => "online", "Stopped" => "offline", "Suspended" => "warning", _ => "offline" }; private static string GetHealthBadge(string status) => status switch { "Healthy" => "online", "Warning" => "warning", "Critical" or "Failed" => "error", _ => "offline" }; private static string GetEventBadge(LifecycleEventType type) => type switch { LifecycleEventType.RouteStarted or LifecycleEventType.ContextStarted => "online", LifecycleEventType.RouteStopped or LifecycleEventType.ContextStopped => "offline", LifecycleEventType.RouteErrored => "error", LifecycleEventType.RouteSuspended or LifecycleEventType.ExchangeTimedOut => "warning", LifecycleEventType.ExchangeHung or LifecycleEventType.WatchdogAutoRestart => "error", _ => "info" }; private static string FormatNumber(long num) { if (num < 1_000) return num.ToString(); if (num < 1_000_000) return $"{num / 1_000.0:F1}K"; return $"{num / 1_000_000.0:F1}M"; } private string GetLeaderDisplay() { if (_detail?.PolicyMetadata is not { } meta) return ""; if (GetMetaBool(meta, "leader") == true) return "Leader: This node"; if (GetMetaBool(meta, "suspended") == true) return "Suspended"; return "Leader: Other node"; } private bool IsClusterRoute() => _detail?.PolicyMetadata is { } meta && GetMetaBool(meta, "cluster") == true; private static bool? GetMetaBool(IReadOnlyDictionary meta, string key) { if (!meta.TryGetValue(key, out var val)) return null; if (val is bool b) return b; if (val is System.Text.Json.JsonElement je) return je.ValueKind == System.Text.Json.JsonValueKind.True ? true : je.ValueKind == System.Text.Json.JsonValueKind.False ? false : null; return null; } private static string FormatTimeAgo(DateTime? timestamp) { if (timestamp is null) return "—"; var diff = DateTime.UtcNow - timestamp.Value; if (diff.TotalSeconds < 60) return $"{(int)diff.TotalSeconds}s ago"; if (diff.TotalMinutes < 60) return $"{(int)diff.TotalMinutes}m ago"; if (diff.TotalHours < 24) return $"{(int)diff.TotalHours}h ago"; return $"{(int)diff.TotalDays}d ago"; } public void Dispose() { _cts?.Cancel(); _cts?.Dispose(); _timer?.Dispose(); } } Path: redb-tsak/src/redb.Tsak.Web/Components/Pages/Routes.razor Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Components/Pages/Routes.razor ---- @page "/node/{NodeId}/routes" @inject INodeClientProvider NodeProvider @inject ILogger Log @inject NavigationManager Nav @inject ToastService Toast @using redb.Tsak.Client @using redb.Tsak.Contracts @using redb.Tsak.Web.Components.Shared @implements IDisposable @if (_loading) {

Loading routes…

} else if (_allRoutes.Length > 0) {
@foreach (var group in GroupedRoutes) {
@group.Key (@group.Value.Length routes) r.Route.Status == "Started")}/{group.Value.Length}")" Variant="@(group.Value.All(r => r.Route.Status == "Started") ? "online" : "warning")" ShowDot="false" />
@if (!_collapsed.Contains(group.Key)) {
Route ID From URI Status AutoStart Inflight Actions @context.Route.RouteId @if (context.Route.IsCluster) { } @context.Route.FromUri @context.Route.InflightCount
@if (context.Route.Status is "Started") { } else { }
}
} } else {

No routes on this node

} @code { [Parameter] public string NodeId { get; set; } = ""; private bool _loading = true; // The status filter travels in the address (?status=Started), so a reload, a shared link and the node switcher keep it. [SupplyParameterFromQuery(Name = "status")] public string? StatusQuery { get; set; } private string _statusValue = ""; private string _statusFilter { get => _statusValue; set { _statusValue = value ?? ""; QueryState.Set(Nav, "status", _statusValue); } } private string _searchText = ""; private RouteEntry[] _allRoutes = []; private readonly HashSet _collapsed = new(); private TsakConfirmDialog _confirmDialog = null!; private PeriodicTimer? _timer; private CancellationTokenSource? _cts; // Component-scoped token: API calls abort when the component is disposed (navigated away) (4.9). // Guard the disposed state — reading _cts.Token after Dispose throws ObjectDisposedException; a call // that started before Dispose already holds the (now-cancelled) token, so returning None here is safe. private CancellationToken Ct { get { try { return _cts?.Token ?? default; } catch (ObjectDisposedException) { return default; } } } private record RouteEntry(string ContextName, TsakRouteInfo Route); private KeyValuePair[] GroupedRoutes { get { IEnumerable filtered = _allRoutes; if (!string.IsNullOrEmpty(_statusFilter)) filtered = filtered.Where(r => r.Route.Status == _statusFilter); if (!string.IsNullOrEmpty(_searchText)) filtered = filtered.Where(r => r.Route.RouteId.Contains(_searchText, StringComparison.OrdinalIgnoreCase) || r.Route.FromUri.Contains(_searchText, StringComparison.OrdinalIgnoreCase)); return filtered .GroupBy(r => r.ContextName) .OrderBy(g => g.Key) .Select(g => new KeyValuePair(g.Key, g.ToArray())) .ToArray(); } } protected override async Task OnInitializedAsync() { _statusValue = StatusQuery ?? ""; // _cts BEFORE the initial load — a component disposed mid-load must not start an // unstoppable orphan poll loop afterwards (review 2026-09-02, С19). _cts = new CancellationTokenSource(); await LoadData(); if (!_cts.IsCancellationRequested) _ = PollLoop(_cts.Token); } private Task PollLoop(CancellationToken ct) { _timer = new PeriodicTimer(TimeSpan.FromSeconds(5)); return PollLoops.RunAsync(_timer, ct, Log, async () => { await LoadData(); await InvokeAsync(StateHasChanged); }); } private async Task LoadData() { var client = NodeProvider.GetClient(NodeId); if (client is null) { _loading = false; return; } try { var contexts = await client.ListContextsAsync(Ct); var entries = new List(); foreach (var ctx in contexts) { try { var routes = await client.ListRoutesAsync(ctx.Name, Ct); entries.AddRange(routes.Select(r => new RouteEntry(ctx.Name, r))); } catch { /* skip failing contexts */ } } _allRoutes = entries.ToArray(); } catch { /* retain previous data on error */ } _loading = false; } private async Task Refresh() => await LoadData(); private void ToggleCollapse(string name) { if (!_collapsed.Remove(name)) _collapsed.Add(name); } private async Task RouteAction(RouteEntry entry, bool start) { try { var client = NodeProvider.GetClient(NodeId) ?? throw new InvalidOperationException($"No API client for node {NodeId}"); if (start) await client.StartRouteAsync(entry.ContextName, entry.Route.RouteId, Ct); else await client.StopRouteAsync(entry.ContextName, entry.Route.RouteId, ct: Ct); await LoadData(); Toast.Success($"Route '{entry.Route.RouteId}' {(start ? "started" : "stopped")}"); } catch (Exception ex) { Toast.Error($"Route action failed: {ex.Message}"); } } private async Task ForceStop(RouteEntry entry) { var confirmed = await _confirmDialog.ShowAsync( $"Force-stop route '{entry.Route.RouteId}' in '{entry.ContextName}'? This will immediately cancel all in-flight exchanges.", "Force-Stop Route"); if (!confirmed) return; try { // Control timeout: force-stop drains longer than the 5s polling default (С12). var client = NodeProvider.GetControlClient(NodeId) ?? throw new InvalidOperationException($"No API client for node {NodeId}"); await client.ForceStopRouteAsync(entry.ContextName, entry.Route.RouteId, Ct); await LoadData(); Toast.Success($"Route '{entry.Route.RouteId}' force-stopped"); } catch (Exception ex) { Toast.Error($"Force-stop failed: {ex.Message}"); } } // The id goes in the query string: a module that does not call .RouteId(...) gets an id derived from its // URI — slashes, '?' and '&' included — which no path segment can carry, and the detail page answered // "Page not found" for every such route. private void NavigateToDetail(RouteEntry entry) => Nav.NavigateTo($"node/{NodeId}/routes/{Uri.EscapeDataString(entry.ContextName)}?route={Uri.EscapeDataString(entry.Route.RouteId)}"); private static string GetStatusBadge(string status) => status switch { "Started" => "online", "Stopped" => "offline", "Suspended" => "warning", _ => "offline" }; public void Dispose() { _cts?.Cancel(); _cts?.Dispose(); _timer?.Dispose(); } } Path: redb-tsak/src/redb.Tsak.Web/Components/Pages/Storage.razor Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Components/Pages/Storage.razor ---- @page "/node/{NodeId}/storage" @inject INodeClientProvider NodeProvider @inject ILogger Log @inject ToastService Toast @using redb.Tsak.Client @using redb.Tsak.Contracts @using redb.Tsak.Web.Components.Shared @implements IDisposable @if (_groups.Count > 1) { } @if (_groups.Count > 0) { @if (_readAt is { } readAt) { read @readAt.ToString("HH:mm:ss") } @if (_stats is not null) { } } @if (_loadingInstances) {

Asking the node which databases it uses…

} else if (_groups.Count == 0 && _error is { Length: > 0 }) { @* Not the same as "no databases": the node was asked and did not answer. Saying "none" here would be an answer this page has not got. *@

The node did not answer which databases it uses

@_error

} else if (_groups.Count == 0) {

This node uses no redb database

} else {
@if (_stats is not null) { }
@* Who asked for this database. Identity alone declares the same three databases in five of its contexts, so the rows are grouped by the database itself and the contexts are named here instead. *@
@if (Current.Primary.ContextName is null) { Tsak's own database: modules, contexts, keys, audit and dead-letter live here. } else if (Current.Members.Count == 1) { Declared by the context @Current.Primary.ContextName as "@Current.Primary.Name". } else { The same database is declared by @Current.Members.Count contexts: @string.Join(", ", Current.Members.Select(m => $"{m.ContextName} ({m.Name})")) }
@if (_error is { Length: > 0 }) { @* The refusal stays on the page, not only in a toast that fades: it carries the reference the worker log is searchable by, and the operator needs it to hand on. *@
The database refused to report its statistics
@_error
The worker log holds the engine's own message under that reference.
} @if (_stats is null) { @* Nothing is read until asked: a database a context declared but never activated opens its connection on exactly this call, and the page must not do that behind the operator's back. *@

Nothing read yet

Press Read to query the catalogs of @Current.Title: its tables with their sizes and row counts, its indexes with their columns, and what the engine knows about how they are used.

This never happens on a timer — a database a context declared but never activated opens its connection on this very call.

} else { @* The window the counters cover decides whether "nothing read this index" is a fact or our ignorance, so it is stated before any number that depends on it. *@
@if (!Current.Primary.SupportsUsageCounters) { This engine counts no index usage, so the tables below say what the indexes are, not whether anything reads them. } else if (_stats.CountersSince is { } since) { Usage counters cover everything since @since.ToLocalTime().ToString("yyyy-MM-dd HH:mm"). @if (_stats.IsReplica == true) { This node is a replica: they count the reads served here. } } else { The engine does not say since when the counters have been counting, so a zero read count is not evidence. }
@if (_advice.Count > 0) {
Remarks — only indexes nothing structural depends on
@foreach (var item in _advice) {
@QualifiedName(item.Schema, item.Table).@item.Index
@item.Detail
}
}
Tables

No tables

QualifiedName(t.Schema, t.Table)))">Table@(_tables?.SortIndicator("table")) t.IsRedbOwned ? 0 : 1))">Owner@(_tables?.SortIndicator("owner")) t.EstimatedRows ?? -1))">Rows@(_tables?.SortIndicator("rows")) t.DataSizeBytes ?? -1))">Data@(_tables?.SortIndicator("data")) t.IndexesSizeBytes ?? -1))">Indexes@(_tables?.SortIndicator("indexes")) @if (Current.Primary.SupportsAnalyzeTimestamps) { t.DeadRows ?? -1))">Dead rows@(_tables?.SortIndicator("dead")) t.LastAnalyze ?? t.LastAutoAnalyze ?? DateTimeOffset.MinValue))">Analyzed@(_tables?.SortIndicator("analyzed")) } else { t.HasStatistics == true ? 0 : 1))">Statistics@(_tables?.SortIndicator("stats")) } @QualifiedName(context.Schema, context.Table) @Number(context.EstimatedRows) @Size(context.DataSizeBytes) @Size(context.IndexesSizeBytes) @if (Current.Primary.SupportsAnalyzeTimestamps) { @Number(context.DeadRows) @Moment(context.LastAnalyze ?? context.LastAutoAnalyze) } else { }
Indexes

No indexes

i.Name))">Index@(_indexes?.SortIndicator("index")) QualifiedName(i.Schema, i.Table)))">Table@(_indexes?.SortIndicator("table")) string.Join(",", i.Columns)))">Columns@(_indexes?.SortIndicator("columns")) i.IsSystemCritical ? i.CriticalReason : i.IsUnique == true ? "unique" : "zzz"))">Holds@(_indexes?.SortIndicator("holds")) i.SizeBytes ?? -1))">Size@(_indexes?.SortIndicator("size")) @if (Current.Primary.SupportsUsageCounters) { (i.Seeks ?? 0) + (i.Scans ?? 0)))">Reads@(_indexes?.SortIndicator("reads")) i.LastUsed ?? DateTimeOffset.MinValue))">Last read@(_indexes?.SortIndicator("last")) } @context.Name @QualifiedName(context.Schema, context.Table) @string.Join(", ", context.Columns) @if (context.IncludedColumns.Count > 0) { + @string.Join(", ", context.IncludedColumns) } @if (context.IsSystemCritical) { } else if (context.IsUnique == true) { } else { — } @Size(context.SizeBytes) @if (Current.Primary.SupportsUsageCounters) { @Reads(context) @Moment(context.LastUsed) }
} } @code { [Parameter] public string NodeId { get; set; } = ""; /// What the two analyze buttons promise, in the words an operator needs before pressing. private const string AnalyzeAllHint = "Refresh the planner statistics of the whole database. On a large one this runs for minutes, and the " + "database keeps serving traffic while it does."; private const string AnalyzeTableHint = "Refresh the planner statistics of this table only — the usual answer when one table turned slow."; private IReadOnlyList _groups = []; private string _selectedKey = ""; private RedbStorageStats? _stats; private IReadOnlyList _advice = []; private string? _error; /// What was read, per database, with the moment it was read. private sealed record ReadResult(RedbStorageStats Stats, IReadOnlyList Advice, DateTimeOffset At); // Switching back to a database already read shows what was read instead of asking for Read again. Only // what the operator asked for is kept — a database never read is still never connected to. private readonly Dictionary _read = new(StringComparer.Ordinal); private DateTimeOffset? _readAt; /// Page sizes offered under both tables; a database has as many indexes as it has. private static readonly int[] PageSizes = [20, 50, 100, 200]; // The size the reader picked, kept by the page: the grids are re-created whenever the page swaps what it // shows, and a choice that lives inside them would be forgotten on every switch of database. private int _pageSize = 20; private TsakGrid? _tables; private TsakGrid? _indexes; // Sorting lives in the grid, which owns the paging the order has to agree with; the page only says what // each column sorts by. A value the engine did not report sorts as -1 or as the earliest moment, so the // rows that say "—" gather at one end instead of being scattered through the order. private void SortTables(string column, Func selector) => _tables?.Sort(column, selector); private void SortIndexes(string column, Func selector) => _indexes?.Sort(column, selector); private bool _loadingInstances = true; private bool _loadingStats; private bool _analyzing; private TsakConfirmDialog? _confirm; private CancellationTokenSource? _cts; // Component-scoped token: the read of a large catalog is abandoned when the operator navigates away. private CancellationToken Ct { get { try { return _cts?.Token ?? default; } catch (ObjectDisposedException) { return default; } } } private StorageInstanceGroup Current => _groups.FirstOrDefault(g => g.Key == _selectedKey) ?? _groups[0]; protected override async Task OnInitializedAsync() { _cts = new CancellationTokenSource(); await LoadInstances(); } /// /// Asks the node which databases it uses. On the control client, not the polling one: a worker busy with /// an analyze, a start-up or fifteen declarations of its own answers this in more than the five seconds /// the polling client allows, and a page with no list is a page with nothing at all. /// private async Task LoadInstances() { var client = NodeProvider.GetControlClient(NodeId) ?? NodeProvider.GetClient(NodeId); if (client is null) { _groups = []; return; } _loadingInstances = true; try { var instances = await client.ListRedbInstancesAsync(Ct); _groups = StorageInstanceGrouping.Group(instances); _error = null; if (_groups.Count > 0) _selectedKey = _groups[0].Key; } catch (Exception ex) { Log.LogWarning(ex, "[Storage] failed to list redb instances of node {NodeId}", LogValue.Of(NodeId)); // The list stays unknown, not empty: "no databases" is an answer this page has not got. _groups = []; _error = ex.Message; } finally { _loadingInstances = false; } } /// /// Reads the catalogs of the selected database. Deliberately not on a timer: an instance a context /// declared but never activated opens its database connection on exactly this call. /// private async Task LoadStats() { if (_groups.Count == 0) return; var client = NodeProvider.GetControlClient(NodeId) ?? NodeProvider.GetClient(NodeId); if (client is null) return; _loadingStats = true; try { var instance = Current.Primary; _error = null; _stats = await client.GetStorageStatsAsync( string.IsNullOrEmpty(instance.Name) ? null : instance.Name, instance.ContextName, Ct); _advice = IndexAdvice.Collect( _stats.Indexes, countersAreMeaningful: instance.SupportsUsageCounters && _stats.CountersSince is not null); _readAt = DateTimeOffset.Now; _read[Current.Key] = new ReadResult(_stats, _advice, _readAt.Value); } catch (Exception ex) { Log.LogWarning(ex, "[Storage] failed to read statistics of {Instance}", _selectedKey); _error = ex.Message; Toast.Error($"Could not read the statistics: {ex.Message}"); } finally { _loadingStats = false; } } private void OnInstanceChanged(ChangeEventArgs e) { _selectedKey = e.Value?.ToString() ?? ""; _error = null; // The numbers on screen belong to the database selected a moment ago. If this one was read earlier, // show that reading; otherwise the page waits to be asked, as it does on first arrival. if (_read.TryGetValue(_selectedKey, out var previous)) { _stats = previous.Stats; _advice = previous.Advice; _readAt = previous.At; } else { _stats = null; _advice = []; _readAt = null; } } private async Task AnalyzeAll() { var confirmed = await _confirm!.ShowAsync( $"Refresh the planner statistics of the whole database behind '{Current.Title}'? " + "On a large database this runs for minutes.", "Analyze database"); if (!confirmed) return; await RunAnalyze(null, null, $"Statistics of '{Current.Title}' refreshed"); } private async Task AnalyzeTable(RedbTableInfo table) { await RunAnalyze(table.Table, table.Schema, $"Statistics of '{QualifiedName(table.Schema, table.Table)}' refreshed"); } private async Task RunAnalyze(string? table, string? schema, string success) { // Control client: an ANALYZE outlasts the polling timeout by design, and a false client-side timeout // would have the operator run it a second time (С12). var client = NodeProvider.GetControlClient(NodeId); if (client is null) return; _analyzing = true; try { var instance = Current.Primary; var result = await client.AnalyzeStorageAsync( string.IsNullOrEmpty(instance.Name) ? null : instance.Name, instance.ContextName, table, schema, Ct); Toast.Success($"{success} in {result.ElapsedMs} ms"); await LoadStats(); } catch (Exception ex) { Log.LogWarning(ex, "[Storage] analyze failed on {Instance}", _selectedKey); Toast.Error($"Analyze failed: {ex.Message}"); } finally { _analyzing = false; } } private static string QualifiedName(string? schema, string table) => string.IsNullOrEmpty(schema) ? table : $"{schema}.{table}"; private static string KindLabel(IndexAdviceKind kind) => kind switch { IndexAdviceKind.Unused => "unread", IndexAdviceKind.Duplicate => "duplicate", IndexAdviceKind.CoveredByWiderIndex => "covered", _ => "remark" }; /// Reads as the engine counts them: PostgreSQL reports one combined number, SQL Server two. private static string Reads(RedbIndexInfo i) => i.Scans is null ? Number(i.Seeks) : $"{Number(i.Seeks)} / {Number(i.Scans)}"; private static string Number(long? value) => value is null ? "—" : value.Value.ToString("N0"); private static string Moment(DateTimeOffset? value) => value is null ? "—" : value.Value.ToLocalTime().ToString("yyyy-MM-dd HH:mm"); private static string Size(long? bytes) { if (bytes is null) return "—"; double value = bytes.Value; string[] units = ["B", "KB", "MB", "GB", "TB"]; var unit = 0; while (value >= 1024 && unit < units.Length - 1) { value /= 1024; unit++; } return unit == 0 ? $"{bytes.Value} B" : $"{value:F1} {units[unit]}"; } public void Dispose() { _cts?.Cancel(); _cts?.Dispose(); } } Path: redb-tsak/src/redb.Tsak.Web/Components/Pages/Watchdog.razor Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Components/Pages/Watchdog.razor ---- @page "/node/{NodeId}/watchdog" @inject INodeClientProvider NodeProvider @inject ILogger Log @inject ToastService Toast @using redb.Tsak.Client @using redb.Tsak.Contracts @implements IDisposable @if (_loading) {

Loading watchdog state…

} else if (_state is not null) { @* Status cards *@
@* Enable/Disable *@
@if (_state.Enabled) { } else { }
@* Active Alerts *@
Active Alerts
@if (_state.ActiveAlerts.Count > 0) { Route ID Context Level Exchange ID Elapsed Detected At @context.RouteId @context.ContextName @context.ExchangeId @FormatElapsed(context.ElapsedSeconds) @context.DetectedAt.ToString("yyyy-MM-dd HH:mm:ss") } else {

All clear — no active alerts

}
@* Alert delivery *@
Alert Delivery @if (_alertStatus is not null) { }
@if (_alertStatus is { Active: true }) {

Channels: @foreach (var c in _alertStatus.Channels) { @c }

@if (_testResult is not null) {
@foreach (var ch in _testResult.Channels) {
@ch.Channel @if (!ch.Success) { — @ch.Error }
}
} } else {

Alert delivery is off. Enable it and at least one channel (webhook / telegram / email / endpoint) under Tsak:Watchdog:Alerts. With no database or channel configured, alerts still go to the log.

}
@* Lifecycle events filtered to watchdog-related *@ @if (_watchdogEvents is { Length: > 0 }) {
Auto-Restart History
Timestamp Event Context Route Details @context.Timestamp.ToString("yyyy-MM-dd HH:mm:ss") @context.ContextName @(context.RouteId ?? "—") @(context.Details ?? "—")
} } else {

Watchdog not available on this node

} @code { [Parameter] public string NodeId { get; set; } = ""; private bool _loading = true; private WatchdogState? _state; private LifecycleEvent[]? _watchdogEvents; private AlertDeliveryStatus? _alertStatus; private AlertTestResult? _testResult; private bool _testing; private PeriodicTimer? _timer; private CancellationTokenSource? _cts; // Component-scoped token: API calls abort when the component is disposed (navigated away) (4.9). // Guard the disposed state — reading _cts.Token after Dispose throws ObjectDisposedException; a call // that started before Dispose already holds the (now-cancelled) token, so returning None here is safe. private CancellationToken Ct { get { try { return _cts?.Token ?? default; } catch (ObjectDisposedException) { return default; } } } protected override async Task OnInitializedAsync() { // _cts BEFORE the initial load — a component disposed mid-load must not start an // unstoppable orphan poll loop afterwards (review 2026-09-02, С19). _cts = new CancellationTokenSource(); await LoadData(); if (!_cts.IsCancellationRequested) _ = PollLoop(_cts.Token); } private Task PollLoop(CancellationToken ct) { _timer = new PeriodicTimer(TimeSpan.FromSeconds(15)); return PollLoops.RunAsync(_timer, ct, Log, async () => { await LoadData(); await InvokeAsync(StateHasChanged); }); } private async Task LoadData() { var client = NodeProvider.GetClient(NodeId); if (client is null) { _loading = false; return; } try { _state = await client.GetWatchdogStatusAsync(Ct); try { var events = await client.GetLifecycleEventsAsync( type: nameof(LifecycleEventType.WatchdogAutoRestart), limit: 50, ct: Ct); _watchdogEvents = events; } catch { } try { _alertStatus = await client.GetAlertStatusAsync(Ct); } catch { } } catch { } _loading = false; } private async Task TestAlert() { var client = NodeProvider.GetClient(NodeId); if (client is null) return; _testing = true; _testResult = null; try { _testResult = await client.TestAlertAsync(Ct); if (_testResult.Delivered) Toast.Success("Test alert delivered to all channels"); else Toast.Warning(_testResult.Message ?? "Some channels failed — see details"); } catch (Exception ex) { Toast.Error($"Test failed: {ex.Message}"); } finally { _testing = false; } } private async Task Refresh() => await LoadData(); private async Task Enable() { var client = NodeProvider.GetClient(NodeId); if (client is null) return; try { await client.EnableWatchdogAsync(Ct); await LoadData(); Toast.Success("Watchdog enabled"); } catch (Exception ex) { Toast.Error($"Failed: {ex.Message}"); } } private async Task Disable() { var client = NodeProvider.GetClient(NodeId); if (client is null) return; try { await client.DisableWatchdogAsync(Ct); await LoadData(); Toast.Success("Watchdog disabled"); } catch (Exception ex) { Toast.Error($"Failed: {ex.Message}"); } } private static string FormatElapsed(double seconds) { if (seconds < 60) return $"{seconds:F0}s"; if (seconds < 3600) return $"{(int)(seconds / 60)}m {(int)(seconds % 60)}s"; return $"{(int)(seconds / 3600)}h {(int)((seconds % 3600) / 60)}m"; } public void Dispose() { _cts?.Cancel(); _cts?.Dispose(); _timer?.Dispose(); } } Path: redb-tsak/src/redb.Tsak.Web/Components/Routes.razor Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Components/Routes.razor ---- @using Microsoft.AspNetCore.Components.Routing @using Microsoft.AspNetCore.Components.Authorization @* Anonymous: to the login form. Signed in, but below the page's role: told so, in place. *@ @if (auth.User.Identity?.IsAuthenticated == true) { } else { }

Page not found

The requested page does not exist.

Path: redb-tsak/src/redb.Tsak.Web/Components/Shared/AccessDenied.razor Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Components/Shared/AccessDenied.razor ---- @* What a signed-in user sees on a page above their role. Being sent to the login form instead read as a logout, and signing in again led straight back to the same refusal. *@

Access denied

Your role@(string.IsNullOrEmpty(_role) ? "" : $" ({_role})") does not open this page. Logs and the dead-letter queue need the operator role; the audit trail and Auth & Users need the admin role.

@code { [CascadingParameter] private Task? AuthState { get; set; } private string? _role; protected override async Task OnParametersSetAsync() { if (AuthState is null) return; _role = (await AuthState).User.FindFirst(System.Security.Claims.ClaimTypes.Role)?.Value; } } Path: redb-tsak/src/redb.Tsak.Web/Components/Shared/AuthorizedView.razor Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Components/Shared/AuthorizedView.razor ---- @using Microsoft.AspNetCore.Components.Authorization @if (_show) { @ChildContent } @code { [CascadingParameter] private Task? AuthState { get; set; } [Parameter] public bool AdminOnly { get; set; } [Parameter] public bool OperatorOnly { get; set; } [Parameter] public RenderFragment? ChildContent { get; set; } private bool _show; protected override async Task OnParametersSetAsync() { // The roles come from a signed auth cookie, so they cannot be forged client-side. // Pages themselves are gated by the [Authorize] in _Imports.razor (anonymous access is // refused at the route); this component only differentiates tiers within a page. var state = AuthState is null ? null : await AuthState; var user = state?.User; if (AdminOnly) { _show = user?.IsInRole("admin") ?? false; return; } if (OperatorOnly) { _show = user?.IsInRole("operator") ?? false; return; } // Any authenticated dashboard user. _show = user?.Identity?.IsAuthenticated ?? false; } } Path: redb-tsak/src/redb.Tsak.Web/Components/Shared/LifecyclePanel.razor Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Components/Shared/LifecyclePanel.razor ---- @* Embeddable lifecycle event feed for Dashboard or standalone use. *@ @using redb.Tsak.Client @using redb.Tsak.Contracts @if (_events is not null) {
Lifecycle Events @if (!string.IsNullOrEmpty(NodeLabel)) { — @NodeLabel }
@if (FilteredEvents.Length > 0) {
Timestamp Type Context Route Details @context.Timestamp.ToString("HH:mm:ss") @context.ContextName @(context.RouteId ?? "—") @(context.Details ?? "—")
} else {

No lifecycle events

}
} @code { [Parameter] public TsakApiClient? Client { get; set; } [Parameter] public int Limit { get; set; } = 20; [Parameter] public string? NodeLabel { get; set; } private LifecycleEvent[]? _events; private string _typeFilter = ""; private string _contextFilter = ""; private string[] _contextNames => _events? .Select(e => e.ContextName) .Distinct().OrderBy(n => n).ToArray() ?? []; private LifecycleEvent[] FilteredEvents { get { if (_events is null) return []; IEnumerable result = _events; if (!string.IsNullOrEmpty(_typeFilter) && Enum.TryParse(_typeFilter, out var t)) result = result.Where(e => e.EventType == t); if (!string.IsNullOrEmpty(_contextFilter)) result = result.Where(e => e.ContextName == _contextFilter); return result.ToArray(); } } protected override async Task OnParametersSetAsync() { await LoadEvents(); } public async Task RefreshAsync() { await LoadEvents(); // Callable from any thread (a page poll tick, a button handler): a direct StateHasChanged // off the Blazor dispatcher throws, and that silently killed the Dashboard refresh tick. await InvokeAsync(StateHasChanged); } private async Task LoadEvents() { if (Client is null) return; try { _events = await Client.GetLifecycleEventsAsync(limit: Limit); } catch { /* lifecycle may not be available */ } } private static string GetEventBadge(LifecycleEventType type) => type switch { LifecycleEventType.RouteStarted or LifecycleEventType.ContextStarted => "online", LifecycleEventType.RouteStopped or LifecycleEventType.ContextStopped or LifecycleEventType.ContextRemoved => "offline", LifecycleEventType.RouteErrored => "error", LifecycleEventType.RouteSuspended or LifecycleEventType.ExchangeTimedOut => "warning", LifecycleEventType.ExchangeHung or LifecycleEventType.WatchdogAutoRestart => "error", _ => "info" }; } Path: redb-tsak/src/redb.Tsak.Web/Components/Shared/NodeSwitcher.razor Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Components/Shared/NodeSwitcher.razor ---- @* The node chip of the top bar: the node of the page, and a list of every node with its state, to open the same page on another node. The sub-page, the entity and the query of the address stay (NodePath.WithNode). Keys: n opens it, [ and ] go to the previous and next node of the group; in the list the arrows move, Enter opens, Esc closes. Not shown with a single node. *@ @inject INodeClientProvider NodeProvider @inject NavigationManager Nav @inject IJSRuntime JS @implements IAsyncDisposable @if (NodeSwitch.IsShown(_entries)) {
@if (_open) {
@{ var shown = Shown; var index = 0; string? group = null; } @if (shown.Count == 0) {
No node matches
} @foreach (var e in shown) { var i = index++; if (!string.Equals(group, e.GroupName, StringComparison.OrdinalIgnoreCase) && _groups > 1) { group = e.GroupName;
@e.GroupName
} }
↑ ↓ move · Enter open · Esc close · [ ] previous / next
}
} @code { private IReadOnlyList _entries = []; private int _groups; private string? _currentId; private bool _open; private bool _focusPending; private string _filter = string.Empty; private int _highlight; private ElementReference _filterInput; private DotNetObjectReference? _self; private NodeSwitchEntry? Current => _entries.FirstOrDefault(e => e.NodeId == _currentId); private IReadOnlyList Shown => NodeSwitch.Filter(_entries, _filter); protected override async Task OnInitializedAsync() { Nav.LocationChanged += OnLocationChanged; _currentId = NodePath.NodeIdOf(Nav.ToBaseRelativePath(Nav.Uri)); SetEntries(NodeProvider.Topology ?? await NodeProvider.LoadTopologyAsync()); } protected override async Task OnAfterRenderAsync(bool firstRender) { if (firstRender) { _self = DotNetObjectReference.Create(this); await JS.InvokeVoidAsync("tsakNodeSwitch.attach", _self); } if (_focusPending) { _focusPending = false; await _filterInput.FocusAsync(); } } private void SetEntries(ClusterTopology? topology) { _entries = NodeSwitch.Entries(topology); _groups = _entries.Select(e => e.GroupName).Distinct(StringComparer.OrdinalIgnoreCase).Count(); } private void OnLocationChanged(object? sender, Microsoft.AspNetCore.Components.Routing.LocationChangedEventArgs e) { _currentId = NodePath.NodeIdOf(Nav.ToBaseRelativePath(e.Location)); _open = false; InvokeAsync(StateHasChanged); } private async Task Toggle() { if (_open) { Close(); return; } await Open(); } private async Task Open() { // The state shown is the state at the moment of choosing, not the one of the page load. SetEntries(await NodeProvider.LoadTopologyAsync(forceRefresh: true)); _filter = string.Empty; _highlight = Math.Max(0, Shown.ToList().FindIndex(e => e.NodeId == _currentId)); _open = true; _focusPending = true; } private void Close() { _open = false; _filter = string.Empty; } private void OnFilterChanged() => _highlight = 0; private void OnMenuKey(KeyboardEventArgs e) { var shown = Shown; switch (e.Key) { case "ArrowDown": if (shown.Count > 0) _highlight = (_highlight + 1) % shown.Count; break; case "ArrowUp": if (shown.Count > 0) _highlight = (_highlight - 1 + shown.Count) % shown.Count; break; case "Enter": if (_highlight >= 0 && _highlight < shown.Count) Go(shown[_highlight].NodeId); break; case "Escape": Close(); break; } } private void Go(string nodeId) { _open = false; _filter = string.Empty; if (nodeId == _currentId) return; Nav.NavigateTo(NodePath.WithNode(Nav.ToBaseRelativePath(Nav.Uri), nodeId)); } /// A shortcut pressed outside an input (nodeswitch.js): n, [ or ]. [JSInvokable] public async Task OnShortcut(string key) { if (!NodeSwitch.IsShown(_entries)) return; switch (key) { case "n": if (!_open) await Open(); break; case "[": case "]": if (NodeSwitch.Neighbour(_entries, _currentId, key == "]" ? 1 : -1) is { } next) Go(next); break; } StateHasChanged(); } public async ValueTask DisposeAsync() { Nav.LocationChanged -= OnLocationChanged; if (_self is not null) { try { await JS.InvokeVoidAsync("tsakNodeSwitch.detach"); } catch (JSDisconnectedException) { } _self.Dispose(); } } } Path: redb-tsak/src/redb.Tsak.Web/Components/Shared/RedirectToLogin.razor Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Components/Shared/RedirectToLogin.razor ---- @inject NavigationManager Nav @code { // Sends an unauthenticated visitor to /login, preserving where they were headed so the login // endpoint can bounce them back after sign-in. protected override void OnInitialized() { var returnUrl = Nav.ToBaseRelativePath(Nav.Uri); var target = string.IsNullOrEmpty(returnUrl) || returnUrl.StartsWith("login") ? "login" : $"login?returnUrl={Uri.EscapeDataString("/" + returnUrl)}"; Nav.NavigateTo(target, forceLoad: false); } } Path: redb-tsak/src/redb.Tsak.Web/Components/Shared/TsakBadge.razor Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Components/Shared/TsakBadge.razor ---- @* Status badge with colored dot. Usage: *@ @if (ShowDot) { } @Text @code { /// Display text. [Parameter, EditorRequired] public string Text { get; set; } = ""; /// Badge variant: online, warning, error, info, offline. [Parameter] public string Variant { get; set; } = "offline"; /// Show colored dot indicator. [Parameter] public bool ShowDot { get; set; } = true; } Path: redb-tsak/src/redb.Tsak.Web/Components/Shared/TsakCard.razor Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Components/Shared/TsakCard.razor ---- @* Metric card with title, icon, value, and optional content. *@
@Title @if (Icon is not null) { } @if (HeaderExtra is not null) { @HeaderExtra }
@if (ChildContent is not null) { @ChildContent } else { @Value }
@code { [Parameter, EditorRequired] public string Title { get; set; } = ""; [Parameter] public string? Icon { get; set; } [Parameter] public string? Value { get; set; } [Parameter] public string? ValueStyle { get; set; } [Parameter] public RenderFragment? HeaderExtra { get; set; } [Parameter] public RenderFragment? ChildContent { get; set; } } Path: redb-tsak/src/redb.Tsak.Web/Components/Shared/TsakChart.razor Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Components/Shared/TsakChart.razor ---- @using Microsoft.JSInterop @inject IJSRuntime JS @implements IAsyncDisposable
@code { [Parameter, EditorRequired] public string ChartId { get; set; } = default!; [Parameter] public int? Height { get; set; } private string _canvasId => $"chart-{ChartId}"; public async Task CreateLineAsync(string[] labels, ChartDataset[] datasets, string? yAxisLabel = null) { await JS.InvokeVoidAsync("tsakCharts.createLine", _canvasId, labels, datasets, yAxisLabel); } /// /// Creates an area chart (line with fill) with the given labels and datasets. /// public async Task CreateAreaAsync(string[] labels, ChartDataset[] datasets, string? yAxisLabel = null) { await JS.InvokeVoidAsync("tsakCharts.createArea", _canvasId, labels, datasets, yAxisLabel); } /// /// Creates a bar chart with the given labels and datasets. /// public async Task CreateBarAsync(string[] labels, ChartDataset[] datasets, string? yAxisLabel = null) { await JS.InvokeVoidAsync("tsakCharts.createBar", _canvasId, labels, datasets, yAxisLabel); } /// /// Creates a donut chart with the given labels, values and colors. /// public async Task CreateDonutAsync(string[] labels, double[] data, string[] colors) { await JS.InvokeVoidAsync("tsakCharts.createDonut", _canvasId, labels, data, colors); } /// /// Updates chart data without recreating it. /// public async Task UpdateAsync(string[] labels, ChartDataset[] datasets) { await JS.InvokeVoidAsync("tsakCharts.update", _canvasId, labels, datasets); } public async ValueTask DisposeAsync() { try { await JS.InvokeVoidAsync("tsakCharts.destroy", _canvasId); } catch (JSDisconnectedException) { } catch (JSException) { } catch (InvalidOperationException) { } } public record ChartDataset(string Label, double[] Data, string BorderColor, string? BackgroundColor = null); } Path: redb-tsak/src/redb.Tsak.Web/Components/Shared/TsakConfirmDialog.razor Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Components/Shared/TsakConfirmDialog.razor ---- @* Confirmation dialog for destructive actions. *@ @if (_visible) {
@Title

@Message

} @code { private bool _visible; private string _variant = "danger"; private TaskCompletionSource? _tcs; [Parameter] public string Title { get; set; } = "Confirm action"; [Parameter] public string Message { get; set; } = "Are you sure?"; [Parameter] public string ConfirmText { get; set; } = "Confirm"; public Task ShowAsync(string? message = null, string? title = null, string variant = "danger") { _tcs = new TaskCompletionSource(); if (message is not null) Message = message; if (title is not null) Title = title; _variant = variant; _visible = true; InvokeAsync(StateHasChanged); return _tcs.Task; } private void Confirm() { _visible = false; _tcs?.TrySetResult(true); StateHasChanged(); } private void Cancel() { _visible = false; _tcs?.TrySetResult(false); StateHasChanged(); } } Path: redb-tsak/src/redb.Tsak.Web/Components/Shared/TsakErrorBoundary.razor Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Components/Shared/TsakErrorBoundary.razor ---- @inherits ErrorBoundaryBase @inject ILogger Logger @if (CurrentException is not null) {

Something went wrong

@* Generic message only (review item 4.7): the raw exception text can carry internal detail (paths, config, connection strings) and is written to the server log instead. *@

An unexpected error occurred. Try refreshing the page.

} else { @ChildContent } @code { protected override Task OnErrorAsync(Exception exception) { // Keep the detail server-side (the UI shows only a generic message — review item 4.7). Logger.LogError(exception, "Unhandled UI error caught by TsakErrorBoundary"); return Task.CompletedTask; } } Path: redb-tsak/src/redb.Tsak.Web/Components/Shared/TsakGrid.razor Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Components/Shared/TsakGrid.razor ---- @* Generic data grid with sorting, filtering, and pagination. *@ @typeparam T @if (Items is null || !Items.Any()) { @if (EmptyContent is not null) { @EmptyContent } else {

No data

} } else { @if (Filterable) {
}
@HeaderContent @foreach (var item in PagedItems) { @RowContent(item) }
@if (EffectivePageSize > 0 && (TotalPages > 1 || PageSizeOptions is { Length: > 0 })) {
Page @_page / @TotalPages (@_filteredItems.Count items) @if (PageSizeOptions is { Length: > 0 } sizes) { }
} } @code { [Parameter, EditorRequired] public IEnumerable? Items { get; set; } [Parameter, EditorRequired] public RenderFragment? HeaderContent { get; set; } [Parameter, EditorRequired] public RenderFragment RowContent { get; set; } = default!; [Parameter] public RenderFragment? EmptyContent { get; set; } [Parameter] public int PageSize { get; set; } [Parameter] public bool Filterable { get; set; } /// /// Page sizes the reader may switch between, shown next to the pager. Null leaves /// fixed, which is what every grid that does not pass this keeps doing. /// [Parameter] public int[]? PageSizeOptions { get; set; } /// /// Raised when the reader picks another page size, so a page that outlives this grid can remember the /// choice. Without it the size is forgotten every time the grid is re-created — which happens as soon as /// the page swaps what it shows. /// [Parameter] public EventCallback PageSizeChanged { get; set; } [Parameter] public Func? FilterSelector { get; set; } [Parameter] public EventCallback OnRowClick { get; set; } // The size the reader picked, if any; otherwise the one the page asked for. private int? _chosenPageSize; private int EffectivePageSize => _chosenPageSize ?? PageSize; private async Task OnPageSizeChanged(ChangeEventArgs e) { if (!int.TryParse(e.Value?.ToString(), out var size) || size <= 0) return; _chosenPageSize = size; // The reader is looking at a row that is now on another page; the first page is the honest answer. _page = 1; await PageSizeChanged.InvokeAsync(size); } private string _filterText = ""; private int _page = 1; private List _filteredItems = new(); private string? _sortColumn; private bool _sortAsc = true; private Func? _sortSelector; private int TotalPages => EffectivePageSize > 0 ? Math.Max(1, (int)Math.Ceiling(_filteredItems.Count / (double)EffectivePageSize)) : 1; private IEnumerable PagedItems => EffectivePageSize > 0 ? _filteredItems.Skip((_page - 1) * EffectivePageSize).Take(EffectivePageSize) : _filteredItems; protected override void OnParametersSet() { ApplyFilter(); } public void Sort(string column, Func selector) { if (_sortColumn == column) _sortAsc = !_sortAsc; else { _sortColumn = column; _sortAsc = true; } _sortSelector = selector; ApplySort(); StateHasChanged(); } public string SortIndicator(string column) => _sortColumn != column ? "" : _sortAsc ? " ↑" : " ↓"; /// /// Rebuilds the visible rows. The page the reader is on survives: every render of the parent lands here, /// and resetting to the first page then meant a row clicked on page three sent the reader back to page /// one. Only a change of the filter starts over; otherwise the page is merely kept inside the range the /// data still has. /// private void ApplyFilter(bool resetPage = false) { if (Items is null) { _filteredItems = new(); return; } if (string.IsNullOrWhiteSpace(_filterText) || FilterSelector is null) _filteredItems = Items.ToList(); else { var term = _filterText; _filteredItems = Items .Where(i => FilterSelector(i).Contains(term, StringComparison.OrdinalIgnoreCase)) .ToList(); } ApplySort(); _page = resetPage ? 1 : Math.Clamp(_page, 1, TotalPages); } private void OnFilterChanged() => ApplyFilter(resetPage: true); private void ApplySort() { if (_sortSelector is null) return; _filteredItems = _sortAsc ? _filteredItems.OrderBy(_sortSelector).ToList() : _filteredItems.OrderByDescending(_sortSelector).ToList(); } private void GoToPage(int page) { _page = Math.Clamp(page, 1, TotalPages); } } Path: redb-tsak/src/redb.Tsak.Web/Components/Shared/TsakIcon.razor Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Components/Shared/TsakIcon.razor ---- @* Inline SVG icon component. Usage: *@ @((MarkupString)GetPath(Name)) @code { [Parameter] public string Name { get; set; } = ""; [Parameter] public int Size { get; set; } = 20; private static string GetPath(string name) => name switch { // Navigation "dashboard" => "", "cluster" => "", "route" => "", "package" => "", "clock" => "", "activity" => "", "terminal" => "", "shield" => "", // Status "check-circle" => "", "alert-triangle" => "", "alert-circle" => "", "x-circle" => "", // Actions "refresh" => "", "play" => "", "pause" => "", "stop" => "", "trash" => "", "download" => "", "upload" => "", "search" => "", "filter" => "", "copy" => "", "logout" => "", "settings" => "", // Data "database" => "", "server" => "", "cpu" => "", // Theme "sun" => "", "moon" => "", // Misc "key" => "", "user" => "", "info" => "", "chevron-right" => "", "chevron-left" => "", "send" => "", "chevron-down" => "", "chevron-up" => "", "external-link" => "", "menu" => "", "x" => "", "arrow-left" => "", _ => "" }; } Path: redb-tsak/src/redb.Tsak.Web/Components/Shared/TsakPageHeader.razor Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Components/Shared/TsakPageHeader.razor ---- @* Page header with title, description, auto-refresh label and refresh button. *@ @code { [Parameter, EditorRequired] public string Title { get; set; } = ""; [Parameter] public string? Description { get; set; } [Parameter] public string? RefreshInterval { get; set; } [Parameter] public EventCallback OnRefresh { get; set; } [Parameter] public RenderFragment? Actions { get; set; } } Path: redb-tsak/src/redb.Tsak.Web/Components/Shared/TsakSparkline.razor Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Components/Shared/TsakSparkline.razor ---- @* Inline SVG sparkline — no Chart.js dependency *@ @if (Data.Length > 1) { } @code { [Parameter] public double[] Data { get; set; } = []; [Parameter] public int Width { get; set; } = 80; [Parameter] public int Height { get; set; } = 24; [Parameter] public string Color { get; set; } = "var(--primary)"; private string GetPoints() { if (Data.Length < 2) return ""; var min = Data.Min(); var max = Data.Max(); var range = max - min; if (range == 0) range = 1; var padding = 2; var w = Width - padding * 2; var h = Height - padding * 2; var step = (double)w / (Data.Length - 1); var points = new System.Text.StringBuilder(); for (var i = 0; i < Data.Length; i++) { var x = padding + i * step; var y = padding + h - (Data[i] - min) / range * h; if (i > 0) points.Append(' '); points.Append($"{x:F1},{y:F1}"); } return points.ToString(); } } Path: redb-tsak/src/redb.Tsak.Web/Components/Shared/TsakToast.razor Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Components/Shared/TsakToast.razor ---- @* Toast notification service component. Place once in TsakShell. *@ @if (_toasts.Count > 0) {
@foreach (var toast in _toasts) {
@toast.Message
}
} @code { private readonly List _toasts = new(); private int _nextId; public void Show(string message, string level = "info", int durationMs = 4000) { var toast = new ToastItem(++_nextId, message, level); _toasts.Add(toast); InvokeAsync(StateHasChanged); if (durationMs > 0) { _ = AutoDismiss(toast.Id, durationMs); } } public void Success(string message) => Show(message, "success"); public void Error(string message) => Show(message, "error", 8000); public void Warning(string message) => Show(message, "warning", 6000); private async Task AutoDismiss(int id, int ms) { await Task.Delay(ms); Dismiss(id); } private void Dismiss(int id) { _toasts.RemoveAll(t => t.Id == id); InvokeAsync(StateHasChanged); } private static string GetIcon(string level) => level switch { "success" => "check-circle", "error" => "x-circle", "warning" => "alert-triangle", _ => "info" }; private record ToastItem(int Id, string Message, string Level); } Path: redb-tsak/src/redb.Tsak.Web/Components/Shared/WatchdogPanel.razor Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Components/Shared/WatchdogPanel.razor ---- @* Embeddable watchdog status panel for Dashboard or standalone use. *@ @using redb.Tsak.Client @using redb.Tsak.Contracts @if (_state is not null) {
Watchdog @if (!string.IsNullOrEmpty(NodeLabel)) { — @NodeLabel }
@if (ShowActions) { @if (_state.Enabled) { } else { } }
@if (_state.ActiveAlerts.Count > 0) {
Route Context Level Exchange Elapsed Detected @context.RouteId @context.ContextName @context.ExchangeId[..Math.Min(12, context.ExchangeId.Length)]… @($"{context.ElapsedSeconds:F0}s") @context.DetectedAt.ToString("HH:mm:ss")
} else if (_state.Enabled) {

No active alerts

}
} @code { [Parameter] public TsakApiClient? Client { get; set; } [Parameter] public bool ShowActions { get; set; } = true; [Parameter] public EventCallback OnStateChanged { get; set; } [Parameter] public string? NodeLabel { get; set; } private WatchdogState? _state; protected override async Task OnParametersSetAsync() { await LoadState(); } public async Task RefreshAsync() { await LoadState(); // Callable from any thread (a page poll tick, a button handler): a direct StateHasChanged // off the Blazor dispatcher throws, and that silently killed the Dashboard refresh tick. await InvokeAsync(StateHasChanged); } private async Task LoadState() { if (Client is null) return; try { _state = await Client.GetWatchdogStatusAsync(); } catch { /* watchdog may not be available */ } } private async Task Enable() { if (Client is null) return; try { await Client.EnableWatchdogAsync(); await LoadState(); await OnStateChanged.InvokeAsync(); } catch { } } private async Task Disable() { if (Client is null) return; try { await Client.DisableWatchdogAsync(); await LoadState(); await OnStateChanged.InvokeAsync(); } catch { } } } Path: redb-tsak/src/redb.Tsak.Web/Components/_Imports.razor Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Components/_Imports.razor ---- @using Microsoft.AspNetCore.Components.Web @using Microsoft.AspNetCore.Components.Routing @* Components.Forms is where lives. Without this using the tag is NOT a component — it renders as inert markup, the login/logout forms carry no token, and every login POST fails antiforgery validation before credentials are even read (RZ10012 was the only symptom at build time; found live 2026-09-08). *@ @using Microsoft.AspNetCore.Components.Forms @using Microsoft.AspNetCore.Components.Authorization @using Microsoft.AspNetCore.Authorization @* Every page requires an authenticated user. AuthorizeRouteView enforces ONLY the [Authorize] metadata declared on the routed page itself — without this line it is a no-op and the whole dashboard renders anonymously (review 2026-09-02, К1). Login.razor opts out via [AllowAnonymous]; pages needing a higher tier add [Authorize(Policy = ...)] on top. *@ @attribute [Authorize] @using Microsoft.JSInterop @using redb.Tsak.Contracts @using redb.Tsak.Web.Pro @using redb.Tsak.Web.Components.Layout @using redb.Tsak.Web.Components.Shared @using redb.Tsak.Web.Services Path: redb-tsak/src/redb.Tsak.Web/Program.cs Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Program.cs ---- using System.Security.Claims; using Microsoft.AspNetCore.Antiforgery; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using redb.Tsak.Web.Pro; using redb.Tsak.Web.Pro.Extensions; using redb.Tsak.Web.Security; using redb.Tsak.Web.Services; using Serilog; var builder = WebApplication.CreateBuilder(args); // Serilog — same pattern as Worker builder.Host.UseSerilog((context, services, configuration) => configuration .ReadFrom.Configuration(context.Configuration)); // Standalone defaults — always registered builder.Services.AddSingleton(); builder.Services.AddScoped(); builder.Services.AddScoped(); // The log lines a browser tab has seen, per node, for the life of its circuit (Logs page). builder.Services.AddScoped(); // Pro — always called, mode check inside (like Core.Pro AddTsakCluster) builder.Services.AddTsakWebPro(builder.Configuration); // ── Authentication / authorization ───────────────────────────────────────── // Real server-side session: an ASP.NET Core auth cookie, not a per-circuit in-memory flag. This is // what makes the dashboard a proper BFF — the browser holds only the cookie; the server holds the // Tsak keys and only uses them for an authenticated principal. Pages are gated by the [Authorize] // attribute they inherit from Components/_Imports.razor (AuthorizeRouteView enforces the page's // own authorize metadata — it is NOT a gate by itself; review 2026-09-02, К1); plain HTTP // endpoints (e.g. the log-download proxy) carry explicit RequireAuthorization. builder.Services.AddHttpContextAccessor(); builder.Services.AddCascadingAuthenticationState(); // Behind a TLS-terminating reverse proxy (the DEPLOYMENT.md nginx shape) the app must honor // X-Forwarded-Proto/For — otherwise it sees plain HTTP, issues the auth cookie without Secure and // never sends HSTS, and the login throttle cannot see real client addresses (review 2026-09-02, // В12/В15). Opt-in, mirroring the worker's Tsak:Http:TrustedProxies posture. var trustProxyHeaders = builder.Configuration.GetValue("Tsak:Web:TrustProxyHeaders", false); if (trustProxyHeaders) { builder.Services.Configure(o => { o.ForwardedHeaders = Microsoft.AspNetCore.HttpOverrides.ForwardedHeaders.XForwardedFor | Microsoft.AspNetCore.HttpOverrides.ForwardedHeaders.XForwardedProto; // The dashboard sits directly behind the operator's own proxy; which hop is trusted is the // operator's choice, expressed by turning the flag on. o.KnownIPNetworks.Clear(); o.KnownProxies.Clear(); }); } builder.Services .AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { options.Cookie.Name = "tsak.auth"; options.Cookie.HttpOnly = true; options.Cookie.SameSite = SameSiteMode.Strict; // Dashboard often runs plain HTTP on loopback / behind a TLS-terminating proxy; require // HTTPS only when the request itself is HTTPS so local runs are not locked out. Behind a // proxy, Tsak:Web:TrustProxyHeaders=true makes the request scheme (and thus Secure) real. options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest; options.LoginPath = "/login"; // A signed-in user below a page's role is told so; the login form read as a logout, and signing in // again led back to the same refusal. options.AccessDeniedPath = "/denied"; options.ExpireTimeSpan = TimeSpan.FromHours(8); options.SlidingExpiration = true; // A deleted or demoted user must not ride an 8-hour sliding cookie (review 2026-09-02, // В14): re-resolve the account every 5 minutes; reject the principal when it is gone or // its role changed. Blazor circuits are covered by the revalidating state provider below. options.Events = new CookieAuthenticationEvents { OnValidatePrincipal = ctx => DashboardAuth.RevalidatePrincipalAsync(ctx) }; }); // Failed-login throttle (lockout) — shared across all requests on the node. builder.Services.AddSingleton(sp => { var cfg = sp.GetRequiredService(); return new LoginThrottle( maxAttempts: cfg.GetValue("Tsak:Web:Lockout:MaxAttempts", 5), window: TimeSpan.FromSeconds(cfg.GetValue("Tsak:Web:Lockout:WindowSeconds", 300)), lockoutDuration: TimeSpan.FromSeconds(cfg.GetValue("Tsak:Web:Lockout:DurationSeconds", 60))); }); builder.Services.AddAuthorization(options => { // Role ladder is expanded into claims at sign-in, so RequireRole is a simple membership test. options.AddPolicy("Viewer", p => p.RequireRole("viewer")); options.AddPolicy("Operator", p => p.RequireRole("operator")); options.AddPolicy("Admin", p => p.RequireRole("admin")); }); // Fast shutdown on Ctrl+C (default is 30s) builder.Services.Configure(o => o.ShutdownTimeout = TimeSpan.FromSeconds(5)); // Blazor Server builder.Services.AddRazorComponents() .AddInteractiveServerComponents(); // Circuit-side session revalidation (review 2026-09-02, В14) — pairs with the cookie's // OnValidatePrincipal: a live circuit fixes its auth state at connect time and must be re-checked. builder.Services.AddScoped(); var app = builder.Build(); var pathBase = app.Configuration["ASPNETCORE_PATHBASE"] ?? Environment.GetEnvironmentVariable("ASPNETCORE_PATHBASE"); if (!string.IsNullOrEmpty(pathBase)) app.UsePathBase(pathBase); if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseStaticFiles(); if (trustProxyHeaders) app.UseForwardedHeaders(); // before auth: the scheme/client-IP must be real when cookies are issued app.UseAuthentication(); app.UseAuthorization(); app.UseAntiforgery(); // ── Auth endpoints ───────────────────────────────────────────────────────── // Sign-in must happen on a plain HTTP request (SignInAsync writes the Set-Cookie header), which a // Blazor interactive circuit cannot do after the response has started. The login form POSTs here. app.MapPost("/auth/login", async ( HttpContext http, IAntiforgery antiforgery, IAuthService auth, LoginThrottle throttle) => { // ABSOLUTE path (as below): the request path is /auth/login, so a relative "login?..." // resolved under /auth/ and sent the browser to GET this POST-only endpoint — HTTP 405 // instead of an error message. A distinct code, so a stale/missing token is not // misreported as wrong credentials. try { await antiforgery.ValidateRequestAsync(http); } catch { return Results.Redirect("/login?error=stale"); } var form = await http.Request.ReadFormAsync(); var login = form["login"].ToString(); var password = form["password"].ToString(); var returnUrl = form["returnUrl"].ToString(); // Two throttle dimensions (review 2026-09-02, В15). Keying on the username alone let a remote // attacker lock the real administrator out with ~5 wrong passwords a minute, from anywhere; // (username, client IP) confines a lockout to the attacker's own address. The coarser IP-only // bucket (4x budget) slows password spraying across many usernames from one source. Behind a // proxy the client IP is real only with Tsak:Web:TrustProxyHeaders=true. var clientIp = http.Connection.RemoteIpAddress?.ToString() ?? "unknown"; var userKey = $"u:{login.Trim().ToLowerInvariant()}|{clientIp}"; var ipKey = $"ip:{clientIp}"; if (throttle.IsLockedOut(userKey) || throttle.IsLockedOut(ipKey)) return Results.Redirect("/login?error=locked"); var user = string.IsNullOrEmpty(login) ? null : await auth.ValidateAsync(login, password); if (user is null) { throttle.RecordFailure(userKey); throttle.RecordFailure(ipKey, maxAttemptsOverride: throttle.MaxAttempts * 4); return Results.Redirect("/login?error=1"); } throttle.RecordSuccess(userKey); var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme, ClaimTypes.Name, ClaimTypes.Role); identity.AddClaim(new Claim(ClaimTypes.Name, user.Login)); if (!string.IsNullOrEmpty(user.DisplayName)) identity.AddClaim(new Claim("display_name", user.DisplayName)); foreach (var role in DashboardAuth.ExpandRoles(user.Role)) identity.AddClaim(new Claim(ClaimTypes.Role, role)); await http.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity), new AuthenticationProperties { IsPersistent = true }); // Only ever redirect to a local path — never an attacker-supplied absolute URL. return DashboardAuth.IsLocalUrl(returnUrl) ? Results.LocalRedirect(returnUrl) : Results.Redirect("/"); }).DisableAntiforgery(); // validated manually above app.MapPost("/auth/logout", async (HttpContext http, IAntiforgery antiforgery) => { try { await antiforgery.ValidateRequestAsync(http); } catch { /* logout is idempotent — a bad token just means we still sign out */ } await http.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); return Results.Redirect("/login"); // absolute: relative "login" resolved to /auth/login (405) }).DisableAntiforgery(); // ── BFF proxy: download log files from worker nodes ──────────────────────── // Now behind the same auth as the rest of the dashboard: Operator+ only, node validated by the // client provider, filename constrained to a bare name (no path traversal). Anonymous / viewer // callers get 401/403 from the auth middleware before this handler runs. app.MapGet("/api/proxy/{nodeId}/logs/download/{filename}", async ( string nodeId, string filename, INodeClientProvider nodeProvider, CancellationToken ct) => // bound to HttpContext.RequestAborted — a cancelled download aborts the fetch (4.9) { // Reject anything that is not a plain file name (path traversal, nested paths). if (!DashboardAuth.IsSafeLogFileName(filename)) return Results.BadRequest(new { Error = "InvalidFilename" }); var client = nodeProvider.GetClient(nodeId); if (client is null) return Results.NotFound(new { Error = "NodeNotFound", Message = $"Node '{nodeId}' not available" }); try { var zipBytes = await client.DownloadLogFileAsync(filename, ct); return Results.File(zipBytes, "application/zip", $"{filename}.zip"); } catch (redb.Tsak.Client.ApiException ex) { return Results.StatusCode(ex.StatusCode); } catch (OperationCanceledException) when (!ct.IsCancellationRequested) { // The download client's own (longer) timeout elapsed — not a browser disconnect (which sets `ct` // and is handled by ASP.NET as a client abort). Return a clean 504 instead of an unhandled 500 (4.9). return Results.StatusCode(504); } }).RequireAuthorization("Admin"); // review item 2.8: full log files are admin-only (exfil risk) app.MapRazorComponents() .AddInteractiveServerRenderMode(); // Startup visibility: log the port(s) the dashboard actually bound to, once the server is listening. // app.Urls is only populated after the host starts, so read it from the ApplicationStarted callback. app.Lifetime.ApplicationStarted.Register(() => { var urls = app.Urls.Count > 0 ? string.Join(", ", app.Urls) : "(configured via ASPNETCORE_URLS / launch profile / Kestrel config)"; var tsakNode = app.Configuration["Tsak:Web:StandaloneUrl"] ?? "http://localhost:9090"; app.Logger.LogInformation( "Tsak dashboard listening on {Urls}; proxying to Tsak management API at {Node}", urls, tsakNode); }); app.Run(); // Exposed so integration tests can reference the entry-point assembly. public partial class Program { } Path: redb-tsak/src/redb.Tsak.Web/Properties/launchSettings.json Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Properties/launchSettings.json ---- { "profiles": { "redb.Tsak.Web": { "commandName": "Project", "launchBrowser": true, "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" }, "applicationUrl": "https://localhost:5181;http://localhost:5180" } } } Path: redb-tsak/src/redb.Tsak.Web/README.md Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/README.md ---- # redb.Tsak.Web Blazor Server dashboard for monitoring and managing **redb.Tsak** worker nodes. Provides real-time visibility into node health, route execution, contexts, watchdog alerts, and cluster topology. ## Operating Modes The dashboard supports two deployment modes, controlled by a single configuration key: | Mode | `Tsak:Web:Mode` | Database required | Description | |------|-----------------|-------------------|-------------| | **Standalone** | `"standalone"` (or omitted) | No | Connects to worker nodes directly via HTTP. Node list is defined in config. | | **Cluster** | `"cluster"` | Yes | Discovers nodes dynamically from the shared redb store. Supports multi-node topology, leader election, and group management. | ## Quick Start ```bash dotnet run --project src/redb.Tsak.Web ``` Default URL: `http://localhost:5100` Default credentials: `admin` / `admin` (configurable) --- ## Configuration Reference All settings live under the `Tsak:Web` section in `appsettings.json`. ### Authentication | Key | Type | Default | Description | |-----|------|---------|-------------| | `AdminLogin` | `string` | — | Login for dashboard access. Required in both modes. | | `AdminPassword` | `string` | — | Password for dashboard access. Required in both modes. | In **standalone** mode, credentials are validated directly against these config values. In **cluster** mode, credentials are validated against users stored in the redb store (seeded from config on first startup). > **Important — auth durability:** the admin sign-in state lives **in-memory per Blazor circuit**. > After a Web process restart (or a circuit reconnect that lost server state), all admins are > logged out and must sign in again. Persistent sign-in (cookie / JWT bearer) is **not** on the > current roadmap — Web is intended as an internal operator console, not a public portal. ### Standalone Mode No database, no redb store — the dashboard talks to worker nodes over HTTP using `TsakApiClient`. | Key | Type | Default | Description | |-----|------|---------|-------------| | `Mode` | `string` | `"standalone"` | Can be omitted — standalone is the default. | | `Nodes` | `array` | — | List of worker nodes to connect to. | | `Nodes[].Id` | `string` | `node-{n}` | Unique node identifier. Auto-generated if omitted. | | `Nodes[].Url` | `string` | — | Worker API base URL (e.g. `http://localhost:9090`). **Required.** | | `Nodes[].ApiKey` | `string` | — | API key for authenticating with the worker. Must match the worker's `Tsak:Api:Key`. | | `StandaloneUrl` | `string` | `http://localhost:9090` | Legacy fallback — used only if `Nodes` array is absent. Single-node shortcut. | **Example:** ```jsonc { "Tsak": { "Web": { "AdminLogin": "admin", "AdminPassword": "admin", "Nodes": [ { "Id": "worker-1", "Url": "http://localhost:9090", "ApiKey": "your_api_key" } ] } } } ``` > **Note:** ConnectionStrings and `Tsak:Redb` sections are **not required** in standalone mode. ### Cluster Mode Requires a shared database (Postgres or MSSQL). Node topology is discovered from the redb store. Supports leader election, node groups, module assignments, and automatic dead-node detection. | Key | Type | Default | Description | |-----|------|---------|-------------| | `Mode` | `string` | — | Must be `"cluster"`. | | `ServiceApiKey` | `string` | — | API key for node-to-node communication. Must match workers' `Tsak:Api:Key`. | **Additional sections required in cluster mode:** | Section | Description | |---------|-------------| | `ConnectionStrings:Postgres` or `ConnectionStrings:MSSql` | Database connection string for the redb store. | | `Tsak:Redb:Provider` | Database provider: `"postgres"` or `"mssql"`. | | `Tsak:Redb:UsePro` | Must be `true` for cluster features. Pro is free of charge and needs no key. | | `Tsak:Redb:PropsSaveStrategy` | Props save strategy (e.g. `"ChangeTracking"`). | **Example:** ```jsonc { "ConnectionStrings": { "Postgres": "Host=localhost;Port=5432;Username=postgres;Password=postgres;Database=redb" }, "Tsak": { "Redb": { "Provider": "postgres", "UsePro": true, "PropsSaveStrategy": "ChangeTracking" }, "Web": { "AdminLogin": "admin", "AdminPassword": "admin", "Mode": "cluster", "ServiceApiKey": "your_api_key" } } } ``` ### Logging (Serilog) Logging is configured via the standard `Serilog` section. The dashboard uses [Serilog.AspNetCore](https://github.com/serilog/serilog-aspnetcore) with console and file sinks. | Key | Description | |-----|-------------| | `Serilog:MinimumLevel:Default` | Global minimum level (`Information`, `Debug`, etc.) | | `Serilog:MinimumLevel:Override:redb.Tsak.Web` | Override for dashboard-specific logs. | | `Serilog:WriteTo` | Sink configuration (Console, File). | Log files are written to `Logs/web-{Date}.txt` with 7-day retention by default. ### Path Base For reverse-proxy deployments (e.g. behind nginx at `/dashboard`): | Key | Type | Description | |-----|------|-------------| | `ASPNETCORE_PATHBASE` | `string` | Base path prefix. Can also be set as an environment variable. | --- ## Architecture ``` Program.cs ├── Register standalone defaults (always) │ ├── StandaloneClientProvider → INodeClientProvider │ └── ConfigAuthService → IAuthService │ └── AddTsakWebPro() (always called, mode check inside) └── if Mode == "cluster": ├── ConfigureRedb() → redb store access ├── ClusterClientProvider → INodeClientProvider (overrides standalone) └── RedbAuthService → IAuthService (overrides standalone) ``` The **always-included** pattern means `Program.cs` has zero conditional logic. The Pro assembly checks `Tsak:Web:Mode` internally and either overrides the standalone defaults or no-ops. ### Key Interfaces | Interface | Standalone impl | Cluster impl | Description | |-----------|----------------|--------------|-------------| | `INodeClientProvider` | `StandaloneClientProvider` | `ClusterClientProvider` | Provides `TsakApiClient` instances for worker nodes. | | `IAuthService` | `ConfigAuthService` | `RedbAuthService` | Dashboard authentication and authorization. | ### Project Dependencies ``` redb.Tsak.Web ├── redb.Tsak.Client (HTTP client for worker API) ├── redb.Tsak.Contracts (shared models: ClusterTopology, NodeInfo, NodeStatus) └── redb.Tsak.Web.Pro (cluster-mode services, interfaces) ├── redb.Tsak.Client ├── redb.Tsak.Contracts └── redb.Tsak.Core.Pro (redb store, node registry) ``` ### UI Features | Page | Description | Mode | |------|-------------|------| | **Dashboard** | Node health overview, sparklines, route metrics, watchdog alerts | Both | | **Cluster** | Group topology, node grid, leader info, module assignments | Cluster only | | **Node Detail** | Per-node deep dive: contexts, routes, endpoints, modules, metrics, logs | Both | ### BFF Proxy The dashboard exposes a single BFF endpoint for log file downloads: ``` GET /api/proxy/{nodeId}/logs/download/{filename} ``` This proxies the request to the appropriate worker node via `TsakApiClient`, so the browser doesn't need direct access to worker APIs. --- ## Switching Modes To switch from cluster to standalone (or vice versa), edit `appsettings.json` and restart: ```jsonc // Standalone — comment out cluster block, uncomment standalone "Web": { "AdminLogin": "admin", "AdminPassword": "admin", "Nodes": [ { "Id": "local", "Url": "http://localhost:9090", "ApiKey": "..." } ] } // Cluster — set Mode, remove Nodes "Web": { "AdminLogin": "admin", "AdminPassword": "admin", "Mode": "cluster", "ServiceApiKey": "..." } ``` No code changes, no recompilation — just config. Path: redb-tsak/src/redb.Tsak.Web/Security/DashboardAuth.cs Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Security/DashboardAuth.cs ---- using System.Security.Claims; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using redb.Tsak.Web.Pro; namespace redb.Tsak.Web.Security; /// /// Pure, side-effect-free security helpers for the dashboard's auth endpoints. Kept out of /// Program.cs so the security-critical rules (path-traversal guard, open-redirect guard, /// role ladder, session revalidation) are unit-testable in isolation. /// public static class DashboardAuth { /// How often a signed-in principal is re-checked against the account store. public static readonly TimeSpan RevalidationInterval = TimeSpan.FromMinutes(5); private const string RevalidatedAtClaim = "revalidated_at"; /// /// Cookie-side half of session revalidation (review 2026-09-02, В14): every /// the account is re-resolved through /// — a deleted user or a changed role rejects the /// principal and signs the cookie out instead of riding the 8-hour sliding expiration. /// public static async Task RevalidatePrincipalAsync(CookieValidatePrincipalContext ctx) { var principal = ctx.Principal; var login = principal?.Identity?.Name; if (principal is null || string.IsNullOrEmpty(login)) { ctx.RejectPrincipal(); return; } var stamp = principal.FindFirst(RevalidatedAtClaim)?.Value; if (stamp is not null && long.TryParse(stamp, out var ticks) && DateTimeOffset.UtcNow - new DateTimeOffset(ticks, TimeSpan.Zero) < RevalidationInterval) return; // checked recently var auth = ctx.HttpContext.RequestServices.GetRequiredService(); var user = await auth.FindAsync(login); if (user is null || !RolesMatch(principal, user.Role)) { ctx.RejectPrincipal(); await ctx.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); return; } // Still valid — restamp so the next requests within the interval skip the store lookup. var identity = (ClaimsIdentity)principal.Identity!; var old = identity.FindFirst(RevalidatedAtClaim); if (old is not null) identity.RemoveClaim(old); identity.AddClaim(new Claim(RevalidatedAtClaim, DateTimeOffset.UtcNow.Ticks.ToString())); ctx.ReplacePrincipal(principal); ctx.ShouldRenew = true; } /// True when the principal's role claims equal the ladder expansion of . public static bool RolesMatch(ClaimsPrincipal principal, string? role) { var expected = ExpandRoles(role).ToHashSet(StringComparer.Ordinal); var actual = principal.FindAll(ClaimTypes.Role).Select(c => c.Value).ToHashSet(StringComparer.Ordinal); return expected.SetEquals(actual); } /// /// A log file name is safe only when it is a bare file name: no directory separators, no /// parent-directory segments, nothing that could escape the node's log directory. /// public static bool IsSafeLogFileName(string? filename) => !string.IsNullOrWhiteSpace(filename) && !filename.Contains("..", StringComparison.Ordinal) && filename.IndexOfAny(new[] { '/', '\\' }) < 0 && string.Equals(filename, Path.GetFileName(filename), StringComparison.Ordinal); /// /// Only a local, single-slash-rooted path is a safe post-login redirect target. Absolute URLs, /// protocol-relative (//host) and back-slash tricks (/\host) are rejected so a /// crafted returnUrl cannot bounce the user off-site. /// public static bool IsLocalUrl(string? url) => !string.IsNullOrEmpty(url) && url.StartsWith('/') && !url.StartsWith("//", StringComparison.Ordinal) && !url.StartsWith("/\\", StringComparison.Ordinal) // Reject control chars (tab/CR/LF/…): browsers strip them before parsing, so "/\t/evil.com" // collapses to "//evil.com" — a protocol-relative off-site redirect that slips past the checks // above (review: cookie-auth finding #2). && !ContainsControlChar(url); private static bool ContainsControlChar(string s) { foreach (var c in s) if (char.IsControl(c)) return true; return false; } /// /// Expands a dashboard role into the privilege ladder, so a policy that requires /// operator is satisfied by an admin too. Unknown/custom roles pass through by /// exact name only (an admin is not a custom release-bot). /// public static IEnumerable ExpandRoles(string? role) { if (string.IsNullOrWhiteSpace(role)) yield break; var r = role.Trim().ToLowerInvariant(); yield return r; if (r == "admin") { yield return "operator"; yield return "viewer"; } else if (r == "operator") { yield return "viewer"; } } } Path: redb-tsak/src/redb.Tsak.Web/Security/DashboardRevalidatingAuthenticationStateProvider.cs Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Security/DashboardRevalidatingAuthenticationStateProvider.cs ---- using Microsoft.AspNetCore.Components.Authorization; using Microsoft.AspNetCore.Components.Server; using redb.Tsak.Web.Pro; namespace redb.Tsak.Web.Security; /// /// Circuit-side half of session revalidation (review 2026-09-02, В14). The cookie's /// OnValidatePrincipal covers plain HTTP requests, but a live Blazor circuit fixes its /// AuthenticationState at connection time and never re-reads the cookie — so a deleted or /// demoted user would keep an open dashboard indefinitely. This provider re-resolves the /// account every and tears the circuit's /// auth state down when the account is gone or its role changed. /// public sealed class DashboardRevalidatingAuthenticationStateProvider : RevalidatingServerAuthenticationStateProvider { private readonly IServiceScopeFactory _scopeFactory; public DashboardRevalidatingAuthenticationStateProvider( ILoggerFactory loggerFactory, IServiceScopeFactory scopeFactory) : base(loggerFactory) { _scopeFactory = scopeFactory; } protected override TimeSpan RevalidationInterval => DashboardAuth.RevalidationInterval; protected override async Task ValidateAuthenticationStateAsync( AuthenticationState authenticationState, CancellationToken cancellationToken) { var principal = authenticationState.User; var login = principal.Identity?.Name; if (string.IsNullOrEmpty(login)) return false; // IAuthService is scoped; the revalidation timer runs outside any circuit scope. await using var scope = _scopeFactory.CreateAsyncScope(); var auth = scope.ServiceProvider.GetRequiredService(); var user = await auth.FindAsync(login); return user is not null && DashboardAuth.RolesMatch(principal, user.Role); } } Path: redb-tsak/src/redb.Tsak.Web/Security/LoginThrottle.cs Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Security/LoginThrottle.cs ---- using System.Collections.Concurrent; namespace redb.Tsak.Web.Security; /// /// Per-login failed-attempt throttle for the dashboard sign-in (review item 2.6). After /// failures within the window a login is locked out for /// , defeating online password guessing. A successful login clears the /// counter. Registered as a singleton so the state is shared across all requests on the node. /// Pure and clock-injectable so lockout timing is unit-testable without waiting. /// public sealed class LoginThrottle { private sealed class Entry { public int Failures; public DateTimeOffset WindowStart; public DateTimeOffset LockedUntil; } private readonly ConcurrentDictionary _entries = new(StringComparer.OrdinalIgnoreCase); private readonly Func _now; public int MaxAttempts { get; } public TimeSpan Window { get; } public TimeSpan LockoutDuration { get; } public LoginThrottle( int maxAttempts = 5, TimeSpan? window = null, TimeSpan? lockoutDuration = null, Func? now = null) { MaxAttempts = maxAttempts < 1 ? 1 : maxAttempts; Window = window ?? TimeSpan.FromMinutes(5); LockoutDuration = lockoutDuration ?? TimeSpan.FromMinutes(1); _now = now ?? (() => DateTimeOffset.UtcNow); } /// True when is currently locked out. public bool IsLockedOut(string key) { if (string.IsNullOrEmpty(key)) return false; if (!_entries.TryGetValue(key, out var e)) return false; lock (e) { return _now() < e.LockedUntil; } } /// /// Entries are only removed on a successful login for their exact key, and keys are /// attacker-chosen (usernames, IPs) — without a sweep the map grows without bound /// (review 2026-09-02, В15; mirrors FailedAttemptThrottle's threshold). /// private const int SweepThreshold = 10_000; /// /// Record a failed attempt; may transition the key into lockout. /// lets a caller use a wider budget for a coarser /// bucket (e.g. the per-IP spray bucket) on the same shared instance. /// public void RecordFailure(string key, int? maxAttemptsOverride = null) { if (string.IsNullOrEmpty(key)) return; var now = _now(); var maxAttempts = maxAttemptsOverride is > 0 ? maxAttemptsOverride.Value : MaxAttempts; if (_entries.Count > SweepThreshold) SweepExpired(now); // GetOrAdd hands back a single shared Entry; the read-modify-write below MUST be under the // entry lock. The previous AddOrUpdate mutated the entry in place and returned the same // reference, so ConcurrentDictionary did a no-op reference "update" with no serialization — // two concurrent failures both did a non-atomic Failures++ and one increment was lost, which // let concurrent guessing slip under the lockout threshold (review: cookie-auth finding #1). var entry = _entries.GetOrAdd(key, _ => new Entry { WindowStart = now }); lock (entry) { // Fresh window if the previous one elapsed (and we are not already locked). if (now >= entry.LockedUntil && now - entry.WindowStart > Window) { entry.Failures = 0; entry.WindowStart = now; } entry.Failures++; if (entry.Failures >= maxAttempts) { entry.LockedUntil = now + LockoutDuration; entry.Failures = 0; // reset so the next lockout needs a fresh burst entry.WindowStart = now + LockoutDuration; } } } /// Drop entries whose window and lockout both elapsed — they carry no state. private void SweepExpired(DateTimeOffset now) { foreach (var (key, e) in _entries) { bool expired; lock (e) { expired = now >= e.LockedUntil && now - e.WindowStart > Window; } if (expired) _entries.TryRemove(key, out _); } } /// Clear any failure/lockout state for after a successful login. public void RecordSuccess(string key) { if (string.IsNullOrEmpty(key)) return; _entries.TryRemove(key, out _); } } Path: redb-tsak/src/redb.Tsak.Web/Services/ConfigAuthService.cs Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Services/ConfigAuthService.cs ---- using System.Security.Cryptography; using System.Text; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using redb.Core.Security; using redb.Tsak.Web.Pro; namespace redb.Tsak.Web.Services; /// /// Standalone implementation of . /// Validates credentials against config (Tsak:Web:AdminLogin / Tsak:Web:AdminPassword). /// No database, no IUserProvider — pure config-driven. Stateless: the session is an auth cookie, not /// an in-memory flag. /// public sealed class ConfigAuthService : IAuthService { private readonly IConfiguration _configuration; private readonly ILogger _logger; private readonly IPasswordHasher _hasher = new BcryptPasswordHasher(); private bool _warnedPlaintext; public ConfigAuthService(IConfiguration configuration, ILogger logger) { _configuration = configuration; _logger = logger; } /// public Task ValidateAsync(string login, string password) { _logger.LogInformation("Login attempt for '{Login}' (config auth)", login); var adminLogin = _configuration["Tsak:Web:AdminLogin"]; var adminHash = _configuration["Tsak:Web:AdminPasswordHash"]; var adminPassword = _configuration["Tsak:Web:AdminPassword"]; if (string.IsNullOrEmpty(adminLogin) || (string.IsNullOrEmpty(adminHash) && string.IsNullOrEmpty(adminPassword))) { _logger.LogWarning("AdminLogin and AdminPasswordHash/AdminPassword not configured — login rejected"); return Task.FromResult(null); } var loginOk = string.Equals(login, adminLogin, StringComparison.OrdinalIgnoreCase); // Prefer a stored BCrypt hash (Tsak:Web:AdminPasswordHash). BCrypt verification is itself // constant-time and also accepts the core's legacy SHA256 hashes. Fall back to a plaintext // AdminPassword for back-compat, compared in constant time. (Plaintext in config is // discouraged — set AdminPasswordHash instead; see docs.) bool passwordOk; if (!string.IsNullOrEmpty(adminHash)) { passwordOk = _hasher.VerifyPassword(password, adminHash); } else { if (_warnedPlaintext is false) { _warnedPlaintext = true; _logger.LogWarning( "Tsak:Web:AdminPassword is stored in plaintext config. Prefer Tsak:Web:AdminPasswordHash " + "(a BCrypt hash) so the dashboard password is not recoverable from config."); } passwordOk = FixedTimeEquals(password, adminPassword!); } if (!loginOk || !passwordOk) { _logger.LogWarning("Login failed for '{Login}' — invalid credentials", login); return Task.FromResult(null); } _logger.LogInformation("Login succeeded: '{Login}' (config auth)", login); return Task.FromResult(new AuthUser(login, "Administrator", "admin")); } /// public Task FindAsync(string login) { // Standalone has exactly one account — the config admin. It "exists" as long as the // config still names it. var adminLogin = _configuration["Tsak:Web:AdminLogin"]; var configured = !string.IsNullOrEmpty(adminLogin) && (!string.IsNullOrEmpty(_configuration["Tsak:Web:AdminPasswordHash"]) || !string.IsNullOrEmpty(_configuration["Tsak:Web:AdminPassword"])); var found = configured && string.Equals(login, adminLogin, StringComparison.OrdinalIgnoreCase); return Task.FromResult(found ? new AuthUser(adminLogin!, "Administrator", "admin") : null); } /// Length-independent constant-time string comparison over UTF-8 bytes. private static bool FixedTimeEquals(string a, string b) { var ba = Encoding.UTF8.GetBytes(a); var bb = Encoding.UTF8.GetBytes(b); return CryptographicOperations.FixedTimeEquals( SHA256.HashData(ba), SHA256.HashData(bb)); } } Path: redb-tsak/src/redb.Tsak.Web/Services/IndexAdvice.cs Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Services/IndexAdvice.cs ---- using redb.Tsak.Contracts; namespace redb.Tsak.Web.Services; /// What the storage page says about one index, beyond the numbers the catalogs gave. public enum IndexAdviceKind { /// The counters say nothing has read it since they started counting. Unused, /// Another index keys on exactly the same columns. Duplicate, /// Its key columns are the leading part of another index, which can serve the same lookups. CoveredByWiderIndex } /// One remark about one index, with the index it is about and, where there is one, the other index. /// What kind of remark this is. /// Schema of the table; null on an engine without schemas. /// Table the index belongs to. /// The index the remark is about. /// The index that duplicates or covers it, when the remark is about a pair. /// The remark in words, as the page prints it. public sealed record IndexAdviceItem( IndexAdviceKind Kind, string? Schema, string Table, string Index, string? OtherIndex, string Detail); /// /// Reads a set of index statistics and points out what an operator could act on. Three rules only, and all /// three refuse to speak about an index the engine depends on. /// /// The refusal is the point. An index that holds a primary key, a uniqueness constraint or a foreign key — /// and every index of redb's own tables — reads zero because it enforces something, not because nobody needs /// it. Dropping one on that evidence breaks the database, so IsSystemCritical from the engine /// ends every rule before it starts. /// /// public static class IndexAdvice { /// /// Collects the remarks. is false when the engine keeps no usage /// counters (SQLite) or when nothing says since when they have been counting — then "nothing read it" is /// not a fact about the index, only about our ignorance, and no unused remark is made. /// public static IReadOnlyList Collect( IReadOnlyList? indexes, bool countersAreMeaningful) { if (indexes is null || indexes.Count == 0) return []; var items = new List(); if (countersAreMeaningful) items.AddRange(indexes.Where(IsUnused).Select(UnusedItem)); foreach (var group in indexes.GroupBy(i => (i.Schema ?? "", i.Table), TableKeyComparer)) { var ofTable = group.ToArray(); items.AddRange(Duplicates(ofTable)); items.AddRange(Covered(ofTable)); } return items; } private static readonly IEqualityComparer<(string Schema, string Table)> TableKeyComparer = EqualityComparer<(string Schema, string Table)>.Create( (a, b) => string.Equals(a.Schema, b.Schema, StringComparison.OrdinalIgnoreCase) && string.Equals(a.Table, b.Table, StringComparison.OrdinalIgnoreCase), k => HashCode.Combine(k.Schema.ToLowerInvariant(), k.Table.ToLowerInvariant())); /// /// An index nothing structural depends on. Uniqueness counts as structural even when the catalog reports /// it outside a constraint: such an index is a rule about the data, and its read counter says nothing /// about whether the rule is still wanted. /// private static bool IsAdvisable(RedbIndexInfo i) => !i.IsSystemCritical && !i.IsPrimaryKey && !i.IsUniqueConstraint && !i.BacksForeignKey && i.IsUnique != true; private static bool IsUnused(RedbIndexInfo i) => IsAdvisable(i) && (i.Seeks ?? 0) == 0 && (i.Scans ?? 0) == 0; private static IndexAdviceItem UnusedItem(RedbIndexInfo i) => new( IndexAdviceKind.Unused, i.Schema, i.Table, i.Name, null, "No read has touched this index in the window the counters cover."); private static IEnumerable Duplicates(IReadOnlyList ofTable) { foreach (var group in ofTable.GroupBy(Signature, StringComparer.OrdinalIgnoreCase)) { if (group.Count() < 2) continue; // The pair is reported on the advisable members only: when one of two identical indexes holds a // key, it is the other one that is spare. var names = group.Select(i => i.Name).ToArray(); foreach (var index in group.Where(IsAdvisable)) { var others = string.Join(", ", names.Where(n => n != index.Name)); yield return new IndexAdviceItem( IndexAdviceKind.Duplicate, index.Schema, index.Table, index.Name, others, $"Keys on the same columns as {others}."); } } } private static IEnumerable Covered(IReadOnlyList ofTable) { foreach (var index in ofTable.Where(IsAdvisable)) { if (index.Columns.Count == 0) continue; var wider = ofTable.FirstOrDefault(other => other.Name != index.Name && other.Columns.Count > index.Columns.Count && IsPrefix(index.Columns, other.Columns)); if (wider is not null) { yield return new IndexAdviceItem( IndexAdviceKind.CoveredByWiderIndex, index.Schema, index.Table, index.Name, wider.Name, $"Its columns are the leading part of {wider.Name}, which serves the same lookups."); } } } private static bool IsPrefix(IReadOnlyList shorter, IReadOnlyList longer) { for (var i = 0; i < shorter.Count; i++) { if (!string.Equals(shorter[i], longer[i], StringComparison.OrdinalIgnoreCase)) return false; } return true; } /// /// Key columns in order, then the carried columns as a set: two indexes are the same index when they key /// on the same columns in the same order and carry the same payload, and differ otherwise. /// private static string Signature(RedbIndexInfo i) => string.Join(",", i.Columns) + "|" + string.Join(",", i.IncludedColumns.OrderBy(c => c, StringComparer.OrdinalIgnoreCase)); } Path: redb-tsak/src/redb.Tsak.Web/Services/LogTail.cs Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Services/LogTail.cs ---- using redb.Tsak.Client; using redb.Tsak.Contracts; namespace redb.Tsak.Web.Services; /// A row of the log view: a log line, or a marker the dashboard puts between lines (a gap, a restart). /// The log line; null for a marker. /// The marker's text; null for a log line. public sealed record LogRow(LogEntry? Entry, string? Marker) { /// A log line. public static LogRow Line(LogEntry entry) => new(entry, null); /// A marker between lines. public static LogRow Note(string text) => new(null, text); } /// Where a tail reads a node's log buffer from; through . public interface ILogSource { /// The newest entries, newest first. Task RecentAsync(int limit, CancellationToken ct); /// Up to entries after , oldest first. Task AfterAsync(long afterId, int limit, CancellationToken ct); /// Up to entries before , newest first. Task BeforeAsync(long beforeId, int limit, CancellationToken ct); } /// The node API of one node as a . public sealed class ClientLogSource(TsakApiClient client) : ILogSource { /// public Task RecentAsync(int limit, CancellationToken ct) => client.GetLogsAsync(limit: limit, ct: ct); /// public Task AfterAsync(long afterId, int limit, CancellationToken ct) => client.GetLogsAsync(afterId: afterId, limit: limit, ct: ct); /// public Task BeforeAsync(long beforeId, int limit, CancellationToken ct) => client.GetLogsBeforeAsync(beforeId, limit: limit, ct: ct); } /// /// The log lines of one node that this browser tab has seen, kept while the tab is open (see /// ), so that coming back to the node's log page shows them at once and fetches only what /// is new. The node numbers its lines from 0 in each process and keeps the newest of them (2000 by default): /// /// the first visit reads the newest lines; "load older" pages back from the oldest one /// shown, at a time, as far as the node still has them; /// a return reads everything after the last line seen, in one go; lines the node dropped from its buffer in the /// meantime are shown as one "N lines skipped" marker; /// a restart of the node (its start time in the topology changed, or its newest line is older than the last one /// seen) starts the tail anew with a marker, since the new process numbers its lines from 0 again. /// /// public sealed class LogTail { /// Lines read on the first visit. public const int FirstPage = 200; /// Lines read per "load older". public const int OlderPage = 200; /// Lines read per request when catching up. public const int AfterPage = 500; /// Requests at most per catch-up: well past a node buffer of 2000 lines. public const int MaxCatchUpRounds = 20; /// Every how many empty polls the tail checks that the node did not restart. public const int RestartCheckEvery = 10; private readonly List _rows = new(); private readonly object _gate = new(); private int _emptyPolls; // One read of the node at a time: the poll, a refresh and "load older" may overlap, and each moves the ids. private readonly SemaphoreSlim _io = new(1, 1); /// Creates the tail of node , keeping at most rows. public LogTail(string nodeId, int capacity = 5000) { NodeId = nodeId; Capacity = capacity; } /// The node whose lines these are. public string NodeId { get; } /// Rows kept at most; the oldest go first, and "load older" brings them back. public int Capacity { get; } /// Whether the first page was read. public bool Loaded { get; private set; } /// Whether the node answered that it keeps no log buffer. public bool Unavailable { get; private set; } /// The node's start time when the tail was read, if the topology knows it. public DateTimeOffset? StartedAt { get; private set; } /// The id of the newest line held, -1 before any. public long LastId { get; private set; } = -1; /// The id of the oldest line held, null before any. public long? OldestId { get; private set; } /// Whether the node may still have lines older than the oldest one held. public bool HasOlder { get; private set; } /// The size of the node's buffer, as it last said. public int? BufferCapacity { get; private set; } /// The rows, oldest first (a copy). public IReadOnlyList Rows { get { lock (_gate) return _rows.ToArray(); } } /// Lines held, markers not counted. public int LineCount { get { lock (_gate) return _rows.Count(r => r.Entry is not null); } } /// /// Brings the tail up to date: the first page on the first visit, otherwise every line after the last one seen. /// is the node's start time from the topology (null when unknown); a change of it /// starts the tail anew. marks a periodic refresh, which checks for a restart only every /// empty answers; a return to the page checks at once. /// public async Task SyncAsync(ILogSource source, DateTimeOffset? startedAt, bool poll, CancellationToken ct) { await _io.WaitAsync(ct).ConfigureAwait(false); try { await SyncCoreAsync(source, startedAt, poll, ct).ConfigureAwait(false); } finally { _io.Release(); } } private async Task SyncCoreAsync(ILogSource source, DateTimeOffset? startedAt, bool poll, CancellationToken ct) { if (Loaded && startedAt is { } now && StartedAt is { } then && now != then) Restart($"The node restarted at {now:yyyy-MM-dd HH:mm:ss zzz}; the lines before are in its log files."); if (!Loaded) { await LoadFirstPageAsync(source, ct).ConfigureAwait(false); StartedAt = startedAt; return; } var any = false; for (var round = 0; round < MaxCatchUpRounds; round++) { var response = await source.AfterAsync(LastId, AfterPage, ct).ConfigureAwait(false); if (!Accept(response, out var entries)) return; if (entries.Length == 0) break; any = true; AppendNewer(entries); if (entries.Length < AfterPage) break; } if (any) { _emptyPolls = 0; return; } if (poll && ++_emptyPolls % RestartCheckEvery != 0) return; // Nothing after the last line seen: either nothing new, or a new process that numbers from 0 again. var newest = await source.RecentAsync(1, ct).ConfigureAwait(false); if (Accept(newest, out var top) && top.Length > 0 && top[0].Id < LastId) { Restart("The node restarted; the lines before are in its log files."); await LoadFirstPageAsync(source, ct).ConfigureAwait(false); StartedAt = startedAt; } } /// Reads the lines before the oldest one held and puts them on top. public async Task LoadOlderAsync(ILogSource source, CancellationToken ct) { await _io.WaitAsync(ct).ConfigureAwait(false); try { await LoadOlderCoreAsync(source, ct).ConfigureAwait(false); } finally { _io.Release(); } } private async Task LoadOlderCoreAsync(ILogSource source, CancellationToken ct) { if (!HasOlder || OldestId is not { } oldest) return; var response = await source.BeforeAsync(oldest, OlderPage, ct).ConfigureAwait(false); if (!Accept(response, out var newestFirst)) return; lock (_gate) { var older = newestFirst.Reverse().Select(LogRow.Line).ToList(); var at = _rows.FindIndex(r => r.Entry is not null); _rows.InsertRange(at < 0 ? _rows.Count : at, older); if (older.Count > 0) OldestId = older[0].Entry!.Id; HasOlder = newestFirst.Length == OlderPage && OldestId > 0; } } /// Empties the view; new lines keep coming, and "load older" brings the cleared ones back. public void Clear() { lock (_gate) { _rows.Clear(); OldestId = LastId + 1; HasOlder = LastId >= 0; } } private async Task LoadFirstPageAsync(ILogSource source, CancellationToken ct) { var response = await source.RecentAsync(FirstPage, ct).ConfigureAwait(false); if (!Accept(response, out var newestFirst)) return; lock (_gate) { _rows.AddRange(newestFirst.Reverse().Select(LogRow.Line)); if (newestFirst.Length > 0) { LastId = newestFirst[0].Id; OldestId = newestFirst[^1].Id; } HasOlder = newestFirst.Length == FirstPage && OldestId > 0; Loaded = true; } } private void AppendNewer(LogEntry[] oldestFirst) { lock (_gate) { var skipped = LastId >= 0 ? oldestFirst[0].Id - LastId - 1 : 0; if (skipped > 0) _rows.Add(LogRow.Note(skipped == 1 ? "1 line skipped: the node dropped it from its buffer before this page read it." : $"{skipped} lines skipped: the node dropped them from its buffer before this page read them.")); _rows.AddRange(oldestFirst.Select(LogRow.Line)); LastId = oldestFirst[^1].Id; OldestId ??= oldestFirst[0].Id; if (_rows.Count > Capacity) { _rows.RemoveRange(0, _rows.Count - Capacity); OldestId = _rows.FirstOrDefault(r => r.Entry is not null)?.Entry!.Id ?? LastId + 1; HasOlder = true; } } } private void Restart(string note) { lock (_gate) { _rows.Clear(); _rows.Add(LogRow.Note(note)); LastId = -1; OldestId = null; HasOlder = false; Loaded = false; _emptyPolls = 0; } } private bool Accept(LogsResponse? response, out LogEntry[] entries) { entries = response?.Entries ?? []; if (response is null) return false; Unavailable = !response.Available; if (response.BufferCapacity is { } cap) BufferCapacity = cap; return response.Available; } } /// /// The log tails of the nodes this browser tab has looked at, for as long as the tab is open (one per Blazor /// circuit). The most recently opened are kept; an older one is dropped and read anew. /// public sealed class LogTailCache { /// Nodes kept at most. public const int MaxNodes = 5; private readonly LinkedList _recent = new(); private readonly object _gate = new(); /// The tail of , made the most recent; a new one when it was not kept. public LogTail Get(string nodeId) { lock (_gate) { var node = _recent.First; while (node is not null && node.Value.NodeId != nodeId) node = node.Next; if (node is not null) _recent.Remove(node); else node = new LinkedListNode(new LogTail(nodeId)); _recent.AddFirst(node); while (_recent.Count > MaxNodes) _recent.RemoveLast(); return node.Value; } } /// The nodes kept, most recent first. public IReadOnlyList Nodes { get { lock (_gate) return _recent.Select(t => t.NodeId).ToArray(); } } } /// The log page's filter, applied to the rows the page holds: a level and a text; markers always pass. public static class LogFilter { /// /// The rows of (any case; empty for all) whose message, source or exception contains /// (any case; empty for all), and every marker. /// public static List Apply(IReadOnlyList rows, string? level, string? text) { var byLevel = !string.IsNullOrEmpty(level); var byText = !string.IsNullOrEmpty(text); if (!byLevel && !byText) return rows as List ?? [.. rows]; return rows.Where(r => r.Entry is not { } e || ((!byLevel || string.Equals(e.Level, level, StringComparison.OrdinalIgnoreCase)) && (!byText || e.Message.Contains(text!, StringComparison.OrdinalIgnoreCase) || (e.Source?.Contains(text!, StringComparison.OrdinalIgnoreCase) ?? false) || (e.Exception?.Contains(text!, StringComparison.OrdinalIgnoreCase) ?? false)))) .ToList(); } } Path: redb-tsak/src/redb.Tsak.Web/Services/LogTime.cs Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Services/LogTime.cs ---- using System.Globalization; namespace redb.Tsak.Web.Services; /// /// How the dashboard writes the time of a log line: the line's own timestamp in the node's time zone (the offset the /// worker logged it with), date included, so lines of different days are told apart. The tooltip form adds the offset, /// as the worker's log files write it. Invariant culture: some cultures replace the ':' separators. /// public static class LogTime { /// Column header of a log line's time. public const string Header = "Node time"; /// "2026-11-09 10:01:04.349", in the node's time zone. public static string Format(DateTimeOffset timestamp) => timestamp.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture); /// "2026-11-09 10:01:04.349 +01:00": the same moment with the node's UTC offset. public static string FormatWithOffset(DateTimeOffset timestamp) => timestamp.ToString("yyyy-MM-dd HH:mm:ss.fff zzz", CultureInfo.InvariantCulture); } Path: redb-tsak/src/redb.Tsak.Web/Services/LogValue.cs Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Services/LogValue.cs ---- namespace redb.Tsak.Web.Services; /// /// A value taken from the request (a node id in the page address) before it goes into a log line. The address is /// percent-decoded, so %0D%0A would arrive as a real line break and could start a forged log line; the line /// breaks are written escaped instead (\r, \n, and the Unicode line separators). /// public static class LogValue { /// The value with its line breaks escaped; an absent value is an empty text. /// /// Every value goes through the replacements, with no early return for a value without line breaks: a code scanner /// (CodeQL's log forging query) takes of a line break as the sanitizer /// and cannot see that a guard made the replacement unneeded, so a shortcut path reads as an unsanitized log entry. /// A replacement that finds nothing returns the same string without copying it. /// public static string Of(string? value) => value? .Replace("\r", "\\r") .Replace("\n", "\\n") .Replace("\u0085", "\\u0085") .Replace("\u2028", "\\u2028") .Replace("\u2029", "\\u2029") ?? string.Empty; } Path: redb-tsak/src/redb.Tsak.Web/Services/NodeAttention.cs Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Services/NodeAttention.cs ---- using redb.Tsak.Contracts; namespace redb.Tsak.Web.Services; /// /// One thing on a node an operator should look at, in the form the overview renders: a level that decides the /// badge, a headline, a detail line, and — when the thing is a route — where to go to act on it. /// /// "error" or "warning": the badge variant, and the sort key. /// Name of the icon shown next to the headline. /// What happened, in one line. /// The numbers or the message behind it. /// Context of the route this is about, when it is about a route. /// Route this is about, when it is about a route. public sealed record AttentionItem( string Level, string Icon, string Title, string Detail, string? ContextName = null, string? RouteId = null); /// /// Turns a node's dashboard snapshot into the list of things that need an operator. Kept out of the page so /// the rules can be tested: what counts as needing attention is the whole content of the overview, and an /// empty list is a real answer — the node is fine — not a missing one. /// public static class NodeAttention { /// The error level, first in the list and shown in the error colour. public const string Error = "error"; /// The warning level: worth knowing, not yet broken. public const string Warning = "warning"; /// /// Collects everything worth an operator's attention from one poll of a node. A null snapshot means the /// node was not reached at all, which the page reports by itself, so nothing is invented here. /// public static IReadOnlyList Collect(DashboardSnapshot? snapshot, IReadOnlyList? modules) { var items = new List(); if (snapshot is not null) { items.AddRange(snapshot.ActiveAlerts.Select(FromAlert)); items.AddRange(snapshot.ErrorProneRoutes.Select(FromErrors)); items.AddRange(snapshot.SheddingRoutes.Select(FromShedding)); items.AddRange(snapshot.RefusingRoutes.Select(FromRefusals)); var stopped = snapshot.TotalContexts - snapshot.RunningContexts; if (stopped > 0) { items.Add(new AttentionItem(Warning, "route", $"{stopped} of {snapshot.TotalContexts} contexts are stopped", "A stopped context runs none of its routes. The Contexts tab says which ones.")); } } if (modules is not null) items.AddRange(modules.Where(NeedsAttention).Select(FromModule)); // Errors before warnings, order inside a level as collected: alerts, then routes, then modules. return items.OrderBy(i => i.Level == Error ? 0 : 1).ToArray(); } /// A hung exchange is an error, a suspected one is a warning — that is the watchdog's own wording. private static AttentionItem FromAlert(WatchdogAlert alert) => new( alert.Level.Equals("Hung", StringComparison.OrdinalIgnoreCase) ? Error : Warning, "shield", $"Exchange {alert.Level.ToLowerInvariant()} in route '{alert.RouteId}'", $"{alert.ElapsedSeconds:F0}s in flight, exchange {alert.ExchangeId}, detected {alert.DetectedAt:HH:mm:ss}", alert.ContextName, alert.RouteId); private static AttentionItem FromErrors(RouteMetricsSummary route) => new( Error, "alert-triangle", $"Route '{route.RouteId}' reported {route.Errors} error{(route.Errors == 1 ? "" : "s")}", route.LastError is { Length: > 0 } last ? $"Last: {last}" : "No message was recorded with the last error.", route.ContextName, route.RouteId); /// /// Shedding is deliberately not an error: a route rejecting at its concurrency ceiling is working as /// configured and under-provisioned, and the answer is a limit or a node, not a bug hunt. /// private static AttentionItem FromShedding(RouteMetricsSummary route) => new( Warning, "activity", $"Route '{route.RouteId}' shed {route.Rejected} request{(route.Rejected == 1 ? "" : "s")}", "The route is at its admission limit: raise the limit or add nodes.", route.ContextName, route.RouteId); /// /// A refusal is the sender's fault, not the route's: a warning, with the reason of the last one, so the operator knows /// what to tell the partner (a signature that does not verify, an envelope that is not well formed, an agreement). /// private static AttentionItem FromRefusals(RouteMetricsSummary route) => new( Warning, "shield", $"Route '{route.RouteId}' refused {route.Refused} request{(route.Refused == 1 ? "" : "s")} from its callers", route.LastRefusal is { Length: > 0 } last ? $"Last: {last}" : "No reason was recorded with the last refusal.", route.ContextName, route.RouteId); private static bool NeedsAttention(ModuleInfo module) => !module.Status.Equals("Initialized", StringComparison.OrdinalIgnoreCase) && !module.Status.Equals("Loaded", StringComparison.OrdinalIgnoreCase); private static AttentionItem FromModule(ModuleInfo module) => new( module.Status.Equals("Error", StringComparison.OrdinalIgnoreCase) ? Error : Warning, "package", $"Module '{module.ModuleName}' is {module.Status}", module.CanInitialize ? "Its routes are not running. The Modules tab has the details." : "The module reports it cannot initialize on this node."); } Path: redb-tsak/src/redb.Tsak.Web/Services/NodePath.cs Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Services/NodePath.cs ---- namespace redb.Tsak.Web.Services; /// /// The node a dashboard address is about. Node pages live under node/{nodeId}/...; the node id is the segment /// after node/, and everything after it (sub-page, entity, query) belongs to that node's page. /// public static class NodePath { /// The node id of a base-relative path (node/w2/monitoring?range=60 gives w2), or null. public static string? NodeIdOf(string baseRelativePath) { ArgumentNullException.ThrowIfNull(baseRelativePath); var path = StripQueryAndFragment(baseRelativePath); if (!path.StartsWith("node/", StringComparison.OrdinalIgnoreCase)) return null; var rest = path[5..]; var slash = rest.IndexOf('/'); var id = slash >= 0 ? rest[..slash] : rest; return id.Length == 0 ? null : Uri.UnescapeDataString(id); } /// /// The same address on another node: the node segment is replaced, the sub-page, the entity segments, the query /// and the fragment are kept. A path that is not a node page goes to the target node's overview. /// public static string WithNode(string baseRelativePath, string nodeId) { ArgumentNullException.ThrowIfNull(baseRelativePath); ArgumentException.ThrowIfNullOrEmpty(nodeId); var escaped = Uri.EscapeDataString(nodeId); if (NodeIdOf(baseRelativePath) is null) return $"node/{escaped}"; var rest = baseRelativePath[5..]; var end = rest.IndexOfAny(['/', '?', '#']); var tail = end >= 0 ? rest[end..] : string.Empty; return $"node/{escaped}{tail}"; } private static string StripQueryAndFragment(string path) { var cut = path.IndexOfAny(['?', '#']); return cut >= 0 ? path[..cut] : path; } } Path: redb-tsak/src/redb.Tsak.Web/Services/NodeSwitch.cs Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Services/NodeSwitch.cs ---- using redb.Tsak.Contracts; namespace redb.Tsak.Web.Services; /// One node as the node switcher lists it. /// The node id, as in the address. /// The node's host name. /// The cluster group the node belongs to. /// Whether the node is up. /// Whether the node leads its group. /// The node's version. /// Whether the node takes no new work. /// The node's last heartbeat. public sealed record NodeSwitchEntry( string NodeId, string Hostname, string GroupName, bool IsAlive, bool IsLeader, string Version, bool Cordoned, DateTimeOffset LastHeartbeat); /// /// The nodes of the topology in the switcher's order (by group, then by node id), the filter, and the previous and /// next node of the same group for the [ and ] keys. /// public static class NodeSwitch { /// The topology's nodes, ordered by group then node id; a node leads when its group's leader is it. public static IReadOnlyList Entries(ClusterTopology? topology) { if (topology is null) return []; return topology.Nodes .Select(n => new NodeSwitchEntry( n.NodeId, n.Hostname, n.GroupName, n.IsAlive, topology.Leaders.TryGetValue(n.GroupName, out var leader) && leader.NodeId == n.NodeId, n.Version, n.Cordoned, n.LastHeartbeat)) .OrderBy(e => e.GroupName, StringComparer.OrdinalIgnoreCase) .ThenBy(e => e.NodeId, StringComparer.OrdinalIgnoreCase) .ToList(); } /// Whether the switcher is shown at all: only with more than one node. public static bool IsShown(IReadOnlyList entries) => entries.Count > 1; /// The entries whose node id or host name contains (any case); all for an empty filter. public static IReadOnlyList Filter(IReadOnlyList entries, string? filter) { if (string.IsNullOrWhiteSpace(filter)) return entries; var f = filter.Trim(); return entries .Where(e => e.NodeId.Contains(f, StringComparison.OrdinalIgnoreCase) || e.Hostname.Contains(f, StringComparison.OrdinalIgnoreCase)) .ToList(); } /// /// The node before ( = -1) or after (+1) in its group, wrapping /// around; null when the group has no other node or is not listed. /// public static string? Neighbour(IReadOnlyList entries, string? current, int step) { if (current is null) return null; var me = entries.FirstOrDefault(e => e.NodeId == current); if (me is null) return null; var group = entries.Where(e => string.Equals(e.GroupName, me.GroupName, StringComparison.OrdinalIgnoreCase)).ToList(); if (group.Count < 2) return null; var i = group.FindIndex(e => e.NodeId == current); return group[((i + step) % group.Count + group.Count) % group.Count].NodeId; } /// "3m ago", "2h ago", "4d ago": how long ago a down node was last heard of. public static string Ago(DateTimeOffset at, DateTimeOffset now) { var d = now - at; if (d < TimeSpan.FromMinutes(1)) return $"{Math.Max(0, (int)d.TotalSeconds)}s ago"; if (d < TimeSpan.FromHours(1)) return $"{(int)d.TotalMinutes}m ago"; if (d < TimeSpan.FromDays(1)) return $"{(int)d.TotalHours}h ago"; return $"{(int)d.TotalDays}d ago"; } } Path: redb-tsak/src/redb.Tsak.Web/Services/NodeTabs.cs Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Services/NodeTabs.cs ---- namespace redb.Tsak.Web.Services; /// /// The tabs of the node page, and the rule that turns the {Tab} route value into one of them. /// /// The sidebar links a node with no tab at all — node/{id} — so "no tab" has to mean the first tab. /// While it meant "keep whatever is open", clicking Overview in the sidebar from any other tab left that /// other tab on screen, and the operator had to pick Overview again in the tab strip (found live 2026-09-21). /// /// public static class NodeTabs { /// The tabs in the order the strip shows them. The first one is what a tab-less URL selects. public static readonly string[] All = ["Overview", "Contexts", "Scheduler", "Modules", "Monitoring", "Logs"]; /// The default tab: what node/{id} opens on. public static string Default => All[0]; /// /// The tab a route value selects: the one it names, or the default for no value and for a value that /// names no tab. /// public static string Resolve(string? tab) => All.FirstOrDefault(t => t.Equals(tab, StringComparison.OrdinalIgnoreCase)) ?? Default; } Path: redb-tsak/src/redb.Tsak.Web/Services/PollLoops.cs Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Services/PollLoops.cs ---- namespace redb.Tsak.Web.Services; /// /// Shared body of the pages' auto-refresh loops (review 2026-09-02, С18): one transient /// exception (a node timeout, a DB blip, a JS-interop disconnect) must not silently kill the /// fire-and-forget loop — the page would keep showing stale data under a live "Auto-refresh" /// label for the rest of the circuit. A failed tick is logged and dropped, and the next tick /// retries; only the loop's OWN cancellation ends it. /// /// Threading contract: tick runs on the thread pool, NOT on the Blazor dispatcher. A tick /// that touches component state or calls StateHasChanged (its own or a child's) must wrap its /// body in the component's InvokeAsync. /// /// public static class PollLoops { public static async Task RunAsync(PeriodicTimer timer, CancellationToken ct, ILogger log, Func tick) { try { while (await timer.WaitForNextTickAsync(ct).ConfigureAwait(false)) { try { await tick().ConfigureAwait(false); } catch (Exception) when (ct.IsCancellationRequested) { // The page is being disposed; whatever the in-flight tick threw is moot. break; } catch (Exception ex) { // Includes OperationCanceledException from a FOREIGN token: an HttpClient // timeout is a TaskCanceledException, and the old catch-and-break on any // cancellation turned one slow node response into auto-refresh dead for the // rest of the circuit. Warning, not Debug: a failed tick means stale data on // screen, and the silent catch that used to be here hid a Dashboard failure // on every tick for twelve days. log.LogWarning(ex, "Poll tick failed; the page keeps its last data and retries on the next tick"); } } } catch (OperationCanceledException) { /* disposed */ } } } Path: redb-tsak/src/redb.Tsak.Web/Services/QueryState.cs Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Services/QueryState.cs ---- using Microsoft.AspNetCore.Components; namespace redb.Tsak.Web.Services; /// /// A page's meaningful state (time range, filters, sub-tab) kept in the address query, so that it survives a reload, /// a shared link and a change of node through the switcher (which keeps the query). The address is replaced, not /// pushed: changing a filter does not add a step to the browser history. /// public static class QueryState { /// Writes under ; an empty value or the default removes the parameter. public static void Set(NavigationManager nav, string name, string? value, string? defaultValue = null) { ArgumentNullException.ThrowIfNull(nav); var keep = string.IsNullOrEmpty(value) || value == defaultValue ? null : value; var target = nav.GetUriWithQueryParameter(name, keep); if (target != nav.Uri) nav.NavigateTo(target, replace: true); } /// Writes several parameters at once (one address change); empty values remove theirs. public static void Set(NavigationManager nav, IReadOnlyDictionary values) { ArgumentNullException.ThrowIfNull(nav); var parameters = values.ToDictionary(kv => kv.Key, kv => (object?)(string.IsNullOrEmpty(kv.Value) ? null : kv.Value)); var target = nav.GetUriWithQueryParameters(parameters); if (target != nav.Uri) nav.NavigateTo(target, replace: true); } /// One of (any case, returned as listed), else . public static string OneOf(string? value, IReadOnlyList allowed, string fallback) => allowed.FirstOrDefault(a => string.Equals(a, value, StringComparison.OrdinalIgnoreCase)) ?? fallback; /// One of parsed from , else . public static int OneOf(string? value, IReadOnlyList allowed, int fallback) => int.TryParse(value, out var n) && allowed.Contains(n) ? n : fallback; } Path: redb-tsak/src/redb.Tsak.Web/Services/RouteActionHints.cs Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Services/RouteActionHints.cs ---- namespace redb.Tsak.Web.Services; /// /// What the route buttons do, in the words an operator needs before clicking. The force-stop button in the /// routes table carries an icon and no label at all, so without these the difference between stopping and /// force-stopping was visible only in the confirmation dialog — after the click. /// public static class RouteActionHints { /// Tooltip of the Start button. public const string Start = "Start the route: its consumer begins accepting exchanges again. The choice is remembered, so the route " + "stays started after the context restarts."; /// Tooltip of the Stop button. public const string Stop = "Stop the route: its consumer accepts no new exchanges, the ones in flight are allowed to finish. The " + "choice is remembered, so the route stays stopped after the context restarts."; /// Tooltip of the Force-stop button. public const string ForceStop = "Force-stop the route: the exchanges in flight are cancelled at once, not awaited. For a route that is " + "stuck; an exchange cancelled this way is not delivered."; } Path: redb-tsak/src/redb.Tsak.Web/Services/StandaloneClientProvider.cs Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Services/StandaloneClientProvider.cs ---- using System.Collections.Concurrent; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using redb.Tsak.Client; using redb.Tsak.Contracts; using redb.Tsak.Web.Pro; namespace redb.Tsak.Web.Services; /// /// Standalone implementation of . /// Reads node URLs from config (Tsak:Web:Nodes[] or Tsak:Web:StandaloneUrl fallback). /// No redb, no database — pure config-driven. /// public sealed class StandaloneClientProvider : INodeClientProvider { private readonly IConfiguration _configuration; private readonly ILogger _logger; private readonly ConcurrentDictionary _clients = new(); private readonly ConcurrentDictionary _controlClients = new(); private ClusterTopology? _topology; public StandaloneClientProvider( IConfiguration configuration, ILogger logger) { _configuration = configuration; _logger = logger; } /// public bool IsCluster => false; /// public ClusterTopology? Topology => _topology; /// public Task LoadTopologyAsync(bool forceRefresh = false) { if (_topology is not null) { // Refresh heartbeat so IsAlive stays true for standalone nodes (no real heartbeat mechanism) var now = DateTimeOffset.UtcNow; foreach (var node in _topology.Nodes) node.LastHeartbeat = now; return Task.FromResult(_topology); } var nodes = new List(); // Try Tsak:Web:Nodes[] array first var nodesSection = _configuration.GetSection("Tsak:Web:Nodes"); if (nodesSection.Exists()) { var children = nodesSection.GetChildren().ToList(); foreach (var child in children) { var id = child["Id"] ?? $"node-{children.IndexOf(child) + 1}"; var url = child["Url"]; if (string.IsNullOrEmpty(url)) continue; nodes.Add(new NodeInfo { NodeId = id, Hostname = id, ApiEndpoint = url, Status = NodeStatus.Online, LastHeartbeat = DateTimeOffset.UtcNow, StartedAt = DateTimeOffset.UtcNow }); } } // Fallback: Tsak:Web:StandaloneUrl (single node, backward compatibility) if (nodes.Count == 0) { var standaloneUrl = _configuration["Tsak:Web:StandaloneUrl"] ?? "http://localhost:9090"; nodes.Add(new NodeInfo { NodeId = "default", Hostname = "localhost", ApiEndpoint = standaloneUrl, Status = NodeStatus.Online, LastHeartbeat = DateTimeOffset.UtcNow, StartedAt = DateTimeOffset.UtcNow }); } _topology = new ClusterTopology { ClusterName = "standalone", Nodes = nodes, Groups = [], Assignments = [], Leader = null }; _logger.LogDebug("Standalone topology loaded: {NodeCount} node(s)", nodes.Count); return Task.FromResult(_topology); } /// public TsakApiClient? GetClient(string nodeId) => Resolve(nodeId, _clients, controlTimeout: false); /// public TsakApiClient? GetControlClient(string nodeId) => Resolve(nodeId, _controlClients, controlTimeout: true); private TsakApiClient? Resolve(string nodeId, ConcurrentDictionary cache, bool controlTimeout) { if (cache.TryGetValue(nodeId, out var client)) return client; if (_topology is null) { // Deep link on a fresh process: the config topology is cheap — build it now instead // of returning a dead page until another page happens to load it (review 2026-09-02, С26). LoadTopologyAsync().GetAwaiter().GetResult(); } var node = _topology?.Nodes.FirstOrDefault(n => n.NodeId == nodeId); if (node is null || string.IsNullOrEmpty(node.ApiEndpoint)) { _logger.LogWarning("GetClient({NodeId}): node not found in standalone config", LogValue.Of(nodeId)); return null; } // Check for per-node ApiKey in config var nodesSection = _configuration.GetSection("Tsak:Web:Nodes"); string? apiKey = null; if (nodesSection.Exists()) { foreach (var child in nodesSection.GetChildren()) { if (child["Id"] == nodeId || child["Url"] == node.ApiEndpoint) { apiKey = child["ApiKey"]; break; } } } // GetOrAdd so a racing second resolve never leaks the losing client's sockets // (review 2026-09-02, С26). Control clients get the patient timeout (С12). var timeout = controlTimeout ? TimeSpan.FromSeconds(_configuration.GetValue("Tsak:Web:ControlTimeoutSeconds", 60)) : (TimeSpan?)null; return cache.GetOrAdd(nodeId, _ => new TsakApiClient(node.ApiEndpoint, apiKey, timeout)); } /// public Task RemoveNodeAsync(string nodeId) => Task.FromResult(false); public Task SetCordonedAsync(string nodeId, bool cordoned) => Task.FromResult(false); public void Dispose() { foreach (var cache in new[] { _clients, _controlClients }) { foreach (var client in cache.Values) client.Dispose(); cache.Clear(); } } } Path: redb-tsak/src/redb.Tsak.Web/Services/StorageInstanceGrouping.cs Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Services/StorageInstanceGrouping.cs ---- using redb.Tsak.Contracts; namespace redb.Tsak.Web.Services; /// One database, and every instance declaration that points at it. /// Identity of the group, used as the value of the picker. /// The database as the page names it. /// The title plus how many contexts declare it, for the picker. /// The declaration the page queries through. /// Every declaration pointing at this database. public sealed record StorageInstanceGroup( string Key, string Title, string Label, RedbInstanceInfo Primary, IReadOnlyList Members); /// /// Turns the instances a node reports into the databases they actually are. /// /// Contexts declare instances, not databases. Identity alone declares the same three databases in five of its /// contexts, which listed one per row is fifteen near-identical lines to choose from. They are grouped by the /// fingerprint the node computes over the connection string — never by name, because two contexts may use one /// name for different databases, and merging those would point the page's analyze button at the wrong one. /// /// public static class StorageInstanceGrouping { /// Groups the instances; the host's own storage comes first, the rest by name. public static IReadOnlyList Group(IReadOnlyList? instances) { if (instances is null || instances.Count == 0) return []; return instances // Without a fingerprint — a declaration whose connection string the node could not read — the // instance stands alone rather than being merged with anything on a guess. .GroupBy(i => string.IsNullOrEmpty(i.Fingerprint) ? $"?{i.ContextName}/{i.Name}" : i.Fingerprint) .Select(g => { var members = g.ToArray(); // The host's own storage speaks for its group; otherwise an active declaration, since a // non-active one is the copy that was registered without ever being connected. var primary = members.FirstOrDefault(m => m.ContextName is null) ?? members.FirstOrDefault(m => m.IsActive) ?? members[0]; var title = TitleOf(primary, members); var label = members.Length > 1 ? $"{title} — {members.Length} contexts" : title; return new StorageInstanceGroup(g.Key, title, label, primary, members); }) .OrderBy(g => g.Primary.ContextName is null ? 0 : 1) .ThenBy(g => g.Title, StringComparer.OrdinalIgnoreCase) .ToArray(); } /// /// What to call the database. The host's own storage is "this node"; a declared one is its name, and the /// names of all its declarations when contexts named the same database differently. /// private static string TitleOf(RedbInstanceInfo primary, IReadOnlyList members) { if (primary.ContextName is null) return "this node"; var names = members .Select(m => m.Name) .Distinct(StringComparer.OrdinalIgnoreCase) .OrderBy(n => n, StringComparer.OrdinalIgnoreCase) .ToArray(); return names.Length == 1 ? names[0] : string.Join(" / ", names); } } Path: redb-tsak/src/redb.Tsak.Web/Services/ToastService.cs Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/Services/ToastService.cs ---- namespace redb.Tsak.Web.Services; public sealed class ToastService { public event Action? OnShow; public void Show(string message, string level = "info", int durationMs = 4000) => OnShow?.Invoke(message, level, durationMs); public void Success(string message) => Show(message, "success"); public void Error(string message) => Show(message, "error", 8000); public void Warning(string message) => Show(message, "warning", 6000); } Path: redb-tsak/src/redb.Tsak.Web/appsettings.json Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/appsettings.json ---- { "Kestrel": { "Endpoints": { "Http": { "Url": "http://localhost:5180" }, "Https": { "Url": "https://localhost:5181" } } }, "ConnectionStrings": { "Postgres": "Host=localhost;Port=5432;Username=postgres;Password=;Database=redb;Pooling=true;Include Error Detail=true", "MSSql": "Server=localhost;Database=redb;User Id=sa;Password=;TrustServerCertificate=true", "//Sqlite": "A relative path resolves against the working directory; in cluster mode use the worker's database file.", "Sqlite": "Data Source=../../redb.db" }, "Tsak": { "Redb": { "//Provider": "postgres | mssql | sqlite — Sqlite uses ConnectionStrings:Sqlite (Data Source=…db)", "Provider": "sqlite", "UsePro": true, "//PropsSaveStrategy": "Free supports DeleteInsert only; ChangeTracking requires Pro", "PropsSaveStrategy": "DeleteInsert" }, "Web": { "AdminLogin": "admin", "AdminPassword": "admin", // === STANDALONE === // "Mode": "standalone", // "Nodes": [ // { "Id": "local", "Url": "http://localhost:9090", "ApiKey": "" } // ] // === CLUSTER (active) === "Mode": "cluster", "ServiceApiKey": "" } }, "Serilog": { "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ], "MinimumLevel": { "Default": "Information", "Override": { "Microsoft": "Warning", "Microsoft.AspNetCore": "Warning", "redb.Tsak.Web": "Debug" } }, "WriteTo": [ { "Name": "Console", "Args": { "outputTemplate": "{Timestamp:HH:mm:ss.fff} [{Level:u3}] {Message:lj}{NewLine}{Exception}" } }, { "Name": "File", "Args": { "path": "Logs/web-.txt", "rollingInterval": "Day", "retainedFileCountLimit": 7, "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level:u3}] {Message:lj}{NewLine}{Exception}" } } ], "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ] } } Path: redb-tsak/src/redb.Tsak.Web/redb.Tsak.Web.csproj Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/redb.Tsak.Web.csproj ---- net10.0 redb.Tsak.Web Path: redb-tsak/src/redb.Tsak.Web/wwwroot/css/app.css Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/wwwroot/css/app.css ---- /* ============================================================ redb.Tsak.Web — Design Tokens & Theme System CSS custom properties for consistent theming across all components. ============================================================ */ /* --- Light Theme (default) --- */ :root { /* Typography */ --font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; --font-mono: 'Cascadia Code', 'Fira Code', 'JetBrains Mono', Consolas, monospace; --font-size-xs: 0.75rem; --font-size-sm: 0.8125rem; --font-size-base: 0.875rem; --font-size-lg: 1rem; --font-size-xl: 1.25rem; --font-size-2xl: 1.5rem; --font-size-3xl: 2rem; --line-height: 1.5; /* Spacing */ --space-1: 0.25rem; --space-2: 0.5rem; --space-3: 0.75rem; --space-4: 1rem; --space-5: 1.25rem; --space-6: 1.5rem; --space-8: 2rem; --space-10: 2.5rem; --space-12: 3rem; /* Border radius */ --radius-sm: 4px; --radius-md: 6px; --radius-lg: 8px; --radius-xl: 12px; --radius-full: 9999px; /* Shadows */ --shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.05); --shadow-md: 0 4px 6px rgba(0, 0, 0, 0.07); --shadow-lg: 0 10px 15px rgba(0, 0, 0, 0.1); /* Transitions */ --transition-fast: 150ms ease; --transition-base: 200ms ease; --transition-slow: 300ms ease; /* Layout */ --sidebar-width: 240px; --sidebar-collapsed-width: 60px; --topbar-height: 52px; /* --- Color Palette: Light --- */ --bg-app: #f1f5f9; --bg-surface: #ffffff; --bg-surface-hover: #f8fafc; --bg-surface-active: #f1f5f9; --bg-inset: #f8fafc; --text-primary: #0f172a; --text-secondary: #475569; --text-tertiary: #94a3b8; --text-inverse: #ffffff; --border-default: #e2e8f0; --border-strong: #cbd5e1; --accent: #3b82f6; --accent-hover: #2563eb; --accent-light: #dbeafe; --accent-text: #1e40af; /* Sidebar */ --sidebar-bg: #ffffff; --sidebar-text: #64748b; --sidebar-text-hover: #334155; --sidebar-text-active: #0f172a; --sidebar-active-bg: rgba(59, 130, 246, 0.08); --sidebar-active-border: #3b82f6; --sidebar-divider: #e2e8f0; --sidebar-group-text: #94a3b8; --sidebar-brand-text: #0f172a; /* Status */ --status-online: #22c55e; --status-online-bg: #f0fdf4; --status-warning: #f59e0b; --status-warning-bg: #fffbeb; --status-error: #ef4444; --status-error-bg: #fef2f2; --status-info: #3b82f6; --status-info-bg: #eff6ff; --status-offline: #94a3b8; --status-offline-bg: #f1f5f9; /* Interactive */ --btn-primary-bg: #3b82f6; --btn-primary-hover: #2563eb; --btn-primary-text: #ffffff; --btn-secondary-bg: #f1f5f9; --btn-secondary-hover: #e2e8f0; --btn-secondary-text: #334155; --btn-danger-bg: #ef4444; --btn-danger-hover: #dc2626; --btn-danger-text: #ffffff; --btn-ghost-hover: #f1f5f9; --input-bg: #ffffff; --input-border: #cbd5e1; --input-focus-border: #3b82f6; --input-focus-ring: rgba(59, 130, 246, 0.25); /* Scrollbar */ --scrollbar-track: transparent; --scrollbar-thumb: #cbd5e1; --scrollbar-thumb-hover: #94a3b8; } /* --- Dark Theme --- */ [data-theme="dark"] { --bg-app: #0c1222; --bg-surface: #1e293b; --bg-surface-hover: #263548; --bg-surface-active: #334155; --bg-inset: #0f172a; --text-primary: #e2e8f0; --text-secondary: #94a3b8; --text-tertiary: #64748b; --text-inverse: #0f172a; --border-default: #334155; --border-strong: #475569; --accent: #60a5fa; --accent-hover: #3b82f6; --accent-light: rgba(96, 165, 250, 0.15); --accent-text: #93c5fd; --sidebar-bg: #0a0f1a; --sidebar-text: #94a3b8; --sidebar-text-hover: #e2e8f0; --sidebar-text-active: #ffffff; --sidebar-active-bg: rgba(59, 130, 246, 0.15); --sidebar-active-border: #3b82f6; --sidebar-divider: #1e293b; --sidebar-group-text: #64748b; --sidebar-brand-text: #f1f5f9; --shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.3); --shadow-md: 0 4px 6px rgba(0, 0, 0, 0.4); --shadow-lg: 0 10px 15px rgba(0, 0, 0, 0.5); --status-online-bg: rgba(34, 197, 94, 0.15); --status-warning-bg: rgba(245, 158, 11, 0.15); --status-error-bg: rgba(239, 68, 68, 0.15); --status-info-bg: rgba(59, 130, 246, 0.15); --status-offline-bg: rgba(148, 163, 184, 0.1); --btn-secondary-bg: #334155; --btn-secondary-hover: #475569; --btn-secondary-text: #e2e8f0; --btn-ghost-hover: #334155; --input-bg: #0f172a; --input-border: #475569; --scrollbar-thumb: #475569; --scrollbar-thumb-hover: #64748b; } /* ============================================================ Base Styles ============================================================ */ *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; } html, body { height: 100%; font-family: var(--font-family); font-size: var(--font-size-base); line-height: var(--line-height); color: var(--text-primary); background: var(--bg-app); -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } /* Scrollbar styling */ ::-webkit-scrollbar { width: 6px; height: 6px; } ::-webkit-scrollbar-track { background: var(--scrollbar-track); } ::-webkit-scrollbar-thumb { background: var(--scrollbar-thumb); border-radius: var(--radius-full); } ::-webkit-scrollbar-thumb:hover { background: var(--scrollbar-thumb-hover); } /* Focus */ :focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } /* Links */ a { color: var(--accent); text-decoration: none; } a:hover { color: var(--accent-hover); } /* Code */ code, pre { font-family: var(--font-mono); font-size: var(--font-size-sm); } code { background: var(--bg-inset); padding: 0.125em 0.375em; border-radius: var(--radius-sm); color: var(--accent-text); } pre { background: var(--bg-inset); padding: var(--space-4); border-radius: var(--radius-md); overflow-x: auto; border: 1px solid var(--border-default); } /* Tables base */ table { width: 100%; border-collapse: collapse; } th { text-align: left; font-weight: 600; font-size: var(--font-size-xs); text-transform: uppercase; letter-spacing: 0.05em; color: var(--text-secondary); padding: var(--space-3) var(--space-4); border-bottom: 2px solid var(--border-default); } /* A column header that sorts its table when clicked */ th.grid-sortable { cursor: pointer; user-select: none; } th.grid-sortable:hover { color: var(--text-primary); } td { padding: var(--space-3) var(--space-4); border-bottom: 1px solid var(--border-default); vertical-align: middle; } tr:hover td { background: var(--bg-surface-hover); } /* ============================================================ Utility Classes ============================================================ */ .text-xs { font-size: var(--font-size-xs); } .text-sm { font-size: var(--font-size-sm); } .text-base { font-size: var(--font-size-base); } .text-lg { font-size: var(--font-size-lg); } .text-xl { font-size: var(--font-size-xl); } .text-2xl { font-size: var(--font-size-2xl); } .text-3xl { font-size: var(--font-size-3xl); } .text-secondary { color: var(--text-secondary); } .text-tertiary { color: var(--text-tertiary); } .font-medium { font-weight: 500; } .font-semibold { font-weight: 600; } .font-bold { font-weight: 700; } .mono { font-family: var(--font-mono); } /* Status badges */ .badge { display: inline-flex; align-items: center; gap: var(--space-1); padding: 0.125rem 0.5rem; border-radius: var(--radius-full); font-size: var(--font-size-xs); font-weight: 600; line-height: 1.5; } .badge-online { background: var(--status-online-bg); color: var(--status-online); } .badge-warning { background: var(--status-warning-bg); color: var(--status-warning); } .badge-error { background: var(--status-error-bg); color: var(--status-error); } .badge-info { background: var(--status-info-bg); color: var(--status-info); } .badge-offline { background: var(--status-offline-bg); color: var(--status-offline); } .badge-dot { width: 6px; height: 6px; border-radius: 50%; background: currentColor; } /* Buttons */ .btn { display: inline-flex; align-items: center; justify-content: center; gap: var(--space-2); padding: var(--space-2) var(--space-4); border: none; border-radius: var(--radius-md); font-family: var(--font-family); font-size: var(--font-size-sm); font-weight: 500; cursor: pointer; transition: all var(--transition-fast); line-height: 1.5; white-space: nowrap; } .btn:disabled { opacity: 0.5; cursor: not-allowed; } .btn-primary { background: var(--btn-primary-bg); color: var(--btn-primary-text); } .btn-primary:hover:not(:disabled) { background: var(--btn-primary-hover); } .btn-secondary { background: var(--btn-secondary-bg); color: var(--btn-secondary-text); } .btn-secondary:hover:not(:disabled) { background: var(--btn-secondary-hover); } .btn-danger { background: var(--btn-danger-bg); color: var(--btn-danger-text); } .btn-danger:hover:not(:disabled) { background: var(--btn-danger-hover); } .btn-ghost { background: transparent; color: var(--text-secondary); } .btn-ghost:hover:not(:disabled) { background: var(--btn-ghost-hover); color: var(--text-primary); } .btn-sm { padding: var(--space-1) var(--space-3); font-size: var(--font-size-xs); } .btn-icon { padding: var(--space-2); width: 36px; height: 36px; } .btn-group { display: inline-flex; gap: 1px; } .btn-group .btn { border-radius: 0; } .btn-group .btn:first-child { border-radius: var(--radius-md) 0 0 var(--radius-md); } .btn-group .btn:last-child { border-radius: 0 var(--radius-md) var(--radius-md) 0; } /* Cards */ .card { background: var(--bg-surface); border: 1px solid var(--border-default); border-radius: var(--radius-lg); padding: var(--space-3) var(--space-4); box-shadow: var(--shadow-sm); } .card-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: var(--space-2); } .card-title { font-size: var(--font-size-sm); font-weight: 600; color: var(--text-secondary); text-transform: uppercase; letter-spacing: 0.05em; } .card-value { font-size: var(--font-size-xl); font-weight: 700; color: var(--text-primary); font-variant-numeric: tabular-nums; } /* Monitoring charts layout — JS sets height via fitToViewport */ .monitoring-charts { display: flex; flex-direction: column; gap: var(--space-4); overflow: hidden; } /* Chart cards */ .card-chart { overflow: hidden; padding: var(--space-2) var(--space-3); display: flex; flex-direction: column; min-height: 0; } .card-chart .card-header { margin-bottom: var(--space-1); flex-shrink: 0; } .chart-body { flex: 1; min-height: 0; overflow: hidden; padding: 0 var(--space-2) var(--space-2); } .chart-container { position: relative; width: 100%; height: 100%; } .chart-container canvas { position: absolute; top: 0; left: 0; } .grid-charts { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); grid-template-rows: 1fr; gap: var(--space-4); flex: 1 1 0; min-height: 0; overflow: hidden; } @media (max-width: 768px) { .grid-charts { grid-template-columns: 1fr; } } /* Inputs */ .input { width: 100%; padding: var(--space-2) var(--space-3); background: var(--input-bg); border: 1px solid var(--input-border); border-radius: var(--radius-md); font-family: var(--font-family); font-size: var(--font-size-base); color: var(--text-primary); transition: border-color var(--transition-fast), box-shadow var(--transition-fast); line-height: 1.5; } .input:focus { border-color: var(--input-focus-border); box-shadow: 0 0 0 3px var(--input-focus-ring); outline: none; } .input::placeholder { color: var(--text-tertiary); } /* Page layout helpers */ .page-header { margin-bottom: var(--space-6); } .page-title { font-size: var(--font-size-xl); font-weight: 700; color: var(--text-primary); } .page-description { font-size: var(--font-size-sm); color: var(--text-secondary); margin-top: var(--space-1); } .grid-stats { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: var(--space-3); margin-bottom: var(--space-4); } /* Spinner */ .spinner { display: inline-block; width: 20px; height: 20px; border: 2px solid var(--border-default); border-top-color: var(--accent); border-radius: 50%; animation: spin 0.6s linear infinite; } .spinner-lg { width: 32px; height: 32px; border-width: 3px; } @keyframes spin { to { transform: rotate(360deg); } } /* Empty state */ .empty-state { display: flex; flex-direction: column; align-items: center; justify-content: center; padding: var(--space-12) var(--space-8); color: var(--text-tertiary); text-align: center; } .empty-state svg { width: 48px; height: 48px; margin-bottom: var(--space-4); opacity: 0.5; } /* One line of the node overview's "needs attention" list */ .attention-row { display: flex; align-items: flex-start; gap: var(--space-3); padding: var(--space-3) 0; border-bottom: 1px solid var(--border); } .attention-row:last-child { border-bottom: none; } /* Toast container */ .toast-container { position: fixed; top: var(--space-4); right: var(--space-4); z-index: 9999; display: flex; flex-direction: column; gap: var(--space-2); } /* ============================================================ Shell Layout ============================================================ */ .shell { display: flex; height: 100vh; overflow: hidden; } .shell-main { flex: 1; display: flex; flex-direction: column; min-width: 0; } .shell-content { flex: 1; overflow-y: auto; padding: var(--space-6); } /* The keyed wrapper of the page (TsakShell): no box of its own. */ .shell-page { display: contents; } /* ============================================================ Sidebar ============================================================ */ .sidebar { width: var(--sidebar-width); height: 100vh; background: var(--sidebar-bg); display: flex; flex-direction: column; flex-shrink: 0; overflow-y: auto; border-right: 1px solid var(--sidebar-divider); } .sidebar-brand { display: flex; align-items: center; gap: var(--space-3); padding: var(--space-4) var(--space-5); height: var(--topbar-height); color: var(--sidebar-brand-text); border-bottom: 1px solid var(--sidebar-divider); flex-shrink: 0; } .sidebar-brand-text { font-size: var(--font-size-lg); font-weight: 700; letter-spacing: -0.02em; } .sidebar-version { margin-left: auto; font-size: var(--font-size-xs); color: var(--sidebar-brand-text); opacity: 0.55; text-decoration: none; } .sidebar-version:hover { opacity: 1; } .sidebar-nav { flex: 1; padding: var(--space-3) 0; } .sidebar-group { padding: var(--space-2) 0; } .sidebar-group-label { display: block; font-size: var(--font-size-xs); font-weight: 600; text-transform: uppercase; letter-spacing: 0.08em; color: var(--sidebar-group-text); padding: var(--space-2) var(--space-5) var(--space-1); } .sidebar-link { display: flex; align-items: center; gap: var(--space-3); padding: var(--space-2) var(--space-5); color: var(--sidebar-text); font-size: var(--font-size-sm); font-weight: 500; text-decoration: none; transition: all var(--transition-fast); border-left: 3px solid transparent; margin: 1px 0; } .sidebar-link:hover { color: var(--sidebar-text-hover); background: rgba(255, 255, 255, 0.04); } .sidebar-link.active { color: var(--sidebar-text-active); background: var(--sidebar-active-bg); border-left-color: var(--sidebar-active-border); } .sidebar-link svg { flex-shrink: 0; opacity: 0.7; } .sidebar-link.active svg { opacity: 1; } /* ============================================================ Top Bar ============================================================ */ .topbar { display: flex; align-items: center; justify-content: space-between; height: var(--topbar-height); padding: 0 var(--space-6); background: var(--bg-surface); border-bottom: 1px solid var(--border-default); flex-shrink: 0; } .topbar-left { display: flex; align-items: center; gap: var(--space-4); } .topbar-title { font-size: var(--font-size-lg); font-weight: 600; color: var(--text-primary); } .topbar-right { display: flex; align-items: center; gap: var(--space-3); } .topbar-cluster { display: flex; align-items: center; gap: var(--space-2); font-size: var(--font-size-sm); color: var(--text-secondary); padding-right: var(--space-3); border-right: 1px solid var(--border-default); } /* ============================================================ Login / Auth ============================================================ */ .login-backdrop { display: flex; align-items: center; justify-content: center; min-height: 100vh; background: var(--bg-app); } .login-card { width: 400px; padding: 40px; background: var(--bg-surface); border: 1px solid var(--border-default); border-radius: var(--radius-lg); box-shadow: var(--shadow-lg); } .login-brand { display: flex; align-items: center; gap: 10px; margin-bottom: 32px; } .login-brand svg { color: var(--accent); } .login-brand-name { font-size: 20px; font-weight: 600; color: var(--text-primary); } .login-title { font-size: 22px; font-weight: 600; margin: 0 0 6px 0; color: var(--text-primary); } .login-subtitle { color: var(--text-secondary); margin-bottom: 24px; font-size: var(--font-size-sm); } .login-error { display: flex; align-items: center; gap: var(--space-2); padding: var(--space-3); margin-bottom: 20px; background: var(--status-error-bg); color: var(--status-error); border-radius: var(--radius-md); font-size: var(--font-size-sm); } /* Floating label field */ .float-field { position: relative; margin-bottom: 20px; } .float-field input { width: 100%; padding: 12px; border: 1px solid var(--input-border); border-radius: var(--radius-md); font-size: var(--font-size-base); font-family: var(--font-family); background: var(--input-bg); color: var(--text-primary); outline: none; box-sizing: border-box; transition: border-color var(--transition-fast), box-shadow var(--transition-fast); } .float-field label { position: absolute; left: 10px; top: 50%; transform: translateY(-50%); font-size: var(--font-size-base); color: var(--text-tertiary); background: var(--input-bg); padding: 0 4px; border-radius: var(--radius-sm); transition: all 0.15s ease; pointer-events: none; } .float-field input:focus + label, .float-field input:not(:placeholder-shown) + label { top: 0; transform: translateY(-50%); font-size: var(--font-size-xs); color: var(--accent); } .float-field input:focus { border-color: var(--input-focus-border); box-shadow: 0 0 0 3px var(--input-focus-ring); } .login-actions { margin-top: 24px; } .login-btn { width: 100%; padding: 12px; font-size: var(--font-size-base); } /* ============================================================ Toast Notifications ============================================================ */ .toast { display: flex; align-items: center; gap: var(--space-2); padding: var(--space-3) var(--space-4); border-radius: var(--radius-md); font-size: var(--font-size-sm); background: var(--bg-surface); border: 1px solid var(--border-default); box-shadow: var(--shadow-md); min-width: 280px; max-width: 420px; animation: toast-in 0.2s ease; } @keyframes toast-in { from { opacity: 0; transform: translateX(20px); } to { opacity: 1; transform: translateX(0); } } .toast-success { border-left: 3px solid var(--status-online); } .toast-error { border-left: 3px solid var(--status-error); } .toast-warning { border-left: 3px solid var(--status-warning); } .toast-info { border-left: 3px solid var(--status-info); } .toast-success svg { color: var(--status-online); } .toast-error svg { color: var(--status-error); } .toast-warning svg { color: var(--status-warning); } .toast-info svg { color: var(--status-info); } .toast-close { margin-left: auto; background: none; border: none; color: var(--text-tertiary); cursor: pointer; padding: 2px; border-radius: var(--radius-sm); display: flex; } .toast-close:hover { color: var(--text-primary); background: var(--bg-surface-hover); } /* ============================================================ Confirm Dialog ============================================================ */ .confirm-overlay { position: fixed; inset: 0; background: rgba(0, 0, 0, 0.5); display: flex; align-items: center; justify-content: center; z-index: 10000; animation: fade-in 0.15s ease; } @keyframes fade-in { from { opacity: 0; } to { opacity: 1; } } .confirm-dialog { background: var(--bg-surface); border: 1px solid var(--border-default); border-radius: var(--radius-lg); padding: var(--space-6); box-shadow: var(--shadow-lg); max-width: 400px; width: 90%; } .confirm-header { display: flex; align-items: center; gap: var(--space-2); margin-bottom: var(--space-3); color: var(--status-warning); } .confirm-message { color: var(--text-secondary); font-size: var(--font-size-sm); margin-bottom: var(--space-5); line-height: 1.5; } .confirm-actions { display: flex; justify-content: flex-end; gap: var(--space-2); } /* ============================================================ Grid ============================================================ */ .grid-row-clickable { cursor: pointer; } .grid-row-clickable:hover { background: var(--bg-surface-hover); } .grid-pager { display: flex; align-items: center; justify-content: center; gap: var(--space-3); padding: var(--space-3) 0; margin-top: var(--space-2); } /* ============================================================ Tabs ============================================================ */ .tabs { display: flex; gap: 0; border-bottom: 2px solid var(--border-default); margin-bottom: var(--space-4); } .tab { padding: var(--space-2) var(--space-4); font-size: var(--font-size-sm); font-weight: 500; color: var(--text-secondary); background: none; border: none; border-bottom: 2px solid transparent; margin-bottom: -2px; cursor: pointer; transition: all var(--transition-fast); } .tab:hover { color: var(--text-primary); background: var(--bg-surface-hover); } .tab-active { color: var(--accent); border-bottom-color: var(--accent); } /* Node detail page */ .node-detail { } .tab-content { min-height: 200px; } /* ============================================================ Error Boundary ============================================================ */ .error-boundary { display: flex; flex-direction: column; align-items: center; justify-content: center; padding: var(--space-8); text-align: center; color: var(--status-error); } .error-boundary h2 { margin-bottom: var(--space-2); } .error-boundary pre { margin-top: var(--space-3); padding: var(--space-3); background: var(--bg-surface); border: 1px solid var(--border-default); border-radius: var(--radius-md); font-size: var(--font-size-xs); max-width: 600px; overflow-x: auto; text-align: left; color: var(--text-secondary); } /* ============================================================ Modal (endpoint detail, etc.) ============================================================ */ .modal-overlay { position: fixed; inset: 0; background: rgba(0, 0, 0, 0.5); display: flex; align-items: center; justify-content: center; z-index: 9000; animation: fade-in 0.15s ease; } .modal { background: var(--bg-surface); border: 1px solid var(--border-default); border-radius: var(--radius-lg); box-shadow: var(--shadow-lg); max-width: 800px; width: 90%; max-height: 85vh; overflow-y: auto; } .modal-header { display: flex; align-items: center; justify-content: space-between; padding: var(--space-4) var(--space-5); border-bottom: 1px solid var(--border-default); } .modal-header h3 { margin: 0; font-size: var(--font-size-base); font-weight: 600; } .modal-body { padding: var(--space-4) var(--space-5); } /* ============================================================ Node switcher (Components/Shared/NodeSwitcher.razor) ============================================================ */ .node-switch { position: relative; } .node-switch-chip { display: inline-flex; align-items: center; gap: var(--space-2); padding: var(--space-1) var(--space-3); background: var(--bg-surface); border: 1px solid var(--border-default); border-radius: var(--radius-full); color: var(--text-primary); font-size: var(--font-size-sm); cursor: pointer; transition: background var(--transition-fast), border-color var(--transition-fast); } .node-switch-chip:hover, .node-switch-chip[aria-expanded="true"] { background: var(--bg-surface-hover); border-color: var(--border-strong); } .node-switch-chip-id { font-weight: 600; } .node-switch-dot { width: 8px; height: 8px; border-radius: var(--radius-full); flex: none; } .node-switch-dot.is-up { background: var(--status-online); } .node-switch-dot.is-down { background: var(--status-offline); } .node-switch-backdrop { position: fixed; inset: 0; z-index: 900; } .node-switch-menu { position: absolute; right: 0; top: calc(100% + var(--space-2)); z-index: 901; width: 360px; max-height: 60vh; overflow-y: auto; padding: var(--space-2); background: var(--bg-surface); border: 1px solid var(--border-default); border-radius: var(--radius-lg); box-shadow: var(--shadow-lg); } .node-switch-filter { margin-bottom: var(--space-2); } .node-switch-group { padding: var(--space-2) var(--space-2) var(--space-1); font-size: var(--font-size-xs, 0.7rem); text-transform: uppercase; letter-spacing: 0.04em; color: var(--text-tertiary); } .node-switch-item { display: grid; grid-template-columns: auto auto 1fr auto; align-items: center; gap: var(--space-2); width: 100%; padding: var(--space-2); background: none; border: none; border-radius: var(--radius-md); color: var(--text-primary); font-size: var(--font-size-sm); text-align: left; cursor: pointer; } .node-switch-item.is-highlighted { background: var(--bg-surface-hover); } .node-switch-item.is-current { background: var(--accent-light); } .node-switch-item.is-current.is-highlighted { background: var(--accent-light); outline: 1px solid var(--accent); } .node-switch-item.is-down { color: var(--text-tertiary); } .node-switch-item-id { font-weight: 600; } .node-switch-item-host { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--text-secondary); } .node-switch-item-meta { display: inline-flex; align-items: center; gap: var(--space-1); } .node-switch-version, .node-switch-down { font-size: var(--font-size-xs, 0.7rem); color: var(--text-tertiary); white-space: nowrap; } .node-switch-empty { padding: var(--space-3); color: var(--text-tertiary); font-size: var(--font-size-sm); } .node-switch-hint { margin-top: var(--space-2); padding: var(--space-2) var(--space-2) 0; border-top: 1px solid var(--border-default); font-size: var(--font-size-xs, 0.7rem); color: var(--text-tertiary); } /* The notice above a page whose node is down or unknown (TsakShell). */ .node-down-notice { display: flex; align-items: center; gap: var(--space-2); margin-bottom: var(--space-4); padding: var(--space-3) var(--space-4); background: var(--status-warning-bg); color: var(--status-warning); border: 1px solid var(--status-warning); border-radius: var(--radius-md); font-size: var(--font-size-sm); } /* Logs page: a marker between lines (lines skipped, node restarted) and the "load older" bar above them. */ .log-marker td { background: var(--status-warning-bg); color: var(--text-secondary); font-style: italic; text-align: center; } .log-older { display: flex; justify-content: center; padding: var(--space-2); } Path: redb-tsak/src/redb.Tsak.Web/wwwroot/js/charts.js Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/wwwroot/js/charts.js ---- // Chart.js interop for Blazor — create, update, destroy Chart.js instances (function () { const _charts = {}; // Blazor JSInterop serializes C# records in PascalCase, // but Chart.js expects camelCase dataset properties. // Colors are OMITTED when absent rather than passed through: JSInterop turns a C# null // into an explicit JS null, and `undefined || null` kept it. Chart.js v4 derives // hoverBackgroundColor by PARSING backgroundColor, and its color parser routes null into // the object branch (typeof null === 'object') — a TypeError on every update() while the // cursor hovers the chart, so a hovered line chart froze mid-poll. An absent key falls // back to Chart.js defaults instead. function mapDatasets(datasets) { return datasets.map(function (ds) { var mapped = { label: ds.Label || ds.label || '', data: ds.Data || ds.data || [], borderWidth: 2, pointRadius: 0, tension: 0.3 }; var border = ds.BorderColor != null ? ds.BorderColor : ds.borderColor; if (border != null) mapped.borderColor = border; var bg = ds.BackgroundColor != null ? ds.BackgroundColor : ds.backgroundColor; if (bg != null) mapped.backgroundColor = bg; return mapped; }); } window.tsakCharts = { create: function (canvasId, config) { const canvas = document.getElementById(canvasId); if (!canvas) return; // Destroy existing chart on same canvas if (_charts[canvasId]) { _charts[canvasId].destroy(); delete _charts[canvasId]; } _charts[canvasId] = new Chart(canvas, config); }, // Single-step creators: build config + create chart in one call (no C#↔JS round-trip) createLine: function (canvasId, labels, datasets, yAxisLabel) { var config = this.lineConfig(labels, datasets, yAxisLabel); this.create(canvasId, config); }, createArea: function (canvasId, labels, datasets, yAxisLabel) { var config = this.areaConfig(labels, datasets, yAxisLabel); this.create(canvasId, config); }, createBar: function (canvasId, labels, datasets, yAxisLabel) { var config = this.barConfig(labels, datasets, yAxisLabel); this.create(canvasId, config); }, createDonut: function (canvasId, labels, data, colors) { var config = this.donutConfig(labels, data, colors); this.create(canvasId, config); }, update: function (canvasId, labels, datasets) { const chart = _charts[canvasId]; if (!chart) return; chart.data.labels = labels; var mapped = mapDatasets(datasets); for (let i = 0; i < mapped.length; i++) { if (chart.data.datasets[i]) { chart.data.datasets[i].data = mapped[i].data; if (mapped[i].label) chart.data.datasets[i].label = mapped[i].label; } } chart.update('none'); // skip animation on data update }, destroy: function (canvasId) { if (_charts[canvasId]) { _charts[canvasId].destroy(); delete _charts[canvasId]; } }, // Pre-built config builders for common chart types lineConfig: function (labels, datasets, yAxisLabel) { return { type: 'line', data: { labels: labels, datasets: mapDatasets(datasets) }, options: { responsive: true, maintainAspectRatio: false, animation: false, interaction: { mode: 'index', intersect: false }, plugins: { legend: { position: 'bottom', labels: { usePointStyle: false, boxWidth: 14, boxHeight: 10, borderRadius: 3, useBorderRadius: true, padding: 16, font: { size: 12 } } }, tooltip: { mode: 'index', intersect: false } }, scales: { x: { grid: { display: false }, ticks: { maxTicksLimit: 10, font: { size: 11 } } }, y: { beginAtZero: true, title: yAxisLabel ? { display: true, text: yAxisLabel, font: { size: 12 } } : { display: false }, ticks: { font: { size: 11 } }, grid: { color: 'rgba(128,128,128,0.1)' } } } } }; }, areaConfig: function (labels, datasets, yAxisLabel) { var cfg = this.lineConfig(labels, datasets, yAxisLabel); for (var i = 0; i < cfg.data.datasets.length; i++) { cfg.data.datasets[i].fill = true; } return cfg; }, barConfig: function (labels, datasets, yAxisLabel) { var mapped = mapDatasets(datasets); for (var i = 0; i < mapped.length; i++) { if (!mapped[i].backgroundColor && mapped[i].borderColor) { mapped[i].backgroundColor = mapped[i].borderColor; } delete mapped[i].pointRadius; delete mapped[i].tension; mapped[i].borderWidth = 0; } return { type: 'bar', data: { labels: labels, datasets: mapped }, options: { responsive: true, maintainAspectRatio: false, animation: false, interaction: { mode: 'index', intersect: false }, plugins: { legend: { position: 'bottom', labels: { usePointStyle: false, boxWidth: 14, boxHeight: 10, borderRadius: 3, useBorderRadius: true, padding: 16, font: { size: 12 } } }, tooltip: { mode: 'index', intersect: false } }, scales: { x: { grid: { display: false }, ticks: { maxTicksLimit: 10, font: { size: 11 } } }, y: { beginAtZero: true, title: yAxisLabel ? { display: true, text: yAxisLabel, font: { size: 12 } } : { display: false }, ticks: { font: { size: 11 } }, grid: { color: 'rgba(128,128,128,0.1)' } } } } }; }, donutConfig: function (labels, data, colors) { return { type: 'doughnut', data: { labels: labels, datasets: [{ data: data, backgroundColor: colors, borderWidth: 0, hoverOffset: 4 }] }, options: { responsive: true, maintainAspectRatio: false, animation: false, cutout: '65%', plugins: { legend: { position: 'bottom', labels: { usePointStyle: true, boxWidth: 8, padding: 12, font: { size: 12 } } }, tooltip: { enabled: true } } } }; }, // Fit .monitoring-charts to remaining viewport height using ResizeObserver. // Recalculates on every resize of the scrollable container. _resizeObserver: null, fitToViewport: function (containerSelector) { var container = document.querySelector(containerSelector); if (!container) return; var scrollParent = container.closest('.shell-content'); if (!scrollParent) return; function recalc() { // Temporarily reset so we can measure the natural scroll height container.style.height = '0px'; // Available = scrollParent viewport height - everything above & below charts - padding var scrollRect = scrollParent.getBoundingClientRect(); var containerRect = container.getBoundingClientRect(); var offsetTop = containerRect.top - scrollRect.top + scrollParent.scrollTop; var padding = parseFloat(getComputedStyle(scrollParent).paddingBottom) || 0; var available = scrollParent.clientHeight - offsetTop - padding; // Minimum so charts don't collapse completely var minH = 300; container.style.height = Math.max(available, minH) + 'px'; } recalc(); // Observe the scroll parent for size changes (window resize, sidebar collapse, etc.) if (this._resizeObserver) { this._resizeObserver.disconnect(); } this._resizeObserver = new ResizeObserver(function () { recalc(); }); this._resizeObserver.observe(scrollParent); }, disconnectResize: function () { if (this._resizeObserver) { this._resizeObserver.disconnect(); this._resizeObserver = null; } } }; })(); Path: redb-tsak/src/redb.Tsak.Web/wwwroot/js/logs.js Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/wwwroot/js/logs.js ---- (function () { 'use strict'; window.tsakLogs = { // Scroll container to bottom if user is already near the bottom (within 50px) autoScroll: function (elementId) { var el = document.getElementById(elementId); if (!el) return; var atBottom = el.scrollHeight - el.scrollTop - el.clientHeight < 50; if (atBottom) { el.scrollTop = el.scrollHeight; } }, // Force scroll to bottom scrollToBottom: function (elementId) { var el = document.getElementById(elementId); if (el) el.scrollTop = el.scrollHeight; } }; })(); Path: redb-tsak/src/redb.Tsak.Web/wwwroot/js/nodeswitch.js Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/wwwroot/js/nodeswitch.js ---- (function () { 'use strict'; // Keys of the node switcher (Components/Shared/NodeSwitcher.razor), outside any input: n opens the list, // [ and ] go to the previous and next node of the group. Typing into a field is never taken. var target = null; function typing(el) { if (!el) return false; var tag = el.tagName; return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || el.isContentEditable; } function onKey(e) { if (!target || e.ctrlKey || e.metaKey || e.altKey || typing(e.target)) return; if (e.key === 'n' || e.key === '[' || e.key === ']') { e.preventDefault(); target.invokeMethodAsync('OnShortcut', e.key); } } window.tsakNodeSwitch = { attach: function (dotNetRef) { target = dotNetRef; document.removeEventListener('keydown', onKey); document.addEventListener('keydown', onKey); }, detach: function () { target = null; document.removeEventListener('keydown', onKey); } }; })(); Path: redb-tsak/src/redb.Tsak.Web/wwwroot/js/theme.js Snapshot: redb-tsak, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-tsak Page: https://redbase.app/src/dev-2026-12-06/redb-tsak/src/redb.Tsak.Web/wwwroot/js/theme.js ---- // Theme persistence: stores preference in localStorage, applies on load (function () { const STORAGE_KEY = 'tsak-theme'; function getPreferred() { const stored = localStorage.getItem(STORAGE_KEY); if (stored === 'dark' || stored === 'light') return stored; return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'; } function apply(theme) { document.documentElement.setAttribute('data-theme', theme); localStorage.setItem(STORAGE_KEY, theme); } // Apply immediately to prevent flash apply(getPreferred()); // Expose toggle for Blazor interop window.tsakTheme = { toggle: function () { const current = document.documentElement.getAttribute('data-theme'); const next = current === 'dark' ? 'light' : 'dark'; apply(next); return next; }, get: function () { return document.documentElement.getAttribute('data-theme') || 'light'; } }; })();