aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2026-04-24 18:51:44 -0500
committerGitHub <noreply@github.com>2026-04-24 18:51:44 -0500
commit14f94a4825d6da485f08b9c9e967c61181e41c81 (patch)
tree9f413cb07787c018e679bd5c3a6d69b90d5be24b /src
parentfc722e4a78aa5369fcd5ca0d8e88bd98d874a1d8 (diff)
parent46966b6e284a9ef8bb3d182928bf9211118681e8 (diff)
downloadslskd-14f94a4825d6da485f08b9c9e967c61181e41c81.tar.gz
Merge pull request #1664 from slskd/retries
Add transfer retries and batches
Diffstat (limited to 'src')
-rw-r--r--src/slskd/Common/Retry.cs15
-rw-r--r--src/slskd/Core/Options.cs37
-rw-r--r--src/slskd/Program.cs10
-rw-r--r--src/slskd/Telemetry/ReportsService.cs3
-rw-r--r--src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs57
-rw-r--r--src/slskd/Transfers/Downloads/DownloadService.cs122
-rw-r--r--src/slskd/Transfers/Extensions.cs1
-rw-r--r--src/slskd/Transfers/Types/RetryIncompleteStrategy.cs49
-rw-r--r--src/web/src/components/Transfers/TransferDetails.jsx2
-rw-r--r--src/web/src/components/Transfers/TransferList.jsx4
10 files changed, 273 insertions, 27 deletions
diff --git a/src/slskd/Common/Retry.cs b/src/slskd/Common/Retry.cs
index 53aa59db..a14d2def 100644
--- a/src/slskd/Common/Retry.cs
+++ b/src/slskd/Common/Retry.cs
@@ -52,6 +52,7 @@ namespace slskd
/// <param name="maxAttempts">The maximum number of retry attempts.</param>
/// <param name="baseDelayInMilliseconds">The base delay in milliseconds.</param>
/// <param name="maxDelayInMilliseconds">The maximum delay in milliseconds.</param>
+ /// <param name="exceptionHistoryLimit">The maximum number of Exceptions to keep in history.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>The execution context.</returns>
public static async Task Do(
@@ -62,13 +63,14 @@ namespace slskd
int maxAttempts = 3,
int baseDelayInMilliseconds = 1000,
int maxDelayInMilliseconds = int.MaxValue,
+ int exceptionHistoryLimit = 5,
CancellationToken cancellationToken = default)
{
await Do<object>(async () =>
{
await task();
return Task.FromResult<object>(null);
- }, isRetryable, onRetry, onFailure, maxAttempts, baseDelayInMilliseconds, maxDelayInMilliseconds, cancellationToken);
+ }, isRetryable, onRetry, onFailure, maxAttempts, baseDelayInMilliseconds, maxDelayInMilliseconds, exceptionHistoryLimit, cancellationToken);
}
/// <summary>
@@ -81,6 +83,7 @@ namespace slskd
/// <param name="maxAttempts">The maximum number of retry attempts.</param>
/// <param name="baseDelayInMilliseconds">The base delay in milliseconds.</param>
/// <param name="maxDelayInMilliseconds">The maximum delay in milliseconds.</param>
+ /// <param name="exceptionHistoryLimit">The maximum number of Exceptions to keep in history.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <typeparam name="T">The Type of the logic return value.</typeparam>
/// <returns>The execution context.</returns>
@@ -92,11 +95,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<Exception>();
+ var exceptions = new Queue<Exception>();
for (int attempts = 0; attempts < maxAttempts; attempts++)
{
@@ -119,7 +123,12 @@ namespace slskd
}
catch (Exception ex)
{
- exceptions.Add(ex);
+ exceptions.Enqueue(ex);
+
+ if (exceptions.Count > exceptionHistoryLimit)
+ {
+ exceptions.Dequeue();
+ }
try
{
diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs
index fcc65c3b..8cc369af 100644
--- a/src/slskd/Core/Options.cs
+++ b/src/slskd/Core/Options.cs
@@ -50,6 +50,7 @@ namespace slskd
using slskd.Events;
using slskd.Relay;
using slskd.Shares;
+ using slskd.Transfers;
using slskd.Validation;
using Utility.CommandLine;
using Utility.EnvironmentVariables;
@@ -1010,6 +1011,42 @@ namespace slskd
[Description("the total download speed limit")]
[Range(1, int.MaxValue)]
public int SpeedLimit { get; init; } = int.MaxValue;
+
+ /// <summary>
+ /// Gets download retry options.
+ /// </summary>
+ [Validate]
+ public RetryOptions Retry { get; init; } = new RetryOptions();
+
+ /// <summary>
+ /// Download retry options.
+ /// </summary>
+ public class RetryOptions
+ {
+ /// <summary>
+ /// Gets the maximum number of times to retry a failed transfer.
+ /// </summary>
+ [Range(1, int.MaxValue)]
+ public int Attempts { get; init; } = 3;
+
+ /// <summary>
+ /// Gets the base time to wait between retry attempts, in milliseconds.
+ /// </summary>
+ [Range(1000, int.MaxValue)]
+ public int Delay { get; init; } = 5000;
+
+ /// <summary>
+ /// Gets the maximum time to wait between retry attempts, in milliseconds.
+ /// </summary>
+ [Range(30_000, int.MaxValue)]
+ public int MaxDelay { get; init; } = 60_000;
+
+ /// <summary>
+ /// Gets the strategy for handling incomplete files upon retry.
+ /// </summary>
+ [Enum(typeof(RetryIncompleteStrategy))]
+ public string Incomplete { get; init; } = RetryIncompleteStrategy.Overwrite.ToString().ToLowerInvariant();
+ }
}
/// <summary>
diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs
index 25077de7..42f43918 100644
--- a/src/slskd/Program.cs
+++ b/src/slskd/Program.cs
@@ -706,11 +706,11 @@ namespace slskd
new SoulseekClient(
minorVersion: NetworkMinorVersion,
options: new SoulseekClientOptions(
- maximumConcurrentUploads: OptionsAtStartup.Transfers.Upload.Slots,
- maximumConcurrentDownloads: OptionsAtStartup.Transfers.Download.Slots,
- minimumDiagnosticLevel: OptionsAtStartup.Soulseek.DiagnosticLevel.ToEnum<Soulseek.Diagnostics.DiagnosticLevel>(),
- maximumConcurrentSearches: 2,
- raiseEventsAsynchronously: true)));
+ maximumConcurrentUploads: OptionsAtStartup.Transfers.Upload.Slots,
+ maximumConcurrentDownloads: OptionsAtStartup.Transfers.Download.Slots,
+ minimumDiagnosticLevel: OptionsAtStartup.Soulseek.DiagnosticLevel.ToEnum<Soulseek.Diagnostics.DiagnosticLevel>(),
+ maximumConcurrentSearches: 2,
+ raiseEventsAsynchronously: true)));
// add the core application service to DI as well as a hosted service so that other services can
// access instance methods
diff --git a/src/slskd/Telemetry/ReportsService.cs b/src/slskd/Telemetry/ReportsService.cs
index cab4e406..ae2d1129 100644
--- a/src/slskd/Telemetry/ReportsService.cs
+++ b/src/slskd/Telemetry/ReportsService.cs
@@ -38,6 +38,7 @@ using System.Linq;
using Dapper;
using Microsoft.Data.Sqlite;
using Serilog;
+using slskd.Transfers;
using Soulseek;
/// <summary>
@@ -99,6 +100,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
@@ -186,6 +188,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
diff --git a/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs
new file mode 100644
index 00000000..ce3331ca
--- /dev/null
+++ b/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs
@@ -0,0 +1,57 @@
+// <copyright file="EnqueueDownloadBatchRequest.cs" company="JP Dillingham">
+// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
+// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
+// █__ --█ █__ --█ ◄█ - █
+// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
+// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉
+// │ 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
+// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
+// </copyright>
+
+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<EnqueueDownloadBatchItem> 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
diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs
index c8e10fe6..d4d8004a 100644
--- a/src/slskd/Transfers/Downloads/DownloadService.cs
+++ b/src/slskd/Transfers/Downloads/DownloadService.cs
@@ -937,6 +937,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
@@ -967,6 +968,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);
}
@@ -1017,26 +1028,79 @@ namespace slskd.Transfers.Downloads
? OptionsMonitor.CurrentValue.Permissions.File.Mode.ToUnixFileMode()
: null;
+ // 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;
+ SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: CancellationToken.None);
+
+ var completedTransfer = await Retry.Do(() =>
+ {
+ var incompleteFileInfo = Files.ResolveFileInfo(incompleteFilename);
+ var incompleteStrategy = retryOptions.Incomplete.ToEnum<RetryIncompleteStrategy>();
+
+ var shouldResume = false;
+ var startOffset = 0L;
- 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
+ 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
{
- 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);
+ 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
+ && 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) =>
+ {
+ 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);
@@ -1053,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),
diff --git a/src/slskd/Transfers/Extensions.cs b/src/slskd/Transfers/Extensions.cs
index 1c5ff4b5..48179ff2 100644
--- a/src/slskd/Transfers/Extensions.cs
+++ b/src/slskd/Transfers/Extensions.cs
@@ -53,6 +53,7 @@ namespace slskd.Transfers
BytesTransferred = t.BytesTransferred,
AverageSpeed = t.AverageSpeed,
Exception = t.Exception?.Message,
+ Attempts = transfer.Attempts,
};
}
}
diff --git a/src/slskd/Transfers/Types/RetryIncompleteStrategy.cs b/src/slskd/Transfers/Types/RetryIncompleteStrategy.cs
new file mode 100644
index 00000000..9ac8d8e2
--- /dev/null
+++ b/src/slskd/Transfers/Types/RetryIncompleteStrategy.cs
@@ -0,0 +1,49 @@
+// <copyright file="RetryIncompleteStrategy.cs" company="JP Dillingham">
+// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
+// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
+// █__ --█ █__ --█ ◄█ - █
+// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
+// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉
+// │ 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
+// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈
+// </copyright>
+
+namespace slskd.Transfers;
+
+/// <summary>
+/// Strategy for retrying incomplete files.
+/// </summary>
+public enum RetryIncompleteStrategy
+{
+ /// <summary>
+ /// Overwrite the existing file.
+ /// </summary>
+ Overwrite = 0,
+
+ /// <summary>
+ /// Resume the transfer using the size of the incomplete file as the initial offset.
+ /// </summary>
+ Resume = 1,
+} \ No newline at end of file
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 (
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})` : ''}
</Button>
)}
</Table.Cell>