// // ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ // ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ // █__ --█ █__ --█ ◄█ - █ // █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ // ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ // │ 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 slskd.Files; using Soulseek; namespace slskd.Transfers.Uploads { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Query; using Serilog; using slskd.Events; using slskd.Relay; using slskd.Shares; using slskd.Users; /// /// Manages uploads. /// public interface IUploadService { /// /// Gets the upload governor. /// IUploadGovernor Governor { get; } /// /// Gets the upload queue. /// IUploadQueue Queue { get; } /// /// Adds the specified . Supersedes any existing record for the same file and username. /// /// This should generally not be called; use instead. /// void AddOrSupersede(Transfer transfer); /// /// Enqueues the requested file. /// /// The username of the requesting user. /// The local filename of the requested file. /// The token to monitor for cancellation. /// The operation context. Task EnqueueAsync(string username, string filename, CancellationToken cancellationToken = default); /// /// Uploads the specified enqueued to the requesting user. /// /// The Transfer to upload. /// 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 an upload matching the username and filename is already tracked by Soulseek.NET. /// Thrown if the specified file can't be found on disk. Task UploadAsync(Transfer transfer, CancellationToken cancellationToken = default); /// /// Finds a single upload matching the specified . /// /// The unique identifier of the upload. /// The found transfer, or default if not found. Transfer Find(Guid id); /// /// Gets upload statistics for the specified . /// /// The username of the user. /// An optional timestamp representing the current time in UTC. /// The gathered statistics. UserUploadStatistics GetUserStatistics(string username, DateTime? utcNow = null); /// /// Returns a list of all uploads matching the specified . /// /// An expression used to match uploads. /// A value indicating whether to include uploads that have been removed previously. /// The list of uploads matching the specified expression, or all uploads if no expression is specified. List List(Expression> expression, bool includeRemoved); /// /// Removes uploads older than the specified . /// /// The age after which uploads are eligible for pruning, in minutes. /// One or more states by which uploads are filtered for pruning. /// The number of pruned uploads. int Prune(int age, params TransferStates[] states); /// /// Returns a list of all uploads matching the specified , projected to type . /// /// The Type of the returned projection. /// The query expression. /// A value indicating whether to include uploads that have been removed previously. /// The list of uploads matching the specified query. List Query(Func, IQueryable> query, bool includeRemoved = false); /// /// Removes the completed upload matching the specified . /// /// This is a soft delete; the record is retained for historical retrieval. /// The unique identifier of the upload. /// A value indicating whether the record was removed. bool Remove(Guid id); /// /// Removes all completed uploads matching the specified . /// /// This is a soft delete; the record is retained for historical retrieval. /// The expression used to match uploads. /// The number of records removed. int Remove(Expression> expression); /// /// Cancels the upload matching the specified , if it is in progress. /// /// The unique identifier for the upload. /// A value indicating whether the upload was successfully cancelled. bool TryCancel(Guid id); /// /// Fails the upload 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 upload. /// The exception that caused the failure. /// A value indicating whether the upload was successfully failed. bool TryFail(Guid id, Exception exception); /// /// Synchronously updates the specified . /// /// The transfer to update. void Update(Transfer transfer); } /// /// Manages uploads. /// public class UploadService : IUploadService { public UploadService( FileService fileService, IUserService userService, ISoulseekClient soulseekClient, IOptionsMonitor optionsMonitor, IShareService shareService, IRelayService relayService, IDbContextFactory contextFactory, EventBus eventBus) { Files = fileService; Users = userService; Client = soulseekClient; Shares = shareService; Relay = relayService; ContextFactory = contextFactory; OptionsMonitor = optionsMonitor; EventBus = eventBus; Governor = new UploadGovernor(userService, optionsMonitor); Queue = new UploadQueue(userService, optionsMonitor); Clock.EveryFiveSeconds += (_, _) => Task.Run(() => EmitMetrics()); } /// /// Gets the upload governor. /// public IUploadGovernor Governor { get; init; } /// /// Gets the upload queue. /// public IUploadQueue Queue { get; init; } private FileService Files { get; } private ConcurrentDictionary CancellationTokens { get; } = new ConcurrentDictionary(); private ISoulseekClient Client { get; set; } private IDbContextFactory ContextFactory { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); private IOptionsMonitor OptionsMonitor { get; } private IRelayService Relay { get; } private IShareService Shares { get; set; } private IUserService Users { get; set; } private EventBus EventBus { get; } private ConcurrentDictionary Locks { get; } = new(); /// /// Adds the specified . Supersedes any existing record for the same file and username. /// /// This should generally not be called; use instead. /// public void AddOrSupersede(Transfer transfer) { using var context = ContextFactory.CreateDbContext(); var existing = context.Transfers .Where(t => t.Direction == TransferDirection.Upload) .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(); } /// /// Uploads the specified enqueued to the requesting user. /// /// The Transfer to upload. /// 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 an upload matching the username and filename is already tracked by Soulseek.NET. /// Thrown if the specified file can't be found on disk. public async Task UploadAsync(Transfer transfer, CancellationToken cancellationToken = default) { var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); var syncRoot = new SemaphoreSlim(1, 1); string host = default; string localFilename = default; long localFileLength = default; var stateHistory = new List(); DateTime lastReportedAverageSpeed = default; var lockName = $"{nameof(UploadAsync)}:{transfer.Username}:{transfer.Filename}"; if (!Locks.TryAdd(lockName, true)) { Log.Debug("Ignoring concurrent invocation; lock {LockName} already held", lockName); return null; } /* from this point forward, any exit from this method MUST result in an update to the Transfer record in the database that sets EndedAt and ensures that the State property includes the Completed flag failure to do so means records will get "stuck" in the database/on the UI additionally, any acquired locks/semaphores must be released, including (and most importantly) the queue slot */ try { Log.Debug("Acquired lock {LockName}", lockName); /* fetch an updated copy of the transfer record from the database; now that we are locked, we *should* have exclusive access to this record we're not using DbContext and tracked changes here because we don't want to hold a connection open for the duration of the upload */ transfer = Find(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 upload; expected {TransferStates.Queued | TransferStates.Locally}, encountered {transfer.State}"); } /* Soulseek.NET keeps an internal dictionary of all transfers for the duration of the transfer logic; check that list to see if there's already an instance of this upload in it, just in case we've gotten out of sync somehow */ if (Client.Uploads.Any(u => u.Username == transfer.Username && u.Filename == transfer.Filename)) { throw new DuplicateTransferException("A duplicate upload of the same file to the same user is already registered"); } // users with uploads must be watched so that we can keep informed of their online status, privileges, and // statistics. this is so that we can accurately determine their effective group. try { if (!Users.IsWatched(transfer.Username)) { await Users.WatchAsync(transfer.Username); } } catch (Exception ex) { Log.Warning(ex, "Failed to watch user {Username}", transfer.Username); } Log.Information("Initializing upload of {Filename} to {Username}", transfer.Filename, transfer.Username); // locate the file on disk. we checked this once already when enqueueing, but it may have moved since // can throw NotFoundException (host, localFilename, localFileLength) = await ResolveFileInfoAsync(remoteFilename: transfer.Filename); using var rateLimiter = new RateLimiter(250, concurrencyLimit: 1, flushOnDispose: true); var topts = new TransferOptions( stateChanged: (args) => { Log.Debug("Upload of {Filename} to user {Username} changed state from {Previous} to {New}", localFilename, 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("Upload update of {Filename} to {Username} not persisted; app is shutting down", transfer.Filename, transfer.Username); return; } transfer = transfer.WithSoulseekTransfer(args.Transfer); Telemetry.Metrics.Update(() => { if (!TransferStateCategories.Queued.Contains(args.PreviousState) && TransferStateCategories.Queued.Contains(transfer.State)) { Telemetry.Metrics.Transfers.Uploads.Queued.Files.Inc(1); Telemetry.Metrics.Transfers.Uploads.Queued.Bytes.Inc(transfer.Size); } if (!TransferStateCategories.InProgress.Contains(args.PreviousState) && TransferStateCategories.InProgress.Contains(transfer.State)) { Telemetry.Metrics.Transfers.Uploads.Queued.Files.Dec(1); Telemetry.Metrics.Transfers.Uploads.Queued.Bytes.Dec(transfer.Size); Telemetry.Metrics.Transfers.Uploads.InProgress.Files.Inc(1); Telemetry.Metrics.Transfers.Uploads.InProgress.Bytes.Inc(transfer.Size); } }, cancellationToken); stateHistory.Add(transfer.State); // todo: broadcast SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: cts.Token); }, 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 (syncRoot.Wait(millisecondsTimeout: 0, cts.Token)) { 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.Uploads.InProgress.CurrentAverageSpeed.Update(transfer.AverageSpeed); }, cancellationToken); lastReportedAverageSpeed = now; } } finally { syncRoot.Release(); } } else { Log.Debug("Skipped progress update of {Filename} to {Username} {BytesTransferred}/{TotalBytes}; previous update still pending", transfer.Filename, transfer.Username, args.Transfer.BytesTransferred, args.Transfer.Size); } } }), seekInputStreamAutomatically: false, disposeInputStreamOnCompletion: true, // note: don't set this to false! governor: (tx, req, ct) => Governor.GetBytesAsync(tx.Username, req, ct), reporter: (tx, att, grant, act) => Governor.ReturnBytes(tx.Username, att, grant, act), slotAwaiter: (tx, ct) => Queue.AwaitStartAsync(transfer, ct), slotReleased: (tx) => Queue.Complete(transfer)); // register the cancellation token CancellationTokens.TryAdd(transfer.Id, cts); // add the transfer to the UploadQueue so that it can become eligible for selection Queue.Enqueue(transfer); transfer.EnqueuedAt = DateTime.UtcNow; SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: cts.Token); Soulseek.Transfer completedTransfer; if (host == Program.LocalHostName) { completedTransfer = await Client.UploadAsync( username: transfer.Username, remoteFilename: transfer.Filename, size: localFileLength, inputStreamFactory: (startOffset) => { #pragma warning disable S2930 // "IDisposables" should be disposed // disposeInputStreamOnCompletion takes care of this var stream = new FileStream(localFilename, FileMode.Open, FileAccess.Read); #pragma warning restore S2930 // "IDisposables" should be disposed stream.Seek(startOffset, SeekOrigin.Begin); return Task.FromResult((Stream)stream); }, options: topts, cancellationToken: cts.Token); } else { completedTransfer = await Client.UploadAsync( username: transfer.Username, remoteFilename: transfer.Filename, size: localFileLength, inputStreamFactory: (startOffset) => Relay.GetFileStreamAsync(agentName: host, filename: transfer.Filename, startOffset, id: transfer.Id), options: topts, cancellationToken: cts.Token); Relay.TryCloseFileStream(host, id: transfer.Id); } // explicitly dispose the rate limiter to prevent updates from it beyond this point, and in doing so we // flushe 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 SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); Telemetry.Metrics.Update(() => { Telemetry.Metrics.Transfers.Uploads.Completed.Succeeded.Inc(1); Telemetry.Metrics.Transfers.Uploads.Completed.Bytes.Inc(transfer.BytesTransferred); Telemetry.Metrics.Transfers.Uploads.Completed.AverageSpeed.Observe(transfer.AverageSpeed); }, cancellationToken); EventBus.Raise(new UploadFileCompleteEvent { Timestamp = transfer.EndedAt.Value, LocalFilename = localFilename, RemoteFilename = transfer.Filename, Transfer = transfer, }); return transfer; } catch (NotFoundException ex) { Log.Error(ex, "Upload of {Filename} to user {Username} failed: {Message}", transfer.Filename, transfer.Username, ex.Message); SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); TryFail(transfer.Id, "File could not be found", TransferStates.Completed | TransferStates.Aborted); // todo: broadcast transfer state to a hub Telemetry.Metrics.Update(() => { Telemetry.Metrics.Transfers.Uploads.Completed.Failed.Inc(1); }, cancellationToken); throw; } catch (Exception ex) when (ex is OperationCanceledException || ex is TimeoutException) { Log.Error(ex, "Upload of {Filename} to user {Username} failed: {Message}", transfer.Filename, transfer.Username, ex.Message); SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); TryFail(transfer.Id, exception: ex); // todo: broadcast transfer state to a hub Telemetry.Metrics.Update(() => { Telemetry.Metrics.Transfers.Uploads.Completed.Failed.Inc(1); }, cancellationToken); throw; } catch (Exception ex) { Log.Error(ex, "Upload of {Filename} to user {Username} failed: {Message}", transfer.Filename, transfer.Username, ex.Message); SynchronizedUpdate(transfer, semaphore: syncRoot, cancellationToken: CancellationToken.None); TryFail(transfer.Id, exception: ex); // todo: broadcast transfer state to a hub Telemetry.Metrics.Update(() => { Telemetry.Metrics.Transfers.Uploads.Completed.Failed.Inc(1); }, cancellationToken); throw; } finally { Log.Debug("Upload of {Filename} to 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.Uploads.InProgress.Files.Value > 0) { Telemetry.Metrics.Transfers.Uploads.InProgress.Files.Dec(1); Telemetry.Metrics.Transfers.Uploads.InProgress.Bytes.Dec(transfer.Size); } else if (TransferStateCategories.Queued.Contains(mostRecentQueuedOrInProgressState) && Telemetry.Metrics.Transfers.Uploads.Queued.Files.Value > 0) { Telemetry.Metrics.Transfers.Uploads.Queued.Files.Dec(1); Telemetry.Metrics.Transfers.Uploads.Queued.Bytes.Dec(transfer.Size); } }, cancellationToken); if (host != Program.LocalHostName) { try { Relay.TryCloseFileStream(host, id: transfer.Id); } catch { // noop } } try { Locks.TryRemove(lockName, out _); Log.Debug("Released lock {LockName}", lockName); CancellationTokens.TryRemove(transfer.Id, out var registeredCts); registeredCts?.TryDispose(); cts?.TryDispose(); // if for some reason this logic exits without the slotReleased delegate and Complete() being invoked, // the file will get stuck in the queue and prevent any further uploads to the user. be extra cautious // and ensure it gets removed Queue.TryComplete(transfer); } catch (Exception ex) { Log.Error(ex, "Failed to finalize upload of {Filename} to {Username}: {Message}", transfer.Filename, transfer.Username, ex.Message); } } } /// /// Enqueues the requested file. /// /// The username of the requesting user. /// The local filename of the requested file. /// The token to monitor for cancellation. /// The operation context. public async Task EnqueueAsync(string username, string filename, CancellationToken cancellationToken = default) { if (string.IsNullOrEmpty(username)) { throw new ArgumentNullException(nameof(username), "Username is required"); } if (string.IsNullOrEmpty(filename)) { throw new ArgumentNullException(nameof(filename), "Filename is required"); } var lockName = $"{nameof(EnqueueAsync)}:{username}:{filename}"; if (!Locks.TryAdd(lockName, true)) { Log.Debug("Ignoring concurrent upload enqueue attempt; lock {LockName} already held", lockName); return null; } Guid id = Guid.NewGuid(); try { Log.Debug("Acquired lock {LockName}", lockName); Log.Information("Upload of {Filename} to {Username} requested", filename, username); using var context = ContextFactory.CreateDbContext(); /* first, get all past uploads to this user for this filename */ var existingRecords = context.Transfers .Where(t => t.Direction == TransferDirection.Upload) .Where(t => t.Username == username) .Where(t => t.Filename == 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! */ if (existingInProgressRecords.Count != 0) { Log.Information("Upload of {Filename} to {Username} is already queued or is in progress (ids: {Ids})", filename, username, string.Join(", ", existingInProgressRecords.Select(t => t.Id))); return null; } /* check the tracked upload 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.Uploads.Any(u => u.Username == username && u.Filename == filename)) { throw new DuplicateTransferException("A duplicate upload of the same file to the same user is already registered"); } /* no existing transfers. next, check to see if they are requesting a file we are sharing we do this after checking the database because database I/O is "cheaper" than disk and potentially network (if we check a relay) */ string host = default; string localFilename = default; long localFileLength = default; try { (host, localFilename, localFileLength) = await ResolveFileInfoAsync(remoteFilename: filename); } catch (NotFoundException) { Log.Information("Upload of {Filename} to {Username} {Rejected}: {Message}", filename, username, "REJECTED", "File not shared."); throw new DownloadEnqueueException($"File not shared."); } Log.Debug("Resolved {Remote} to physical file {Physical} on host '{Host}'", filename, localFilename, host); /* 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.Upload, Filename = filename, // important! use the remote filename Size = localFileLength, 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 upload record of {Filename} to {Username} removed (id: {Id})", filename, username, record.Id); } context.SaveChanges(); Log.Information("Successfully enqueued upload of {Filename} to {Username} (id: {Id})", filename, username, id); // users with uploads must be watched so that we can keep informed of their online status, privileges, and // statistics. this is so that we can accurately determine their effective group. try { if (!Users.IsWatched(username)) { await Users.WatchAsync(username); } } catch (Exception ex) { Log.Warning(ex, "Failed to watch user {Username}", username); } /* schedule the upload immediately 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(() => UploadAsync(transfer)).ContinueWith(task => { if (task.IsCompletedSuccessfully) { Log.Information("Task for upload of {Filename} to {Username} completed successfully", filename, username); return; } /* things that can cause us to arrive here: * file not found (moved, deleted somehow) * transfer record deleted somehow * transfer record updated so that it's no longer in Queued | Locally * Soulseek.NET already tracking an identical upload (slskd <> Soulseek.NET desync) */ Log.Error(task.Exception, "Task for upload of {Filename} to {Username} did not complete successfully: {Error}", filename, username, task.Exception.Message); if (!TryFail(id, task.Exception)) { Log.Error(task.Exception, "Failed to clean up transfer {Id} after failed execution: {Message}", id, task.Exception.Message); } }, cancellationToken); return transfer; } catch (Exception ex) { Log.Error(ex, "Failed to enqueue upload of {Filename} to {Username}: {Message}", filename, username, ex.Message); if (!TryFail(id, exception: ex)) { Log.Error(ex, "Failed to clean up transfer {Id} after failed enqueue: {Message}", id, ex.Message); throw; } throw; } finally { if (Locks.TryRemove(lockName, out _)) { Log.Debug("Released lock {LockName}", lockName); } } } /// /// Finds a single upload matching the specified . /// /// The unique identifier of the upload. /// The found transfer, or default if not found. public Transfer Find(Guid id) { try { return Query(q => q.Where(t => t.Id == id), includeRemoved: true).SingleOrDefault(); } catch (Exception ex) { Log.Error(ex, "Failed to find upload: {Message}", ex.Message); throw; } } /// /// Returns a list of all uploads matching the specified . /// /// An expression used to match uploads. /// A value indicating whether to include uploads that have been removed previously. /// The list of uploads matching the specified expression, or all uploads if no expression is specified. public List List(Expression> expression, bool includeRemoved) { expression ??= t => true; try { return Query(q => q.Where(expression), includeRemoved); } catch (Exception ex) { Log.Error(ex, "Failed to list uploads: {Message}", ex.Message); throw; } } /// /// Returns a list of all uploads matching the specified , projected to type . /// /// The Type of the returned projection. /// The query expression. /// A value indicating whether to include uploads that have been removed previously. /// The list of uploads matching the specified query. public List Query(Func, IQueryable> query, bool includeRemoved = false) { ArgumentNullException.ThrowIfNull(query); try { using var context = ContextFactory.CreateDbContext(); var transfers = context.Transfers .AsNoTracking() .Where(t => t.Direction == TransferDirection.Upload); if (!includeRemoved) { transfers = transfers.Where(t => !t.Removed); } var result = query(transfers); if (result.Provider is not IAsyncQueryProvider) { throw new InvalidOperationException("Query must be fully translatable to SQL; in-memory evaluation is not allowed (remove any AsEnumerable() present in the query)"); } return result.ToList(); } catch (Exception ex) { Log.Error(ex, "Failed to execute upload queury: {Message}", ex.Message); throw; } } /// /// Removes uploads older than the specified . /// /// The age after which uploads are eligible for pruning, in minutes. /// One or more states by which uploads are filtered for pruning. /// The number of pruned uploads. 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.Upload) .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 uploads with states {States}", pruned, statesSet); } return pruned; } catch (Exception ex) { Log.Error(ex, "Failed to prune uploads: {Message}", ex.Message); throw; } } /// /// Removes the completed upload matching the specified . /// /// This is a soft delete; the record is retained for historical retrieval. /// The unique identifier of the upload. /// A value indicating whether the record was removed. public bool Remove(Guid id) { return Remove(t => t.Id == id) > 0; } /// /// Removes all completed uploads matching the specified . /// /// This is a soft delete; the record is retained for historical retrieval. /// The expression used to match uploads. /// 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.Upload) .Where(t => TransferStateCategories.Completed.Contains(t.State)) .Where(expression) .ExecuteUpdate(r => r.SetProperty(c => c.Removed, true)); Log.Debug("Removed {Count} uploads by expression", count); return count; } catch (Exception ex) { Log.Error(ex, "Failed to remove uploads by expression: {Message}", ex.Message); throw; } } /// /// Cancels the upload matching the specified , if it is in progress. /// /// The unique identifier for the upload. /// A value indicating whether the upload was successfully cancelled. public bool TryCancel(Guid id) { if (CancellationTokens.TryRemove(id, out var cts)) { cts.Cancel(swallowObjectDisposedException: true); return true; } return false; } /// /// Fails the upload 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 upload. /// The exception that caused the failure. /// A value indicating whether the upload was successfully failed. public bool TryFail(Guid id, Exception exception) { var state = exception switch { NotFoundException => TransferStates.Aborted, OperationCanceledException => TransferStates.Cancelled, TimeoutException => TransferStates.TimedOut, _ => TransferStates.Errored, }; return TryFail(id, exception.Message, state); } /// /// Synchronously updates the specified . /// /// The transfer to update. public void Update(Transfer transfer) { using var context = ContextFactory.CreateDbContext(); context.Update(transfer); context.SaveChanges(); } /// /// Gets upload statistics for the specified . /// /// The username of the user. /// An optional timestamp representing the current time in UTC. /// The gathered statistics. public UserUploadStatistics GetUserStatistics(string username, DateTime? utcNow = null) { utcNow ??= DateTime.UtcNow; var dailyCutoff = utcNow.Value.AddDays(-1); var weeklyCutoff = utcNow.Value.AddDays(-7); using var context = ContextFactory.CreateDbContext(); var failedStates = TransferStateCategories.Failed.ToList(); var successState = TransferStates.Completed | TransferStates.Succeeded; var stats = context.Transfers .AsNoTracking() .Where(t => t.Username == username) .Where(t => t.Direction == TransferDirection.Upload) .Where(t => t.EndedAt == null || t.StartedAt >= weeklyCutoff) .GroupBy(t => 1) // aggregate everything into one row .Select(g => new UserUploadStatistics { QueuedFiles = g.Count(t => t.EndedAt == null), QueuedBytes = g.Where(t => t.EndedAt == null).Sum(t => (long?)t.Size) ?? 0, // note: this generates some funky json_each() expression under the hood; it's an EF optimization // that helps with optimization of query plans. i've tried expanding this out to force an IN // and there's either no difference, or there's a slight improvement with the json_each method. WeeklyFailedFiles = g.Count(t => t.StartedAt >= weeklyCutoff && failedStates.Contains(t.State)), WeeklySucceededFiles = g.Count(t => t.StartedAt >= weeklyCutoff && t.State == successState), WeeklySucceededBytes = g.Where(t => t.StartedAt >= weeklyCutoff && t.State == successState) .Sum(t => (long?)t.Size) ?? 0, DailyFailedFiles = g.Count(t => t.StartedAt >= dailyCutoff && failedStates.Contains(t.State)), DailySucceededFiles = g.Count(t => t.StartedAt >= dailyCutoff && t.State == successState), DailySucceededBytes = g.Where(t => t.StartedAt >= dailyCutoff && t.State == successState) .Sum(t => (long?)t.Size) ?? 0, }) .FirstOrDefault(); return stats ?? new UserUploadStatistics(); } protected virtual void EmitMetrics() { void EmitQueuedMetrics() { var queued = Client.Uploads.Where(u => u.State.HasFlag(TransferStates.Queued)); Telemetry.Metrics.Transfers.Uploads.Queued.Users .Set(queued.Select(u => u.Username).Distinct().Count()); Telemetry.Metrics.Transfers.Uploads.Queued.Files .Set(queued.Count()); Telemetry.Metrics.Transfers.Uploads.Queued.Bytes .Set(queued.Sum(q => q.Size)); } void EmitInProgressMetrics() { var inProgress = Client.Uploads.Where(u => u.State == TransferStates.InProgress); Telemetry.Metrics.Transfers.Uploads.InProgress.Users .Set(inProgress.Select(u => u.Username).Distinct().Count()); Telemetry.Metrics.Transfers.Uploads.InProgress.Files .Set(inProgress.Count()); Telemetry.Metrics.Transfers.Uploads.InProgress.Bytes .Set(inProgress.Sum(u => u.Size)); if (inProgress.Any()) { Telemetry.Metrics.Transfers.Uploads.InProgress.CurrentTotalSpeed .Update(inProgress.Sum(u => u.AverageSpeed)); Telemetry.Metrics.Transfers.Uploads.InProgress.CurrentAverageSpeed .Update(inProgress.Any() ? inProgress.Average(u => u.AverageSpeed) : 0); } else { Telemetry.Metrics.Transfers.Uploads.InProgress.CurrentTotalSpeed.Reset(); Telemetry.Metrics.Transfers.Uploads.InProgress.CurrentAverageSpeed.Reset(); } } Telemetry.Metrics.Update(() => { EmitQueuedMetrics(); EmitInProgressMetrics(); }); } private bool TryFail(Guid id, string exception, TransferStates state) { var t = Find(id); if (t is null) { return false; } t.EndedAt ??= DateTime.UtcNow; // 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; t.Exception ??= m.Contains(':') ? m.Substring(m.IndexOf(':') + 1).Trim() : m; if (!t.State.HasFlag(TransferStates.Completed)) { t.State = TransferStates.Completed | state; } try { Update(t); return true; } catch (Exception ex) { Log.Error(ex, "Failed to update database: {Message}", ex.Message); return false; } } /// /// Resolves a remote file's location and size from shares and potentially disk. /// /// The file to resolve. /// The resolved host, filename (on disk), and length. /// Thrown if the file can't be located, either in a share or on disk. private async Task<(string Host, string Filename, long Length)> ResolveFileInfoAsync(string remoteFilename) { string host; string filename; long length; /* locate the file and the stored details from shares. the size returned here will be the size the remote client is expecting. throws NotFoundException */ (host, filename, length) = await Shares.ResolveFileAsync(remoteFilename); Log.Debug("Resolved shared file {RemoteFilename} to host {Host} and file {ShareFilename} (length: {ShareLength})", remoteFilename, host, filename, length); /* if the file is hosted locally, do some quick I/O to check to see if the file still exists at the location and of the size stored in the scan. the cost is negligible and this will keep transfers that are doomed to fail out of our queue. */ if (host == Program.LocalHostName) { var info = Files.ResolveFileInfo(filename); // if the file doesn't exist we can't continue; shares have diverged from disk if (!info.Exists) { Shares.RequestScan(); Log.Warning("The shared file '{File}' could not be located on disk. A share scan should be performed", filename); throw new NotFoundException($"The file '{filename}' could not be located on disk. A share scan should be performed."); } // shares have diverged from disk, but we *MIGHT* be able to upload this file, if the remote client // doesn't care that the size is exact. we definitely need to re-scan though. if (info.Length != length) { Log.Warning("The length of shared file '{File}' differs between the share ({ShareSize}) and disk ({DiskSize}). A share scan should be performed", filename, length, info.Length); Shares.RequestScan(); } length = info.Length; } else if (!OptionsMonitor.CurrentValue.Flags.OptimisticRelayFileInfo) { /* if the file is hosted on a relay agent and the user has set the pessimistic flag to true, get the file info from the agent. this was, at one time, the default behavior, but users complained that it caused a lot of timeouts so now it is opt-in. */ var (exists, relayLength) = await Relay.GetFileInfoAsync(agentName: host, remoteFilename); if (!exists || relayLength <= 0) { // todo: force a remote scan throw new NotFoundException($"The file '{remoteFilename}' could not be located on Agent {host}. A share scan should be performed."); } if (relayLength != length) { // todo: force a remote scan Log.Warning("The length of shared file '{File}' on host {Host} differs between the share ({ShareSize}) and disk ({DiskSize}). A share scan should be performed", filename, host, length, relayLength); } length = relayLength; } return (host, filename, length); } private void SynchronizedUpdate(Transfer transfer, SemaphoreSlim semaphore, CancellationToken cancellationToken = default) { semaphore.Wait(cancellationToken); try { Update(transfer); } finally { semaphore.Release(); } } } }