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 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 src/slskd/Core/EventBus.cs (limited to 'src/slskd/Core') 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 -- 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 (limited to 'src/slskd/Core') 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 (limited to 'src/slskd/Core') 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 (limited to 'src/slskd/Core') 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 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(-) (limited to 'src/slskd/Core') 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(-) (limited to 'src/slskd/Core') 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(-) (limited to 'src/slskd/Core') 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 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 (limited to 'src/slskd/Core') 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 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(-) (limited to 'src/slskd/Core') 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 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(-) (limited to 'src/slskd/Core') 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 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(-) (limited to 'src/slskd/Core') 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