aboutsummaryrefslogtreecommitdiffstats
path: root/src/slskd/Events/EventBus.cs
blob: 72f797ffa72317a0738235460b4e7cdb41ec48aa (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
// <copyright file="EventBus.cs" company="JP Dillingham">
//           ▄▄▄▄     ▄▄▄▄     ▄▄▄▄
//     ▄▄▄▄▄▄█  █▄▄▄▄▄█  █▄▄▄▄▄█  █
//     █__ --█  █__ --█    ◄█  -  █
//     █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
//   ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━  ━┉   ┉     ┉
//   │ 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
//   ╰───────────────────────────────────────────╶──── ─ ─── ─  ── ──┈  ┈
// </copyright>

namespace slskd.Events;

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Serilog;

/// <summary>
///     The event bus supporting interoperability and ancillary functions.
/// </summary>
/// <remarks>
///     <para>
///         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.
///     </para>
///     <para>
///         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.
///     </para>
///     <para>
///         This design was chosen over built-in C# events to give greater control over how events are dispatched,
///         and bound.
///     </para>
/// </remarks>
public class EventBus
{
    /// <summary>
    ///     Initializes a new instance of the <see cref="EventBus"/> class.
    /// </summary>
    /// <param name="eventService"/>
    public EventBus(EventService eventService)
    {
        Events = eventService;
    }

    private ILogger Log { get; } = Serilog.Log.ForContext<EventBus>();
    private EventService Events { get; }

    /// <summary>
    ///     Gets the internal list of event subscriptions.
    /// </summary>
    /// <remarks>
    ///     Note that the value is a dictionary to prevent multiple subscriptions from the same subscriber, and to
    ///     support unsubscribing.
    /// </remarks>
    private ConcurrentDictionary<Type, ConcurrentDictionary<string, object>> Subscriptions { get; } = new();

    /// <summary>
    ///     Raises an event.
    /// </summary>
    /// <param name="data">The event data.</param>
    /// <typeparam name="T">The Type of the event.</typeparam>
    public virtual void Raise<T>(T data)
        where T : Event
    {
        // we look up the list of subscribers using T, and then cast the callback to Func<T, Task>, 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<T>(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<T, Task>)(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<Event, Task>)(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)));
        }
    }

    /// <summary>
    ///     Subscribes a <paramref name="subscriber"/>'s <paramref name="callback"/> to an event.
    /// </summary>
    /// <param name="subscriber">The unique name of the subscriber.</param>
    /// <param name="callback">The callback function to execute when an event is raised.</param>
    /// <typeparam name="T">The Type of the event.</typeparam>
    /// <exception cref="ArgumentException">Thrown if the specified <paramref name="subscriber"/> is null or whitespace.</exception>
    /// <exception cref="ArgumentNullException">Thrown if the specified <paramref name="callback"/> is null.</exception>
    public virtual void Subscribe<T>(string subscriber, Action<T> callback)
        where T : Event
    {
        Subscribe<T>(subscriber, e =>
        {
            callback(e);
            return Task.CompletedTask;
        });
    }

    /// <summary>
    ///     Subscribes a <paramref name="subscriber"/>'s <paramref name="callback"/> to an event.
    /// </summary>
    /// <param name="subscriber">The unique name of the subscriber.</param>
    /// <param name="callback">The callback function to execute when an event is raised.</param>
    /// <typeparam name="T">The Type of the event.</typeparam>
    /// <exception cref="ArgumentException">Thrown if the specified <paramref name="subscriber"/> is null or whitespace.</exception>
    /// <exception cref="ArgumentNullException">Thrown if the specified <paramref name="callback"/> is null.</exception>
    public virtual void Subscribe<T>(string subscriber, Func<T, Task> callback)
        where T : Event
    {
        ArgumentException.ThrowIfNullOrWhiteSpace(subscriber);

        if (callback is null)
        {
            throw new ArgumentNullException(nameof(callback));
        }

        Subscriptions.AddOrUpdate(
            key: typeof(T),
            addValue: new ConcurrentDictionary<string, object>(
                new Dictionary<string, object> { [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));
    }

    /// <summary>
    ///     Unsubscribes a <paramref name="subscriber"/> from an event.
    /// </summary>
    /// <remarks>
    ///     Will not throw if a subscription doesn't exist.
    /// </remarks>
    /// <typeparam name="T">The Type of the event.</typeparam>
    /// <param name="subscriber">The unique name of the subscriber.</param>
    public virtual void Unsubscribe<T>(string subscriber)
        where T : Event
    {
        if (Subscriptions.TryGetValue(typeof(T), out var subscriptions))
        {
            subscriptions.TryRemove(subscriber, out _);
        }
    }
}