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') 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