From 2e519997abe3a15a9f6b9dba8637644ac6b81af8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 17 Feb 2026 21:44:14 -0600 Subject: change migration naming scheme to order by year --- src/slskd/Core/Data/Migrations/README.md | 2 +- .../Migrations/Z04012025_TransferStateMigration.cs | 236 --------------------- .../Z07062025_TransferIndexesMigration.cs | 92 -------- ...Z07262025_PrivateMessageWasReplayedMigration.cs | 84 -------- ...Z12282025_AdditionalTransferIndexesMigration.cs | 93 -------- .../Z2025_04_01_TransferStateMigration.cs | 236 +++++++++++++++++++++ .../Z2025_07_06_TransferIndexesMigration.cs | 92 ++++++++ ...025_07_26_PrivateMessageWasReplayedMigration.cs | 83 ++++++++ ...025_12_28_AdditionalTransferIndexesMigration.cs | 93 ++++++++ 9 files changed, 505 insertions(+), 506 deletions(-) delete mode 100644 src/slskd/Core/Data/Migrations/Z04012025_TransferStateMigration.cs delete mode 100644 src/slskd/Core/Data/Migrations/Z07062025_TransferIndexesMigration.cs delete mode 100644 src/slskd/Core/Data/Migrations/Z07262025_PrivateMessageWasReplayedMigration.cs delete mode 100644 src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs create mode 100644 src/slskd/Core/Data/Migrations/Z2025_04_01_TransferStateMigration.cs create mode 100644 src/slskd/Core/Data/Migrations/Z2025_07_06_TransferIndexesMigration.cs create mode 100644 src/slskd/Core/Data/Migrations/Z2025_07_26_PrivateMessageWasReplayedMigration.cs create mode 100644 src/slskd/Core/Data/Migrations/Z2025_12_28_AdditionalTransferIndexesMigration.cs (limited to 'src') diff --git a/src/slskd/Core/Data/Migrations/README.md b/src/slskd/Core/Data/Migrations/README.md index 2b5fd6f4..46da7ded 100644 --- a/src/slskd/Core/Data/Migrations/README.md +++ b/src/slskd/Core/Data/Migrations/README.md @@ -11,7 +11,7 @@ The `Migrator` creates a backup of each database prior to running any migrations Each migration must be created as a class that implements the `IMigration` interface. The naming convention for migration classes is: ``` -Z_Migration +Z_Migration ``` Migrations MUST: diff --git a/src/slskd/Core/Data/Migrations/Z04012025_TransferStateMigration.cs b/src/slskd/Core/Data/Migrations/Z04012025_TransferStateMigration.cs deleted file mode 100644 index c6e3d2f1..00000000 --- a/src/slskd/Core/Data/Migrations/Z04012025_TransferStateMigration.cs +++ /dev/null @@ -1,236 +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.Migrations; - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Linq; -using Microsoft.Data.Sqlite; -using Serilog; -using slskd.Transfers; - -/// -/// Updates the Transfers table to: -/// -/// * Add a new StateDescription (TEXT) column -/// * Copy the current (string) contents of the State column to StateDescription -/// * Change the type of the State column to INTEGER -/// * Set the contents of the State column to the numeric representation of the existing State -/// -/// This is necessary because Entity Framework doesn't work with [Flags] enums that are stored -/// as strings; it tries to use bitwise operators to apply HasFlags(), and these obviously don't -/// work against strings. Not sure why EF didn't complain about this, but here we are. -/// -public class Z04012025_TransferStateMigration : IMigration -{ - public Z04012025_TransferStateMigration(ConnectionStringDictionary connectionStrings) - { - ConnectionString = connectionStrings[Database.Transfers]; - } - - private ILogger Log { get; } = Serilog.Log.ForContext(); - private string ConnectionString { get; } - - public bool NeedsToBeApplied() - { - // first, check the existing database to see if the StateDescription column exists - // if it does, the migration has already been applied, or the database has been recreated - var schema = SchemaInspector.GetDatabaseSchema(ConnectionString); - var txfers = schema["Transfers"]; - - return !txfers.Any(c => c.Name == nameof(Transfer.StateDescription)); - } - - public void Apply() - { - if (!NeedsToBeApplied()) - { - Log.Information("> Migration {Name} is not necessary or has already been applied", nameof(Z04012025_TransferStateMigration)); - return; - } - - using var connection = new SqliteConnection(ConnectionString); - connection.Open(); - - // get a distinct list of states from the existing data and translate each into the corresponding integer - var stateMapping = GetStateMapping(connection); - - ModifyTableAndMassageData(connection, stateMapping); - } - - private Dictionary GetStateMapping(SqliteConnection connection) - { - Log.Debug("Fetching states and mapping to integers..."); - - using var command = new SqliteCommand("SELECT DISTINCT State FROM Transfers;", connection); - using var reader = command.ExecuteReader(); - - var dict = new Dictionary(); - - while (reader.Read()) - { - var state = reader.GetString(0); - dict[state] = (int)Enum.Parse(typeof(Z04012025_TransferStateMigration_TransferStates), state); - } - - Log.Debug("State -> int map: {Map}", dict); - return dict; - } - - private void ModifyTableAndMassageData(SqliteConnection connection, Dictionary stateMapping) - { - using var transaction = connection.BeginTransaction(); - - try - { - /* - rename old table so we can create the new one with the layout we want - while preserving the existing data - */ - var rename = @" - ALTER TABLE Transfers RENAME TO Transfers_old; - "; - - using var renameCommand = new SqliteCommand(rename, connection, transaction); - renameCommand.ExecuteNonQuery(); - - /* - create the new table with StateDescription appearing after State - */ - var create = @" - CREATE TABLE Transfers ( - Id TEXT NOT NULL, - Username TEXT, - Direction TEXT NOT NULL, - Filename TEXT, - Size INTEGER NOT NULL, - StartOffset INTEGER NOT NULL, - State INTEGER NOT NULL, - StateDescription TEXT, -- new column - RequestedAt TEXT NOT NULL, - EnqueuedAt TEXT, - StartedAt TEXT, - EndedAt TEXT, - BytesTransferred INTEGER NOT NULL, - AverageSpeed REAL NOT NULL, - PlaceInQueue INTEGER, - Exception TEXT, - Removed INTEGER NOT NULL, - CONSTRAINT PK_Transfers PRIMARY KEY(Id) - ); - "; - - using var createCommand = new SqliteCommand(create, connection, transaction); - createCommand.ExecuteNonQuery(); - - Log.Information("> Schema changes applied, copying data..."); - - /* - copy the existing data into the new table - */ - var copy = @" - INSERT INTO Transfers ( - Id, Username, Direction, Filename, Size, StartOffset, State, - RequestedAt, EnqueuedAt, StartedAt, EndedAt, BytesTransferred, - AverageSpeed, PlaceInQueue, Exception, Removed - ) - SELECT - Id, Username, Direction, Filename, Size, StartOffset, State, - RequestedAt, EnqueuedAt, StartedAt, EndedAt, BytesTransferred, - AverageSpeed, PlaceInQueue, Exception, Removed - FROM Transfers_old;"; - - using var copyCommand = new SqliteCommand(copy, connection, transaction); - copyCommand.ExecuteNonQuery(); - - Log.Information("> Data copied, adjusting columns..."); - - /* - we no longer need the old table, so drop it - */ - using var dropCommand = new SqliteCommand("DROP TABLE Transfers_old;", connection, transaction); - dropCommand.ExecuteNonQuery(); - - /* - copy the existing (string) State value from State to StateDescription - */ - var copyColumnCommand = new SqliteCommand("UPDATE Transfers SET StateDescription = State", connection, transaction); - copyColumnCommand.ExecuteNonQuery(); - - /* - for each of the distinct State values that exist in the data, convert the string - representation into the numeric - - there surely exist better ways to do this, but the reality is that 99% of the records - will be "Completed, Succeeded" (48), with a few "Completed, Errored" or "Completed, Cancelled" - sprinkled in. this should run in reasonable time for large collections - */ - var sw = new Stopwatch(); - var step = 1; - - foreach (var state in stateMapping) - { - sw.Reset(); - Log.Information("> Updating column {Step} of {Total}. This may take some time...", step++, stateMapping.Count); - - Log.Debug("Setting {String} to {Int}", state.Key, state.Value); - - var mapCommand = new SqliteCommand($"UPDATE Transfers SET State = {state.Value} WHERE State = '{state.Key}';", connection, transaction); - mapCommand.ExecuteNonQuery(); - - Log.Debug("{String} to {Int} in {Duration}", state.Key, state.Value, sw.ElapsedMilliseconds); - } - - Log.Debug("Committing transation..."); - transaction.Commit(); - Log.Debug("Transaction committed!"); - Log.Information("> Done!"); - } - catch (Exception) - { - transaction.Rollback(); - throw; - } - } - -#pragma warning disable SA1201 // Elements should appear in the correct order - /// - /// This is a copy of the TransferStates enum as it was at the time this migration was written. This exists to ensure - /// that the migration can be applied to any version of the database, even if the enum changes in the future. - /// - [Flags] - private enum Z04012025_TransferStateMigration_TransferStates - { - None = 0, - Requested = 1, - Queued = 2, - Initializing = 4, - InProgress = 8, - Completed = 16, - Succeeded = 32, - Cancelled = 64, - TimedOut = 128, - Errored = 256, - Rejected = 512, - Aborted = 1024, - Locally = 2048, - Remotely = 4096, - } -#pragma warning restore SA1201 // Elements should appear in the correct order -} diff --git a/src/slskd/Core/Data/Migrations/Z07062025_TransferIndexesMigration.cs b/src/slskd/Core/Data/Migrations/Z07062025_TransferIndexesMigration.cs deleted file mode 100644 index 8ae13734..00000000 --- a/src/slskd/Core/Data/Migrations/Z07062025_TransferIndexesMigration.cs +++ /dev/null @@ -1,92 +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.Migrations; - -using System; -using System.Linq; -using Microsoft.Data.Sqlite; -using Serilog; - -/// -/// Updates the Transfers table to add indexes on the Direction and State columns. -/// -public class Z07062025_TransferIndexesMigration : IMigration -{ - public Z07062025_TransferIndexesMigration(ConnectionStringDictionary connectionStrings) - { - ConnectionString = connectionStrings[Database.Transfers]; - } - - private ILogger Log { get; } = Serilog.Log.ForContext(); - private string ConnectionString { get; } - - public bool NeedsToBeApplied() - { - // check to see if *BOTH* of the indexes are in place. if one or both are missing, we must apply - var idxes = SchemaInspector.GetDatabaseIndexes(ConnectionString); - var txfers = idxes["Transfers"]; - - var directionExists = txfers.Any(c => c.Name.Equals("IDX_Transfers_Direction", StringComparison.OrdinalIgnoreCase)); - var stateExists = txfers.Any(c => c.Name.Equals("IDX_Transfers_State", StringComparison.OrdinalIgnoreCase)); - - if (directionExists && stateExists) - { - return false; - } - - return true; - } - - public void Apply() - { - if (!NeedsToBeApplied()) - { - Log.Information("> Migration {Name} is not necessary or has already been applied", nameof(Z07062025_TransferIndexesMigration)); - return; - } - - using var connection = new SqliteConnection(ConnectionString); - connection.Open(); - - using var transaction = connection.BeginTransaction(); - - try - { - Log.Information("> Adding missing index(es) on the Transfers table..."); - - var directionCommand = new SqliteCommand(@" - CREATE INDEX IF NOT EXISTS IDX_Transfers_Direction ON Transfers (Direction) - ", connection, transaction); - directionCommand.ExecuteNonQuery(); - - var stateCommand = new SqliteCommand(@" - CREATE INDEX IF NOT EXISTS IDX_Transfers_State ON Transfers (State) - ", connection, transaction); - stateCommand.ExecuteNonQuery(); - - Log.Information("> Index(es) created"); - transaction.Commit(); - Log.Information("> Done!"); - } - catch (Exception) - { - transaction.Rollback(); - throw; - } - } -} diff --git a/src/slskd/Core/Data/Migrations/Z07262025_PrivateMessageWasReplayedMigration.cs b/src/slskd/Core/Data/Migrations/Z07262025_PrivateMessageWasReplayedMigration.cs deleted file mode 100644 index a458a756..00000000 --- a/src/slskd/Core/Data/Migrations/Z07262025_PrivateMessageWasReplayedMigration.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.Migrations; - -using System; -using System.Linq; -using Microsoft.Data.Sqlite; -using Serilog; -using slskd.Messaging; - -/// -/// Updates the Transfers table to add indexes on the Direction and State columns. -/// -public class Z07262025_PrivateMessageWasReplayedMigration : IMigration -{ - public Z07262025_PrivateMessageWasReplayedMigration(ConnectionStringDictionary connectionStrings) - { - ConnectionString = connectionStrings[Database.Messaging]; - } - - private ILogger Log { get; } = Serilog.Log.ForContext(); - private string ConnectionString { get; } - - public bool NeedsToBeApplied() - { - // check to see if *BOTH* of the indexes are in place. if one or both are missing, we must apply - var schema = SchemaInspector.GetDatabaseSchema(ConnectionString); - var pms = schema["PrivateMessages"]; - - if (pms.Any(r => r.Name == nameof(PrivateMessage.WasReplayed))) - { - return false; - } - - return true; - } - - public void Apply() - { - if (!NeedsToBeApplied()) - { - Log.Information("> Migration {Name} is not necessary or has already been applied", nameof(Z07262025_PrivateMessageWasReplayedMigration)); - return; - } - - using var connection = new SqliteConnection(ConnectionString); - connection.Open(); - - using var transaction = connection.BeginTransaction(); - - try - { - Log.Information("> Adding missing column WasReplayed to PrivateMessages table..."); - - var addColumnCommand = new SqliteCommand(@" - ALTER TABLE PrivateMessages ADD COLUMN WasReplayed INTEGER NOT NULL DEFAULT 0 - ", connection, transaction); - addColumnCommand.ExecuteNonQuery(); - - transaction.Commit(); - Log.Information("> Done!"); - } - catch (Exception) - { - transaction.Rollback(); - throw; - } - } -} diff --git a/src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs b/src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs deleted file mode 100644 index 2deffeb3..00000000 --- a/src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs +++ /dev/null @@ -1,93 +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.Migrations; - -using System; -using System.Linq; -using Microsoft.Data.Sqlite; -using Serilog; - -/// -/// Adds additional indexes to the Transfers table for Removed, Username/Filename, and user upload statistics. -/// -public class Z12282025_AdditionalTransferIndexesMigration : IMigration -{ - public Z12282025_AdditionalTransferIndexesMigration(ConnectionStringDictionary connectionStrings) - { - ConnectionString = connectionStrings[Database.Transfers]; - } - - private ILogger Log { get; } = Serilog.Log.ForContext(); - private string ConnectionString { get; } - - public bool NeedsToBeApplied() - { - // check to see if *BOTH* of the indexes are in place. if one or both are missing, we must apply - var idxes = SchemaInspector.GetDatabaseIndexes(ConnectionString); - var txfers = idxes["Transfers"]; - - var removedExists = txfers.Any(c => c.Name.Equals("IDX_Transfers_Removed", StringComparison.OrdinalIgnoreCase)); - var usernameFilenameExists = txfers.Any(c => c.Name.Equals("IDX_Transfers_UsernameFilename", StringComparison.OrdinalIgnoreCase)); - var statsExist = txfers.Any(c => c.Name.Equals("IDX_Transfers_UserUploadStatistics", StringComparison.OrdinalIgnoreCase)); - - if (removedExists && usernameFilenameExists && statsExist) - { - return false; - } - - return true; - } - - public void Apply() - { - if (!NeedsToBeApplied()) - { - Log.Information("> Migration {Name} is not necessary or has already been applied", nameof(Z12282025_AdditionalTransferIndexesMigration)); - return; - } - - using var connection = new SqliteConnection(ConnectionString); - connection.Open(); - - using var transaction = connection.BeginTransaction(); - - try - { - void Exec(string sql) - { - using var command = new SqliteCommand(sql, connection, transaction); - command.ExecuteNonQuery(); - } - - Log.Information("> Adding missing index(es) on the Transfers table..."); - - Exec("CREATE INDEX IF NOT EXISTS IDX_Transfers_Removed ON Transfers (Removed)"); - Exec("CREATE INDEX IF NOT EXISTS IDX_Transfers_UsernameFilename ON Transfers (Username, Filename)"); - Exec("CREATE INDEX IF NOT EXISTS IDX_Transfers_UserUploadStatistics ON Transfers (Username, Direction, EndedAt, StartedAt, State, Size)"); - - Log.Information("> Index(es) created"); - transaction.Commit(); - Log.Information("> Done!"); - } - catch (Exception) - { - transaction.Rollback(); - throw; - } - } -} diff --git a/src/slskd/Core/Data/Migrations/Z2025_04_01_TransferStateMigration.cs b/src/slskd/Core/Data/Migrations/Z2025_04_01_TransferStateMigration.cs new file mode 100644 index 00000000..146541dd --- /dev/null +++ b/src/slskd/Core/Data/Migrations/Z2025_04_01_TransferStateMigration.cs @@ -0,0 +1,236 @@ +// +// 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.Migrations; + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using Microsoft.Data.Sqlite; +using Serilog; +using slskd.Transfers; + +/// +/// Updates the Transfers table to: +/// +/// * Add a new StateDescription (TEXT) column +/// * Copy the current (string) contents of the State column to StateDescription +/// * Change the type of the State column to INTEGER +/// * Set the contents of the State column to the numeric representation of the existing State +/// +/// This is necessary because Entity Framework doesn't work with [Flags] enums that are stored +/// as strings; it tries to use bitwise operators to apply HasFlags(), and these obviously don't +/// work against strings. Not sure why EF didn't complain about this, but here we are. +/// +public class Z2025_04_01_TransferStateMigration : IMigration +{ + public Z2025_04_01_TransferStateMigration(ConnectionStringDictionary connectionStrings) + { + ConnectionString = connectionStrings[Database.Transfers]; + } + + private ILogger Log { get; } = Serilog.Log.ForContext(); + private string ConnectionString { get; } + + public bool NeedsToBeApplied() + { + // first, check the existing database to see if the StateDescription column exists + // if it does, the migration has already been applied, or the database has been recreated + var schema = SchemaInspector.GetDatabaseSchema(ConnectionString); + var txfers = schema["Transfers"]; + + return !txfers.Any(c => c.Name == nameof(Transfer.StateDescription)); + } + + public void Apply() + { + if (!NeedsToBeApplied()) + { + Log.Information("> Migration {Name} is not necessary or has already been applied", nameof(Z2025_04_01_TransferStateMigration)); + return; + } + + using var connection = new SqliteConnection(ConnectionString); + connection.Open(); + + // get a distinct list of states from the existing data and translate each into the corresponding integer + var stateMapping = GetStateMapping(connection); + + ModifyTableAndMassageData(connection, stateMapping); + } + + private Dictionary GetStateMapping(SqliteConnection connection) + { + Log.Debug("Fetching states and mapping to integers..."); + + using var command = new SqliteCommand("SELECT DISTINCT State FROM Transfers;", connection); + using var reader = command.ExecuteReader(); + + var dict = new Dictionary(); + + while (reader.Read()) + { + var state = reader.GetString(0); + dict[state] = (int)Enum.Parse(typeof(Z04012025_TransferStateMigration_TransferStates), state); + } + + Log.Debug("State -> int map: {Map}", dict); + return dict; + } + + private void ModifyTableAndMassageData(SqliteConnection connection, Dictionary stateMapping) + { + using var transaction = connection.BeginTransaction(); + + try + { + /* + rename old table so we can create the new one with the layout we want + while preserving the existing data + */ + var rename = @" + ALTER TABLE Transfers RENAME TO Transfers_old; + "; + + using var renameCommand = new SqliteCommand(rename, connection, transaction); + renameCommand.ExecuteNonQuery(); + + /* + create the new table with StateDescription appearing after State + */ + var create = @" + CREATE TABLE Transfers ( + Id TEXT NOT NULL, + Username TEXT, + Direction TEXT NOT NULL, + Filename TEXT, + Size INTEGER NOT NULL, + StartOffset INTEGER NOT NULL, + State INTEGER NOT NULL, + StateDescription TEXT, -- new column + RequestedAt TEXT NOT NULL, + EnqueuedAt TEXT, + StartedAt TEXT, + EndedAt TEXT, + BytesTransferred INTEGER NOT NULL, + AverageSpeed REAL NOT NULL, + PlaceInQueue INTEGER, + Exception TEXT, + Removed INTEGER NOT NULL, + CONSTRAINT PK_Transfers PRIMARY KEY(Id) + ); + "; + + using var createCommand = new SqliteCommand(create, connection, transaction); + createCommand.ExecuteNonQuery(); + + Log.Information("> Schema changes applied, copying data..."); + + /* + copy the existing data into the new table + */ + var copy = @" + INSERT INTO Transfers ( + Id, Username, Direction, Filename, Size, StartOffset, State, + RequestedAt, EnqueuedAt, StartedAt, EndedAt, BytesTransferred, + AverageSpeed, PlaceInQueue, Exception, Removed + ) + SELECT + Id, Username, Direction, Filename, Size, StartOffset, State, + RequestedAt, EnqueuedAt, StartedAt, EndedAt, BytesTransferred, + AverageSpeed, PlaceInQueue, Exception, Removed + FROM Transfers_old;"; + + using var copyCommand = new SqliteCommand(copy, connection, transaction); + copyCommand.ExecuteNonQuery(); + + Log.Information("> Data copied, adjusting columns..."); + + /* + we no longer need the old table, so drop it + */ + using var dropCommand = new SqliteCommand("DROP TABLE Transfers_old;", connection, transaction); + dropCommand.ExecuteNonQuery(); + + /* + copy the existing (string) State value from State to StateDescription + */ + var copyColumnCommand = new SqliteCommand("UPDATE Transfers SET StateDescription = State", connection, transaction); + copyColumnCommand.ExecuteNonQuery(); + + /* + for each of the distinct State values that exist in the data, convert the string + representation into the numeric + + there surely exist better ways to do this, but the reality is that 99% of the records + will be "Completed, Succeeded" (48), with a few "Completed, Errored" or "Completed, Cancelled" + sprinkled in. this should run in reasonable time for large collections + */ + var sw = new Stopwatch(); + var step = 1; + + foreach (var state in stateMapping) + { + sw.Reset(); + Log.Information("> Updating column {Step} of {Total}. This may take some time...", step++, stateMapping.Count); + + Log.Debug("Setting {String} to {Int}", state.Key, state.Value); + + var mapCommand = new SqliteCommand($"UPDATE Transfers SET State = {state.Value} WHERE State = '{state.Key}';", connection, transaction); + mapCommand.ExecuteNonQuery(); + + Log.Debug("{String} to {Int} in {Duration}", state.Key, state.Value, sw.ElapsedMilliseconds); + } + + Log.Debug("Committing transation..."); + transaction.Commit(); + Log.Debug("Transaction committed!"); + Log.Information("> Done!"); + } + catch (Exception) + { + transaction.Rollback(); + throw; + } + } + +#pragma warning disable SA1201 // Elements should appear in the correct order + /// + /// This is a copy of the TransferStates enum as it was at the time this migration was written. This exists to ensure + /// that the migration can be applied to any version of the database, even if the enum changes in the future. + /// + [Flags] + private enum Z04012025_TransferStateMigration_TransferStates + { + None = 0, + Requested = 1, + Queued = 2, + Initializing = 4, + InProgress = 8, + Completed = 16, + Succeeded = 32, + Cancelled = 64, + TimedOut = 128, + Errored = 256, + Rejected = 512, + Aborted = 1024, + Locally = 2048, + Remotely = 4096, + } +#pragma warning restore SA1201 // Elements should appear in the correct order +} diff --git a/src/slskd/Core/Data/Migrations/Z2025_07_06_TransferIndexesMigration.cs b/src/slskd/Core/Data/Migrations/Z2025_07_06_TransferIndexesMigration.cs new file mode 100644 index 00000000..df93f685 --- /dev/null +++ b/src/slskd/Core/Data/Migrations/Z2025_07_06_TransferIndexesMigration.cs @@ -0,0 +1,92 @@ +// +// 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.Migrations; + +using System; +using System.Linq; +using Microsoft.Data.Sqlite; +using Serilog; + +/// +/// Updates the Transfers table to add indexes on the Direction and State columns. +/// +public class Z2025_07_06_TransferIndexesMigration : IMigration +{ + public Z2025_07_06_TransferIndexesMigration(ConnectionStringDictionary connectionStrings) + { + ConnectionString = connectionStrings[Database.Transfers]; + } + + private ILogger Log { get; } = Serilog.Log.ForContext(); + private string ConnectionString { get; } + + public bool NeedsToBeApplied() + { + // check to see if *BOTH* of the indexes are in place. if one or both are missing, we must apply + var idxes = SchemaInspector.GetDatabaseIndexes(ConnectionString); + var txfers = idxes["Transfers"]; + + var directionExists = txfers.Any(c => c.Name.Equals("IDX_Transfers_Direction", StringComparison.OrdinalIgnoreCase)); + var stateExists = txfers.Any(c => c.Name.Equals("IDX_Transfers_State", StringComparison.OrdinalIgnoreCase)); + + if (directionExists && stateExists) + { + return false; + } + + return true; + } + + public void Apply() + { + if (!NeedsToBeApplied()) + { + Log.Information("> Migration {Name} is not necessary or has already been applied", nameof(Z2025_07_06_TransferIndexesMigration)); + return; + } + + using var connection = new SqliteConnection(ConnectionString); + connection.Open(); + + using var transaction = connection.BeginTransaction(); + + try + { + Log.Information("> Adding missing index(es) on the Transfers table..."); + + var directionCommand = new SqliteCommand(@" + CREATE INDEX IF NOT EXISTS IDX_Transfers_Direction ON Transfers (Direction) + ", connection, transaction); + directionCommand.ExecuteNonQuery(); + + var stateCommand = new SqliteCommand(@" + CREATE INDEX IF NOT EXISTS IDX_Transfers_State ON Transfers (State) + ", connection, transaction); + stateCommand.ExecuteNonQuery(); + + Log.Information("> Index(es) created"); + transaction.Commit(); + Log.Information("> Done!"); + } + catch (Exception) + { + transaction.Rollback(); + throw; + } + } +} diff --git a/src/slskd/Core/Data/Migrations/Z2025_07_26_PrivateMessageWasReplayedMigration.cs b/src/slskd/Core/Data/Migrations/Z2025_07_26_PrivateMessageWasReplayedMigration.cs new file mode 100644 index 00000000..c3f3664b --- /dev/null +++ b/src/slskd/Core/Data/Migrations/Z2025_07_26_PrivateMessageWasReplayedMigration.cs @@ -0,0 +1,83 @@ +// +// 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.Migrations; + +using System; +using System.Linq; +using Microsoft.Data.Sqlite; +using Serilog; +using slskd.Messaging; + +/// +/// Updates the Transfers table to add indexes on the Direction and State columns. +/// +public class Z2025_07_26_PrivateMessageWasReplayedMigration : IMigration +{ + public Z2025_07_26_PrivateMessageWasReplayedMigration(ConnectionStringDictionary connectionStrings) + { + ConnectionString = connectionStrings[Database.Messaging]; + } + + private ILogger Log { get; } = Serilog.Log.ForContext(); + private string ConnectionString { get; } + + public bool NeedsToBeApplied() + { + var schema = SchemaInspector.GetDatabaseSchema(ConnectionString); + var pms = schema["PrivateMessages"]; + + if (pms.Any(r => r.Name == nameof(PrivateMessage.WasReplayed))) + { + return false; + } + + return true; + } + + public void Apply() + { + if (!NeedsToBeApplied()) + { + Log.Information("> Migration {Name} is not necessary or has already been applied", nameof(Z2025_07_26_PrivateMessageWasReplayedMigration)); + return; + } + + using var connection = new SqliteConnection(ConnectionString); + connection.Open(); + + using var transaction = connection.BeginTransaction(); + + try + { + Log.Information("> Adding missing column WasReplayed to PrivateMessages table..."); + + var addColumnCommand = new SqliteCommand(@" + ALTER TABLE PrivateMessages ADD COLUMN WasReplayed INTEGER NOT NULL DEFAULT 0 + ", connection, transaction); + addColumnCommand.ExecuteNonQuery(); + + transaction.Commit(); + Log.Information("> Done!"); + } + catch (Exception) + { + transaction.Rollback(); + throw; + } + } +} diff --git a/src/slskd/Core/Data/Migrations/Z2025_12_28_AdditionalTransferIndexesMigration.cs b/src/slskd/Core/Data/Migrations/Z2025_12_28_AdditionalTransferIndexesMigration.cs new file mode 100644 index 00000000..e66cc59d --- /dev/null +++ b/src/slskd/Core/Data/Migrations/Z2025_12_28_AdditionalTransferIndexesMigration.cs @@ -0,0 +1,93 @@ +// +// 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.Migrations; + +using System; +using System.Linq; +using Microsoft.Data.Sqlite; +using Serilog; + +/// +/// Adds additional indexes to the Transfers table for Removed, Username/Filename, and user upload statistics. +/// +public class Z2025_12_28_AdditionalTransferIndexesMigration : IMigration +{ + public Z2025_12_28_AdditionalTransferIndexesMigration(ConnectionStringDictionary connectionStrings) + { + ConnectionString = connectionStrings[Database.Transfers]; + } + + private ILogger Log { get; } = Serilog.Log.ForContext(); + private string ConnectionString { get; } + + public bool NeedsToBeApplied() + { + // check to see if *BOTH* of the indexes are in place. if one or both are missing, we must apply + var idxes = SchemaInspector.GetDatabaseIndexes(ConnectionString); + var txfers = idxes["Transfers"]; + + var removedExists = txfers.Any(c => c.Name.Equals("IDX_Transfers_Removed", StringComparison.OrdinalIgnoreCase)); + var usernameFilenameExists = txfers.Any(c => c.Name.Equals("IDX_Transfers_UsernameFilename", StringComparison.OrdinalIgnoreCase)); + var statsExist = txfers.Any(c => c.Name.Equals("IDX_Transfers_UserUploadStatistics", StringComparison.OrdinalIgnoreCase)); + + if (removedExists && usernameFilenameExists && statsExist) + { + return false; + } + + return true; + } + + public void Apply() + { + if (!NeedsToBeApplied()) + { + Log.Information("> Migration {Name} is not necessary or has already been applied", nameof(Z2025_12_28_AdditionalTransferIndexesMigration)); + return; + } + + using var connection = new SqliteConnection(ConnectionString); + connection.Open(); + + using var transaction = connection.BeginTransaction(); + + try + { + void Exec(string sql) + { + using var command = new SqliteCommand(sql, connection, transaction); + command.ExecuteNonQuery(); + } + + Log.Information("> Adding missing index(es) on the Transfers table..."); + + Exec("CREATE INDEX IF NOT EXISTS IDX_Transfers_Removed ON Transfers (Removed)"); + Exec("CREATE INDEX IF NOT EXISTS IDX_Transfers_UsernameFilename ON Transfers (Username, Filename)"); + Exec("CREATE INDEX IF NOT EXISTS IDX_Transfers_UserUploadStatistics ON Transfers (Username, Direction, EndedAt, StartedAt, State, Size)"); + + Log.Information("> Index(es) created"); + transaction.Commit(); + Log.Information("> Done!"); + } + catch (Exception) + { + transaction.Rollback(); + throw; + } + } +} -- cgit v1.2.3 From 9361ecce8e36cd59fcb923f54144757e26bf2708 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 17 Feb 2026 21:44:42 -0600 Subject: add Attempts and GroupId to Transfer --- ...26_02_17_TransferAttemptsAndGroupIdMigration.cs | 109 +++++++++++++++++++++ src/slskd/Core/Data/Migrator.cs | 9 +- src/slskd/Transfers/TransfersDbContext.cs | 10 ++ src/slskd/Transfers/Types/Transfer.cs | 4 + 4 files changed, 128 insertions(+), 4 deletions(-) create mode 100644 src/slskd/Core/Data/Migrations/Z2026_02_17_TransferAttemptsAndGroupIdMigration.cs (limited to 'src') diff --git a/src/slskd/Core/Data/Migrations/Z2026_02_17_TransferAttemptsAndGroupIdMigration.cs b/src/slskd/Core/Data/Migrations/Z2026_02_17_TransferAttemptsAndGroupIdMigration.cs new file mode 100644 index 00000000..dfdd68eb --- /dev/null +++ b/src/slskd/Core/Data/Migrations/Z2026_02_17_TransferAttemptsAndGroupIdMigration.cs @@ -0,0 +1,109 @@ +// +// 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.Migrations; + +using System; +using System.Linq; +using Microsoft.Data.Sqlite; +using Serilog; +using slskd.Transfers; + +/// +/// Updates the Transfers table to add Attempts and GroupId columns. +/// +public class Z2026_02_17_TransferAttemptsAndGroupIdMigration : IMigration +{ + public Z2026_02_17_TransferAttemptsAndGroupIdMigration(ConnectionStringDictionary connectionStrings) + { + ConnectionString = connectionStrings[Database.Transfers]; + } + + private ILogger Log { get; } = Serilog.Log.ForContext(); + private string ConnectionString { get; } + + public bool NeedsToBeApplied() + { + var schema = SchemaInspector.GetDatabaseSchema(ConnectionString); + var idxes = SchemaInspector.GetDatabaseIndexes(ConnectionString); + + var columns = schema["Transfers"]; + var indexes = idxes["Transfers"]; + + // check to see if the Attempts and GroupId columns exist + if (columns.Any(c => c.Name == nameof(Transfer.Attempts)) + && columns.Any(c => c.Name == nameof(Transfer.GroupId)) + && indexes.Any(i => i.Name.Equals("IDX_Transfers_GroupId", StringComparison.OrdinalIgnoreCase))) + { + return false; + } + + return true; + } + + public void Apply() + { + if (!NeedsToBeApplied()) + { + Log.Information("> Migration {Name} is not necessary or has already been applied", nameof(Z2026_02_17_TransferAttemptsAndGroupIdMigration)); + return; + } + + var columns = SchemaInspector.GetDatabaseSchema(ConnectionString)["Transfers"]; + + using var connection = new SqliteConnection(ConnectionString); + connection.Open(); + + using var transaction = connection.BeginTransaction(); + + try + { + void Exec(string sql) + { + using var command = new SqliteCommand(sql, connection, transaction); + command.ExecuteNonQuery(); + } + + Log.Information("> Adding GroupId and Attempts columns to the Transfers table..."); + + if (!columns.Any(c => c.Name == nameof(Transfer.GroupId))) + { + Exec("ALTER TABLE Transfers ADD COLUMN GroupId TEXT NULL;"); + } + + if (!columns.Any(c => c.Name == nameof(Transfer.Attempts))) + { + Exec("ALTER TABLE Transfers ADD COLUMN Attempts INTEGER NOT NULL DEFAULT 0;"); + } + + Log.Information("> New columns added"); + + Log.Information("> Adding missing index(es) on the Transfers table..."); + + Exec("CREATE INDEX IF NOT EXISTS IDX_Transfers_GroupId ON Transfers (GroupId)"); + + Log.Information("> Index(es) created"); + transaction.Commit(); + Log.Information("> Done!"); + } + catch (Exception) + { + transaction.Rollback(); + throw; + } + } +} diff --git a/src/slskd/Core/Data/Migrator.cs b/src/slskd/Core/Data/Migrator.cs index 5561de4b..a5096143 100644 --- a/src/slskd/Core/Data/Migrator.cs +++ b/src/slskd/Core/Data/Migrator.cs @@ -40,10 +40,11 @@ public class Migrator Migrations = new() { - { nameof(Z04012025_TransferStateMigration), new Z04012025_TransferStateMigration(connectionStrings: Databases) }, - { nameof(Z07062025_TransferIndexesMigration), new Z07062025_TransferIndexesMigration(connectionStrings: Databases) }, - { nameof(Z07262025_PrivateMessageWasReplayedMigration), new Z07262025_PrivateMessageWasReplayedMigration(connectionStrings: Databases) }, - { nameof(Z12282025_AdditionalTransferIndexesMigration), new Z12282025_AdditionalTransferIndexesMigration(connectionStrings: Databases) }, + { nameof(Z2025_04_01_TransferStateMigration), new Z2025_04_01_TransferStateMigration(connectionStrings: Databases) }, + { nameof(Z2025_07_06_TransferIndexesMigration), new Z2025_07_06_TransferIndexesMigration(connectionStrings: Databases) }, + { nameof(Z2025_07_26_PrivateMessageWasReplayedMigration), new Z2025_07_26_PrivateMessageWasReplayedMigration(connectionStrings: Databases) }, + { nameof(Z2025_12_28_AdditionalTransferIndexesMigration), new Z2025_12_28_AdditionalTransferIndexesMigration(connectionStrings: Databases) }, + { nameof(Z2026_02_17_TransferAttemptsAndGroupIdMigration), new Z2026_02_17_TransferAttemptsAndGroupIdMigration(connectionStrings: Databases) }, }; } diff --git a/src/slskd/Transfers/TransfersDbContext.cs b/src/slskd/Transfers/TransfersDbContext.cs index 422595e9..79171809 100644 --- a/src/slskd/Transfers/TransfersDbContext.cs +++ b/src/slskd/Transfers/TransfersDbContext.cs @@ -76,6 +76,16 @@ namespace slskd.Transfers .HasIndex(t => t.Removed) .HasDatabaseName("IDX_Transfers_Removed"); + modelBuilder + .Entity() + .Property(e => e.Attempts) + .HasDefaultValue(0); // force EF to match the migration + + modelBuilder + .Entity() + .HasIndex(t => t.GroupId) + .HasDatabaseName("IDX_Transfers_GroupId"); + // covers the check for existing records when enqueueing uploads and downloads modelBuilder .Entity() diff --git a/src/slskd/Transfers/Types/Transfer.cs b/src/slskd/Transfers/Types/Transfer.cs index 338aba38..e2ef6d5d 100644 --- a/src/slskd/Transfers/Types/Transfer.cs +++ b/src/slskd/Transfers/Types/Transfer.cs @@ -25,6 +25,8 @@ namespace slskd.Transfers public class Transfer { + public Guid? GroupId { get; init; } = null; + [Key] public Guid Id { get; init; } public string Username { get; init; } @@ -65,6 +67,8 @@ namespace slskd.Transfers public int? PlaceInQueue { get; set; } public string Exception { get; set; } + public int Attempts { get; set; } = 0; + [JsonIgnore] public bool Removed { get; set; } -- cgit v1.2.3 From 1fd765471018c283761eb32c33ce229b2aaa86b5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 17 Feb 2026 21:45:15 -0600 Subject: flatten params --- src/slskd/Common/Retry.cs | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/Retry.cs b/src/slskd/Common/Retry.cs index 300c1c51..f57b59d8 100644 --- a/src/slskd/Common/Retry.cs +++ b/src/slskd/Common/Retry.cs @@ -37,7 +37,13 @@ namespace slskd /// The maximum delay in milliseconds. /// The token to monitor for cancellation requests. /// The execution context. - public static async Task Do(Func task, Func isRetryable = null, Action onFailure = null, int maxAttempts = 3, int maxDelayInMilliseconds = int.MaxValue, CancellationToken cancellationToken = default) + public static async Task Do( + Func task, + Func isRetryable = null, + Action onFailure = null, + int maxAttempts = 3, + int maxDelayInMilliseconds = int.MaxValue, + CancellationToken cancellationToken = default) { await Do(async () => { @@ -57,7 +63,13 @@ namespace slskd /// The token to monitor for cancellation requests. /// The Type of the logic return value. /// The execution context. - public static async Task Do(Func> task, Func isRetryable = null, Action onFailure = null, int maxAttempts = 3, int maxDelayInMilliseconds = int.MaxValue, CancellationToken cancellationToken = default) + public static async Task Do( + Func> task, + Func isRetryable = null, + Action onFailure = null, + int maxAttempts = 3, + int maxDelayInMilliseconds = int.MaxValue, + CancellationToken cancellationToken = default) { isRetryable ??= (_, _) => true; onFailure ??= (_, _) => { }; -- cgit v1.2.3 From c5493131664457885f34172e15348db9fb2a95af Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 17 Feb 2026 22:10:00 -0600 Subject: allow base delay to be sent to ExponentialBackoffDelay --- src/slskd/Common/Compute.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/Compute.cs b/src/slskd/Common/Compute.cs index befceb88..f614d011 100644 --- a/src/slskd/Common/Compute.cs +++ b/src/slskd/Common/Compute.cs @@ -26,14 +26,14 @@ namespace slskd /// public static class Compute { - public static (int Delay, int Jitter) ExponentialBackoffDelay(int iteration, int maxDelayInMilliseconds = int.MaxValue) + public static (int Delay, int Jitter) ExponentialBackoffDelay(int iteration, int baseDelayInMilliseconds = 1000, int maxDelayInMilliseconds = int.MaxValue) { iteration = Math.Min(100, iteration); - var computedDelay = Math.Floor((Math.Pow(2, iteration) - 1) / 2) * 1000; + var computedDelay = Math.Floor((Math.Pow(2, iteration) - 1) / 2) * baseDelayInMilliseconds; var clampedDelay = (int)Math.Min(computedDelay, maxDelayInMilliseconds); - var jitter = new Random().Next(1000); + var jitter = Random.Shared.Next(baseDelayInMilliseconds); return (clampedDelay, jitter); } -- cgit v1.2.3 From 9d9259214d9c3ce01758528ddcde508d7d895783 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 17 Feb 2026 22:10:12 -0600 Subject: add base delay --- src/slskd/Common/Retry.cs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/Retry.cs b/src/slskd/Common/Retry.cs index f57b59d8..eff88659 100644 --- a/src/slskd/Common/Retry.cs +++ b/src/slskd/Common/Retry.cs @@ -34,6 +34,7 @@ namespace slskd /// A function returning a value indicating whether the last Exception is retryable. /// An action to execute on failure. /// The maximum number of retry attempts. + /// The base delay in milliseconds. /// The maximum delay in milliseconds. /// The token to monitor for cancellation requests. /// The execution context. @@ -42,6 +43,7 @@ namespace slskd Func isRetryable = null, Action onFailure = null, int maxAttempts = 3, + int baseDelayInMilliseconds = 1000, int maxDelayInMilliseconds = int.MaxValue, CancellationToken cancellationToken = default) { @@ -49,7 +51,7 @@ namespace slskd { await task(); return Task.FromResult(null); - }, isRetryable, onFailure, maxAttempts, maxDelayInMilliseconds, cancellationToken); + }, isRetryable, onFailure, maxAttempts, baseDelayInMilliseconds, maxDelayInMilliseconds, cancellationToken); } /// @@ -59,6 +61,7 @@ namespace slskd /// A function returning a value indicating whether the last Exception is retryable. /// An action to execute on failure. /// The maximum number of retry attempts. + /// The base delay in milliseconds. /// The maximum delay in milliseconds. /// The token to monitor for cancellation requests. /// The Type of the logic return value. @@ -68,6 +71,7 @@ namespace slskd Func isRetryable = null, Action onFailure = null, int maxAttempts = 3, + int baseDelayInMilliseconds = 1000, int maxDelayInMilliseconds = int.MaxValue, CancellationToken cancellationToken = default) { @@ -87,7 +91,7 @@ namespace slskd { if (attempts > 0) { - var (delay, jitter) = Compute.ExponentialBackoffDelay(attempts, maxDelayInMilliseconds); + var (delay, jitter) = Compute.ExponentialBackoffDelay(attempts, baseDelayInMilliseconds, maxDelayInMilliseconds); await Task.Delay(delay + jitter, cancellationToken); } -- cgit v1.2.3 From c4574d13c454cfcef27ed29da446159e7f46f919 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 18 Feb 2026 18:54:19 -0600 Subject: add onRetry delegate --- src/slskd/Common/Retry.cs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/Retry.cs b/src/slskd/Common/Retry.cs index eff88659..457d32fb 100644 --- a/src/slskd/Common/Retry.cs +++ b/src/slskd/Common/Retry.cs @@ -32,6 +32,7 @@ namespace slskd /// /// The logic to execute. /// A function returning a value indicating whether the last Exception is retryable. + /// An action to execute before beginning a retry attempt. /// An action to execute on failure. /// The maximum number of retry attempts. /// The base delay in milliseconds. @@ -41,6 +42,7 @@ namespace slskd public static async Task Do( Func task, Func isRetryable = null, + Action onRetry = null, Action onFailure = null, int maxAttempts = 3, int baseDelayInMilliseconds = 1000, @@ -51,7 +53,7 @@ namespace slskd { await task(); return Task.FromResult(null); - }, isRetryable, onFailure, maxAttempts, baseDelayInMilliseconds, maxDelayInMilliseconds, cancellationToken); + }, isRetryable, onRetry, onFailure, maxAttempts, baseDelayInMilliseconds, maxDelayInMilliseconds, cancellationToken); } /// @@ -59,6 +61,7 @@ namespace slskd /// /// The logic to execute. /// A function returning a value indicating whether the last Exception is retryable. + /// An action to execute before beginning a retry attempt. /// An action to execute on failure. /// The maximum number of retry attempts. /// The base delay in milliseconds. @@ -69,6 +72,7 @@ namespace slskd public static async Task Do( Func> task, Func isRetryable = null, + Action onRetry = null, Action onFailure = null, int maxAttempts = 3, int baseDelayInMilliseconds = 1000, @@ -76,7 +80,6 @@ namespace slskd CancellationToken cancellationToken = default) { isRetryable ??= (_, _) => true; - onFailure ??= (_, _) => { }; var exceptions = new List(); @@ -92,6 +95,8 @@ namespace slskd if (attempts > 0) { var (delay, jitter) = Compute.ExponentialBackoffDelay(attempts, baseDelayInMilliseconds, maxDelayInMilliseconds); + + onRetry?.Invoke(attempts + 1, delay + jitter); await Task.Delay(delay + jitter, cancellationToken); } @@ -103,7 +108,7 @@ namespace slskd try { - onFailure(attempts + 1, ex); + onFailure?.Invoke(attempts + 1, ex); if (!isRetryable(attempts + 1, ex)) { -- cgit v1.2.3 From bd4393c41afcc55520be7ab8e2464bee0d55308a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 18 Feb 2026 18:54:53 -0600 Subject: specify baseDelay --- src/slskd/Core/ConnectionWatchdog.cs | 1 + src/slskd/Integrations/FTP/FTPService.cs | 1 + src/slskd/Integrations/Pushbullet/PushbulletService.cs | 1 + src/slskd/Integrations/Webhooks/WebhookService.cs | 1 + src/slskd/Relay/RelayClient.cs | 7 +++++-- 5 files changed, 9 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/ConnectionWatchdog.cs b/src/slskd/Core/ConnectionWatchdog.cs index d2f7caa8..1cf1779f 100644 --- a/src/slskd/Core/ConnectionWatchdog.cs +++ b/src/slskd/Core/ConnectionWatchdog.cs @@ -264,6 +264,7 @@ namespace slskd { var (delay, jitter) = Compute.ExponentialBackoffDelay( iteration: attempts, + baseDelayInMilliseconds: 1000, maxDelayInMilliseconds: ReconnectMaxDelayMilliseconds); var approximateDelay = (int)Math.Ceiling((double)(delay + jitter) / 1000); diff --git a/src/slskd/Integrations/FTP/FTPService.cs b/src/slskd/Integrations/FTP/FTPService.cs index cb2b3a3f..ebf34708 100644 --- a/src/slskd/Integrations/FTP/FTPService.cs +++ b/src/slskd/Integrations/FTP/FTPService.cs @@ -76,6 +76,7 @@ namespace slskd.Integrations.FTP isRetryable: (attempts, ex) => true, onFailure: (attempts, ex) => Log.LogInformation("Failed attempt #{Attempts} to upload {Filename} to FTP: {Message}", attempts, fileAndParentDirectory, ex.Message), maxAttempts: FtpOptions.RetryAttempts, + baseDelayInMilliseconds: 1000, maxDelayInMilliseconds: 30000); } catch (RetryException ex) diff --git a/src/slskd/Integrations/Pushbullet/PushbulletService.cs b/src/slskd/Integrations/Pushbullet/PushbulletService.cs index 29033381..4c9df98c 100644 --- a/src/slskd/Integrations/Pushbullet/PushbulletService.cs +++ b/src/slskd/Integrations/Pushbullet/PushbulletService.cs @@ -153,6 +153,7 @@ namespace slskd.Integrations.Pushbullet isRetryable: (attempts, ex) => true, onFailure: (attempts, ex) => Log.LogWarning("Failed attempt #{Attempts} to send Pushbullet notification {Title} {Body}: {Message}", attempts, title, body, ex.Message), maxAttempts: PushbulletOptions.RetryAttempts, + baseDelayInMilliseconds: 1000, maxDelayInMilliseconds: 30000); Log.LogInformation("Sent Pushbullet notification {Title} {Body}", title, body); diff --git a/src/slskd/Integrations/Webhooks/WebhookService.cs b/src/slskd/Integrations/Webhooks/WebhookService.cs index 62739d7a..8a009623 100644 --- a/src/slskd/Integrations/Webhooks/WebhookService.cs +++ b/src/slskd/Integrations/Webhooks/WebhookService.cs @@ -125,6 +125,7 @@ public class WebhookService } }, maxAttempts: webhook.Value.Retry.Attempts, + baseDelayInMilliseconds: 1000, maxDelayInMilliseconds: 30000); sw.Stop(); diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs index ae34e344..3e1903fb 100644 --- a/src/slskd/Relay/RelayClient.cs +++ b/src/slskd/Relay/RelayClient.cs @@ -162,8 +162,9 @@ namespace slskd.Relay Log.Warning("Failed attempt #{Attempts} to connect to relay controller: {Message}", attempts, ex.Message); }, maxAttempts: int.MaxValue, + baseDelayInMilliseconds: 1000, maxDelayInMilliseconds: 30000, - StartCancellationTokenSource.Token); + cancellationToken: StartCancellationTokenSource.Token); } finally { @@ -482,6 +483,7 @@ namespace slskd.Relay isRetryable: (_, _) => true, onFailure: (_, ex) => Log.Error(ex, "Failed to handle file download notification for {Filename} ({Token})", filename, token), maxAttempts: 3, + baseDelayInMilliseconds: 1000, maxDelayInMilliseconds: 60000); Log.Information("File {Filename} successfully downloaded to {Destination}", filename, destinationFile); @@ -592,8 +594,9 @@ namespace slskd.Relay isRetryable: (_, _) => true, onFailure: (count, ex) => Log.Warning("Failed attempt #{Attempts} to obtain share upload token: {Message}", count, ex.Message), maxAttempts: 3, + baseDelayInMilliseconds: 1000, maxDelayInMilliseconds: 5000, - cancellationToken); + cancellationToken: cancellationToken); Log.Debug("Share upload token {Token}", token); -- cgit v1.2.3 From 570cfb6eb96488f65a2d8761dc74e870e07098a5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 18 Feb 2026 18:55:11 -0600 Subject: map groupid and attempts when copying --- src/slskd/Transfers/Extensions.cs | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src') diff --git a/src/slskd/Transfers/Extensions.cs b/src/slskd/Transfers/Extensions.cs index 7ec1b55c..bf139a1d 100644 --- a/src/slskd/Transfers/Extensions.cs +++ b/src/slskd/Transfers/Extensions.cs @@ -23,6 +23,7 @@ namespace slskd.Transfers { return new Transfer() { + GroupId = transfer.GroupId, Id = transfer.Id, Username = transfer.Username, Direction = transfer.Direction, @@ -37,6 +38,7 @@ namespace slskd.Transfers BytesTransferred = t.BytesTransferred, AverageSpeed = t.AverageSpeed, Exception = t.Exception?.Message, + Attempts = transfer.Attempts, }; } } -- cgit v1.2.3 From 50e694f0e10d203c051041443a059e061459b681 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 1 Mar 2026 13:44:22 -0600 Subject: move transfer options into the same type, move limits under upload --- config/slskd.example.yml | 128 ++++++++-------- src/slskd/Core/Options.cs | 380 +++++++++++++++++++++++----------------------- 2 files changed, 250 insertions(+), 258 deletions(-) (limited to 'src') diff --git a/config/slskd.example.yml b/config/slskd.example.yml index 7e820d9f..d0c0f27a 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -54,80 +54,78 @@ # storage_mode: memory # workers: 16 # retention: ~ # retain indefinitely (do not automatically re-scan) -# rooms: -# - ~ -# global: +# transfers: # upload: # slots: 20 # speed_limit: 1000 # in kibibytes -# limits: -# queued: -# files: 500 -# megabytes: 5000 -# daily: -# files: 1000 -# megabytes: 10000 -# failures: 200 -# weekly: -# files: 5000 -# megabytes: 50000 -# failures: 1000 -# download: -# slots: 500 -# speed_limit: 1000 -# groups: -# default: -# upload: -# priority: 500 -# strategy: roundrobin -# slots: 10 -# limits: -# queued: -# files: 150 -# megabytes: 1500 -# daily: ~ # no daily limits (weekly still apply) -# weekly: -# files: 1500 -# megabytes: 15000 -# failures: 150 -# leechers: -# thresholds: -# files: 1 -# directories: 1 -# upload: -# priority: 999 -# strategy: roundrobin -# slots: 1 -# speed_limit: 100 # limits: # queued: -# files: 15 -# megabytes: 150 +# files: 500 +# megabytes: 5000 # daily: -# files: 30 -# megabytes: 300 -# failures: 10 +# files: 1000 +# megabytes: 10000 +# failures: 200 # weekly: -# files: 150 -# megabytes: 1500 -# failures: 30 -# blacklisted: -# members: -# - -# cidrs: -# - -# user_defined: -# my_buddies: +# files: 5000 +# megabytes: 50000 +# failures: 1000 +# download: +# slots: 500 +# speed_limit: 1000 +# groups: +# default: # upload: -# priority: 250 -# strategy: firstinfirstout +# priority: 500 +# strategy: roundrobin # slots: 10 -# limits: -# queued: -# files: 1000 # override global default +# limits: +# queued: +# files: 150 +# megabytes: 1500 +# daily: ~ # no daily limits (weekly still apply) +# weekly: +# files: 1500 +# megabytes: 15000 +# failures: 150 +# leechers: +# thresholds: +# files: 1 +# directories: 1 +# upload: +# priority: 999 +# strategy: roundrobin +# slots: 1 +# speed_limit: 100 +# limits: +# queued: +# files: 15 +# megabytes: 150 +# daily: +# files: 30 +# megabytes: 300 +# failures: 10 +# weekly: +# files: 150 +# megabytes: 1500 +# failures: 30 +# blacklisted: # members: -# - alice -# - bob +# - +# cidrs: +# - +# user_defined: +# my_buddies: +# upload: +# priority: 250 +# strategy: firstinfirstout +# slots: 10 +# limits: +# queued: +# files: 1000 # override global default +# members: +# - alice +# - bob # blacklist: # enabled: true # file: @@ -135,6 +133,8 @@ # search: # request: # - ^.{1,2}$ +# rooms: +# - ~ # web: # port: 5030 # ip_address: 0.0.0.0,[::] diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 1464cf99..c68b6131 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -239,16 +239,9 @@ namespace slskd public SharesOptions Shares { get; init; } = new SharesOptions(); /// - /// Gets global options. + /// Gets transfer options. /// - [Validate] - public GlobalOptions Global { get; init; } = new GlobalOptions(); - - /// - /// Gets user groups. - /// - [Validate] - public GroupsOptions Groups { get; init; } = new GroupsOptions(); + public TransfersOptions Transfers { get; init; } = new TransfersOptions(); /// /// Gets blacklist options. @@ -904,9 +897,9 @@ namespace slskd } /// - /// Global options. + /// Transfer options. /// - public class GlobalOptions + public class TransfersOptions { /// /// Gets global upload options. @@ -915,16 +908,16 @@ namespace slskd public GlobalUploadOptions Upload { get; init; } = new GlobalUploadOptions(); /// - /// Gets global limits. + /// Gets global download options. /// [Validate] - public LimitsOptions Limits { get; init; } = new LimitsOptions(); + public GlobalDownloadOptions Download { get; init; } = new GlobalDownloadOptions(); /// - /// Gets global download options. + /// Gets user groups. /// [Validate] - public GlobalDownloadOptions Download { get; init; } = new GlobalDownloadOptions(); + public GroupsOptions Groups { get; init; } = new GroupsOptions(); /// /// Global upload options. @@ -949,6 +942,12 @@ namespace slskd [Description("the total upload speed limit")] [Range(1, int.MaxValue)] public int SpeedLimit { get; init; } = int.MaxValue; + + /// + /// Gets global limits. + /// + [Validate] + public LimitsOptions Limits { get; init; } = new LimitsOptions(); } /// @@ -975,244 +974,237 @@ namespace slskd [Range(1, int.MaxValue)] public int SpeedLimit { get; init; } = int.MaxValue; } - } - - /// - /// Limit options. - /// - public class LimitsOptions - { - /// - /// Gets limits for queued transfers. - /// - [Validate] - public Limits Queued { get; init; } = new Limits(); - - /// - /// Gets daily limits for transfers. - /// - [Validate] - public Limits Daily { get; init; } = new Limits(); - - /// - /// Gets weekly limits for transfers. - /// - [Validate] - public Limits Weekly { get; init; } = new Limits(); /// - /// Limits. + /// User groups. /// - public class Limits + public class GroupsOptions : IValidatableObject { /// - /// Gets the limit for number of files. + /// Gets options for the default user group. /// - [Range(1, int.MaxValue)] - public int? Files { get; init; } = null; + /// + /// These options apply to users that are not privileged, have not been identified as leechers, + /// and have not been added as a member of any group. + /// + [Validate] + public GroupOptions Default { get; init; } = new GroupOptions(); /// - /// Gets the limit for number of megabytes. + /// Gets options for the leecher user group. /// - [Range(1, int.MaxValue)] - public int? Megabytes { get; init; } = null; + /// + /// These options apply to users that have been identified as leechers, and have not been added as a member of any group. + /// + [Validate] + public LeecherOptions Leechers { get; init; } = new LeecherOptions(); /// - /// Gets the limit for number of failures. + /// Gets options for the blacklisted user group. /// - [Range(1, int.MaxValue)] - public int? Failures { get; init; } = null; - } - } - - /// - /// User groups. - /// - public class GroupsOptions : IValidatableObject - { - /// - /// Gets options for the default user group. - /// - /// - /// These options apply to users that are not privileged, have not been identified as leechers, - /// and have not been added as a member of any group. - /// - [Validate] - public BuiltInOptions Default { get; init; } = new BuiltInOptions(); - - /// - /// Gets options for the leecher user group. - /// - /// - /// These options apply to users that have been identified as leechers, and have not been added as a member of any group. - /// - [Validate] - public LeecherOptions Leechers { get; init; } = new LeecherOptions(); - - /// - /// Gets options for the blacklisted user group. - /// - [Validate] - public BlacklistedOptions Blacklisted { get; init; } = new BlacklistedOptions(); - - /// - /// Gets user defined groups and options. - /// - [Validate] - public Dictionary UserDefined { get; init; } = new Dictionary(); - - /// - /// Extended validation. - /// - /// - /// - public IEnumerable Validate(ValidationContext validationContext) - { - var builtInGroups = new[] { Application.PrivilegedGroup, Application.DefaultGroup, Application.LeecherGroup }; - var intersection = UserDefined.Keys.Intersect(builtInGroups); - - return intersection.Select(group => new ValidationResult($"User defined group '{group}' collides with a built in group. Choose a different name.")); - } + [Validate] + public BlacklistedOptions Blacklisted { get; init; } = new BlacklistedOptions(); - /// - /// Options that are common to all groups. - /// - public class GroupOptions - { /// - /// Gets upload options. + /// Gets user defined groups and options. /// [Validate] - public UploadOptions Upload { get; init; } = new UploadOptions(); + public Dictionary UserDefined { get; init; } = new Dictionary(); /// - /// Gets limit options. + /// Extended validation. /// - [Validate] - public LimitsOptions Limits { get; init; } = new LimitsOptions(); - } + /// + /// + public IEnumerable Validate(ValidationContext validationContext) + { + var builtInGroups = new[] { Application.PrivilegedGroup, Application.DefaultGroup, Application.LeecherGroup }; + var intersection = UserDefined.Keys.Intersect(builtInGroups); - /// - /// Built in user group options. - /// - public class BuiltInOptions : GroupOptions - { - } + return intersection.Select(group => new ValidationResult($"User defined group '{group}' collides with a built in group. Choose a different name.")); + } - /// - /// Built in blacklisted group options. - /// - public class BlacklistedOptions : IValidatableObject - { /// - /// Gets the list of group member usernames. + /// Options that are common to all groups. /// - public string[] Members { get; init; } = Array.Empty(); + public class GroupOptions + { + /// + /// Gets upload options. + /// + [Validate] + public GroupUploadOptions Upload { get; init; } = new GroupUploadOptions(); + + /// + /// User group upload options. + /// + public class GroupUploadOptions + { + /// + /// Gets the priority of the group. + /// + [Range(1, int.MaxValue)] + public int Priority { get; init; } = 1; + + /// + /// Gets the queue strategy for the group. + /// + [Enum(typeof(Transfers.QueueStrategy))] + public string Strategy { get; init; } = slskd.Transfers.QueueStrategy.RoundRobin.ToString().ToLowerInvariant(); + + /// + /// Gets the limit for the total number of upload slots for the group. + /// + [Range(1, int.MaxValue)] + public int Slots { get; init; } = int.MaxValue; + + /// + /// Gets the total upload speed limit for the group, in kibibytes. + /// + [Range(1, int.MaxValue)] + public int SpeedLimit { get; init; } = int.MaxValue; + + /// + /// Gets limit options. + /// + [Validate] + public LimitsOptions Limits { get; init; } = new LimitsOptions(); + } + } /// - /// Gets the list of group CIDRs. + /// Built in leecher group options. /// - public string[] Cidrs { get; init; } = Array.Empty(); + public class LeecherOptions : GroupOptions + { + /// + /// Gets leecher threshold options. + /// + [Validate] + public ThresholdOptions Thresholds { get; init; } = new ThresholdOptions(); + + /// + /// Leecher threshold options. + /// + public class ThresholdOptions + { + /// + /// Gets the minimum number of shared files required to avoid being classified as a leecher. + /// + [Range(1, int.MaxValue)] + public int Files { get; init; } = 1; + + /// + /// Gets the minimum number of shared directories required to avoid being classified as a leecher. + /// + [Range(1, int.MaxValue)] + public int Directories { get; init; } = 1; + } + } /// - /// Extended validation. + /// Built in blacklisted group options. /// - /// - /// - public IEnumerable Validate(ValidationContext validationContext) + public class BlacklistedOptions : IValidatableObject { - var results = new List(); + /// + /// Gets the list of group member usernames. + /// + public string[] Members { get; init; } = Array.Empty(); + + /// + /// Gets the list of group CIDRs. + /// + public string[] Cidrs { get; init; } = Array.Empty(); - foreach (var cidr in Cidrs ?? Array.Empty()) + /// + /// Extended validation. + /// + /// + /// + public IEnumerable Validate(ValidationContext validationContext) { - try + var results = new List(); + + foreach (var cidr in Cidrs ?? Array.Empty()) { - if (cidr.StartsWith("::ffff", StringComparison.OrdinalIgnoreCase)) + try { - throw new Exception("IPv4 mapped IPv6 addresses are not allowed"); - } + if (cidr.StartsWith("::ffff", StringComparison.OrdinalIgnoreCase)) + { + throw new Exception("IPv4 mapped IPv6 addresses are not allowed"); + } - _ = IPAddressRange.Parse(cidr); - } - catch (Exception ex) - { - results.Add(new ValidationResult($"CIDR {cidr} is invalid: {ex.Message}")); + _ = IPAddressRange.Parse(cidr); + } + catch (Exception ex) + { + results.Add(new ValidationResult($"CIDR {cidr} is invalid: {ex.Message}")); + } } - } - return results; + return results; + } } - } - /// - /// Built in leecher group options. - /// - public class LeecherOptions : GroupOptions - { /// - /// Gets leecher threshold options. + /// User defined user group options. /// - [Validate] - public ThresholdOptions Thresholds { get; init; } = new ThresholdOptions(); + public class UserDefinedOptions : GroupOptions + { + /// + /// Gets the list of group member usernames. + /// + public string[] Members { get; init; } = Array.Empty(); + } } /// - /// Leecher threshold options. + /// Limit options. /// - public class ThresholdOptions + public class LimitsOptions { /// - /// Gets the minimum number of shared files required to avoid being classified as a leecher. - /// - [Range(1, int.MaxValue)] - public int Files { get; init; } = 1; - - /// - /// Gets the minimum number of shared directories required to avoid being classified as a leecher. + /// Gets limits for queued transfers. /// - [Range(1, int.MaxValue)] - public int Directories { get; init; } = 1; - } + [Validate] + public Limits Queued { get; init; } = new Limits(); - /// - /// User defined user group options. - /// - public class UserDefinedOptions : GroupOptions - { /// - /// Gets the list of group member usernames. + /// Gets daily limits for transfers. /// - public string[] Members { get; init; } = Array.Empty(); - } + [Validate] + public Limits Daily { get; init; } = new Limits(); - /// - /// User group upload options. - /// - public class UploadOptions - { /// - /// Gets the priority of the group. + /// Gets weekly limits for transfers. /// - [Range(1, int.MaxValue)] - public int Priority { get; init; } = 1; + [Validate] + public Limits Weekly { get; init; } = new Limits(); /// - /// Gets the queue strategy for the group. + /// Limits. /// - [Enum(typeof(Transfers.QueueStrategy))] - public string Strategy { get; init; } = Transfers.QueueStrategy.RoundRobin.ToString().ToLowerInvariant(); + public class Limits + { + /// + /// Gets the limit for number of files. + /// + [Range(1, int.MaxValue)] + public int? Files { get; init; } = null; - /// - /// Gets the limit for the total number of upload slots for the group. - /// - [Range(1, int.MaxValue)] - public int Slots { get; init; } = int.MaxValue; + /// + /// Gets the limit for number of megabytes. + /// + [Range(1, int.MaxValue)] + public int? Megabytes { get; init; } = null; - /// - /// Gets the total upload speed limit for the group, in kibibytes. - /// - [Range(1, int.MaxValue)] - public int SpeedLimit { get; init; } = int.MaxValue; + /// + /// Gets the limit for number of failures. + /// + [Range(1, int.MaxValue)] + public int? Failures { get; init; } = null; + } } } -- cgit v1.2.3 From 230d676a8b4b06128b2d3322fac4c8f2a2d1cdf2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 1 Mar 2026 15:43:24 -0600 Subject: add retry options --- config/slskd.example.yml | 5 +++ src/slskd/Core/Options.cs | 38 ++++++++++++++++++++++ .../Transfers/Types/RetryIncompleteStrategy.cs | 34 +++++++++++++++++++ 3 files changed, 77 insertions(+) create mode 100644 src/slskd/Transfers/Types/RetryIncompleteStrategy.cs (limited to 'src') diff --git a/config/slskd.example.yml b/config/slskd.example.yml index d0c0f27a..00b984a2 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -73,6 +73,11 @@ # download: # slots: 500 # speed_limit: 1000 +# retry: +# incomplete: resume # 'overwrite' or 'resume' +# attempts: 3 +# delay: 5000 # initial time between retries, in milliseconds +# max_delay: 60000 # maximum time between retries, in milliseconds # groups: # default: # upload: diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index c68b6131..d7d2931f 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -35,6 +35,7 @@ namespace slskd using slskd.Events; using slskd.Relay; using slskd.Shares; + using slskd.Transfers; using slskd.Validation; using Utility.CommandLine; using Utility.EnvironmentVariables; @@ -241,6 +242,7 @@ namespace slskd /// /// Gets transfer options. /// + [Validate] public TransfersOptions Transfers { get; init; } = new TransfersOptions(); /// @@ -973,6 +975,42 @@ namespace slskd [Description("the total download speed limit")] [Range(1, int.MaxValue)] public int SpeedLimit { get; init; } = int.MaxValue; + + /// + /// Gets download retry options. + /// + [Validate] + public RetryOptions Retry { get; init; } = new RetryOptions(); + + /// + /// Download retry options. + /// + public class RetryOptions + { + /// + /// Gets the maximum number of times to retry a failed transfer. + /// + [Range(1, int.MaxValue)] + public int Attempts { get; init; } = 3; + + /// + /// Gets the base time to wait between retry attempts, in milliseconds. + /// + [Range(1000, int.MaxValue)] + public int Delay { get; init; } = 5000; + + /// + /// Gets the maximum time to wait between retry attempts, in milliseconds. + /// + [Range(1000, int.MaxValue)] + public int MaxDelay { get; init; } = 60_000; + + /// + /// Gets the strategy for handling incomplete files upon retry. + /// + [Enum(typeof(RetryIncompleteStrategy))] + public string Incomplete { get; init; } = RetryIncompleteStrategy.Overwrite.ToString().ToLowerInvariant(); + } } /// diff --git a/src/slskd/Transfers/Types/RetryIncompleteStrategy.cs b/src/slskd/Transfers/Types/RetryIncompleteStrategy.cs new file mode 100644 index 00000000..2655ed96 --- /dev/null +++ b/src/slskd/Transfers/Types/RetryIncompleteStrategy.cs @@ -0,0 +1,34 @@ +// +// 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.Transfers; + +/// +/// Strategy for retrying incomplete files. +/// +public enum RetryIncompleteStrategy +{ + /// + /// Overwrite the existing file. + /// + Overwrite = 0, + + /// + /// Resume the transfer using the size of the incomplete file as the initial offset. + /// + Resume = 1, +} \ No newline at end of file -- cgit v1.2.3 From 0d4be63b40737e351b3ffb8bc31370458fe1a2af Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 1 Mar 2026 16:49:49 -0600 Subject: fix stuff broken by options refactor --- src/slskd/Application.cs | 30 ++-- src/slskd/Program.cs | 4 +- src/slskd/Transfers/Uploads/UploadGovernor.cs | 14 +- src/slskd/Transfers/Uploads/UploadQueue.cs | 22 +-- src/slskd/Users/UserService.cs | 10 +- .../Transfers/Uploads/UploadGovernorTests.cs | 24 ++- .../Transfers/Uploads/UploadQueueTests.cs | 190 +++++++++++---------- tests/slskd.Tests.Unit/Users/UserServiceTests.cs | 72 ++++---- 8 files changed, 195 insertions(+), 171 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index daed5d3f..2e9639c6 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -421,8 +421,8 @@ namespace slskd distributedChildLimit: OptionsAtStartup.Soulseek.DistributedNetwork.ChildLimit, enableDistributedNetwork: !OptionsAtStartup.Soulseek.DistributedNetwork.Disabled, acceptDistributedChildren: !OptionsAtStartup.Soulseek.DistributedNetwork.DisableChildren, - maximumUploadSpeed: OptionsAtStartup.Global.Upload.SpeedLimit, - maximumDownloadSpeed: OptionsAtStartup.Global.Download.SpeedLimit, + maximumUploadSpeed: OptionsAtStartup.Transfers.Upload.SpeedLimit, + maximumDownloadSpeed: OptionsAtStartup.Transfers.Download.SpeedLimit, autoAcknowledgePrivateMessages: false, acceptPrivateRoomInvitations: true, serverConnectionOptions: serverOptions, @@ -660,26 +660,26 @@ namespace slskd } // we'll fall back to global limits for any limit that isn't set at the group level - var global = Options.Global.Limits; + var global = Options.Transfers.Upload.Limits; // resolve the limits for this user's group. - Options.LimitsOptions limits; + Options.TransfersOptions.LimitsOptions limits; - if (Options.Groups.UserDefined.TryGetValue(group, out var userDefinedOptions)) + if (Options.Transfers.Groups.UserDefined.TryGetValue(group, out var userDefinedOptions)) { - limits = userDefinedOptions.Limits; + limits = userDefinedOptions.Upload.Limits; } else { limits = group switch { - DefaultGroup => Options.Groups.Default.Limits, - LeecherGroup => Options.Groups.Leechers.Limits, - _ => Options.Groups.Default.Limits, // that's weird! we'll just go with defaults.. + DefaultGroup => Options.Transfers.Groups.Default.Upload.Limits, + LeecherGroup => Options.Transfers.Groups.Leechers.Upload.Limits, + _ => Options.Transfers.Groups.Default.Upload.Limits, // that's weird! we'll just go with defaults.. }; } - bool IsNull(Options.LimitsOptions.Limits lim, Options.LimitsOptions.Limits global) + bool IsNull(Options.TransfersOptions.LimitsOptions.Limits lim, Options.TransfersOptions.LimitsOptions.Limits global) => (lim is null && global is null) || ((lim?.Files ?? global?.Files ?? lim?.Megabytes ?? global?.Megabytes ?? lim.Failures ?? global.Failures) is null); /* @@ -692,8 +692,8 @@ namespace slskd (bool Files, bool Megabytes) OverLimits( int files, long bytes, - Options.LimitsOptions.Limits options, - Options.LimitsOptions.Limits defaults, + Options.TransfersOptions.LimitsOptions.Limits options, + Options.TransfersOptions.LimitsOptions.Limits defaults, long size) { var filesOver = false; @@ -1482,7 +1482,7 @@ namespace slskd // determine whether any Soulseek options changed. if so, we need to construct a patch and invoke ReconfigureOptionsAsync(). var slskDiff = PreviousOptions.Soulseek.DiffWith(newOptions.Soulseek); - var globalDiff = PreviousOptions.Global.DiffWith(newOptions.Global); + var globalDiff = PreviousOptions.Transfers.DiffWith(newOptions.Transfers); if (slskDiff.Any() || globalDiff.Any()) { @@ -1544,8 +1544,8 @@ namespace slskd enableDistributedNetwork: old.DistributedNetwork.Disabled == update.DistributedNetwork.Disabled ? null : !update.DistributedNetwork.Disabled, distributedChildLimit: old.DistributedNetwork.ChildLimit == update.DistributedNetwork.ChildLimit ? null : update.DistributedNetwork.ChildLimit, acceptDistributedChildren: old.DistributedNetwork.DisableChildren == update.DistributedNetwork.DisableChildren ? null : !update.DistributedNetwork.DisableChildren, - maximumUploadSpeed: newOptions.Global.Upload.SpeedLimit, - maximumDownloadSpeed: newOptions.Global.Download.SpeedLimit, + maximumUploadSpeed: newOptions.Transfers.Upload.SpeedLimit, + maximumDownloadSpeed: newOptions.Transfers.Download.SpeedLimit, serverConnectionOptions: serverPatch, peerConnectionOptions: connectionPatch, transferConnectionOptions: transferPatch, diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 948bb9a6..8d67e803 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -681,8 +681,8 @@ namespace slskd // complete configuration at startup. services.AddSingleton(_ => new SoulseekClient(options: new SoulseekClientOptions( - maximumConcurrentUploads: OptionsAtStartup.Global.Upload.Slots, - maximumConcurrentDownloads: OptionsAtStartup.Global.Download.Slots, + maximumConcurrentUploads: OptionsAtStartup.Transfers.Upload.Slots, + maximumConcurrentDownloads: OptionsAtStartup.Transfers.Download.Slots, minimumDiagnosticLevel: OptionsAtStartup.Soulseek.DiagnosticLevel.ToEnum(), maximumConcurrentSearches: 2, raiseEventsAsynchronously: true))); diff --git a/src/slskd/Transfers/Uploads/UploadGovernor.cs b/src/slskd/Transfers/Uploads/UploadGovernor.cs index 11fc4dcf..8a035f13 100644 --- a/src/slskd/Transfers/Uploads/UploadGovernor.cs +++ b/src/slskd/Transfers/Uploads/UploadGovernor.cs @@ -139,9 +139,9 @@ namespace slskd.Transfers return new(capacity, interval: intervalInMs); } - var optionsHash = Compute.Sha1Hash(options.Groups.ToJson()); + var optionsHash = Compute.Sha1Hash(options.Transfers.Groups.ToJson()); - if (optionsHash == LastOptionsHash && options.Global.Upload.SpeedLimit == LastGlobalSpeedLimit) + if (optionsHash == LastOptionsHash && options.Transfers.Upload.SpeedLimit == LastGlobalSpeedLimit) { return; } @@ -153,19 +153,19 @@ namespace slskd.Transfers // also, so transfers in progress will briefly exceed the intended speeds. var tokenBuckets = new Dictionary() { - { Application.PrivilegedGroup, CreateBucket(speedInKiB: options.Global.Upload.SpeedLimit) }, - { Application.DefaultGroup, CreateBucket(speedInKiB: options.Groups.Default.Upload.SpeedLimit) }, - { Application.LeecherGroup, CreateBucket(speedInKiB: options.Groups.Leechers.Upload.SpeedLimit) }, + { Application.PrivilegedGroup, CreateBucket(speedInKiB: options.Transfers.Upload.SpeedLimit) }, + { Application.DefaultGroup, CreateBucket(speedInKiB: options.Transfers.Groups.Default.Upload.SpeedLimit) }, + { Application.LeecherGroup, CreateBucket(speedInKiB: options.Transfers.Groups.Leechers.Upload.SpeedLimit) }, }; - foreach (var group in options.Groups.UserDefined) + foreach (var group in options.Transfers.Groups.UserDefined) { tokenBuckets.Add(group.Key, CreateBucket(group.Value.Upload.SpeedLimit)); } TokenBuckets = tokenBuckets; - LastGlobalSpeedLimit = options.Global.Upload.SpeedLimit; + LastGlobalSpeedLimit = options.Transfers.Upload.SpeedLimit; LastOptionsHash = optionsHash; } } diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index c20e2312..1ecf264f 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -403,14 +403,14 @@ namespace slskd.Transfers try { - var optionsHash = Compute.Sha1Hash(options.Groups.ToJson()); + var optionsHash = Compute.Sha1Hash(options.Transfers.Groups.ToJson()); - if (optionsHash == LastOptionsHash && options.Global.Upload.Slots == LastGlobalSlots) + if (optionsHash == LastOptionsHash && options.Transfers.Upload.Slots == LastGlobalSlots) { return; } - GlobalSlots = options.Global.Upload.Slots; + GlobalSlots = options.Transfers.Upload.Slots; // statically add built-in groups var groups = new List() @@ -431,23 +431,23 @@ namespace slskd.Transfers new UploadGroup() { Name = Application.DefaultGroup, - Priority = options.Groups.Default.Upload.Priority, - Slots = Math.Min(options.Groups.Default.Upload.Slots, GlobalSlots), + Priority = options.Transfers.Groups.Default.Upload.Priority, + Slots = Math.Min(options.Transfers.Groups.Default.Upload.Slots, GlobalSlots), UsedSlots = GetExistingUsedSlotsOrDefault(Application.DefaultGroup), - Strategy = options.Groups.Default.Upload.Strategy.ToEnum(), + Strategy = options.Transfers.Groups.Default.Upload.Strategy.ToEnum(), }, new UploadGroup() { Name = Application.LeecherGroup, - Priority = options.Groups.Leechers.Upload.Priority, - Slots = Math.Min(options.Groups.Leechers.Upload.Slots, GlobalSlots), + Priority = options.Transfers.Groups.Leechers.Upload.Priority, + Slots = Math.Min(options.Transfers.Groups.Leechers.Upload.Slots, GlobalSlots), UsedSlots = GetExistingUsedSlotsOrDefault(Application.LeecherGroup), - Strategy = options.Groups.Leechers.Upload.Strategy.ToEnum(), + Strategy = options.Transfers.Groups.Leechers.Upload.Strategy.ToEnum(), }, }; // dynamically add user-defined groups - groups.AddRange(options.Groups.UserDefined.Select(kvp => new UploadGroup() + groups.AddRange(options.Transfers.Groups.UserDefined.Select(kvp => new UploadGroup() { Name = kvp.Key, Priority = kvp.Value.Upload.Priority, @@ -458,7 +458,7 @@ namespace slskd.Transfers Groups = groups.ToDictionary(g => g.Name); - LastGlobalSlots = options.Global.Upload.Slots; + LastGlobalSlots = options.Transfers.Upload.Slots; LastOptionsHash = optionsHash; } finally diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index ead1d812..2939fd17 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -172,7 +172,7 @@ namespace slskd.Users return user.Group; } - var thresholds = OptionsMonitor.CurrentValue.Groups.Leechers.Thresholds; + var thresholds = OptionsMonitor.CurrentValue.Transfers.Groups.Leechers.Thresholds; if (user.Statistics?.FileCount < thresholds.Files || user.Statistics?.DirectoryCount < thresholds.Directories) { @@ -276,7 +276,7 @@ namespace slskd.Users /// A value indicating whether the specified user and/or IP are blacklisted. public bool IsBlacklisted(string username, IPAddress ipAddress = null) { - var blacklist = OptionsMonitor.CurrentValue.Groups.Blacklisted; + var blacklist = OptionsMonitor.CurrentValue.Transfers.Groups.Blacklisted; if (blacklist.Members.Contains(username)) { @@ -364,14 +364,14 @@ namespace slskd.Users private void Configure(Options options, bool force = false) { - var optionsHash = Compute.Sha1Hash(options.Groups.UserDefined.ToJson()); + var optionsHash = Compute.Sha1Hash(options.Transfers.Groups.UserDefined.ToJson()); if (optionsHash != LastOptionsHash || force) { // get a list of tracked names that haven't been explicitly added to any group, including those that were previously // configured but have now been removed var usernamesBeforeUpdate = UserDictionary.Keys.ToList(); - var usernamesAfterUpdate = options.Groups.UserDefined.SelectMany(g => g.Value.Members); + var usernamesAfterUpdate = options.Transfers.Groups.UserDefined.SelectMany(g => g.Value.Members); var usernamesRemoved = usernamesBeforeUpdate.Except(usernamesAfterUpdate); // clear the configured group for anyone that was removed from config, or that was added transiently @@ -385,7 +385,7 @@ namespace slskd.Users // sort by priority, descending. this will cause the highest priority group for the user to be persisted when the // operation is complete. - foreach (var group in options.Groups.UserDefined.OrderByDescending(kvp => kvp.Value.Upload.Priority)) + foreach (var group in options.Transfers.Groups.UserDefined.OrderByDescending(kvp => kvp.Value.Upload.Priority)) { foreach (var username in group.Value.Members) { diff --git a/tests/slskd.Tests.Unit/Transfers/Uploads/UploadGovernorTests.cs b/tests/slskd.Tests.Unit/Transfers/Uploads/UploadGovernorTests.cs index 4052236f..acf74e61 100644 --- a/tests/slskd.Tests.Unit/Transfers/Uploads/UploadGovernorTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/Uploads/UploadGovernorTests.cs @@ -30,12 +30,15 @@ { var options = new Options() { - Groups = new Options.GroupsOptions() + Transfers = new Options.TransfersOptions { - UserDefined = new Dictionary() + Groups = new Options.TransfersOptions.GroupsOptions() { - { group1, new Options.GroupsOptions.UserDefinedOptions() }, - { group2, new Options.GroupsOptions.UserDefinedOptions() }, + UserDefined = new Dictionary() + { + { group1, new Options.TransfersOptions.GroupsOptions.UserDefinedOptions() }, + { group2, new Options.TransfersOptions.GroupsOptions.UserDefinedOptions() }, + } } } }; @@ -199,12 +202,15 @@ { var options = new Options() { - Groups = new Options.GroupsOptions() + Transfers = new Options.TransfersOptions { - UserDefined = new Dictionary() - { - { group, new Options.GroupsOptions.UserDefinedOptions() }, - } + Groups = new Options.TransfersOptions.GroupsOptions() + { + UserDefined = new Dictionary() + { + { group, new Options.TransfersOptions.GroupsOptions.UserDefinedOptions() }, + } + } } }; diff --git a/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs b/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs index 925ad9b2..e5d6e1b5 100644 --- a/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs @@ -39,7 +39,7 @@ Assert.Equal(Application.PrivilegedGroup, p.Name); Assert.Equal(0, p.Priority); - Assert.Equal(new Options().Global.Upload.Slots, p.Slots); + Assert.Equal(new Options().Transfers.Upload.Slots, p.Slots); Assert.Equal(0, p.UsedSlots); Assert.Equal(QueueStrategy.FirstInFirstOut, p.Strategy); } @@ -49,25 +49,25 @@ { var (queue, _) = GetFixture(new Options() { - Global = new Options.GlobalOptions + Transfers = new Options.TransfersOptions { - Upload = new Options.GlobalOptions.GlobalUploadOptions + Upload = new Options.TransfersOptions.GlobalUploadOptions { Slots = int.MaxValue, }, - }, - Groups = new Options.GroupsOptions() - { - Default = new Options.GroupsOptions.BuiltInOptions() + Groups = new Options.TransfersOptions.GroupsOptions() { - Upload = new Options.GroupsOptions.UploadOptions() + Default = new Options.TransfersOptions.GroupsOptions.BaseGroupOptions() { - Priority = priority, - Slots = slots, - Strategy = strategy.ToString(), + Upload = new Options.TransfersOptions.GroupsOptions.BaseGroupOptions.GroupUploadOptions() + { + Priority = priority, + Slots = slots, + Strategy = strategy.ToString(), + } } } - } + }, }); var groups = queue.GetProperty>("Groups"); @@ -86,23 +86,23 @@ { var (queue, _) = GetFixture(new Options() { - Global = new Options.GlobalOptions + Transfers = new Options.TransfersOptions { - Upload = new Options.GlobalOptions.GlobalUploadOptions + Upload = new Options.TransfersOptions.GlobalUploadOptions { Slots = int.MaxValue, }, - }, - Groups = new Options.GroupsOptions() - { - Leechers = new Options.GroupsOptions.LeecherOptions() + Groups = new Options.TransfersOptions.GroupsOptions() { - Thresholds = new Options.GroupsOptions.ThresholdOptions(), - Upload = new Options.GroupsOptions.UploadOptions() + Leechers = new Options.TransfersOptions.GroupsOptions.LeecherOptions() { - Priority = priority, - Slots = slots, - Strategy = strategy.ToString(), + Thresholds = new Options.TransfersOptions.GroupsOptions.LeecherOptions.ThresholdOptions(), + Upload = new Options.TransfersOptions.GroupsOptions.BaseGroupOptions.GroupUploadOptions() + { + Priority = priority, + Slots = slots, + Strategy = strategy.ToString(), + } } } } @@ -124,38 +124,38 @@ { var (queue, _) = GetFixture(new Options() { - Global = new Options.GlobalOptions + Transfers = new Options.TransfersOptions { - Upload = new Options.GlobalOptions.GlobalUploadOptions + Upload = new Options.TransfersOptions.GlobalUploadOptions { Slots = int.MaxValue, }, - }, - Groups = new Options.GroupsOptions() - { - UserDefined = new Dictionary() + Groups = new Options.TransfersOptions.GroupsOptions() { + UserDefined = new Dictionary() { - group1, - new Options.GroupsOptions.UserDefinedOptions() { - Upload = new Options.GroupsOptions.UploadOptions() + group1, + new Options.TransfersOptions.GroupsOptions.UserDefinedOptions() { - Priority = priority1, - Slots = slots1, - Strategy = strategy1.ToString(), + Upload = new Options.TransfersOptions.GroupsOptions.BaseGroupOptions.GroupUploadOptions() + { + Priority = priority1, + Slots = slots1, + Strategy = strategy1.ToString(), + } } - } - }, - { - group2, - new Options.GroupsOptions.UserDefinedOptions() + }, { - Upload = new Options.GroupsOptions.UploadOptions() + group2, + new Options.TransfersOptions.GroupsOptions.UserDefinedOptions() { - Priority = priority2, - Slots = slots2, - Strategy = strategy2.ToString(), + Upload = new Options.TransfersOptions.GroupsOptions.BaseGroupOptions.GroupUploadOptions() + { + Priority = priority2, + Slots = slots2, + Strategy = strategy2.ToString(), + } } } } @@ -189,29 +189,29 @@ { var options = new Options() { - Global = new Options.GlobalOptions + Transfers = new Options.TransfersOptions { - Upload = new Options.GlobalOptions.GlobalUploadOptions + Upload = new Options.TransfersOptions.GlobalUploadOptions { Slots = int.MaxValue, }, - }, - Groups = new Options.GroupsOptions() - { - UserDefined = new Dictionary() + Groups = new Options.TransfersOptions.GroupsOptions() { + UserDefined = new Dictionary() { - group, - new Options.GroupsOptions.UserDefinedOptions() { - Upload = new Options.GroupsOptions.UploadOptions() + group, + new Options.TransfersOptions.GroupsOptions.UserDefinedOptions() { - Priority = priority, - Slots = slots, - Strategy = strategy.ToString(), + Upload = new Options.TransfersOptions.GroupsOptions.BaseGroupOptions.GroupUploadOptions() + { + Priority = priority, + Slots = slots, + Strategy = strategy.ToString(), + } } - } - }, + }, + } } } }; @@ -246,29 +246,29 @@ { var options = new Options() { - Global = new Options.GlobalOptions + Transfers = new Options.TransfersOptions { - Upload = new Options.GlobalOptions.GlobalUploadOptions + Upload = new Options.TransfersOptions.GlobalUploadOptions { Slots = 42, }, - }, - Groups = new Options.GroupsOptions() - { - UserDefined = new Dictionary() + Groups = new Options.TransfersOptions.GroupsOptions() { + UserDefined = new Dictionary() { - group, - new Options.GroupsOptions.UserDefinedOptions() { - Upload = new Options.GroupsOptions.UploadOptions() + group, + new Options.TransfersOptions.GroupsOptions.UserDefinedOptions() { - Priority = priority, - Slots = int.MaxValue, // lots - Strategy = strategy.ToString(), + Upload = new Options.TransfersOptions.GroupsOptions.BaseGroupOptions.GroupUploadOptions() + { + Priority = priority, + Slots = int.MaxValue, // lots + Strategy = strategy.ToString(), + } } - } - }, + }, + } } } }; @@ -303,22 +303,25 @@ { var options = new Options() { - Groups = new Options.GroupsOptions() + Transfers = new Options.TransfersOptions { - UserDefined = new Dictionary() + Groups = new Options.TransfersOptions.GroupsOptions() { + UserDefined = new Dictionary() { - group, - new Options.GroupsOptions.UserDefinedOptions() { - Upload = new Options.GroupsOptions.UploadOptions() + group, + new Options.TransfersOptions.GroupsOptions.UserDefinedOptions() { - Priority = 0, - Slots = 0, - Strategy = QueueStrategy.FirstInFirstOut.ToString(), + Upload = new Options.TransfersOptions.GroupsOptions.BaseGroupOptions.GroupUploadOptions() + { + Priority = 0, + Slots = 0, + Strategy = QueueStrategy.FirstInFirstOut.ToString(), + } } - } - }, + }, + } } } }; @@ -331,22 +334,25 @@ // reconfigure with different options to bypass the hash check options = new Options() { - Groups = new Options.GroupsOptions() + Transfers = new Options.TransfersOptions { - UserDefined = new Dictionary() + Groups = new Options.TransfersOptions.GroupsOptions() { + UserDefined = new Dictionary() { - group, - new Options.GroupsOptions.UserDefinedOptions() { - Upload = new Options.GroupsOptions.UploadOptions() + group, + new Options.TransfersOptions.GroupsOptions.UserDefinedOptions() { - Priority = newPriority, // change priority - Slots = 0, - Strategy = QueueStrategy.FirstInFirstOut.ToString(), + Upload = new Options.TransfersOptions.GroupsOptions.BaseGroupOptions.GroupUploadOptions() + { + Priority = newPriority, // change priority + Slots = 0, + Strategy = QueueStrategy.FirstInFirstOut.ToString(), + } } - } - }, + }, + } } } }; diff --git a/tests/slskd.Tests.Unit/Users/UserServiceTests.cs b/tests/slskd.Tests.Unit/Users/UserServiceTests.cs index ca45d5b9..7680ec11 100644 --- a/tests/slskd.Tests.Unit/Users/UserServiceTests.cs +++ b/tests/slskd.Tests.Unit/Users/UserServiceTests.cs @@ -32,18 +32,21 @@ { var options = new Options() { - Groups = new Options.GroupsOptions() - { - UserDefined = new Dictionary() + Transfers = new Options.TransfersOptions { + Groups = new Options.TransfersOptions.GroupsOptions() { - group, - new Options.GroupsOptions.UserDefinedOptions() + UserDefined = new Dictionary() { - Members = new[] { username }, + { + group, + new Options.TransfersOptions.GroupsOptions.UserDefinedOptions() + { + Members = new[] { username }, + } + }, } - }, - } + } } }; @@ -60,15 +63,21 @@ { var options = new Options() { - Groups = new Options.GroupsOptions() - { - UserDefined = new Dictionary() + Transfers = new Options.TransfersOptions { - { group, new Options.GroupsOptions.UserDefinedOptions() + Groups = new Options.TransfersOptions.GroupsOptions() { - Members = new[] { user }, - } }, - } + UserDefined = new Dictionary() + { + { + group, + new Options.TransfersOptions.GroupsOptions.UserDefinedOptions() + { + Members = new[] { user }, + } + }, + } + } } }; @@ -89,26 +98,29 @@ { var options = new Options() { - Groups = new Options.GroupsOptions() + Transfers = new Options.TransfersOptions { - UserDefined = new Dictionary() + Groups = new Options.TransfersOptions.GroupsOptions() { + UserDefined = new Dictionary() { - group100, - new Options.GroupsOptions.UserDefinedOptions() { - Upload = new Options.GroupsOptions.UploadOptions() { Priority = 100 }, - Members = new[] { user }, - } - }, - { - group0, - new Options.GroupsOptions.UserDefinedOptions() + group100, + new Options.TransfersOptions.GroupsOptions.UserDefinedOptions() + { + Upload = new Options.TransfersOptions.GroupsOptions.BaseGroupOptions.GroupUploadOptions() { Priority = 100 }, + Members = new[] { user }, + } + }, { - Upload = new Options.GroupsOptions.UploadOptions() { Priority = 0 }, - Members = new[] { user }, - } - }, + group0, + new Options.TransfersOptions.GroupsOptions.UserDefinedOptions() + { + Upload = new Options.TransfersOptions.GroupsOptions.BaseGroupOptions.GroupUploadOptions() { Priority = 0 }, + Members = new[] { user }, + } + }, + } } } }; -- cgit v1.2.3 From 4835791c9df15771d249e6580de2bd4a2634dcb5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 1 Mar 2026 16:50:23 -0600 Subject: disambiguate BaseGroupOptions --- src/slskd/Core/Options.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index d7d2931f..0d22cad3 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1026,7 +1026,7 @@ namespace slskd /// and have not been added as a member of any group. /// [Validate] - public GroupOptions Default { get; init; } = new GroupOptions(); + public BaseGroupOptions Default { get; init; } = new BaseGroupOptions(); /// /// Gets options for the leecher user group. @@ -1065,7 +1065,7 @@ namespace slskd /// /// Options that are common to all groups. /// - public class GroupOptions + public class BaseGroupOptions { /// /// Gets upload options. @@ -1113,7 +1113,7 @@ namespace slskd /// /// Built in leecher group options. /// - public class LeecherOptions : GroupOptions + public class LeecherOptions : BaseGroupOptions { /// /// Gets leecher threshold options. @@ -1188,7 +1188,7 @@ namespace slskd /// /// User defined user group options. /// - public class UserDefinedOptions : GroupOptions + public class UserDefinedOptions : BaseGroupOptions { /// /// Gets the list of group member usernames. -- cgit v1.2.3 From 2cc9adfe04df35326a871ed9bf065402d3376b36 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 1 Mar 2026 18:27:58 -0600 Subject: add WIP retry logic --- src/slskd/Transfers/Downloads/DownloadService.cs | 69 +++++++++++++++++------- 1 file changed, 51 insertions(+), 18 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index e6a65dcd..030eeb5e 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -998,30 +998,63 @@ namespace slskd.Transfers.Downloads }), disposeOutputStreamOnCompletion: true); + var retryOptions = OptionsMonitor.CurrentValue.Transfers.Download.Retry; + System.IO.UnixFileMode? unixFileMode = !string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Permissions.File.Mode) ? OptionsMonitor.CurrentValue.Permissions.File.Mode.ToUnixFileMode() : null; + var incompleteFilename = transfer.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Incomplete); + var incompleteFileInfo = Files.ResolveFileInfo(incompleteFilename); + var incompleteStrategy = retryOptions.Incomplete.ToEnum(); + + bool shouldResume = incompleteFileInfo.Exists && incompleteFileInfo.Length > 0 && incompleteStrategy == RetryIncompleteStrategy.Resume; + Log.Debug("Invoking Soulseek DownloadAsync() for {Filename} from {Username}", transfer.Filename, transfer.Username); + transfer.Attempts = 1; + SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: CancellationToken.None); - var completedTransfer = await Client.DownloadAsync( - username: transfer.Username, - remoteFilename: transfer.Filename, - outputStreamFactory: () => Task.FromResult( - Files.CreateFile( - filename: transfer.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Incomplete), - options: new CreateFileOptions - { - Access = System.IO.FileAccess.Write, - Mode = System.IO.FileMode.Create, // overwrites file if it exists - Share = System.IO.FileShare.None, // exclusive access for the duration of the download - UnixCreateMode = unixFileMode, - })), - size: transfer.Size, - startOffset: 0, - token: null, - cancellationToken: cancellationToken, - options: topts); + + var completedTransfer = await Retry.Do(() => Client.DownloadAsync( + username: transfer.Username, + remoteFilename: transfer.Filename, + outputStreamFactory: () => Task.FromResult( + Files.CreateFile( + filename: incompleteFilename, + options: new CreateFileOptions + { + Access = System.IO.FileAccess.Write, + Mode = shouldResume ? System.IO.FileMode.Append : System.IO.FileMode.Create, + Share = System.IO.FileShare.None, // exclusive access for the duration of the download + UnixCreateMode = unixFileMode, + })), + size: transfer.Size, + startOffset: shouldResume ? incompleteFileInfo.Length : 0, + token: null, + cancellationToken: cancellationToken, + options: topts), + isRetryable: (attempts, ex) => + ex is not OperationCanceledException + && ex is not TransferRejectedException + && ex is not DuplicateTransferException + && ex is not TransferSizeMismatchException, + onRetry: (attempts, delay) => + { + Log.Information("Waiting about {Delay} second(s) to retry attempt #{Attempt} to download {Filename} from user {Username} in {Delay}ms", (int)Math.Ceiling((double)delay / 1000), attempts, transfer.Filename, transfer.Username); + + transfer.Attempts = attempts; + transfer.State = TransferStates.Queued | TransferStates.Locally; + SynchronizedUpdate(transfer, updateSyncRoot); + }, + onFailure: (attempts, ex) => + { + Console.WriteLine($"---------------------------------------------{ex.GetType()}"); + Log.Warning("Failed attempt #{Attempts} to download {Filename} from user {Username}: {Message}", attempts, transfer.Filename, transfer.Username, ex.Message); + }, + maxAttempts: retryOptions.Attempts, + baseDelayInMilliseconds: retryOptions.Delay, + maxDelayInMilliseconds: retryOptions.MaxDelay, + cancellationToken: cancellationToken); Log.Debug("Invocation of Soulseek DownloadAsync() for {Filename} from user {Username} completed successfully", transfer.Filename, transfer.Username); -- cgit v1.2.3 From 225ac9a1a78f743dd0c0ce201b222296ae8528ea Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 1 Mar 2026 18:52:02 -0600 Subject: rename GroupId to BatchId --- ...26_02_17_TransferAttemptsAndBatchIdMigration.cs | 109 +++++++++++++++++++++ ...26_02_17_TransferAttemptsAndGroupIdMigration.cs | 109 --------------------- src/slskd/Core/Data/Migrator.cs | 2 +- src/slskd/Transfers/Extensions.cs | 2 +- src/slskd/Transfers/TransfersDbContext.cs | 4 +- src/slskd/Transfers/Types/Transfer.cs | 2 +- 6 files changed, 114 insertions(+), 114 deletions(-) create mode 100644 src/slskd/Core/Data/Migrations/Z2026_02_17_TransferAttemptsAndBatchIdMigration.cs delete mode 100644 src/slskd/Core/Data/Migrations/Z2026_02_17_TransferAttemptsAndGroupIdMigration.cs (limited to 'src') diff --git a/src/slskd/Core/Data/Migrations/Z2026_02_17_TransferAttemptsAndBatchIdMigration.cs b/src/slskd/Core/Data/Migrations/Z2026_02_17_TransferAttemptsAndBatchIdMigration.cs new file mode 100644 index 00000000..66083a83 --- /dev/null +++ b/src/slskd/Core/Data/Migrations/Z2026_02_17_TransferAttemptsAndBatchIdMigration.cs @@ -0,0 +1,109 @@ +// +// 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.Migrations; + +using System; +using System.Linq; +using Microsoft.Data.Sqlite; +using Serilog; +using slskd.Transfers; + +/// +/// Updates the Transfers table to add Attempts and BatchId columns. +/// +public class Z2026_02_17_TransferAttemptsAndBatchIdMigration : IMigration +{ + public Z2026_02_17_TransferAttemptsAndBatchIdMigration(ConnectionStringDictionary connectionStrings) + { + ConnectionString = connectionStrings[Database.Transfers]; + } + + private ILogger Log { get; } = Serilog.Log.ForContext(); + private string ConnectionString { get; } + + public bool NeedsToBeApplied() + { + var schema = SchemaInspector.GetDatabaseSchema(ConnectionString); + var idxes = SchemaInspector.GetDatabaseIndexes(ConnectionString); + + var columns = schema["Transfers"]; + var indexes = idxes["Transfers"]; + + // check to see if the Attempts and BatchId columns exist + if (columns.Any(c => c.Name == nameof(Transfer.Attempts)) + && columns.Any(c => c.Name == nameof(Transfer.BatchId)) + && indexes.Any(i => i.Name.Equals("IDX_Transfers_BatchId", StringComparison.OrdinalIgnoreCase))) + { + return false; + } + + return true; + } + + public void Apply() + { + if (!NeedsToBeApplied()) + { + Log.Information("> Migration {Name} is not necessary or has already been applied", nameof(Z2026_02_17_TransferAttemptsAndBatchIdMigration)); + return; + } + + var columns = SchemaInspector.GetDatabaseSchema(ConnectionString)["Transfers"]; + + using var connection = new SqliteConnection(ConnectionString); + connection.Open(); + + using var transaction = connection.BeginTransaction(); + + try + { + void Exec(string sql) + { + using var command = new SqliteCommand(sql, connection, transaction); + command.ExecuteNonQuery(); + } + + Log.Information("> Adding BatchId and Attempts columns to the Transfers table..."); + + if (!columns.Any(c => c.Name == nameof(Transfer.BatchId))) + { + Exec("ALTER TABLE Transfers ADD COLUMN BatchId TEXT NULL;"); + } + + if (!columns.Any(c => c.Name == nameof(Transfer.Attempts))) + { + Exec("ALTER TABLE Transfers ADD COLUMN Attempts INTEGER NOT NULL DEFAULT 0;"); + } + + Log.Information("> New columns added"); + + Log.Information("> Adding missing index(es) on the Transfers table..."); + + Exec("CREATE INDEX IF NOT EXISTS IDX_Transfers_BatchId ON Transfers (BatchId)"); + + Log.Information("> Index(es) created"); + transaction.Commit(); + Log.Information("> Done!"); + } + catch (Exception) + { + transaction.Rollback(); + throw; + } + } +} diff --git a/src/slskd/Core/Data/Migrations/Z2026_02_17_TransferAttemptsAndGroupIdMigration.cs b/src/slskd/Core/Data/Migrations/Z2026_02_17_TransferAttemptsAndGroupIdMigration.cs deleted file mode 100644 index dfdd68eb..00000000 --- a/src/slskd/Core/Data/Migrations/Z2026_02_17_TransferAttemptsAndGroupIdMigration.cs +++ /dev/null @@ -1,109 +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.Migrations; - -using System; -using System.Linq; -using Microsoft.Data.Sqlite; -using Serilog; -using slskd.Transfers; - -/// -/// Updates the Transfers table to add Attempts and GroupId columns. -/// -public class Z2026_02_17_TransferAttemptsAndGroupIdMigration : IMigration -{ - public Z2026_02_17_TransferAttemptsAndGroupIdMigration(ConnectionStringDictionary connectionStrings) - { - ConnectionString = connectionStrings[Database.Transfers]; - } - - private ILogger Log { get; } = Serilog.Log.ForContext(); - private string ConnectionString { get; } - - public bool NeedsToBeApplied() - { - var schema = SchemaInspector.GetDatabaseSchema(ConnectionString); - var idxes = SchemaInspector.GetDatabaseIndexes(ConnectionString); - - var columns = schema["Transfers"]; - var indexes = idxes["Transfers"]; - - // check to see if the Attempts and GroupId columns exist - if (columns.Any(c => c.Name == nameof(Transfer.Attempts)) - && columns.Any(c => c.Name == nameof(Transfer.GroupId)) - && indexes.Any(i => i.Name.Equals("IDX_Transfers_GroupId", StringComparison.OrdinalIgnoreCase))) - { - return false; - } - - return true; - } - - public void Apply() - { - if (!NeedsToBeApplied()) - { - Log.Information("> Migration {Name} is not necessary or has already been applied", nameof(Z2026_02_17_TransferAttemptsAndGroupIdMigration)); - return; - } - - var columns = SchemaInspector.GetDatabaseSchema(ConnectionString)["Transfers"]; - - using var connection = new SqliteConnection(ConnectionString); - connection.Open(); - - using var transaction = connection.BeginTransaction(); - - try - { - void Exec(string sql) - { - using var command = new SqliteCommand(sql, connection, transaction); - command.ExecuteNonQuery(); - } - - Log.Information("> Adding GroupId and Attempts columns to the Transfers table..."); - - if (!columns.Any(c => c.Name == nameof(Transfer.GroupId))) - { - Exec("ALTER TABLE Transfers ADD COLUMN GroupId TEXT NULL;"); - } - - if (!columns.Any(c => c.Name == nameof(Transfer.Attempts))) - { - Exec("ALTER TABLE Transfers ADD COLUMN Attempts INTEGER NOT NULL DEFAULT 0;"); - } - - Log.Information("> New columns added"); - - Log.Information("> Adding missing index(es) on the Transfers table..."); - - Exec("CREATE INDEX IF NOT EXISTS IDX_Transfers_GroupId ON Transfers (GroupId)"); - - Log.Information("> Index(es) created"); - transaction.Commit(); - Log.Information("> Done!"); - } - catch (Exception) - { - transaction.Rollback(); - throw; - } - } -} diff --git a/src/slskd/Core/Data/Migrator.cs b/src/slskd/Core/Data/Migrator.cs index a5096143..c1089090 100644 --- a/src/slskd/Core/Data/Migrator.cs +++ b/src/slskd/Core/Data/Migrator.cs @@ -44,7 +44,7 @@ public class Migrator { nameof(Z2025_07_06_TransferIndexesMigration), new Z2025_07_06_TransferIndexesMigration(connectionStrings: Databases) }, { nameof(Z2025_07_26_PrivateMessageWasReplayedMigration), new Z2025_07_26_PrivateMessageWasReplayedMigration(connectionStrings: Databases) }, { nameof(Z2025_12_28_AdditionalTransferIndexesMigration), new Z2025_12_28_AdditionalTransferIndexesMigration(connectionStrings: Databases) }, - { nameof(Z2026_02_17_TransferAttemptsAndGroupIdMigration), new Z2026_02_17_TransferAttemptsAndGroupIdMigration(connectionStrings: Databases) }, + { nameof(Z2026_02_17_TransferAttemptsAndBatchIdMigration), new Z2026_02_17_TransferAttemptsAndBatchIdMigration(connectionStrings: Databases) }, }; } diff --git a/src/slskd/Transfers/Extensions.cs b/src/slskd/Transfers/Extensions.cs index bf139a1d..5a0bd914 100644 --- a/src/slskd/Transfers/Extensions.cs +++ b/src/slskd/Transfers/Extensions.cs @@ -23,7 +23,7 @@ namespace slskd.Transfers { return new Transfer() { - GroupId = transfer.GroupId, + BatchId = transfer.BatchId, Id = transfer.Id, Username = transfer.Username, Direction = transfer.Direction, diff --git a/src/slskd/Transfers/TransfersDbContext.cs b/src/slskd/Transfers/TransfersDbContext.cs index 79171809..d82259e7 100644 --- a/src/slskd/Transfers/TransfersDbContext.cs +++ b/src/slskd/Transfers/TransfersDbContext.cs @@ -83,8 +83,8 @@ namespace slskd.Transfers modelBuilder .Entity() - .HasIndex(t => t.GroupId) - .HasDatabaseName("IDX_Transfers_GroupId"); + .HasIndex(t => t.BatchId) + .HasDatabaseName("IDX_Transfers_BatchId"); // covers the check for existing records when enqueueing uploads and downloads modelBuilder diff --git a/src/slskd/Transfers/Types/Transfer.cs b/src/slskd/Transfers/Types/Transfer.cs index e2ef6d5d..56f6b333 100644 --- a/src/slskd/Transfers/Types/Transfer.cs +++ b/src/slskd/Transfers/Types/Transfer.cs @@ -25,7 +25,7 @@ namespace slskd.Transfers public class Transfer { - public Guid? GroupId { get; init; } = null; + public Guid? BatchId { get; init; } = null; [Key] public Guid Id { get; init; } -- cgit v1.2.3 From b41d978ac1acd1a324669fd539fc945a911f96f4 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 7 Mar 2026 19:25:06 -0600 Subject: rough in batch request type --- .../API/DTO/EnqueueDownloadBatchRequest.cs | 42 ++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs (limited to 'src') diff --git a/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs new file mode 100644 index 00000000..810b1529 --- /dev/null +++ b/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs @@ -0,0 +1,42 @@ +// +// 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.Collections.Generic; +using System.ComponentModel.DataAnnotations; + +namespace slskd.Transfers.API; + +public record EnqueueDownloadBatchRequest +{ + public Guid? BatchId { get; init; } + public Guid? SearchId { get; init; } + + [Required] + [StringLength(500, MinimumLength = 1)] + public string Username { get; init; } + public List Files { get; init; } = []; +} + +public record EnqueueDownloadBatchItem +{ + [Required] + public string Filename { get; set; } + + [Range(0, int.MaxValue)] + public long Size { get; set; } +} \ No newline at end of file -- cgit v1.2.3 From c5ae6da8ef092f77acade63f3ef79be162bb25b0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 8 Mar 2026 16:43:24 -0500 Subject: bump soulseek.net to 9.0.0 --- src/slskd/slskd.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj index ce5a7d54..ccc22a42 100644 --- a/src/slskd/slskd.csproj +++ b/src/slskd/slskd.csproj @@ -69,7 +69,7 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive -- cgit v1.2.3 From 1e6ef0791e2f6a4cbbec72573a52afc62e4717d8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 8 Mar 2026 17:05:52 -0500 Subject: provide a minor version of 760 when logging in --- src/slskd/Program.cs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 8d67e803..a9504bb8 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -156,6 +156,14 @@ namespace slskd /// public static string FullVersion { get; } = $"{SemanticVersion} ({InformationalVersion})"; + /// + /// Gets the minor version to identify slskd on the network. + /// + /// + /// NOTICE: If you have forked slskd, change this number to something else. + /// + public static int NetworkMinorVersion { get; } = 760; + /// /// Gets a value indicating whether the current version is a Canary build. /// @@ -680,7 +688,9 @@ namespace slskd // add a partially configured instance of SoulseekClient. the Application instance will // complete configuration at startup. services.AddSingleton(_ => - new SoulseekClient(options: new SoulseekClientOptions( + new SoulseekClient( + minorVersion: NetworkMinorVersion, + options: new SoulseekClientOptions( maximumConcurrentUploads: OptionsAtStartup.Transfers.Upload.Slots, maximumConcurrentDownloads: OptionsAtStartup.Transfers.Download.Slots, minimumDiagnosticLevel: OptionsAtStartup.Soulseek.DiagnosticLevel.ToEnum(), -- cgit v1.2.3 From 8e096e0c7c3c2808cdf316a809ba2568c55988ce Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 8 Mar 2026 18:38:51 -0500 Subject: ready report queries for retries --- src/slskd/Telemetry/ReportsService.cs | 3 +++ 1 file changed, 3 insertions(+) (limited to 'src') diff --git a/src/slskd/Telemetry/ReportsService.cs b/src/slskd/Telemetry/ReportsService.cs index da325dc0..2c9308ad 100644 --- a/src/slskd/Telemetry/ReportsService.cs +++ b/src/slskd/Telemetry/ReportsService.cs @@ -23,6 +23,7 @@ using System.Linq; using Dapper; using Microsoft.Data.Sqlite; using Serilog; +using slskd.Transfers; using Soulseek; /// @@ -84,6 +85,7 @@ public class ReportsService FROM Transfers WHERE EndedAt IS NOT NULL AND EndedAt BETWEEN @Start AND @End + AND State IN ({string.Join(", ", TransferStateCategories.Completed.Select(s => (int)s))}) {(direction is not null ? "AND Direction = @Direction" : string.Empty)} {(username is not null ? "AND Username = @Username" : string.Empty)} GROUP BY Direction, StateDescription @@ -171,6 +173,7 @@ public class ReportsService FROM Transfers WHERE EndedAt IS NOT NULL AND EndedAt BETWEEN @Start AND @End + AND State IN ({string.Join(", ", TransferStateCategories.Completed.Select(s => (int)s))}) {(direction is not null ? "AND Direction = @Direction" : string.Empty)} {(username is not null ? "AND Username = @Username" : string.Empty)} GROUP BY Interval, Direction, StateDescription -- cgit v1.2.3 From f5dae4af3ba121983f1cac20f310f86916b82202 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 8 Mar 2026 18:57:55 -0500 Subject: show attempts and exception on ui --- src/web/src/components/Transfers/TransferDetails.jsx | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src') diff --git a/src/web/src/components/Transfers/TransferDetails.jsx b/src/web/src/components/Transfers/TransferDetails.jsx index 256ddcac..2ec890e9 100644 --- a/src/web/src/components/Transfers/TransferDetails.jsx +++ b/src/web/src/components/Transfers/TransferDetails.jsx @@ -79,6 +79,8 @@ const TransferDetails = ({ file }) => { 'elapsedTime', 'percentComplete', 'remainingTime', + 'attempts', + 'exception', ]; return ( -- cgit v1.2.3 From 733e513407fe455f8523924e7ef4edf774f44f2f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 8 Mar 2026 19:04:43 -0500 Subject: show retry stuff if retrying --- src/web/src/components/Transfers/TransferList.jsx | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'src') diff --git a/src/web/src/components/Transfers/TransferList.jsx b/src/web/src/components/Transfers/TransferList.jsx index 4bd1e14e..42e58933 100644 --- a/src/web/src/components/Transfers/TransferList.jsx +++ b/src/web/src/components/Transfers/TransferList.jsx @@ -163,6 +163,9 @@ class TransferList extends Component { padding: 7, }} {...getColor(f.state)} + {...(!getColor(f.state).color && f.attempts > 1 + ? { color: 'yellow' } + : {})} active={f.direction === 'Upload'} onClick={() => this.handleClick(f)} > @@ -176,6 +179,7 @@ class TransferList extends Component { )} {f.state} {f.placeInQueue ? ` (#${f.placeInQueue})` : ''} + {f.attempts > 1 ? ` (Retry #${f.attempts})` : ''} )} -- cgit v1.2.3 From a7b5682ccaf37cbfad5b5302cfbeab5fd3d577b6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 8 Mar 2026 19:05:04 -0500 Subject: don't set Completed until all retries are exhausted --- src/slskd/Transfers/Downloads/DownloadService.cs | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 030eeb5e..53730980 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -922,6 +922,7 @@ namespace slskd.Transfers.Downloads using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, cancellationTokenSource?.Token ?? CancellationToken.None); cancellationToken = cts.Token; + var retryOptions = OptionsMonitor.CurrentValue.Transfers.Download.Retry; var updateSyncRoot = new SemaphoreSlim(1, 1); try @@ -952,6 +953,16 @@ namespace slskd.Transfers.Downloads transfer.EnqueuedAt ??= DateTime.UtcNow; } + // important! the transfer on the Soulseek.NET side may have completed, but the slskd transfer + // *might* still have remaining retry attempts. leave this non-committal for now, and allow + // the final update after all retry attempts have been exhausted to add it. + // this means that the ONLY way to check whether a transfer is really 'dead' inclusive of all + // retries is to look for this flag + if (transfer.Attempts < retryOptions.Attempts) + { + transfer.State &= ~TransferStates.Completed; // remove the Completed flag + } + // todo: broadcast SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: cancellationToken); } @@ -998,8 +1009,6 @@ namespace slskd.Transfers.Downloads }), disposeOutputStreamOnCompletion: true); - var retryOptions = OptionsMonitor.CurrentValue.Transfers.Download.Retry; - System.IO.UnixFileMode? unixFileMode = !string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Permissions.File.Mode) ? OptionsMonitor.CurrentValue.Permissions.File.Mode.ToUnixFileMode() : null; @@ -1014,7 +1023,6 @@ namespace slskd.Transfers.Downloads transfer.Attempts = 1; SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: CancellationToken.None); - var completedTransfer = await Retry.Do(() => Client.DownloadAsync( username: transfer.Username, remoteFilename: transfer.Filename, @@ -1048,7 +1056,6 @@ namespace slskd.Transfers.Downloads }, onFailure: (attempts, ex) => { - Console.WriteLine($"---------------------------------------------{ex.GetType()}"); Log.Warning("Failed attempt #{Attempts} to download {Filename} from user {Username}: {Message}", attempts, transfer.Filename, transfer.Username, ex.Message); }, maxAttempts: retryOptions.Attempts, @@ -1177,6 +1184,7 @@ namespace slskd.Transfers.Downloads try { + Log.Warning("-------------------> Synchronized update for transfer: {Filename}; state: {State}, attempts: {Attempts}, endedAt: {EndedAt}, exception: {Exception}", transfer.Filename, transfer.State, transfer.Attempts, transfer.EndedAt, transfer.Exception); Update(transfer); } finally -- cgit v1.2.3 From c4040a707823999d4612922a77ca6485dc1ca06f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 10 Mar 2026 21:31:03 -0500 Subject: cap number of tracked exceptions --- src/slskd/Common/Retry.cs | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/Retry.cs b/src/slskd/Common/Retry.cs index 457d32fb..80d0bc7f 100644 --- a/src/slskd/Common/Retry.cs +++ b/src/slskd/Common/Retry.cs @@ -37,6 +37,7 @@ namespace slskd /// The maximum number of retry attempts. /// The base delay in milliseconds. /// The maximum delay in milliseconds. + /// The maximum number of Exceptions to keep in history. /// The token to monitor for cancellation requests. /// The execution context. public static async Task Do( @@ -47,13 +48,14 @@ namespace slskd int maxAttempts = 3, int baseDelayInMilliseconds = 1000, int maxDelayInMilliseconds = int.MaxValue, + int exceptionHistoryLimit = 5, CancellationToken cancellationToken = default) { await Do(async () => { await task(); return Task.FromResult(null); - }, isRetryable, onRetry, onFailure, maxAttempts, baseDelayInMilliseconds, maxDelayInMilliseconds, cancellationToken); + }, isRetryable, onRetry, onFailure, maxAttempts, baseDelayInMilliseconds, maxDelayInMilliseconds, exceptionHistoryLimit, cancellationToken); } /// @@ -66,6 +68,7 @@ namespace slskd /// The maximum number of retry attempts. /// The base delay in milliseconds. /// The maximum delay in milliseconds. + /// The maximum number of Exceptions to keep in history. /// The token to monitor for cancellation requests. /// The Type of the logic return value. /// The execution context. @@ -77,11 +80,12 @@ namespace slskd int maxAttempts = 3, int baseDelayInMilliseconds = 1000, int maxDelayInMilliseconds = int.MaxValue, + int exceptionHistoryLimit = 5, CancellationToken cancellationToken = default) { isRetryable ??= (_, _) => true; - var exceptions = new List(); + var exceptions = new Queue(); for (int attempts = 0; attempts < maxAttempts; attempts++) { @@ -104,7 +108,12 @@ namespace slskd } catch (Exception ex) { - exceptions.Add(ex); + exceptions.Enqueue(ex); + + if (exceptions.Count > exceptionHistoryLimit) + { + exceptions.Dequeue(); + } try { -- cgit v1.2.3 From 76781b730a392f11af0548664c2928c89d013f5c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 10 Mar 2026 21:31:28 -0500 Subject: derive incomplete file stats inside of retry loop to enable resume --- src/slskd/Transfers/Downloads/DownloadService.cs | 63 +++++++++++++++--------- 1 file changed, 41 insertions(+), 22 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 53730980..8f55a0c5 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -1014,33 +1014,52 @@ namespace slskd.Transfers.Downloads : null; var incompleteFilename = transfer.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Incomplete); - var incompleteFileInfo = Files.ResolveFileInfo(incompleteFilename); - var incompleteStrategy = retryOptions.Incomplete.ToEnum(); - - bool shouldResume = incompleteFileInfo.Exists && incompleteFileInfo.Length > 0 && incompleteStrategy == RetryIncompleteStrategy.Resume; Log.Debug("Invoking Soulseek DownloadAsync() for {Filename} from {Username}", transfer.Filename, transfer.Username); transfer.Attempts = 1; SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: CancellationToken.None); - var completedTransfer = await Retry.Do(() => Client.DownloadAsync( - username: transfer.Username, - remoteFilename: transfer.Filename, - outputStreamFactory: () => Task.FromResult( - Files.CreateFile( - filename: incompleteFilename, - options: new CreateFileOptions - { - Access = System.IO.FileAccess.Write, - Mode = shouldResume ? System.IO.FileMode.Append : System.IO.FileMode.Create, - Share = System.IO.FileShare.None, // exclusive access for the duration of the download - UnixCreateMode = unixFileMode, - })), - size: transfer.Size, - startOffset: shouldResume ? incompleteFileInfo.Length : 0, - token: null, - cancellationToken: cancellationToken, - options: topts), + var completedTransfer = await Retry.Do(() => + { + var incompleteFileInfo = Files.ResolveFileInfo(incompleteFilename); + var incompleteStrategy = retryOptions.Incomplete.ToEnum(); + + var shouldResume = false; + var startOffset = 0L; + + if (incompleteFileInfo.Exists && incompleteFileInfo.Length > 0) + { + if (incompleteStrategy == RetryIncompleteStrategy.Resume) + { + shouldResume = true; + startOffset = incompleteFileInfo.Length; + Log.Information("Resuming download of {Filename} from user {Username} at offset {Offet}", transfer.Filename, transfer.Username, incompleteFileInfo.Length); + } + else + { + Log.Information("Overwriting partial download of {Length} bytes for download of {Filename} from user {Username} at offset {Offet}", incompleteFileInfo.Length, transfer.Filename, transfer.Username); + } + } + + return Client.DownloadAsync( + username: transfer.Username, + remoteFilename: transfer.Filename, + outputStreamFactory: () => Task.FromResult( + Files.CreateFile( + filename: incompleteFilename, + options: new CreateFileOptions + { + Access = System.IO.FileAccess.Write, + Mode = shouldResume ? System.IO.FileMode.Append : System.IO.FileMode.Create, + Share = System.IO.FileShare.None, // exclusive access for the duration of the download + UnixCreateMode = unixFileMode, + })), + size: transfer.Size, + startOffset: startOffset, + token: null, + cancellationToken: cancellationToken, + options: topts); + }, isRetryable: (attempts, ex) => ex is not OperationCanceledException && ex is not TransferRejectedException -- cgit v1.2.3 From 8fd512878c96d46678f67b1e19c182fc3df10ec5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 14 Mar 2026 13:52:02 -0500 Subject: update Soulseek.NET to 9.1.0 to fix reporting issue with resumed transfers --- src/slskd/slskd.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj index ccc22a42..d715964e 100644 --- a/src/slskd/slskd.csproj +++ b/src/slskd/slskd.csproj @@ -69,7 +69,7 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive -- cgit v1.2.3 From 7d65971847354f9068ae7ea2c3bf53857566189f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 14 Mar 2026 19:12:52 -0500 Subject: remove logging --- src/slskd/Transfers/Downloads/DownloadService.cs | 1 - 1 file changed, 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 8f55a0c5..1a0c5e6c 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -1203,7 +1203,6 @@ namespace slskd.Transfers.Downloads try { - Log.Warning("-------------------> Synchronized update for transfer: {Filename}; state: {State}, attempts: {Attempts}, endedAt: {EndedAt}, exception: {Exception}", transfer.Filename, transfer.State, transfer.Attempts, transfer.EndedAt, transfer.Exception); Update(transfer); } finally -- cgit v1.2.3 From 7033851e42d1412c34c4022f6a8dd1632c64586e Mon Sep 17 00:00:00 2001 From: ofernander Date: Sun, 12 Apr 2026 18:40:01 -0700 Subject: feat: add username reg pattern matching to blacklist group Adds a field to that accepts a list of regular expressions matched against usernames. --- config/slskd.example.yml | 2 ++ docs/config.md | 4 ++++ src/slskd/Core/Options.cs | 16 ++++++++++++++++ src/slskd/Users/UserService.cs | 17 +++++++++++++++++ 4 files changed, 39 insertions(+) (limited to 'src') diff --git a/config/slskd.example.yml b/config/slskd.example.yml index 72aadaed..ee72a2e0 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -112,6 +112,8 @@ # blacklisted: # members: # - +# patterns: +# - # cidrs: # - # user_defined: diff --git a/docs/config.md b/docs/config.md index 6ba449f0..1b77a674 100644 --- a/docs/config.md +++ b/docs/config.md @@ -489,6 +489,8 @@ Private and chat room messages from blacklisted users are also ignored. Users can be blacklisted by adding their username to the `members` list. Additionally, users can be blacklisted by IP address, or range of addresses by adding a CIDR entry to the `cidrs` list. +The `patterns` list accepts regular expressions matched against usernames. Any username matching one or more patterns will be blacklisted. This is useful for blocking bots or automated clients that share a common username prefix or suffix — for example, `^user` would block any username starting with `user`, and `_bot$` would block any username ending with `_bot`. Patterns follow the same case sensitivity rules as other user-defined regular expressions in the application — case insensitive by default, controlled by the `flags.case_sensitive_regex` option. + Users added to the blacklist will be blocked from enqueueing any new files. Any existing active or queued transfers will need to be cancelled manually. A managed blacklist file may also be used to achieve the same effects. Read more about this in the [Managed Blacklist](#managed-blacklist) section below. @@ -499,6 +501,8 @@ groups: blacklisted: members: - + patterns: + - cidrs: - ``` diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 7b38143e..dda1b7b5 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1149,6 +1149,14 @@ namespace slskd /// public string[] Members { get; init; } = Array.Empty(); + /// + /// Gets the list of regular expression patterns matched against usernames. + /// Any username matching one or more patterns will be blacklisted. + /// Follows the same case sensitivity rules as other user-defined regular expressions + /// (case insensitive by default; controlled by the flags.case_sensitive_regex option). + /// + public string[] Patterns { get; init; } = Array.Empty(); + /// /// Gets the list of group CIDRs. /// @@ -1163,6 +1171,14 @@ namespace slskd { var results = new List(); + foreach (var pattern in Patterns ?? Array.Empty()) + { + if (!pattern.IsValidRegex()) + { + results.Add(new ValidationResult($"Blacklist username pattern '{pattern}' is not a valid regular expression")); + } + } + foreach (var cidr in Cidrs ?? Array.Empty()) { try diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index d8b24f4d..31c1e540 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -38,6 +38,7 @@ namespace slskd.Users using System.Collections.Generic; using System.Linq; using System.Net; + using System.Text.RegularExpressions; using System.Threading.Tasks; using NetTools; using Serilog; @@ -291,6 +292,8 @@ namespace slskd.Users /// A value indicating whether the specified user and/or IP are blacklisted. public bool IsBlacklisted(string username, IPAddress ipAddress = null) { + if (username is null) return false; + var blacklist = OptionsMonitor.CurrentValue.Transfers.Groups.Blacklisted; if (blacklist.Members.Contains(username)) @@ -298,6 +301,20 @@ namespace slskd.Users return true; } + // check username patterns (regex). respects the same case sensitivity flag used by other + // user-defined regular expressions throughout the application. + if (blacklist.Patterns.Length > 0) + { + var regexOptions = OptionsMonitor.CurrentValue.Flags.CaseSensitiveRegEx + ? RegexOptions.None + : RegexOptions.IgnoreCase; + + if (blacklist.Patterns.Any(p => Regex.IsMatch(username, p, regexOptions))) + { + return true; + } + } + // check the user-curated list of blacklisted CIDRs that exists along with the list of // blacklisted usernames. these CIDRs should be one-offs and would not be expected to appear in a // blacklist supplied by a third party (but might?) -- cgit v1.2.3 From 19d8070d6ce046f8dd3aecd34b30077fbfe6c29d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 19 Apr 2026 18:41:14 -0500 Subject: handle nulls in DiffWith --- src/slskd/Common/CommonExtensions.cs | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) (limited to 'src') diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs index 88e6d3c8..1cdf9854 100644 --- a/src/slskd/Common/CommonExtensions.cs +++ b/src/slskd/Common/CommonExtensions.cs @@ -116,6 +116,16 @@ namespace slskd throw new InvalidCastException($"Unable to diff types {left?.GetType()} and {right?.GetType()}"); } + if (left is null || right is null) + { + if (left is null == right is null) + { + return []; + } + + return [(null, parentFqn ?? string.Empty, left, right)]; + } + var differences = new List<(PropertyInfo Property, string FQN, object Left, object Right)>(); foreach (var prop in left?.GetType().GetProperties()) @@ -125,6 +135,16 @@ namespace slskd var propType = prop.PropertyType; var fqn = string.IsNullOrEmpty(parentFqn) ? prop.Name : string.Join(".", parentFqn, prop.Name); + if (leftVal is null || rightVal is null) + { + if (leftVal is null == rightVal is null) + { + continue; + } + + differences.Add((prop, fqn, leftVal, rightVal)); + } + if (propType.IsArray || (propType.IsGenericType && propType.GetGenericTypeDefinition() == typeof(Dictionary<,>))) { if (leftVal.ToJson() != rightVal.ToJson()) -- cgit v1.2.3 From 8ef80b442688288a40fb8c8fa8392249dc6ebb10 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 19 Apr 2026 18:50:04 -0500 Subject: support null propertyinfo --- src/slskd/Application.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index a8a7883a..86dd9dd1 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -1452,7 +1452,7 @@ namespace slskd foreach (var (property, fqn, left, right) in diff) { - static bool HasAttribute(PropertyInfo property) => property.CustomAttributes.Any(a => a.AttributeType == typeof(T)); + static bool HasAttribute(PropertyInfo property) => property?.CustomAttributes.Any(a => a.AttributeType == typeof(T)) ?? false; var requiresRestart = HasAttribute(property); var requiresReconnect = HasAttribute(property); -- cgit v1.2.3 From d415e5ca568f55cf9c45e84b05892219f9e1465a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 19 Apr 2026 18:50:28 -0500 Subject: check for nulls first --- src/slskd/Common/CommonExtensions.cs | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs index 1cdf9854..77db91ef 100644 --- a/src/slskd/Common/CommonExtensions.cs +++ b/src/slskd/Common/CommonExtensions.cs @@ -111,11 +111,6 @@ namespace slskd /// A list of differences between the two objects. public static IEnumerable<(PropertyInfo Property, string FQN, object Left, object Right)> DiffWith(this object left, object right, string parentFqn = null) { - if (left?.GetType() != right?.GetType()) - { - throw new InvalidCastException($"Unable to diff types {left?.GetType()} and {right?.GetType()}"); - } - if (left is null || right is null) { if (left is null == right is null) @@ -126,9 +121,14 @@ namespace slskd return [(null, parentFqn ?? string.Empty, left, right)]; } + if (left.GetType() != right.GetType()) + { + throw new InvalidCastException($"Unable to diff types {left.GetType()} and {right.GetType()}"); + } + var differences = new List<(PropertyInfo Property, string FQN, object Left, object Right)>(); - foreach (var prop in left?.GetType().GetProperties()) + foreach (var prop in left.GetType().GetProperties()) { var leftVal = prop.GetValue(left); var rightVal = prop.GetValue(right); @@ -143,6 +143,7 @@ namespace slskd } differences.Add((prop, fqn, leftVal, rightVal)); + continue; } if (propType.IsArray || (propType.IsGenericType && propType.GetGenericTypeDefinition() == typeof(Dictionary<,>))) -- cgit v1.2.3 From 795a78e441e28988bed629a0dc61874f760b43cd Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 20 Apr 2026 22:03:16 -0500 Subject: compile blacklist patterns --- src/slskd/Users/UserService.cs | 13 +++++++++++++ 1 file changed, 13 insertions(+) (limited to 'src') diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index 31c1e540..73bf1118 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -138,6 +138,7 @@ namespace slskd.Users private ILogger Log { get; set; } = Serilog.Log.ForContext(); private IOptionsMonitor OptionsMonitor { get; } private Blacklist Blacklist { get; } = new Blacklist(); + private IReadOnlyCollection CompiledBlacklistPatterns { get; set; } = []; /// /// Gets or sets the internal cache of User data. @@ -433,6 +434,18 @@ namespace slskd.Users } } + var regexOptions = RegexOptions.Compiled; + + if (!OptionsMonitor.CurrentValue.Flags.CaseSensitiveRegEx) + { + regexOptions |= RegexOptions.IgnoreCase; + } + + CompiledBlacklistPatterns = OptionsMonitor.CurrentValue.Transfers.Groups.Blacklisted.Patterns + .Select(f => new Regex(f, regexOptions)) + .ToList() + .AsReadOnly(); + LastOptionsHash = optionsHash; } -- cgit v1.2.3 From 73634ad0b54d486cc278c4950583754ad77aac00 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 21 Apr 2026 19:28:35 -0500 Subject: consistent options --- src/slskd/Core/Options.cs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index dda1b7b5..fcc65c3b 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1151,9 +1151,6 @@ namespace slskd /// /// Gets the list of regular expression patterns matched against usernames. - /// Any username matching one or more patterns will be blacklisted. - /// Follows the same case sensitivity rules as other user-defined regular expressions - /// (case insensitive by default; controlled by the flags.case_sensitive_regex option). /// public string[] Patterns { get; init; } = Array.Empty(); @@ -1175,7 +1172,7 @@ namespace slskd { if (!pattern.IsValidRegex()) { - results.Add(new ValidationResult($"Blacklist username pattern '{pattern}' is not a valid regular expression")); + results.Add(new ValidationResult($"Pattern '{pattern}' is not a valid regular expression")); } } -- cgit v1.2.3 From d2a71a7340c5caf7923824910f112be5b169378d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 21 Apr 2026 19:30:06 -0500 Subject: wip, wtf is going on here --- src/slskd/Users/UserService.cs | 60 +++++++++++++++++++++++++++++------------- 1 file changed, 41 insertions(+), 19 deletions(-) (limited to 'src') diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index 73bf1118..0eb541e0 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -34,12 +34,14 @@ using Microsoft.Extensions.Options; namespace slskd.Users { + using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text.RegularExpressions; using System.Threading.Tasks; + using Microsoft.Extensions.Caching.Memory; using NetTools; using Serilog; using Soulseek; @@ -139,6 +141,7 @@ namespace slskd.Users private IOptionsMonitor OptionsMonitor { get; } private Blacklist Blacklist { get; } = new Blacklist(); private IReadOnlyCollection CompiledBlacklistPatterns { get; set; } = []; + private MemoryCache GetGroupCache { get; } = new MemoryCache(new MemoryCacheOptions() { }); /// /// Gets or sets the internal cache of User data. @@ -171,33 +174,49 @@ namespace slskd.Users /// The group for the specified username. public string GetGroup(string username) { + if (GetGroupCache.TryGetValue(username, out var cached)) + { + return cached; + } + else + { + var group = GetGroupInternal(username); + + GetGroupCache.Set(username, group, new MemoryCacheEntryOptions { SlidingExpiration = TimeSpan.FromMinutes(10) }); + + return group; + } + // note: this is an extremely hot path; keep the work done to an absolute minimum. - if (UserDictionary.TryGetValue(username ?? string.Empty, out var user)) + string GetGroupInternal(string username) { - if (IsBlacklisted(user.Username)) + if (UserDictionary.TryGetValue(username ?? string.Empty, out var user)) { - return Application.BlacklistedGroup; - } + if (IsBlacklisted(user.Username)) + { + return Application.BlacklistedGroup; + } - if (user.Status?.IsPrivileged ?? false) - { - return Application.PrivilegedGroup; - } + if (user.Status?.IsPrivileged ?? false) + { + return Application.PrivilegedGroup; + } - if (user.Group != null) - { - return user.Group; - } + if (user.Group != null) + { + return user.Group; + } - var thresholds = OptionsMonitor.CurrentValue.Transfers.Groups.Leechers.Thresholds; + var thresholds = OptionsMonitor.CurrentValue.Transfers.Groups.Leechers.Thresholds; - if (user.Statistics?.FileCount < thresholds.Files || user.Statistics?.DirectoryCount < thresholds.Directories) - { - return Application.LeecherGroup; + if (user.Statistics?.FileCount < thresholds.Files || user.Statistics?.DirectoryCount < thresholds.Directories) + { + return Application.LeecherGroup; + } } - } - return Application.DefaultGroup; + return Application.DefaultGroup; + } } /// @@ -293,7 +312,10 @@ namespace slskd.Users /// A value indicating whether the specified user and/or IP are blacklisted. public bool IsBlacklisted(string username, IPAddress ipAddress = null) { - if (username is null) return false; + if (string.IsNullOrEmpty(username)) + { + throw new ArgumentNullException(nameof(username)); + } var blacklist = OptionsMonitor.CurrentValue.Transfers.Groups.Blacklisted; -- cgit v1.2.3 From ee041dc6c810982393745df7502c1630876bca6b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 21 Apr 2026 20:59:03 -0500 Subject: clarify purpose of group --- src/slskd/Users/Types/User.cs | 3 +++ 1 file changed, 3 insertions(+) (limited to 'src') diff --git a/src/slskd/Users/Types/User.cs b/src/slskd/Users/Types/User.cs index 7297d747..473bedfb 100644 --- a/src/slskd/Users/Types/User.cs +++ b/src/slskd/Users/Types/User.cs @@ -42,6 +42,9 @@ namespace slskd.Users /// /// Gets the user's configured group. /// + /// + /// This is the group under which the username appears in config, *not* the group derived at runtime. + /// public string Group { get; init; } /// -- cgit v1.2.3 From d49b11b2e74f872ef79a3966bac22601191ba773 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 21 Apr 2026 22:17:23 -0500 Subject: add a memory cache for blacklist decisions, recompile patterns and invalidate cache on config change --- src/slskd/Users/UserService.cs | 97 ++++++++++++++++++++++++++---------------- 1 file changed, 60 insertions(+), 37 deletions(-) (limited to 'src') diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index 73bf1118..9a29e567 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -34,12 +34,14 @@ using Microsoft.Extensions.Options; namespace slskd.Users { + using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text.RegularExpressions; using System.Threading.Tasks; + using Microsoft.Extensions.Caching.Memory; using NetTools; using Serilog; using Soulseek; @@ -139,6 +141,8 @@ namespace slskd.Users private IOptionsMonitor OptionsMonitor { get; } private Blacklist Blacklist { get; } = new Blacklist(); private IReadOnlyCollection CompiledBlacklistPatterns { get; set; } = []; + private MemoryCache BlacklistDecisionCache { get; } = + new MemoryCache(new MemoryCacheOptions { ExpirationScanFrequency = TimeSpan.FromMinutes(1), SizeLimit = 1000 }); /// /// Gets or sets the internal cache of User data. @@ -293,44 +297,59 @@ namespace slskd.Users /// A value indicating whether the specified user and/or IP are blacklisted. public bool IsBlacklisted(string username, IPAddress ipAddress = null) { - if (username is null) return false; + ArgumentNullException.ThrowIfNull(username); - var blacklist = OptionsMonitor.CurrentValue.Transfers.Groups.Blacklisted; - - if (blacklist.Members.Contains(username)) + if (BlacklistDecisionCache.TryGetValue(username, out var u)) { - return true; + return u; } - // check username patterns (regex). respects the same case sensitivity flag used by other - // user-defined regular expressions throughout the application. - if (blacklist.Patterns.Length > 0) + var b = IsBlacklistedInternal(username, ipAddress); + + BlacklistDecisionCache.Set(username, b, new MemoryCacheEntryOptions { SlidingExpiration = TimeSpan.FromMinutes(10) }); + + return b; + + bool IsBlacklistedInternal(string username, IPAddress iPAddress = null) { - var regexOptions = OptionsMonitor.CurrentValue.Flags.CaseSensitiveRegEx - ? RegexOptions.None - : RegexOptions.IgnoreCase; + // first, check to see if the name appears explicitly in the config + var blacklist = OptionsMonitor.CurrentValue.Transfers.Groups.Blacklisted; - if (blacklist.Patterns.Any(p => Regex.IsMatch(username, p, regexOptions))) + if (blacklist.Members.Contains(username)) { return true; } - } - // check the user-curated list of blacklisted CIDRs that exists along with the list of - // blacklisted usernames. these CIDRs should be one-offs and would not be expected to appear in a - // blacklist supplied by a third party (but might?) - if (ipAddress is not null && blacklist.Cidrs.Select(c => IPAddressRange.Parse(c)).Any(range => range.Contains(ipAddress))) - { - return true; - } + // check username patterns (regex). respects the same case sensitivity flag used by other + // user-defined regular expressions throughout the application. + if (blacklist.Patterns.Length > 0) + { + var regexOptions = OptionsMonitor.CurrentValue.Flags.CaseSensitiveRegEx + ? RegexOptions.None + : RegexOptions.IgnoreCase; - // check the managed blacklist loaded from a third party blacklist file - if (ipAddress is not null && Blacklist.Contains(ipAddress)) - { - return true; - } + if (blacklist.Patterns.Any(p => Regex.IsMatch(username, p, regexOptions))) + { + return true; + } + } - return false; + // check the user-curated list of blacklisted CIDRs that exists along with the list of + // blacklisted usernames. these CIDRs should be one-offs and would not be expected to appear in a + // blacklist supplied by a third party (but might?) + if (ipAddress is not null && blacklist.Cidrs.Select(c => IPAddressRange.Parse(c)).Any(range => range.Contains(ipAddress))) + { + return true; + } + + // check the managed blacklist loaded from a third party blacklist file + if (ipAddress is not null && Blacklist.Contains(ipAddress)) + { + return true; + } + + return false; + } } /// @@ -434,21 +453,22 @@ namespace slskd.Users } } - var regexOptions = RegexOptions.Compiled; - - if (!OptionsMonitor.CurrentValue.Flags.CaseSensitiveRegEx) - { - regexOptions |= RegexOptions.IgnoreCase; - } + LastOptionsHash = optionsHash; + } - CompiledBlacklistPatterns = OptionsMonitor.CurrentValue.Transfers.Groups.Blacklisted.Patterns - .Select(f => new Regex(f, regexOptions)) - .ToList() - .AsReadOnly(); + // recompile blacklist patterns, regardless of whether they changed (this cheap to do) + var regexOptions = RegexOptions.Compiled; - LastOptionsHash = optionsHash; + if (!OptionsMonitor.CurrentValue.Flags.CaseSensitiveRegEx) + { + regexOptions |= RegexOptions.IgnoreCase; } + CompiledBlacklistPatterns = OptionsMonitor.CurrentValue.Transfers.Groups.Blacklisted.Patterns + .Select(f => new Regex(f, regexOptions)) + .ToList() + .AsReadOnly(); + var blacklistOptionsHash = Compute.Sha1Hash(options.Blacklist.ToJson()); // there's no forced re-config of the blacklist; either the config changed or it didn't. @@ -494,6 +514,9 @@ namespace slskd.Users LastBlacklistOptionsHash = blacklistOptionsHash; } + + // invalidate cached blacklist decisions + BlacklistDecisionCache.Clear(); } private void Reset() -- cgit v1.2.3 From a379b400b62c7c29fb3ace854b2d8acfdeeee26e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 22 Apr 2026 18:46:50 -0500 Subject: check compiled patterns --- src/slskd/Users/UserService.cs | 14 +++----------- 1 file changed, 3 insertions(+), 11 deletions(-) (limited to 'src') diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index 469680cf..ee117855 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -319,18 +319,10 @@ namespace slskd.Users return true; } - // check username patterns (regex). respects the same case sensitivity flag used by other - // user-defined regular expressions throughout the application. - if (blacklist.Patterns.Length > 0) + // check to see if the username matches any patterns + if (CompiledBlacklistPatterns.Any(pattern => pattern.IsMatch(username))) { - var regexOptions = OptionsMonitor.CurrentValue.Flags.CaseSensitiveRegEx - ? RegexOptions.None - : RegexOptions.IgnoreCase; - - if (blacklist.Patterns.Any(p => Regex.IsMatch(username, p, regexOptions))) - { - return true; - } + return true; } // check the user-curated list of blacklisted CIDRs that exists along with the list of -- cgit v1.2.3 From 13e8d31658fbe9083bb44bc0666983fa988af0ca Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 22 Apr 2026 18:47:48 -0500 Subject: add cache for IsBlacklisted --- src/slskd/Users/IUserService.cs | 3 ++- src/slskd/Users/UserService.cs | 39 ++++++++++++++++++++++++++++++--------- 2 files changed, 32 insertions(+), 10 deletions(-) (limited to 'src') diff --git a/src/slskd/Users/IUserService.cs b/src/slskd/Users/IUserService.cs index f2cfa5f1..28bb6459 100644 --- a/src/slskd/Users/IUserService.cs +++ b/src/slskd/Users/IUserService.cs @@ -144,8 +144,9 @@ namespace slskd.Users /// /// The username to check. /// The IPAddress to check, if available. + /// A value indicating whether to compute blacklisted status on a cache miss. /// A value indicating whether the specified user and/or IP are blacklisted. - bool IsBlacklisted(string username, IPAddress ipAddress = null); + bool IsBlacklisted(string username, IPAddress ipAddress = null, bool bypassCache = true); /// /// Retrieves a value indicating whether the specified peer is privileged. diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index ee117855..0a620992 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -88,15 +88,20 @@ namespace slskd.Users /// /// /// + /// public UserService( ISoulseekClient soulseekClient, - IOptionsMonitor optionsMonitor) + IOptionsMonitor optionsMonitor, + ISystemClock systemClock) { Client = soulseekClient; OptionsMonitor = optionsMonitor; OptionsMonitor.OnChange(options => Configure(options)); + InjectedClock = systemClock; + BlacklistDecisionCache = new MemoryCache(new MemoryCacheOptions { Clock = InjectedClock, ExpirationScanFrequency = TimeSpan.FromMinutes(1), SizeLimit = 1000 }); + // updates may be sent unsolicited from the server, so update when we get them. binding these events will cause // multiple redundant round trips when initially watching a user or when explicitly requesting via // GetStatus/GetStatistics. this is wasteful, but there's no functional side effect. @@ -141,8 +146,8 @@ namespace slskd.Users private IOptionsMonitor OptionsMonitor { get; } private Blacklist Blacklist { get; } = new Blacklist(); private IReadOnlyCollection CompiledBlacklistPatterns { get; set; } = []; - private MemoryCache BlacklistDecisionCache { get; } = - new MemoryCache(new MemoryCacheOptions { ExpirationScanFrequency = TimeSpan.FromMinutes(1), SizeLimit = 1000 }); + private ISystemClock InjectedClock { get; } + private MemoryCache BlacklistDecisionCache { get; } /// /// Gets or sets the internal cache of User data. @@ -291,23 +296,39 @@ namespace slskd.Users /// /// Gets a value indicating whether the specified and/or are blacklisted. /// + /// + /// This method may be taxing if the user has defined a blacklist file or large number of patterns. Call it to 'guard' + /// actions at the network level (with the exception of search results where latency is sensitive), but don't + /// use it to check once the user is 'in' the system (e.g. don't call this in the upload governor or queue logic). + /// /// The username to check. /// The IPAddress to check, if available. + /// A value indicating whether to compute blacklisted status on a cache miss. /// A value indicating whether the specified user and/or IP are blacklisted. - public bool IsBlacklisted(string username, IPAddress ipAddress = null) + public bool IsBlacklisted(string username, IPAddress ipAddress = null, bool bypassCache = true) { ArgumentNullException.ThrowIfNull(username); - if (BlacklistDecisionCache.TryGetValue(username, out var u)) + if (BlacklistDecisionCache.TryGetValue(username, out var cached)) { - return u; + return cached; + } + + // if we have a cache miss and the caller has specified bypassCache = false, assume that a cache miss + // means that the user is not blacklisted. we will only specify bypassCache = false when we're checking + // in a hot path, which at the time of this writing is only when determining whether to search shares for a + // request. we will check again before sending the results with bypassCache = true, and we should always + // follow this pattern when using bypassCache = false (specifically, check again before sending something) + if (!bypassCache) + { + return false; } - var b = IsBlacklistedInternal(username, ipAddress); + var blacklisted = IsBlacklistedInternal(username, ipAddress); - BlacklistDecisionCache.Set(username, b, new MemoryCacheEntryOptions { SlidingExpiration = TimeSpan.FromMinutes(10) }); + BlacklistDecisionCache.Set(username, blacklisted, new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10) }); - return b; + return blacklisted; bool IsBlacklistedInternal(string username, IPAddress iPAddress = null) { -- cgit v1.2.3 From 0e79985655abcbf10380f60fd50da46c47d8af88 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 22 Apr 2026 18:48:15 -0500 Subject: document GetGroup, remove check of IsBlacklisted within --- src/slskd/Users/UserService.cs | 30 +++++++++++++++++++++++------- 1 file changed, 23 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index 0a620992..95892753 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -42,6 +42,7 @@ namespace slskd.Users using System.Text.RegularExpressions; using System.Threading.Tasks; using Microsoft.Extensions.Caching.Memory; + using Microsoft.Extensions.Internal; using NetTools; using Serilog; using Soulseek; @@ -173,30 +174,45 @@ namespace slskd.Users private ConcurrentDictionary WatchedUsernamesDictionary { get; set; } = new ConcurrentDictionary(); /// - /// Gets the name of the group for the specified . + /// Gets the name of the group for the specified from cached data. /// - /// The group name is fetched from cached data, and lookups should always be fast. + /// + /// + /// Excludes the 'blacklisted' group for performance; use to guard network operations instead. + /// + /// + /// This is an extremely hot path, and the value returned may be approximated or incorrect in the case of a + /// cache miss in order to provide low latency values. + /// + /// /// The username of the peer. /// The group for the specified username. public string GetGroup(string username) { + // users end up in this dictionary for a few reasons, including but maybe not limited to: + // * they show up in the user defined group list somewhere + // * the server told us they have privileges when we logged in + // * we 'watched' them + // * we fetched statistics or status for them + // if we handle any of their data they'll probably wind up here. if they show up in the config, + // their Group property will be set. otherwise we must resolve their group dynamically. if (UserDictionary.TryGetValue(username ?? string.Empty, out var user)) { - if (IsBlacklisted(user.Username)) - { - return Application.BlacklistedGroup; - } - + // privileged users trump everything, and we resolve their group accordingly regardless of all other factors if (user.Status?.IsPrivileged ?? false) { return Application.PrivilegedGroup; } + // if the user isn't privileged and the user has put their username in any user defined group, that's + // their group. they aren't subjected to leecher checks. if (user.Group != null) { return user.Group; } + // check to see if they are a leecher. they may be in the dictionary because we checked their stats. + // if we don't have their stats we don't have enough info to make the call, group is inconclusive so fall through var thresholds = OptionsMonitor.CurrentValue.Transfers.Groups.Leechers.Thresholds; if (user.Statistics?.FileCount < thresholds.Files || user.Statistics?.DirectoryCount < thresholds.Directories) -- cgit v1.2.3 From c6f3bcb5da8d9a075789b1136cf46bb1ad86835d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 22 Apr 2026 18:48:42 -0500 Subject: use only cached blacklist status pre-search --- src/slskd/Application.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index a8a7883a..b25713ef 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -1651,7 +1651,9 @@ namespace slskd var sw = new Stopwatch(); sw.Start(); - if (Users.IsBlacklisted(username)) + // opportunistically try and avoid performing the search if we have a cached blacklisted value, otherwise + // hold off on computing it and filling the cache until we have the user's IP + if (Users.IsBlacklisted(username, bypassCache: false)) { return null; } -- cgit v1.2.3 From b7e5f00ce9a9d5f44b956e4f1a70f84fc1b2bea8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 22 Apr 2026 18:48:56 -0500 Subject: add obsolete flag to BlacklistedGroup --- src/slskd/Application.cs | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index b25713ef..6112198c 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -94,6 +94,7 @@ namespace slskd /// /// The name of the blacklisted user group. /// + [Obsolete("use IsBlacklisted instead")] public const string BlacklistedGroup = "blacklisted"; private static readonly string ApplicationShutdownTransferExceptionMessage = "Application shut down"; -- cgit v1.2.3 From afdeba219343136d89e6414e0983a5937e272eb4 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 22 Apr 2026 22:17:53 -0500 Subject: make cache set more legible --- src/slskd/Users/UserService.cs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index 95892753..4354a0eb 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -342,7 +342,14 @@ namespace slskd.Users var blacklisted = IsBlacklistedInternal(username, ipAddress); - BlacklistDecisionCache.Set(username, blacklisted, new MemoryCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10) }); + BlacklistDecisionCache.Set( + key: username, + value: blacklisted, + options: new MemoryCacheEntryOptions + { + AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10), + Size = 1, + }); return blacklisted; -- cgit v1.2.3 From 5a47b87e6c03cd093ce07274479d5c1dcd7aa2b0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 23 Apr 2026 17:54:58 -0500 Subject: blacklisted users appear offline --- .../API/Controllers/ConversationsController.cs | 10 +++++++++ src/slskd/Users/API/Controllers/UsersController.cs | 25 ++++++++++++++++++++++ 2 files changed, 35 insertions(+) (limited to 'src') diff --git a/src/slskd/Messaging/API/Controllers/ConversationsController.cs b/src/slskd/Messaging/API/Controllers/ConversationsController.cs index c60d0c2f..7ed0a92c 100644 --- a/src/slskd/Messaging/API/Controllers/ConversationsController.cs +++ b/src/slskd/Messaging/API/Controllers/ConversationsController.cs @@ -40,6 +40,7 @@ namespace slskd.Messaging.API using Asp.Versioning; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; + using slskd.Users; /// /// Conversations. @@ -56,19 +57,23 @@ namespace slskd.Messaging.API /// /// /// + /// /// public ConversationsController( IStateMonitor applicationStateMonitor, IMessagingService messagingService, + IUserService userService, IOptionsSnapshot optionsSnapshot) { ApplicationStateMonitor = applicationStateMonitor; Messages = messagingService; + Users = userService; OptionsSnapshot = optionsSnapshot; } private IStateMonitor ApplicationStateMonitor { get; } private IMessagingService Messages { get; } + private IUserService Users { get; } private IOptionsSnapshot OptionsSnapshot { get; } /// @@ -264,6 +269,11 @@ namespace slskd.Messaging.API return Forbid(); } + if (Users.IsBlacklisted(username)) + { + return StatusCode(200); + } + if (string.IsNullOrEmpty(message)) { return BadRequest(); diff --git a/src/slskd/Users/API/Controllers/UsersController.cs b/src/slskd/Users/API/Controllers/UsersController.cs index 2a6f535f..8029b5e0 100644 --- a/src/slskd/Users/API/Controllers/UsersController.cs +++ b/src/slskd/Users/API/Controllers/UsersController.cs @@ -93,6 +93,11 @@ namespace slskd.Users.API return Forbid(); } + if (Users.IsBlacklisted(username)) + { + return NotFound(); + } + try { var endpoint = await Users.GetIPEndPointAsync(username); @@ -120,6 +125,11 @@ namespace slskd.Users.API return Forbid(); } + if (Users.IsBlacklisted(username)) + { + return NotFound(); + } + try { var result = await Client.BrowseAsync(username); @@ -184,6 +194,11 @@ namespace slskd.Users.API return BadRequest(); } + if (Users.IsBlacklisted(username)) + { + return NotFound(); + } + try { var result = await Client.GetDirectoryContentsAsync(username, request.Directory); @@ -214,6 +229,11 @@ namespace slskd.Users.API return Forbid(); } + if (Users.IsBlacklisted(username)) + { + return NotFound(); + } + try { var response = await Users.GetInfoAsync(username); @@ -241,6 +261,11 @@ namespace slskd.Users.API return Forbid(); } + if (Users.IsBlacklisted(username)) + { + return NotFound(); + } + try { var response = await Users.GetStatusAsync(username); -- cgit v1.2.3 From 2ac28fe1e35f17d12c6e1c2b09d4b7cb90c8d591 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 23 Apr 2026 17:59:31 -0500 Subject: don't try to download from blacklisted users --- .../Transfers/API/Controllers/TransfersController.cs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) (limited to 'src') diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index 2ffd50d4..494ee722 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -44,6 +44,8 @@ namespace slskd.Transfers.API using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Serilog; + using slskd.Users; + using Soulseek; /// /// Transfers. @@ -58,17 +60,21 @@ namespace slskd.Transfers.API /// Initializes a new instance of the class. /// /// + /// /// public TransfersController( ITransferService transferService, + IUserService userService, IOptionsSnapshot optionsSnapshot) { Transfers = transferService; + Users = userService; OptionsSnapshot = optionsSnapshot; } private static SemaphoreSlim DownloadRequestLimiter { get; } = new SemaphoreSlim(2, 2); private ITransferService Transfers { get; } + private IUserService Users { get; } private IOptionsSnapshot OptionsSnapshot { get; } private ILogger Log { get; set; } = Serilog.Log.ForContext(); @@ -253,6 +259,13 @@ namespace slskd.Transfers.API try { + var endpoint = await Users.GetIPEndPointAsync(username); + + if (Users.IsBlacklisted(username, endpoint.Address)) + { + throw new UserOfflineException($"User {username} appears to be offline"); + } + var (enqueued, failed) = await Transfers.Downloads.EnqueueAsync(username, requests.Select(r => (r.Filename, r.Size))); return StatusCode(201, new { Enqueued = enqueued, Failed = failed }); @@ -382,6 +395,11 @@ namespace slskd.Transfers.API return Forbid(); } + if (Users.IsBlacklisted(username)) + { + return NotFound(); + } + if (!Guid.TryParse(id, out var guid)) { return BadRequest(); -- cgit v1.2.3 From 1b420744ef3942785de2a1bc72a0ff2e8734b5d2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 23 Apr 2026 18:02:04 -0500 Subject: don't send place in queue to blacklisted users --- src/slskd/Application.cs | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 6112198c..814e01a3 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -1381,6 +1381,12 @@ namespace slskd private Task PlaceInQueueResolver(string username, IPEndPoint endpoint, string filename) { + if (Users.IsBlacklisted(username, endpoint.Address)) + { + Log.Information("Returned empty directory listing for blacklisted user {Username} ({IP})", username, endpoint.Address); + return Task.FromResult(null); + } + try { var place = Transfers.Uploads.Queue.EstimatePosition(username, filename); -- cgit v1.2.3 From 3d9bc65bf535a3c4dab440e91587495afba648e6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 23 Apr 2026 18:28:52 -0500 Subject: fix ISystemClock --- src/slskd/Users/UserService.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index 4354a0eb..3ce827c8 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -93,14 +93,14 @@ namespace slskd.Users public UserService( ISoulseekClient soulseekClient, IOptionsMonitor optionsMonitor, - ISystemClock systemClock) + ISystemClock systemClock = null) { Client = soulseekClient; OptionsMonitor = optionsMonitor; OptionsMonitor.OnChange(options => Configure(options)); - InjectedClock = systemClock; + InjectedClock = systemClock ?? new SystemClock(); BlacklistDecisionCache = new MemoryCache(new MemoryCacheOptions { Clock = InjectedClock, ExpirationScanFrequency = TimeSpan.FromMinutes(1), SizeLimit = 1000 }); // updates may be sent unsolicited from the server, so update when we get them. binding these events will cause -- cgit v1.2.3 From f58c6a33b6d0d3b9db1b73f2529696e2e1f3dcbf Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 24 Apr 2026 17:08:28 -0500 Subject: update headers --- .../API/DTO/EnqueueDownloadBatchRequest.cs | 45 ++++++++++++++-------- .../Transfers/Types/RetryIncompleteStrategy.cs | 45 ++++++++++++++-------- 2 files changed, 60 insertions(+), 30 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs index 810b1529..ce3331ca 100644 --- a/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs +++ b/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs @@ -1,18 +1,33 @@ -// -// 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 (c) JP Dillingham. +// │ +// │ 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, version 3. +// │ +// │ 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/. +// │ +// │ This program is distributed with Additional Terms pursuant to Section 7 +// │ of the AGPLv3. See the LICENSE file in the root directory of this +// │ project for the complete terms and conditions. +// │ +// │ https://slskd.org +// │ +// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌ +// │ SPDX-FileCopyrightText: JP Dillingham +// │ SPDX-License-Identifier: AGPL-3.0-only +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ // using System; diff --git a/src/slskd/Transfers/Types/RetryIncompleteStrategy.cs b/src/slskd/Transfers/Types/RetryIncompleteStrategy.cs index 2655ed96..9ac8d8e2 100644 --- a/src/slskd/Transfers/Types/RetryIncompleteStrategy.cs +++ b/src/slskd/Transfers/Types/RetryIncompleteStrategy.cs @@ -1,18 +1,33 @@ -// -// 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 (c) JP Dillingham. +// │ +// │ 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, version 3. +// │ +// │ 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/. +// │ +// │ This program is distributed with Additional Terms pursuant to Section 7 +// │ of the AGPLv3. See the LICENSE file in the root directory of this +// │ project for the complete terms and conditions. +// │ +// │ https://slskd.org +// │ +// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌ +// │ SPDX-FileCopyrightText: JP Dillingham +// │ SPDX-License-Identifier: AGPL-3.0-only +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ // namespace slskd.Transfers; -- cgit v1.2.3 From 3c1ef0528460f335631ef2719ffd0a8c0a2dcfec Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 24 Apr 2026 17:24:12 -0500 Subject: raise minimum max delay to 30 seconds --- src/slskd/Core/Options.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index cc6a8316..8cc369af 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1038,7 +1038,7 @@ namespace slskd /// /// Gets the maximum time to wait between retry attempts, in milliseconds. /// - [Range(1000, int.MaxValue)] + [Range(30_000, int.MaxValue)] public int MaxDelay { get; init; } = 60_000; /// -- cgit v1.2.3 From 0248581eecad4a9ab6c633ad751ba0ec450660ef Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 24 Apr 2026 17:45:08 -0500 Subject: use batchid in incomplete path, if it exists --- src/slskd/Transfers/Downloads/DownloadService.cs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 831d9ba2..c24d43da 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -1028,7 +1028,12 @@ namespace slskd.Transfers.Downloads ? OptionsMonitor.CurrentValue.Permissions.File.Mode.ToUnixFileMode() : null; - var incompleteFilename = transfer.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Incomplete); + // if the transfer has an associated batch id, store the incomplete file in a directory of the same name + // this is to ensure maximal safety when resuming failed downloads (otherwise we risk resuming an unrelated file) + var incompleteFilename = transfer.Filename.ToLocalFilename( + baseDirectory: System.IO.Path.Combine( + OptionsMonitor.CurrentValue.Directories.Incomplete, + transfer.BatchId.HasValue ? transfer.BatchId.ToString() : string.Empty)); Log.Debug("Invoking Soulseek DownloadAsync() for {Filename} from {Username}", transfer.Filename, transfer.Username); transfer.Attempts = 1; -- cgit v1.2.3 From 0a3dc3abcd712c570efa54abf4af775e16b221dd Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 24 Apr 2026 18:02:49 -0500 Subject: move completed transfers to batch folder, if present --- src/slskd/Transfers/Downloads/DownloadService.cs | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index c24d43da..d4d8004a 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -1117,8 +1117,28 @@ namespace slskd.Transfers.Downloads Log.Debug("Successfully updated Transfer for {Filename} from {Username} (state: {State}, progress: {Progress})", transfer.Filename, transfer.Username, transfer.State, transfer.PercentComplete); - // move the file from incomplete to complete - var destinationDirectory = System.IO.Path.GetDirectoryName(transfer.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Downloads)); + /* + move the file from incomplete to complete + + users have a lot of strong opinions about this! + */ + string destinationDirectory; + + if (transfer.BatchId is not null) + { + // if the transfer has an associated batch id, then: + // some/long/remote/path/folder/file.ext -> download_directory/batch_id/file.ext + destinationDirectory = System.IO.Path.Combine(OptionsMonitor.CurrentValue.Directories.Downloads, transfer.BatchId.Value.ToString()); + } + else + { + // ToLocalFilename chops all but the containing folder off of the path and localizes slashes, so: + // some/long/remote/path/folder/file.ext -> folder/file.ext -> download_directory/folder/file.ext + // this is "legacy" behavior that will be familiar to most Soulseek users + destinationDirectory = System.IO.Path.GetDirectoryName(transfer.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Downloads)); + } + + Log.Debug("Destination directory for {Filename}: {Destination}", transfer.Filename, destinationDirectory); var finalFilename = Files.MoveFile( sourceFilename: transfer.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Incomplete), -- cgit v1.2.3 From 300363d8aa1c2314641d374a4a5a7facc5b6b7aa Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 25 Apr 2026 18:53:29 -0500 Subject: map ipv6-mapped ipv4 IPs back to ipv4 before checking them against configured CIDR --- src/slskd/Relay/API/Hubs/RelayHub.cs | 42 ++++++++++++++++++++++++------------ 1 file changed, 28 insertions(+), 14 deletions(-) (limited to 'src') diff --git a/src/slskd/Relay/API/Hubs/RelayHub.cs b/src/slskd/Relay/API/Hubs/RelayHub.cs index 53e2830f..8430164c 100644 --- a/src/slskd/Relay/API/Hubs/RelayHub.cs +++ b/src/slskd/Relay/API/Hubs/RelayHub.cs @@ -109,7 +109,6 @@ namespace slskd.Relay private IOptionsMonitor OptionsMonitor { get; } private OptionsAtStartup OptionsAtStartup { get; } private RelayMode OperationMode => OptionsAtStartup.Relay.Mode.ToEnum(); - private IPAddress RemoteIpAddress => Context.Features.Get().RemoteIpAddress; /// /// Executed when a new connection is established. @@ -119,13 +118,13 @@ namespace slskd.Relay { if (!OptionsAtStartup.Relay.Enabled || !new[] { RelayMode.Controller, RelayMode.Debug }.Contains(OperationMode)) { - Log.Debug("Agent connection {Id} from {IP} aborted; Relay is not enabled, or is not in Controller mode", Context.ConnectionId, RemoteIpAddress); + Log.Debug("Agent connection {Id} from {IP} aborted; Relay is not enabled, or is not in Controller mode", Context.ConnectionId, GetRemoteIPAddress()); Context.Abort(); } var token = Relay.GenerateAuthenticationChallengeToken(Context.ConnectionId); - Log.Information("Agent connection {Id} from {IP} established. Sending authentication challenge {Token}...", Context.ConnectionId, RemoteIpAddress, token); + Log.Information("Agent connection {Id} from {IP} established. Sending authentication challenge {Token}...", Context.ConnectionId, GetRemoteIPAddress(), token); await Clients.Caller.Challenge(token); } @@ -138,7 +137,7 @@ namespace slskd.Relay { if (Relay.TryDeregisterAgent(Context.ConnectionId, out var record)) { - Log.Warning("Agent {Agent} (connection {Id}) from {IP} disconnected", record.Agent.Name, Context.ConnectionId, RemoteIpAddress); + Log.Warning("Agent {Agent} (connection {Id}) from {IP} disconnected", record.Agent.Name, Context.ConnectionId, GetRemoteIPAddress()); Relay.TryDeregisterAgent(record.Agent.Name, out _); } @@ -170,23 +169,25 @@ namespace slskd.Relay return false; } + var remoteIP = GetRemoteIPAddress(); + if (!TryGetAgentConfig(agent, out var agentOptions)) { - Log.Warning("Unauthorized login attempt from unknown Agent {Agent} (connection {Id}) from {IP}", agent, Context.ConnectionId, RemoteIpAddress); + Log.Warning("Unauthorized login attempt from unknown Agent {Agent} (connection {Id}) from {IP}", agent, Context.ConnectionId, remoteIP); throw new UnauthorizedAccessException(); } if (!agentOptions.Cidr.Split(',') .Select(cidr => IPAddressRange.Parse(cidr)) - .Any(range => range.Contains(RemoteIpAddress))) + .Any(range => range.Contains(remoteIP))) { - Log.Warning("Unauthorized login attempt by Agent {Agent} (connection {Id}); remote IP address {IP} is not within the configured range {CIDR}", agent, Context.ConnectionId, RemoteIpAddress, agentOptions.Cidr); + Log.Warning("Unauthorized login attempt by Agent {Agent} (connection {Id}); remote IP address {IP} is not within the configured range {CIDR}", agent, Context.ConnectionId, remoteIP, agentOptions.Cidr); throw new UnauthorizedAccessException(); } if (!Relay.TryValidateAuthenticationCredential(Context.ConnectionId, agent, challengeResponse)) { - Log.Warning("Unauthorized login attempt by Agent {Agent} (connection {Id}) from {IP}; authentication failed", agent, Context.ConnectionId, RemoteIpAddress); + Log.Warning("Unauthorized login attempt by Agent {Agent} (connection {Id}) from {IP}; authentication failed", agent, Context.ConnectionId, remoteIP); Relay.TryDeregisterAgent(Context.ConnectionId, out var _); // just in case! throw new UnauthorizedAccessException(); } @@ -208,12 +209,12 @@ namespace slskd.Relay if (!Relay.TryGetAgentRegistration(Context.ConnectionId, out var record)) { // this can happen if the agent attempts to upload before logging in - Log.Information("Agent connection {Id} from {IP} requested a share upload token, but is not registered.", Context.ConnectionId, RemoteIpAddress); + Log.Information("Agent connection {Id} from {IP} requested a share upload token, but is not registered.", Context.ConnectionId, GetRemoteIPAddress()); throw new UnauthorizedAccessException(); } var token = Relay.GenerateShareUploadToken(record.Agent.Name); - Log.Information("Agent {Agent} (connection {Id}) from {IP} requested share upload token {Token}", record.Agent.Name, record.ConnectionId, RemoteIpAddress, token); + Log.Information("Agent {Agent} (connection {Id}) from {IP} requested share upload token {Token}", record.Agent.Name, record.ConnectionId, GetRemoteIPAddress(), token); return token; } @@ -227,11 +228,11 @@ namespace slskd.Relay { if (!Relay.TryGetAgentRegistration(Context.ConnectionId, out var record)) { - Log.Warning("Agent connection {Id} from {IP} attempted to report a failed upload, but is not registered.", Context.ConnectionId, RemoteIpAddress); + Log.Warning("Agent connection {Id} from {IP} attempted to report a failed upload, but is not registered.", Context.ConnectionId, GetRemoteIPAddress()); throw new UnauthorizedAccessException(); } - Log.Warning("Agent {Agent} (connection {ConnectionId}) from {IP} reported upload failure for {Id}: {Message}", record.Agent, Context.ConnectionId, RemoteIpAddress, id, exception.Message); + Log.Warning("Agent {Agent} (connection {ConnectionId}) from {IP} reported upload failure for {Id}: {Message}", record.Agent, Context.ConnectionId, GetRemoteIPAddress(), id, exception.Message); Relay.NotifyFileStreamException(record.Agent.Name, id, exception); } @@ -247,13 +248,26 @@ namespace slskd.Relay { if (!Relay.TryGetAgentRegistration(Context.ConnectionId, out var record)) { - Log.Warning("Agent connection {Id} from {IP} attempted to return file information, but is not registered.", Context.ConnectionId, RemoteIpAddress); + Log.Warning("Agent connection {Id} from {IP} attempted to return file information, but is not registered.", Context.ConnectionId, GetRemoteIPAddress()); throw new UnauthorizedAccessException(); } - Log.Information("Agent {Agent} (connection {ConnectionId}) from {IP} returned file info for {Id}; exists: {Exists}, length: {Length}", record.Agent.Name, Context.ConnectionId, RemoteIpAddress, id, exists, length); + Log.Information("Agent {Agent} (connection {ConnectionId}) from {IP} returned file info for {Id}; exists: {Exists}, length: {Length}", record.Agent.Name, Context.ConnectionId, GetRemoteIPAddress(), id, exists, length); Relay.HandleFileInfoResponse(record.Agent.Name, id, (exists, length)); } + + private IPAddress GetRemoteIPAddress() + { + var ip = Context.Features.Get().RemoteIpAddress; + + // looks like '::ffff:127.0.0.1'; not compatible with CIDR.Contains(), so convert it back to IPv4 + if (ip.IsIPv4MappedToIPv6) + { + ip = ip.MapToIPv4(); + } + + return ip; + } } } \ No newline at end of file -- cgit v1.2.3 From 38c821d0eb5f22c30ca9be8f24e452f5ce0b83ca Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 25 Apr 2026 18:53:51 -0500 Subject: don't log share upload success on failure --- src/slskd/Relay/RelayClient.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs index 6fb2f360..de6edcf7 100644 --- a/src/slskd/Relay/RelayClient.cs +++ b/src/slskd/Relay/RelayClient.cs @@ -532,6 +532,8 @@ namespace slskd.Relay Log.Information("Uploading shares..."); await UploadSharesAsync(); + + Log.Information("Shares uploaded. Ready to relay files."); } catch (Exception ex) { @@ -542,8 +544,6 @@ namespace slskd.Relay await StopAsync(); _ = StartAsync(); } - - Log.Information("Shares uploaded. Ready to relay files."); } private Task HubConnection_Reconnecting(Exception arg) -- cgit v1.2.3 From 3b9d14bf6f128d771149f6589f345967aea5dc4d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 25 Apr 2026 18:54:10 -0500 Subject: don't try to catch typed exceptions from hub invocations --- src/slskd/Relay/RelayClient.cs | 5 ----- 1 file changed, 5 deletions(-) (limited to 'src') diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs index de6edcf7..9aec7b00 100644 --- a/src/slskd/Relay/RelayClient.cs +++ b/src/slskd/Relay/RelayClient.cs @@ -362,11 +362,6 @@ namespace slskd.Relay LoggedInTaskCompletionSource.TrySetResult(); } - catch (UnauthorizedAccessException) - { - await HubConnection.StopAsync(); - Log.Error("Relay controller authentication failed. Check configuration."); - } catch (Exception ex) { Log.Error(ex, "Failed to handle authentication challenge: {Message}", ex.Message); -- cgit v1.2.3 From acbfa366baa274c04499e835f469168477e387af Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 27 Apr 2026 03:42:48 +0000 Subject: Bump follow-redirects from 1.15.11 to 1.16.0 in /src/web Bumps [follow-redirects](https://github.com/follow-redirects/follow-redirects) from 1.15.11 to 1.16.0. - [Release notes](https://github.com/follow-redirects/follow-redirects/releases) - [Commits](https://github.com/follow-redirects/follow-redirects/compare/v1.15.11...v1.16.0) --- updated-dependencies: - dependency-name: follow-redirects dependency-version: 1.16.0 dependency-type: indirect ... Signed-off-by: dependabot[bot] --- src/web/package-lock.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/web/package-lock.json b/src/web/package-lock.json index f309d9af..22d9c714 100644 --- a/src/web/package-lock.json +++ b/src/web/package-lock.json @@ -10906,9 +10906,9 @@ "license": "ISC" }, "node_modules/follow-redirects": { - "version": "1.15.11", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.11.tgz", - "integrity": "sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ==", + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.0.tgz", + "integrity": "sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==", "funding": [ { "type": "individual", -- cgit v1.2.3