aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2025-10-10 18:47:00 -0500
committerGitHub <noreply@github.com>2025-10-10 18:47:00 -0500
commitbaafe5f4b4454b985ee33d5ff2e9df6213667bc4 (patch)
treeb7574508f134f6580feddf795810af4d72274698 /src
parentde5103fb7db29a9fff95604de883fd4886e47c88 (diff)
parent515b0910ab63100c7421c30211ff1c932c70c6f5 (diff)
downloadslskd-baafe5f4b4454b985ee33d5ff2e9df6213667bc4.tar.gz
Merge pull request #1472 from slskd/prime-transfers
Implement a number of improvements and bug fixes with download logic
Diffstat (limited to 'src')
-rw-r--r--src/slskd/Application.cs19
-rw-r--r--src/slskd/Transfers/Downloads/DownloadService.cs566
-rw-r--r--src/slskd/slskd.csproj2
3 files changed, 322 insertions, 265 deletions
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs
index 48b8fb22..7754c4ef 100644
--- a/src/slskd/Application.cs
+++ b/src/slskd/Application.cs
@@ -374,14 +374,16 @@ namespace slskd
var connectionOptions = new ConnectionOptions(
readBufferSize: OptionsAtStartup.Soulseek.Connection.Buffer.Read,
writeBufferSize: OptionsAtStartup.Soulseek.Connection.Buffer.Write,
- writeQueueSize: OptionsAtStartup.Soulseek.Connection.Buffer.WriteQueue,
+ writeQueueSize: int.MaxValue, // no write queue for peer, server or transfer connections
connectTimeout: OptionsAtStartup.Soulseek.Connection.Timeout.Connect,
inactivityTimeout: OptionsAtStartup.Soulseek.Connection.Timeout.Inactivity,
proxyOptions: proxyOptions);
// os-specific keepalive is configured for long-lived connections for the server and distributed parent/children
- var serverOptions = connectionOptions.With(configureSocketAction: socket => ConfigureSocketKeepAlive(socket, OptionsAtStartup.Soulseek.Connection));
- var distributedOptions = connectionOptions.With(configureSocketAction: socket => ConfigureSocketKeepAlive(socket, OptionsAtStartup.Soulseek.Connection));
+ var serverOptions = connectionOptions.With(configureSocketAction: socket => ConfigureSocketOptions(socket, OptionsAtStartup.Soulseek.Connection));
+ var distributedOptions = connectionOptions.With(
+ writeBufferSize: OptionsAtStartup.Soulseek.Connection.Buffer.WriteQueue, // write queue set to keep distributed children from impacting performance
+ configureSocketAction: socket => ConfigureSocketOptions(socket, OptionsAtStartup.Soulseek.Connection));
var transferOptions = connectionOptions.With(
readBufferSize: OptionsAtStartup.Soulseek.Connection.Buffer.Transfer,
@@ -495,7 +497,7 @@ namespace slskd
return Task.CompletedTask;
}
- private void ConfigureSocketKeepAlive(Socket socket, Options.SoulseekOptions.ConnectionOptions options)
+ private void ConfigureSocketOptions(Socket socket, Options.SoulseekOptions.ConnectionOptions options)
{
/*
os-specific keepalive is configured for long-lived connections for the server and distributed parent/children
@@ -507,6 +509,11 @@ namespace slskd
*/
try
{
+ // these are set in Soulseek.NET too, but to be super, super sure, do it again; these options can cause
+ // I/O loops to hang indefinitely and are suspected to be a cause of 'stuck' transfers
+ socket.SendTimeout = options.Timeout.Inactivity;
+ socket.ReceiveTimeout = options.Timeout.Inactivity;
+
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
if (OperatingSystem.IsWindows() && OptionsAtStartup.Flags.LegacyWindowsTcpKeepalive)
@@ -1391,8 +1398,8 @@ namespace slskd
inactivityTimeout: connection.Timeout.Inactivity,
proxyOptions: proxyPatch);
- serverPatch = connectionPatch.With(configureSocketAction: socket => ConfigureSocketKeepAlive(socket, options: connection));
- distributedPatch = connectionPatch.With(configureSocketAction: socket => ConfigureSocketKeepAlive(socket, options: connection));
+ serverPatch = connectionPatch.With(configureSocketAction: socket => ConfigureSocketOptions(socket, options: connection));
+ distributedPatch = connectionPatch.With(configureSocketAction: socket => ConfigureSocketOptions(socket, options: connection));
transferPatch = connectionPatch.With(
readBufferSize: OptionsAtStartup.Soulseek.Connection.Buffer.Transfer,
diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs
index db1a92ad..a462f3de 100644
--- a/src/slskd/Transfers/Downloads/DownloadService.cs
+++ b/src/slskd/Transfers/Downloads/DownloadService.cs
@@ -25,6 +25,7 @@ namespace slskd.Transfers.Downloads
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
+ using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
@@ -60,18 +61,7 @@ namespace slskd.Transfers.Downloads
/// <exception cref="ArgumentException">Thrown when the username is null or an empty string.</exception>
/// <exception cref="ArgumentException">Thrown when no files are requested.</exception>
/// <exception cref="AggregateException">Thrown when at least one of the requested files throws.</exception>
- Task<List<Transfer>> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, CancellationToken cancellationToken = default);
-
- /// <summary>
- /// Enqueues the specified <paramref name="filename"/> from the specified <paramref name="username"/>.
- /// </summary>
- /// <param name="username">The username of remote user.</param>
- /// <param name="filename">The remote filename to download.</param>
- /// <param name="size">The size of the file.</param>
- /// <param name="stateChanged">An optional delegate to invoke the transfer state changes.</param>
- /// <param name="cancellationToken">The token to monitor for cancellation.</param>
- /// <returns>The operation context.</returns>
- Task<Transfer> EnqueueAsync(string username, string filename, long size, Action<Transfer> stateChanged = null, CancellationToken cancellationToken = default);
+ Task<(List<Transfer> Enqueued, List<Transfer> Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, CancellationToken cancellationToken = default);
/// <summary>
/// Downloads the specified enqueued <paramref name="transfer"/> from the remote user.
@@ -279,29 +269,34 @@ namespace slskd.Transfers.Downloads
var topts = new TransferOptions(
stateChanged: (args) =>
{
- Log.Debug("Download of {Filename} from user {Username} changed state from {Previous} to {New}", transfer.Filename, transfer.Username, args.PreviousState, args.Transfer.State);
-
- // prevent Exceptions thrown during shutdown from updating the transfer record with related Exceptions;
- // instead, allow these to be left "hanging" so that they are properly cleaned up at the next startup
- if (Application.IsShuttingDown)
+ try
{
- Log.Debug("Download update of {Filename} to {Username} not persisted; app is shutting down", transfer.Filename, transfer.Username);
- return;
- }
+ Log.Debug("Download of {Filename} from user {Username} changed state from {Previous} to {New}", transfer.Filename, transfer.Username, args.PreviousState, args.Transfer.State);
- transfer = transfer.WithSoulseekTransfer(args.Transfer);
+ // prevent Exceptions thrown during shutdown from updating the transfer record with related Exceptions;
+ // instead, allow these to be left "hanging" so that they are properly cleaned up at the next startup
+ if (Application.IsShuttingDown)
+ {
+ Log.Debug("Download update of {Filename} to {Username} not persisted; app is shutting down", transfer.Filename, transfer.Username);
+ return;
+ }
- // we don't know when the download is actually enqueued (remotely) until it switches into that state
- // when it is enqueued locally is irrelevant, due to internal throttling etc
- if (args.Transfer.State.HasFlag(TransferStates.Queued) && args.Transfer.State.HasFlag(TransferStates.Remotely))
- {
- transfer.EnqueuedAt ??= DateTime.UtcNow;
- }
+ transfer = transfer.WithSoulseekTransfer(args.Transfer);
- // todo: broadcast
- SynchronizedUpdate(transfer);
+ // we don't know when the download is actually enqueued (remotely) until it switches into that state
+ // when it is enqueued locally is irrelevant, due to internal throttling etc
+ if (args.Transfer.State.HasFlag(TransferStates.Queued) && args.Transfer.State.HasFlag(TransferStates.Remotely))
+ {
+ transfer.EnqueuedAt ??= DateTime.UtcNow;
+ }
- stateChanged?.Invoke(transfer);
+ // todo: broadcast
+ SynchronizedUpdate(transfer);
+ }
+ finally
+ {
+ stateChanged?.Invoke(transfer);
+ }
},
progressUpdated: (args) => rateLimiter.Invoke(() =>
{
@@ -474,300 +469,355 @@ namespace slskd.Transfers.Downloads
}
/// <summary>
- /// Enqueues the specified <paramref name="filename"/> from the specified <paramref name="username"/>.
+ /// Enqueues the requested list of <paramref name="files"/>.
/// </summary>
- /// <param name="username">The username of remote user.</param>
- /// <param name="filename">The remote filename to download.</param>
- /// <param name="size">The size of the file.</param>
- /// <param name="stateChanged">An optional delegate to invoke the transfer state changes.</param>
+ /// <param name="username">The username of the remote user.</param>
+ /// <param name="files">The list of files to enqueue.</param>
/// <param name="cancellationToken">The token to monitor for cancellation.</param>
/// <returns>The operation context.</returns>
- public Task<Transfer> EnqueueAsync(string username, string filename, long size, Action<Transfer> stateChanged = null, CancellationToken cancellationToken = default)
+ /// <exception cref="ArgumentException">Thrown when the username is null or an empty string.</exception>
+ /// <exception cref="ArgumentException">Thrown when no files are requested.</exception>
+ /// <exception cref="AggregateException">Thrown when at least one of the requested files throws.</exception>
+ public async Task<(List<Transfer> Enqueued, List<Transfer> Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, CancellationToken cancellationToken = default)
{
if (string.IsNullOrEmpty(username))
{
- throw new ArgumentNullException(nameof(username), "Username is required");
+ throw new ArgumentException("Username is required", nameof(username));
}
- if (string.IsNullOrEmpty(filename))
+ if (!files.Any())
{
- throw new ArgumentNullException(nameof(filename), "Filename is required");
+ throw new ArgumentException("At least one file is required", nameof(files));
}
- if (size <= 0)
+ IPEndPoint endpoint;
+
+ try
{
- throw new ArgumentOutOfRangeException(nameof(size), "Size must be greater than zero");
+ // get the user's ip and port. this will throw if they are offline.
+ endpoint = await Client.GetUserEndPointAsync(username, cancellationToken);
}
-
- var lockName = $"{nameof(EnqueueAsync)}:{username}:{filename}";
-
- if (!Locks.TryAdd(lockName, true))
+ catch (Exception ex)
{
- Log.Debug("Ignoring concurrent download enqueue attempt; lock {LockName} already held", lockName);
- return null;
+ Log.Error(ex, "Failed to enqueue {Count} files from {Username}: {Message}", files.Count(), username, ex.Message);
+ throw;
}
- Guid id = Guid.NewGuid();
+ List<string> acquiredLocks = [];
try
{
- Log.Debug("Acquired lock {LockName}", lockName);
-
- Log.Information("Download of {Filename} from {Username} requested", filename, username);
-
- using var context = ContextFactory.CreateDbContext();
+ List<Transfer> enqueued = [];
+ List<Transfer> failed = [];
/*
- first, get all past downloads from this user for this filename
- */
- var existingRecords = context.Transfers
- .Where(t => t.Direction == TransferDirection.Download)
- .Where(t => t.Username == username)
- .Where(t => t.Filename == filename)
- .AsNoTracking()
- .ToList();
+ first, check inputs and do an _exhaustive_ check for all of the files provided, separating files out
+ into good/bad
- var existingInProgressRecords = existingRecords
- .Where(t => t.EndedAt == null || !t.State.HasFlag(TransferStates.Completed))
- .ToList();
-
- /*
- if there are any that haven't ended yet (checking a few ways out of paranoia), then there's already
- an existing transfer record covering this file, and we're already enqueued. nothing more to do!
- */
- if (existingInProgressRecords.Count != 0)
- {
- Log.Information("Download of {Filename} from {Username} is already queued or is in progress (ids: {Ids})", filename, username, string.Join(", ", existingInProgressRecords.Select(t => t.Id)));
- return null;
- }
-
- /*
- check the tracked download dictionary in Soulseek.NET to see if it knows about this already
- it shouldn't, if the slskd database doesn't. but things could get desynced
- */
- if (Client.Downloads.Any(u => u.Username == username && u.Filename == filename))
- {
- throw new DuplicateTransferException("A duplicate download of the same file from the same user is already registered");
- }
-
- /*
- we're cleared to enqueue! create a new transfer record, and automatically mark any existing records
- we found as 'removed' to clean up the UI
- */
- var transfer = new Transfer()
- {
- Id = id,
- Username = username,
- Direction = TransferDirection.Download,
- Filename = filename, // important! use the remote filename
- Size = size,
- StartOffset = 0, // todo: maybe implement resumeable downloads?
- RequestedAt = DateTime.UtcNow,
- State = TransferStates.Queued | TransferStates.Locally,
- };
-
- context.Add(transfer);
-
- foreach (var record in existingRecords.Where(t => !t.Removed))
- {
- record.Removed = true;
- context.Update(record);
- Log.Debug("Marked existing download record of {Filename} from {Username} removed (id: {Id})", filename, username, record.Id);
- }
-
- context.SaveChanges();
-
- Log.Information("Successfully enqueued download of {Filename} from {Username} (id: {Id})", filename, username, id);
-
- /*
- schedule the download immediately
-
- Task.Run can fail due to thread pool exhaustion or OOM, and this *SHOULD* throw up the chain and
- fail the enqueue request
+ acquire locks for each, and track them so we can release them later (in the finally block)
*/
- _ = Task.Run(() => DownloadAsync(transfer, stateChanged, cancellationToken)).ContinueWith(task =>
+ foreach (var file in files)
{
- if (task.IsCompletedSuccessfully)
+ var transfer = new Transfer()
{
- Log.Information("Task for download of {Filename} from {Username} completed successfully", filename, username);
- return;
+ Id = Guid.NewGuid(),
+ Username = username,
+ Direction = TransferDirection.Download,
+ Filename = file.Filename, // important! use the remote filename
+ Size = file.Size,
+ StartOffset = 0, // todo: maybe implement resumeable downloads?
+ RequestedAt = DateTime.UtcNow,
+ State = TransferStates.Queued | TransferStates.Locally,
+ };
+
+ var lockName = $"{nameof(EnqueueAsync)}:{username}:{file.Filename}";
+
+ if (!Locks.TryAdd(lockName, true))
+ {
+ Log.Debug("Ignoring concurrent download enqueue attempt; lock {LockName} already held", lockName);
+ transfer.Exception = "A download for this file from this user is already underway";
+ transfer.State = TransferStates.Aborted | TransferStates.Completed;
+ failed.Add(transfer);
+ continue;
}
- /*
- things that can cause us to arrive here:
-
- * transfer record deleted somehow
- * transfer record updated so that it's no longer in Queued | Locally
- * Soulseek.NET already tracking an identical download (slskd <> Soulseek.NET desync)
- */
- Log.Error(task.Exception, "Task for download of {Filename} from {Username} did not complete successfully: {Error}", filename, username, task.Exception.Message);
-
try
{
- var transfer = Find(t => t.Id == id);
-
- if (transfer is not null)
+ acquiredLocks.Add(lockName);
+ Log.Debug("Acquired lock {LockName}", lockName);
+
+ Log.Information("Download of {Filename} from {Username} requested", file.Filename, username);
+
+ using var context = ContextFactory.CreateDbContext();
+
+ /*
+ first, get all past downloads from this user for this filename
+ */
+ var existingRecords = context.Transfers
+ .Where(t => t.Direction == TransferDirection.Download)
+ .Where(t => t.Username == username)
+ .Where(t => t.Filename == file.Filename)
+ .AsNoTracking()
+ .ToList();
+
+ var existingInProgressRecords = existingRecords
+ .Where(t => t.EndedAt == null || !t.State.HasFlag(TransferStates.Completed))
+ .ToList();
+
+ /*
+ if there are any that haven't ended yet (checking a few ways out of paranoia), then there's already
+ an existing transfer record covering this file, and we're already enqueued. nothing more to do!
+
+ check the tracked download dictionary in Soulseek.NET to see if it knows about this already
+ it shouldn't, if the slskd database doesn't. but things could get desynced
+ */
+ if (existingInProgressRecords.Count != 0 || Client.Downloads.Any(u => u.Username == username && u.Filename == file.Filename))
{
- transfer.EndedAt ??= DateTime.UtcNow;
- transfer.Exception ??= task.Exception.Message;
- transfer.State = TransferStates.Completed | transfer.State;
+ Log.Debug("Ignoring concurrent download enqueue attempt; lock {LockName} already held", lockName);
+ transfer.Exception = "A download for this file from this user is already underway";
+ transfer.State = TransferStates.Aborted | TransferStates.Completed;
+ failed.Add(transfer);
+ continue;
+ }
+
+ /*
+ we've passed 3 different checks to ensure that this file is not already being downloaded, so
+ add it to the database and remove any existing (past) records of it from the UI
+ */
+ context.Add(transfer);
- Update(transfer);
+ foreach (var record in existingRecords.Where(t => !t.Removed))
+ {
+ record.Removed = true;
+ context.Update(record);
+ Log.Debug("Marked existing download record of {Filename} from {Username} removed (id: {Id})", file.Filename, username, record.Id);
}
+
+ context.SaveChanges();
+ enqueued.Add(transfer);
+
+ Log.Information("Successfully enqueued download of {Filename} from {Username} (id: {Id})", file.Filename, username, transfer.Id);
}
catch (Exception ex)
{
- Log.Error(ex, "Failed to clean up transfer {Id} after failed execution: {Message}", id, ex.Message);
- throw;
+ // note: there's nothing to cancel or download yet, so any failure to execute the above is an error
+ Log.Error(ex, "Failed to enqueue download of {Filename} from {Username}: {Message}", file.Filename, username, ex.Message);
+ transfer.Exception = ex.Message;
+ transfer.State = TransferStates.Errored | TransferStates.Completed;
+ failed.Add(transfer);
+ continue;
}
- }, cancellationToken);
+ }
- return Task.FromResult(transfer);
- }
- catch (Exception ex)
- {
- Log.Error(ex, "Failed to enqueue download of {Filename} from {Username}: {Message}", filename, username, ex.Message);
+ if (enqueued.Count == 0)
+ {
+ return (enqueued, failed);
+ }
+ // prime the cache for this user, to 1) make sure we can connect, and 2) avoid needing to race for it in the loop
try
{
- var transfer = Find(t => t.Id == id);
-
- if (transfer is not null)
- {
- transfer.EndedAt ??= DateTime.UtcNow;
- transfer.Exception ??= ex.Message;
- transfer.State = TransferStates.Completed | transfer.State;
-
- Update(transfer);
- }
+ await Client.ConnectToUserAsync(username, invalidateCache: false, cancellationToken);
}
- catch (Exception innerEx)
+ catch (Exception ex)
{
- Log.Error(innerEx, "Failed to clean up transfer {Id} after failed enqueue: {Message}", id, innerEx.Message);
+ Log.Error(ex, "Failed to connect to {Username}: {Message}", username, ex.Message);
throw;
}
- throw;
- }
- finally
- {
- if (Locks.TryRemove(lockName, out _))
+ /*
+ the files are all now in the database in the Queued | Locally state.
+
+ we'll proceed with downloading them, but in a separate task run in the background
+ */
+ _ = Task.Run(async () =>
{
- Log.Debug("Released lock {LockName}", lockName);
- }
- }
- }
+ /*
+ enqueue each of the specified files, waiting to ensure that the remote client has responded to our
+ request to enqueue before moving on to the next
- /// <summary>
- /// Enqueues the requested list of <paramref name="files"/>.
- /// </summary>
- /// <remarks>
- /// If one file in the specified collection fails, the rest will continue. An <see cref="AggregateException"/> will be
- /// thrown after all files are dispositioned if any throws.
- /// </remarks>
- /// <param name="username">The username of the remote user.</param>
- /// <param name="files">The list of files to enqueue.</param>
- /// <param name="cancellationToken">The token to monitor for cancellation.</param>
- /// <returns>The operation context.</returns>
- /// <exception cref="ArgumentException">Thrown when the username is null or an empty string.</exception>
- /// <exception cref="ArgumentException">Thrown when no files are requested.</exception>
- /// <exception cref="AggregateException">Thrown when at least one of the requested files throws.</exception>
- public async Task<List<Transfer>> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, CancellationToken cancellationToken = default)
- {
- if (string.IsNullOrEmpty(username))
- {
- throw new ArgumentException("Username is required", nameof(username));
- }
+ we do this because Soulseek.NET sends a TransferRequest/40 which expects a TransferResponse/41 in return,
+ telling us that either 1) the transfer can begin immediately 2) the transfer was enqueued remotely
+ or 3) the transfer was rejected
- if (!files.Any())
- {
- throw new ArgumentException("At least one file is required", nameof(files));
- }
+ if at a later date Soulseek.NET is refactored to use different logic, we'll want to rethink this, particularly
+ to avoid the need to wait for a confirmation from the remote client.
- List<Transfer> transfers = [];
- List<Exception> exceptions = [];
+ note: we can't just fire off all of these requests at the same time, because the remote client will get
+ overwhelmed, responses will be delayed, and the timeout within Soulseek.NET that's waiting for the
+ TransferResponse/41 message will expire and fail the download
+ */
+ var concurrentRequests = 10;
+ var maxTimeToWaitForTransferAck = TimeSpan.FromMinutes(1);
- /*
- enqueue each of the specified files, waiting to ensure that the remote client has responded to our
- request to enqueue before moving on to the next
+ var semaphore = new SemaphoreSlim(initialCount: concurrentRequests, maxCount: concurrentRequests);
+
+ var tasks = enqueued.Select(async transfer =>
+ {
+ await semaphore.WaitAsync();
- we do this because Soulseek.NET sends a TransferRequest/40 which expects a TransferResponse/41 in return,
- telling us that either 1) the transfer can begin immediately 2) the transfer was enqueued remotely
- or 3) the transfer was rejected
+ try
+ {
+ Log.Debug("Acquired download semaphore for {Filename} from {Username}", transfer.Filename, transfer.Username);
- if at a later date Soulseek.NET is refactored to use different logic, we'll want to rethink this, particularly
- to avoid the need to wait for a confirmation from the remote client.
+ try
+ {
+ var enqueuedTcs = new TaskCompletionSource<Transfer>();
+ List<string> transitions = [];
- note: we can't just fire off all of these requests at the same time, because the remote client will get
- overwhelmed, responses will be delayed, and the timeout within Soulseek.NET that's waiting for the
- TransferResponse/41 message will expire and fail the download
- */
- foreach (var file in files)
- {
- if (cancellationToken.IsCancellationRequested)
- {
- break;
- }
+ // set a hard limit on the time we are willing to wait for the remote client to confirm or reject
+ // the enqueue of the file. we have to do this so that we don't get stuck indefinitely
+ using var timeoutCts = new CancellationTokenSource(maxTimeToWaitForTransferAck);
+ timeoutCts.Token.Register(() =>
+ {
+ if (!enqueuedTcs.Task.IsCompleted)
+ {
+ Log.Warning("Download of {Filename} from {Username} failed to enqueue remotely after hard time limit. State transition history: {History}", transfer.Filename, username, string.Join(", ", transitions));
+ enqueuedTcs.TrySetException(new TimeoutException("Download failed to enqueue remotely after hard time limit"));
+ }
+ });
+
+ void stateChanged(Transfer transfer)
+ {
+ transitions.Add(transfer.State.ToString());
+
+ // _contractually_ (covered by unit tests!) all downloads will at some point enter the Queued | Remotely state
+ // there _should be_ no way we can get hung up here, but if we do, also check for Completed as a backstop
+ if (transfer.State.HasFlag(TransferStates.Queued) && transfer.State.HasFlag(TransferStates.Remotely))
+ {
+ enqueuedTcs.TrySetResult(transfer);
+ }
+
+ // if something goes wrong and we never get to enqueued, trip the result when we transition into
+ // completed, so we don't get stuck. we shouldn't take this to mean we were successful, we're just
+ // trying to ensure we don't get stuck
+ if (transfer.State.HasFlag(TransferStates.Completed))
+ {
+ if (transfer.State.HasFlag(TransferStates.Succeeded))
+ {
+ enqueuedTcs.TrySetResult(transfer);
+ }
+ else
+ {
+ enqueuedTcs.TrySetException(new TransferException(transfer.Exception));
+ }
+ }
+ }
- try
- {
- var enqueuedTcs = new TaskCompletionSource<Transfer>();
- List<string> transitions = [];
+ // enqueue the file. this call will return when the record has been inserted and the download task
+ // kicked off. the stateChanged delegate will be passed down to the download task, which will eventually trip it
+ _ = Task.Run(() => DownloadAsync(transfer, stateChanged, cancellationToken)).ContinueWith(task =>
+ {
+ if (task.IsCompletedSuccessfully)
+ {
+ Log.Information("Task for download of {Filename} from {Username} completed successfully", transfer.Filename, transfer.Username);
+ return;
+ }
+
+ /*
+ things that can cause us to arrive here:
+
+ * transfer record deleted somehow
+ * transfer record updated so that it's no longer in Queued | Locally
+ * Soulseek.NET already tracking an identical download (slskd <> Soulseek.NET desync)
+ */
+ Log.Error(task.Exception, "Task for download of {Filename} from {Username} did not complete successfully: {Error}", transfer.Filename, transfer.Username, task.Exception.Message);
+
+ try
+ {
+ var foundTransfer = Find(t => t.Id == transfer.Id);
+
+ if (transfer is not null)
+ {
+ transfer.EndedAt ??= DateTime.UtcNow;
+ transfer.Exception ??= task.Exception.InnerException.Message;
+
+ if (!transfer.State.HasFlag(TransferStates.Completed))
+ {
+ transfer.State = TransferStates.Completed | task.Exception.InnerException switch
+ {
+ OperationCanceledException => TransferStates.Cancelled,
+ TimeoutException => TransferStates.TimedOut,
+ _ => TransferStates.Errored,
+ };
+ }
+
+ Update(transfer);
+ }
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Failed to clean up transfer {Id} after failed execution: {Message}", transfer.Id, ex.Message);
+ }
+ }, cancellationToken);
+
+ // wait for the download to either enter the Queued | Remotely or Completed states, or for the hard limit
+ // timeout to trip and set an exception
+ await enqueuedTcs.Task;
+ }
+ catch (Exception ex)
+ {
+ Log.Error(ex, "Failed to download {Filename} from {Username}: {Message}", transfer.Filename, transfer.Username, ex.Message);
- // set a hard limit on the time we are willing to wait for the remote client to confirm or reject
- // the enqueue of the file. we have to do this so that we don't get stuck indefinitely
- using var timeoutCts = new CancellationTokenSource(TimeSpan.FromMinutes(1));
- timeoutCts.Token.Register(() =>
- {
- if (!enqueuedTcs.Task.IsCompleted)
+ try
+ {
+ var transferRecord = Find(t => t.Id == transfer.Id);
+
+ if (transfer is not null)
+ {
+ transfer.EndedAt ??= DateTime.UtcNow;
+ transfer.Exception ??= ex.Message;
+
+ if (!transfer.State.HasFlag(TransferStates.Completed))
+ {
+ transfer.State = TransferStates.Completed | ex switch
+ {
+ OperationCanceledException => TransferStates.Cancelled,
+ TimeoutException => TransferStates.TimedOut,
+ _ => TransferStates.Errored,
+ };
+ }
+
+ Update(transfer);
+ }
+ }
+ catch (Exception innerEx)
+ {
+ Log.Error(innerEx, "Failed to clean up transfer {Id} after failed enqueue: {Message}", transfer.Id, innerEx.Message);
+ }
+ }
+ }
+ finally
{
- Log.Warning("Download of {Filename} from {Username} failed to enqueue remotely after hard time limit. State transition history: {History}", file.Filename, username, string.Join(", ", transitions));
- enqueuedTcs.TrySetException(new TimeoutException("Download failed to enqueue remotely after hard time limit"));
+ semaphore.Release();
+ Log.Debug("Released download semaphore for {Filename} from {Username}", transfer.Filename, transfer.Username);
}
});
- void stateChanged(Transfer transfer)
+ await Task.WhenAll(tasks);
+ }, cancellationToken).ContinueWith(task =>
+ {
+ if (task.IsCompletedSuccessfully)
{
- transitions.Add(transfer.State.ToString());
-
- // _contractually_ (covered by unit tests!) all downloads will at some point enter the Queued | Remotely state
- // there _should be_ no way we can get hung up here, but if we do
- if (transfer.State.HasFlag(TransferStates.Queued) && transfer.State.HasFlag(TransferStates.Remotely))
- {
- enqueuedTcs.TrySetResult(transfer);
- }
-
- // if something goes wrong and we never get to enqueued, trip the result when we transition into
- // completed, so we don't get stuck. we shouldn't take this to mean we were successful, we're just
- // trying to ensure we don't get stuck
- if (transfer.State.HasFlag(TransferStates.Completed))
- {
- enqueuedTcs.TrySetResult(transfer);
- }
+ Log.Warning("Task for enqueue of {Count} files from {Username} completed successfully", files.Count(), username);
+ return;
}
- // enqueue the file. this call will return when the record has been inserted and the download task
- // kicked off. the stateChanged delegate will be passed down to the download task, which will eventually trip it
- await EnqueueAsync(username, file.Filename, file.Size, stateChanged, cancellationToken);
-
- // wait for the download to either enter the Queued | Remotely or Completed states, or for the hard limit
- // timeout to trip and set an exception
- var transfer = await enqueuedTcs.Task;
+ Log.Error(task.Exception, "Task for enqueue of {Count} files from {Username} did not complete successfully: {Error}", files.Count(), username, task.Exception.Flatten().Message);
+ }, cancellationToken: CancellationToken.None);
- transfers.Add(transfer);
- }
- catch (Exception ex)
- {
- exceptions.Add(ex);
- }
+ return (enqueued, failed);
}
-
- if (exceptions.Count != 0)
+ finally
{
- throw new AggregateException(exceptions);
+ foreach (var lockName in acquiredLocks)
+ {
+ if (Locks.TryRemove(lockName, out _))
+ {
+ Log.Debug("Released lock {LockName}", lockName);
+ }
+ }
}
-
- return transfers.ToList();
}
/// <summary>
diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj
index ae042d68..7f5c1004 100644
--- a/src/slskd/slskd.csproj
+++ b/src/slskd/slskd.csproj
@@ -68,7 +68,7 @@
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
<PackageReference Include="Serilog.Sinks.Grafana.Loki" Version="7.1.1" />
<PackageReference Include="Serilog.Sinks.Http" Version="8.0.0" />
- <PackageReference Include="Soulseek" Version="8.2.1" />
+ <PackageReference Include="Soulseek" Version="8.3.0" />
<PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.556">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>