diff options
| author | JP Dillingham <jp@dillingham.me> | 2024-10-06 18:06:22 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2024-10-06 18:06:22 -0500 |
| commit | bac18981efba4daa4e4668dd382b7fbed8765636 (patch) | |
| tree | 86307843bd193b5eb5750e254e231dc3751d1f40 /src/slskd/Events | |
| parent | 3fb1176c9788d2de5527df282702aefb0497a0ec (diff) | |
| parent | 5dea82dbd647cdc28c89a1d37e168d3a47abeea7 (diff) | |
| download | slskd-bac18981efba4daa4e4668dd382b7fbed8765636.tar.gz | |
Merge pull request #1215 from slskd/tasks
Add 'Events'
Diffstat (limited to 'src/slskd/Events')
| -rw-r--r-- | src/slskd/Events/API/EventsController.cs | 66 | ||||
| -rw-r--r-- | src/slskd/Events/EventBus.cs | 158 | ||||
| -rw-r--r-- | src/slskd/Events/EventService.cs | 128 | ||||
| -rw-r--r-- | src/slskd/Events/EventsDbContext.cs | 40 | ||||
| -rw-r--r-- | src/slskd/Events/Types/EventRecord.cs | 84 | ||||
| -rw-r--r-- | src/slskd/Events/Types/Events.cs | 41 |
6 files changed, 517 insertions, 0 deletions
diff --git a/src/slskd/Events/API/EventsController.cs b/src/slskd/Events/API/EventsController.cs new file mode 100644 index 00000000..e9780fad --- /dev/null +++ b/src/slskd/Events/API/EventsController.cs @@ -0,0 +1,66 @@ +// <copyright file="EventsController.cs" company="slskd Team"> +// 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/. +// </copyright> + +namespace slskd.Events.API; + +using Asp.Versioning; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Serilog; + +/// <summary> +/// Events. +/// </summary> +[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<EventsController>(); + + [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); + 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/EventBus.cs b/src/slskd/Events/EventBus.cs new file mode 100644 index 00000000..e5552d2d --- /dev/null +++ b/src/slskd/Events/EventBus.cs @@ -0,0 +1,158 @@ +// <copyright file="EventBus.cs" company="slskd Team"> +// 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/. +// </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 + { + 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 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<T, Task>)(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)); + } + } + + /// <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 _); + } + } +}
\ No newline at end of file diff --git a/src/slskd/Events/EventService.cs b/src/slskd/Events/EventService.cs new file mode 100644 index 00000000..d6f1a3f5 --- /dev/null +++ b/src/slskd/Events/EventService.cs @@ -0,0 +1,128 @@ +// <copyright file="EventService.cs" company="slskd Team"> +// 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/. +// </copyright> + +namespace slskd.Events; + +using System; +using System.Collections.Generic; +using System.Linq; +using Microsoft.EntityFrameworkCore; +using Serilog; + +/// <summary> +/// Manages events. +/// </summary> +public class EventService +{ + /// <summary> + /// Initializes a new instance of the <see cref="EventService"/> class. + /// </summary> + /// <param name="contextFactory"></param> + public EventService(IDbContextFactory<EventsDbContext> contextFactory) + { + ContextFactory = contextFactory; + } + + private IDbContextFactory<EventsDbContext> ContextFactory { get; } + private ILogger Log { get; } = Serilog.Log.ForContext<EventService>(); + + /// <summary> + /// Gets list of events, optionally applying the specified <paramref name="offset"/> and <paramref name="limit"/>. + /// </summary> + /// <param name="offset">The beginning offset for the page.</param> + /// <param name="limit">The page size limit.</param> + /// <returns>The retrieved list.</returns> + /// <exception cref="ArgumentOutOfRangeException">Thrown when the specified <paramref name="offset"/> is less than zero.</exception> + /// <exception cref="ArgumentOutOfRangeException">Thrown when the specified <paramref name="limit"/> is zero.</exception> + public virtual IReadOnlyCollection<EventRecord> Get(int offset = 0, int limit = int.MaxValue) + { + 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 + .OrderByDescending(e => e.Timestamp) + .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; + } + } + + /// <summary> + /// Gets the total number of events. + /// </summary> + /// <returns>The total number of events.</returns> + 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; + } + } + + /// <summary> + /// Adds the specified event <paramref name="eventRecord"/>. + /// </summary> + /// <remarks> + /// To ensure proper construction of the record, use <see cref="EventRecord.From"/>. + /// </remarks> + /// <param name="eventRecord">The record to add.</param> + /// <exception cref="ArgumentNullException">Thrown when the specified record is null.</exception> + public virtual void Add(EventRecord eventRecord) + { + if (eventRecord is null) + { + throw new ArgumentNullException(nameof(eventRecord)); + } + + try + { + using var context = ContextFactory.CreateDbContext(); + context.Add(eventRecord); + context.SaveChanges(); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to add event record: {Message}", ex.Message); + throw; + } + } +}
\ No newline at end of file diff --git a/src/slskd/Events/EventsDbContext.cs b/src/slskd/Events/EventsDbContext.cs new file mode 100644 index 00000000..9acbc9a4 --- /dev/null +++ b/src/slskd/Events/EventsDbContext.cs @@ -0,0 +1,40 @@ +// <copyright file="EventsDbContext.cs" company="slskd Team"> +// 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/. +// </copyright> + +namespace slskd.Events; + +using System; +using Microsoft.EntityFrameworkCore; + +public class EventsDbContext : DbContext +{ + public EventsDbContext(DbContextOptions<EventsDbContext> options) + : base(options) + { + Database.EnsureCreated(); + } + + public DbSet<EventRecord> Events { get; set; } + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + modelBuilder + .Entity<EventRecord>() + .Property(e => e.Timestamp) + .HasConversion(v => v, v => DateTime.SpecifyKind(v, DateTimeKind.Utc)); + } +}
\ 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..11825c09 --- /dev/null +++ b/src/slskd/Events/Types/EventRecord.cs @@ -0,0 +1,84 @@ +// <copyright file="EventRecord.cs" company="slskd Team"> +// 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/. +// </copyright> + +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, + }; + + /// <summary> + /// Converts the specified event <paramref name="e"/> into an instance of <see cref="EventRecord"/> + /// for the purpose of database storage. + /// </summary> + /// <remarks> + /// The <see cref="Data"/> 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. + /// </remarks> + /// <param name="e">The Event to convert.</param> + /// <typeparam name="T">The specific type of the Event.</typeparam> + /// <returns>The converted EventRecord.</returns> + public static EventRecord From<T>(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 new file mode 100644 index 00000000..20ec3f9f --- /dev/null +++ b/src/slskd/Events/Types/Events.cs @@ -0,0 +1,41 @@ +// <copyright file="Events.cs" company="slskd Team"> +// 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/. +// </copyright> + +namespace slskd.Events; + +using System; +using slskd.Transfers; + +public abstract record Event +{ + public Guid Id { get; } = Guid.NewGuid(); + public DateTime Timestamp { get; init; } = DateTime.UtcNow; +} + +public sealed record DownloadFileCompleteEvent : Event +{ + public string LocalFilename { get; init; } + public string RemoteFilename { get; init; } + public Transfer Transfer { get; init; } +} + +public sealed record DownloadDirectoryCompleteEvent : Event +{ + public string LocalDirectoryName { get; init; } + public string RemoteDirectoryName { get; init; } + public string Username { get; init; } +}
\ No newline at end of file |
