[CHANGE] Service extended and events

This commit is contained in:
max
2025-09-10 01:46:07 +02:00
parent 9ff4fcded2
commit 03631cd0c8
9 changed files with 202 additions and 26 deletions

View File

@@ -16,7 +16,7 @@
</MudTooltip>
}
</MudAppBar>
<div style="margin: 20px">
<div style="display: flex; flex-direction: column; flex: 1; padding: 20px; min-height: 0;">
@Body
</div>
</CascadingValue>

View File

@@ -7,7 +7,7 @@
<CascadingValue Value="this">
<MudLayout>
<MudMainContent>
<MudMainContent Style="display: flex; flex-direction: column; height: 100vh;">
@Body
</MudMainContent>
</MudLayout>

View File

@@ -1,26 +1,90 @@
@page "/Services"
@using Manager.App.Services.System
@implements IDisposable
@inject BackgroundServiceManager ServiceManager
<title>Services</title>
<MudDataGrid T="ExtendedBackgroundService" MultiSelection Items="@_backgroundServices">
<MudDataGrid T="ExtendedBackgroundService" Items="@_backgroundServices" Filterable QuickFilter="@QuickFilter">
<ToolBarContent>
<MudText Typo="Typo.h6">Services</MudText>
<MudSpacer />
<MudSpacer/>
<MudTextField T="string" @bind-Value="@_searchText" Immediate
Placeholder="Search" Adornment="Adornment.Start"
AdornmentIcon="@Icons.Material.Filled.Search" IconSize="Size.Medium"/>
</ToolBarContent>
<Columns>
<PropertyColumn Property="x => x.Name" Title="Service"/>
<PropertyColumn Property="x => x.Description" Title="Description"/>
<PropertyColumn Property="x => x.State" Title="Status"/>
<PropertyColumn Property="x => x.ExecuteInterval" Title="Execute interval"/>
<TemplateColumn></TemplateColumn>
<TemplateColumn>
<CellTemplate>
<MudStack Row Spacing="2">
<MudButton Disabled="@(context.Item?.State == ServiceState.Paused)"
OnClick="@(() => { context.Item?.Pause(); })" Variant="Variant.Outlined">Pause
</MudButton>
<MudButton Disabled="@(context.Item?.State == ServiceState.Running)"
OnClick="@(() => { context.Item?.Resume(); })" Variant="Variant.Outlined">Resume
</MudButton>
</MudStack>
</CellTemplate>
</TemplateColumn>
</Columns>
<PagerContent>
<MudDataGridPager T="ExtendedBackgroundService" />
<MudDataGridPager T="ExtendedBackgroundService"/>
</PagerContent>
</MudDataGrid>
<MudPaper Elevation="0" Class="mt-3" Style="flex: 1; display: flex; flex-direction: column; min-height: 0;">
<MudStack Class="ml-2 mb-2" Spacing="1">
<MudText Typo="Typo.h5">Service events</MudText>
<MudText Typo="Typo.caption">@($"{_serviceEvents.Count}/{VisibleEventCapacity} events")</MudText>
</MudStack>
<div class="console-container">
@foreach (var serviceEvent in _serviceEvents)
{
<div class="log-line">
<span>@serviceEvent.Date</span>
<span>|</span>
<span class="@GetLogClass(serviceEvent)">@serviceEvent.Severity</span>
<span>|</span>
<span style="color: #4d69f1">@serviceEvent.Source</span>
<span>-</span>
<span style="color: #d4d4d4">@serviceEvent.Message</span>
</div>
}
</div>
</MudPaper>
<style>
.console-container {
background-color: #1e1e1e;
color: #9c9898;
padding: 10px;
border-radius: 8px;
flex: 1;
overflow-y: auto;
font-family: monospace;
}
.log-line {
display: flex;
justify-content: start;
align-items: center;
gap: 0.25rem;
}
.log-info {
color: #9cdcfe;
}
.log-warning {
color: #dcdcaa;
}
.log-error {
color: #f44747;
}
</style>

View File

@@ -1,16 +1,67 @@
using DotBased.Logging;
using Manager.App.Extensions;
using Manager.App.Services;
using Microsoft.AspNetCore.Components;
using MudBlazor;
namespace Manager.App.Components.Pages;
public partial class Services : ComponentBase
{
private const int VisibleEventCapacity = 500;
private string _searchText = "";
private List<ExtendedBackgroundService> _backgroundServices = [];
private List<ServiceEvent> _serviceEvents = [];
private CancellationTokenSource _cts = new();
protected override void OnInitialized()
{
_backgroundServices = ServiceManager.GetServices();
_ = Task.Run(() => ReadEventStreamsAsync(_cts.Token));
}
private Func<ExtendedBackgroundService, bool> QuickFilter
=> x => string.IsNullOrWhiteSpace(_searchText) || $"{x.Name} {x.Description} {x.State} {x.ExecuteInterval}".Contains(_searchText);
private async Task ReadEventStreamsAsync(CancellationToken token)
{
if (_backgroundServices.Count == 0)
{
return;
}
var totalToGet = VisibleEventCapacity / _backgroundServices.Count;
_serviceEvents.AddRange(_backgroundServices.SelectMany(x => x.ProgressEvents.Items.TakeLast(totalToGet)));
var asyncEnumerators = _backgroundServices.Select(x => x.ProgressEvents.GetStreamAsync());
await foreach (var serviceEvent in AsyncEnumerableExtensions.Merge(asyncEnumerators, token))
{
if (!_serviceEvents.Contains(serviceEvent))
{
_serviceEvents.Add(serviceEvent);
}
if (_serviceEvents.Count > VisibleEventCapacity)
{
_serviceEvents.RemoveAt(0);
}
await InvokeAsync(StateHasChanged);
}
}
private string GetLogClass(ServiceEvent serviceEvent) =>
serviceEvent.Severity switch
{
LogSeverity.Info => "log-info",
LogSeverity.Warning => "log-warning",
LogSeverity.Error => "log-error",
_ => "log-info"
};
public void Dispose()
{
_cts.Cancel();
_cts.Dispose();
}
}

View File

@@ -0,0 +1,48 @@
using System.Threading.Channels;
namespace Manager.App.Extensions;
public static class AsyncEnumerableExtensions
{
public static async IAsyncEnumerable<T> Merge<T>(IEnumerable<IAsyncEnumerable<T>> sources, [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default)
{
var channel = Channel.CreateUnbounded<T>( new UnboundedChannelOptions { SingleReader = true, SingleWriter = false });
var writerTasks = sources.Select(source => Task.Run(async () =>
{
try
{
await foreach (var item in source.WithCancellation(cancellationToken))
{
await channel.Writer.WriteAsync(item, cancellationToken);
}
}
catch (OperationCanceledException)
{
}
catch (Exception ex)
{
channel.Writer.TryComplete(ex);
}
}, cancellationToken)).ToArray();
_ = Task.Run(async () =>
{
try
{
await Task.WhenAll(writerTasks);
channel.Writer.TryComplete();
}
catch
{
channel.Writer.TryComplete();
}
}, cancellationToken);
await foreach (var item in channel.Reader.ReadAllAsync(cancellationToken))
{
yield return item;
}
}
}

View File

@@ -6,6 +6,7 @@ public class CircularBuffer <T>
{
private readonly T[] _buffer;
private readonly Channel<T> _channel;
private readonly object _lock = new();
public int Capacity { get; }
public int Head { get; private set; }
@@ -30,12 +31,15 @@ public class CircularBuffer <T>
public void Add(T item)
{
_buffer[Head] = item;
Head = (Head + 1) % _buffer.Length;
if (Count < _buffer.Length)
lock (_lock)
{
Count++;
_buffer[Head] = item;
Head = (Head + 1) % _buffer.Length;
if (Count < _buffer.Length)
{
Count++;
}
}
_channel.Writer.TryWrite(item);
@@ -47,7 +51,10 @@ public class CircularBuffer <T>
{
for (var i = 0; i < Count; i++)
{
yield return _buffer[(Head - Count + i + _buffer.Length) % _buffer.Length];
lock (_lock)
{
yield return _buffer[(Head - Count + i + _buffer.Length) % _buffer.Length];
}
}
}
}

View File

@@ -9,16 +9,18 @@ public abstract class ExtendedBackgroundService : BackgroundService
private TaskCompletionSource _resumeSignal = new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly ILogger _logger;
public ServiceState State { get; private set; } = ServiceState.Stopped;
public CircularBuffer<ServiceProgress> ProgressLog { get; } = new(500);
public CircularBuffer<ServiceEvent> ProgressEvents { get; } = new(500);
public string Name { get; }
public string Description { get; set; }
public TimeSpan ExecuteInterval { get; set; }
public ExtendedBackgroundService(string name, ILogger logger, BackgroundServiceManager manager, TimeSpan? executeInterval = null)
public ExtendedBackgroundService(string name, string description, ILogger logger, BackgroundServiceManager manager, TimeSpan? executeInterval = null)
{
Name = name;
Description = description;
_logger = logger;
manager.RegisterService(this);
ExecuteInterval = executeInterval ?? TimeSpan.Zero;
ExecuteInterval = executeInterval ?? TimeSpan.FromMinutes(1);
}
protected sealed override async Task ExecuteAsync(CancellationToken stoppingToken)
@@ -58,7 +60,7 @@ public abstract class ExtendedBackgroundService : BackgroundService
}
}
protected void LogProgress(string message, LogSeverity severity = LogSeverity.Info) => ProgressLog.Add(new ServiceProgress(message, DateTime.UtcNow, severity));
protected void LogEvent(string message, LogSeverity severity = LogSeverity.Info) => ProgressEvents.Add(new ServiceEvent(Name, message, DateTime.UtcNow, severity));
public void Pause()
{
@@ -101,4 +103,4 @@ public enum ServiceState
Paused
}
public record ServiceProgress(string Message, DateTime StartTime, LogSeverity Severity);
public record ServiceEvent(string Source, string Message, DateTime Date, LogSeverity Severity);

View File

@@ -1,4 +1,5 @@
using System.Net;
using DotBased.Logging;
using DotBased.Monads;
using Manager.App.Models.Library;
using Manager.Data.Entities.LibraryContext;
@@ -6,7 +7,8 @@ using Manager.YouTube;
namespace Manager.App.Services.System;
public class ClientService(IServiceScopeFactory scopeFactory, ILogger<ClientService> logger, BackgroundServiceManager serviceManager) : ExtendedBackgroundService("ClientService", logger, serviceManager)
public class ClientService(IServiceScopeFactory scopeFactory, ILogger<ClientService> logger, BackgroundServiceManager serviceManager)
: ExtendedBackgroundService("ClientService", "Managing YouTube clients", logger, serviceManager, TimeSpan.FromMilliseconds(100))
{
private readonly List<YouTubeClient> _clients = [];
private CancellationToken _cancellationToken;
@@ -18,13 +20,15 @@ public class ClientService(IServiceScopeFactory scopeFactory, ILogger<ClientServ
stoppingToken.Register(CancellationRequested);
using var scope = scopeFactory.CreateScope();
_libraryService = scope.ServiceProvider.GetRequiredService<ILibraryService>();
LogProgress("Initializing service...");
LogEvent("Initializing service...");
Pause();
}
protected override async Task ExecuteServiceAsync(CancellationToken stoppingToken)
{
LogEvent("Sending event...");
LogEvent("Sending warning event...", LogSeverity.Warning);
LogEvent("Sending error event...", LogSeverity.Error);
}
private void CancellationRequested()

View File

@@ -3,11 +3,11 @@
"Logging": {
"Severity": "Debug",
"SeverityFilters":{
"Microsoft": "Debug",
"Microsoft": "Info",
"Microsoft.Hosting.Lifetime": "Debug",
"Microsoft.AspNetCore": "Warning",
"Microsoft.AspNetCore.Authentication": "Debug",
"MudBlazor": "Debug"
"MudBlazor": "Info"
}
}
},