// // ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ // ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ // █__ --█ █__ --█ ◄█ - █ // █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ // ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ // │ Copyright (c) JP Dillingham. // │ // │ 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, version 3. // │ // │ 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/. // │ // │ This program is distributed with Additional Terms pursuant to Section 7 // │ of the AGPLv3. See the LICENSE file in the root directory of this // │ project for the complete terms and conditions. // │ // │ https://slskd.org // │ // ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌ // │ SPDX-FileCopyrightText: JP Dillingham // │ SPDX-License-Identifier: AGPL-3.0-only // ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ // namespace slskd.Events; 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. /// /// /// 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(EventService eventService) { Events = eventService; } private ILogger Log { get; } = Serilog.Log.ForContext(); private EventService Events { 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 { // we look up the list of subscribers using T, and then cast the callback to Func, and this breaks when // T is Event rather than the derived type. the fix for this involves wrapping the callbacks with another delegate // that performs the proper cast (or just rethinking this approach entirely), so we're just going to throw // at run-time instead, which the smallest amount of functional testing will surface if (typeof(T) == typeof(Event)) { throw new ArgumentException($"Raise can not be called with a type argument of type Event because the bus can't properly source the list of subscribers. Supply the derived Event Type when calling"); } Log.Debug("Handling {Type}: {Data}", typeof(T), data); // save the event to the database before broadcasting to consumers Events.Add(EventRecord.From(data)); // broadcast the event to granular subscribers 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, data.Type, 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), continuationOptions: TaskContinuationOptions.OnlyOnFaulted))); } else { Log.Debug("No subscribers for {Type}", typeof(T)); } // broadcast the event to catch-all subscribers of type Event; listening for all types if (Subscriptions.TryGetValue(typeof(Event), out subscribers)) { Log.Debug("{Count} catch-all subscriber(s): {Names}", subscribers.Count, 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, "Catch-All Subscriber {Name} for {Type} encountered an error: {Message}", subscriber.Key, typeof(Event), task.Exception.Message), continuationOptions: TaskContinuationOptions.OnlyOnFaulted))); } } /// /// 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, Action callback) where T : Event { Subscribe(subscriber, e => { callback(e); return Task.CompletedTask; }); } /// /// 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) where T : Event { if (Subscriptions.TryGetValue(typeof(T), out var subscriptions)) { subscriptions.TryRemove(subscriber, out _); } } }