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 (limited to '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 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 (limited to 'src/slskd/Events/EventService.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 (limited to 'src/slskd/Events/EventService.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 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/Events/EventService.cs') 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 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(-) (limited to 'src/slskd/Events/EventService.cs') 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(-) (limited to 'src/slskd/Events/EventService.cs') 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(-) (limited to 'src/slskd/Events/EventService.cs') 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 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(+) (limited to 'src/slskd/Events/EventService.cs') 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 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(-) (limited to 'src/slskd/Events/EventService.cs') 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