aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2023-09-18 08:46:09 -0500
committerGitHub <noreply@github.com>2023-09-18 08:46:09 -0500
commit77ec3da43c11449d2d4ae64c1413505f7a7741a2 (patch)
tree3eb7d438339be0b7e7b8ef2ded969231422d26fa /src
parenta505a5ee4072d0f50e747e05e1f4b1de86f4c396 (diff)
parent4cdefceae542f59de2d55ffcafc03f2af5edfcc9 (diff)
downloadslskd-77ec3da43c11449d2d4ae64c1413505f7a7741a2.tar.gz
Merge pull request #972 from slskd/scheduler
Add retention settings for transfers, check for 'expired' transfers on a 5 minute interval and remove (soft delete) them
Diffstat (limited to 'src')
-rw-r--r--src/slskd/Application.cs52
-rw-r--r--src/slskd/Core/Clock.cs27
-rw-r--r--src/slskd/Core/Options.cs48
-rw-r--r--src/slskd/Transfers/Downloads/DownloadService.cs125
-rw-r--r--src/slskd/Transfers/Downloads/IDownloadService.cs94
-rw-r--r--src/slskd/Transfers/Uploads/IUploadService.cs90
-rw-r--r--src/slskd/Transfers/Uploads/UploadService.cs121
7 files changed, 371 insertions, 186 deletions
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs
index d15d2025..7002da24 100644
--- a/src/slskd/Application.cs
+++ b/src/slskd/Application.cs
@@ -179,6 +179,9 @@ namespace slskd
ConnectionWatchdog = connectionWatchdog;
Clock.EveryMinute += Clock_EveryMinute;
+ Clock.EveryFiveMinutes += Clock_EveryFiveMinutes;
+ Clock.EveryThirtyMinutes += Clock_EveryThirtyMinutes;
+ Clock.EveryHour += Clock_EveryHour;
}
/// <summary>
@@ -722,6 +725,55 @@ namespace slskd
Metrics.DistributedNetwork.CurrentBroadcastLatency.Set(Client.DistributedNetwork.AverageBroadcastLatency ?? 0);
}
+ private void Clock_EveryFiveMinutes(object sender, EventArgs e)
+ {
+ PruneTransfers();
+ }
+
+ private void Clock_EveryThirtyMinutes(object sender, EventArgs e)
+ {
+ }
+
+ private void Clock_EveryHour(object sender, EventArgs e)
+ {
+ }
+
+ private void PruneTransfers()
+ {
+ var options = OptionsMonitor.CurrentValue.Retention;
+
+ void PruneUpload(int? age, TransferStates state)
+ {
+ if (age.HasValue)
+ {
+ Transfers.Uploads.Prune(age.Value, TransferStates.Completed | state);
+ }
+ }
+
+ void PruneDownload(int? age, TransferStates state)
+ {
+ if (age.HasValue)
+ {
+ Transfers.Downloads.Prune(age.Value, TransferStates.Completed | state);
+ }
+ }
+
+ try
+ {
+ PruneUpload(options.Upload.Succeeded, TransferStates.Succeeded);
+ PruneUpload(options.Upload.Cancelled, TransferStates.Cancelled);
+ PruneUpload(options.Upload.Errored, TransferStates.Errored);
+
+ PruneDownload(options.Download.Succeeded, TransferStates.Succeeded);
+ PruneDownload(options.Download.Cancelled, TransferStates.Cancelled);
+ PruneDownload(options.Download.Errored, TransferStates.Errored);
+ }
+ catch
+ {
+ Log.Error("Encountered one or more errors while pruning transfers");
+ }
+ }
+
private void Client_TransferProgressUpdated(object sender, TransferProgressUpdatedEventArgs args)
{
// no-op. this is really verbose, use for troubleshooting.
diff --git a/src/slskd/Core/Clock.cs b/src/slskd/Core/Clock.cs
index 4d2e6c10..332308d7 100644
--- a/src/slskd/Core/Clock.cs
+++ b/src/slskd/Core/Clock.cs
@@ -28,13 +28,36 @@ namespace slskd
static Clock()
{
EveryMinuteTimer.Elapsed += (_, _) => EveryMinute?.Invoke(null, EventArgs.Empty);
+ EveryFiveMinutesTimer.Elapsed += (_, _) => EveryFiveMinutes?.Invoke(null, EventArgs.Empty);
+ EveryThirtyMinutesTimer.Elapsed += (_, _) => EveryThirtyMinutes?.Invoke(null, EventArgs.Empty);
+ EveryHourTimer.Elapsed += (_, _) => EveryHour?.Invoke(null, EventArgs.Empty);
}
/// <summary>
- /// Fires every 60 seconds.
+ /// Fires every minute.
/// </summary>
public static event EventHandler EveryMinute;
- private static Timer EveryMinuteTimer { get; } = new Timer() { AutoReset = true, Interval = 60000, Enabled = true };
+ /// <summary>
+ /// Fires every 5 minutes.
+ /// </summary>
+ public static event EventHandler EveryFiveMinutes;
+
+ /// <summary>
+ /// Fires every 30 minutes.
+ /// </summary>
+ public static event EventHandler EveryThirtyMinutes;
+
+ /// <summary>
+ /// Fires every hour.
+ /// </summary>
+ public static event EventHandler EveryHour;
+
+ private static Timer EveryMinuteTimer { get; } = CreateTimer(interval: 1000 * 60);
+ private static Timer EveryFiveMinutesTimer { get; } = CreateTimer(interval: 1000 * 60 * 5);
+ private static Timer EveryThirtyMinutesTimer { get; } = CreateTimer(interval: 1000 * 60 * 30);
+ private static Timer EveryHourTimer { get; } = CreateTimer(interval: 1000 * 60 * 60);
+
+ private static Timer CreateTimer(double interval) => new() { AutoReset = true, Interval = interval, Enabled = true };
}
} \ No newline at end of file
diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs
index 2ee21733..30297cac 100644
--- a/src/slskd/Core/Options.cs
+++ b/src/slskd/Core/Options.cs
@@ -254,6 +254,12 @@ namespace slskd
public WebOptions Web { get; init; } = new WebOptions();
/// <summary>
+ /// Gets retention options.
+ /// </summary>
+ [Validate]
+ public RetentionOptions Retention { get; init; } = new RetentionOptions();
+
+ /// <summary>
/// Gets logger options.
/// </summary>
[Validate]
@@ -1049,6 +1055,48 @@ namespace slskd
}
/// <summary>
+ /// Retention options.
+ /// </summary>
+ public class RetentionOptions
+ {
+ /// <summary>
+ /// Gets upload retention options.
+ /// </summary>
+ [Validate]
+ public TransferRetentionOptions Upload { get; init; } = new TransferRetentionOptions();
+
+ /// <summary>
+ /// Gets download retention options.
+ /// </summary>
+ [Validate]
+ public TransferRetentionOptions Download { get; init; } = new TransferRetentionOptions();
+
+ /// <summary>
+ /// Transfer retention options.
+ /// </summary>
+ public class TransferRetentionOptions
+ {
+ /// <summary>
+ /// Gets the time to retain successful transfers, in minutes.
+ /// </summary>
+ [Range(5, maximum: int.MaxValue)]
+ public int? Succeeded { get; init; } = null;
+
+ /// <summary>
+ /// Gets the time to retain errored transfers, in minutes.
+ /// </summary>
+ [Range(5, maximum: int.MaxValue)]
+ public int? Errored { get; init; } = null;
+
+ /// <summary>
+ /// Gets the time to retain cancelled transfers, in minutes.
+ /// </summary>
+ [Range(5, maximum: int.MaxValue)]
+ public int? Cancelled { get; init; } = null;
+ }
+ }
+
+ /// <summary>
/// Metrics options.
/// </summary>
public class MetricsOptions
diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs
index 827a0528..25133629 100644
--- a/src/slskd/Transfers/Downloads/DownloadService.cs
+++ b/src/slskd/Transfers/Downloads/DownloadService.cs
@@ -36,6 +36,84 @@ namespace slskd.Transfers.Downloads
/// <summary>
/// Manages downloads.
/// </summary>
+ public interface IDownloadService
+ {
+ /// <summary>
+ /// Adds the specified <paramref name="transfer"/>. Supersedes any existing record for the same file and username.
+ /// </summary>
+ /// <remarks>This should generally not be called; use EnqueueAsync() instead.</remarks>
+ /// <param name="transfer"></param>
+ void AddOrSupersede(Transfer transfer);
+
+ /// <summary>
+ /// Enqueues the requested list of <paramref name="files"/>.
+ /// </summary>
+ /// <remarks>
+ /// If one file in the specified collection fails, the rest will continue. An <see cref="AggregateException"/> will be
+ /// thrown after all files are dispositioned if any throws.
+ /// </remarks>
+ /// <param name="username">The username of remote user.</param>
+ /// <param name="files">The list of files to enqueue.</param>
+ /// <returns>The operation context.</returns>
+ /// <exception cref="ArgumentException">Thrown when the username is null or an empty string.</exception>
+ /// <exception cref="ArgumentException">Thrown when no files are requested.</exception>
+ /// <exception cref="AggregateException">Thrown when at least one of the requested files throws.</exception>
+ Task EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files);
+
+ /// <summary>
+ /// Finds a single download matching the specified <paramref name="expression"/>.
+ /// </summary>
+ /// <param name="expression">The expression to use to match downloads.</param>
+ /// <returns>The found transfer, or default if not found.</returns>
+ Transfer Find(Expression<Func<Transfer, bool>> expression);
+
+ /// <summary>
+ /// Retrieves the place in the remote queue for the download matching the specified <paramref name="id"/>.
+ /// </summary>
+ /// <param name="id">The unique identifier for the download.</param>
+ /// <returns>The retrieved place in queue.</returns>
+ Task<int> GetPlaceInQueueAsync(Guid id);
+
+ /// <summary>
+ /// Returns a list of all downloads matching the optional <paramref name="expression"/>.
+ /// </summary>
+ /// <param name="expression">An optional expression used to match downloads.</param>
+ /// <param name="includeRemoved">Optionally include downloads that have been removed previously.</param>
+ /// <returns>The list of downloads matching the specified expression, or all downloads if no expression is specified.</returns>
+ List<Transfer> List(Expression<Func<Transfer, bool>> expression = null, bool includeRemoved = false);
+
+ /// <summary>
+ /// Removes <see cref="TransferStates.Completed"/> downloads older than the specified <paramref name="age"/>.
+ /// </summary>
+ /// <param name="age">The age after which downloads are eligible for pruning, in hours.</param>
+ /// <param name="state">An optional, additional state by which downloads are filtered for pruning.</param>
+ /// <returns>The number of pruned downloads.</returns>
+ int Prune(int age, TransferStates state = TransferStates.Completed);
+
+ /// <summary>
+ /// Removes the download matching the specified <paramref name="id"/>.
+ /// </summary>
+ /// <remarks>This is a soft delete; the record is retained for historical retrieval.</remarks>
+ /// <param name="id">The unique identifier of the download.</param>
+ void Remove(Guid id);
+
+ /// <summary>
+ /// Cancels the download matching the specified <paramref name="id"/>, if it is in progress.
+ /// </summary>
+ /// <param name="id">The unique identifier for the download.</param>
+ /// <returns>A value indicating whether the download was successfully cancelled.</returns>
+ bool TryCancel(Guid id);
+
+ /// <summary>
+ /// Updates the specified <paramref name="transfer"/>.
+ /// </summary>
+ /// <param name="transfer">The transfer to update.</param>
+ void Update(Transfer transfer);
+ }
+
+ /// <summary>
+ /// Manages downloads.
+ /// </summary>
public class DownloadService : IDownloadService
{
public DownloadService(
@@ -399,6 +477,53 @@ namespace slskd.Transfers.Downloads
}
/// <summary>
+ /// Removes <see cref="TransferStates.Completed"/> downloads older than the specified <paramref name="age"/>.
+ /// </summary>
+ /// <param name="age">The age after which downloads are eligible for pruning, in hours.</param>
+ /// <param name="state">An optional, additional state by which downloads are filtered for pruning.</param>
+ /// <returns>The number of pruned downloads.</returns>
+ public int Prune(int age, TransferStates state = TransferStates.Completed)
+ {
+ if (!state.HasFlag(TransferStates.Completed))
+ {
+ throw new ArgumentException($"State must include {TransferStates.Completed}", nameof(state));
+ }
+
+ try
+ {
+ using var context = ContextFactory.CreateDbContext();
+
+ var cutoffDateTime = DateTime.UtcNow.AddMinutes(-age);
+
+ var expired = context.Transfers
+ .Where(t => t.Direction == TransferDirection.Download)
+ .Where(t => !t.Removed)
+ .Where(t => t.EndedAt.HasValue && t.EndedAt.Value < cutoffDateTime)
+ .Where(t => t.State == state) // https://github.com/dotnet/efcore/issues/20094
+ .ToList();
+
+ foreach (var tx in expired)
+ {
+ tx.Removed = true;
+ }
+
+ var pruned = context.SaveChanges();
+
+ if (pruned > 0)
+ {
+ Log.Debug("Pruned {Count} expired downloads with state {State}", pruned, state);
+ }
+
+ return pruned;
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Failed to prune downloads: {Message}", ex.Message);
+ throw;
+ }
+ }
+
+ /// <summary>
/// Removes the download matching the specified <paramref name="id"/>.
/// </summary>
/// <remarks>This is a soft delete; the record is retained for historical retrieval.</remarks>
diff --git a/src/slskd/Transfers/Downloads/IDownloadService.cs b/src/slskd/Transfers/Downloads/IDownloadService.cs
deleted file mode 100644
index b49d575c..00000000
--- a/src/slskd/Transfers/Downloads/IDownloadService.cs
+++ /dev/null
@@ -1,94 +0,0 @@
-// <copyright file="IDownloadService.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.Transfers.Downloads
-{
- using System;
- using System.Collections.Generic;
- using System.Linq.Expressions;
- using System.Threading.Tasks;
-
- /// <summary>
- /// Manages downloads.
- /// </summary>
- public interface IDownloadService
- {
- /// <summary>
- /// Adds the specified <paramref name="transfer"/>. Supersedes any existing record for the same file and username.
- /// </summary>
- /// <remarks>This should generally not be called; use EnqueueAsync() instead.</remarks>
- /// <param name="transfer"></param>
- void AddOrSupersede(Transfer transfer);
-
- /// <summary>
- /// Enqueues the requested list of <paramref name="files"/>.
- /// </summary>
- /// <remarks>
- /// If one file in the specified collection fails, the rest will continue. An <see cref="AggregateException"/> will be
- /// thrown after all files are dispositioned if any throws.
- /// </remarks>
- /// <param name="username">The username of remote user.</param>
- /// <param name="files">The list of files to enqueue.</param>
- /// <returns>The operation context.</returns>
- /// <exception cref="ArgumentException">Thrown when the username is null or an empty string.</exception>
- /// <exception cref="ArgumentException">Thrown when no files are requested.</exception>
- /// <exception cref="AggregateException">Thrown when at least one of the requested files throws.</exception>
- Task EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files);
-
- /// <summary>
- /// Finds a single download matching the specified <paramref name="expression"/>.
- /// </summary>
- /// <param name="expression">The expression to use to match downloads.</param>
- /// <returns>The found transfer, or default if not found.</returns>
- Transfer Find(Expression<Func<Transfer, bool>> expression);
-
- /// <summary>
- /// Retrieves the place in the remote queue for the download matching the specified <paramref name="id"/>.
- /// </summary>
- /// <param name="id">The unique identifier for the download.</param>
- /// <returns>The retrieved place in queue.</returns>
- Task<int> GetPlaceInQueueAsync(Guid id);
-
- /// <summary>
- /// Returns a list of all downloads matching the optional <paramref name="expression"/>.
- /// </summary>
- /// <param name="expression">An optional expression used to match downloads.</param>
- /// <param name="includeRemoved">Optionally include downloads that have been removed previously.</param>
- /// <returns>The list of downloads matching the specified expression, or all downloads if no expression is specified.</returns>
- List<Transfer> List(Expression<Func<Transfer, bool>> expression = null, bool includeRemoved = false);
-
- /// <summary>
- /// Removes the download matching the specified <paramref name="id"/>.
- /// </summary>
- /// <remarks>This is a soft delete; the record is retained for historical retrieval.</remarks>
- /// <param name="id">The unique identifier of the download.</param>
- void Remove(Guid id);
-
- /// <summary>
- /// Cancels the download matching the specified <paramref name="id"/>, if it is in progress.
- /// </summary>
- /// <param name="id">The unique identifier for the download.</param>
- /// <returns>A value indicating whether the download was successfully cancelled.</returns>
- bool TryCancel(Guid id);
-
- /// <summary>
- /// Updates the specified <paramref name="transfer"/>.
- /// </summary>
- /// <param name="transfer">The transfer to update.</param>
- void Update(Transfer transfer);
- }
-} \ No newline at end of file
diff --git a/src/slskd/Transfers/Uploads/IUploadService.cs b/src/slskd/Transfers/Uploads/IUploadService.cs
deleted file mode 100644
index 8fa0b194..00000000
--- a/src/slskd/Transfers/Uploads/IUploadService.cs
+++ /dev/null
@@ -1,90 +0,0 @@
-// <copyright file="IUploadService.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.Transfers.Uploads
-{
- using System;
- using System.Collections.Generic;
- using System.Linq.Expressions;
- using System.Threading.Tasks;
-
- /// <summary>
- /// Manages uploads.
- /// </summary>
- public interface IUploadService
- {
- /// <summary>
- /// Gets the upload governor.
- /// </summary>
- IUploadGovernor Governor { get; }
-
- /// <summary>
- /// Gets the upload queue.
- /// </summary>
- IUploadQueue Queue { get; }
-
- /// <summary>
- /// Adds the specified <paramref name="transfer"/>. Supersedes any existing record for the same file and username.
- /// </summary>
- /// <remarks>This should generally not be called; use <see cref="EnqueueAsync(string, string)"/> instead.</remarks>
- /// <param name="transfer"></param>
- void AddOrSupersede(Transfer transfer);
-
- /// <summary>
- /// Enqueues the requested file.
- /// </summary>
- /// <param name="username">The username of the requesting user.</param>
- /// <param name="filename">The local filename of the requested file.</param>
- /// <returns>The operation context.</returns>
- Task EnqueueAsync(string username, string filename);
-
- /// <summary>
- /// Finds a single upload matching the specified <paramref name="expression"/>.
- /// </summary>
- /// <param name="expression">The expression to use to match uploads.</param>
- /// <returns>The found transfer, or default if not found.</returns>
- Transfer Find(Expression<Func<Transfer, bool>> expression);
-
- /// <summary>
- /// Returns a list of all uploads matching the optional <paramref name="expression"/>.
- /// </summary>
- /// <param name="expression">An optional expression used to match uploads.</param>
- /// <param name="includeRemoved">Optionally include uploads that have been removed previously.</param>
- /// <returns>The list of uploads matching the specified expression, or all uploads if no expression is specified.</returns>
- List<Transfer> List(Expression<Func<Transfer, bool>> expression = null, bool includeRemoved = false);
-
- /// <summary>
- /// Removes the upload matching the specified <paramref name="id"/>.
- /// </summary>
- /// <remarks>This is a soft delete; the record is retained for historical retrieval.</remarks>
- /// <param name="id">The unique identifier of the upload.</param>
- void Remove(Guid id);
-
- /// <summary>
- /// Cancels the upload matching the specified <paramref name="id"/>, if it is in progress.
- /// </summary>
- /// <param name="id">The unique identifier for the upload.</param>
- /// <returns>A value indicating whether the upload was successfully cancelled.</returns>
- bool TryCancel(Guid id);
-
- /// <summary>
- /// Synchronously updates the specified <paramref name="transfer"/>.
- /// </summary>
- /// <param name="transfer">The transfer to update.</param>
- void Update(Transfer transfer);
- }
-} \ No newline at end of file
diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs
index cfbeeb8b..04e6a431 100644
--- a/src/slskd/Transfers/Uploads/UploadService.cs
+++ b/src/slskd/Transfers/Uploads/UploadService.cs
@@ -37,6 +37,80 @@ namespace slskd.Transfers.Uploads
/// <summary>
/// Manages uploads.
/// </summary>
+ public interface IUploadService
+ {
+ /// <summary>
+ /// Gets the upload governor.
+ /// </summary>
+ IUploadGovernor Governor { get; }
+
+ /// <summary>
+ /// Gets the upload queue.
+ /// </summary>
+ IUploadQueue Queue { get; }
+
+ /// <summary>
+ /// Adds the specified <paramref name="transfer"/>. Supersedes any existing record for the same file and username.
+ /// </summary>
+ /// <remarks>This should generally not be called; use <see cref="EnqueueAsync(string, string)"/> instead.</remarks>
+ /// <param name="transfer"></param>
+ void AddOrSupersede(Transfer transfer);
+
+ /// <summary>
+ /// Enqueues the requested file.
+ /// </summary>
+ /// <param name="username">The username of the requesting user.</param>
+ /// <param name="filename">The local filename of the requested file.</param>
+ /// <returns>The operation context.</returns>
+ Task EnqueueAsync(string username, string filename);
+
+ /// <summary>
+ /// Finds a single upload matching the specified <paramref name="expression"/>.
+ /// </summary>
+ /// <param name="expression">The expression to use to match uploads.</param>
+ /// <returns>The found transfer, or default if not found.</returns>
+ Transfer Find(Expression<Func<Transfer, bool>> expression);
+
+ /// <summary>
+ /// Returns a list of all uploads matching the optional <paramref name="expression"/>.
+ /// </summary>
+ /// <param name="expression">An optional expression used to match uploads.</param>
+ /// <param name="includeRemoved">Optionally include uploads that have been removed previously.</param>
+ /// <returns>The list of uploads matching the specified expression, or all uploads if no expression is specified.</returns>
+ List<Transfer> List(Expression<Func<Transfer, bool>> expression = null, bool includeRemoved = false);
+
+ /// <summary>
+ /// Removes <see cref="TransferStates.Completed"/> uploads older than the specified <paramref name="age"/>.
+ /// </summary>
+ /// <param name="age">The age after which uploads are eligible for pruning, in hours.</param>
+ /// <param name="state">An optional, additional state by which uploads are filtered for pruning.</param>
+ /// <returns>The number of pruned uploads.</returns>
+ int Prune(int age, TransferStates state = TransferStates.Completed);
+
+ /// <summary>
+ /// Removes the upload matching the specified <paramref name="id"/>.
+ /// </summary>
+ /// <remarks>This is a soft delete; the record is retained for historical retrieval.</remarks>
+ /// <param name="id">The unique identifier of the upload.</param>
+ void Remove(Guid id);
+
+ /// <summary>
+ /// Cancels the upload matching the specified <paramref name="id"/>, if it is in progress.
+ /// </summary>
+ /// <param name="id">The unique identifier for the upload.</param>
+ /// <returns>A value indicating whether the upload was successfully cancelled.</returns>
+ bool TryCancel(Guid id);
+
+ /// <summary>
+ /// Synchronously updates the specified <paramref name="transfer"/>.
+ /// </summary>
+ /// <param name="transfer">The transfer to update.</param>
+ void Update(Transfer transfer);
+ }
+
+ /// <summary>
+ /// Manages uploads.
+ /// </summary>
public class UploadService : IUploadService
{
public UploadService(
@@ -379,6 +453,53 @@ namespace slskd.Transfers.Uploads
}
/// <summary>
+ /// Removes <see cref="TransferStates.Completed"/> uploads older than the specified <paramref name="age"/>.
+ /// </summary>
+ /// <param name="age">The age after which uploads are eligible for pruning, in hours.</param>
+ /// <param name="state">An optional, additional state by which uploads are filtered for pruning.</param>
+ /// <returns>The number of pruned uploads.</returns>
+ public int Prune(int age, TransferStates state = TransferStates.Completed)
+ {
+ if (!state.HasFlag(TransferStates.Completed))
+ {
+ throw new ArgumentException($"State must include {TransferStates.Completed}", nameof(state));
+ }
+
+ try
+ {
+ using var context = ContextFactory.CreateDbContext();
+
+ var cutoffDateTime = DateTime.UtcNow.AddMinutes(-age);
+
+ var expired = context.Transfers
+ .Where(t => t.Direction == TransferDirection.Upload)
+ .Where(t => !t.Removed)
+ .Where(t => t.EndedAt.HasValue && t.EndedAt.Value < cutoffDateTime)
+ .Where(t => t.State == state) // https://github.com/dotnet/efcore/issues/20094
+ .ToList();
+
+ foreach (var tx in expired)
+ {
+ tx.Removed = true;
+ }
+
+ var pruned = context.SaveChanges();
+
+ if (pruned > 0)
+ {
+ Log.Debug("Pruned {Count} expired uploads with state {State}", pruned, state);
+ }
+
+ return pruned;
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Failed to prune uploads: {Message}", ex.Message);
+ throw;
+ }
+ }
+
+ /// <summary>
/// Removes the upload matching the specified <paramref name="id"/>.
/// </summary>
/// <remarks>This is a soft delete; the record is retained for historical retrieval.</remarks>