aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/slskd/Application.cs328
-rw-r--r--src/slskd/Program.cs3
-rw-r--r--src/slskd/Transfers/Downloads/DownloadService.cs101
-rw-r--r--src/slskd/slskd.csproj2
4 files changed, 260 insertions, 174 deletions
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs
index 7efd5c0d..48b8fb22 100644
--- a/src/slskd/Application.cs
+++ b/src/slskd/Application.cs
@@ -529,211 +529,221 @@ namespace slskd
// todo: consider moving this somewhere else; it's pretty long and complicated
private async Task EnqueueDownload(string username, IPEndPoint endpoint, string filename)
{
- if (Users.IsBlacklisted(username, endpoint.Address))
- {
- Log.Information("Rejected enqueue request for blacklisted user {Username} ({IP})", username, endpoint.Address);
- throw new DownloadEnqueueException("File not shared.");
- }
-
- // in order to properly determine if the requested file would exceed any limits, we need to know the size of the file
- // it helps, too, that this will tell us whether the file is even shared.
- (string Host, string Filename, long Size) resolved;
+ var stopwatch = new Stopwatch();
+ var decisionStopwatch = new Stopwatch();
try
{
- resolved = await Shares.ResolveFileAsync(filename);
- }
- catch (NotFoundException)
- {
- throw new DownloadEnqueueException("File not shared.");
- }
+ stopwatch.Start();
- // get the user's group. this will be the name of the user's group, if they have been added to a
- // user defined group, or one of the built-ins; 'default', 'privileged', 'leecher', or 'blacklisted'
- var group = await Users.GetOrFetchGroupAsync(username);
+ if (Users.IsBlacklisted(username, endpoint.Address))
+ {
+ Log.Information("Rejected enqueue request for blacklisted user {Username} ({IP})", username, endpoint.Address);
+ throw new DownloadEnqueueException("File not shared.");
+ }
- // privileged users aren't subject to limits (for now)
- // i'm putting this off because 1) limits are unique to slskd, so all other clients are "unlimited"
- // and 2) i can't figure out what the limits would be, if not unlimited. users should get some level
- // of control, but i'd need to figure out a lower bound
- if (string.Equals(group, PrivilegedGroup))
- {
- Log.Debug("Limits bypassed for {Username} and {File}; user is privileged", username, filename);
- await Transfers.Uploads.EnqueueAsync(username, filename);
- return;
- }
+ // in order to properly determine if the requested file would exceed any limits, we need to know the size of the file
+ // it helps, too, that this will tell us whether the file is even shared.
+ (string Host, string Filename, long Size) resolved;
- // we'll fall back to global limits for any limit that isn't set at the group level
- var global = Options.Global.Limits;
+ try
+ {
+ resolved = await Shares.ResolveFileAsync(filename);
+ }
+ catch (NotFoundException)
+ {
+ throw new DownloadEnqueueException("File not shared.");
+ }
- // resolve the limits for this user's group.
- Options.LimitsOptions limits;
+ // get the user's group. this will be the name of the user's group, if they have been added to a
+ // user defined group, or one of the built-ins; 'default', 'privileged', 'leecher', or 'blacklisted'
+ var group = await Users.GetOrFetchGroupAsync(username);
- if (Options.Groups.UserDefined.TryGetValue(group, out var userDefinedOptions))
- {
- limits = userDefinedOptions.Limits;
- }
- else
- {
- limits = group switch
+ // privileged users aren't subject to limits (for now)
+ // i'm putting this off because 1) limits are unique to slskd, so all other clients are "unlimited"
+ // and 2) i can't figure out what the limits would be, if not unlimited. users should get some level
+ // of control, but i'd need to figure out a lower bound
+ if (string.Equals(group, PrivilegedGroup))
{
- DefaultGroup => Options.Groups.Default.Limits,
- LeecherGroup => Options.Groups.Leechers.Limits,
- _ => Options.Groups.Default.Limits, // that's weird! we'll just go with defaults..
- };
- }
+ Log.Debug("Limits bypassed for {Username} and {File}; user is privileged", username, filename);
+ await Transfers.Uploads.EnqueueAsync(username, filename);
+ return;
+ }
- bool IsNull(Options.LimitsOptions.Limits lim, Options.LimitsOptions.Limits global)
- => (lim is null && global is null) || ((lim?.Files ?? global?.Files ?? lim?.Megabytes ?? global?.Megabytes ?? lim.Failures ?? global.Failures) is null);
+ // we'll fall back to global limits for any limit that isn't set at the group level
+ var global = Options.Global.Limits;
- /*
- * we have limits set, so now we have to fetch the data and compare to see if any would be hit if we allow this transfer to be enqueued.
- * the strategy here is to summarize all uploads:
- * 1) belonging to this user
- * 2) that were started within the time period
- * 3) that did not end due to an error (state includes errored, exception column is set)
- */
- (bool Files, bool Megabytes) OverLimits(
- (int Files, long Bytes) stats,
- Options.LimitsOptions.Limits options,
- Options.LimitsOptions.Limits defaults,
- long size)
- {
- var files = false;
- var megabytes = false;
- var byteLimitInMegabytes = options?.Megabytes ?? defaults?.Megabytes;
+ // resolve the limits for this user's group.
+ Options.LimitsOptions limits;
- if (byteLimitInMegabytes is not null && (stats.Bytes + size) > (byteLimitInMegabytes * 1000L * 1000L))
+ if (Options.Groups.UserDefined.TryGetValue(group, out var userDefinedOptions))
{
- Log.Debug("Projected bytes {Bytes} exceeds limit {Limit}", stats.Bytes + size, byteLimitInMegabytes * 1000L * 1000L);
- megabytes = true;
+ limits = userDefinedOptions.Limits;
}
-
- var fileLimit = options?.Files ?? defaults?.Files;
-
- if (fileLimit is not null && (stats.Files + 1) > fileLimit)
+ else
{
- Log.Debug("Projected file count {Files} exceeds limit {Limit}", stats.Files + 1, fileLimit);
- files = true;
+ 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..
+ };
}
- return (files, megabytes);
- }
+ bool IsNull(Options.LimitsOptions.Limits lim, Options.LimitsOptions.Limits global)
+ => (lim is null && global is null) || ((lim?.Files ?? global?.Files ?? lim?.Megabytes ?? global?.Megabytes ?? lim.Failures ?? global.Failures) is null);
+
+ /*
+ * we have limits set, so now we have to fetch the data and compare to see if any would be hit if we allow this transfer to be enqueued.
+ * the strategy here is to summarize all uploads:
+ * 1) belonging to this user
+ * 2) that were started within the time period
+ * 3) that did not end due to an error (state includes errored, exception column is set)
+ */
+ (bool Files, bool Megabytes) OverLimits(
+ (int Files, long Bytes) stats,
+ Options.LimitsOptions.Limits options,
+ Options.LimitsOptions.Limits defaults,
+ long size)
+ {
+ var files = false;
+ var megabytes = false;
+ var byteLimitInMegabytes = options?.Megabytes ?? defaults?.Megabytes;
- var sw = new Stopwatch();
- sw.Start();
+ if (byteLimitInMegabytes is not null && (stats.Bytes + size) > (byteLimitInMegabytes * 1000L * 1000L))
+ {
+ Log.Debug("Projected bytes {Bytes} exceeds limit {Limit}", stats.Bytes + size, byteLimitInMegabytes * 1000L * 1000L);
+ megabytes = true;
+ }
- // start with the queue, since that should contain the fewest files and should be the least expensive to check
- // "queued" includes both queued and in progress; records with a null EndedAt property, which is guaranteed to be set
- // for terminal transfers.
- if (!IsNull(limits?.Queued, global?.Queued))
- {
- var queued = Transfers.Uploads.Summarize(
- expression: t => t.Username == username && t.EndedAt == null);
+ var fileLimit = options?.Files ?? defaults?.Files;
+
+ if (fileLimit is not null && (stats.Files + 1) > fileLimit)
+ {
+ Log.Debug("Projected file count {Files} exceeds limit {Limit}", stats.Files + 1, fileLimit);
+ files = true;
+ }
- Log.Debug("Fetched queue stats: files: {Files}, bytes: {Bytes} ({Time}ms)", queued.Files, queued.Bytes, sw.ElapsedMilliseconds);
+ return (files, megabytes);
+ }
- var over = OverLimits(queued, limits?.Queued, global?.Queued, resolved.Size);
+ decisionStopwatch.Start();
- if (over.Files || over.Megabytes)
+ // start with the queue, since that should contain the fewest files and should be the least expensive to check
+ // "queued" includes both queued and in progress; records with a null EndedAt property, which is guaranteed to be set
+ // for terminal transfers.
+ if (!IsNull(limits?.Queued, global?.Queued))
{
- Log.Information("Rejected enqueue request for user {Username}: Queued limits exceeded", username);
+ var queued = Transfers.Uploads.Summarize(
+ expression: t => t.Username == username && t.EndedAt == null);
+
+ Log.Debug("Fetched queue stats: files: {Files}, bytes: {Bytes} ({Time}ms)", queued.Files, queued.Bytes, decisionStopwatch.ElapsedMilliseconds);
+
+ var over = OverLimits(queued, limits?.Queued, global?.Queued, resolved.Size);
+
+ if (over.Files || over.Megabytes)
+ {
+ Log.Information("Rejected enqueue request for user {Username}: Queued limits exceeded", username);
- // note: return exactly 'Too many files' or 'Too many megabytes' to ensure interop with other clients.
- // these messages are retryable, while anything else is not
- throw new DownloadEnqueueException($"Too many {(over.Megabytes ? "megabytes" : "files")}");
+ // note: return exactly 'Too many files' or 'Too many megabytes' to ensure interop with other clients.
+ // these messages are retryable, while anything else is not
+ throw new DownloadEnqueueException($"Too many {(over.Megabytes ? "megabytes" : "files")}");
+ }
}
- }
- // start with weekly, as this is the most likely limit to be hit and we want to keep the work to a minimum
- // transfers that 'count' for the weekly limit are uploads that:
- // * started within the last week
- // * which have or have not ended (assuming queued files will complete)
- // * that were not errored
- if (!IsNull(limits?.Weekly, global?.Weekly))
- {
- var erroredState = TransferStates.Completed | TransferStates.Errored;
- var cutoffDateTime = DateTime.UtcNow.AddDays(-7);
+ // start with weekly, as this is the most likely limit to be hit and we want to keep the work to a minimum
+ // transfers that 'count' for the weekly limit are uploads that:
+ // * started within the last week
+ // * which have or have not ended (assuming queued files will complete)
+ // * that were not errored
+ if (!IsNull(limits?.Weekly, global?.Weekly))
+ {
+ var erroredState = TransferStates.Completed | TransferStates.Errored;
+ var cutoffDateTime = DateTime.UtcNow.AddDays(-7);
- var failures = Transfers.Uploads.Summarize(
- expression: t =>
- t.Username == username
- && t.StartedAt >= cutoffDateTime
- && (t.State.HasFlag(erroredState) || t.Exception != null));
+ var failures = Transfers.Uploads.Summarize(
+ expression: t =>
+ t.Username == username
+ && t.StartedAt >= cutoffDateTime
+ && (t.State.HasFlag(erroredState) || t.Exception != null));
- Log.Debug("Fetched weekly failures: {Failures} ({Time}ms)", failures.Files, sw.ElapsedMilliseconds);
+ Log.Debug("Fetched weekly failures: {Failures} ({Time}ms)", failures.Files, decisionStopwatch.ElapsedMilliseconds);
- var failureLimit = limits?.Weekly?.Failures ?? global?.Weekly?.Failures;
+ var failureLimit = limits?.Weekly?.Failures ?? global?.Weekly?.Failures;
- if (failureLimit is not null && failures.Files >= failureLimit)
- {
- Log.Information("Rejected enqueue request for user {Username}: Weekly failure limit met or exceeded", username);
- throw new DownloadEnqueueException("Too many failed transfers this week");
- }
+ if (failureLimit is not null && failures.Files >= failureLimit)
+ {
+ Log.Information("Rejected enqueue request for user {Username}: Weekly failure limit met or exceeded", username);
+ throw new DownloadEnqueueException("Too many failed transfers this week");
+ }
- var weekly = Transfers.Uploads.Summarize(
- expression: t =>
- t.Username == username
- && t.StartedAt >= cutoffDateTime
- && !t.State.HasFlag(erroredState)
- && t.Exception == null);
+ var weekly = Transfers.Uploads.Summarize(
+ expression: t =>
+ t.Username == username
+ && t.StartedAt >= cutoffDateTime
+ && !t.State.HasFlag(erroredState)
+ && t.Exception == null);
- Log.Debug("Fetched weekly stats: files: {Files}, bytes: {Bytes} ({Time}ms)", weekly.Files, weekly.Bytes, sw.ElapsedMilliseconds);
+ Log.Debug("Fetched weekly stats: files: {Files}, bytes: {Bytes} ({Time}ms)", weekly.Files, weekly.Bytes, decisionStopwatch.ElapsedMilliseconds);
- var over = OverLimits(weekly, limits?.Weekly, global?.Weekly, resolved.Size);
+ var over = OverLimits(weekly, limits?.Weekly, global?.Weekly, resolved.Size);
- if (over.Files || over.Megabytes)
- {
- Log.Information("Rejected enqueue request for user {Username}: Weekly limits exceeded", username);
- throw new DownloadEnqueueException($"Too many {(over.Files ? "files" : "megabytes")} this week");
+ if (over.Files || over.Megabytes)
+ {
+ Log.Information("Rejected enqueue request for user {Username}: Weekly limits exceeded", username);
+ throw new DownloadEnqueueException($"Too many {(over.Files ? "files" : "megabytes")} this week");
+ }
}
- }
- // lastly, check daily limits. the criteria for this is the same as weekly, just looking over the previous day instead
- // of the previous 7.
- if (!IsNull(limits?.Daily, global?.Daily))
- {
- var erroredState = TransferStates.Completed | TransferStates.Errored;
- var cutoffDateTime = DateTime.UtcNow.AddDays(-1);
+ // lastly, check daily limits. the criteria for this is the same as weekly, just looking over the previous day instead
+ // of the previous 7.
+ if (!IsNull(limits?.Daily, global?.Daily))
+ {
+ var erroredState = TransferStates.Completed | TransferStates.Errored;
+ var cutoffDateTime = DateTime.UtcNow.AddDays(-1);
- var failures = Transfers.Uploads.Summarize(
- expression: t =>
- t.Username == username
- && t.StartedAt >= cutoffDateTime
- && (t.State.HasFlag(erroredState) || t.Exception != null));
+ var failures = Transfers.Uploads.Summarize(
+ expression: t =>
+ t.Username == username
+ && t.StartedAt >= cutoffDateTime
+ && (t.State.HasFlag(erroredState) || t.Exception != null));
- Log.Debug("Fetched daily failures: {Failures} ({Time}ms)", failures.Files, sw.ElapsedMilliseconds);
+ Log.Debug("Fetched daily failures: {Failures} ({Time}ms)", failures.Files, decisionStopwatch.ElapsedMilliseconds);
- var failureLimit = limits?.Daily?.Failures ?? global?.Daily?.Failures;
+ var failureLimit = limits?.Daily?.Failures ?? global?.Daily?.Failures;
- if (failureLimit is not null && failures.Files >= failureLimit)
- {
- Log.Information("Rejected enqueue request for user {Username}: Daily failure limit met or exceeded", username);
- throw new DownloadEnqueueException("Too many failed transfers today");
- }
+ if (failureLimit is not null && failures.Files >= failureLimit)
+ {
+ Log.Information("Rejected enqueue request for user {Username}: Daily failure limit met or exceeded", username);
+ throw new DownloadEnqueueException("Too many failed transfers today");
+ }
- var daily = Transfers.Uploads.Summarize(
- expression: t =>
- t.Username == username
- && t.StartedAt >= cutoffDateTime
- && !t.State.HasFlag(erroredState)
- && t.Exception == null);
+ var daily = Transfers.Uploads.Summarize(
+ expression: t =>
+ t.Username == username
+ && t.StartedAt >= cutoffDateTime
+ && !t.State.HasFlag(erroredState)
+ && t.Exception == null);
- Log.Debug("Fetched daily stats: files: {Files}, bytes: {Bytes} ({Time}ms)", daily.Files, daily.Bytes, sw.ElapsedMilliseconds);
+ Log.Debug("Fetched daily stats: files: {Files}, bytes: {Bytes} ({Time}ms)", daily.Files, daily.Bytes, decisionStopwatch.ElapsedMilliseconds);
- var over = OverLimits(daily, limits?.Daily, global?.Daily, resolved.Size);
+ var over = OverLimits(daily, limits?.Daily, global?.Daily, resolved.Size);
- if (over.Files || over.Megabytes)
- {
- Log.Information("Rejected enqueue request for user {Username}: Daily limits exceeded", username);
- throw new DownloadEnqueueException($"Too many {(over.Files ? "files" : "megabytes")} today");
+ if (over.Files || over.Megabytes)
+ {
+ Log.Information("Rejected enqueue request for user {Username}: Daily limits exceeded", username);
+ throw new DownloadEnqueueException($"Too many {(over.Files ? "files" : "megabytes")} today");
+ }
}
- }
- sw.Stop();
- Log.Debug("Enqueue decision made in {Duration}ms", sw.ElapsedMilliseconds);
-
- await Transfers.Uploads.EnqueueAsync(username, filename);
+ await Transfers.Uploads.EnqueueAsync(username, filename);
+ }
+ finally
+ {
+ decisionStopwatch.Stop();
+ stopwatch.Stop();
+ Log.Debug("EnqueueDownload for {Username}/{Filename} completed in {ElapsedOverall}ms, decision made in {ElapsedDecision}ms", username, filename, stopwatch.ElapsedMilliseconds, decisionStopwatch.ElapsedMilliseconds);
+ }
}
/// <summary>
diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs
index 0d879d0c..350f1354 100644
--- a/src/slskd/Program.cs
+++ b/src/slskd/Program.cs
@@ -590,7 +590,8 @@ namespace slskd
new SoulseekClient(options: new SoulseekClientOptions(
maximumConcurrentUploads: OptionsAtStartup.Global.Upload.Slots,
maximumConcurrentDownloads: OptionsAtStartup.Global.Download.Slots,
- minimumDiagnosticLevel: OptionsAtStartup.Soulseek.DiagnosticLevel.ToEnum<Soulseek.Diagnostics.DiagnosticLevel>())));
+ minimumDiagnosticLevel: OptionsAtStartup.Soulseek.DiagnosticLevel.ToEnum<Soulseek.Diagnostics.DiagnosticLevel>(),
+ 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/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs
index 8969eeaf..db1a92ad 100644
--- a/src/slskd/Transfers/Downloads/DownloadService.cs
+++ b/src/slskd/Transfers/Downloads/DownloadService.cs
@@ -55,11 +55,12 @@ namespace slskd.Transfers.Downloads
/// </remarks>
/// <param name="username">The username of 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>
- Task<List<Transfer>> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files);
+ 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"/>.
@@ -67,19 +68,23 @@ namespace slskd.Transfers.Downloads
/// <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);
+ Task<Transfer> EnqueueAsync(string username, string filename, long size, Action<Transfer> stateChanged = null, CancellationToken cancellationToken = default);
/// <summary>
/// Downloads the specified enqueued <paramref name="transfer"/> from the remote user.
/// </summary>
/// <param name="transfer">The Transfer to download.</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>
/// <exception cref="ArgumentNullException">Thrown if the specified Transfer is null.</exception>
/// <exception cref="TransferNotFoundException">Thrown if the specified Transfer ID can't be found in the database.</exception>
/// <exception cref="InvalidOperationException">Thrown if the specified Transfer is not in the Queued | Locally state.</exception>
/// <exception cref="DuplicateTransferException">Thrown if a download matching the username and filename is already tracked by Soulseek.NET.</exception>
- Task<Transfer> DownloadAsync(Transfer transfer);
+ Task<Transfer> DownloadAsync(Transfer transfer, Action<Transfer> stateChanged = null, CancellationToken cancellationToken = default);
/// <summary>
/// Finds a single download matching the specified <paramref name="expression"/>.
@@ -196,14 +201,16 @@ namespace slskd.Transfers.Downloads
/// Downloads the specified enqueued <paramref name="transfer"/> from the remote user.
/// </summary>
/// <param name="transfer">The Transfer to download.</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>
/// <exception cref="ArgumentNullException">Thrown if the specified Transfer is null.</exception>
/// <exception cref="TransferNotFoundException">Thrown if the specified Transfer ID can't be found in the database.</exception>
/// <exception cref="InvalidOperationException">Thrown if the specified Transfer is not in the Queued | Locally state.</exception>
/// <exception cref="DuplicateTransferException">Thrown if a download matching the username and filename is already tracked by Soulseek.NET.</exception>
- public async Task<Transfer> DownloadAsync(Transfer transfer)
+ public async Task<Transfer> DownloadAsync(Transfer transfer, Action<Transfer> stateChanged = null, CancellationToken cancellationToken = default)
{
- var cts = new CancellationTokenSource();
+ var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
var syncRoot = new SemaphoreSlim(1, 1);
void SynchronizedUpdate(Transfer transfer, bool cancellable = true)
@@ -286,13 +293,15 @@ namespace slskd.Transfers.Downloads
// 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 (transfer.EnqueuedAt is null && args.Transfer.State.HasFlag(TransferStates.Queued) && args.Transfer.State.HasFlag(TransferStates.Remotely))
+ if (args.Transfer.State.HasFlag(TransferStates.Queued) && args.Transfer.State.HasFlag(TransferStates.Remotely))
{
- transfer.EnqueuedAt = DateTime.UtcNow;
+ transfer.EnqueuedAt ??= DateTime.UtcNow;
}
// todo: broadcast
SynchronizedUpdate(transfer);
+
+ stateChanged?.Invoke(transfer);
},
progressUpdated: (args) => rateLimiter.Invoke(() =>
{
@@ -470,8 +479,10 @@ namespace slskd.Transfers.Downloads
/// <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>
- public Task<Transfer> EnqueueAsync(string username, string filename, long size)
+ public Task<Transfer> EnqueueAsync(string username, string filename, long size, Action<Transfer> stateChanged = null, CancellationToken cancellationToken = default)
{
if (string.IsNullOrEmpty(username))
{
@@ -574,7 +585,7 @@ namespace slskd.Transfers.Downloads
Task.Run can fail due to thread pool exhaustion or OOM, and this *SHOULD* throw up the chain and
fail the enqueue request
*/
- _ = Task.Run(() => DownloadAsync(transfer)).ContinueWith(task =>
+ _ = Task.Run(() => DownloadAsync(transfer, stateChanged, cancellationToken)).ContinueWith(task =>
{
if (task.IsCompletedSuccessfully)
{
@@ -609,7 +620,7 @@ namespace slskd.Transfers.Downloads
Log.Error(ex, "Failed to clean up transfer {Id} after failed execution: {Message}", id, ex.Message);
throw;
}
- });
+ }, cancellationToken);
return Task.FromResult(transfer);
}
@@ -656,11 +667,12 @@ namespace slskd.Transfers.Downloads
/// </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)
+ public async Task<List<Transfer>> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, CancellationToken cancellationToken = default)
{
if (string.IsNullOrEmpty(username))
{
@@ -675,11 +687,74 @@ namespace slskd.Transfers.Downloads
List<Transfer> transfers = [];
List<Exception> exceptions = [];
+ /*
+ 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
+
+ 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 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.
+
+ 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;
+ }
+
try
{
- transfers.Add(await EnqueueAsync(username, file.Filename, file.Size));
+ var enqueuedTcs = new TaskCompletionSource<Transfer>();
+ List<string> transitions = [];
+
+ // 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)
+ {
+ 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"));
+ }
+ });
+
+ 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
+ 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);
+ }
+ }
+
+ // 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;
+
+ transfers.Add(transfer);
}
catch (Exception ex)
{
@@ -687,7 +762,7 @@ namespace slskd.Transfers.Downloads
}
}
- if (exceptions.Any())
+ if (exceptions.Count != 0)
{
throw new AggregateException(exceptions);
}
diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj
index 49e48552..ae042d68 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.1.2" />
+ <PackageReference Include="Soulseek" Version="8.2.1" />
<PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.556">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>