From 49d2a78b0edc5237411f770bb8584b96c361d9c1 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 7 Aug 2024 08:33:38 -0500 Subject: stub EventBus --- src/slskd/Core/EventBus.cs | 42 ++++++++++++++++++++++++ src/slskd/Transfers/Downloads/DownloadService.cs | 3 ++ 2 files changed, 45 insertions(+) create mode 100644 src/slskd/Core/EventBus.cs diff --git a/src/slskd/Core/EventBus.cs b/src/slskd/Core/EventBus.cs new file mode 100644 index 00000000..b90e3fc2 --- /dev/null +++ b/src/slskd/Core/EventBus.cs @@ -0,0 +1,42 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +using System.Threading.Tasks; + +namespace slskd; + +public enum EventType +{ + NOOP, + DOWNLOAD_FILE_COMPLETE, + DOWNLOAD_DIRECTORY_COMPLETE, +} + +public class EventData +{ +} + +/// +/// The application event bus. +/// +public class EventBus +{ + public async Task RaiseAsync(EventType type, T data) + { + + } +} \ No newline at end of file diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 32903bf9..69e2d2c4 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -331,6 +331,9 @@ namespace slskd.Transfers.Downloads _ = Relay.NotifyFileDownloadCompleteAsync(finalFilename); } + // todo: raise DOWNLOAD_FILE_COMPLETE + // todo: determine if there are any pending transfers in this same directory, and if not raise DOWNLOAD_DIRECTORY_COMPLETE + if (OptionsMonitor.CurrentValue.Integration.Ftp.Enabled) { _ = FTP.UploadAsync(finalFilename); -- cgit v1.2.3 From 621973f393ac0e18f854baeec1ac203bd4805ac1 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 10 Aug 2024 19:29:51 -0500 Subject: wip --- src/slskd/Core/EventBus.cs | 51 ++++++++++++++++++++---- src/slskd/Tasks/TaskService.cs | 0 src/slskd/Transfers/Downloads/DownloadService.cs | 6 ++- src/slskd/Transfers/Types/Transfer.cs | 4 ++ src/slskd/Transfers/Types/Upload.cs | 2 +- 5 files changed, 54 insertions(+), 9 deletions(-) create mode 100644 src/slskd/Tasks/TaskService.cs diff --git a/src/slskd/Core/EventBus.cs b/src/slskd/Core/EventBus.cs index b90e3fc2..ee4254ca 100644 --- a/src/slskd/Core/EventBus.cs +++ b/src/slskd/Core/EventBus.cs @@ -15,19 +15,32 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // +namespace slskd; + +using System; +using System.Collections.Concurrent; +using System.Linq; using System.Threading.Tasks; +using Serilog; +using slskd.Transfers; -namespace slskd; +public record Event +{ +} -public enum EventType +public record DownloadFileCompleteEvent : Event { - NOOP, - DOWNLOAD_FILE_COMPLETE, - DOWNLOAD_DIRECTORY_COMPLETE, + public string LocalFilename { get; init; } + public string RemoteFilename { get; init; } + public string Username { get; init; } + public Transfer Transfer { get; init; } } -public class EventData +public record DownloadDirectoryCompleteEvent : Event { + public string LocalDirectoryName { get; init; } + public string RemoteFilename { get; init; } + public string Username { get; init; } } /// @@ -35,8 +48,32 @@ public class EventData /// public class EventBus { - public async Task RaiseAsync(EventType type, T data) + private ILogger Log { get; } = Serilog.Log.ForContext(); + private ConcurrentDictionary>> Subscriptions { get; } = new(); + + public async Task RaiseAsync(T data) + where T : Event { + Log.Debug("Handling {Type}: {Data}", typeof(T), data); + + if (!Subscriptions.TryGetValue(typeof(T), out var callbacks)) + { + Log.Debug("No subscribers for {Type}", typeof(T)); + } + // fire and forget on a few levels! there's not much we can (or want to) + // do here, just rely on the continuation to log the error + _ = callbacks.Select(callback => Task.Run(() => + { + _ = callback(data); + }).ContinueWith((task, obj) => + { + Log.Error(task?.Exception, "Error handling {Type}: {Message}", typeof(T), task?.Exception?.Message); + }, TaskContinuationOptions.OnlyOnFaulted)); + } + + public void Subscribe(Func callback) + where T : Event + { } } \ No newline at end of file diff --git a/src/slskd/Tasks/TaskService.cs b/src/slskd/Tasks/TaskService.cs new file mode 100644 index 00000000..e69de29b diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 69e2d2c4..32493422 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -122,7 +122,8 @@ namespace slskd.Transfers.Downloads IDbContextFactory contextFactory, FileService fileService, IRelayService relayService, - IFTPService ftpClient) + IFTPService ftpClient, + EventBus eventBus) { Client = soulseekClient; OptionsMonitor = optionsMonitor; @@ -130,6 +131,7 @@ namespace slskd.Transfers.Downloads Files = fileService; FTP = ftpClient; Relay = relayService; + Events = eventBus; } private ConcurrentDictionary CancellationTokens { get; } = new ConcurrentDictionary(); @@ -140,6 +142,7 @@ namespace slskd.Transfers.Downloads private IRelayService Relay { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); private IOptionsMonitor OptionsMonitor { get; } + private EventBus Events { get; } /// /// Adds the specified . Supersedes any existing record for the same file and username. @@ -332,6 +335,7 @@ namespace slskd.Transfers.Downloads } // todo: raise DOWNLOAD_FILE_COMPLETE + Events.Downloads.FileComplete?.Invoke() // todo: determine if there are any pending transfers in this same directory, and if not raise DOWNLOAD_DIRECTORY_COMPLETE if (OptionsMonitor.CurrentValue.Integration.Ftp.Enabled) diff --git a/src/slskd/Transfers/Types/Transfer.cs b/src/slskd/Transfers/Types/Transfer.cs index 1797adcd..ddb3e017 100644 --- a/src/slskd/Transfers/Types/Transfer.cs +++ b/src/slskd/Transfers/Types/Transfer.cs @@ -29,6 +29,10 @@ namespace slskd.Transfers public Guid Id { get; init; } public string Username { get; init; } public TransferDirection Direction { get; init; } + + /// + /// Gets the remote filename. + /// public string Filename { get; init; } public long Size { get; set; } public long StartOffset { get; init; } diff --git a/src/slskd/Transfers/Types/Upload.cs b/src/slskd/Transfers/Types/Upload.cs index bc2b69b1..9dbd6696 100644 --- a/src/slskd/Transfers/Types/Upload.cs +++ b/src/slskd/Transfers/Types/Upload.cs @@ -30,4 +30,4 @@ namespace slskd.Transfers public TaskCompletionSource TaskCompletionSource { get; set; } = new TaskCompletionSource(); public string Username { get; set; } } -} +} \ No newline at end of file -- cgit v1.2.3 From 9a4bace4c006324fc9aa3d51c48c7ed7c9529957 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 11 Aug 2024 16:46:09 -0500 Subject: add EventBus and events --- src/slskd/Core/EventBus.cs | 122 +++++++++++++++++++++++++++++------------ src/slskd/Core/Types/Events.cs | 39 +++++++++++++ src/slskd/Program.cs | 1 + 3 files changed, 128 insertions(+), 34 deletions(-) create mode 100644 src/slskd/Core/Types/Events.cs diff --git a/src/slskd/Core/EventBus.cs b/src/slskd/Core/EventBus.cs index ee4254ca..730fb848 100644 --- a/src/slskd/Core/EventBus.cs +++ b/src/slskd/Core/EventBus.cs @@ -19,61 +19,115 @@ namespace slskd; using System; using System.Collections.Concurrent; +using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Serilog; -using slskd.Transfers; - -public record Event -{ -} - -public record DownloadFileCompleteEvent : Event -{ - public string LocalFilename { get; init; } - public string RemoteFilename { get; init; } - public string Username { get; init; } - public Transfer Transfer { get; init; } -} - -public record DownloadDirectoryCompleteEvent : Event -{ - public string LocalDirectoryName { get; init; } - public string RemoteFilename { get; init; } - public string Username { get; init; } -} /// -/// The application event bus. +/// The event bus supporting interoperability and ancillary functions. /// +/// +/// +/// This "bus" is meant to mimic an event bus you'd find in a distributed system; fire and forget. If an +/// Exception is encountered while an event is being raised, it will be logged and swallowed. +/// +/// +/// It is also intended to be used *ONLY* for ancillary and/or third party logic that isn't part of the +/// core application. The core application should continue to use regular old C# events and method calls +/// to communicate within and among modules. +/// +/// public class EventBus { private ILogger Log { get; } = Serilog.Log.ForContext(); - private ConcurrentDictionary>> Subscriptions { get; } = new(); - public async Task RaiseAsync(T data) + /// + /// Gets the internal list of event subscriptions. + /// + /// + /// Note that the value is a dictionary to prevent multiple subscriptions from the same subscriber, and to + /// support unsubscribing. + /// + private ConcurrentDictionary>> Subscriptions { get; } = new(); + + /// + /// Raises an event. + /// + /// The event data. + /// The Type of the event. + public virtual void Raise(T data) where T : Event { Log.Debug("Handling {Type}: {Data}", typeof(T), data); - if (!Subscriptions.TryGetValue(typeof(T), out var callbacks)) + if (!Subscriptions.TryGetValue(typeof(T), out var subscribers)) { Log.Debug("No subscribers for {Type}", typeof(T)); } - // fire and forget on a few levels! there's not much we can (or want to) - // do here, just rely on the continuation to log the error - _ = callbacks.Select(callback => Task.Run(() => - { - _ = callback(data); - }).ContinueWith((task, obj) => - { - Log.Error(task?.Exception, "Error handling {Type}: {Message}", typeof(T), task?.Exception?.Message); - }, TaskContinuationOptions.OnlyOnFaulted)); + // we don't care about any of these tasks; contractually we are only obligated to invoke them + _ = subscribers.Select(subscriber => + Task.Run(() => subscriber.Value(data)).ContinueWith(task => + { + Log.Error(task.Exception, "Subscriber {Name} for {Type} encountered an error: {Message}", subscriber.Key, typeof(T), task.Exception.Message); + }, continuationOptions: TaskContinuationOptions.OnlyOnFaulted)); } - public void Subscribe(Func callback) + /// + /// Subscribes a 's to an event. + /// + /// The unique name of the subscriber. + /// The callback function to execute when an event is raised. + /// The Type of the event. + /// Thrown if the specified is null or whitespace. + /// Thrown if the specified is null. + public virtual void Subscribe(string subscriber, Func callback) where T : Event { + ArgumentException.ThrowIfNullOrWhiteSpace(subscriber); + + if (callback is null) + { + throw new ArgumentNullException(nameof(callback)); + } + + Subscriptions.AddOrUpdate( + key: typeof(T), + addValue: new ConcurrentDictionary>( + new Dictionary> { [subscriber] = (Func)callback }), + updateValueFactory: (_, subscribers) => + { + subscribers.AddOrUpdate( + key: subscriber, + addValue: (Func)callback, + updateValueFactory: (_, existingSubscription) => + { + if (existingSubscription is not null) + { + Log.Debug("Warning! {Type} subscriber {Name} attempted to create a redundant subscription. The existing subscription was overwritten.", typeof(T), subscriber); + } + + return (Func)callback; + }); + + return subscribers; + }); + } + + /// + /// Unsubscribes a from an event. + /// + /// + /// Will not throw if a subscription doesn't exist. + /// + /// The Type of the event. + /// The unique name of the subscriber. + public virtual void Unsubscribe(string subscriber) + { + if (Subscriptions.TryGetValue(typeof(T), out var subscriptions)) + { + subscriptions.TryRemove(subscriber, out _); + } } } \ No newline at end of file diff --git a/src/slskd/Core/Types/Events.cs b/src/slskd/Core/Types/Events.cs new file mode 100644 index 00000000..cad97a11 --- /dev/null +++ b/src/slskd/Core/Types/Events.cs @@ -0,0 +1,39 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd; + +using slskd.Transfers; + +public abstract record Event +{ +} + +public sealed record DownloadFileCompleteEvent : Event +{ + public string LocalFilename { get; init; } + public string RemoteFilename { get; init; } + public string Username { get; init; } + public Transfer Transfer { get; init; } +} + +public sealed record DownloadDirectoryCompleteEvent : Event +{ + public string LocalDirectoryName { get; init; } + public string RemoteFilename { get; init; } + public string Username { get; init; } +} \ No newline at end of file diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index d47d3d91..4a6ab38b 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -553,6 +553,7 @@ namespace slskd services.AddHostedService(p => p.GetRequiredService()); services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); -- cgit v1.2.3 From c818b42bb16bf8ade77b1ad20322cf4b30b43bc5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 11 Aug 2024 17:13:55 -0500 Subject: hack shell service in --- src/slskd/Core/EventBus.cs | 18 ++++++++---- src/slskd/Integrations/Shell/ShellService.cs | 42 ++++++++++++++++++++++++++++ src/slskd/Program.cs | 8 +++++- 3 files changed, 62 insertions(+), 6 deletions(-) create mode 100644 src/slskd/Integrations/Shell/ShellService.cs diff --git a/src/slskd/Core/EventBus.cs b/src/slskd/Core/EventBus.cs index 730fb848..9076f947 100644 --- a/src/slskd/Core/EventBus.cs +++ b/src/slskd/Core/EventBus.cs @@ -40,6 +40,11 @@ using Serilog; /// public class EventBus { + public EventBus() + { + Log.Debug("EventBus initialized"); + } + private ILogger Log { get; } = Serilog.Log.ForContext(); /// @@ -49,7 +54,7 @@ public class EventBus /// Note that the value is a dictionary to prevent multiple subscriptions from the same subscriber, and to /// support unsubscribing. /// - private ConcurrentDictionary>> Subscriptions { get; } = new(); + private ConcurrentDictionary>> Subscriptions { get; } = new(); /// /// Raises an event. @@ -64,6 +69,7 @@ public class EventBus if (!Subscriptions.TryGetValue(typeof(T), out var subscribers)) { Log.Debug("No subscribers for {Type}", typeof(T)); + return; } // we don't care about any of these tasks; contractually we are only obligated to invoke them @@ -94,13 +100,13 @@ public class EventBus Subscriptions.AddOrUpdate( key: typeof(T), - addValue: new ConcurrentDictionary>( - new Dictionary> { [subscriber] = (Func)callback }), + addValue: new ConcurrentDictionary>( + new Dictionary> { [subscriber] = (Func)callback }), updateValueFactory: (_, subscribers) => { subscribers.AddOrUpdate( key: subscriber, - addValue: (Func)callback, + addValue: (Func)callback, updateValueFactory: (_, existingSubscription) => { if (existingSubscription is not null) @@ -108,11 +114,13 @@ public class EventBus Log.Debug("Warning! {Type} subscriber {Name} attempted to create a redundant subscription. The existing subscription was overwritten.", typeof(T), subscriber); } - return (Func)callback; + return (Func)callback; }); return subscribers; }); + + Log.Debug("Subscribed {Name} to {Type}", subscriber, typeof(T)); } /// diff --git a/src/slskd/Integrations/Shell/ShellService.cs b/src/slskd/Integrations/Shell/ShellService.cs new file mode 100644 index 00000000..ddb65a53 --- /dev/null +++ b/src/slskd/Integrations/Shell/ShellService.cs @@ -0,0 +1,42 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Integrations.Shell; + +using System; +using System.Threading.Tasks; +using Serilog; + +public class ShellService +{ + public ShellService(EventBus eventBus) + { + Events = eventBus; + + Events.Subscribe(nameof(ShellService), HandleDownloadFileCompleteEvent); + + Log.Debug("Shell service initialized"); + } + + private ILogger Log { get; } = Serilog.Log.ForContext(); + private EventBus Events { get; } + + private async Task HandleDownloadFileCompleteEvent(DownloadFileCompleteEvent data) + { + Console.WriteLine("here is where we would call an external application!"); + } +} \ No newline at end of file diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 4a6ab38b..4a2b1c51 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -39,7 +39,6 @@ namespace slskd using Microsoft.AspNetCore.Diagnostics; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; - using Microsoft.AspNetCore.Mvc.ApiExplorer; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; @@ -60,6 +59,8 @@ namespace slskd using slskd.Files; using slskd.Integrations.FTP; using slskd.Integrations.Pushbullet; + using slskd.Integrations.Shell; + using slskd.Messaging; using slskd.Relay; using slskd.Search; @@ -484,6 +485,9 @@ namespace slskd var app = builder.Build(); + // hack: nothing depends on ShellService but we need to initialize it + _ = app.Services.GetService(); + app.ConfigureAspDotNetPipeline(); if (OptionsAtStartup.Flags.NoStart) @@ -592,6 +596,8 @@ namespace slskd services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); -- cgit v1.2.3 From 8d719c20a32998b1b0ce8c3a59c4b712ed50d455 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 11 Aug 2024 17:14:07 -0500 Subject: raise file download event --- src/slskd/Transfers/Downloads/DownloadService.cs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 32493422..ae4062c0 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -335,7 +335,14 @@ namespace slskd.Transfers.Downloads } // todo: raise DOWNLOAD_FILE_COMPLETE - Events.Downloads.FileComplete?.Invoke() + Events.Raise(new DownloadFileCompleteEvent + { + LocalFilename = finalFilename, + RemoteFilename = transfer.Filename, + Username = transfer.Username, + Transfer = transfer, + }); + // todo: determine if there are any pending transfers in this same directory, and if not raise DOWNLOAD_DIRECTORY_COMPLETE if (OptionsMonitor.CurrentValue.Integration.Ftp.Enabled) -- cgit v1.2.3 From 0f9b9601d96f347e4c011a16a3669f053ae21889 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 11 Aug 2024 17:14:15 -0500 Subject: remove TaskService --- src/slskd/Tasks/TaskService.cs | 0 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 src/slskd/Tasks/TaskService.cs diff --git a/src/slskd/Tasks/TaskService.cs b/src/slskd/Tasks/TaskService.cs deleted file mode 100644 index e69de29b..00000000 -- cgit v1.2.3 From 10219484bc0510fbffa4d359f33ba0635900ce22 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 12 Aug 2024 20:59:20 -0500 Subject: store callbacks as plain objects --- src/slskd/Core/EventBus.cs | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/src/slskd/Core/EventBus.cs b/src/slskd/Core/EventBus.cs index 9076f947..5ac6b0a5 100644 --- a/src/slskd/Core/EventBus.cs +++ b/src/slskd/Core/EventBus.cs @@ -54,7 +54,7 @@ public class EventBus /// Note that the value is a dictionary to prevent multiple subscriptions from the same subscriber, and to /// support unsubscribing. /// - private ConcurrentDictionary>> Subscriptions { get; } = new(); + private ConcurrentDictionary> Subscriptions { get; } = new(); /// /// Raises an event. @@ -72,12 +72,15 @@ public class EventBus return; } + Log.Debug("{Count} subscribers for {Type}", subscribers.Count, typeof(T)); + // we don't care about any of these tasks; contractually we are only obligated to invoke them - _ = subscribers.Select(subscriber => - Task.Run(() => subscriber.Value(data)).ContinueWith(task => - { - Log.Error(task.Exception, "Subscriber {Name} for {Type} encountered an error: {Message}", subscriber.Key, typeof(T), task.Exception.Message); - }, continuationOptions: TaskContinuationOptions.OnlyOnFaulted)); + _ = Task.WhenAll(subscribers.Select(subscriber => + Task.Run(() => (subscriber.Value as Func)(data)) + .ContinueWith(task => + { + Log.Error(task.Exception, "Subscriber {Name} for {Type} encountered an error: {Message}", subscriber.Key, typeof(T), task.Exception.Message); + }))); } /// @@ -100,13 +103,13 @@ public class EventBus Subscriptions.AddOrUpdate( key: typeof(T), - addValue: new ConcurrentDictionary>( - new Dictionary> { [subscriber] = (Func)callback }), + addValue: new ConcurrentDictionary( + new Dictionary { [subscriber] = callback }), updateValueFactory: (_, subscribers) => { subscribers.AddOrUpdate( key: subscriber, - addValue: (Func)callback, + addValue: callback, updateValueFactory: (_, existingSubscription) => { if (existingSubscription is not null) @@ -114,7 +117,7 @@ public class EventBus Log.Debug("Warning! {Type} subscriber {Name} attempted to create a redundant subscription. The existing subscription was overwritten.", typeof(T), subscriber); } - return (Func)callback; + return callback; }); return subscribers; -- cgit v1.2.3 From 82b022b231a65ced183bc0812ba45247392f1486 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 12 Aug 2024 21:01:03 -0500 Subject: simplify --- src/slskd/Core/EventBus.cs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/slskd/Core/EventBus.cs b/src/slskd/Core/EventBus.cs index 5ac6b0a5..a281c9cc 100644 --- a/src/slskd/Core/EventBus.cs +++ b/src/slskd/Core/EventBus.cs @@ -77,10 +77,7 @@ public class EventBus // we don't care about any of these tasks; contractually we are only obligated to invoke them _ = Task.WhenAll(subscribers.Select(subscriber => Task.Run(() => (subscriber.Value as Func)(data)) - .ContinueWith(task => - { - Log.Error(task.Exception, "Subscriber {Name} for {Type} encountered an error: {Message}", subscriber.Key, typeof(T), task.Exception.Message); - }))); + .ContinueWith(task => Log.Error(task.Exception, "Subscriber {Name} for {Type} encountered an error: {Message}", subscriber.Key, typeof(T), task.Exception.Message)))); } /// -- cgit v1.2.3 From 65e3399b3361bb682a03bb4d8b52f3baf390a4ce Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 12 Aug 2024 21:02:41 -0500 Subject: tweak logs --- src/slskd/Core/EventBus.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/slskd/Core/EventBus.cs b/src/slskd/Core/EventBus.cs index a281c9cc..c0952ed8 100644 --- a/src/slskd/Core/EventBus.cs +++ b/src/slskd/Core/EventBus.cs @@ -72,7 +72,7 @@ public class EventBus return; } - Log.Debug("{Count} subscribers for {Type}", subscribers.Count, typeof(T)); + Log.Debug("{Count} subscriber(s) for {Type}: {Names}", subscribers.Count, typeof(T), string.Join(", ", subscribers.Keys)); // we don't care about any of these tasks; contractually we are only obligated to invoke them _ = Task.WhenAll(subscribers.Select(subscriber => -- cgit v1.2.3 From c541bc60e56369bd2b3e20c79e24efa119f29429 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 24 Aug 2024 17:45:59 -0500 Subject: add events db context to DI --- src/slskd/Program.cs | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 4a2b1c51..985095f1 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -56,11 +56,12 @@ namespace slskd using slskd.Configuration; using slskd.Core.API; using slskd.Cryptography; + using slskd.Events; + using slskd.Files; using slskd.Integrations.FTP; using slskd.Integrations.Pushbullet; using slskd.Integrations.Shell; - using slskd.Messaging; using slskd.Relay; using slskd.Search; @@ -563,15 +564,21 @@ namespace slskd if (OptionsAtStartup.Flags.Volatile) { - services.AddDbContext($"Data Source=file:search?mode=memory;Cache=shared;Pooling=True;"); - services.AddDbContext($"Data Source=file:transfers?mode=memory;Cache=shared;Pooling=True;"); - services.AddDbContext($"Data Source=file:messaging?mode=memory;Cache=shared;Pooling=True;"); + static string MemoryConnectionString(string name) => $"Data Source=file:{name}?mode=memory;Cache=shared;Pooling=True;"; + + services.AddDbContext(MemoryConnectionString("search")); + services.AddDbContext(MemoryConnectionString("transfers")); + services.AddDbContext(MemoryConnectionString("messaging")); + services.AddDbContext(MemoryConnectionString("events")); } else { - services.AddDbContext($"Data Source={Path.Combine(DataDirectory, "search.db")};Cache=shared;Pooling=True;"); - services.AddDbContext($"Data Source={Path.Combine(DataDirectory, "transfers.db")};Cache=shared;Pooling=True;"); - services.AddDbContext($"Data Source={Path.Combine(DataDirectory, "messaging.db")};Cache=shared;Pooling=True;"); + static string DiskConnectionString(string name) => $"Data Source={Path.Combine(DataDirectory, $"{name}.db")};Cache=shared;Pooling=True;"; + + services.AddDbContext(DiskConnectionString("search")); + services.AddDbContext(DiskConnectionString("transfers")); + services.AddDbContext(DiskConnectionString("messaging")); + services.AddDbContext(DiskConnectionString("events")); } services.AddSingleton(); -- cgit v1.2.3 From da7371484fcf256eb1efe394593cb6d748043afc Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 24 Aug 2024 17:46:08 -0500 Subject: add dbcontext for events --- src/slskd/Events/EventsDbContext.cs | 41 +++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 src/slskd/Events/EventsDbContext.cs diff --git a/src/slskd/Events/EventsDbContext.cs b/src/slskd/Events/EventsDbContext.cs new file mode 100644 index 00000000..65b09699 --- /dev/null +++ b/src/slskd/Events/EventsDbContext.cs @@ -0,0 +1,41 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +using System; +using Microsoft.EntityFrameworkCore; + +namespace slskd.Events +{ + public class EventsDbContext : DbContext + { + public EventsDbContext(DbContextOptions options) + : base(options) + { + Database.EnsureCreated(); + } + + public DbSet Events { get; set; } + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + modelBuilder + .Entity() + .Property(e => e.Timestamp) + .HasConversion(v => v, v => DateTime.SpecifyKind(v, DateTimeKind.Utc)); + } + } +} \ No newline at end of file -- cgit v1.2.3 From 82af4f0014a45b6e57a3ba314c3498d0ad17400c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 24 Aug 2024 17:46:22 -0500 Subject: move events, add id and timestamp --- src/slskd/Events/Types/Events.cs | 42 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 src/slskd/Events/Types/Events.cs diff --git a/src/slskd/Events/Types/Events.cs b/src/slskd/Events/Types/Events.cs new file mode 100644 index 00000000..7e9080df --- /dev/null +++ b/src/slskd/Events/Types/Events.cs @@ -0,0 +1,42 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd; + +using System; +using slskd.Transfers; + +public record Event +{ + public Guid Id { get; } = Guid.NewGuid(); + public DateTime Timestamp { get; } = DateTime.UtcNow; +} + +public sealed record DownloadFileCompleteEvent : Event +{ + public string LocalFilename { get; init; } + public string RemoteFilename { get; init; } + public string Username { get; init; } + public Transfer Transfer { get; init; } +} + +public sealed record DownloadDirectoryCompleteEvent : Event +{ + public string LocalDirectoryName { get; init; } + public string RemoteFilename { get; init; } + public string Username { get; init; } +} \ No newline at end of file -- cgit v1.2.3 From 773ad74900353da845ef6f954ff1383d92322529 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 24 Aug 2024 17:46:36 -0500 Subject: add eventrecord to model database --- src/slskd/Events/Types/EventRecord.cs | 81 +++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 src/slskd/Events/Types/EventRecord.cs diff --git a/src/slskd/Events/Types/EventRecord.cs b/src/slskd/Events/Types/EventRecord.cs new file mode 100644 index 00000000..b5bc5bd0 --- /dev/null +++ b/src/slskd/Events/Types/EventRecord.cs @@ -0,0 +1,81 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Events; + +using System; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text.Encodings.Web; +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Text.Json.Serialization; + +public record EventRecord +{ + public DateTime Timestamp { get; init; } = DateTime.UtcNow; + public string Type { get; private set; } + public string Data { get; init; } + [Key] + public Guid Id { get; private set; } + + private static JsonSerializerOptions JsonSerializerOptions { get; } = new JsonSerializerOptions() + { + PropertyNameCaseInsensitive = true, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, + WriteIndented = false, + }; + + /// + /// Converts the specified event into an instance of + /// for the purpose of database storage. + /// + /// + /// The property contains the event-specific data serialized as json, applying + /// standard formatting such as camel cased property names and null value omission. This is important so that + /// the values stored in the database will match the values exposed through other means. Maybe not *that* important, + /// but standardizing json is a good practice. + /// + /// The Event to convert. + /// The specific type of the Event. + /// The converted EventRecord. + public static EventRecord From(Event e) + where T : Event + { + // this will be 'slskd.NameOfEvent'; we want to chop off 'slskd.' and 'Event' = 'NameOf' + var type = e.GetType().Name.Split('.').TakeLast(1).First(); + type = type.Substring(0, type.Length - nameof(Event).Length); + + // construct the data for the record by serializing the event and removing redundant properties + var json = JsonSerializer.Serialize(e as T, JsonSerializerOptions); + var data = JsonNode.Parse(json).AsObject(); + data.Remove(nameof(Timestamp).ToLower()); + data.Remove(nameof(Type).ToLower()); + data.Remove(nameof(Id).ToLower()); + data.Remove(nameof(Data).ToLower()); + + return new EventRecord + { + Timestamp = e.Timestamp, + Type = type, + Id = e.Id, + Data = data.ToJsonString(JsonSerializerOptions), + }; + } +} \ No newline at end of file -- cgit v1.2.3 From d253bc167961a8d46acaef52d5e5184f03f28dd4 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 24 Aug 2024 17:46:47 -0500 Subject: move out of core --- src/slskd/Core/EventBus.cs | 141 ----------------------------------------- src/slskd/Core/Types/Events.cs | 39 ------------ 2 files changed, 180 deletions(-) delete mode 100644 src/slskd/Core/EventBus.cs delete mode 100644 src/slskd/Core/Types/Events.cs diff --git a/src/slskd/Core/EventBus.cs b/src/slskd/Core/EventBus.cs deleted file mode 100644 index c0952ed8..00000000 --- a/src/slskd/Core/EventBus.cs +++ /dev/null @@ -1,141 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd; - -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using Serilog; - -/// -/// The event bus supporting interoperability and ancillary functions. -/// -/// -/// -/// This "bus" is meant to mimic an event bus you'd find in a distributed system; fire and forget. If an -/// Exception is encountered while an event is being raised, it will be logged and swallowed. -/// -/// -/// It is also intended to be used *ONLY* for ancillary and/or third party logic that isn't part of the -/// core application. The core application should continue to use regular old C# events and method calls -/// to communicate within and among modules. -/// -/// -public class EventBus -{ - public EventBus() - { - Log.Debug("EventBus initialized"); - } - - private ILogger Log { get; } = Serilog.Log.ForContext(); - - /// - /// Gets the internal list of event subscriptions. - /// - /// - /// Note that the value is a dictionary to prevent multiple subscriptions from the same subscriber, and to - /// support unsubscribing. - /// - private ConcurrentDictionary> Subscriptions { get; } = new(); - - /// - /// Raises an event. - /// - /// The event data. - /// The Type of the event. - public virtual void Raise(T data) - where T : Event - { - Log.Debug("Handling {Type}: {Data}", typeof(T), data); - - if (!Subscriptions.TryGetValue(typeof(T), out var subscribers)) - { - Log.Debug("No subscribers for {Type}", typeof(T)); - return; - } - - Log.Debug("{Count} subscriber(s) for {Type}: {Names}", subscribers.Count, typeof(T), string.Join(", ", subscribers.Keys)); - - // we don't care about any of these tasks; contractually we are only obligated to invoke them - _ = Task.WhenAll(subscribers.Select(subscriber => - Task.Run(() => (subscriber.Value as Func)(data)) - .ContinueWith(task => Log.Error(task.Exception, "Subscriber {Name} for {Type} encountered an error: {Message}", subscriber.Key, typeof(T), task.Exception.Message)))); - } - - /// - /// Subscribes a 's to an event. - /// - /// The unique name of the subscriber. - /// The callback function to execute when an event is raised. - /// The Type of the event. - /// Thrown if the specified is null or whitespace. - /// Thrown if the specified is null. - public virtual void Subscribe(string subscriber, Func callback) - where T : Event - { - ArgumentException.ThrowIfNullOrWhiteSpace(subscriber); - - if (callback is null) - { - throw new ArgumentNullException(nameof(callback)); - } - - Subscriptions.AddOrUpdate( - key: typeof(T), - addValue: new ConcurrentDictionary( - new Dictionary { [subscriber] = callback }), - updateValueFactory: (_, subscribers) => - { - subscribers.AddOrUpdate( - key: subscriber, - addValue: callback, - updateValueFactory: (_, existingSubscription) => - { - if (existingSubscription is not null) - { - Log.Debug("Warning! {Type} subscriber {Name} attempted to create a redundant subscription. The existing subscription was overwritten.", typeof(T), subscriber); - } - - return callback; - }); - - return subscribers; - }); - - Log.Debug("Subscribed {Name} to {Type}", subscriber, typeof(T)); - } - - /// - /// Unsubscribes a from an event. - /// - /// - /// Will not throw if a subscription doesn't exist. - /// - /// The Type of the event. - /// The unique name of the subscriber. - public virtual void Unsubscribe(string subscriber) - { - if (Subscriptions.TryGetValue(typeof(T), out var subscriptions)) - { - subscriptions.TryRemove(subscriber, out _); - } - } -} \ No newline at end of file diff --git a/src/slskd/Core/Types/Events.cs b/src/slskd/Core/Types/Events.cs deleted file mode 100644 index cad97a11..00000000 --- a/src/slskd/Core/Types/Events.cs +++ /dev/null @@ -1,39 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd; - -using slskd.Transfers; - -public abstract record Event -{ -} - -public sealed record DownloadFileCompleteEvent : Event -{ - public string LocalFilename { get; init; } - public string RemoteFilename { get; init; } - public string Username { get; init; } - public Transfer Transfer { get; init; } -} - -public sealed record DownloadDirectoryCompleteEvent : Event -{ - public string LocalDirectoryName { get; init; } - public string RemoteFilename { get; init; } - public string Username { get; init; } -} \ No newline at end of file -- cgit v1.2.3 From c0fbdc7a423ffdc573ce9117faabab0646d35520 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 24 Aug 2024 17:47:02 -0500 Subject: persist events prior to broadcast --- src/slskd/Events/EventBus.cs | 157 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 157 insertions(+) create mode 100644 src/slskd/Events/EventBus.cs diff --git a/src/slskd/Events/EventBus.cs b/src/slskd/Events/EventBus.cs new file mode 100644 index 00000000..15f75fd0 --- /dev/null +++ b/src/slskd/Events/EventBus.cs @@ -0,0 +1,157 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd; + +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using Serilog; +using slskd.Events; + +/// +/// The event bus supporting interoperability and ancillary functions. +/// +/// +/// +/// This "bus" is meant to mimic an event bus you'd find in a distributed system; fire and forget. If an +/// Exception is encountered while an event is being raised, it will be logged and swallowed. +/// +/// +/// It is also intended to be used *ONLY* for ancillary and/or third party logic that isn't part of the +/// core application. The core application should continue to use regular old C# events and method calls +/// to communicate within and among modules. +/// +/// +/// This design was chosen over built-in C# events to give greater control over how events are dispatched, +/// and bound. +/// +/// +public class EventBus +{ + /// + /// Initializes a new instance of the class. + /// + /// + public EventBus(IDbContextFactory contextFactory) + { + ContextFactory = contextFactory; + } + + private ILogger Log { get; } = Serilog.Log.ForContext(); + private IDbContextFactory ContextFactory { get; } + + /// + /// Gets the internal list of event subscriptions. + /// + /// + /// Note that the value is a dictionary to prevent multiple subscriptions from the same subscriber, and to + /// support unsubscribing. + /// + private ConcurrentDictionary> Subscriptions { get; } = new(); + + /// + /// Raises an event. + /// + /// The event data. + /// The Type of the event. + public virtual void Raise(T data) + where T : Event + { + Log.Debug("Handling {Type}: {Data}", typeof(T), data); + + // save the event to the database before broadcasting to consumers + var ctx = ContextFactory.CreateDbContext(); + ctx.Add(EventRecord.From(data)); + ctx.SaveChanges(); + + // broadcast the event in a fire-and-forget fashion + // we don't need to wait for anything, just need to kick off the tasks + // if something throws it will be logged and the consumer can figure it out + if (Subscriptions.TryGetValue(typeof(T), out var subscribers)) + { + Log.Debug("{Count} subscriber(s) for {Type}: {Names}", subscribers.Count, typeof(T), string.Join(", ", subscribers.Keys)); + + // we don't care about any of these tasks; contractually we are only obligated to invoke them + _ = Task.WhenAll(subscribers.Select(subscriber => + Task.Run(() => (subscriber.Value as Func)(data)) + .ContinueWith(task => Log.Error(task.Exception, "Subscriber {Name} for {Type} encountered an error: {Message}", subscriber.Key, typeof(T), task.Exception.Message)))); + } + } + + /// + /// Subscribes a 's to an event. + /// + /// The unique name of the subscriber. + /// The callback function to execute when an event is raised. + /// The Type of the event. + /// Thrown if the specified is null or whitespace. + /// Thrown if the specified is null. + public virtual void Subscribe(string subscriber, Func callback) + where T : Event + { + ArgumentException.ThrowIfNullOrWhiteSpace(subscriber); + + if (callback is null) + { + throw new ArgumentNullException(nameof(callback)); + } + + Subscriptions.AddOrUpdate( + key: typeof(T), + addValue: new ConcurrentDictionary( + new Dictionary { [subscriber] = callback }), + updateValueFactory: (_, subscribers) => + { + subscribers.AddOrUpdate( + key: subscriber, + addValue: callback, + updateValueFactory: (_, existingSubscription) => + { + if (existingSubscription is not null) + { + Log.Debug("Warning! {Type} subscriber {Name} attempted to create a redundant subscription. The existing subscription was overwritten.", typeof(T), subscriber); + } + + return callback; + }); + + return subscribers; + }); + + Log.Debug("Subscribed {Name} to {Type}", subscriber, typeof(T)); + } + + /// + /// Unsubscribes a from an event. + /// + /// + /// Will not throw if a subscription doesn't exist. + /// + /// The Type of the event. + /// The unique name of the subscriber. + public virtual void Unsubscribe(string subscriber) + { + if (Subscriptions.TryGetValue(typeof(T), out var subscriptions)) + { + subscriptions.TryRemove(subscriber, out _); + } + } +} \ No newline at end of file -- cgit v1.2.3 From db06192dda4369a7a2cb97e74d20ebac771c02c6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 25 Aug 2024 17:33:19 -0500 Subject: fix namespaces --- src/slskd/Events/EventBus.cs | 3 +-- src/slskd/Events/EventsDbContext.cs | 29 ++++++++++++++--------------- 2 files changed, 15 insertions(+), 17 deletions(-) diff --git a/src/slskd/Events/EventBus.cs b/src/slskd/Events/EventBus.cs index 15f75fd0..b38591b3 100644 --- a/src/slskd/Events/EventBus.cs +++ b/src/slskd/Events/EventBus.cs @@ -15,7 +15,7 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // -namespace slskd; +namespace slskd.Events; using System; using System.Collections.Concurrent; @@ -24,7 +24,6 @@ using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Serilog; -using slskd.Events; /// /// The event bus supporting interoperability and ancillary functions. diff --git a/src/slskd/Events/EventsDbContext.cs b/src/slskd/Events/EventsDbContext.cs index 65b09699..9acbc9a4 100644 --- a/src/slskd/Events/EventsDbContext.cs +++ b/src/slskd/Events/EventsDbContext.cs @@ -15,27 +15,26 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // +namespace slskd.Events; + using System; using Microsoft.EntityFrameworkCore; -namespace slskd.Events +public class EventsDbContext : DbContext { - public class EventsDbContext : DbContext + public EventsDbContext(DbContextOptions options) + : base(options) { - public EventsDbContext(DbContextOptions options) - : base(options) - { - Database.EnsureCreated(); - } + Database.EnsureCreated(); + } - public DbSet Events { get; set; } + public DbSet Events { get; set; } - protected override void OnModelCreating(ModelBuilder modelBuilder) - { - modelBuilder - .Entity() - .Property(e => e.Timestamp) - .HasConversion(v => v, v => DateTime.SpecifyKind(v, DateTimeKind.Utc)); - } + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + modelBuilder + .Entity() + .Property(e => e.Timestamp) + .HasConversion(v => v, v => DateTime.SpecifyKind(v, DateTimeKind.Utc)); } } \ No newline at end of file -- cgit v1.2.3 From 8af2d0b847d55121269f4a741f90f10305139cde Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 1 Sep 2024 18:41:00 -0500 Subject: add some new extensions for path manipulation --- src/slskd/Common/CommonExtensions.cs | 37 +++++++++++++++++++++++++++++++++--- 1 file changed, 34 insertions(+), 3 deletions(-) diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs index a68ce2f2..44e3c034 100644 --- a/src/slskd/Common/CommonExtensions.cs +++ b/src/slskd/Common/CommonExtensions.cs @@ -132,6 +132,39 @@ namespace slskd return differences; } + /// + /// Makes a best-guess determination of the directory separator character used by a remote system, + /// based on the characters present in the specified . + /// + /// The fully qualified remote filename to inspect. + /// The guessed directory separator. + public static char GuessDirectorySeparator(this string remoteFilename) + { + // forward slash is a forbidden character on all operating systems; if the specified string contains it, + // then it is coming from the OS's directory separator + if (remoteFilename.Contains('/')) + { + return '/'; + } + + // if the given string doesn't contain any forward slashes, it either lacks a directory separator at all + // (potentially impossible?) or it is using backspaces. backspaces are used by all major clients, so + // this should be a safe assumption. + return '\\'; + } + + /// + /// Returns the directory name of the given , using the specified + /// to split and join directories and filename. + /// + /// The path for which to return the directory name. + /// The directory separator character. + /// The specified path, less the last segment. + public static string GetDirectoryName(this string path, char directorySeparator) + { + return string.Join(directorySeparator, path.Split(directorySeparator).SkipLast(1)); + } + /// /// Returns the directory from the given path, regardless of separator format. /// @@ -139,9 +172,7 @@ namespace slskd /// The directory. public static string DirectoryName(this string path) { - var separator = path.Contains('\\') ? '\\' : '/'; - var parts = path.Split(separator); - return string.Join(separator, parts.Take(parts.Length - 1)); + return path.GetDirectoryName(path.GuessDirectorySeparator()); } /// -- cgit v1.2.3 From d7ac846e4f3832e3897228c5d46ca0d5cd5ae80f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 1 Sep 2024 18:41:19 -0500 Subject: log when there are no subscribers for an event --- src/slskd/Events/EventBus.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/slskd/Events/EventBus.cs b/src/slskd/Events/EventBus.cs index b38591b3..d51e2fd7 100644 --- a/src/slskd/Events/EventBus.cs +++ b/src/slskd/Events/EventBus.cs @@ -93,6 +93,10 @@ public class EventBus Task.Run(() => (subscriber.Value as Func)(data)) .ContinueWith(task => Log.Error(task.Exception, "Subscriber {Name} for {Type} encountered an error: {Message}", subscriber.Key, typeof(T), task.Exception.Message)))); } + else + { + Log.Debug("No subscribers for {Type}", typeof(T)); + } } /// -- cgit v1.2.3 From c66f7a23c321b0b110b035df228093722f7c857a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 1 Sep 2024 18:41:39 -0500 Subject: include remote directory name, not filename --- src/slskd/Events/Types/Events.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/slskd/Events/Types/Events.cs b/src/slskd/Events/Types/Events.cs index 7e9080df..e54c2abe 100644 --- a/src/slskd/Events/Types/Events.cs +++ b/src/slskd/Events/Types/Events.cs @@ -37,6 +37,6 @@ public sealed record DownloadFileCompleteEvent : Event public sealed record DownloadDirectoryCompleteEvent : Event { public string LocalDirectoryName { get; init; } - public string RemoteFilename { get; init; } + public string RemoteDirectoryName { get; init; } public string Username { get; init; } } \ No newline at end of file -- cgit v1.2.3 From 82e1ae5f13aec70548bd7fc98e4d4a35e682f6df Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 1 Sep 2024 18:41:58 -0500 Subject: subscribe to directory event in shell service --- src/slskd/Integrations/Shell/ShellService.cs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/slskd/Integrations/Shell/ShellService.cs b/src/slskd/Integrations/Shell/ShellService.cs index ddb65a53..baed28f8 100644 --- a/src/slskd/Integrations/Shell/ShellService.cs +++ b/src/slskd/Integrations/Shell/ShellService.cs @@ -20,6 +20,7 @@ namespace slskd.Integrations.Shell; using System; using System.Threading.Tasks; using Serilog; +using slskd.Events; public class ShellService { @@ -28,6 +29,7 @@ public class ShellService Events = eventBus; Events.Subscribe(nameof(ShellService), HandleDownloadFileCompleteEvent); + Events.Subscribe(nameof(ShellService), HandleDownloadDirectoryCompleteEvent); Log.Debug("Shell service initialized"); } @@ -39,4 +41,9 @@ public class ShellService { Console.WriteLine("here is where we would call an external application!"); } + + private async Task HandleDownloadDirectoryCompleteEvent(DownloadDirectoryCompleteEvent data) + { + Console.WriteLine("wow we downloaded a whole directory"); + } } \ No newline at end of file -- cgit v1.2.3 From 45e24f623a6cf5d7d9a400b7f8bc07809e8993d0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 1 Sep 2024 18:42:28 -0500 Subject: use events namespace, rename Events to EventBus --- src/slskd/Transfers/Downloads/DownloadService.cs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index ae4062c0..3864c3a5 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -29,6 +29,7 @@ namespace slskd.Transfers.Downloads using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Serilog; + using slskd.Events; using slskd.Files; using slskd.Integrations.FTP; using slskd.Relay; @@ -131,7 +132,7 @@ namespace slskd.Transfers.Downloads Files = fileService; FTP = ftpClient; Relay = relayService; - Events = eventBus; + EventBus = eventBus; } private ConcurrentDictionary CancellationTokens { get; } = new ConcurrentDictionary(); @@ -142,7 +143,7 @@ namespace slskd.Transfers.Downloads private IRelayService Relay { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); private IOptionsMonitor OptionsMonitor { get; } - private EventBus Events { get; } + private EventBus EventBus { get; } /// /// Adds the specified . Supersedes any existing record for the same file and username. -- cgit v1.2.3 From c82c64fa3c2df97d09b37d721ac7ce0eccec216c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 1 Sep 2024 18:43:00 -0500 Subject: clarify todos --- src/slskd/Transfers/Downloads/DownloadService.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 3864c3a5..92ab061f 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -285,7 +285,7 @@ namespace slskd.Transfers.Downloads { transfer = transfer.WithSoulseekTransfer(args.Transfer); - // todo: broadcast + // todo: broadcast to signalr hub SynchronizedUpdate(transfer); })); @@ -316,7 +316,7 @@ namespace slskd.Transfers.Downloads transfer = transfer.WithSoulseekTransfer(completedTransfer); - // todo: broadcast + // todo: broadcast to signalr hub SynchronizedUpdate(transfer, cancellable: false); // this would be the ideal place to hook in a generic post-download task processor for now, we'll @@ -357,7 +357,7 @@ namespace slskd.Transfers.Downloads transfer.Exception = ex.Message; transfer.State = TransferStates.Completed | TransferStates.Cancelled; - // todo: broadcast + // todo: broadcast to signalr hub SynchronizedUpdate(transfer, cancellable: false); throw; @@ -370,7 +370,7 @@ namespace slskd.Transfers.Downloads transfer.Exception = ex.Message; transfer.State = TransferStates.Completed | TransferStates.Errored; - // todo: broadcast + // todo: broadcast to signalr hub SynchronizedUpdate(transfer, cancellable: false); throw; -- cgit v1.2.3 From 75d6377548ce946189d86aa9433281132ce58195 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 1 Sep 2024 18:43:31 -0500 Subject: pull out destinationDirectory --- src/slskd/Transfers/Downloads/DownloadService.cs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 92ab061f..00d6dbbc 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -319,12 +319,11 @@ namespace slskd.Transfers.Downloads // todo: broadcast to signalr hub SynchronizedUpdate(transfer, cancellable: false); - // this would be the ideal place to hook in a generic post-download task processor for now, we'll - // just carry out hard coded behavior. these carry the risk of failing the transfer, and i could - // argue both ways for that being the correct behavior. revisit this later. + var destinationDirectory = System.IO.Path.GetDirectoryName(file.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Downloads)); + var finalFilename = Files.MoveFile( sourceFilename: file.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Incomplete), - destinationDirectory: System.IO.Path.GetDirectoryName(file.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Downloads)), + destinationDirectory: destinationDirectory, overwrite: false, deleteSourceDirectoryIfEmptyAfterMove: true); -- cgit v1.2.3 From 59de4b493724b6c863c0666f56524398dc6a9594 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 1 Sep 2024 18:44:53 -0500 Subject: raise DownloadDirectoryCompleteEvent when final file from directory is completed --- src/slskd/Transfers/Downloads/DownloadService.cs | 26 ++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 00d6dbbc..5a32f6fe 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -329,13 +329,14 @@ namespace slskd.Transfers.Downloads Log.Debug("Moved file to {Destination}", finalFilename); + // begin post-processing tasks; the file is downloaded, it has been removed from the client's download dictionary, + // and the file has been moved from the incomplete directory to the downloads directory if (OptionsMonitor.CurrentValue.Relay.Enabled) { _ = Relay.NotifyFileDownloadCompleteAsync(finalFilename); } - // todo: raise DOWNLOAD_FILE_COMPLETE - Events.Raise(new DownloadFileCompleteEvent + EventBus.Raise(new DownloadFileCompleteEvent { LocalFilename = finalFilename, RemoteFilename = transfer.Filename, @@ -343,7 +344,24 @@ namespace slskd.Transfers.Downloads Transfer = transfer, }); - // todo: determine if there are any pending transfers in this same directory, and if not raise DOWNLOAD_DIRECTORY_COMPLETE + // try to figure out if this file is the last of a directory, and if so, raise the associated + // event. this can be tricky because we want to be sure that this is the last file in this specific + // directory, excluding any pending downloads in a subdirectory. + var remoteDirectorySeparator = transfer.Filename.GuessDirectorySeparator(); + var remoteDirectoryName = transfer.Filename.GetDirectoryName(directorySeparator: remoteDirectorySeparator); + var pendingDownloadsInDirectory = Client.Downloads + .Where(t => t.Username == transfer.Username) + .Where(t => t.Filename.GetDirectoryName(directorySeparator: remoteDirectorySeparator) == remoteDirectoryName); + + if (!pendingDownloadsInDirectory.Any()) + { + EventBus.Raise(new DownloadDirectoryCompleteEvent + { + LocalDirectoryName = destinationDirectory, + RemoteDirectoryName = remoteDirectoryName, + Username = transfer.Username, + }); + } if (OptionsMonitor.CurrentValue.Integration.Ftp.Enabled) { -- cgit v1.2.3 From 4368231d4487c7d0ec85572bf7f1a9343e1d0e83 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 2 Sep 2024 17:50:39 -0500 Subject: add indexes --- src/slskd/Events/Types/EventRecord.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/slskd/Events/Types/EventRecord.cs b/src/slskd/Events/Types/EventRecord.cs index b5bc5bd0..8ca0ff4d 100644 --- a/src/slskd/Events/Types/EventRecord.cs +++ b/src/slskd/Events/Types/EventRecord.cs @@ -24,7 +24,10 @@ using System.Text.Encodings.Web; using System.Text.Json; using System.Text.Json.Nodes; using System.Text.Json.Serialization; +using Microsoft.EntityFrameworkCore; +[Index(nameof(Timestamp))] +[Index(nameof(Type))] public record EventRecord { public DateTime Timestamp { get; init; } = DateTime.UtcNow; -- cgit v1.2.3 From 6e16b8727a8f15dfe6d1ef0a8064c5a9400ce514 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 2 Sep 2024 17:51:06 -0500 Subject: make Timestamp settable --- src/slskd/Events/Types/Events.cs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/slskd/Events/Types/Events.cs b/src/slskd/Events/Types/Events.cs index e54c2abe..bcfdb8d3 100644 --- a/src/slskd/Events/Types/Events.cs +++ b/src/slskd/Events/Types/Events.cs @@ -15,7 +15,7 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // -namespace slskd; +namespace slskd.Events; using System; using slskd.Transfers; @@ -23,14 +23,13 @@ using slskd.Transfers; public record Event { public Guid Id { get; } = Guid.NewGuid(); - public DateTime Timestamp { get; } = DateTime.UtcNow; + public DateTime Timestamp { get; init; } = DateTime.UtcNow; } public sealed record DownloadFileCompleteEvent : Event { public string LocalFilename { get; init; } public string RemoteFilename { get; init; } - public string Username { get; init; } public Transfer Transfer { get; init; } } -- cgit v1.2.3 From 9dac9a07ea15a2a4dceb43703ee3cac879be6619 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 2 Sep 2024 17:51:15 -0500 Subject: tweak event init props --- src/slskd/Transfers/Downloads/DownloadService.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 5a32f6fe..37df355c 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -338,9 +338,9 @@ namespace slskd.Transfers.Downloads EventBus.Raise(new DownloadFileCompleteEvent { + Timestamp = transfer.EndedAt.Value, LocalFilename = finalFilename, RemoteFilename = transfer.Filename, - Username = transfer.Username, Transfer = transfer, }); @@ -357,9 +357,10 @@ namespace slskd.Transfers.Downloads { EventBus.Raise(new DownloadDirectoryCompleteEvent { + Timestamp = transfer.EndedAt.Value, + Username = transfer.Username, LocalDirectoryName = destinationDirectory, RemoteDirectoryName = remoteDirectoryName, - Username = transfer.Username, }); } -- cgit v1.2.3 From 453ac03bf30d4581477065d3f317dfd8fc50ed7b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 2 Sep 2024 18:24:05 -0500 Subject: add retention option for events --- config/slskd.example.yml | 3 ++- src/slskd/Core/Options.cs | 6 ++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/config/slskd.example.yml b/config/slskd.example.yml index 5f028582..d4f99b21 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -168,7 +168,8 @@ # files: # complete: 20160 # 2 weeks # incomplete: 43200 # 30 days -# logs: 259200 # 180 days +# events: 30 # days +# logs: 180 # days # logger: # disk: false # no_color: false diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index cad58817..17c017f7 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1322,6 +1322,12 @@ namespace slskd [Validate] public FileRetentionOptions Files { get; init; } = new FileRetentionOptions(); + /// + /// Gets the time to retain events, in days. + /// + [Range(1, maximum: int.MaxValue)] + public int Events { get; init; } = 30; + /// /// Gets the time to retain logs, in days. /// -- cgit v1.2.3 From 9657cb704b3a26f6e082331e8dcba14507e2cf53 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 2 Sep 2024 18:24:17 -0500 Subject: add EventService --- src/slskd/Events/EventService.cs | 95 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 src/slskd/Events/EventService.cs diff --git a/src/slskd/Events/EventService.cs b/src/slskd/Events/EventService.cs new file mode 100644 index 00000000..c10f0d32 --- /dev/null +++ b/src/slskd/Events/EventService.cs @@ -0,0 +1,95 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +using System; +using System.Linq; +using Microsoft.EntityFrameworkCore; +using Serilog; + +namespace slskd.Events; + +/// +/// Manages events. +/// +public class EventService +{ + /// + /// Initializes a new instance of the class. + /// + /// + public EventService(IDbContextFactory contextFactory) + { + ContextFactory = contextFactory; + } + + private IDbContextFactory ContextFactory { get; } + private ILogger Log { get; } = Serilog.Log.ForContext(); + + /// + /// Adds the specified event . + /// + /// The record to add. + /// Thrown when the specified record is null. + public virtual void Add(EventRecord record) + { + if (record is null) + { + throw new ArgumentNullException(nameof(record)); + } + + try + { + using var context = ContextFactory.CreateDbContext(); + context.Add(record); + context.SaveChanges(); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to add event record: {Message}", ex.Message); + throw; + } + } + + /// + /// Removes event records older than the specified . + /// + /// The age after which event records are eligible for pruning, in days. + /// The number of pruned event records. + public virtual int Prune(int ageInDays) + { + try + { + using var context = ContextFactory.CreateDbContext(); + + var cutoffDateTime = DateTime.UtcNow.AddDays(-ageInDays); + + var pruned = context.Events.Where(e => e.Timestamp < cutoffDateTime).ExecuteDelete(); + + if (pruned > 0) + { + Log.Debug("Pruned {Count} expired events", pruned); + } + + return pruned; + } + catch (Exception ex) + { + Log.Error(ex, "Failed to prune events: {Message}", ex.Message); + throw; + } + } +} \ No newline at end of file -- cgit v1.2.3 From 18edc102e0c2a7aca57a98ca27494a93e890c253 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 2 Sep 2024 18:24:28 -0500 Subject: use EventService instead of dbcontext --- src/slskd/Events/EventBus.cs | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/src/slskd/Events/EventBus.cs b/src/slskd/Events/EventBus.cs index d51e2fd7..bc05e1b8 100644 --- a/src/slskd/Events/EventBus.cs +++ b/src/slskd/Events/EventBus.cs @@ -22,7 +22,6 @@ using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using Microsoft.EntityFrameworkCore; using Serilog; /// @@ -48,14 +47,14 @@ public class EventBus /// /// Initializes a new instance of the class. /// - /// - public EventBus(IDbContextFactory contextFactory) + /// + public EventBus(EventService eventService) { - ContextFactory = contextFactory; + Events = eventService; } private ILogger Log { get; } = Serilog.Log.ForContext(); - private IDbContextFactory ContextFactory { get; } + private EventService Events { get; } /// /// Gets the internal list of event subscriptions. @@ -77,9 +76,7 @@ public class EventBus Log.Debug("Handling {Type}: {Data}", typeof(T), data); // save the event to the database before broadcasting to consumers - var ctx = ContextFactory.CreateDbContext(); - ctx.Add(EventRecord.From(data)); - ctx.SaveChanges(); + Events.Add(EventRecord.From(data)); // broadcast the event in a fire-and-forget fashion // we don't need to wait for anything, just need to kick off the tasks -- cgit v1.2.3 From 5296a22f737fb55770835f0e45f9a74b7d96171b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 2 Sep 2024 18:24:41 -0500 Subject: add EventService to DI --- src/slskd/Program.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 985095f1..93734a35 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -558,7 +558,6 @@ namespace slskd services.AddHostedService(p => p.GetRequiredService()); services.AddSingleton(); - services.AddSingleton(); services.AddSingleton(); @@ -581,6 +580,9 @@ namespace slskd services.AddDbContext(DiskConnectionString("events")); } + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(_ => new RoomTracker(messageLimit: 250)); -- cgit v1.2.3 From 0a2c2db6c0a8f2a8325f128b314894e4db8cd369 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 2 Sep 2024 18:33:10 -0500 Subject: newlines --- src/slskd/Application.cs | 4 ++-- src/slskd/Core/Options.cs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 18231ec1..a3d86034 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -1650,4 +1650,4 @@ namespace slskd } } } -} +} \ No newline at end of file diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 17c017f7..97b596d0 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -2221,4 +2221,4 @@ namespace slskd } } } -} +} \ No newline at end of file -- cgit v1.2.3 From 51836f520fe400a33ad9daab932f13c2ed24467d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 2 Sep 2024 18:34:20 -0500 Subject: rename types --- src/slskd/Events/EventBus.cs | 4 +- src/slskd/Events/EventService.cs | 12 ++--- src/slskd/Events/Types/Event.cs | 84 +++++++++++++++++++++++++++++++++++ src/slskd/Events/Types/EventRecord.cs | 84 ----------------------------------- src/slskd/Events/Types/Events.cs | 6 +-- 5 files changed, 95 insertions(+), 95 deletions(-) create mode 100644 src/slskd/Events/Types/Event.cs delete mode 100644 src/slskd/Events/Types/EventRecord.cs diff --git a/src/slskd/Events/EventBus.cs b/src/slskd/Events/EventBus.cs index bc05e1b8..c3e418e7 100644 --- a/src/slskd/Events/EventBus.cs +++ b/src/slskd/Events/EventBus.cs @@ -71,12 +71,12 @@ public class EventBus /// The event data. /// The Type of the event. public virtual void Raise(T data) - where T : Event + where T : BaseEvent { Log.Debug("Handling {Type}: {Data}", typeof(T), data); // save the event to the database before broadcasting to consumers - Events.Add(EventRecord.From(data)); + Events.Add(Event.From(data)); // broadcast the event in a fire-and-forget fashion // we don't need to wait for anything, just need to kick off the tasks diff --git a/src/slskd/Events/EventService.cs b/src/slskd/Events/EventService.cs index c10f0d32..759dc8cf 100644 --- a/src/slskd/Events/EventService.cs +++ b/src/slskd/Events/EventService.cs @@ -40,21 +40,21 @@ public class EventService private ILogger Log { get; } = Serilog.Log.ForContext(); /// - /// Adds the specified event . + /// Adds the specified event . /// - /// The record to add. + /// The record to add. /// Thrown when the specified record is null. - public virtual void Add(EventRecord record) + public virtual void Add(Event @event) { - if (record is null) + if (@event is null) { - throw new ArgumentNullException(nameof(record)); + throw new ArgumentNullException(nameof(@event)); } try { using var context = ContextFactory.CreateDbContext(); - context.Add(record); + context.Add(@event); context.SaveChanges(); } catch (Exception ex) diff --git a/src/slskd/Events/Types/Event.cs b/src/slskd/Events/Types/Event.cs new file mode 100644 index 00000000..5b57aa5d --- /dev/null +++ b/src/slskd/Events/Types/Event.cs @@ -0,0 +1,84 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Events; + +using System; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text.Encodings.Web; +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Text.Json.Serialization; +using Microsoft.EntityFrameworkCore; + +[Index(nameof(Timestamp))] +[Index(nameof(Type))] +public record Event +{ + public DateTime Timestamp { get; init; } = DateTime.UtcNow; + public string Type { get; private set; } + public string Data { get; init; } + [Key] + public Guid Id { get; private set; } + + private static JsonSerializerOptions JsonSerializerOptions { get; } = new JsonSerializerOptions() + { + PropertyNameCaseInsensitive = true, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, + WriteIndented = false, + }; + + /// + /// Converts the specified event into an instance of + /// for the purpose of database storage. + /// + /// + /// The property contains the event-specific data serialized as json, applying + /// standard formatting such as camel cased property names and null value omission. This is important so that + /// the values stored in the database will match the values exposed through other means. Maybe not *that* important, + /// but standardizing json is a good practice. + /// + /// The Event to convert. + /// The specific type of the Event. + /// The converted EventRecord. + public static Event From(BaseEvent e) + where T : BaseEvent + { + // this will be 'slskd.NameOfEvent'; we want to chop off 'slskd.' and 'Event' = 'NameOf' + var type = e.GetType().Name.Split('.').TakeLast(1).First(); + type = type.Substring(0, type.Length - "Event".Length); // chop off "Event" suffix + + // construct the data for the record by serializing the event and removing redundant properties + var json = JsonSerializer.Serialize(e as T, JsonSerializerOptions); + var data = JsonNode.Parse(json).AsObject(); + data.Remove(nameof(Timestamp).ToLower()); + data.Remove(nameof(Type).ToLower()); + data.Remove(nameof(Id).ToLower()); + data.Remove(nameof(Data).ToLower()); + + return new Event + { + Timestamp = e.Timestamp, + Type = type, + Id = e.Id, + Data = data.ToJsonString(JsonSerializerOptions), + }; + } +} \ No newline at end of file diff --git a/src/slskd/Events/Types/EventRecord.cs b/src/slskd/Events/Types/EventRecord.cs deleted file mode 100644 index 8ca0ff4d..00000000 --- a/src/slskd/Events/Types/EventRecord.cs +++ /dev/null @@ -1,84 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Events; - -using System; -using System.ComponentModel.DataAnnotations; -using System.Linq; -using System.Text.Encodings.Web; -using System.Text.Json; -using System.Text.Json.Nodes; -using System.Text.Json.Serialization; -using Microsoft.EntityFrameworkCore; - -[Index(nameof(Timestamp))] -[Index(nameof(Type))] -public record EventRecord -{ - public DateTime Timestamp { get; init; } = DateTime.UtcNow; - public string Type { get; private set; } - public string Data { get; init; } - [Key] - public Guid Id { get; private set; } - - private static JsonSerializerOptions JsonSerializerOptions { get; } = new JsonSerializerOptions() - { - PropertyNameCaseInsensitive = true, - DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, - PropertyNamingPolicy = JsonNamingPolicy.CamelCase, - Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, - WriteIndented = false, - }; - - /// - /// Converts the specified event into an instance of - /// for the purpose of database storage. - /// - /// - /// The property contains the event-specific data serialized as json, applying - /// standard formatting such as camel cased property names and null value omission. This is important so that - /// the values stored in the database will match the values exposed through other means. Maybe not *that* important, - /// but standardizing json is a good practice. - /// - /// The Event to convert. - /// The specific type of the Event. - /// The converted EventRecord. - public static EventRecord From(Event e) - where T : Event - { - // this will be 'slskd.NameOfEvent'; we want to chop off 'slskd.' and 'Event' = 'NameOf' - var type = e.GetType().Name.Split('.').TakeLast(1).First(); - type = type.Substring(0, type.Length - nameof(Event).Length); - - // construct the data for the record by serializing the event and removing redundant properties - var json = JsonSerializer.Serialize(e as T, JsonSerializerOptions); - var data = JsonNode.Parse(json).AsObject(); - data.Remove(nameof(Timestamp).ToLower()); - data.Remove(nameof(Type).ToLower()); - data.Remove(nameof(Id).ToLower()); - data.Remove(nameof(Data).ToLower()); - - return new EventRecord - { - Timestamp = e.Timestamp, - Type = type, - Id = e.Id, - Data = data.ToJsonString(JsonSerializerOptions), - }; - } -} \ No newline at end of file diff --git a/src/slskd/Events/Types/Events.cs b/src/slskd/Events/Types/Events.cs index bcfdb8d3..416074e6 100644 --- a/src/slskd/Events/Types/Events.cs +++ b/src/slskd/Events/Types/Events.cs @@ -20,20 +20,20 @@ namespace slskd.Events; using System; using slskd.Transfers; -public record Event +public abstract record BaseEvent { public Guid Id { get; } = Guid.NewGuid(); public DateTime Timestamp { get; init; } = DateTime.UtcNow; } -public sealed record DownloadFileCompleteEvent : Event +public sealed record DownloadFileCompleteEvent : BaseEvent { public string LocalFilename { get; init; } public string RemoteFilename { get; init; } public Transfer Transfer { get; init; } } -public sealed record DownloadDirectoryCompleteEvent : Event +public sealed record DownloadDirectoryCompleteEvent : BaseEvent { public string LocalDirectoryName { get; init; } public string RemoteDirectoryName { get; init; } -- cgit v1.2.3 From 2805a4c368e9585162f6379bb862e0951790613e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 2 Sep 2024 18:41:51 -0500 Subject: rename types back :shrug: --- src/slskd/Events/EventBus.cs | 5 ++- src/slskd/Events/EventService.cs | 15 ++++--- src/slskd/Events/Types/Event.cs | 84 ----------------------------------- src/slskd/Events/Types/EventRecord.cs | 84 +++++++++++++++++++++++++++++++++++ src/slskd/Events/Types/Events.cs | 6 +-- 5 files changed, 99 insertions(+), 95 deletions(-) delete mode 100644 src/slskd/Events/Types/Event.cs create mode 100644 src/slskd/Events/Types/EventRecord.cs diff --git a/src/slskd/Events/EventBus.cs b/src/slskd/Events/EventBus.cs index c3e418e7..e5552d2d 100644 --- a/src/slskd/Events/EventBus.cs +++ b/src/slskd/Events/EventBus.cs @@ -71,12 +71,12 @@ public class EventBus /// The event data. /// The Type of the event. public virtual void Raise(T data) - where T : BaseEvent + where T : Event { Log.Debug("Handling {Type}: {Data}", typeof(T), data); // save the event to the database before broadcasting to consumers - Events.Add(Event.From(data)); + Events.Add(EventRecord.From(data)); // broadcast the event in a fire-and-forget fashion // we don't need to wait for anything, just need to kick off the tasks @@ -148,6 +148,7 @@ public class EventBus /// The Type of the event. /// The unique name of the subscriber. public virtual void Unsubscribe(string subscriber) + where T : Event { if (Subscriptions.TryGetValue(typeof(T), out var subscriptions)) { diff --git a/src/slskd/Events/EventService.cs b/src/slskd/Events/EventService.cs index 759dc8cf..188d5895 100644 --- a/src/slskd/Events/EventService.cs +++ b/src/slskd/Events/EventService.cs @@ -40,21 +40,24 @@ public class EventService private ILogger Log { get; } = Serilog.Log.ForContext(); /// - /// Adds the specified event . + /// Adds the specified event . /// - /// The record to add. + /// + /// To ensure proper construction of the record, use . + /// + /// The record to add. /// Thrown when the specified record is null. - public virtual void Add(Event @event) + public virtual void Add(EventRecord eventRecord) { - if (@event is null) + if (eventRecord is null) { - throw new ArgumentNullException(nameof(@event)); + throw new ArgumentNullException(nameof(eventRecord)); } try { using var context = ContextFactory.CreateDbContext(); - context.Add(@event); + context.Add(eventRecord); context.SaveChanges(); } catch (Exception ex) diff --git a/src/slskd/Events/Types/Event.cs b/src/slskd/Events/Types/Event.cs deleted file mode 100644 index 5b57aa5d..00000000 --- a/src/slskd/Events/Types/Event.cs +++ /dev/null @@ -1,84 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Events; - -using System; -using System.ComponentModel.DataAnnotations; -using System.Linq; -using System.Text.Encodings.Web; -using System.Text.Json; -using System.Text.Json.Nodes; -using System.Text.Json.Serialization; -using Microsoft.EntityFrameworkCore; - -[Index(nameof(Timestamp))] -[Index(nameof(Type))] -public record Event -{ - public DateTime Timestamp { get; init; } = DateTime.UtcNow; - public string Type { get; private set; } - public string Data { get; init; } - [Key] - public Guid Id { get; private set; } - - private static JsonSerializerOptions JsonSerializerOptions { get; } = new JsonSerializerOptions() - { - PropertyNameCaseInsensitive = true, - DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, - PropertyNamingPolicy = JsonNamingPolicy.CamelCase, - Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, - WriteIndented = false, - }; - - /// - /// Converts the specified event into an instance of - /// for the purpose of database storage. - /// - /// - /// The property contains the event-specific data serialized as json, applying - /// standard formatting such as camel cased property names and null value omission. This is important so that - /// the values stored in the database will match the values exposed through other means. Maybe not *that* important, - /// but standardizing json is a good practice. - /// - /// The Event to convert. - /// The specific type of the Event. - /// The converted EventRecord. - public static Event From(BaseEvent e) - where T : BaseEvent - { - // this will be 'slskd.NameOfEvent'; we want to chop off 'slskd.' and 'Event' = 'NameOf' - var type = e.GetType().Name.Split('.').TakeLast(1).First(); - type = type.Substring(0, type.Length - "Event".Length); // chop off "Event" suffix - - // construct the data for the record by serializing the event and removing redundant properties - var json = JsonSerializer.Serialize(e as T, JsonSerializerOptions); - var data = JsonNode.Parse(json).AsObject(); - data.Remove(nameof(Timestamp).ToLower()); - data.Remove(nameof(Type).ToLower()); - data.Remove(nameof(Id).ToLower()); - data.Remove(nameof(Data).ToLower()); - - return new Event - { - Timestamp = e.Timestamp, - Type = type, - Id = e.Id, - Data = data.ToJsonString(JsonSerializerOptions), - }; - } -} \ No newline at end of file diff --git a/src/slskd/Events/Types/EventRecord.cs b/src/slskd/Events/Types/EventRecord.cs new file mode 100644 index 00000000..921daa4e --- /dev/null +++ b/src/slskd/Events/Types/EventRecord.cs @@ -0,0 +1,84 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Events; + +using System; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text.Encodings.Web; +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Text.Json.Serialization; +using Microsoft.EntityFrameworkCore; + +[Index(nameof(Timestamp))] +[Index(nameof(Type))] +public record EventRecord +{ + public DateTime Timestamp { get; init; } = DateTime.UtcNow; + public string Type { get; private set; } + public string Data { get; init; } + [Key] + public Guid Id { get; private set; } + + private static JsonSerializerOptions JsonSerializerOptions { get; } = new JsonSerializerOptions() + { + PropertyNameCaseInsensitive = true, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, + WriteIndented = false, + }; + + /// + /// Converts the specified event into an instance of + /// for the purpose of database storage. + /// + /// + /// The property contains the event-specific data serialized as json, applying + /// standard formatting such as camel cased property names and null value omission. This is important so that + /// the values stored in the database will match the values exposed through other means. Maybe not *that* important, + /// but standardizing json is a good practice. + /// + /// The Event to convert. + /// The specific type of the Event. + /// The converted EventRecord. + public static EventRecord From(Event e) + where T : Event + { + // this will be 'slskd.NameOfEvent'; we want to chop off 'slskd.' and 'Event' = 'NameOf' + var type = e.GetType().Name.Split('.').TakeLast(1).First(); + type = type.Substring(0, type.Length - "Event".Length); // chop off "Event" suffix + + // construct the data for the record by serializing the event and removing redundant properties + var json = JsonSerializer.Serialize(e as T, JsonSerializerOptions); + var data = JsonNode.Parse(json).AsObject(); + data.Remove(nameof(Timestamp).ToLower()); + data.Remove(nameof(Type).ToLower()); + data.Remove(nameof(Id).ToLower()); + data.Remove(nameof(Data).ToLower()); + + return new EventRecord + { + Timestamp = e.Timestamp, + Type = type, + Id = e.Id, + Data = data.ToJsonString(JsonSerializerOptions), + }; + } +} \ No newline at end of file diff --git a/src/slskd/Events/Types/Events.cs b/src/slskd/Events/Types/Events.cs index 416074e6..20ec3f9f 100644 --- a/src/slskd/Events/Types/Events.cs +++ b/src/slskd/Events/Types/Events.cs @@ -20,20 +20,20 @@ namespace slskd.Events; using System; using slskd.Transfers; -public abstract record BaseEvent +public abstract record Event { public Guid Id { get; } = Guid.NewGuid(); public DateTime Timestamp { get; init; } = DateTime.UtcNow; } -public sealed record DownloadFileCompleteEvent : BaseEvent +public sealed record DownloadFileCompleteEvent : Event { public string LocalFilename { get; init; } public string RemoteFilename { get; init; } public Transfer Transfer { get; init; } } -public sealed record DownloadDirectoryCompleteEvent : BaseEvent +public sealed record DownloadDirectoryCompleteEvent : Event { public string LocalDirectoryName { get; init; } public string RemoteDirectoryName { get; init; } -- cgit v1.2.3 From 4e89ea54eca5fe577e879d2d5bb11f3dcf3a559a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 2 Sep 2024 18:44:44 -0500 Subject: prune events every hour --- src/slskd/Application.cs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index a3d86034..d0dbabbb 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -40,6 +40,7 @@ namespace slskd using Serilog.Events; using slskd.Configuration; using slskd.Core.API; + using slskd.Events; using slskd.Files; using slskd.Integrations.Pushbullet; using slskd.Messaging; @@ -97,6 +98,7 @@ namespace slskd IShareService shareService, IPushbulletService pushbulletService, IRelayService relayService, + EventService eventService, IHubContext applicationHub, IHubContext logHub) { @@ -144,6 +146,8 @@ namespace slskd Shares = shareService; Shares.StateMonitor.OnChange(state => ShareState_OnChange(state)); + Events = eventService; + Transfers = transferService; BrowseTracker = browseTracker; Pushbullet = pushbulletService; @@ -223,6 +227,7 @@ namespace slskd private IHubContext LogHub { get; set; } private IUserService Users { get; set; } private IShareService Shares { get; set; } + private EventService Events { get; } private IRelayService Relay { get; set; } private IMemoryCache Cache { get; set; } = new MemoryCache(new MemoryCacheOptions()); private IEnumerable CompiledSearchResponseFilters { get; set; } @@ -1008,6 +1013,7 @@ namespace slskd private void Clock_EveryHour(object sender, ClockEventArgs e) { + _ = Task.Run(() => Events.Prune(ageInDays: Options.Retention.Events)); _ = Task.Run(() => MaybeRescanShares()); } -- cgit v1.2.3 From 378010887b29d549acf639ddc69af9c132c68529 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 2 Sep 2024 18:52:24 -0500 Subject: fix docs --- src/slskd/Events/Types/EventRecord.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/slskd/Events/Types/EventRecord.cs b/src/slskd/Events/Types/EventRecord.cs index 921daa4e..11825c09 100644 --- a/src/slskd/Events/Types/EventRecord.cs +++ b/src/slskd/Events/Types/EventRecord.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify -- cgit v1.2.3 From 1eb7649c460518bbedae2bc25fae120b9faf8157 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 15 Sep 2024 17:47:04 -0500 Subject: don't prune events (yet?) --- config/slskd.example.yml | 1 - src/slskd/Application.cs | 1 - src/slskd/Core/Options.cs | 6 ------ src/slskd/Events/EventService.cs | 29 ----------------------------- 4 files changed, 37 deletions(-) diff --git a/config/slskd.example.yml b/config/slskd.example.yml index d4f99b21..4b4f0996 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -168,7 +168,6 @@ # files: # complete: 20160 # 2 weeks # incomplete: 43200 # 30 days -# events: 30 # days # logs: 180 # days # logger: # disk: false diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 1d13f73c..d441160e 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -1013,7 +1013,6 @@ namespace slskd private void Clock_EveryHour(object sender, ClockEventArgs e) { - _ = Task.Run(() => Events.Prune(ageInDays: Options.Retention.Events)); _ = Task.Run(() => MaybeRescanShares()); } diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 97b596d0..0f86ff62 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1322,12 +1322,6 @@ namespace slskd [Validate] public FileRetentionOptions Files { get; init; } = new FileRetentionOptions(); - /// - /// Gets the time to retain events, in days. - /// - [Range(1, maximum: int.MaxValue)] - public int Events { get; init; } = 30; - /// /// Gets the time to retain logs, in days. /// diff --git a/src/slskd/Events/EventService.cs b/src/slskd/Events/EventService.cs index 188d5895..85f82238 100644 --- a/src/slskd/Events/EventService.cs +++ b/src/slskd/Events/EventService.cs @@ -66,33 +66,4 @@ public class EventService throw; } } - - /// - /// Removes event records older than the specified . - /// - /// The age after which event records are eligible for pruning, in days. - /// The number of pruned event records. - public virtual int Prune(int ageInDays) - { - try - { - using var context = ContextFactory.CreateDbContext(); - - var cutoffDateTime = DateTime.UtcNow.AddDays(-ageInDays); - - var pruned = context.Events.Where(e => e.Timestamp < cutoffDateTime).ExecuteDelete(); - - if (pruned > 0) - { - Log.Debug("Pruned {Count} expired events", pruned); - } - - return pruned; - } - catch (Exception ex) - { - Log.Error(ex, "Failed to prune events: {Message}", ex.Message); - throw; - } - } } \ No newline at end of file -- cgit v1.2.3 From a01994b6c6dd2a798cf2fe23706dacb894c807c1 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 22 Sep 2024 16:54:42 -0500 Subject: remove (temporarily) ShellService --- src/slskd/Integrations/Shell/ShellService.cs | 49 ---------------------------- src/slskd/Program.cs | 7 ---- 2 files changed, 56 deletions(-) delete mode 100644 src/slskd/Integrations/Shell/ShellService.cs diff --git a/src/slskd/Integrations/Shell/ShellService.cs b/src/slskd/Integrations/Shell/ShellService.cs deleted file mode 100644 index baed28f8..00000000 --- a/src/slskd/Integrations/Shell/ShellService.cs +++ /dev/null @@ -1,49 +0,0 @@ -// -// Copyright (c) slskd Team. All rights reserved. -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as published -// by the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see https://www.gnu.org/licenses/. -// - -namespace slskd.Integrations.Shell; - -using System; -using System.Threading.Tasks; -using Serilog; -using slskd.Events; - -public class ShellService -{ - public ShellService(EventBus eventBus) - { - Events = eventBus; - - Events.Subscribe(nameof(ShellService), HandleDownloadFileCompleteEvent); - Events.Subscribe(nameof(ShellService), HandleDownloadDirectoryCompleteEvent); - - Log.Debug("Shell service initialized"); - } - - private ILogger Log { get; } = Serilog.Log.ForContext(); - private EventBus Events { get; } - - private async Task HandleDownloadFileCompleteEvent(DownloadFileCompleteEvent data) - { - Console.WriteLine("here is where we would call an external application!"); - } - - private async Task HandleDownloadDirectoryCompleteEvent(DownloadDirectoryCompleteEvent data) - { - Console.WriteLine("wow we downloaded a whole directory"); - } -} \ No newline at end of file diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 93734a35..2d62efd8 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -57,11 +57,9 @@ namespace slskd using slskd.Core.API; using slskd.Cryptography; using slskd.Events; - using slskd.Files; using slskd.Integrations.FTP; using slskd.Integrations.Pushbullet; - using slskd.Integrations.Shell; using slskd.Messaging; using slskd.Relay; using slskd.Search; @@ -486,9 +484,6 @@ namespace slskd var app = builder.Build(); - // hack: nothing depends on ShellService but we need to initialize it - _ = app.Services.GetService(); - app.ConfigureAspDotNetPipeline(); if (OptionsAtStartup.Flags.NoStart) @@ -605,8 +600,6 @@ namespace slskd services.AddSingleton(); - services.AddSingleton(); - services.AddSingleton(); services.AddSingleton(); -- cgit v1.2.3 From c919538d3ca45b9ab5cf656c71deb8f2f4b30846 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 22 Sep 2024 17:10:19 -0500 Subject: add Get --- src/slskd/Events/EventService.cs | 39 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 37 insertions(+), 2 deletions(-) diff --git a/src/slskd/Events/EventService.cs b/src/slskd/Events/EventService.cs index 85f82238..7f09010f 100644 --- a/src/slskd/Events/EventService.cs +++ b/src/slskd/Events/EventService.cs @@ -15,13 +15,15 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // +namespace slskd.Events; + using System; +using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Serilog; -namespace slskd.Events; - /// /// Manages events. /// @@ -39,6 +41,39 @@ public class EventService private IDbContextFactory ContextFactory { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); + /// + /// Gets a paginated list of events. + /// + /// The beginning offset for the page. + /// The page size limit. + /// The retrieved list. + /// Thrown when the specified is less than zero. + /// Thrown when the specified is zero. + public virtual async Task> Get(int offset = 0, int limit = 100) + { + if (offset < 0) + { + throw new ArgumentOutOfRangeException(nameof(offset), "Offset must be greater than or equal to zero"); + } + + if (limit <= 0) + { + throw new ArgumentOutOfRangeException(nameof(limit), "Limit must be greater than zero"); + } + + try + { + using var context = ContextFactory.CreateDbContext(); + var events = context.Events.Skip(offset).Take(limit).ToList(); + return events; + } + catch (Exception ex) + { + Log.Error(ex, "Failed to get event records with options {Options}: {Message}", new { offset, limit }, ex.Message); + throw; + } + } + /// /// Adds the specified event . /// -- cgit v1.2.3 From cc0c9ee32b87b2d2937fce90a55afb7f875b315e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 22 Sep 2024 17:10:51 -0500 Subject: GetPage() isn't async --- src/slskd/Events/EventService.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/slskd/Events/EventService.cs b/src/slskd/Events/EventService.cs index 7f09010f..7a70cf05 100644 --- a/src/slskd/Events/EventService.cs +++ b/src/slskd/Events/EventService.cs @@ -20,7 +20,6 @@ namespace slskd.Events; using System; using System.Collections.Generic; using System.Linq; -using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Serilog; @@ -49,7 +48,7 @@ public class EventService /// The retrieved list. /// Thrown when the specified is less than zero. /// Thrown when the specified is zero. - public virtual async Task> Get(int offset = 0, int limit = 100) + public virtual IReadOnlyCollection GetPage(int offset = 0, int limit = 100) { if (offset < 0) { -- cgit v1.2.3 From 5df5d3378d757868ff3ccc7ada65de15ed7c9794 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 22 Sep 2024 17:13:41 -0500 Subject: keep tweaking the Get --- src/slskd/Events/EventService.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/slskd/Events/EventService.cs b/src/slskd/Events/EventService.cs index 7a70cf05..0406f83d 100644 --- a/src/slskd/Events/EventService.cs +++ b/src/slskd/Events/EventService.cs @@ -41,14 +41,14 @@ public class EventService private ILogger Log { get; } = Serilog.Log.ForContext(); /// - /// Gets a paginated list of events. + /// Gets list of events, optionally applying the specified and . /// /// The beginning offset for the page. /// The page size limit. /// The retrieved list. /// Thrown when the specified is less than zero. /// Thrown when the specified is zero. - public virtual IReadOnlyCollection GetPage(int offset = 0, int limit = 100) + public virtual IReadOnlyCollection Get(int offset = 0, int limit = int.MaxValue) { if (offset < 0) { -- cgit v1.2.3 From 2b4d56e0f4b75d0f7c261558e5dceac156084850 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 22 Sep 2024 17:18:47 -0500 Subject: add EventsController --- src/slskd/Events/API/EventsController.cs | 61 ++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 src/slskd/Events/API/EventsController.cs diff --git a/src/slskd/Events/API/EventsController.cs b/src/slskd/Events/API/EventsController.cs new file mode 100644 index 00000000..8f47fe91 --- /dev/null +++ b/src/slskd/Events/API/EventsController.cs @@ -0,0 +1,61 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Events.API; + +using Asp.Versioning; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Serilog; + +/// +/// Events. +/// +[Route("api/v{version:apiVersion}/[controller]")] +[ApiVersion("0")] +[ApiController] +[Produces("application/json")] +[Consumes("application/json")] +public class EventsController : ControllerBase +{ + public EventsController( + EventService eventService) + { + Events = eventService; + } + + private EventService Events { get; } + private ILogger Log { get; } = Serilog.Log.ForContext(); + + [HttpGet("")] + [Authorize(Policy = AuthPolicy.Any)] + public IActionResult GetEvents([FromQuery] int offset = 0, [FromQuery] int limit = 100) + { + if (offset < 0) + { + return BadRequest("Offset must be greater than or equal to zero."); + } + + if (limit <= 0) + { + return BadRequest("Limit must be greater than zero"); + } + + var events = Events.Get(offset, limit); + return Ok(events); + } +} \ No newline at end of file -- cgit v1.2.3 From 4e5cab89998610c6143c37da26c89f94eade4eee Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 29 Sep 2024 15:12:04 -0500 Subject: add Events to system tab --- src/web/src/components/System/Events/index.jsx | 7 +++++++ src/web/src/components/System/System.jsx | 14 ++++++++++++++ 2 files changed, 21 insertions(+) create mode 100644 src/web/src/components/System/Events/index.jsx diff --git a/src/web/src/components/System/Events/index.jsx b/src/web/src/components/System/Events/index.jsx new file mode 100644 index 00000000..b859255d --- /dev/null +++ b/src/web/src/components/System/Events/index.jsx @@ -0,0 +1,7 @@ +import React from 'react'; + +const Events = () => { + return
hello world!
; +}; + +export default Events; diff --git a/src/web/src/components/System/System.jsx b/src/web/src/components/System/System.jsx index 8746cefe..790a4c45 100644 --- a/src/web/src/components/System/System.jsx +++ b/src/web/src/components/System/System.jsx @@ -1,6 +1,7 @@ import './System.css'; import { Switch } from '../Shared'; import Data from './Data'; +import Events from './Events'; import Files from './Files'; import Info from './Info'; import Logs from './Logs'; @@ -120,6 +121,19 @@ const System = ({ options = {}, state = {}, theme }) => { ), route: 'data', }, + { + menuItem: { + content: 'Events', + icon: 'history', + key: 'events', + }, + render: () => ( + + + + ), + route: 'events', + }, { menuItem: { content: 'Logs', -- cgit v1.2.3 From 481895560f78b687b6958646dd95d932c09bae90 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 29 Sep 2024 16:57:38 -0500 Subject: add events lib --- src/web/src/lib/events.js | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 src/web/src/lib/events.js diff --git a/src/web/src/lib/events.js b/src/web/src/lib/events.js new file mode 100644 index 00000000..5c349a08 --- /dev/null +++ b/src/web/src/lib/events.js @@ -0,0 +1,7 @@ +import api from './api'; + +export const list = async ({ offset, limit }) => { + const response = (await api.get(`/events?offset=${offset}&limit=${limit}`)) + .data; + return response; +}; -- cgit v1.2.3 From f31d6ba3a9fb9efbcac26acc70bfa7e58075f454 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 29 Sep 2024 16:57:48 -0500 Subject: crude table implementation --- src/web/src/components/System/Events/index.jsx | 96 +++++++++++++++++++++++++- src/web/src/components/System/System.css | 8 ++- 2 files changed, 100 insertions(+), 4 deletions(-) diff --git a/src/web/src/components/System/Events/index.jsx b/src/web/src/components/System/Events/index.jsx index b859255d..0912160c 100644 --- a/src/web/src/components/System/Events/index.jsx +++ b/src/web/src/components/System/Events/index.jsx @@ -1,7 +1,99 @@ -import React from 'react'; +import { list } from '../../../lib/events'; +import { LoaderSegment } from '../../Shared'; +import React, { useEffect, useState } from 'react'; +import { Icon, Pagination, Popup, Table } from 'semantic-ui-react'; + +const PER_PAGE = 50; const Events = () => { - return
hello world!
; + const [page, setPage] = useState(1); + const [loading, setLoading] = useState(false); + const [events, setEvents] = useState([]); + + const fetch = async () => { + setLoading(true); + + const eventResult = await list({ + limit: PER_PAGE, + offset: (page - 1) * PER_PAGE, + }); + + setEvents(eventResult); + setLoading(false); + + return eventResult; + }; + + const paginationChanged = ({ activePage }) => { + console.log(activePage); + setPage(activePage); + }; + + useEffect(() => { + fetch(); + }, [page]); // eslint-disable-line react-hooks/exhaustive-deps + + if (loading) { + return ; + } + + return ( + <> + + + + Id + Timestamp + Type + Data + + + + {events?.length === 0 ? ( + + + No events + + + ) : ( + events.map((event) => ( + + + } + wide="very" + /> + + {event.timestamp} + {event.type} + + {event.data} + + + )) + )} + +
+ paginationChanged({ ...data })} + totalPages={100} + /> + + ); }; export default Events; diff --git a/src/web/src/components/System/System.css b/src/web/src/components/System/System.css index ded0449a..33767202 100644 --- a/src/web/src/components/System/System.css +++ b/src/web/src/components/System/System.css @@ -8,11 +8,11 @@ margin-bottom: 16px; } -.logs-table { +.logs-table, .events-table { font-size: smaller; } -.logs-table-body { +.logs-table-body, .events-table-body { font-family: monospace; } @@ -20,6 +20,10 @@ word-break: break-all; } +.events-table-data { + white-space: pre; +} + .logs { min-height: 100px; } -- cgit v1.2.3 From 3da2a3a081e8456254ae8f497dac198ae4a3505a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 29 Sep 2024 17:11:22 -0500 Subject: css tweaks --- src/web/src/components/System/Events/index.jsx | 14 +++++++++----- src/web/src/components/System/System.css | 12 ++++++++++++ 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/src/web/src/components/System/Events/index.jsx b/src/web/src/components/System/Events/index.jsx index 0912160c..5dfc5868 100644 --- a/src/web/src/components/System/Events/index.jsx +++ b/src/web/src/components/System/Events/index.jsx @@ -40,15 +40,19 @@ const Events = () => { return ( <> - Id - Timestamp + Id + + Timestamp + Type - Data + + Data + @@ -80,7 +84,7 @@ const Events = () => { {event.timestamp} {event.type} - {event.data} + {event.data.slice(0, 10)} )) diff --git a/src/web/src/components/System/System.css b/src/web/src/components/System/System.css index 33767202..1d285ed8 100644 --- a/src/web/src/components/System/System.css +++ b/src/web/src/components/System/System.css @@ -24,6 +24,18 @@ white-space: pre; } +.events-list-id { + width: 0px; /* small as possible */ +} + +.events-list-timestamp { + width: 233px; +} + +.events-list-data { + width: 200px; +} + .logs { min-height: 100px; } -- cgit v1.2.3 From c0e02f9806ed95dd43bbb7bff74d6abe5e66109c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 6 Oct 2024 16:55:58 -0500 Subject: expose X-Total-Count --- src/slskd/Program.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 2d62efd8..6392385f 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -640,7 +640,7 @@ namespace slskd .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials() - .WithExposedHeaders("X-URL-Base"))); + .WithExposedHeaders("X-URL-Base", "X-Total-Count"))); services.AddSystemMetrics(); using var runtimeMetrics = DotNetRuntimeStatsBuilder.Default().StartCollecting(); -- cgit v1.2.3 From 8d919e494ef53fbdf625540971414d26c06a96fb Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 6 Oct 2024 16:56:27 -0500 Subject: add X-Total-Count to events GET --- src/slskd/Events/API/EventsController.cs | 5 +++++ src/slskd/Events/EventService.cs | 19 +++++++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/src/slskd/Events/API/EventsController.cs b/src/slskd/Events/API/EventsController.cs index 8f47fe91..e9780fad 100644 --- a/src/slskd/Events/API/EventsController.cs +++ b/src/slskd/Events/API/EventsController.cs @@ -19,6 +19,7 @@ namespace slskd.Events.API; using Asp.Versioning; using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Serilog; @@ -56,6 +57,10 @@ public class EventsController : ControllerBase } var events = Events.Get(offset, limit); + var count = Events.Count(); + + Response.Headers.Append("X-Total-Count", count.ToString()); + return Ok(events); } } \ No newline at end of file diff --git a/src/slskd/Events/EventService.cs b/src/slskd/Events/EventService.cs index 0406f83d..72a71d22 100644 --- a/src/slskd/Events/EventService.cs +++ b/src/slskd/Events/EventService.cs @@ -73,6 +73,25 @@ public class EventService } } + /// + /// Gets the total number of events. + /// + /// The total number of events. + public virtual int Count() + { + try + { + using var context = ContextFactory.CreateDbContext(); + var count = context.Events.Count(); + return count; + } + catch (Exception ex) + { + Log.Error(ex, "Failed to count event records: {Message}", ex.Message); + throw; + } + } + /// /// Adds the specified event . /// -- cgit v1.2.3 From e5659ce50fe1344f5ccf7229482ba450193e389a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 6 Oct 2024 16:56:38 -0500 Subject: retrieve total count from header --- src/web/src/lib/events.js | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/web/src/lib/events.js b/src/web/src/lib/events.js index 5c349a08..9f16a66f 100644 --- a/src/web/src/lib/events.js +++ b/src/web/src/lib/events.js @@ -1,7 +1,10 @@ import api from './api'; export const list = async ({ offset, limit }) => { - const response = (await api.get(`/events?offset=${offset}&limit=${limit}`)) - .data; - return response; + const response = await api.get(`/events?offset=${offset}&limit=${limit}`); + + const events = response.data; + const totalCount = response.headers['x-total-count']; + + return { events, totalCount }; }; -- cgit v1.2.3 From ced0e915da59d3d6008f6da53adb9da1c8a5217b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 6 Oct 2024 17:12:33 -0500 Subject: order by timestamp --- src/slskd/Events/EventService.cs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/slskd/Events/EventService.cs b/src/slskd/Events/EventService.cs index 72a71d22..d6f1a3f5 100644 --- a/src/slskd/Events/EventService.cs +++ b/src/slskd/Events/EventService.cs @@ -63,7 +63,13 @@ public class EventService try { using var context = ContextFactory.CreateDbContext(); - var events = context.Events.Skip(offset).Take(limit).ToList(); + + var events = context.Events + .OrderByDescending(e => e.Timestamp) + .Skip(offset) + .Take(limit) + .ToList(); + return events; } catch (Exception ex) -- cgit v1.2.3 From 83bda1f237997f27b2860a7b887420de795983dc Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 6 Oct 2024 17:14:42 -0500 Subject: finish event screen --- src/web/src/components/System/Events/index.jsx | 43 +++++++++++++++++--------- src/web/src/components/System/System.css | 12 +++---- src/web/src/components/System/System.jsx | 2 +- 3 files changed, 34 insertions(+), 23 deletions(-) diff --git a/src/web/src/components/System/Events/index.jsx b/src/web/src/components/System/Events/index.jsx index 5dfc5868..7f708908 100644 --- a/src/web/src/components/System/Events/index.jsx +++ b/src/web/src/components/System/Events/index.jsx @@ -3,30 +3,38 @@ import { LoaderSegment } from '../../Shared'; import React, { useEffect, useState } from 'react'; import { Icon, Pagination, Popup, Table } from 'semantic-ui-react'; -const PER_PAGE = 50; +const PER_PAGE = 10; + +const replaceHyphensWithNonBreakingEquivalent = (string) => + string?.replaceAll('-', '‑'); const Events = () => { const [page, setPage] = useState(1); + const [totalPages, setTotalPages] = useState(0); const [loading, setLoading] = useState(false); const [events, setEvents] = useState([]); const fetch = async () => { setLoading(true); - const eventResult = await list({ + const { events: items, totalCount } = await list({ limit: PER_PAGE, offset: (page - 1) * PER_PAGE, }); - setEvents(eventResult); + const tp = Math.ceil(totalCount / PER_PAGE); + + setEvents(items); + setTotalPages(Number.isNaN(tp) ? 0 : tp); setLoading(false); - return eventResult; + return items; }; const paginationChanged = ({ activePage }) => { - console.log(activePage); - setPage(activePage); + if (activePage >= 1) { + setPage(activePage); + } }; useEffect(() => { @@ -39,6 +47,14 @@ const Events = () => { return ( <> +
+ paginationChanged({ ...data })} + totalPages={totalPages} + /> +
{ Timestamp - Type + + Type + Data @@ -81,21 +99,18 @@ const Events = () => { wide="very" /> - {event.timestamp} + + {replaceHyphensWithNonBreakingEquivalent(event.timestamp)} + {event.type} - {event.data.slice(0, 10)} + {JSON.stringify(JSON.parse(event.data), null, 2)} )) )}
- paginationChanged({ ...data })} - totalPages={100} - /> ); }; diff --git a/src/web/src/components/System/System.css b/src/web/src/components/System/System.css index 1d285ed8..a3a2c83a 100644 --- a/src/web/src/components/System/System.css +++ b/src/web/src/components/System/System.css @@ -20,20 +20,16 @@ word-break: break-all; } -.events-table-data { - white-space: pre; -} - .events-list-id { - width: 0px; /* small as possible */ + width: 0px; /* shrink to fit */ } .events-list-timestamp { - width: 233px; + width: 0px; /* shrink to fit */ } -.events-list-data { - width: 200px; +.events-list-type { + width: 0px; /* shrink to fit */ } .logs { diff --git a/src/web/src/components/System/System.jsx b/src/web/src/components/System/System.jsx index 790a4c45..2dbd9d91 100644 --- a/src/web/src/components/System/System.jsx +++ b/src/web/src/components/System/System.jsx @@ -124,7 +124,7 @@ const System = ({ options = {}, state = {}, theme }) => { { menuItem: { content: 'Events', - icon: 'history', + icon: 'calendar check', key: 'events', }, render: () => ( -- cgit v1.2.3