//
// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄
// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █
// █__ --█ █__ --█ ◄█ - █
// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉
// │ 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 Microsoft.Extensions.Options;
using Soulseek;
namespace slskd.Transfers.Downloads
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Serilog;
using slskd.Events;
using slskd.Files;
using slskd.Integrations.FTP;
using slskd.Relay;
using slskd.Search;
///
/// Manages downloads.
///
public interface IDownloadService
{
///
/// Gets download batch service.
///
IBatchService Batches { get; }
///
/// Adds the specified . Supersedes any existing record for the same file and username.
///
/// This should generally not be called; use EnqueueAsync() instead.
///
void AddOrSupersede(Transfer transfer);
///
/// Derives the destination subdirectory for the specified based on user and batch
/// configuration.
///
///
///
/// Output is guaranteed to be a localized, sanitized, relative path with no traversal segments.
/// Otherwise, an instance of will be thrown as a backstop.
///
///
/// Empty segments may be present in the output, which more closely aligns with user intent. The
/// method drops them silently, so there's no functional impact.
///
///
/// The transfer.
/// The derived destination directory.
/// Thrown if the specified download doesn't exist.
/// Thrown if the derivation logic produces an absolute path, or one with traversal segments.
Task DeriveDestination(Transfer transfer);
///
/// Enqueues the requested list of .
///
///
/// If one file in the specified collection fails, the rest will continue. An will be
/// thrown after all files are dispositioned if any throws.
///
/// The username of remote user.
/// The list of files to enqueue.
/// The optional batch id for the transfers.
/// The token to monitor for cancellation.
/// The operation context.
/// Thrown when the username is null or an empty string.
/// Thrown when no files are requested.
/// Thrown when at least one of the requested files throws.
Task<(List Enqueued, List<(string Filename, string Message)> Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, Guid? batchId = null, CancellationToken cancellationToken = default);
///
/// Finds a single download matching the specified .
///
/// The expression to use to match downloads.
/// The found transfer, or default if not found.
Transfer Find(Expression> expression);
///
/// Retrieves the place in the remote queue for the download matching the specified .
///
/// The unique identifier for the download.
/// The retrieved place in queue.
Task GetPlaceInQueueAsync(Guid id);
///
/// Returns a list of all downloads matching the optional .
///
/// An optional expression used to match downloads.
/// Optionally include downloads that have been removed previously.
/// The list of downloads matching the specified expression, or all downloads if no expression is specified.
List List(Expression> expression = null, bool includeRemoved = false);
///
/// Removes downloads older than the specified .
///
/// The age after which downloads are eligible for pruning, in hours.
/// One or more states by which downloads are filtered for pruning.
/// The number of pruned downloads.
int Prune(int age, params TransferStates[] states);
///
/// Removes the completed download matching the specified .
///
/// This is a soft delete; the record is retained for historical retrieval.
/// The unique identifier of the download.
/// A value indicating whether the record was removed.
bool Remove(Guid id);
///
/// Removes all completed downloads matching the specified .
///
/// This is a soft delete; the record is retained for historical retrieval.
/// The expression used to match downloads.
/// The number of records removed.
int Remove(Expression> expression);
///
/// Cancels the download matching the specified , if it is in progress.
///
/// The unique identifier for the download.
/// A value indicating whether the download was successfully cancelled.
bool TryCancel(Guid id);
///
/// Fails the download matching the specified with the specified ,
/// and sets the final state accordingly.
///
///
/// This method is designed to be idempotent, meaning subsequent calls for a given transfer shouldn't change
/// the EndedAt or Exception properties if they have already been set. If the transfer State already includes
/// the terminal Completed flag, it is unchanged.
///
/// The unique identifier for the download.
/// The exception that caused the failure.
/// A value indicating whether the download was successfully failed.
bool TryFail(Guid id, Exception exception);
///
/// Updates the specified .
///
/// The transfer to update.
void Update(Transfer transfer);
}
///
/// Manages downloads.
///
public class DownloadService : IDownloadService
{
public DownloadService(
IBatchService batchService,
ISearchService searchService,
IOptionsMonitor optionsMonitor,
ISoulseekClient soulseekClient,
IDbContextFactory contextFactory,
FileService fileService,
IRelayService relayService,
IFTPService ftpClient,
EventBus eventBus,
TimeProvider timeProvider = null)
{
Batches = batchService;
Searches = searchService;
Client = soulseekClient;
OptionsMonitor = optionsMonitor;
ContextFactory = contextFactory;
Files = fileService;
FTP = ftpClient;
Relay = relayService;
EventBus = eventBus;
TimeProvider = timeProvider ?? TimeProvider.System;
Clock.EveryMinute += (_, _) => Task.Run(() => CleanupEnqueueSemaphoresAsync());
Clock.EveryFiveSeconds += (_, _) => Task.Run(() => EmitMetrics());
}
///
/// Gets download batch service.
///
public IBatchService Batches { get; }
///
/// These tokens give users the ability to cancel transfers via the UI (or API).
///
/// The lifecycle is:
///
/// 1. in EnqueueAsync(), just before transfer records are added to the database, these CTS are created and
/// added to the dictionary
/// 2. in EnqueueAsync(), if there was an error or any condition which caused the transfer to not proceed was met,
/// the CTS is removed from the dictionary and disposed
/// 3. in DownloadAsync(), in the finally block after all post-download logic has been executed, the CTS
/// is removed and disposed.
///
/// The CTS should be in the dictionary the entire time the transfer is "in flight", from the first moment it
/// comes into being (via database insert) until the eventual download process has completed or failed.
///
/// Every cancellable operation in this flow needs to use this CTS token either directly or by linking it with another,
/// or we risk transfers getting stuck with no way for users to get rid of them.
///
private ConcurrentDictionary CancellationTokens { get; } = new ConcurrentDictionary();
private ISoulseekClient Client { get; }
private IDbContextFactory ContextFactory { get; }
private IFTPService FTP { get; }
private FileService Files { get; }
private ISearchService Searches { get; }
private IRelayService Relay { get; }
private ILogger Log { get; } = Serilog.Log.ForContext();
private IOptionsMonitor OptionsMonitor { get; }
private EventBus EventBus { get; }
private Regex SubdirectoryPatternTokenRegex { get; } = new Regex(@"\$\{([^\{\}]*)\}", RegexOptions.IgnoreCase | RegexOptions.Compiled);
private TimeProvider TimeProvider { get; }
///
/// Allow only one enqueue operation for a given user at a time. Entries are added on the fly if they
/// don't already exist, and a timer asynchronously cleans the dictionary up.
///
private ConcurrentDictionary EnqueueSemaphores { get; } = [];
///
/// Synchronizes the cleanup process; after gaining exclusive access over the dictionary, checks each entry
/// to see if the containing semaphore can be obtained immediately. If so, it's not in use and is therefore
/// removed from the dictionary and discarded.
///
private SemaphoreSlim EnqueueSemaphoreSyncRoot { get; } = new SemaphoreSlim(initialCount: 1, maxCount: 1);
///
/// Adds the specified . Supersedes any existing record for the same file and username.
///
/// This should generally not be called; use EnqueueAsync() instead.
///
public void AddOrSupersede(Transfer transfer)
{
using var context = ContextFactory.CreateDbContext();
var existing = context.Transfers
.Where(t => t.Direction == TransferDirection.Download)
.Where(t => t.Username == transfer.Username)
.Where(t => t.Filename == transfer.Filename)
.Where(t => !t.Removed)
.FirstOrDefault();
if (existing != default)
{
Log.Debug("Superseding transfer record for {Filename} from {Username}", transfer.Filename, transfer.Username);
existing.Removed = true;
}
context.Add(transfer);
context.SaveChanges();
}
///
/// Enqueues the requested list of .
///
/// The username of the remote user.
/// The list of files to enqueue.
/// The optional batch id for the transfers.
/// The token to monitor for cancellation.
/// The operation context.
/// Thrown when the username is null or an empty string.
/// Thrown when no files are requested.
/// Thrown when at least one of the requested files throws.
public async Task<(List Enqueued, List<(string Filename, string Message)> Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, Guid? batchId = null, CancellationToken cancellationToken = default)
{
if (string.IsNullOrEmpty(username))
{
throw new ArgumentException("Username is required", nameof(username));
}
var fileList = files?.ToList() ?? [];
if (fileList.Count == 0)
{
throw new ArgumentException("At least one file is required", nameof(files));
}
if (fileList.Any(f => string.IsNullOrEmpty(f.Filename)))
{
throw new ArgumentException("At least one filename is null or empty", nameof(files));
}
if (fileList.Any(f => FileSafety.ContainsTraversalSegments(f.Filename)))
{
throw new ArgumentException("One or more files contains a dangerous path traversal segment", nameof(files));
}
if (fileList.Count != fileList.Select(f => f.Filename).Distinct().Count())
{
throw new ArgumentException("Two or more files in request are duplicated", nameof(files));
}
IPEndPoint endpoint;
Log.Information("Requested enqueue of {Count} files from user {Username}", fileList.Count, username);
// get the user's ip and port. this will throw if they are offline.
try
{
endpoint = await Client.GetUserEndPointAsync(username, cancellationToken);
}
catch (Exception ex)
{
Log.Error(ex, "Failed to enqueue {Count} files from {Username}: {Message}", fileList.Count, username, ex.Message);
throw;
}
// 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
{
Log.Debug("Priming message connection to {Username}", username);
await Client.ConnectToUserAsync(username, invalidateCache: false, cancellationToken);
}
catch (Exception ex)
{
Log.Error(ex, "Failed to connect to {Username}: {Message}", username, ex.Message);
throw;
}
List enqueued = [];
List<(string Filename, string Message)> failed = [];
SemaphoreSlim userSemaphore;
Task userSemaphoreWaitTask;
Log.Debug("Awaiting enqueue semaphore sync root");
await EnqueueSemaphoreSyncRoot.WaitAsync(cancellationToken);
try
{
Log.Debug("Acquired enqueue semaphore sync root");
userSemaphore = EnqueueSemaphores.GetOrAdd(username, (username) => new SemaphoreSlim(initialCount: 1, maxCount: 1));
userSemaphoreWaitTask = userSemaphore.WaitAsync(cancellationToken);
}
finally
{
EnqueueSemaphoreSyncRoot.Release();
Log.Debug("Released enqueue semaphore sync root");
}
Log.Debug("Awaiting enqueue semaphore for user {Username}", username);
await userSemaphoreWaitTask;
try
{
Log.Debug("Acquired enqueue semaphore for user {Username}", username);
using var context = ContextFactory.CreateDbContext();
/*
get existing downloads from this user. this list will remain stable throughout this process because
we have exclusive access for this user. we'll be adding new records, but we've already deduplicated
them so we don't have to worry about duplicate records being created in the critical section
we are looking for:
1. anything that's not yet complete (we need to disallow the enqueue)
2. anything complete, but not yet removed from the UI (we need to supersede it)
*/
var existingRecordsNotYetRemoved = context.Transfers
.Where(t => t.Direction == TransferDirection.Download)
.Where(t => t.Username == username)
.Where(t => !t.Removed || !TransferStateCategories.Completed.Contains(t.State))
.AsNoTracking() // note: AI wants to remove this, dont.
.ToList();
var existingInProgressRecords = existingRecordsNotYetRemoved
.Where(t => t.EndedAt == null || !t.State.HasFlag(TransferStates.Completed))
.ToDictionary(t => t.Filename, t => t);
/*
determine how many concurrent enqueue requests we want to send to the remote client.
sending a ton of them can bog the client down and fail transfers due to resource contention on both sides,
but both clients should be able to handle momentary 'bursts'.
if the request contains 30 files or fewer, send all of the requests at the same time. the average number
of tracks in a single album is 15, so this is 2x as many as most enqueue requests will need.
if that number is more than 30, send only 5 at a time; transfers will be starting as we are still
enqueueing files, and this raises the risk of errors considerably.
*/
var concurrentEnqueueRequests = 5;
if (fileList.Count <= 30)
{
concurrentEnqueueRequests = fileList.Count;
}
var maxTimeToWaitForEnqueueRequestAck = TimeSpan.FromMinutes(3);
var enqueueSemaphore = new SemaphoreSlim(initialCount: concurrentEnqueueRequests, maxCount: concurrentEnqueueRequests);
/*
iterate over each of the files in the request. each file must be dispositioned as one of the following:
1. enqueued: passed duplicate checks and successfully kicked off a Task to enqueue the download
2. failed: download is already in progress, or something went wrong kicking off the Task
if we fail to enqueue a file, we must call TryFail() to ensure that if a record was inserted, it is
given a final disposition that will keep it from getting 'stuck'
*/
foreach (var file in fileList)
{
cancellationToken.ThrowIfCancellationRequested();
Guid transferId = Guid.NewGuid();
try
{
Log.Debug("Checking whether download of {Filename} from {Username} is already in progress", file.Filename, username);
/*
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!
*/
existingInProgressRecords.TryGetValue(file.Filename, out var existingInProgressRecord);
if (existingInProgressRecord is not null)
{
Log.Debug("Ignoring concurrent download enqueue attempt; transfer for {Filename} from {Username} already in progress (id: {Id})", file.Filename, username, existingInProgressRecord.Id);
failed.Add((file.Filename, "Skipped: Already in progress"));
continue;
}
/*
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, which is likely a bug
and we'd like to know about it
*/
if (Client.Downloads?.Any(u => u.Username == username && u.Filename == file.Filename) ?? false)
{
Log.Warning("Ignoring concurrent download enqueue attempt; transfer for {Filename} from {Username} is tracked by the Soulseek client but not slskd", file.Filename, username);
failed.Add((file.Filename, "Skipped: Already in progress"));
continue;
}
/*
add the transfer record to the database in the Queued | Locally state, and set the 'Removed'
property of any existing transfer to 'true', allowing the new record to supersede any old record(s)
on the UI
we have to persist these changes to the database at this time so the record shows up on the UI,
otherwise the transfers only show up as they are enqueued.
*/
var transfer = new Transfer()
{
Id = transferId,
BatchId = batchId,
Username = username,
Direction = TransferDirection.Download,
Filename = file.Filename, // important! use the remote filename
Size = file.Size,
RequestedAt = DateTime.UtcNow,
State = TransferStates.Queued | TransferStates.Locally,
};
context.Add(transfer);
Log.Debug("Added Transfer record for download of {Filename} from {Username} (id: {Id})", transfer.Filename, transfer.Username, transfer.Id);
foreach (var record in existingRecordsNotYetRemoved.Where(t => t.Filename == file.Filename && !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);
}
/*
create a TaskCompletionSource that we can await for one of the following:
1. the transfer enters the Queued | Remotely state
2. the transfer enters a state containing Completed
3. the linked CancellationTokenSource we add to CancellationTokens is cancelled
4. the 'max wait time' CancellationTokenSource is cancelled
5. the DownloadAsync() method throws
add this to the dictionary before inserting the record, so we are guaranteed to have it
in the right place once the transfer hits the UI
*/
var enqueuedTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
// satisfies condition #3; CancellationTokenSource set cancelled by the user (via API call)
var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
CancellationTokens.TryAdd(transfer.Id, cts);
cts.Token.Register(() => enqueuedTcs.TrySetCanceled());
/*
DANGER ZONE! this record is in the database now; we're on the hook for making sure it ends up
with a State that includes the Completed flag, else it remain "stuck" on the UI
*/
context.SaveChanges();
Log.Debug("Scheduling Task for enqueue of {Filename} from {Username}", file.Filename, username);
/*
rip off one task for each file in the batch, leaving each to internally wait their turn
to proceed with the actual enqueue request and subsequent download, orchestrated by the
concurrent enqueue request semaphore
we don't wait for any of them; as long as the Task is successfully scheduled (Task.Run doesn't throw),
we consider it a success.
*/
var downloadEnqueueTask = Task.Run(async () =>
{
Log.Debug("Awaiting download enqueue semaphore for {Filename} from {Username}", transfer.Filename, transfer.Username);
await enqueueSemaphore.WaitAsync(cts.Token);
try
{
Log.Debug("Acquired download enqueue semaphore for {Filename} from {Username}", transfer.Filename, transfer.Username);
List transitions = [];
TransferStates state = TransferStates.None;
// satisfies condition #4; remote user doesn't respond after a really long time
using var timeoutCts = new CancellationTokenSource(delay: maxTimeToWaitForEnqueueRequestAck, timeProvider: TimeProvider);
timeoutCts.Token.Register(() =>
{
// note: disposed once we leave the try block, so registration doesn't fire unless it actually times out
Log.Warning("Download of {Filename} from {Username} failed to enqueue remotely after hard time limit of {Duration} seconds. State transition history: {History}", transfer.Filename, username, maxTimeToWaitForEnqueueRequestAck.TotalSeconds, string.Join(", ", transitions));
enqueuedTcs.TrySetException(new TimeoutException($"Download failed to enqueue remotely after hard time limit of {maxTimeToWaitForEnqueueRequestAck.TotalSeconds} secs"));
// cancel the download attempt so that it doesn't keep running (within Soulseek.NET) and cause the internal
// state of slskd to diverge from the internal state of Soulseek.NET.
cts.Cancel(swallowObjectDisposedException: true);
});
// satisfies conditions #1 and #2
void stateChanged(Transfer transfer)
{
state = transfer.State;
transitions.Add(transfer.State.ToString());
if (transfer.State.HasFlag(TransferStates.Queued) && transfer.State.HasFlag(TransferStates.Remotely))
{
// satisfies condition #1; transfer is now remotely queued
enqueuedTcs.TrySetResult(transfer);
}
// satisfies condition #2; transfer advanced to a terminal state before being enqueued remotely (probably failed)
if (transfer.State.HasFlag(TransferStates.Completed))
{
if (transfer.State.HasFlag(TransferStates.Succeeded))
{
enqueuedTcs.TrySetResult(transfer);
}
else
{
enqueuedTcs.TrySetException(new TransferException(transfer.Exception));
}
}
}
Log.Debug("Scheduling Task for download of {Filename} from {Username}", transfer.Filename, transfer.Username);
var downloadTask = Task.Run(() => DownloadAsync(transfer, stateChanged, cancellationToken: cts.Token)).ContinueWith(task =>
{
if (task.IsCompletedSuccessfully)
{
Log.Information("Task for download of {Filename} from {Username} completed successfully", transfer.Filename, transfer.Username);
return;
}
Exception ex = task.IsCanceled ? new OperationCanceledException("Task was cancelled") : task.Exception;
ex = ex?.InnerException ?? ex ?? new Exception("Unknown error");
Log.Error(ex, "Task for download of {Filename} from {Username} did not complete successfully: {Error}", file.Filename, username, ex.Message);
// trip the TCS if DownloadAsync() throws before any of the other conditions trip it
// this is harmless if it has already been tripped
enqueuedTcs.TrySetException(ex);
if (!TryFail(transferId, exception: ex))
{
Log.Error(ex, "Failed to clean up transfer {Id} after failed download", transferId);
}
}, cancellationToken: CancellationToken.None); // end downloadTask.Run();
Log.Debug("Download Task status for {Filename} from {Username}: {Status}", file.Filename, username, downloadTask.Status);
Log.Debug("Waiting for download of {Filename} from {Username} to transition into {State}", transfer.Filename, transfer.Username, TransferStates.Queued | TransferStates.Remotely);
/*
wait for one of the four conditions to be true:
1. the transfer enters the Queued | Remotely state
2. the transfer enters a state containing Completed
3. the linked CancellationTokenSource we add to CancellationTokens is cancelled
4. the 'max wait time' CancellationTokenSource is cancelled
5. the DownloadAsync() method throws
*/
await enqueuedTcs.Task;
Log.Debug("Download of {Filename} from {Username} successfully entered state {State}", transfer.Filename, transfer.Username, state);
}
catch (Exception ex)
{
Log.Error(ex, "Download of {File} from {Username} failed: {Message}", transfer.Filename, transfer.Username, ex.Message);
if (!TryFail(transferId, exception: ex))
{
Log.Error(ex, "Failed to clean up transfer {Id} after failed execution: {Message}", transfer.Id, ex.Message);
}
}
finally
{
enqueueSemaphore.Release();
}
}, cancellationToken: cts.Token).ContinueWith(task =>
{
if (task.IsCompletedSuccessfully)
{
Log.Information("Task for enqueue of {Filename} from {Username} completed successfully", file.Filename, username);
return;
}
Exception ex = task.IsCanceled ? new OperationCanceledException("Task was cancelled") : task.Exception;
ex = ex?.InnerException ?? ex ?? new Exception("Unknown error");
Log.Error(ex, "Task for enqueue of {Filename} from {Username} did not complete successfully: {Error}", file.Filename, username, ex.Message);
if (!TryFail(transferId, exception: ex))
{
Log.Error(ex, "Failed to clean up transfer {Id} after failed enqueue", transferId);
}
}, cancellationToken: CancellationToken.None); // end downloadEnqueueTask.Run();
Log.Debug("Download enqueue Task status for {Filename} from {Username}: {Status}", file.Filename, username, downloadEnqueueTask.Status);
Log.Information("Successfully locally enqueued download of {Filename} from {Username} (id: {Id})", file.Filename, username, transferId);
enqueued.Add(transfer);
}
catch (Exception ex)
{
Log.Error(ex, "Failed to enqueue download of {Filename} from {Username}: {Message}", file.Filename, username, ex.Message);
TryFail(transferId, exception: ex);
failed.Add((file.Filename, $"Error: {ex.Message}"));
if (CancellationTokens.TryRemove(transferId, out var cts))
{
cts.Dispose();
}
continue;
}
} // end foreach()
Log.Information("Successfully enqueued {Count} files from {Username}", enqueued.Count, username);
return (enqueued, failed);
}
catch (Exception ex)
{
Log.Error(ex, "Failed to enqueue one or more of {Count} files from {Username}: {Message}", fileList.Count, username, ex.Message);
throw;
}
finally
{
userSemaphore.Release();
Log.Debug("Released enqueue semaphore for user {Username}", username);
}
}
///
/// Finds a single download matching the specified .
///
/// The expression to use to match downloads.
/// The found transfer, or default if not found.
public Transfer Find(Expression> expression)
{
try
{
using var context = ContextFactory.CreateDbContext();
return context.Transfers
.AsNoTracking()
.Where(t => t.Direction == TransferDirection.Download)
.Where(expression).FirstOrDefault();
}
catch (Exception ex)
{
Log.Error(ex, "Failed to find download: {Message}", ex.Message);
throw;
}
}
///
/// Retrieves the place in the remote queue for the download matching the specified .
///
/// The unique identifier for the download.
/// The retrieved place in queue.
public async Task GetPlaceInQueueAsync(Guid id)
{
try
{
using var context = ContextFactory.CreateDbContext();
var transfer = context.Transfers.Find(id);
if (transfer == default || transfer.Direction != TransferDirection.Download)
{
throw new NotFoundException($"No download matching id {id}");
}
var place = await Client.GetDownloadPlaceInQueueAsync(transfer.Username, transfer.Filename);
transfer.PlaceInQueue = place;
context.SaveChanges();
return place;
}
catch (Exception ex)
{
Log.Error(ex, "Failed to get place in queue for download {Id}: {Message}", id, ex.Message);
throw;
}
}
///
/// Derives the destination subdirectory for the specified based on user and
/// batch configuration.
///
///
///
/// Output is guaranteed to be a localized, sanitized, relative path with no traversal segments.
/// Otherwise, an instance of will be thrown as a backstop.
///
///
/// Empty segments may be present in the output, which more closely aligns with user intent. The
/// method drops them silently, so there's no functional impact.
///
///
/// The transfer.
/// The derived destination directory.
/// Thrown if the derivation logic produces an absolute path, or one with traversal segments.
public async Task DeriveDestination(Transfer transfer)
{
// validation should ensure this is a relative path and that it contains no traversal segments
// we accept any type of slash in the pattern and convert it to the correct variant for the local OS
var pattern = OptionsMonitor.CurrentValue.Transfers.Download.Destination.Subdirectory;
// users can enter '{}' if they want the files to go directly into the root of the downloads directory
if (pattern.Equals("{}", StringComparison.OrdinalIgnoreCase))
{
return string.Empty;
}
string source_username;
string source_path;
string source_directory;
string batch_id;
string batch_external_id;
string search_id;
string search_text;
/*
fetch/extract/derive and sanitize each of the values we're going to replace
when flow leaves this block we can expect that all of the string values
defined above have a value that can be safely substituted for its placeholder
*/
try
{
Batch batch = null;
if (transfer.BatchId is not null)
{
batch = await Batches.FindAsync(b => b.Id == transfer.BatchId);
}
// destination supplied with the batch enqueue request takes precedence over all; return early
if (!string.IsNullOrWhiteSpace(batch?.Options?.Destination))
{
var explicitDestination = FileSafety.SanitizePath(batch.Options.Destination, replacement: '_');
// the only way to get here is through a regression in the logic above; if we are seeing this, ensure we are
// properly sanitizing user input both via the API and in the logic above
if (FileSafety.IsPathAbsolute(explicitDestination) || FileSafety.ContainsTraversalSegments(explicitDestination))
{
throw new SlskdException("Derived a transfer destination that is either not relative or contains traversal segments; neither is allowed. Please report this on GitHub.");
}
return explicitDestination;
}
Search search = null;
if (batch?.SearchId is not null)
{
search = await Searches.FindAsync(s => s.Id == batch.SearchId);
}
source_username = FileSafety.SanitizeFilename(transfer.Username, replacement: '_');
var filename = FileSafety.SanitizePath(transfer.Filename, replacement: '_');
// full remote path, e.g. '@@abcd\Foo\Bar\Baz\Qux.ext' => '@@abcd\Foo\Bar\Baz'
// retains the path root, if there is one (Soulseek NS does this), which may not be what
// people want, so possibly revisit and add StripPathRoot()
source_path = (FileSafety.GetDirectoryNameSafely(filename, retainRoot: false) ?? string.Empty).TrimEnd('/', '\\');
// name of the remote parent directory, so using the example above, 'Baz'
source_directory = (FileSafety.GetFileNameSafely(source_path) ?? string.Empty).TrimEnd('/', '\\');
batch_id = (batch?.Id ?? Guid.Empty) == Guid.Empty ? "unknown_batch_id" : batch.Id.ToString();
// the external id can be any string (it is supplied via API call) so we have to sanitize it just like the destination,
// except we don't want to allow it to tack on directories; that's not what it is for and it could be unintended
batch_external_id = FileSafety.SanitizeFilename(
filename: string.IsNullOrWhiteSpace(batch?.Options?.ExternalId) ? "unknown_batch_external_id" : batch.Options.ExternalId,
replacement: '_');
search_id = (search?.Id ?? Guid.Empty) == Guid.Empty ? "unknown_search_id" : search.Id.ToString();
search_text = FileSafety.SanitizeFilename(
filename: string.IsNullOrWhiteSpace(search?.SearchText) ? "unknown_search_text" : search.SearchText,
replacement: '_');
}
catch (Exception ex)
{
Log.Error(ex, "Failed fetch information for download {Id}: {Message}", transfer.Id, ex.Message);
throw;
}
var args = new Dictionary(
StringComparer.OrdinalIgnoreCase) // important!
{
["SOURCE_USERNAME"] = source_username,
["SOURCE_PATH"] = source_path,
["SOURCE_DIRECTORY"] = source_directory,
["BATCH_ID"] = batch_id,
["BATCH_EXTERNAL_ID"] = batch_external_id,
["SEARCH_ID"] = search_id,
["SEARCH_TEXT"] = search_text,
};
// use Regex.Replace here because it makes one pass; if we chained .Replace() calls the output from one could
// cascade into others and produce unintended results
var destination = SubdirectoryPatternTokenRegex.Replace(
input: pattern,
evaluator: match =>
{
if (args.TryGetValue(match.Groups[1].Value, out var value))
{
return value;
}
return match.Value;
});
destination = FileSafety.SanitizePath(destination, replacement: '_');
Log.Debug("Derived destination for download of {Filename} from {User}: {Destination} (id: {Id}, configuration: {Pattern}, args: {Args})", FileSafety.GetFileNameSafely(transfer.Filename), transfer.Username, destination, transfer.Id, pattern, new { source_username, source_path, source_directory, batch_id, batch_external_id, search_id, search_text });
// the only way to get here is through a regression in the logic above; if we are seeing this, ensure we are
// properly sanitizing the final output to strip leading slashes and replace traversal segments
if (FileSafety.IsPathAbsolute(destination) || FileSafety.ContainsTraversalSegments(destination))
{
Log.Error("Derived destination for download of {Filename} from {User}: {Destination} (id: {Id}, configuration: {Pattern}, args: {Args})", FileSafety.GetFileNameSafely(transfer.Filename), transfer.Username, destination, transfer.Id, pattern, new { source_username, source_path, source_directory, batch_id, batch_external_id, search_id, search_text });
throw new SlskdException("Derived a transfer destination that is either not relative or contains traversal segments; neither is allowed. Please report this on GitHub.");
}
return destination;
}
///
/// Returns a list of all downloads matching the optional .
///
/// An optional expression used to match downloads.
/// Optionally include downloads that have been removed previously.
/// The list of downloads matching the specified expression, or all downloads if no expression is specified.
public List List(Expression> expression = null, bool includeRemoved = false)
{
expression ??= t => true;
try
{
using var context = ContextFactory.CreateDbContext();
return context.Transfers
.AsNoTracking()
.Where(t => t.Direction == TransferDirection.Download)
.Where(t => !t.Removed || includeRemoved)
.Where(expression)
.ToList();
}
catch (Exception ex)
{
Log.Error(ex, "Failed to list downloads: {Message}", ex.Message);
throw;
}
}
///
/// Removes downloads older than the specified .
///
/// The age after which downloads are eligible for pruning, in hours.
/// One or more states by which downloads are filtered for pruning.
/// The number of pruned downloads.
public int Prune(int age, params TransferStates[] states)
{
var statesSet = new HashSet(states.Select(s => (int)s));
if (!statesSet.All(s => ((TransferStates)s).HasFlag(TransferStates.Completed)))
{
throw new ArgumentException($"Each state must include {TransferStates.Completed}", nameof(states));
}
try
{
using var context = ContextFactory.CreateDbContext();
var cutoffDateTime = DateTime.UtcNow.AddMinutes(-age);
var pruned = context.Transfers
.Where(t => t.Direction == TransferDirection.Download)
.Where(t => !t.Removed)
.Where(t => t.EndedAt.HasValue && t.EndedAt.Value < cutoffDateTime)
.Where(t => statesSet.Contains((int)t.State))
.ExecuteUpdate(r => r.SetProperty(c => c.Removed, true));
if (pruned > 0)
{
Log.Debug("Pruned {Count} expired downloads with states {States}", pruned, statesSet);
}
return pruned;
}
catch (Exception ex)
{
Log.Error(ex, "Failed to prune downloads: {Message}", ex.Message);
throw;
}
}
///
/// Removes the completed download matching the specified .
///
/// This is a soft delete; the record is retained for historical retrieval.
/// The unique identifier of the download.
/// A value indicating whether the record was removed.
public bool Remove(Guid id)
{
return Remove(t => t.Id == id) > 0;
}
///
/// Removes all completed downloads matching the specified .
///
/// This is a soft delete; the record is retained for historical retrieval.
/// The expression used to match downloads.
/// The number of records removed.
public int Remove(Expression> expression)
{
try
{
using var context = ContextFactory.CreateDbContext();
var count = context.Transfers
.Where(t => t.Direction == TransferDirection.Download)
.Where(t => TransferStateCategories.Completed.Contains(t.State))
.Where(expression)
.ExecuteUpdate(r => r.SetProperty(c => c.Removed, true));
Log.Debug("Removed {Count} downloads by expression", count);
return count;
}
catch (Exception ex)
{
Log.Error(ex, "Failed to remove downloads by expression: {Message}", ex.Message);
throw;
}
}
///
/// Cancels the download matching the specified , if it is in progress.
///
/// The unique identifier for the download.
/// A value indicating whether the download was successfully cancelled.
public bool TryCancel(Guid id)
{
// if the cancellation token is still in the dictionary, calling Cancel() on it _should_
// cause the transfer operation to fail with an OperationCancelled exception and set the state
// of the transfer to Cancelled. _should_!
if (CancellationTokens.TryRemove(id, out var cts))
{
cts.Cancel(swallowObjectDisposedException: true);
return true;
}
/*
if the cancellation token couldn't be found in the dictionary, either:
1. the transfer completed already
2. something went wrong and the record is 'stuck'
see if we can find the record, and if it's *NOT* completed, cancel it. otherwise,
leave it alone.
*/
var t = Find(t => t.Id == id);
if (t is not null && !t.State.HasFlag(TransferStates.Completed))
{
t.EndedAt = DateTime.UtcNow;
t.State = TransferStates.Completed | TransferStates.Cancelled;
t.Exception = new OperationCanceledException().Message;
Update(t);
return true;
}
// this transfer id didn't have a cancellation token registered, and we couldn't find it in the dictionary
return false;
}
///
/// Fails the download matching the specified with the specified ,
/// and sets the final state accordingly.
///
///
/// This method is designed to be idempotent, meaning subsequent calls for a given transfer shouldn't change
/// the EndedAt or Exception properties if they have already been set. If the transfer State already includes
/// the terminal Completed flag, it is unchanged.
///
/// The unique identifier for the download.
/// The exception that caused the failure.
/// A value indicating whether the download was successfully failed.
public bool TryFail(Guid id, Exception exception)
{
var t = Find(t => t.Id == id);
if (t is null)
{
return false;
}
t.EndedAt ??= DateTime.UtcNow;
// Retry.Do() wraps failures in an AggregateException; use the most recent so that the state reflects what happened
if (exception is AggregateException aggregate && aggregate.InnerExceptions.Count > 0)
{
exception = aggregate.InnerExceptions.Last();
}
// Soulseek.NET will include the filename and username in some messages; this is useful for many things but not tracking
// exceptions in a database. when we encounter one of these, drop the first segment.
var m = exception.Message;
t.Exception ??= m.Contains(':') ? m.Substring(m.IndexOf(':') + 1).Trim() : m;
if (!t.State.HasFlag(TransferStates.Completed))
{
t.State = TransferStates.Completed | exception switch
{
OperationCanceledException => TransferStates.Cancelled,
TimeoutException => TransferStates.TimedOut,
TransferRejectedException => TransferStates.Rejected,
_ => TransferStates.Errored,
};
}
try
{
Update(t);
return true;
}
catch (Exception ex)
{
Log.Error(ex, "Failed to update database: {Message}", ex.Message);
return false;
}
finally
{
CancellationTokens.TryRemove(id, out var cts);
cts?.TryDispose();
}
}
///
/// Synchronously updates the specified .
///
/// The transfer to update.
public void Update(Transfer transfer)
{
using var context = ContextFactory.CreateDbContext();
context.Update(transfer);
context.SaveChanges();
}
protected virtual void EmitMetrics()
{
void EmitQueuedMetrics()
{
var queued = Client.Downloads.Where(u => u.State.HasFlag(TransferStates.Queued));
Telemetry.Metrics.Transfers.Downloads.Queued.Users
.Set(queued.Select(u => u.Username).Distinct().Count());
Telemetry.Metrics.Transfers.Downloads.Queued.Files
.Set(queued.Count());
Telemetry.Metrics.Transfers.Downloads.Queued.Bytes
.Set(queued.Sum(q => q.Size));
}
void EmitInProgressMetrics()
{
var inProgress = Client.Downloads.Where(u => u.State == TransferStates.InProgress);
Telemetry.Metrics.Transfers.Downloads.InProgress.Users
.Set(inProgress.Select(u => u.Username).Distinct().Count());
Telemetry.Metrics.Transfers.Downloads.InProgress.Files
.Set(inProgress.Count());
Telemetry.Metrics.Transfers.Downloads.InProgress.Bytes
.Set(inProgress.Sum(u => u.Size));
if (inProgress.Any())
{
Telemetry.Metrics.Transfers.Downloads.InProgress.CurrentTotalSpeed
.Update(inProgress.Sum(u => u.AverageSpeed));
Telemetry.Metrics.Transfers.Downloads.InProgress.CurrentAverageSpeed
.Update(inProgress.Any() ? inProgress.Average(u => u.AverageSpeed) : 0);
}
else
{
Telemetry.Metrics.Transfers.Downloads.InProgress.CurrentTotalSpeed.Reset();
Telemetry.Metrics.Transfers.Downloads.InProgress.CurrentAverageSpeed.Reset();
}
}
Telemetry.Metrics.Update(() =>
{
EmitQueuedMetrics();
EmitInProgressMetrics();
});
}
///
/// Downloads the specified enqueued from the remote user.
///
/// The Transfer to download.
/// An optional delegate to invoke the transfer state changes.
/// The token to monitor for cancellation.
/// The operation context.
/// Thrown if the specified Transfer is null.
/// Thrown if the specified Transfer ID can't be found in the database.
/// Thrown if the specified Transfer is not in the Queued | Locally state.
/// Thrown if a download matching the username and filename is already tracked by Soulseek.NET.
private async Task DownloadAsync(Transfer transfer, Action stateChanged = null, CancellationToken cancellationToken = default)
{
if (transfer is null)
{
throw new ArgumentNullException(nameof(transfer), "A valid, enqueued Transfer is required");
}
// grab the latest from the database; this may have been sitting behind a semaphore or something
transfer = Find(t => t.Id == transfer.Id)
?? throw new TransferNotFoundException($"Transfer with ID {transfer.Id} not found");
if (transfer.State != (TransferStates.Queued | TransferStates.Locally))
{
throw new InvalidOperationException($"Invalid starting state for download; expected {TransferStates.Queued | TransferStates.Locally}, encountered {transfer.State}");
}
if (Client.Downloads.Any(u => u.Username == transfer.Username && u.Filename == transfer.Filename))
{
throw new DuplicateTransferException("A duplicate download of the same file to the same user is already registered");
}
// there _should_ be a cancellation token for this transfer in the dictionary; if so link it with the one we are given
// (which is probably the same one, harmless if so) to make sure we don't get any wires crossed
CancellationTokens.TryGetValue(transfer.Id, out var cancellationTokenSource);
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);
var stateHistory = new List();
DateTime lastReportedAverageSpeed = default;
try
{
using var rateLimiter = new RateLimiter(250, concurrencyLimit: 1, flushOnDispose: true);
var topts = new TransferOptions(
stateChanged: (args) =>
{
try
{
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)
{
Log.Debug("Download update of {Filename} from {Username} not persisted; app is shutting down", transfer.Filename, transfer.Username);
return;
}
transfer = transfer.WithSoulseekTransfer(args.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;
}
Telemetry.Metrics.Update(() =>
{
if (!TransferStateCategories.Queued.Contains(args.PreviousState) && TransferStateCategories.Queued.Contains(transfer.State))
{
Telemetry.Metrics.Transfers.Downloads.Queued.Files.Inc(1);
Telemetry.Metrics.Transfers.Downloads.Queued.Bytes.Inc(transfer.Size);
}
if (!TransferStateCategories.InProgress.Contains(args.PreviousState) && TransferStateCategories.InProgress.Contains(transfer.State))
{
Telemetry.Metrics.Transfers.Downloads.Queued.Files.Dec(1);
Telemetry.Metrics.Transfers.Downloads.Queued.Bytes.Dec(transfer.Size);
Telemetry.Metrics.Transfers.Downloads.InProgress.Files.Inc(1);
Telemetry.Metrics.Transfers.Downloads.InProgress.Bytes.Inc(transfer.Size);
}
});
stateHistory.Add(transfer.State);
// 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 (args.Transfer.State.HasFlag(TransferStates.Completed)
&& !args.Transfer.State.HasFlag(TransferStates.Succeeded)
&& transfer.Attempts < retryOptions.Attempts)
{
transfer.State = TransferStates.Queued | TransferStates.Locally;
}
// todo: broadcast
SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: cancellationToken);
}
finally
{
stateChanged?.Invoke(transfer);
}
},
progressUpdated: (args) => rateLimiter.Invoke(() =>
{
// don't do anything unless the `transfer` within the outer scope is in the
// InProgress state; this will help prevent out-of-band updates that are sometimes
// being made after the transfer is completed, causing them to appear 'stuck'
if (transfer.State == TransferStates.InProgress)
{
// don't wait for the semaphore; if a previous progress update is still hanging, don't make
// the problem worse. this will result in fewer/jumpy updates on systems with slow filesystems
// but the alternative is to continue to stack slow writes on top of one another
if (updateSyncRoot.Wait(millisecondsTimeout: 0, cancellationToken: cancellationToken))
{
try
{
// update only the properties that we expect to change between progress updates
// this helps prevent this update from 'stepping' on other updates
transfer.BytesTransferred = args.Transfer.BytesTransferred;
transfer.AverageSpeed = args.Transfer.AverageSpeed;
using var context = ContextFactory.CreateDbContext();
context.Transfers.Where(t => t.Id == transfer.Id).ExecuteUpdate(setter => setter
.SetProperty(t => t.BytesTransferred, transfer.BytesTransferred)
.SetProperty(t => t.AverageSpeed, transfer.AverageSpeed));
// progress is reported at 4x the speed (250ms) that the transfer's average speed is calculated (1000ms)
// the transfer's speed is also zero until it has enough data to compute the EMA, so throw both
// repeated and zero values out
var now = DateTime.UtcNow;
if (transfer.AverageSpeed > 0 && now >= lastReportedAverageSpeed.AddMilliseconds(1000))
{
Telemetry.Metrics.Update(() =>
{
Telemetry.Metrics.Transfers.Downloads.InProgress.CurrentAverageSpeed.Update(transfer.AverageSpeed);
}, cancellationToken);
lastReportedAverageSpeed = now;
}
}
finally
{
updateSyncRoot.Release();
}
}
else
{
Log.Debug("Skipped progress update of {Filename} from {Username} {BytesTransferred}/{TotalBytes}; previous update still pending", transfer.Filename, transfer.Username, args.Transfer.BytesTransferred, args.Transfer.Size);
}
}
}),
disposeOutputStreamOnCompletion: true);
UnixFileMode? unixFileMode = !string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Transfers.Download.Destination.Permissions.Mode)
? OptionsMonitor.CurrentValue.Transfers.Download.Destination.Permissions.Mode.ToUnixFileMode()
: null;
/*
store incomplete files under a username subdirectory to prevent collisions between users and to make
it safe to resume partial downloads without risking picking up an unrelated file.
we're going to store the file as:
///
so, a remote file 'C:\Music\Public_Domain\Foo\Bar\Baz.ext' from user 'FooBar' becomes:
linux: incomplete/C:/FooBar/Music/Public_Domain/Foo/Bar/Baz.ext
windows: incomplete\C_\FooBar\Music\Public_Domain\Foo\Bar\Baz.ext
slashes are normalized to the current OS and any invalid characters are replaced with an underscore, _.
this mitigates the risk of an improper partial resume to a great extent.
if the remote file changes size between attempts, Soulseek.NET's DownloadAsync() will throw because
the size we send originates from the original file, and there will be a mismatch.
the only remaining risk is in a case where the file contents have changed but the size remains the same.
the resulting file will be corrupted in that case, and there's nothing we can really do about it. users
that are concerned about this (extremely unlikely) case should configure slskd to always overwrite
partial files.
*/
var incompleteDirectory = OptionsMonitor.CurrentValue.Directories.Incomplete;
var sanitizedUsername = FileSafety.SanitizePathSegment(transfer.Username);
var sanitizedFilename = FileSafety.GetFileNameSafely(transfer.Filename, sanitize: true);
var sanitizedRemotePath = FileSafety.GetDirectoryNameSafely(transfer.Filename, sanitize: true) ?? string.Empty;
var incompleteFilename = FileSafety.CombineSafely(incompleteDirectory, sanitizedUsername, sanitizedRemotePath, sanitizedFilename);
Log.Debug("Incomplete file for {Filename} from {Username} will be: {IncompleteFilename}", FileSafety.GetFileNameSafely(transfer.Filename), transfer.Username, incompleteFilename);
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.Partial.ToEnum();
var shouldResume = false;
var startOffset = 0L;
if (incompleteFileInfo.Exists && incompleteFileInfo.Length > 0)
{
if (incompleteStrategy == RetryPartialStrategy.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
&& ex is not DuplicateTransferException
&& ex is not TransferSizeMismatchException,
onRetry: (attempts, delay) =>
{
// an attempt failed and we have decided that we're going to retry instead of letting it throw
// we *MAY* have incremented queued/in progress metrics as part of the previous attempt
var mostRecentQueuedOrInProgressState = stateHistory
.LastOrDefault(s => TransferStateCategories.InProgress.Contains(s) || TransferStateCategories.Queued.Contains(s));
Telemetry.Metrics.Update(() =>
{
if (TransferStateCategories.InProgress.Contains(mostRecentQueuedOrInProgressState))
{
Telemetry.Metrics.Transfers.Downloads.InProgress.Files.Dec(1);
Telemetry.Metrics.Transfers.Downloads.InProgress.Bytes.Dec(transfer.Size);
}
else if (TransferStateCategories.Queued.Contains(mostRecentQueuedOrInProgressState))
{
Telemetry.Metrics.Transfers.Downloads.Queued.Files.Dec(1);
Telemetry.Metrics.Transfers.Downloads.Queued.Bytes.Dec(transfer.Size);
}
});
// reset the history to make detection logic above easier and more accurate
Log.Debug("Previous attempt to download {Filename} from user {Username} completed with states: {@States}", FileSafety.GetFileNameSafely(transfer.Filename), transfer.Username, stateHistory);
stateHistory = [];
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);
// explicitly dispose the rate limiter to prevent updates from it beyond this point, and in doing so we
// flush any pending update, _probably_ pushing the state of the transfer back to InProgress
rateLimiter.Dispose();
// copy the completed transfer that was returned from Soulseek.NET in a terminal, fully updated state
// over the top of the transfer record, then persist it
transfer = transfer.WithSoulseekTransfer(completedTransfer);
// todo: broadcast to signalr hub
SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: CancellationToken.None);
Telemetry.Metrics.Update(() =>
{
Telemetry.Metrics.Transfers.Downloads.Completed.Succeeded.Inc(1);
Telemetry.Metrics.Transfers.Downloads.Completed.Bytes.Inc(transfer.BytesTransferred);
Telemetry.Metrics.Transfers.Downloads.Completed.AverageSpeed.Observe(transfer.AverageSpeed);
}, cancellationToken);
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
users have a lot of strong opinions about this!
the destination is always rooted in the configured download directory. we derive the subdirectory
for this file based on either the Destination property defined for the Batch that contains this transfer,
or by applying replacements to the user's configured Destination.Subdirectory string.
what we get back will be a relative path (or perhaps an empty string if that's what the user wanted)
that has sanitized and checked for safety against traversal
*/
var subdirectory = await DeriveDestination(transfer);
var destinationDirectory = FileSafety.CombineSafely(OptionsMonitor.CurrentValue.Directories.Downloads, subdirectory);
var existsStrategy = OptionsMonitor.CurrentValue.Transfers.Download.Destination.Exists.ToEnum();
Log.Debug("Destination directory for {Filename}: {Destination}", transfer.Filename, destinationDirectory);
var finalFilename = Files.MoveFile(
sourceFilename: incompleteFilename,
destinationDirectory: destinationDirectory,
unixFileMode: unixFileMode,
overwrite: existsStrategy == DestinationExistsStrategy.Overwrite,
deleteSourceDirectoryIfEmptyAfterMove: true);
Log.Information("Moved file {Filename} from {Username} from {Incomplete} to {Destination}", FileSafety.GetFileNameSafely(transfer.Filename), transfer.Username, incompleteFilename, finalFilename);
if (OptionsMonitor.CurrentValue.Relay.Enabled)
{
_ = Relay.NotifyFileDownloadCompleteAsync(finalFilename);
}
try
{
// begin post-processing tasks; the file is downloaded, it has been removed from the client's download dictionary,
// and the file has been moved from the incomplete directory to the downloads directory
Log.Debug("Running post-download logic for {Filename} from {Username}", transfer.Filename, transfer.Username);
EventBus.Raise(new DownloadFileCompleteEvent
{
Timestamp = transfer.EndedAt.Value,
LocalFilename = finalFilename,
RemoteFilename = transfer.Filename,
Transfer = transfer,
});
// try to figure out if this file is the last of a directory, and if so, raise the associated
// event. this can be tricky because we want to be sure that this is the last file in this specific
// directory, excluding any pending downloads in a subdirectory.
var remoteDirectorySeparator = transfer.Filename.GuessDirectorySeparator();
var remoteDirectoryName = transfer.Filename.GetDirectoryName(directorySeparator: remoteDirectorySeparator);
var pendingDownloadsInDirectory = Client.Downloads
.Where(t => t.Username == transfer.Username)
.Where(t => t.Filename.GetDirectoryName(directorySeparator: remoteDirectorySeparator) == remoteDirectoryName);
if (!pendingDownloadsInDirectory.Any())
{
EventBus.Raise(new DownloadDirectoryCompleteEvent
{
Timestamp = transfer.EndedAt.Value,
Username = transfer.Username,
LocalDirectoryName = destinationDirectory,
RemoteDirectoryName = remoteDirectoryName,
});
}
if (OptionsMonitor.CurrentValue.Integrations.Ftp.Enabled)
{
_ = FTP.UploadAsync(finalFilename);
}
Log.Debug("Completed post-download logic for {Filename} from {Username} successfully", transfer.Filename, transfer.Username);
}
catch (Exception ex)
{
// log, but don't throw. the file ended up in the download folder and is complete; if we throw it looks like it didn't complete
// todo: add a visual indicator/new state for Transfers that indicate this state. or move all of this logic out and handle it via events
Log.Error(ex, "Failed to run post-download processes for {Filename} from {Username}: {Message}", transfer.Filename, transfer.Username, ex.Message);
}
Log.Information("Download of {Filename} from user {Username} completed successfully", transfer.Filename, transfer.Username);
return transfer;
}
catch (Exception ex) when (ex is OperationCanceledException || ex is TimeoutException)
{
Log.Error(ex, "Download of {Filename} from user {Username} failed: {Message}", transfer.Filename, transfer.Username, ex.Message);
SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: CancellationToken.None);
TryFail(transfer.Id, exception: ex);
// todo: broadcast transfer state to a hub
Telemetry.Metrics.Update(() =>
{
Telemetry.Metrics.Transfers.Downloads.Completed.Failed.Inc(1);
}, cancellationToken);
throw;
}
catch (Exception ex)
{
Log.Error(ex, "Download of {Filename} from user {Username} failed: {Message}", transfer.Filename, transfer.Username, ex.Message);
SynchronizedUpdate(transfer, semaphore: updateSyncRoot, cancellationToken: CancellationToken.None);
TryFail(transfer.Id, exception: ex);
// todo: broadcast transfer state to a hub
Telemetry.Metrics.Update(() =>
{
Telemetry.Metrics.Transfers.Downloads.Completed.Failed.Inc(1);
}, cancellationToken);
throw;
}
finally
{
Log.Debug("Download of {Filename} from user {Username} completed with states: {@States}", FileSafety.GetFileNameSafely(transfer.Filename), transfer.Username, stateHistory);
// figure out the most recent state that was either InProgress or Queued so that we can decrement the count and bytes
// for transfers that succeed this will be InProgress, for transfers that never started this will be Queued (cancelled or something)
// state will almost certainly transition to errored or completed before we get here, so we can't just take the last state
var mostRecentQueuedOrInProgressState = stateHistory
.LastOrDefault(s => TransferStateCategories.InProgress.Contains(s) || TransferStateCategories.Queued.Contains(s));
Telemetry.Metrics.Update(() =>
{
if (TransferStateCategories.InProgress.Contains(mostRecentQueuedOrInProgressState) && Telemetry.Metrics.Transfers.Downloads.InProgress.Files.Value > 0)
{
// if the transfer was ever in progress at any time, we decrement because we should have incremented on that transition
Telemetry.Metrics.Transfers.Downloads.InProgress.Files.Dec(1);
Telemetry.Metrics.Transfers.Downloads.InProgress.Bytes.Dec(transfer.Size);
}
else if (TransferStateCategories.Queued.Contains(mostRecentQueuedOrInProgressState) && Telemetry.Metrics.Transfers.Downloads.Queued.Files.Value > 0)
{
// if the transfer never transitioned to in progress but it was queued at any point, decrement queued
Telemetry.Metrics.Transfers.Downloads.Queued.Files.Dec(1);
Telemetry.Metrics.Transfers.Downloads.Queued.Bytes.Dec(transfer.Size);
}
}, cancellationToken);
if (CancellationTokens.TryRemove(transfer.Id, out var storedCancellationTokenSource))
{
storedCancellationTokenSource?.Dispose();
}
}
}
private void SynchronizedUpdate(Transfer transfer, SemaphoreSlim semaphore, CancellationToken cancellationToken = default)
{
semaphore.Wait(cancellationToken);
try
{
Update(transfer);
}
finally
{
semaphore.Release();
}
}
private async Task CleanupEnqueueSemaphoresAsync()
{
if (await EnqueueSemaphoreSyncRoot.WaitAsync(0).ConfigureAwait(false))
{
try
{
foreach (var kvp in EnqueueSemaphores)
{
if (await kvp.Value.WaitAsync(0).ConfigureAwait(false))
{
EnqueueSemaphores.TryRemove(kvp.Key, out var removed);
removed.Dispose();
Log.Debug("Cleaned up enqueue semaphore for {Key}", kvp.Key);
}
}
}
finally
{
EnqueueSemaphoreSyncRoot.Release();
}
}
}
}
}