aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2025-12-26 18:31:20 -0600
committerGitHub <noreply@github.com>2025-12-26 18:31:20 -0600
commit6a9c127062b8408e3cad19d4dd283577de6de045 (patch)
tree09dc72a92699a11f23f2d36f3824b6b944e1628e /src
parentc6b61a76059170875df06bb4281d72a84f004fb9 (diff)
parent92bbb7c7e856a9084f6838e36f3e8ff7fb677022 (diff)
downloadslskd-6a9c127062b8408e3cad19d4dd283577de6de045.tar.gz
Merge pull request #1589 from slskd/indexes
Add several indexes to share database, avoid using HasFlag() in other queries
Diffstat (limited to 'src')
-rw-r--r--src/slskd/Application.cs1
-rw-r--r--src/slskd/Shares/SqliteShareRepository.cs4
-rw-r--r--src/slskd/Transfers/API/Controllers/TransfersController.cs30
-rw-r--r--src/slskd/Transfers/Downloads/DownloadService.cs95
-rw-r--r--src/slskd/Transfers/Types/TransferStateCategories.cs97
-rw-r--r--src/slskd/Transfers/Uploads/UploadService.cs82
6 files changed, 214 insertions, 95 deletions
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs
index 97d3392c..6b66ec6e 100644
--- a/src/slskd/Application.cs
+++ b/src/slskd/Application.cs
@@ -87,7 +87,6 @@ namespace slskd
private static int EnqueueRequestQueueDepth = 0;
#pragma warning restore SA1306 // Field names should begin with lower-case letter
-
public Application(
OptionsAtStartup optionsAtStartup,
IOptionsMonitor<Options> optionsMonitor,
diff --git a/src/slskd/Shares/SqliteShareRepository.cs b/src/slskd/Shares/SqliteShareRepository.cs
index 711bb21e..cb0c331a 100644
--- a/src/slskd/Shares/SqliteShareRepository.cs
+++ b/src/slskd/Shares/SqliteShareRepository.cs
@@ -177,6 +177,10 @@ namespace slskd.Shares
conn.ExecuteNonQuery("CREATE TABLE IF NOT EXISTS files " +
"(maskedFilename TEXT PRIMARY KEY, originalFilename TEXT NOT NULL, size BIGINT NOT NULL, touchedAt TEXT NOT NULL, code INTEGER DEFAULT 1 NOT NULL, " +
"extension TEXT, attributeJson TEXT NOT NULL, timestamp INTEGER NOT NULL);");
+
+ conn.ExecuteNonQuery("CREATE INDEX IF NOT EXISTS idx_files_timestamp ON files(timestamp)");
+ conn.ExecuteNonQuery("CREATE INDEX IF NOT EXISTS idx_directories_timestamp ON directories(timestamp)");
+ conn.ExecuteNonQuery("CREATE INDEX IF NOT EXISTS idx_scans_timestamp ON scans(timestamp DESC)");
}
/// <summary>
diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs
index 6be11b2d..3e380000 100644
--- a/src/slskd/Transfers/API/Controllers/TransfersController.cs
+++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs
@@ -115,14 +115,16 @@ namespace slskd.Transfers.API
return Forbid();
}
- var transfers = Transfers.Downloads.List(t => t.State.HasFlag(Soulseek.TransferStates.Completed));
-
- foreach (var id in transfers.Select(t => t.Id))
+ try
{
- Transfers.Downloads.Remove(id);
+ Transfers.Downloads.Remove(t => !t.Removed && TransferStateCategories.Completed.Contains((int)t.State));
+ return NoContent();
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Failed to remove completed downloads: {Message}", ex.Message);
+ return StatusCode(500, ex.Message);
}
-
- return NoContent();
}
/// <summary>
@@ -182,16 +184,16 @@ namespace slskd.Transfers.API
return Forbid();
}
- // get all the transfers that aren't removed
- var transfers = Transfers.Uploads
- .List(t => t.State.HasFlag(Soulseek.TransferStates.Completed), includeRemoved: false);
-
- foreach (var id in transfers.Select(t => t.Id))
+ try
{
- Transfers.Uploads.Remove(id);
+ Transfers.Uploads.Remove(t => !t.Removed && TransferStateCategories.Completed.Contains((int)t.State));
+ return NoContent();
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Failed to remove completed uploads: {Message}", ex.Message);
+ return StatusCode(500, ex.Message);
}
-
- return NoContent();
}
/// <summary>
diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs
index 9bc25373..f1f39fba 100644
--- a/src/slskd/Transfers/Downloads/DownloadService.cs
+++ b/src/slskd/Transfers/Downloads/DownloadService.cs
@@ -89,16 +89,25 @@ namespace slskd.Transfers.Downloads
/// 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="stateHasFlag">An optional, additional state by which downloads are filtered for pruning.</param>
+ /// <param name="states">One or more states by which downloads are filtered for pruning.</param>
/// <returns>The number of pruned downloads.</returns>
- int Prune(int age, TransferStates stateHasFlag = TransferStates.Completed);
+ int Prune(int age, params TransferStates[] states);
/// <summary>
- /// Removes the download matching the specified <paramref name="id"/>.
+ /// Removes the completed 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);
+ /// <returns>A value indicating whether the record was removed.</returns>
+ bool Remove(Guid id);
+
+ /// <summary>
+ /// Removes all completed downloads matching the specified <paramref name="expression"/>.
+ /// </summary>
+ /// <remarks>This is a soft delete; the record is retained for historical retrieval.</remarks>
+ /// <param name="expression">The expression used to match downloads.</param>
+ /// <returns>The number of records removed.</returns>
+ int Remove(Expression<Func<Transfer, bool>> expression);
/// <summary>
/// Cancels the download matching the specified <paramref name="id"/>, if it is in progress.
@@ -307,17 +316,22 @@ namespace slskd.Transfers.Downloads
using var context = ContextFactory.CreateDbContext();
/*
- get all past downloads from this user. this list will remain stable throughout this process because
+ get existing downloads from this user. this list will remain stable throughout this process because
we have exclusive access for this user. we'll be adding new records, but we've already deduplicated
them so we don't have to worry about duplicate records being created in the critical section
+
+ we are looking for:
+ 1. anything that's not yet complete (we need to disallow the enqueue)
+ 2. anything complete, but not yet removed from the UI (we need to supersede it)
*/
- var existingRecords = context.Transfers
+ var existingRecordsNotYetRemoved = context.Transfers
.Where(t => t.Direction == TransferDirection.Download)
.Where(t => t.Username == username)
+ .Where(t => !t.Removed || !TransferStateCategories.Completed.Contains((int)t.State))
.AsNoTracking()
.ToList();
- var existingInProgressRecords = existingRecords
+ var existingInProgressRecords = existingRecordsNotYetRemoved
.Where(t => t.EndedAt == null || !t.State.HasFlag(TransferStates.Completed))
.ToDictionary(t => t.Filename, t => t);
@@ -401,7 +415,7 @@ namespace slskd.Transfers.Downloads
Log.Debug("Added Transfer record for download of {Filename} from {Username} (id: {Id})", transfer.Filename, transfer.Username, transfer.Id);
- foreach (var record in existingRecords.Where(t => t.Filename == file.Filename && !t.Removed))
+ foreach (var record in existingRecordsNotYetRemoved.Where(t => t.Filename == file.Filename && !t.Removed))
{
record.Removed = true;
context.Update(record);
@@ -663,13 +677,15 @@ namespace slskd.Transfers.Downloads
/// 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="stateHasFlag">An optional, additional state by which downloads are filtered for pruning.</param>
+ /// <param name="states">One or more states by which downloads are filtered for pruning.</param>
/// <returns>The number of pruned downloads.</returns>
- public int Prune(int age, TransferStates stateHasFlag = TransferStates.Completed)
+ public int Prune(int age, params TransferStates[] states)
{
- if (!stateHasFlag.HasFlag(TransferStates.Completed))
+ var statesSet = new HashSet<int>(states.Select(s => (int)s));
+
+ if (!statesSet.All(s => ((TransferStates)s).HasFlag(TransferStates.Completed)))
{
- throw new ArgumentException($"State must include {TransferStates.Completed}", nameof(stateHasFlag));
+ throw new ArgumentException($"Each state must include {TransferStates.Completed}", nameof(states));
}
try
@@ -678,23 +694,16 @@ namespace slskd.Transfers.Downloads
var cutoffDateTime = DateTime.UtcNow.AddMinutes(-age);
- var expired = context.Transfers
+ var pruned = 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 == stateHasFlag)
- .ToList();
-
- foreach (var tx in expired)
- {
- tx.Removed = true;
- }
-
- var pruned = context.SaveChanges();
+ .Where(t => statesSet.Contains((int)t.State))
+ .ExecuteUpdate(r => r.SetProperty(c => c.Removed, true));
if (pruned > 0)
{
- Log.Debug("Pruned {Count} expired downloads with state {State}", pruned, stateHasFlag);
+ Log.Debug("Pruned {Count} expired downloads with states {States}", pruned, statesSet);
}
return pruned;
@@ -707,38 +716,40 @@ namespace slskd.Transfers.Downloads
}
/// <summary>
- /// Removes the download matching the specified <paramref name="id"/>.
+ /// Removes the completed 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>
- public void Remove(Guid id)
+ /// <returns>A value indicating whether the record was removed.</returns>
+ public bool Remove(Guid id)
+ {
+ return Remove(t => t.Id == id) > 0;
+ }
+
+ /// <summary>
+ /// Removes all completed downloads matching the specified <paramref name="expression"/>.
+ /// </summary>
+ /// <remarks>This is a soft delete; the record is retained for historical retrieval.</remarks>
+ /// <param name="expression">The expression used to match downloads.</param>
+ /// <returns>The number of records removed.</returns>
+ public int Remove(Expression<Func<Transfer, bool>> expression)
{
try
{
using var context = ContextFactory.CreateDbContext();
- var transfer = context.Transfers
+ var count = context.Transfers
.Where(t => t.Direction == TransferDirection.Download)
- .Where(t => t.Id == id)
- .FirstOrDefault();
-
- if (transfer == default)
- {
- throw new NotFoundException($"No download matching id ${id}");
- }
-
- if (!transfer.State.HasFlag(TransferStates.Completed))
- {
- throw new InvalidOperationException($"Invalid attempt to remove a download before it is complete");
- }
-
- transfer.Removed = true;
+ .Where(t => TransferStateCategories.Completed.Contains((int)t.State))
+ .Where(expression)
+ .ExecuteUpdate(r => r.SetProperty(c => c.Removed, true));
- context.SaveChanges();
+ Log.Debug("Removed {Count} downloads by expression", count);
+ return count;
}
catch (Exception ex)
{
- Log.Error(ex, "Failed to remove download {Id}: {Message}", id, ex.Message);
+ Log.Error(ex, "Failed to remove downloads by expression: {Message}", ex.Message);
throw;
}
}
diff --git a/src/slskd/Transfers/Types/TransferStateCategories.cs b/src/slskd/Transfers/Types/TransferStateCategories.cs
new file mode 100644
index 00000000..02065714
--- /dev/null
+++ b/src/slskd/Transfers/Types/TransferStateCategories.cs
@@ -0,0 +1,97 @@
+// <copyright file="TransferStateCategories.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;
+
+using System.Collections.Generic;
+using Soulseek;
+
+/// <summary>
+/// A collection of transfer state integers, grouped into sets that represent common states.
+/// </summary>
+/// <remarks>
+/// SQLite can't take advantage of indexes when using bitwise operations, which is what Entity Framework
+/// turns HasFlag() expressions into. These hash sets allow us to use IN expressions instead of bitwise.
+/// </remarks>
+public static class TransferStateCategories
+{
+ /// <summary>
+ /// All states representing a successful transfer:
+ ///
+ /// <list type="bullet">
+ /// <item><see cref="TransferStates.Succeeded"/></item>
+ /// </list>
+ /// </summary>
+ public static readonly HashSet<int> Successful = [
+ (int)(TransferStates.Completed | TransferStates.Succeeded)
+ ];
+
+ /// <summary>
+ /// All states representing a failed transfer:
+ ///
+ /// <list type="bullet">
+ /// <item><see cref="TransferStates.Cancelled"/></item>
+ /// <item><see cref="TransferStates.TimedOut"/></item>
+ /// <item><see cref="TransferStates.Errored"/></item>
+ /// <item><see cref="TransferStates.Rejected"/></item>
+ /// <item><see cref="TransferStates.Aborted"/></item>
+ /// </list>
+ /// </summary>
+ public static readonly HashSet<int> Failed = [
+ (int)(TransferStates.Completed | TransferStates.Cancelled),
+ (int)(TransferStates.Completed | TransferStates.TimedOut),
+ (int)(TransferStates.Completed | TransferStates.Errored),
+ (int)(TransferStates.Completed | TransferStates.Rejected),
+ (int)(TransferStates.Completed | TransferStates.Aborted),
+ ];
+
+ /// <summary>
+ /// All states containing the <see cref="TransferStates.Completed"/> flag.
+ /// </summary>
+ public static readonly HashSet<int> Completed = [
+ (int)TransferStates.Completed, // in case some sort of a malfunction or regression
+ .. Successful,
+ .. Failed
+ ];
+
+ /// <summary>
+ /// All states representing a queued transfer:
+ ///
+ /// <list type="bullet">
+ /// <item><see cref="TransferStates.Locally"/></item>
+ /// <item><see cref="TransferStates.Remotely"/></item>
+ /// </list>
+ /// </summary>
+ public static readonly HashSet<int> Queued = [
+ (int)TransferStates.Queued,
+ (int)(TransferStates.Queued | TransferStates.Locally),
+ (int)(TransferStates.Queued | TransferStates.Remotely),
+ ];
+
+ /// <summary>
+ /// All states representing a transfer that is in progress:
+ ///
+ /// <list type="bullet">
+ /// <item><see cref="TransferStates.Initializing"/></item>
+ /// <item><see cref="TransferStates.InProgress"/></item>
+ /// </list>
+ /// </summary>
+ public static readonly HashSet<int> InProgress = [
+ (int)TransferStates.Initializing,
+ (int)TransferStates.InProgress,
+ ];
+} \ No newline at end of file
diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs
index c96d1131..d75ccea3 100644
--- a/src/slskd/Transfers/Uploads/UploadService.cs
+++ b/src/slskd/Transfers/Uploads/UploadService.cs
@@ -107,16 +107,25 @@ namespace slskd.Transfers.Uploads
/// 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 minutes.</param>
- /// <param name="stateHasFlag">An optional, additional state by which uploads are filtered for pruning.</param>
+ /// <param name="states">One or more states by which uploads are filtered for pruning.</param>
/// <returns>The number of pruned uploads.</returns>
- int Prune(int age, TransferStates stateHasFlag = TransferStates.Completed);
+ int Prune(int age, params TransferStates[] states);
/// <summary>
- /// Removes the upload matching the specified <paramref name="id"/>.
+ /// Removes the completed 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);
+ /// <returns>A value indicating whether the record was removed.</returns>
+ bool Remove(Guid id);
+
+ /// <summary>
+ /// Removes all completed uploads matching the specified <paramref name="expression"/>.
+ /// </summary>
+ /// <remarks>This is a soft delete; the record is retained for historical retrieval.</remarks>
+ /// <param name="expression">The expression used to match uploads.</param>
+ /// <returns>The number of records removed.</returns>
+ int Remove(Expression<Func<Transfer, bool>> expression);
/// <summary>
/// Cancels the upload matching the specified <paramref name="id"/>, if it is in progress.
@@ -780,13 +789,15 @@ namespace slskd.Transfers.Uploads
/// 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 minutes.</param>
- /// <param name="stateHasFlag">An optional, additional state by which uploads are filtered for pruning.</param>
+ /// <param name="states">One or more states by which uploads are filtered for pruning.</param>
/// <returns>The number of pruned uploads.</returns>
- public int Prune(int age, TransferStates stateHasFlag = TransferStates.Completed)
+ public int Prune(int age, params TransferStates[] states)
{
- if (!stateHasFlag.HasFlag(TransferStates.Completed))
+ var statesSet = new HashSet<int>(states.Select(s => (int)s));
+
+ if (!statesSet.All(s => ((TransferStates)s).HasFlag(TransferStates.Completed)))
{
- throw new ArgumentException($"State must include {TransferStates.Completed}", nameof(stateHasFlag));
+ throw new ArgumentException($"Each state must include {TransferStates.Completed}", nameof(states));
}
try
@@ -795,23 +806,16 @@ namespace slskd.Transfers.Uploads
var cutoffDateTime = DateTime.UtcNow.AddMinutes(-age);
- var expired = context.Transfers
+ var pruned = 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.HasFlag(stateHasFlag))
- .ToList();
-
- foreach (var tx in expired)
- {
- tx.Removed = true;
- }
-
- var pruned = context.SaveChanges();
+ .Where(t => statesSet.Contains((int)t.State))
+ .ExecuteUpdate(r => r.SetProperty(c => c.Removed, true));
if (pruned > 0)
{
- Log.Debug("Pruned {Count} expired uploads with state {State}", pruned, stateHasFlag);
+ Log.Debug("Pruned {Count} expired uploads with states {States}", pruned, statesSet);
}
return pruned;
@@ -824,38 +828,40 @@ namespace slskd.Transfers.Uploads
}
/// <summary>
- /// Removes the upload matching the specified <paramref name="id"/>.
+ /// Removes the completed 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>
- public void Remove(Guid id)
+ /// <returns>A value indicating whether the record was removed.</returns>
+ public bool Remove(Guid id)
+ {
+ return Remove(t => t.Id == id) > 0;
+ }
+
+ /// <summary>
+ /// Removes all completed uploads matching the specified <paramref name="expression"/>.
+ /// </summary>
+ /// <remarks>This is a soft delete; the record is retained for historical retrieval.</remarks>
+ /// <param name="expression">The expression used to match uploads.</param>
+ /// <returns>The number of records removed.</returns>
+ public int Remove(Expression<Func<Transfer, bool>> expression)
{
try
{
using var context = ContextFactory.CreateDbContext();
- var transfer = context.Transfers
+ var count = context.Transfers
.Where(t => t.Direction == TransferDirection.Upload)
- .Where(t => t.Id == id)
- .FirstOrDefault();
-
- if (transfer == default)
- {
- throw new NotFoundException($"No upload matching id ${id}");
- }
-
- if (!transfer.State.HasFlag(TransferStates.Completed))
- {
- throw new InvalidOperationException($"Invalid attempt to remove an upload before it is complete");
- }
-
- transfer.Removed = true;
+ .Where(t => TransferStateCategories.Completed.Contains((int)t.State))
+ .Where(expression)
+ .ExecuteUpdate(r => r.SetProperty(c => c.Removed, true));
- context.SaveChanges();
+ Log.Debug("Removed {Count} uploads by expression", count);
+ return count;
}
catch (Exception ex)
{
- Log.Error(ex, "Failed to remove upload {Id}: {Message}", id, ex.Message);
+ Log.Error(ex, "Failed to remove uploads by expression: {Message}", ex.Message);
throw;
}
}