Deleted old message system. Replaced it with new event system

This commit is contained in:
Marcel Baumgartner
2023-04-21 17:17:10 +02:00
parent b790c31606
commit b8893e7976
14 changed files with 111 additions and 220 deletions

View File

@@ -1,4 +1,5 @@
using Microsoft.AspNetCore.Mvc;
using Moonlight.App.Events;
using Moonlight.App.Http.Requests.Wings;
using Moonlight.App.Repositories;
using Moonlight.App.Repositories.Servers;
@@ -11,17 +12,17 @@ namespace Moonlight.App.Http.Controllers.Api.Remote;
public class BackupController : Controller
{
private readonly ServerBackupRepository ServerBackupRepository;
private readonly MessageService MessageService;
private readonly EventSystem Event;
private readonly NodeRepository NodeRepository;
public BackupController(
ServerBackupRepository serverBackupRepository,
NodeRepository nodeRepository,
MessageService messageService)
EventSystem eventSystem)
{
ServerBackupRepository = serverBackupRepository;
NodeRepository = nodeRepository;
MessageService = messageService;
Event = eventSystem;
}
[HttpGet("{uuid}")]
@@ -57,11 +58,11 @@ public class BackupController : Controller
ServerBackupRepository.Update(backup);
await MessageService.Emit($"wings.backups.create", backup);
await Event.Emit($"wings.backups.create", backup);
}
else
{
await MessageService.Emit($"wings.backups.createfailed", backup);
await Event.Emit($"wings.backups.createFailed", backup);
ServerBackupRepository.Delete(backup);
}
@@ -88,7 +89,7 @@ public class BackupController : Controller
if (backup == null)
return NotFound();
await MessageService.Emit($"wings.backups.restore", backup);
await Event.Emit($"wings.backups.restore", backup);
return NoContent();
}

View File

@@ -1,6 +1,7 @@
using Logging.Net;
using Microsoft.AspNetCore.Mvc;
using Moonlight.App.Database.Entities;
using Moonlight.App.Events;
using Moonlight.App.Http.Requests.Daemon;
using Moonlight.App.Repositories;
using Moonlight.App.Services;
@@ -12,13 +13,13 @@ namespace Moonlight.App.Http.Controllers.Api.Remote;
public class DdosController : Controller
{
private readonly NodeRepository NodeRepository;
private readonly MessageService MessageService;
private readonly EventSystem Event;
private readonly DdosAttackRepository DdosAttackRepository;
public DdosController(NodeRepository nodeRepository, MessageService messageService, DdosAttackRepository ddosAttackRepository)
public DdosController(NodeRepository nodeRepository, EventSystem eventSystem, DdosAttackRepository ddosAttackRepository)
{
NodeRepository = nodeRepository;
MessageService = messageService;
Event = eventSystem;
DdosAttackRepository = ddosAttackRepository;
}
@@ -47,7 +48,7 @@ public class DdosController : Controller
ddosAttack = DdosAttackRepository.Add(ddosAttack);
await MessageService.Emit("node.ddos", ddosAttack);
await Event.Emit("node.ddos", ddosAttack);
return Ok();
}

View File

@@ -1,5 +1,6 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Moonlight.App.Events;
using Moonlight.App.Helpers;
using Moonlight.App.Http.Resources.Wings;
using Moonlight.App.Repositories;
@@ -15,18 +16,18 @@ public class ServersController : Controller
private readonly WingsServerConverter Converter;
private readonly ServerRepository ServerRepository;
private readonly NodeRepository NodeRepository;
private readonly MessageService MessageService;
private readonly EventSystem Event;
public ServersController(
WingsServerConverter converter,
ServerRepository serverRepository,
NodeRepository nodeRepository,
MessageService messageService)
EventSystem eventSystem)
{
Converter = converter;
ServerRepository = serverRepository;
NodeRepository = nodeRepository;
MessageService = messageService;
Event = eventSystem;
}
[HttpGet]
@@ -68,7 +69,7 @@ public class ServersController : Controller
totalPages = slice.Length - 1;
}
await MessageService.Emit($"wings.{node.Id}.serverlist", node);
await Event.Emit($"wings.{node.Id}.serverList", node);
//Logger.Debug($"[BRIDGE] Node '{node.Name}' is requesting server list page {page} with {perPage} items per page");
@@ -97,7 +98,7 @@ public class ServersController : Controller
if (token != node.Token)
return Unauthorized();
await MessageService.Emit($"wings.{node.Id}.statereset", node);
await Event.Emit($"wings.{node.Id}.stateReset", node);
foreach (var server in ServerRepository
.Get()
@@ -136,7 +137,7 @@ public class ServersController : Controller
if (server == null)
return NotFound();
await MessageService.Emit($"wings.{node.Id}.serverfetch", server);
await Event.Emit($"wings.{node.Id}.serverFetch", server);
try //TODO: Remove
{
@@ -169,7 +170,7 @@ public class ServersController : Controller
if (server == null)
return NotFound();
await MessageService.Emit($"wings.{node.Id}.serverinstallfetch", server);
await Event.Emit($"wings.{node.Id}.serverInstallFetch", server);
return new WingsServerInstall()
{
@@ -202,8 +203,8 @@ public class ServersController : Controller
server.Installing = false;
ServerRepository.Update(server);
await MessageService.Emit($"wings.{node.Id}.serverinstallcomplete", server);
await MessageService.Emit($"server.{server.Uuid}.installcomplete", server);
await Event.Emit($"wings.{node.Id}.serverInstallComplete", server);
await Event.Emit($"server.{server.Uuid}.installComplete", server);
return Ok();
}

View File

@@ -1,83 +0,0 @@
using System.Diagnostics;
using Logging.Net;
namespace Moonlight.App.MessageSystem;
public class MessageSender
{
private readonly List<MessageSubscriber> Subscribers;
public bool Debug { get; set; }
public TimeSpan TookToLongTime { get; set; } = TimeSpan.FromSeconds(1);
public MessageSender()
{
Subscribers = new();
}
public void Subscribe<T, K>(string name, object bind, Func<K, Task> method)
{
lock (Subscribers)
{
Subscribers.Add(new ()
{
Name = name,
Action = method,
Type = typeof(T),
Bind = bind
});
}
if(Debug)
Logger.Debug($"{bind} subscribed to '{name}'");
}
public void Unsubscribe(string name, object bind)
{
lock (Subscribers)
{
Subscribers.RemoveAll(x => x.Bind == bind);
}
if(Debug)
Logger.Debug($"{bind} unsubscribed from '{name}'");
}
public Task Emit(string name, object? value, bool disableWarning = false)
{
lock (Subscribers)
{
foreach (var subscriber in Subscribers)
{
if (subscriber.Name == name)
{
var stopWatch = new Stopwatch();
stopWatch.Start();
var del = (Delegate)subscriber.Action;
((Task)del.DynamicInvoke(value)!).Wait();
stopWatch.Stop();
if (!disableWarning)
{
if (stopWatch.Elapsed.TotalMilliseconds > TookToLongTime.TotalMilliseconds)
{
Logger.Warn(
$"Subscriber {subscriber.Type.Name} for event '{name}' took long to process. {stopWatch.Elapsed.TotalMilliseconds}ms");
}
}
if (Debug)
{
Logger.Debug(
$"Subscriber {subscriber.Type.Name} for event '{name}' took {stopWatch.Elapsed.TotalMilliseconds}ms");
}
}
}
}
return Task.CompletedTask;
}
}

View File

@@ -1,9 +0,0 @@
namespace Moonlight.App.MessageSystem;
public class MessageSubscriber
{
public string Name { get; set; }
public object Action { get; set; }
public Type Type { get; set; }
public object Bind { get; set; }
}

View File

@@ -7,6 +7,7 @@ using Moonlight.App.Models.Wings;
using Moonlight.App.Repositories;
using Moonlight.App.Repositories.Servers;
using Logging.Net;
using Moonlight.App.Events;
using Newtonsoft.Json;
namespace Moonlight.App.Services;
@@ -23,21 +24,21 @@ public class CleanupService
#endregion
private readonly ConfigService ConfigService;
private readonly MessageService MessageService;
private readonly DateTimeService DateTimeService;
private readonly EventSystem Event;
private readonly IServiceScopeFactory ServiceScopeFactory;
private readonly PeriodicTimer Timer;
public CleanupService(
ConfigService configService,
IServiceScopeFactory serviceScopeFactory,
MessageService messageService,
DateTimeService dateTimeService)
DateTimeService dateTimeService,
EventSystem eventSystem)
{
ServiceScopeFactory = serviceScopeFactory;
MessageService = messageService;
DateTimeService = dateTimeService;
ConfigService = configService;
Event = eventSystem;
StartedAt = DateTimeService.GetCurrent();
CompletedAt = DateTimeService.GetCurrent();
@@ -148,7 +149,7 @@ public class CleanupService
ServersRunning++;
}
await MessageService.Emit("cleanup.updated", null);
await Event.Emit("cleanup.updated");
}
}
else
@@ -178,7 +179,7 @@ public class CleanupService
ServersRunning++;
}
await MessageService.Emit("cleanup.updated", null);
await Event.Emit("cleanup.updated");
}
}
}
@@ -199,7 +200,7 @@ public class CleanupService
IsRunning = false;
CleanupsPerformed++;
await MessageService.Emit("cleanup.updated", null);
await Event.Emit("cleanup.updated");
}
}

View File

@@ -1,11 +0,0 @@
using Moonlight.App.MessageSystem;
namespace Moonlight.App.Services;
public class MessageService : MessageSender
{
public MessageService()
{
Debug = false;
}
}

View File

@@ -1,6 +1,7 @@
using Microsoft.EntityFrameworkCore;
using Moonlight.App.Database;
using Moonlight.App.Database.Entities;
using Moonlight.App.Events;
using Moonlight.App.Exceptions;
using Moonlight.App.Helpers;
using Moonlight.App.Helpers.Files;
@@ -23,7 +24,6 @@ public class ServerService
private readonly NodeRepository NodeRepository;
private readonly NodeAllocationRepository NodeAllocationRepository;
private readonly WingsApiHelper WingsApiHelper;
private readonly MessageService MessageService;
private readonly UserService UserService;
private readonly ConfigService ConfigService;
private readonly WingsJwtHelper WingsJwtHelper;
@@ -32,6 +32,7 @@ public class ServerService
private readonly ErrorLogService ErrorLogService;
private readonly NodeService NodeService;
private readonly DateTimeService DateTimeService;
private readonly EventSystem Event;
public ServerService(
ServerRepository serverRepository,
@@ -39,7 +40,6 @@ public class ServerService
UserRepository userRepository,
ImageRepository imageRepository,
NodeRepository nodeRepository,
MessageService messageService,
UserService userService,
ConfigService configService,
WingsJwtHelper wingsJwtHelper,
@@ -48,14 +48,14 @@ public class ServerService
ErrorLogService errorLogService,
NodeService nodeService,
NodeAllocationRepository nodeAllocationRepository,
DateTimeService dateTimeService)
DateTimeService dateTimeService,
EventSystem eventSystem)
{
ServerRepository = serverRepository;
WingsApiHelper = wingsApiHelper;
UserRepository = userRepository;
ImageRepository = imageRepository;
NodeRepository = nodeRepository;
MessageService = messageService;
UserService = userService;
ConfigService = configService;
WingsJwtHelper = wingsJwtHelper;
@@ -65,6 +65,7 @@ public class ServerService
NodeService = nodeService;
NodeAllocationRepository = nodeAllocationRepository;
DateTimeService = dateTimeService;
Event = eventSystem;
}
private Server EnsureNodeData(Server s)
@@ -212,7 +213,7 @@ public class ServerService
ServerRepository.Update(serverData);
await MessageService.Emit("wings.backups.delete", backup);
await Event.Emit("wings.backups.delete", backup);
await AuditLogService.Log(AuditLogType.DeleteBackup,
x =>

View File

@@ -90,7 +90,6 @@ namespace Moonlight
builder.Services.AddScoped<TotpService>();
builder.Services.AddScoped<ToastService>();
builder.Services.AddScoped<NodeService>();
builder.Services.AddSingleton<MessageService>();
builder.Services.AddScoped<ServerService>();
builder.Services.AddSingleton<PaperService>();
builder.Services.AddScoped<ClipboardService>();

View File

@@ -5,6 +5,7 @@
@using Logging.Net
@using BlazorContextMenu
@using Moonlight.App.Database.Entities
@using Moonlight.App.Events
@using Moonlight.App.Services.Interop
@inject ServerService ServerService
@@ -12,7 +13,7 @@
@inject AlertService AlertService
@inject ToastService ToastService
@inject ClipboardService ClipboardService
@inject MessageService MessageService
@inject EventSystem Event
@inject SmartTranslateService SmartTranslateService
@implements IDisposable
@@ -112,64 +113,51 @@
protected override void OnInitialized()
{
MessageService.Subscribe<ServerBackups, ServerBackup>("wings.backups.create", this, (backup) =>
Event.On<ServerBackup>("wings.backups.create", this, async (backup) =>
{
if (AllBackups == null)
return Task.CompletedTask;
return;
if (AllBackups.Any(x => x.Id == backup.Id))
{
Task.Run(async () =>
{
await Task.Delay(TimeSpan.FromSeconds(1));
await ToastService.Success(SmartTranslateService.Translate("Backup successfully created"));
await LazyLoader.Reload();
});
}
return Task.CompletedTask;
});
MessageService.Subscribe<ServerBackups, ServerBackup>("wings.backups.createfailed", this, (backup) =>
Event.On<ServerBackup>("wings.backups.createFailed", this, async (backup) =>
{
if (AllBackups == null)
return Task.CompletedTask;
return;
if (AllBackups.Any(x => x.Id == backup.Id))
{
Task.Run(async () =>
{
await ToastService.Error(SmartTranslateService.Translate("Backup creation failed"));
await LazyLoader.Reload();
});
}
return Task.CompletedTask;
});
MessageService.Subscribe<ServerBackups, ServerBackup>("wings.backups.delete", this, async (backup) =>
Event.On<ServerBackup>("wings.backups.delete", this, async (backup) =>
{
if (AllBackups == null)
return;
if (AllBackups.Any(x => x.Id == backup.Id))
{
Task.Run(async () =>
{
await ToastService.Success(SmartTranslateService.Translate("Backup successfully deleted"));
await LazyLoader.Reload();
});
}
});
MessageService.Subscribe<ServerBackups, ServerBackup>("wings.backups.restore", this, async (backup) =>
Event.On<ServerBackup>("wings.backups.restore", this, async (backup) =>
{
if (AllBackups == null)
return;
if (AllBackups.Any(x => x.Id == backup.Id))
{
Task.Run(async () => { await ToastService.Success(SmartTranslateService.Translate("Backup successfully restored")); });
await ToastService.Success(SmartTranslateService.Translate("Backup successfully restored"));
}
});
}
@@ -308,11 +296,11 @@
await Refresh(LazyLoader);
}
public void Dispose()
public async void Dispose()
{
MessageService.Unsubscribe("wings.backups.create", this);
MessageService.Unsubscribe("wings.backups.createfailed", this);
MessageService.Unsubscribe("wings.backups.restore", this);
MessageService.Unsubscribe("wings.backups.delete", this);
await Event.Off("wings.backups.create", this);
await Event.Off("wings.backups.createFailed", this);
await Event.Off("wings.backups.restore", this);
await Event.Off("wings.backups.delete", this);
}
}

View File

@@ -9,6 +9,7 @@
@using Moonlight.App.Services.Interop
@using Moonlight.App.Services.Sessions
@using Logging.Net
@using Moonlight.App.Events
@layout ThemeInit
@implements IDisposable
@@ -18,7 +19,7 @@
@inject IdentityService IdentityService
@inject SessionService SessionService
@inject NavigationManager NavigationManager
@inject MessageService MessageService
@inject EventSystem Event
@inject ToastService ToastService
<GlobalErrorBoundary>
@@ -164,17 +165,19 @@
NavigationManager.LocationChanged += (sender, args) => { SessionService.Refresh(); };
/*
MessageService.Subscribe<MainLayout, SupportMessage>(
$"support.{User.Id}.message",
if (User != null)
{
await Event.On<SupportChatMessage>(
$"supportChat.{User.Id}.message",
this,
async message =>
{
if (!NavigationManager.Uri.EndsWith("/support") && (message.IsSupport || message.IsSystem))
if (!NavigationManager.Uri.EndsWith("/support") && message.Sender != User)
{
await ToastService.Info($"Support: {message.Message}");
await ToastService.Info($"Support: {message.Content}");
}
});
}
});*/
RunDelayedMenu(0);
RunDelayedMenu(1);
@@ -188,13 +191,13 @@
}
}
public void Dispose()
public async void Dispose()
{
SessionService.Close();
if (User != null)
{
MessageService.Unsubscribe($"support.{User.Id}.message", this);
await Event.Off($"supportChat.{User.Id}.message", this);
}
}

View File

@@ -5,6 +5,7 @@
@using BlazorTable
@using Microsoft.EntityFrameworkCore
@using Moonlight.App.Database.Entities
@using Moonlight.App.Events
@using Moonlight.App.Helpers
@using Moonlight.App.Services
@@ -12,7 +13,7 @@
@inject DdosAttackRepository DdosAttackRepository
@inject SmartTranslateService SmartTranslateService
@inject MessageService MessageService
@inject EventSystem Event
<OnlyAdmin>
<AdminNodesNavigation Index="1"/>
@@ -75,11 +76,12 @@
private DdosAttack[] DdosAttacks;
private LazyLoader LazyLoader;
protected override Task OnAfterRenderAsync(bool firstRender)
protected override async Task OnAfterRenderAsync(bool firstRender)
{
MessageService.Subscribe<Ddos, DdosAttack>("node.ddos", this, async attack => { Task.Run(async () => await LazyLoader.Reload()); });
return Task.CompletedTask;
if (firstRender)
{
await Event.On<DdosAttack>("node.ddos", this, async attack => await LazyLoader.Reload());
}
}
private Task Load(LazyLoader arg)
@@ -93,8 +95,8 @@
return Task.CompletedTask;
}
public void Dispose()
public async void Dispose()
{
MessageService.Unsubscribe("node.ddos", this);
await Event.Off("node.ddos", this);
}
}

View File

@@ -3,10 +3,11 @@
@using Moonlight.App.Services
@using Moonlight.App.Models.Misc
@using Moonlight.App.Services.LogServices
@using Moonlight.App.Events
@inject CleanupService CleanupService
@inject AuditLogService AuditLogService
@inject MessageService MessageService
@inject EventSystem Event
@implements IDisposable
@@ -83,21 +84,16 @@
@code
{
protected override void OnInitialized()
protected override async Task OnInitializedAsync()
{
MessageService.Subscribe<Cleanup, Object>("cleanup.updated", this, _ =>
{
Task.Run(async () =>
await Event.On<Object>("cleanup.updated", this, async _ =>
{
await InvokeAsync(StateHasChanged);
});
return Task.CompletedTask;
});
}
public void Dispose()
public async void Dispose()
{
MessageService.Unsubscribe("cleanup.updated", this);
await Event.Off("cleanup.updated", this);
}
}

View File

@@ -6,6 +6,7 @@
@using Microsoft.EntityFrameworkCore
@using Logging.Net
@using Moonlight.App.Database.Entities
@using Moonlight.App.Events
@using Moonlight.App.Helpers
@using Moonlight.App.Repositories
@using Moonlight.App.Services
@@ -16,7 +17,7 @@
@inject ImageRepository ImageRepository
@inject ServerRepository ServerRepository
@inject WingsConsoleHelper WingsConsoleHelper
@inject MessageService MessageService
@inject EventSystem Event
@inject ServerService ServerService
@inject NavigationManager NavigationManager
@@ -260,9 +261,9 @@
await WingsConsoleHelper.ConnectWings(Console!, CurrentServer);
MessageService.Subscribe<Index, Server>($"server.{CurrentServer.Uuid}.installcomplete", this, server =>
await Event.On<Server>($"server.{CurrentServer.Uuid}.installComplete", this, server =>
{
Task.Run(() => { NavigationManager.NavigateTo(NavigationManager.Uri); });
NavigationManager.NavigateTo(NavigationManager.Uri);
return Task.CompletedTask;
});
@@ -274,11 +275,11 @@
}
}
public void Dispose()
public async void Dispose()
{
if (CurrentServer != null)
{
MessageService.Unsubscribe($"server.{CurrentServer.Uuid}.installcomplete", this);
await Event.Off($"server.{CurrentServer.Uuid}.installComplete", this);
}
}
}