From 3ccd7738f2603a3710138a933694e6584a4f0dc3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 7 Jul 2022 09:33:10 -0500 Subject: updates to reflect new delegate tuple signature --- src/slskd/Transfers/API/Controllers/TransfersController.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src/slskd/Transfers/API/Controllers/TransfersController.cs') diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index ca442fb3..d3dd5518 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -140,13 +140,13 @@ namespace slskd.Transfers.API { Log.Debug("Download of {Filename} from user {Username} changed state from {Previous} to {New}", request.Filename, username, e.PreviousState, e.Transfer.State); - Tracker.AddOrUpdate(e, cts); + Tracker.AddOrUpdate(e.Transfer, cts); if (e.Transfer.State.HasFlag(TransferStates.Queued) || e.Transfer.State == TransferStates.Initializing) { waitUntilEnqueue.TrySetResult(true); } - }, progressUpdated: (e) => Tracker.AddOrUpdate(e, cts)), cts.Token); + }, progressUpdated: (e) => Tracker.AddOrUpdate(e.Transfer, cts)), cts.Token); MoveFile(request.Filename, Options.Directories.Incomplete, Options.Directories.Downloads); -- cgit v1.2.3 From 277f57a2721ed067320c8ef41289cd105c370f48 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 17 Jul 2022 17:21:31 -0500 Subject: use TransferService to enqueue --- .../API/Controllers/TransfersController.cs | 65 ++-------------------- 1 file changed, 4 insertions(+), 61 deletions(-) (limited to 'src/slskd/Transfers/API/Controllers/TransfersController.cs') diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index d3dd5518..985452bb 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -53,14 +53,17 @@ namespace slskd.Transfers.API IOptionsSnapshot options, ISoulseekClient soulseekClient, ITransferTracker tracker, + ITransferService transferService, IFTPService ftpClient) { Client = soulseekClient; Tracker = tracker; Options = options.Value; FTP = ftpClient; + Transfers = transferService; } + private ITransferService Transfers { get; } private Options Options { get; } private ISoulseekClient Client { get; } private ITransferTracker Tracker { get; } @@ -121,71 +124,11 @@ namespace slskd.Transfers.API { try { - Log.Information("Downloading {Count} files from user {Username}", requests.Count(), username); - - Log.Debug("Priming connection for user {Username}", username); - await Client.ConnectToUserAsync(username, invalidateCache: false); - Log.Debug("Connection for user '{Username}' primed", username); - - foreach (var request in requests) - { - Log.Debug("Attempting to enqueue {Filename} from user {Username}", request.Filename, username); - - var waitUntilEnqueue = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - var cts = new CancellationTokenSource(); - - var downloadTask = Task.Run(async () => - { - await Client.DownloadAsync(username, request.Filename, () => GetLocalFileStream(request.Filename, Options.Directories.Incomplete), request.Size, 0, request.Token, new TransferOptions(disposeOutputStreamOnCompletion: true, stateChanged: (e) => - { - Log.Debug("Download of {Filename} from user {Username} changed state from {Previous} to {New}", request.Filename, username, e.PreviousState, e.Transfer.State); - - Tracker.AddOrUpdate(e.Transfer, cts); - - if (e.Transfer.State.HasFlag(TransferStates.Queued) || e.Transfer.State == TransferStates.Initializing) - { - waitUntilEnqueue.TrySetResult(true); - } - }, progressUpdated: (e) => Tracker.AddOrUpdate(e.Transfer, cts)), cts.Token); - - MoveFile(request.Filename, Options.Directories.Incomplete, Options.Directories.Downloads); - - if (Options.Integration.Ftp.Enabled) - { - _ = FTP.UploadAsync(request.Filename.ToLocalFilename(Options.Directories.Downloads)); - } - }); - - // wait until either the waitUntilEnqueue task completes because the download was successfully queued, or the - // downloadTask throws due to an error prior to successfully queueing. - var task = await Task.WhenAny(waitUntilEnqueue.Task, downloadTask); - - if (task == downloadTask) - { - if (downloadTask.Exception is AggregateException) - { - var rejected = downloadTask.Exception?.InnerExceptions.Where(e => e is TransferRejectedException) ?? Enumerable.Empty(); - if (rejected.Any()) - { - Log.Error("Download of {Filename} from {Username} was rejected: {Reason}", request.Filename, username, rejected.First().Message); - return StatusCode(403, rejected.First().Message); - } - } - - Log.Error("Failed to download {Filename} from {Username}: {Message}", request.Filename, username, downloadTask.Exception.Message); - return StatusCode(500, downloadTask.Exception.Message); - } - - Log.Debug("Successfully enqueued {Filename} from user {Username}", request.Filename, username); - } - - // if nothing threw, just return ok. the download will continue waiting in the background. - Log.Information("Successfully enqueued {Count} files from user {Username}", requests.Count(), username); + await Transfers.Downloads.EnqueueAsync(username, requests.Select(r => (r.Filename, r.Size))); return StatusCode(201); } catch (Exception ex) { - Log.Error(ex, "Failed to download file(s) from user {Username}: {Message}", username, ex.Message); return StatusCode(500, ex.Message); } } -- cgit v1.2.3 From ca9eaf057e70a8514f18719a0de10965a23aec51 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 18 Jul 2022 09:43:27 -0500 Subject: use Downloads service for some endpoints --- .../API/Controllers/TransfersController.cs | 69 +++++++++------------- 1 file changed, 29 insertions(+), 40 deletions(-) (limited to 'src/slskd/Transfers/API/Controllers/TransfersController.cs') diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index 985452bb..74d92d5f 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -83,9 +83,22 @@ namespace slskd.Transfers.API [Authorize] [ProducesResponseType(204)] [ProducesResponseType(404)] - public IActionResult CancelDownload([FromRoute, Required] string username, [FromRoute, Required]string id, [FromQuery]bool remove = false) + public async Task CancelDownloadAsync([FromRoute, Required] string username, [FromRoute, Required]string id, [FromQuery]bool remove = false) { - return CancelTransfer(TransferDirection.Download, username, id, remove); + if (!Guid.TryParse(id, out var guid)) + { + return BadRequest(); + } + + try + { + await Transfers.Downloads.CancelAsync(guid, remove); + return NoContent(); + } + catch (NotFoundException) + { + return NotFound(); + } } /// @@ -180,15 +193,24 @@ namespace slskd.Transfers.API [ProducesResponseType(404)] public async Task GetPlaceInQueue([FromRoute, Required]string username, [FromRoute, Required]string id) { - var record = Tracker.Transfers.WithDirection(TransferDirection.Download).FromUser(username).WithId(id); + if (!Guid.TryParse(id, out var guid)) + { + return BadRequest(); + } - if (record == default) + try + { + var place = await Transfers.Downloads.GetPlaceInQueueAsync(guid); + return Ok(place); + } + catch (NotFoundException) { return NotFound(); } - - record.Transfer.PlaceInQueue = await Client.GetDownloadPlaceInQueueAsync(username, record.Transfer.Filename); - return Ok(record.Transfer); + catch (Exception ex) + { + return StatusCode(500, ex.Message); + } } /// @@ -241,39 +263,6 @@ namespace slskd.Transfers.API .WithId(id).Transfer); } - private static FileStream GetLocalFileStream(string remoteFilename, string saveDirectory) - { - var localFilename = remoteFilename.ToLocalFilename(baseDirectory: saveDirectory); - var path = Path.GetDirectoryName(localFilename); - - if (!System.IO.Directory.Exists(path)) - { - System.IO.Directory.CreateDirectory(path); - } - - return new FileStream(localFilename, FileMode.Create); - } - - private static void MoveFile(string filename, string sourceDirectory, string destinationDirectory) - { - var sourceFilename = filename.ToLocalFilename(sourceDirectory); - var destinationFilename = filename.ToLocalFilename(destinationDirectory); - - var destinationPath = Path.GetDirectoryName(destinationFilename); - - if (!System.IO.Directory.Exists(destinationPath)) - { - System.IO.Directory.CreateDirectory(destinationPath); - } - - System.IO.File.Move(sourceFilename, destinationFilename, overwrite: true); - - if (!System.IO.Directory.EnumerateFileSystemEntries(Path.GetDirectoryName(sourceFilename)).Any()) - { - System.IO.Directory.Delete(Path.GetDirectoryName(sourceFilename)); - } - } - private IActionResult CancelTransfer(TransferDirection direction, string username, string id, bool remove = false) { if (Tracker.TryGet(direction, username, id, out var transfer)) -- cgit v1.2.3 From aa7175a22e51314aa9ba0e818bf21884bec4fe49 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 24 Jul 2022 13:45:04 -0500 Subject: docs and polish --- .../API/Controllers/TransfersController.cs | 62 +++- src/slskd/Transfers/Downloads/DownloadService.cs | 376 +++++++++++---------- src/slskd/Transfers/Downloads/IDownloadService.cs | 82 +++++ 3 files changed, 328 insertions(+), 192 deletions(-) create mode 100644 src/slskd/Transfers/Downloads/IDownloadService.cs (limited to 'src/slskd/Transfers/API/Controllers/TransfersController.cs') diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index 74d92d5f..a45112f8 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -22,9 +22,7 @@ namespace slskd.Transfers.API using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; - using System.IO; using System.Linq; - using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; @@ -92,7 +90,13 @@ namespace slskd.Transfers.API try { - await Transfers.Downloads.CancelAsync(guid, remove); + Transfers.Downloads.TryCancel(guid); + + if (remove) + { + await Transfers.Downloads.RemoveAsync(guid); + } + return NoContent(); } catch (NotFoundException) @@ -133,7 +137,7 @@ namespace slskd.Transfers.API [ProducesResponseType(201)] [ProducesResponseType(typeof(string), 403)] [ProducesResponseType(typeof(string), 500)] - public async Task Enqueue([FromRoute, Required]string username, [FromBody]IEnumerable requests) + public async Task EnqueueAsync([FromRoute, Required]string username, [FromBody]IEnumerable requests) { try { @@ -154,11 +158,22 @@ namespace slskd.Transfers.API [HttpGet("downloads")] [Authorize] [ProducesResponseType(200)] - public IActionResult GetDownloads() + public async Task GetDownloadsAsync([FromQuery]bool includeRemoved = false) { - return Ok(Tracker.Transfers - .WithDirection(TransferDirection.Download) - .ToMap()); + var downloads = await Transfers.Downloads.ListAsync(includeRemoved: includeRemoved); + + var response = downloads.GroupBy(t => t.Username).Select(grouping => new UserResponse() + { + Username = grouping.Key, + Directories = grouping.GroupBy(g => g.Filename.DirectoryName()).Select(d => new DirectoryResponse() + { + Name = d.Key, + FileCount = d.Count(), + Files = d.ToList(), + }), + }); + + return Ok(response); } /// @@ -170,12 +185,27 @@ namespace slskd.Transfers.API [HttpGet("downloads/{username}")] [Authorize] [ProducesResponseType(200)] - public IActionResult GetDownloads([FromRoute, Required]string username) + public async Task GetDownloadsAsync([FromRoute, Required] string username) { - return Ok(Tracker.Transfers - .WithDirection(TransferDirection.Download) - .FromUser(username) - .ToMap()); + var downloads = await Transfers.Downloads.ListAsync(d => d.Username == username); + + if (!downloads.Any()) + { + return NotFound(); + } + + var response = new UserResponse() + { + Username = username, + Directories = downloads.GroupBy(g => g.Filename.DirectoryName()).Select(d => new DirectoryResponse() + { + Name = d.Key, + FileCount = d.Count(), + Files = d.ToList(), + }), + }; + + return Ok(response); } /// @@ -191,7 +221,7 @@ namespace slskd.Transfers.API [Authorize] [ProducesResponseType(typeof(API.Transfer), 200)] [ProducesResponseType(404)] - public async Task GetPlaceInQueue([FromRoute, Required]string username, [FromRoute, Required]string id) + public async Task GetPlaceInQueueAsync([FromRoute, Required] string username, [FromRoute, Required] string id) { if (!Guid.TryParse(id, out var guid)) { @@ -237,7 +267,7 @@ namespace slskd.Transfers.API [HttpGet("uploads/{username}")] [Authorize] [ProducesResponseType(200)] - public IActionResult GetUploads([FromRoute, Required]string username) + public IActionResult GetUploads([FromRoute, Required] string username) { return Ok(Tracker.Transfers .WithDirection(TransferDirection.Upload) @@ -255,7 +285,7 @@ namespace slskd.Transfers.API [HttpGet("uploads/{username}/{id}")] [Authorize] [ProducesResponseType(200)] - public IActionResult GetUploads([FromRoute, Required]string username, [FromRoute, Required]string id) + public IActionResult GetUploads([FromRoute, Required] string username, [FromRoute, Required] string id) { return Ok(Tracker.Transfers .WithDirection(TransferDirection.Upload) diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index f53c6004..87bf3023 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -32,30 +32,6 @@ namespace slskd.Transfers.Downloads using Serilog; using slskd.Integrations.FTP; - /// - /// Manages downloads. - /// - public interface IDownloadService - { - /// - /// 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. - /// - /// - /// - /// - /// - /// Thrown when at least one of the requested files throws. - Task EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files); - Task GetPlaceInQueueAsync(Guid id); - Task CancelAsync(Guid id, bool remove = false); - Task RemoveAsync(Guid id); - Task FindAsync(Expression> expression); - Task> ListAsync(Expression> expression = null); - } - /// /// Manages downloads. /// @@ -75,204 +51,213 @@ namespace slskd.Transfers.Downloads FTP = ftpClient; } - private IDbContextFactory ContextFactory { get; } - private IOptionsMonitor OptionsMonitor { get; } + private ConcurrentDictionary CancellationTokens { get; } = new ConcurrentDictionary(); private ISoulseekClient Client { get; } - private ITransferTracker Tracker { get; } + private IDbContextFactory ContextFactory { get; } private IFTPService FTP { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); - private ConcurrentDictionary CancellationTokens { get; } = new ConcurrentDictionary(); - - public async Task CancelAsync(Guid id, bool remove = false) - { - if (CancellationTokens.TryRemove(id, out var cts)) - { - cts.Cancel(); - - if (remove) - { - await RemoveAsync(id); - } - - return true; - } - - return false; - } + private IOptionsMonitor OptionsMonitor { get; } + private ITransferTracker Tracker { get; } /// /// 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. + /// 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 the requesting user. + /// The list of files to enqueue. + /// 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 EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files) + public Task EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files) { - try + if (string.IsNullOrEmpty(username)) { - Log.Information("Downloading {Count} files from user {Username}", files.Count(), username); + throw new ArgumentException("Username is required", nameof(username)); + } - Log.Debug("Priming connection for user {Username}", username); - await Client.ConnectToUserAsync(username, invalidateCache: false); - Log.Debug("Connection for user '{Username}' primed", username); + if (!files.Any()) + { + throw new ArgumentException("At least one file is require", nameof(files)); + } - var thrownExceptions = new List(); + return EnqueueAsyncInternal(username, files); - foreach (var file in files) + async Task EnqueueAsyncInternal(string username, IEnumerable<(string Filename, long Size)> files) + { + try { - Log.Debug("Attempting to enqueue {Filename} from user {Username}", file.Filename, username); + Log.Information("Downloading {Count} files from user {Username}", files.Count(), username); - var id = Guid.NewGuid(); + Log.Debug("Priming connection for user {Username}", username); + await Client.ConnectToUserAsync(username, invalidateCache: false); + Log.Debug("Connection for user '{Username}' primed", username); - var transfer = new Transfer() - { - Id = id, - Username = username, - Direction = TransferDirection.Download, - Filename = file.Filename, - Size = file.Size, - StartOffset = 0, - RequestedAt = DateTime.UtcNow, - }; - - // persist the transfer to the database so we have a record that it was attempted - using var context = await ContextFactory.CreateDbContextAsync(); - context.Add(transfer); - await context.SaveChangesAsync(); - - var cts = new CancellationTokenSource(); - CancellationTokens.TryAdd(id, cts); - - var waitUntilEnqueue = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - - async Task UpdateAndSaveChangesAsync(Transfer transfer) + var thrownExceptions = new List(); + + foreach (var file in files) { + Log.Debug("Attempting to enqueue {Filename} from user {Username}", file.Filename, username); + + var id = Guid.NewGuid(); + + var transfer = new Transfer() + { + Id = id, + Username = username, + Direction = TransferDirection.Download, + Filename = file.Filename, + Size = file.Size, + StartOffset = 0, + RequestedAt = DateTime.UtcNow, + }; + + // persist the transfer to the database so we have a record that it was attempted using var context = await ContextFactory.CreateDbContextAsync(); - context.Update(transfer); + context.Add(transfer); await context.SaveChangesAsync(); - } - // this task does the actual work of downloading the file. if the transfer is successfully queued remotely, - // the waitUntilEnqueue completion source is set, which yields execution to below so we can return and let - // the caller know. - var downloadTask = Task.Run(async () => - { - using var rateLimiter = new RateLimiter(250); + var cts = new CancellationTokenSource(); + CancellationTokens.TryAdd(id, cts); - try + var waitUntilEnqueue = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + async Task UpdateAndSaveChangesAsync(Transfer transfer) { - var completedTransfer = await Client.DownloadAsync( - username: username, - remoteFilename: file.Filename, - outputStreamFactory: () => GetLocalFileStream(file.Filename, OptionsMonitor.CurrentValue.Directories.Incomplete), - size: file.Size, - startOffset: 0, - token: null, - cancellationToken: cts.Token, - options: new TransferOptions( - disposeOutputStreamOnCompletion: true, - stateChanged: (args) => - { - Log.Debug("Download of {Filename} from user {Username} changed state from {Previous} to {New}", file.Filename, username, args.PreviousState, args.Transfer.State); - - Tracker.AddOrUpdate(args.Transfer, cts); - - transfer = transfer.WithSoulseekTransfer(args.Transfer); - // todo: broadcast - _ = UpdateAndSaveChangesAsync(transfer); - - if (args.Transfer.State.HasFlag(TransferStates.Queued) || args.Transfer.State == TransferStates.Initializing) - { - waitUntilEnqueue.TrySetResult(true); - } - }, - progressUpdated: (args) => rateLimiter.Invoke(() => - { - transfer = transfer.WithSoulseekTransfer(args.Transfer); - // todo: broadcast - _ = UpdateAndSaveChangesAsync(transfer); - - Tracker.AddOrUpdate(args.Transfer, cts); - }))); - - transfer = transfer.WithSoulseekTransfer(completedTransfer); - // todo: broadcast - await UpdateAndSaveChangesAsync(transfer); - - // this would be the ideal place to hook in a generic post-download task processor - // for now, we'll just carry out hard coded behavior - MoveFile(file.Filename, OptionsMonitor.CurrentValue.Directories.Incomplete, OptionsMonitor.CurrentValue.Directories.Downloads); - - if (OptionsMonitor.CurrentValue.Integration.Ftp.Enabled) - { - _ = FTP.UploadAsync(file.Filename.ToLocalFilename(OptionsMonitor.CurrentValue.Directories.Downloads)); - } + using var context = await ContextFactory.CreateDbContextAsync(); + context.Update(transfer); + await context.SaveChangesAsync(); } - finally + + // this task does the actual work of downloading the file. if the transfer is successfully queued + // remotely, the waitUntilEnqueue completion source is set, which yields execution to below so we can + // return and let the caller know. + var downloadTask = Task.Run(async () => { - CancellationTokens.TryRemove(id, out _); - } - }); + using var rateLimiter = new RateLimiter(250); - // wait until either the waitUntilEnqueue task completes because the download was successfully queued, or the - // downloadTask throws due to an error prior to successfully queueing. - var task = await Task.WhenAny(waitUntilEnqueue.Task, downloadTask); + try + { + var completedTransfer = await Client.DownloadAsync( + username: username, + remoteFilename: file.Filename, + outputStreamFactory: () => GetLocalFileStream(file.Filename, OptionsMonitor.CurrentValue.Directories.Incomplete), + size: file.Size, + startOffset: 0, + token: null, + cancellationToken: cts.Token, + options: new TransferOptions( + disposeOutputStreamOnCompletion: true, + stateChanged: (args) => + { + Log.Debug("Download of {Filename} from user {Username} changed state from {Previous} to {New}", file.Filename, username, args.PreviousState, args.Transfer.State); - // if the download task completed first it is a very good indication that it threw an exception or was otherwise - // not successful. try to figure out why and update everything to reflect the failure, but continue processing the batch - if (task == downloadTask) - { - Exception ex = downloadTask.Exception; + Tracker.AddOrUpdate(args.Transfer, cts); + + transfer = transfer.WithSoulseekTransfer(args.Transfer); + // todo: broadcast + _ = UpdateAndSaveChangesAsync(transfer); + + if (args.Transfer.State.HasFlag(TransferStates.Queued) || args.Transfer.State == TransferStates.Initializing) + { + waitUntilEnqueue.TrySetResult(true); + } + }, + progressUpdated: (args) => rateLimiter.Invoke(() => + { + transfer = transfer.WithSoulseekTransfer(args.Transfer); + // todo: broadcast + _ = UpdateAndSaveChangesAsync(transfer); + + Tracker.AddOrUpdate(args.Transfer, cts); + }))); + + transfer = transfer.WithSoulseekTransfer(completedTransfer); + // todo: broadcast + await UpdateAndSaveChangesAsync(transfer); + + // this would be the ideal place to hook in a generic post-download task processor for now, we'll + // just carry out hard coded behavior + MoveFile(file.Filename, OptionsMonitor.CurrentValue.Directories.Incomplete, OptionsMonitor.CurrentValue.Directories.Downloads); + + if (OptionsMonitor.CurrentValue.Integration.Ftp.Enabled) + { + _ = FTP.UploadAsync(file.Filename.ToLocalFilename(OptionsMonitor.CurrentValue.Directories.Downloads)); + } + } + finally + { + CancellationTokens.TryRemove(id, out _); + } + }); + + // wait until either the waitUntilEnqueue task completes because the download was successfully queued, or + // the downloadTask throws due to an error prior to successfully queueing. + var task = await Task.WhenAny(waitUntilEnqueue.Task, downloadTask); - // todo: figure out why this needs to be unwrapped just for this one case. is this always an aggregate? - if (ex is AggregateException aggEx) + // if the download task completed first it is a very good indication that it threw an exception or was + // otherwise not successful. try to figure out why and update everything to reflect the failure, but + // continue processing the batch + if (task == downloadTask) { - var rejected = aggEx.InnerExceptions.Where(e => e is TransferRejectedException) ?? Enumerable.Empty(); - if (rejected.Any()) + Exception ex = downloadTask.Exception; + + // todo: figure out why this needs to be unwrapped just for this one case. is this always an aggregate? + if (ex is AggregateException aggEx) { - ex = rejected.First(); + var rejected = aggEx.InnerExceptions.Where(e => e is TransferRejectedException) ?? Enumerable.Empty(); + if (rejected.Any()) + { + ex = rejected.First(); + } } + + Log.Error("Failed to download {Filename} from {Username}: {Message}", file.Filename, username, ex.Message); + thrownExceptions.Add(ex); + transfer.Exception = ex.Message; + transfer.State = TransferStates.Completed | TransferStates.Errored; + transfer.EndedAt = DateTime.UtcNow; + } + else + { + transfer.EnqueuedAt = DateTime.UtcNow; + Log.Debug("Successfully enqueued {Filename} from user {Username}", file.Filename, username); } - Log.Error("Failed to download {Filename} from {Username}: {Message}", file.Filename, username, ex.Message); - thrownExceptions.Add(ex); - transfer.Exception = ex.Message; - transfer.State = TransferStates.Completed | TransferStates.Errored; - transfer.EndedAt = DateTime.UtcNow; + await context.SaveChangesAsync(); } - else + + if (thrownExceptions.Any()) { - transfer.EnqueuedAt = DateTime.UtcNow; - Log.Debug("Successfully enqueued {Filename} from user {Username}", file.Filename, username); + throw new AggregateException(thrownExceptions); } - await context.SaveChangesAsync(); + Log.Information("Successfully enqueued {Count} files from user {Username}", files.Count(), username); } - - if (thrownExceptions.Any()) + catch (Exception ex) { - throw new AggregateException(thrownExceptions); + Log.Error(ex, "Failed to download one or more files from user {Username}: {Message}", username, ex.Message); + throw; } - - Log.Information("Successfully enqueued {Count} files from user {Username}", files.Count(), username); - } - catch (Exception ex) - { - Log.Error(ex, "Failed to download one or more files from user {Username}: {Message}", username, ex.Message); - throw; } } + /// + /// Finds a single download matching the specified . + /// + /// The expression to use to match downloads. + /// The found transfer, or default if not found. public async Task FindAsync(Expression> expression) { try { var context = await ContextFactory.CreateDbContextAsync(); - return await context.Transfers.Where(expression).FirstOrDefaultAsync(); + return await context.Transfers + .Where(t => t.Direction == TransferDirection.Download) + .Where(expression).FirstOrDefaultAsync(); } catch (Exception ex) { @@ -281,6 +266,11 @@ namespace slskd.Transfers.Downloads } } + /// + /// 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 @@ -307,12 +297,24 @@ namespace slskd.Transfers.Downloads } } - public async Task> ListAsync(Expression> expression = null) + /// + /// 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 async Task> ListAsync(Expression> expression = null, bool includeRemoved = false) { + expression ??= t => true; + try { var context = await ContextFactory.CreateDbContextAsync(); - return await context.Transfers.Where(expression).ToListAsync(); + return await context.Transfers + .Where(t => t.Direction == TransferDirection.Download) + .Where(t => !t.Removed || includeRemoved) + .Where(expression) + .ToListAsync(); } catch (Exception ex) { @@ -321,6 +323,12 @@ namespace slskd.Transfers.Downloads } } + /// + /// Removes the download matching the specified . + /// + /// This is a soft delete; the record is retained for historical retrieval. + /// The unique identifier of the download. + /// public async Task RemoveAsync(Guid id) { try @@ -344,6 +352,22 @@ namespace slskd.Transfers.Downloads } } + /// + /// 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 (CancellationTokens.TryRemove(id, out var cts)) + { + cts.Cancel(); + return true; + } + + return false; + } + private static FileStream GetLocalFileStream(string remoteFilename, string saveDirectory) { var localFilename = remoteFilename.ToLocalFilename(baseDirectory: saveDirectory); @@ -377,4 +401,4 @@ namespace slskd.Transfers.Downloads } } } -} +} \ No newline at end of file diff --git a/src/slskd/Transfers/Downloads/IDownloadService.cs b/src/slskd/Transfers/Downloads/IDownloadService.cs new file mode 100644 index 00000000..07475d31 --- /dev/null +++ b/src/slskd/Transfers/Downloads/IDownloadService.cs @@ -0,0 +1,82 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// 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, either version 3 of the License, or +// (at your option) any later version. +// +// 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/. +// + +namespace slskd.Transfers.Downloads +{ + using System; + using System.Collections.Generic; + using System.Linq.Expressions; + using System.Threading.Tasks; + + /// + /// Manages downloads. + /// + public interface IDownloadService + { + /// + /// 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 the requesting user. + /// The list of files to enqueue. + /// 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 EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files); + + /// + /// Finds a single download matching the specified . + /// + /// The expression to use to match downloads. + /// The found transfer, or default if not found. + Task FindAsync(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. + Task> ListAsync(Expression> expression = null, bool includeRemoved = false); + + /// + /// Removes the download matching the specified . + /// + /// This is a soft delete; the record is retained for historical retrieval. + /// The unique identifier of the download. + /// + Task RemoveAsync(Guid id); + + /// + /// 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); + } +} \ No newline at end of file -- cgit v1.2.3 From 650b5051e92c121cc17343abfc2e0ac8cbd3ff21 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 30 Jul 2022 13:48:29 -0500 Subject: use AsNoTracking() --- src/slskd/Search/SearchService.cs | 11 +- .../API/Controllers/TransfersController.cs | 119 +++++++++++++++------ src/slskd/Transfers/Downloads/DownloadService.cs | 3 + src/slskd/Transfers/Uploads/UploadService.cs | 3 + 4 files changed, 102 insertions(+), 34 deletions(-) (limited to 'src/slskd/Transfers/API/Controllers/TransfersController.cs') diff --git a/src/slskd/Search/SearchService.cs b/src/slskd/Search/SearchService.cs index 54d8bac9..2f71c733 100644 --- a/src/slskd/Search/SearchService.cs +++ b/src/slskd/Search/SearchService.cs @@ -109,7 +109,9 @@ namespace slskd.Search using var context = ContextFactory.CreateDbContext(); - var selector = context.Searches.Where(expression); + var selector = context.Searches + .AsNoTracking() + .Where(expression); if (!includeResponses) { @@ -128,7 +130,12 @@ namespace slskd.Search { expression ??= s => true; using var context = ContextFactory.CreateDbContext(); - return context.Searches.Where(expression).WithoutResponses().ToListAsync(); + + return context.Searches + .AsNoTracking() + .Where(expression) + .WithoutResponses() + .ToListAsync(); } /// diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index a45112f8..3885f416 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -50,12 +50,10 @@ namespace slskd.Transfers.API public TransfersController( IOptionsSnapshot options, ISoulseekClient soulseekClient, - ITransferTracker tracker, ITransferService transferService, IFTPService ftpClient) { Client = soulseekClient; - Tracker = tracker; Options = options.Value; FTP = ftpClient; Transfers = transferService; @@ -64,7 +62,6 @@ namespace slskd.Transfers.API private ITransferService Transfers { get; } private Options Options { get; } private ISoulseekClient Client { get; } - private ITransferTracker Tracker { get; } private IFTPService FTP { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); @@ -118,9 +115,28 @@ namespace slskd.Transfers.API [Authorize] [ProducesResponseType(204)] [ProducesResponseType(404)] - public IActionResult CancelUpload([FromRoute, Required] string username, [FromRoute, Required]string id, [FromQuery]bool remove = false) + public async Task CancelUpload([FromRoute, Required] string username, [FromRoute, Required]string id, [FromQuery]bool remove = false) { - return CancelTransfer(TransferDirection.Upload, username, id, remove); + if (!Guid.TryParse(id, out var guid)) + { + return BadRequest(); + } + + try + { + Transfers.Uploads.TryCancel(guid); + + if (remove) + { + await Transfers.Uploads.RemoveAsync(guid); + } + + return NoContent(); + } + catch (NotFoundException) + { + return NotFound(); + } } /// @@ -208,6 +224,27 @@ namespace slskd.Transfers.API return Ok(response); } + [HttpGet("downloads/{username}/{id}")] + [Authorize] + [ProducesResponseType(typeof(API.Transfer), 200)] + [ProducesResponseType(404)] + public async Task GetDownload([FromRoute, Required] string username, [FromRoute, Required] string id) + { + if (!Guid.TryParse(id, out var guid)) + { + return BadRequest(); + } + + var download = await Transfers.Downloads.FindAsync(t => t.Id == guid); + + if (download == default) + { + return NotFound(); + } + + return Ok(download); + } + /// /// Gets the downlaod for the specified username matching the specified filename, and requests /// the current place in the remote queue of the specified download. @@ -217,7 +254,7 @@ namespace slskd.Transfers.API /// /// The request completed successfully. /// The specified download was not found. - [HttpGet("downloads/{username}/{id}")] + [HttpGet("downloads/{username}/{id}/position")] [Authorize] [ProducesResponseType(typeof(API.Transfer), 200)] [ProducesResponseType(404)] @@ -251,11 +288,22 @@ namespace slskd.Transfers.API [HttpGet("uploads")] [Authorize] [ProducesResponseType(200)] - public IActionResult GetUploads() + public async Task GetUploads([FromQuery] bool includeRemoved = false) { - return Ok(Tracker.Transfers - .WithDirection(TransferDirection.Upload) - .ToMap()); + var uploads = await Transfers.Uploads.ListAsync(includeRemoved: includeRemoved); + + var response = uploads.GroupBy(t => t.Username).Select(grouping => new UserResponse() + { + Username = grouping.Key, + Directories = grouping.GroupBy(g => g.Filename.DirectoryName()).Select(d => new DirectoryResponse() + { + Name = d.Key, + FileCount = d.Count(), + Files = d.ToList(), + }), + }); + + return Ok(response); } /// @@ -267,12 +315,27 @@ namespace slskd.Transfers.API [HttpGet("uploads/{username}")] [Authorize] [ProducesResponseType(200)] - public IActionResult GetUploads([FromRoute, Required] string username) + public async Task GetUploads([FromRoute, Required] string username) { - return Ok(Tracker.Transfers - .WithDirection(TransferDirection.Upload) - .FromUser(username) - .ToMap()); + var uploads = await Transfers.Uploads.ListAsync(d => d.Username == username); + + if (!uploads.Any()) + { + return NotFound(); + } + + var response = new UserResponse() + { + Username = username, + Directories = uploads.GroupBy(g => g.Filename.DirectoryName()).Select(d => new DirectoryResponse() + { + Name = d.Key, + FileCount = d.Count(), + Files = d.ToList(), + }), + }; + + return Ok(response); } /// @@ -285,29 +348,21 @@ namespace slskd.Transfers.API [HttpGet("uploads/{username}/{id}")] [Authorize] [ProducesResponseType(200)] - public IActionResult GetUploads([FromRoute, Required] string username, [FromRoute, Required] string id) - { - return Ok(Tracker.Transfers - .WithDirection(TransferDirection.Upload) - .FromUser(username) - .WithId(id).Transfer); - } - - private IActionResult CancelTransfer(TransferDirection direction, string username, string id, bool remove = false) + public async IActionResult GetUploads([FromRoute, Required] string username, [FromRoute, Required] string id) { - if (Tracker.TryGet(direction, username, id, out var transfer)) + if (!Guid.TryParse(id, out var guid)) { - transfer.CancellationTokenSource.Cancel(); + return BadRequest(); + } - if (remove) - { - Tracker.TryRemove(direction, username, id); - } + var upload = await Transfers.Uploads.FindAsync(t => t.Id == guid); - return NoContent(); + if (upload == default) + { + return NotFound(); } - return NotFound(); + return Ok(upload); } } } \ No newline at end of file diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index a938e767..27d7dfb5 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -249,6 +249,7 @@ namespace slskd.Transfers.Downloads { using var context = await ContextFactory.CreateDbContextAsync(); return await context.Transfers + .AsNoTracking() .Where(t => t.Direction == TransferDirection.Download) .Where(expression).FirstOrDefaultAsync(); } @@ -304,6 +305,7 @@ namespace slskd.Transfers.Downloads { using var context = await ContextFactory.CreateDbContextAsync(); return await context.Transfers + .AsNoTracking() .Where(t => t.Direction == TransferDirection.Download) .Where(t => !t.Removed || includeRemoved) .Where(expression) @@ -328,6 +330,7 @@ namespace slskd.Transfers.Downloads { using var context = await ContextFactory.CreateDbContextAsync(); var transfer = await context.Transfers + .AsNoTracking() .Where(t => t.Direction == TransferDirection.Download) .Where(t => t.Id == id) .FirstOrDefaultAsync(); diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 451afb09..4f545827 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -207,6 +207,7 @@ namespace slskd.Transfers.Uploads { using var context = await ContextFactory.CreateDbContextAsync(); return await context.Transfers + .AsNoTracking() .Where(t => t.Direction == TransferDirection.Upload) .Where(expression).FirstOrDefaultAsync(); } @@ -231,6 +232,7 @@ namespace slskd.Transfers.Uploads { using var context = await ContextFactory.CreateDbContextAsync(); return await context.Transfers + .AsNoTracking() .Where(t => t.Direction == TransferDirection.Upload) .Where(t => !t.Removed || includeRemoved) .Where(expression) @@ -255,6 +257,7 @@ namespace slskd.Transfers.Uploads { using var context = await ContextFactory.CreateDbContextAsync(); var transfer = await context.Transfers + .AsNoTracking() .Where(t => t.Direction == TransferDirection.Upload) .Where(t => t.Id == id) .FirstOrDefaultAsync(); -- cgit v1.2.3 From d830ec75b4f8e33f583a2f1bbb25c822eb7f4a5b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 30 Jul 2022 14:07:45 -0500 Subject: remove deprecated services --- .../API/Controllers/TransfersController.cs | 24 +++------------------- 1 file changed, 3 insertions(+), 21 deletions(-) (limited to 'src/slskd/Transfers/API/Controllers/TransfersController.cs') diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index 3885f416..d12a3f89 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -15,8 +15,6 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // -using Microsoft.Extensions.Options; - namespace slskd.Transfers.API { using System; @@ -26,9 +24,6 @@ namespace slskd.Transfers.API using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; - using Serilog; - using slskd.Integrations.FTP; - using Soulseek; /// /// Transfers. @@ -43,27 +38,14 @@ namespace slskd.Transfers.API /// /// Initializes a new instance of the class. /// - /// - /// - /// - /// + /// public TransfersController( - IOptionsSnapshot options, - ISoulseekClient soulseekClient, - ITransferService transferService, - IFTPService ftpClient) + ITransferService transferService) { - Client = soulseekClient; - Options = options.Value; - FTP = ftpClient; Transfers = transferService; } private ITransferService Transfers { get; } - private Options Options { get; } - private ISoulseekClient Client { get; } - private IFTPService FTP { get; } - private ILogger Log { get; } = Serilog.Log.ForContext(); /// /// Cancels the specified download. @@ -348,7 +330,7 @@ namespace slskd.Transfers.API [HttpGet("uploads/{username}/{id}")] [Authorize] [ProducesResponseType(200)] - public async IActionResult GetUploads([FromRoute, Required] string username, [FromRoute, Required] string id) + public async Task GetUploads([FromRoute, Required] string username, [FromRoute, Required] string id) { if (!Guid.TryParse(id, out var guid)) { -- cgit v1.2.3 From 2e1b8ce9179341b69d32bef4dd5104c363995da3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 14 Aug 2022 11:59:53 -0500 Subject: rename DirectoryResponse Name prop to Directory --- src/slskd/Transfers/API/Controllers/TransfersController.cs | 8 ++++---- src/slskd/Transfers/API/DTO/DirectoryResponse.cs | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) (limited to 'src/slskd/Transfers/API/Controllers/TransfersController.cs') diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index d12a3f89..6395a477 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -165,7 +165,7 @@ namespace slskd.Transfers.API Username = grouping.Key, Directories = grouping.GroupBy(g => g.Filename.DirectoryName()).Select(d => new DirectoryResponse() { - Name = d.Key, + Directory = d.Key, FileCount = d.Count(), Files = d.ToList(), }), @@ -197,7 +197,7 @@ namespace slskd.Transfers.API Username = username, Directories = downloads.GroupBy(g => g.Filename.DirectoryName()).Select(d => new DirectoryResponse() { - Name = d.Key, + Directory = d.Key, FileCount = d.Count(), Files = d.ToList(), }), @@ -279,7 +279,7 @@ namespace slskd.Transfers.API Username = grouping.Key, Directories = grouping.GroupBy(g => g.Filename.DirectoryName()).Select(d => new DirectoryResponse() { - Name = d.Key, + Directory = d.Key, FileCount = d.Count(), Files = d.ToList(), }), @@ -311,7 +311,7 @@ namespace slskd.Transfers.API Username = username, Directories = uploads.GroupBy(g => g.Filename.DirectoryName()).Select(d => new DirectoryResponse() { - Name = d.Key, + Directory = d.Key, FileCount = d.Count(), Files = d.ToList(), }), diff --git a/src/slskd/Transfers/API/DTO/DirectoryResponse.cs b/src/slskd/Transfers/API/DTO/DirectoryResponse.cs index 1f8b1df9..81da0f2f 100644 --- a/src/slskd/Transfers/API/DTO/DirectoryResponse.cs +++ b/src/slskd/Transfers/API/DTO/DirectoryResponse.cs @@ -21,7 +21,7 @@ namespace slskd.Transfers.API public record DirectoryResponse { - public string Name { get; init; } + public string Directory { get; init; } public int FileCount { get; init; } public IEnumerable Files { get; init; } } -- cgit v1.2.3 From b9d0fdfd50eb185c967d70b15e89134d406be875 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 19 Aug 2022 17:31:15 -0500 Subject: remove SQLite asynchrony --- src/slskd/Application.cs | 10 ++-- .../API/Controllers/TransfersController.cs | 16 +++--- src/slskd/Transfers/Downloads/DownloadService.cs | 63 +++++++++++----------- src/slskd/Transfers/Downloads/IDownloadService.cs | 14 +++-- src/slskd/Transfers/Uploads/IUploadService.cs | 12 ++--- src/slskd/Transfers/Uploads/UploadService.cs | 58 ++++++++++---------- 6 files changed, 87 insertions(+), 86 deletions(-) (limited to 'src/slskd/Transfers/API/Controllers/TransfersController.cs') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 6f1c2c86..f9cb95d2 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -263,7 +263,7 @@ namespace slskd // records to be updated if the application has started to shut down so that we can do this cleanup and properly // disposition them as having failed due to an application shutdown, instead of some random exception thrown while // things are being disposed. - var activeUploads = (await Transfers.Uploads.ListAsync(t => !t.State.HasFlag(TransferStates.Completed) && !t.Removed)) + var activeUploads = Transfers.Uploads.List(t => !t.State.HasFlag(TransferStates.Completed) && !t.Removed) .Where(t => !t.State.HasFlag(TransferStates.Completed)) // https://github.com/dotnet/efcore/issues/10434 .ToList(); @@ -272,10 +272,10 @@ namespace slskd Log.Debug("Cleaning up dangling upload {Filename} to {Username}", upload.Filename, upload.Username); upload.State = TransferStates.Completed | TransferStates.Errored; upload.Exception = ApplicationShutdownTransferExceptionMessage; - Transfers.Uploads.UpdateSync(upload); + Transfers.Uploads.Update(upload); } - var activeDownloads = (await Transfers.Downloads.ListAsync(t => !t.State.HasFlag(TransferStates.Completed) && !t.Removed)) + var activeDownloads = Transfers.Downloads.List(t => !t.State.HasFlag(TransferStates.Completed) && !t.Removed) .Where(t => !t.State.HasFlag(TransferStates.Completed)) // https://github.com/dotnet/efcore/issues/10434 .ToList(); @@ -284,7 +284,7 @@ namespace slskd Log.Debug("Cleaning up dangling download {Filename} from {Username}", download.Filename, download.Username); download.State = TransferStates.Completed | TransferStates.Errored; download.Exception = ApplicationShutdownTransferExceptionMessage; - Transfers.Downloads.UpdateSync(download); + Transfers.Downloads.Update(download); } // save the ids of any downloads that were active, so we can re-enqueue them after we've connected and logged in. @@ -526,7 +526,7 @@ namespace slskd // we previously saved a list of all of the download ids that were active at the previous shutdown; fetch the latest // record for those transfers from the db and ensure they haven't been removed from the UI while the application was offline // the user doesn't want those transfers anymore and we don't want to add them back. - var resumeableDownloads = await Transfers.Downloads.ListAsync(t => !t.Removed && ActiveDownloadIdsAtPreviousShutdown.Contains(t.Id)); + var resumeableDownloads = Transfers.Downloads.List(t => !t.Removed && ActiveDownloadIdsAtPreviousShutdown.Contains(t.Id)); if (resumeableDownloads.Any()) { diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index 6395a477..bdab6582 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -73,7 +73,7 @@ namespace slskd.Transfers.API if (remove) { - await Transfers.Downloads.RemoveAsync(guid); + Transfers.Downloads.Remove(guid); } return NoContent(); @@ -110,7 +110,7 @@ namespace slskd.Transfers.API if (remove) { - await Transfers.Uploads.RemoveAsync(guid); + Transfers.Uploads.Remove(guid); } return NoContent(); @@ -158,7 +158,7 @@ namespace slskd.Transfers.API [ProducesResponseType(200)] public async Task GetDownloadsAsync([FromQuery]bool includeRemoved = false) { - var downloads = await Transfers.Downloads.ListAsync(includeRemoved: includeRemoved); + var downloads = Transfers.Downloads.List(includeRemoved: includeRemoved); var response = downloads.GroupBy(t => t.Username).Select(grouping => new UserResponse() { @@ -185,7 +185,7 @@ namespace slskd.Transfers.API [ProducesResponseType(200)] public async Task GetDownloadsAsync([FromRoute, Required] string username) { - var downloads = await Transfers.Downloads.ListAsync(d => d.Username == username); + var downloads = Transfers.Downloads.List(d => d.Username == username); if (!downloads.Any()) { @@ -217,7 +217,7 @@ namespace slskd.Transfers.API return BadRequest(); } - var download = await Transfers.Downloads.FindAsync(t => t.Id == guid); + var download = Transfers.Downloads.Find(t => t.Id == guid); if (download == default) { @@ -272,7 +272,7 @@ namespace slskd.Transfers.API [ProducesResponseType(200)] public async Task GetUploads([FromQuery] bool includeRemoved = false) { - var uploads = await Transfers.Uploads.ListAsync(includeRemoved: includeRemoved); + var uploads = Transfers.Uploads.List(includeRemoved: includeRemoved); var response = uploads.GroupBy(t => t.Username).Select(grouping => new UserResponse() { @@ -299,7 +299,7 @@ namespace slskd.Transfers.API [ProducesResponseType(200)] public async Task GetUploads([FromRoute, Required] string username) { - var uploads = await Transfers.Uploads.ListAsync(d => d.Username == username); + var uploads = Transfers.Uploads.List(d => d.Username == username); if (!uploads.Any()) { @@ -337,7 +337,7 @@ namespace slskd.Transfers.API return BadRequest(); } - var upload = await Transfers.Uploads.FindAsync(t => t.Id == guid); + var upload = Transfers.Uploads.Find(t => t.Id == guid); if (upload == default) { diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 1c0f9969..f224a94c 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -61,17 +61,16 @@ namespace slskd.Transfers.Downloads /// /// This should generally not be called; use instead. /// - /// - public async Task AddOrSupersedeAsync(Transfer transfer) + public void AddOrSupersede(Transfer transfer) { - using var context = await ContextFactory.CreateDbContextAsync(); + using var context = ContextFactory.CreateDbContext(); - var existing = await context.Transfers + 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) - .FirstOrDefaultAsync(); + .FirstOrDefault(); if (existing != default) { @@ -80,7 +79,7 @@ namespace slskd.Transfers.Downloads } context.Add(transfer); - await context.SaveChangesAsync(); + context.SaveChanges(); } /// @@ -140,7 +139,7 @@ namespace slskd.Transfers.Downloads }; // persist the transfer to the database so we have a record that it was attempted - await AddOrSupersedeAsync(transfer); + AddOrSupersede(transfer); var cts = new CancellationTokenSource(); CancellationTokens.TryAdd(id, cts); @@ -176,13 +175,13 @@ namespace slskd.Transfers.Downloads waitUntilEnqueue.TrySetResult(true); } - UpdateSync(transfer); + Update(transfer); }, progressUpdated: (args) => rateLimiter.Invoke(() => { transfer = transfer.WithSoulseekTransfer(args.Transfer); // todo: broadcast - UpdateSync(transfer); + Update(transfer); })); var completedTransfer = await Client.DownloadAsync( @@ -201,7 +200,7 @@ namespace slskd.Transfers.Downloads transfer = transfer.WithSoulseekTransfer(completedTransfer); // todo: broadcast - UpdateSync(transfer); + Update(transfer); // this would be the ideal place to hook in a generic post-download task processor for now, we'll // just carry out hard coded behavior. these carry the risk of failing the transfer, and i could @@ -220,7 +219,7 @@ namespace slskd.Transfers.Downloads transfer.State = TransferStates.Completed | TransferStates.Cancelled; // todo: broadcast - UpdateSync(transfer); + Update(transfer); throw; } @@ -233,7 +232,7 @@ namespace slskd.Transfers.Downloads transfer.State = TransferStates.Completed | TransferStates.Errored; // todo: broadcast - UpdateSync(transfer); + Update(transfer); throw; } @@ -293,15 +292,16 @@ namespace slskd.Transfers.Downloads /// /// The expression to use to match downloads. /// The found transfer, or default if not found. - public async Task FindAsync(Expression> expression) + public Transfer Find(Expression> expression) { try { - using var context = await ContextFactory.CreateDbContextAsync(); - return await context.Transfers + using var context = ContextFactory.CreateDbContext(); + + return context.Transfers .AsNoTracking() .Where(t => t.Direction == TransferDirection.Download) - .Where(expression).FirstOrDefaultAsync(); + .Where(expression).FirstOrDefault(); } catch (Exception ex) { @@ -319,8 +319,9 @@ namespace slskd.Transfers.Downloads { try { - using var context = await ContextFactory.CreateDbContextAsync(); - var transfer = await context.Transfers.FindAsync(id); + using var context = ContextFactory.CreateDbContext(); + + var transfer = context.Transfers.Find(id); if (transfer == default) { @@ -330,7 +331,7 @@ namespace slskd.Transfers.Downloads var place = await Client.GetDownloadPlaceInQueueAsync(transfer.Username, transfer.Filename); transfer.PlaceInQueue = place; - await context.SaveChangesAsync(); + context.SaveChanges(); return place; } @@ -347,19 +348,20 @@ namespace slskd.Transfers.Downloads /// 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 async Task> ListAsync(Expression> expression = null, bool includeRemoved = false) + public List List(Expression> expression = null, bool includeRemoved = false) { expression ??= t => true; try { - using var context = await ContextFactory.CreateDbContextAsync(); - return await context.Transfers + using var context = ContextFactory.CreateDbContext(); + + return context.Transfers .AsNoTracking() .Where(t => t.Direction == TransferDirection.Download) .Where(t => !t.Removed || includeRemoved) .Where(expression) - .ToListAsync(); + .ToList(); } catch (Exception ex) { @@ -373,16 +375,16 @@ namespace slskd.Transfers.Downloads /// /// This is a soft delete; the record is retained for historical retrieval. /// The unique identifier of the download. - /// - public async Task RemoveAsync(Guid id) + public void Remove(Guid id) { try { - using var context = await ContextFactory.CreateDbContextAsync(); - var transfer = await context.Transfers + using var context = ContextFactory.CreateDbContext(); + + var transfer = context.Transfers .Where(t => t.Direction == TransferDirection.Download) .Where(t => t.Id == id) - .FirstOrDefaultAsync(); + .FirstOrDefault(); if (transfer == default) { @@ -396,7 +398,7 @@ namespace slskd.Transfers.Downloads transfer.Removed = true; - await context.SaveChangesAsync(); + context.SaveChanges(); } catch (Exception ex) { @@ -425,7 +427,7 @@ namespace slskd.Transfers.Downloads /// Synchronously updates the specified . /// /// The transfer to update. - public void UpdateSync(Transfer transfer) + public void Update(Transfer transfer) { var experimental = OptionsMonitor.CurrentValue.Experimental; var id = Guid.NewGuid(); @@ -436,6 +438,7 @@ namespace slskd.Transfers.Downloads } using var context = ContextFactory.CreateDbContext(); + context.Update(transfer); context.SaveChanges(); diff --git a/src/slskd/Transfers/Downloads/IDownloadService.cs b/src/slskd/Transfers/Downloads/IDownloadService.cs index 0e0e08fd..cc0064fd 100644 --- a/src/slskd/Transfers/Downloads/IDownloadService.cs +++ b/src/slskd/Transfers/Downloads/IDownloadService.cs @@ -32,8 +32,7 @@ namespace slskd.Transfers.Downloads /// /// This should generally not be called; use instead. /// - /// - Task AddOrSupersedeAsync(Transfer transfer); + void AddOrSupersede(Transfer transfer); /// /// Enqueues the requested list of . @@ -55,7 +54,7 @@ namespace slskd.Transfers.Downloads /// /// The expression to use to match downloads. /// The found transfer, or default if not found. - Task FindAsync(Expression> expression); + Transfer Find(Expression> expression); /// /// Retrieves the place in the remote queue for the download matching the specified . @@ -70,15 +69,14 @@ namespace slskd.Transfers.Downloads /// 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. - Task> ListAsync(Expression> expression = null, bool includeRemoved = false); + List List(Expression> expression = null, bool includeRemoved = false); /// /// Removes the download matching the specified . /// /// This is a soft delete; the record is retained for historical retrieval. /// The unique identifier of the download. - /// - Task RemoveAsync(Guid id); + void Remove(Guid id); /// /// Cancels the download matching the specified , if it is in progress. @@ -88,9 +86,9 @@ namespace slskd.Transfers.Downloads bool TryCancel(Guid id); /// - /// Synchronously updates the specified . + /// Updates the specified . /// /// The transfer to update. - void UpdateSync(Transfer transfer); + void Update(Transfer transfer); } } \ No newline at end of file diff --git a/src/slskd/Transfers/Uploads/IUploadService.cs b/src/slskd/Transfers/Uploads/IUploadService.cs index 07423630..8fa0b194 100644 --- a/src/slskd/Transfers/Uploads/IUploadService.cs +++ b/src/slskd/Transfers/Uploads/IUploadService.cs @@ -42,8 +42,7 @@ namespace slskd.Transfers.Uploads /// /// This should generally not be called; use instead. /// - /// - Task AddOrSupersedeAsync(Transfer transfer); + void AddOrSupersede(Transfer transfer); /// /// Enqueues the requested file. @@ -58,7 +57,7 @@ namespace slskd.Transfers.Uploads /// /// The expression to use to match uploads. /// The found transfer, or default if not found. - Task FindAsync(Expression> expression); + Transfer Find(Expression> expression); /// /// Returns a list of all uploads matching the optional . @@ -66,15 +65,14 @@ namespace slskd.Transfers.Uploads /// An optional expression used to match uploads. /// Optionally include uploads that have been removed previously. /// The list of uploads matching the specified expression, or all uploads if no expression is specified. - Task> ListAsync(Expression> expression = null, bool includeRemoved = false); + List List(Expression> expression = null, bool includeRemoved = false); /// /// Removes the upload matching the specified . /// /// This is a soft delete; the record is retained for historical retrieval. /// The unique identifier of the upload. - /// - Task RemoveAsync(Guid id); + void Remove(Guid id); /// /// Cancels the upload matching the specified , if it is in progress. @@ -87,6 +85,6 @@ namespace slskd.Transfers.Uploads /// Synchronously updates the specified . /// /// The transfer to update. - void UpdateSync(Transfer transfer); + void Update(Transfer transfer); } } \ No newline at end of file diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 0e7e340e..026b24b4 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -78,17 +78,16 @@ namespace slskd.Transfers.Uploads /// /// This should generally not be called; use instead. /// - /// - public async Task AddOrSupersedeAsync(Transfer transfer) + public void AddOrSupersede(Transfer transfer) { - using var context = await ContextFactory.CreateDbContextAsync(); + using var context = ContextFactory.CreateDbContext(); - var existing = await context.Transfers + 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) - .FirstOrDefaultAsync(); + .FirstOrDefault(); if (existing != default) { @@ -97,7 +96,7 @@ namespace slskd.Transfers.Uploads } context.Add(transfer); - await context.SaveChangesAsync(); + context.SaveChanges(); } /// @@ -131,7 +130,7 @@ namespace slskd.Transfers.Uploads } // find existing records for this username and file that haven't been removed from the UI - var existingRecords = await ListAsync(t => t.Username == username && t.Filename == localFilename && !t.Removed); + var existingRecords = List(t => t.Username == username && t.Filename == localFilename && !t.Removed); // check whether any of these records is in a non-complete state and bail out if so if (existingRecords.Any(t => !t.State.HasFlag(TransferStates.Completed))) @@ -154,7 +153,7 @@ namespace slskd.Transfers.Uploads }; // persist the transfer to the database so we have a record that it was attempted - await AddOrSupersedeAsync(transfer); + AddOrSupersede(transfer); // create a new cancellation token source so that we can cancel the upload from the UI. var cts = new CancellationTokenSource(); @@ -195,13 +194,13 @@ namespace slskd.Transfers.Uploads } // todo: broadcast - UpdateSync(transfer); + Update(transfer); }, progressUpdated: (args) => rateLimiter.Invoke(() => { transfer = transfer.WithSoulseekTransfer(args.Transfer); // todo: broadcast - UpdateSync(transfer); + Update(transfer); }), governor: (tx, req, ct) => Governor.GetBytesAsync(tx.Username, req, ct), reporter: (tx, att, grant, act) => Governor.ReturnBytes(tx.Username, att, grant, act), @@ -222,7 +221,7 @@ namespace slskd.Transfers.Uploads transfer = transfer.WithSoulseekTransfer(completedTransfer); //todo: broadcast - UpdateSync(transfer); + Update(transfer); } catch (TaskCanceledException ex) { @@ -231,7 +230,7 @@ namespace slskd.Transfers.Uploads transfer.State = TransferStates.Completed | TransferStates.Cancelled; // todo: broadcast - UpdateSync(transfer); + Update(transfer); throw; } @@ -244,7 +243,7 @@ namespace slskd.Transfers.Uploads transfer.State = TransferStates.Completed | TransferStates.Errored; // todo: broadcast - UpdateSync(transfer); + Update(transfer); throw; } @@ -260,15 +259,16 @@ namespace slskd.Transfers.Uploads /// /// The expression to use to match uploads. /// The found transfer, or default if not found. - public async Task FindAsync(Expression> expression) + public Transfer Find(Expression> expression) { try { - using var context = await ContextFactory.CreateDbContextAsync(); - return await context.Transfers + using var context = ContextFactory.CreateDbContext(); + + return context.Transfers .AsNoTracking() .Where(t => t.Direction == TransferDirection.Upload) - .Where(expression).FirstOrDefaultAsync(); + .Where(expression).FirstOrDefault(); } catch (Exception ex) { @@ -283,19 +283,20 @@ namespace slskd.Transfers.Uploads /// An optional expression used to match uploads. /// Optionally include uploads that have been removed previously. /// The list of uploads matching the specified expression, or all uploads if no expression is specified. - public async Task> ListAsync(Expression> expression = null, bool includeRemoved = false) + public List List(Expression> expression = null, bool includeRemoved = false) { expression ??= t => true; try { - using var context = await ContextFactory.CreateDbContextAsync(); - return await context.Transfers + using var context = ContextFactory.CreateDbContext(); + + return context.Transfers .AsNoTracking() .Where(t => t.Direction == TransferDirection.Upload) .Where(t => !t.Removed || includeRemoved) .Where(expression) - .ToListAsync(); + .ToList(); } catch (Exception ex) { @@ -309,16 +310,16 @@ namespace slskd.Transfers.Uploads /// /// This is a soft delete; the record is retained for historical retrieval. /// The unique identifier of the upload. - /// - public async Task RemoveAsync(Guid id) + public void Remove(Guid id) { try { - using var context = await ContextFactory.CreateDbContextAsync(); - var transfer = await context.Transfers + using var context = ContextFactory.CreateDbContext(); + + var transfer = context.Transfers .Where(t => t.Direction == TransferDirection.Upload) .Where(t => t.Id == id) - .FirstOrDefaultAsync(); + .FirstOrDefault(); if (transfer == default) { @@ -332,7 +333,7 @@ namespace slskd.Transfers.Uploads transfer.Removed = true; - await context.SaveChangesAsync(); + context.SaveChanges(); } catch (Exception ex) { @@ -361,7 +362,7 @@ namespace slskd.Transfers.Uploads /// Synchronously updates the specified . /// /// The transfer to update. - public void UpdateSync(Transfer transfer) + public void Update(Transfer transfer) { var experimental = OptionsMonitor.CurrentValue.Experimental; var id = Guid.NewGuid(); @@ -372,6 +373,7 @@ namespace slskd.Transfers.Uploads } using var context = ContextFactory.CreateDbContext(); + context.Update(transfer); context.SaveChanges(); -- cgit v1.2.3