From a0a38f224acb405b323da8d6336c37fe67aa4ac3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 16 Jul 2022 16:00:39 -0500 Subject: add Transfer --- src/slskd/Transfers/Types/Transfer.cs | 54 +++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 src/slskd/Transfers/Types/Transfer.cs (limited to 'src') diff --git a/src/slskd/Transfers/Types/Transfer.cs b/src/slskd/Transfers/Types/Transfer.cs new file mode 100644 index 00000000..514d2c12 --- /dev/null +++ b/src/slskd/Transfers/Types/Transfer.cs @@ -0,0 +1,54 @@ +// +// 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 +{ + using System; + using System.ComponentModel.DataAnnotations; + using System.ComponentModel.DataAnnotations.Schema; + using Soulseek; + + public class Transfer + { + [Key] + public Guid Id { get; init; } + public string Username { get; init; } + public TransferDirection Direction { get; init; } + public string Filename { get; init; } + public long Size { get; set; } + public long StartOffset { get; init; } + + public TransferStates State { get; set; } + public DateTime RequestedAt { get; set; } + public DateTime? EnqueuedAt { get; set; } + public DateTime? StartedAt { get; set; } + public DateTime? EndedAt { get; set; } + public long BytesTransferred { get; set; } + public double AverageSpeed { get; set; } + + public Exception Exception { get; set; } + + [NotMapped] + public long BytesRemaining => Size - BytesTransferred : null; + [NotMapped] + public TimeSpan? ElapsedTime => StartedAt == null ? null : (EndedAt ?? DateTime.UtcNow) - StartedAt.Value; + [NotMapped] + public double PercentComplete => Size == 0 ? 0 : (BytesTransferred / (double)Size) * 100; + [NotMapped] + public TimeSpan? RemainingTime => AverageSpeed == 0 ? null : TimeSpan.FromSeconds(BytesRemaining / AverageSpeed); + } +} \ No newline at end of file -- cgit v1.2.3 From 41fbfb22a4a9f61ca202d941b1645ccb8e7c01eb Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 16 Jul 2022 16:01:01 -0500 Subject: add TransfersDbContext --- src/slskd/Transfers/TransfersDbContext.cs | 44 +++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 src/slskd/Transfers/TransfersDbContext.cs (limited to 'src') diff --git a/src/slskd/Transfers/TransfersDbContext.cs b/src/slskd/Transfers/TransfersDbContext.cs new file mode 100644 index 00000000..5feee8fd --- /dev/null +++ b/src/slskd/Transfers/TransfersDbContext.cs @@ -0,0 +1,44 @@ +// +// 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 +{ + using System; + using Microsoft.EntityFrameworkCore; + + public class TransfersDbContext : DbContext + { + public TransfersDbContext(DbContextOptions options) + : base(options) + { + Database.EnsureCreated(); + } + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + modelBuilder + .Entity() + .Property(e => e.StartedAt) + .HasConversion(v => v, v => v.HasValue ? DateTime.SpecifyKind(v.Value, DateTimeKind.Utc) : null); + + modelBuilder + .Entity() + .Property(e => e.EndedAt) + .HasConversion(v => v, v => v.HasValue ? DateTime.SpecifyKind(v.Value, DateTimeKind.Utc) : null); + } + } +} -- cgit v1.2.3 From e6a60ae20ad5d925da015d2426f478689d52ecdf Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 16 Jul 2022 16:01:39 -0500 Subject: disambiguate Transfer --- src/slskd/Transfers/ITransferTracker.cs | 2 +- src/slskd/Transfers/TransferTracker.cs | 11 ++++------- 2 files changed, 5 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/ITransferTracker.cs b/src/slskd/Transfers/ITransferTracker.cs index fabcf856..e25539f7 100644 --- a/src/slskd/Transfers/ITransferTracker.cs +++ b/src/slskd/Transfers/ITransferTracker.cs @@ -36,7 +36,7 @@ namespace slskd.Transfers /// /// /// - void AddOrUpdate(Transfer transfer, CancellationTokenSource cancellationTokenSource); + void AddOrUpdate(Soulseek.Transfer transfer, CancellationTokenSource cancellationTokenSource); /// /// Removes a tracked transfer. diff --git a/src/slskd/Transfers/TransferTracker.cs b/src/slskd/Transfers/TransferTracker.cs index 522da0fe..d809e792 100644 --- a/src/slskd/Transfers/TransferTracker.cs +++ b/src/slskd/Transfers/TransferTracker.cs @@ -125,7 +125,7 @@ namespace slskd.Transfers /// /// /// - public void AddOrUpdate(Transfer transfer, CancellationTokenSource cancellationTokenSource) + public void AddOrUpdate(Soulseek.Transfer transfer, CancellationTokenSource cancellationTokenSource) { Transfers.TryGetValue(transfer.Direction, out var direction); @@ -190,18 +190,15 @@ namespace slskd.Transfers /// public bool Contains(TransferDirection direction, string username, string filename) { - if (Transfers.TryGetValue(direction, out var directionDict)) + if (Transfers.TryGetValue(direction, out var directionDict) && directionDict.TryGetValue(username, out var userDict)) { - if (directionDict.TryGetValue(username, out var userDict)) - { - return userDict.Values.Any(record => record.Transfer.Filename == filename); - } + return userDict.Values.Any(record => record.Transfer.Filename == filename); } return false; } - private ConcurrentDictionary GetNewDictionaryForUser(Transfer transfer, CancellationTokenSource cancellationTokenSource) + private ConcurrentDictionary GetNewDictionaryForUser(Soulseek.Transfer transfer, CancellationTokenSource cancellationTokenSource) { var r = new ConcurrentDictionary(); var xfer = API.Transfer.FromSoulseekTransfer(transfer); -- cgit v1.2.3 From aab146e3c05273a61b836e6d4c7fcfc4fdc6b513 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 16 Jul 2022 16:02:00 -0500 Subject: add Transfer context factory to DI --- src/slskd/Program.cs | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index ae4f2015..c462ba52 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -449,6 +449,7 @@ namespace slskd services.AddSingleton(); services.AddDbContext("search.db"); + services.AddDbContext("transfers.db"); services.AddSingleton(); services.AddSingleton(); -- cgit v1.2.3 From 1f482b465ac371b44c1dfa118b0a5e7e61617ddb Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 16 Jul 2022 16:06:30 -0500 Subject: add WithSoulseekTransfer extension --- src/slskd/Transfers/Extensions.cs | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 src/slskd/Transfers/Extensions.cs (limited to 'src') diff --git a/src/slskd/Transfers/Extensions.cs b/src/slskd/Transfers/Extensions.cs new file mode 100644 index 00000000..9b8845f1 --- /dev/null +++ b/src/slskd/Transfers/Extensions.cs @@ -0,0 +1,26 @@ +namespace slskd.Transfers +{ + public static class Extensions + { + public static Transfer WithSoulseekTransfer(this Transfer transfer, Soulseek.Transfer t) + { + return new Transfer() + { + Id = transfer.Id, + Username = transfer.Username, + Direction = transfer.Direction, + Filename = transfer.Filename, + Size = transfer.Size, + StartOffset = transfer.StartOffset, + State = t.State, + RequestedAt = transfer.RequestedAt, + EnqueuedAt = transfer.EnqueuedAt, + StartedAt = t.StartTime, + EndedAt = t.EndTime, + BytesTransferred = t.BytesTransferred, + AverageSpeed = t.AverageSpeed, + Exception = t.Exception, + }; + } + } +} -- cgit v1.2.3 From ca4eeb32e145c4b17705ece252fda412db746586 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 16 Jul 2022 16:06:48 -0500 Subject: docs --- src/slskd/Core/Extensions.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Core/Extensions.cs b/src/slskd/Core/Extensions.cs index d818d387..65942180 100644 --- a/src/slskd/Core/Extensions.cs +++ b/src/slskd/Core/Extensions.cs @@ -75,7 +75,7 @@ namespace slskd /// /// Creates a new instance of from this instance of . /// - /// The UserStatistics instance from which to copy data + /// The UserStatistics instance from which to copy data. /// The new instance. public static UserStatisticsState ToUserStatisticsState(this UserStatistics stats) => new() { -- cgit v1.2.3 From 8432e1395cbe4f5788dec579fbf0516f59847f34 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 16 Jul 2022 16:07:06 -0500 Subject: stub DownloadService --- src/slskd/Transfers/Downloads/DownloadService.cs | 262 +++++++++++++++++++++++ 1 file changed, 262 insertions(+) create mode 100644 src/slskd/Transfers/Downloads/DownloadService.cs (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs new file mode 100644 index 00000000..bca7ca12 --- /dev/null +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -0,0 +1,262 @@ +// +// 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/. +// + +using Microsoft.Extensions.Options; +using Soulseek; + +namespace slskd.Transfers.Downloads +{ + using System; + 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 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); + Task RemoveAsync(Guid id, bool cancel = false); + Task FindAsync(Expression> expression); + Task> ListAsync(Expression> expression = null); + } + + /// + /// Manages downloads. + /// + public class DownloadService : IDownloadService + { + public DownloadService( + IOptionsSnapshot options, + ISoulseekClient soulseekClient, + ITransferTracker tracker, + IDbContextFactory contextFactory, + IFTPService ftpClient) + { + Client = soulseekClient; + Tracker = tracker; + Options = options.Value; + FTP = ftpClient; + } + + private IDbContextFactory ContextFactory { get; } + private Options Options { get; } + private ISoulseekClient Client { get; } + private ITransferTracker Tracker { get; } + private IFTPService FTP { get; } + private ILogger Log { get; } = Serilog.Log.ForContext(); + + public Task CancelAsync(Guid id) + { + throw new NotImplementedException(); + } + + /// + /// 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. + public async Task EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files) + { + try + { + Log.Information("Downloading {Count} files from user {Username}", files.Count(), username); + + Log.Debug("Priming connection for user {Username}", username); + await Client.ConnectToUserAsync(username, invalidateCache: false); + Log.Debug("Connection for user '{Username}' primed", username); + + var thrownExceptions = new List(); + + foreach (var file in files) + { + Log.Debug("Attempting to enqueue {Filename} from user {Username}", file.Filename, username); + + var transfer = new Transfer() + { + Id = Guid.NewGuid(), + Username = username, + Direction = TransferDirection.Download, + Filename = file.Filename, + Size = file.Size, + StartOffset = 0, + RequestedAt = DateTime.UtcNow, + }; + + using var context = ContextFactory.CreateDbContext(); + context.Add(transfer); + + var waitUntilEnqueue = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var cts = new CancellationTokenSource(); + + var downloadTask = Task.Run(async () => + { + using var context = ContextFactory.CreateDbContext(); + using var rateLimiter = new RateLimiter(250); + + await Client.DownloadAsync(username, file.Filename, () => GetLocalFileStream(file.Filename, Options.Directories.Incomplete), file.Size, 0, token: null, new TransferOptions(disposeOutputStreamOnCompletion: true, stateChanged: (e) => + { + Log.Debug("Download of {Filename} from user {Username} changed state from {Previous} to {New}", file.Filename, username, e.PreviousState, e.Transfer.State); + + transfer.UpdateFromSoulseekTransfer(e.Transfer); + + 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); + + // TODO: transfer is complete. make sure a final broadcast is sent + // TODO: save final state in db + + MoveFile(file.Filename, Options.Directories.Incomplete, Options.Directories.Downloads); + + if (Options.Integration.Ftp.Enabled) + { + _ = FTP.UploadAsync(file.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); + + // the download task finished first, meaning the transfer was stopped before it was enqueued (and therefore threw) + if (task == downloadTask) + { + 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) + { + 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; + 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); + } + + await context.SaveChangesAsync(); + } + + if (thrownExceptions.Any()) + { + throw new AggregateException(thrownExceptions); + } + + 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; + } + } + + public Task FindAsync(Expression> expression) + { + throw new NotImplementedException(); + } + + public Task GetPlaceInQueueAsync(Guid id) + { + throw new NotImplementedException(); + } + + public Task> ListAsync(Expression> expression = null) + { + throw new NotImplementedException(); + } + + public Task RemoveAsync(Guid id, bool cancel = false) + { + throw new NotImplementedException(); + } + + private static FileStream GetLocalFileStream(string remoteFilename, string saveDirectory) + { + var localFilename = remoteFilename.ToLocalFilename(baseDirectory: saveDirectory); + var path = Path.GetDirectoryName(localFilename); + + if (!Directory.Exists(path)) + { + 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 (!Directory.Exists(destinationPath)) + { + Directory.CreateDirectory(destinationPath); + } + + File.Move(sourceFilename, destinationFilename, overwrite: true); + + if (!Directory.EnumerateFileSystemEntries(Path.GetDirectoryName(sourceFilename)).Any()) + { + Directory.Delete(Path.GetDirectoryName(sourceFilename)); + } + } + } +} -- cgit v1.2.3 From 36ba3ab11afa871a2fa34a2383b455686989566d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 17 Jul 2022 17:19:53 -0500 Subject: simplify interface of UploadGovernor and UploadQueue --- src/slskd/Application.cs | 10 +-- src/slskd/Transfers/Uploads/UploadGovernor.cs | 25 +++--- src/slskd/Transfers/Uploads/UploadQueue.cs | 55 +++++++------ .../Transfers/Uploads/UploadQueueTests.cs | 95 +++++++++------------- 4 files changed, 84 insertions(+), 101 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index a307a291..249376fd 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -636,14 +636,14 @@ namespace slskd if (e.Transfer.State.HasFlag(TransferStates.Queued)) { - Transfers.Uploads.Queue.Enqueue(e.Transfer); + Transfers.Uploads.Queue.Enqueue(e.Transfer.Username, e.Transfer.Filename); } }, progressUpdated: (e) => tracker.AddOrUpdate(e.Transfer, cts), - governor: (tx, req, ct) => Transfers.Uploads.Governor.GetBytesAsync(tx, req, ct), - reporter: (tx, att, grant, act) => Transfers.Uploads.Governor.ReturnBytes(tx, att, grant, act), - slotAwaiter: (tx, ct) => Transfers.Uploads.Queue.AwaitStartAsync(tx), - slotReleased: (tx) => Transfers.Uploads.Queue.Complete(tx)); + governor: (tx, req, ct) => Transfers.Uploads.Governor.GetBytesAsync(tx.Username, req, ct), + reporter: (tx, att, grant, act) => Transfers.Uploads.Governor.ReturnBytes(tx.Username, att, grant, act), + slotAwaiter: (tx, ct) => Transfers.Uploads.Queue.AwaitStartAsync(tx.Username, tx.Filename), + slotReleased: (tx) => Transfers.Uploads.Queue.Complete(tx.Username, tx.Filename)); // accept all download requests, and begin the upload immediately. normally there would be an internal queue, and // uploads would be handled separately. diff --git a/src/slskd/Transfers/Uploads/UploadGovernor.cs b/src/slskd/Transfers/Uploads/UploadGovernor.cs index a806815f..0f481e69 100644 --- a/src/slskd/Transfers/Uploads/UploadGovernor.cs +++ b/src/slskd/Transfers/Uploads/UploadGovernor.cs @@ -24,7 +24,6 @@ namespace slskd.Transfers using System.Threading; using System.Threading.Tasks; using slskd.Users; - using Soulseek; /// /// Governs upload transfer speed. @@ -32,26 +31,26 @@ namespace slskd.Transfers public interface IUploadGovernor { /// - /// Asynchronously obtains a grant of for the specified . + /// Asynchronously obtains a grant of for the requesting . /// /// /// This operation completes when any number of bytes can be granted. The amount returned may be smaller than the /// requested amount. /// - /// The transfer for which the grant is requested. + /// The username of the requesting user. /// The number of requested bytes. /// The token to monitor for cancellation. /// The operation context, including the number of bytes granted. - Task GetBytesAsync(Transfer transfer, int requestedBytes, CancellationToken cancellationToken); + Task GetBytesAsync(string username, int requestedBytes, CancellationToken cancellationToken); /// /// Returns wasted bytes for redistribution. /// - /// The transfer which generated the waste. + /// The username of the user that generated the waste. /// The number of bytes that were attempted to be transferred. /// The number of bytes granted by all governors in the system. /// The actual number of bytes transferred. - public void ReturnBytes(Transfer transfer, int attemptedBytes, int grantedBytes, int actualBytes); + public void ReturnBytes(string username, int attemptedBytes, int grantedBytes, int actualBytes); } /// @@ -83,19 +82,19 @@ namespace slskd.Transfers private IUserService Users { get; } /// - /// Asynchronously obtains a grant of for the specified . + /// Asynchronously obtains a grant of for the requesting . /// /// /// This operation completes when any number of bytes can be granted. The amount returned may be smaller than the /// requested amount. /// - /// The transfer for which the grant is requested. + /// The username of the requesting user. /// The number of requested bytes. /// The token to monitor for cancellation. /// The operation context, including the number of bytes granted. - public Task GetBytesAsync(Transfer transfer, int requestedBytes, CancellationToken cancellationToken) + public Task GetBytesAsync(string username, int requestedBytes, CancellationToken cancellationToken) { - var group = Users.GetGroup(transfer.Username); + var group = Users.GetGroup(username); var bucket = TokenBuckets.GetValueOrDefault(group ?? string.Empty, TokenBuckets[Application.DefaultGroup]); return bucket.GetAsync(requestedBytes, cancellationToken); @@ -104,11 +103,11 @@ namespace slskd.Transfers /// /// Returns wasted bytes for redistribution. /// - /// The transfer which generated the waste. + /// The username of the user that generated the waste. /// The number of bytes that were attempted to be transferred. /// The number of bytes granted by all governors in the system. /// The actual number of bytes transferred. - public void ReturnBytes(Transfer transfer, int attemptedBytes, int grantedBytes, int actualBytes) + public void ReturnBytes(string username, int attemptedBytes, int grantedBytes, int actualBytes) { var waste = Math.Max(0, grantedBytes - actualBytes); @@ -117,7 +116,7 @@ namespace slskd.Transfers return; } - var group = Users.GetGroup(transfer.Username); + var group = Users.GetGroup(username); var bucket = TokenBuckets.GetValueOrDefault(group ?? string.Empty, TokenBuckets[Application.DefaultGroup]); // we don't have enough information to tell whether grantedBytes was reduced by the global limiter within diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index f694a887..9ac6b385 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -28,7 +28,6 @@ namespace slskd.Transfers using System.Threading.Tasks; using Serilog; using slskd.Users; - using Soulseek; /// /// Orchestrates uploads. @@ -38,21 +37,24 @@ namespace slskd.Transfers /// /// Awaits the start of an upload. /// - /// The upload for which to wait. + /// The username of the remote user. + /// The filename for which to await the start. /// The operation context. - Task AwaitStartAsync(Transfer transfer); + Task AwaitStartAsync(string username, string filename); /// /// Signals the completion of an upload. /// - /// The completed upload. - void Complete(Transfer transfer); + /// The username of the remote user. + /// The completed filename. + void Complete(string username, string filename); /// /// Enqueues an upload. /// - /// The upload to enqueue. - void Enqueue(Transfer transfer); + /// The username of the remote user. + /// The filename to enqueue. + void Enqueue(string username, string filename); /// /// Computes the estimated queue position of the specified for the specified . @@ -109,24 +111,25 @@ namespace slskd.Transfers /// /// Awaits the start of an upload. /// - /// The upload for which to wait. + /// The username of the remote user. + /// The filename for which to await the start. /// The operation context. - public Task AwaitStartAsync(Transfer transfer) + public Task AwaitStartAsync(string username, string filename) { SyncRoot.Wait(); try { - if (!Uploads.TryGetValue(transfer.Username, out var list)) + if (!Uploads.TryGetValue(username, out var list)) { - throw new SlskdException($"No enqueued uploads for user {transfer.Username}"); + throw new SlskdException($"No enqueued uploads for user {username}"); } - var upload = list.FirstOrDefault(e => e.Filename == transfer.Filename); + var upload = list.FirstOrDefault(e => e.Filename == filename); if (upload == default) { - throw new SlskdException($"File {transfer.Filename} is not enqueued for user {transfer.Username}"); + throw new SlskdException($"File {filename} is not enqueued for user {username}"); } upload.Ready = DateTime.UtcNow; @@ -144,23 +147,24 @@ namespace slskd.Transfers /// /// Signals the completion of an upload. /// - /// The completed upload. - public void Complete(Transfer transfer) + /// The username of the remote user. + /// The completed filename. + public void Complete(string username, string filename) { SyncRoot.Wait(); try { - if (!Uploads.TryGetValue(transfer.Username, out var list)) + if (!Uploads.TryGetValue(username, out var list)) { - throw new SlskdException($"No enqueued uploads for user {transfer.Username}"); + throw new SlskdException($"No enqueued uploads for user {username}"); } - var upload = list.FirstOrDefault(e => e.Filename == transfer.Filename); + var upload = list.FirstOrDefault(e => e.Filename == filename); if (upload == default) { - throw new SlskdException($"File {transfer.Filename} is not enqueued for user {transfer.Username}"); + throw new SlskdException($"File {filename} is not enqueued for user {username}"); } list.Remove(upload); @@ -176,9 +180,9 @@ namespace slskd.Transfers Log.Debug("Group {Group} slots: {Used}/{Available}", group.Name, group.UsedSlots, group.Slots); } - if (!list.Any() && Uploads.TryRemove(transfer.Username, out _)) + if (!list.Any() && Uploads.TryRemove(username, out _)) { - Log.Debug("Cleaned up tracking list for {User}; no more queued uploads to track", transfer.Username); + Log.Debug("Cleaned up tracking list for {User}; no more queued uploads to track", username); } } finally @@ -191,17 +195,18 @@ namespace slskd.Transfers /// /// Enqueues an upload. /// - /// The upload to enqueue. - public void Enqueue(Transfer transfer) + /// The username of the remote user. + /// The filename to enqueue. + public void Enqueue(string username, string filename) { SyncRoot.Wait(); try { - var upload = new Upload() { Username = transfer.Username, Filename = transfer.Filename }; + var upload = new Upload() { Username = username, Filename = filename }; Uploads.AddOrUpdate( - key: transfer.Username, + key: username, addValue: new List(new[] { upload }), updateValueFactory: (key, list) => { diff --git a/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs b/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs index d1caeac9..6b9f442c 100644 --- a/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs @@ -284,50 +284,45 @@ public void Enqueue_Enqueues_If_Nothing_Is_Enqueued_Already(string username, string filename) { var (queue, _) = GetFixture(); - var tx = GetTransfer(username, filename); - + Assert.Empty(queue.GetProperty>>("Uploads")); - queue.Enqueue(tx); + queue.Enqueue(username, filename); var uploads = queue.GetProperty>>("Uploads"); Assert.Single(uploads); Assert.True(uploads.ContainsKey(username)); Assert.Single(uploads.GetValueOrDefault(username)); - Assert.Equal(tx.Filename, uploads.GetValueOrDefault(username).First().Filename); + Assert.Equal(filename, uploads.GetValueOrDefault(username).First().Filename); } [Theory, AutoData] public void Enqueue_Enqueues_If_Something_Is_Enqueued_Already(string username, string filename, string filename2) { var (queue, _) = GetFixture(); - var tx = GetTransfer(username, filename); - var tx2 = GetTransfer(username, filename2); - - queue.Enqueue(tx); - queue.Enqueue(tx2); + + queue.Enqueue(username, filename); + queue.Enqueue(username, filename2); var uploads = queue.GetProperty>>("Uploads"); Assert.Single(uploads); Assert.True(uploads.ContainsKey(username)); Assert.Equal(2, uploads.GetValueOrDefault(username).Count); - Assert.Equal(tx.Filename, uploads.GetValueOrDefault(username)[0].Filename); - Assert.Equal(tx2.Filename, uploads.GetValueOrDefault(username)[1].Filename); + Assert.Equal(filename, uploads.GetValueOrDefault(username)[0].Filename); + Assert.Equal(filename2, uploads.GetValueOrDefault(username)[1].Filename); } [Theory, AutoData] public void Enqueue_Enqueues_Transfers_From_Different_Users(string username, string filename, string username2, string filename2) { var (queue, _) = GetFixture(); - var tx = GetTransfer(username, filename); - var tx2 = GetTransfer(username2, filename2); Assert.Empty(queue.GetProperty>>("Uploads")); - queue.Enqueue(tx); - queue.Enqueue(tx2); + queue.Enqueue(username, filename); + queue.Enqueue(username, filename2); var uploads = queue.GetProperty>>("Uploads"); @@ -337,11 +332,11 @@ // username should have a list containing 1 file Assert.Single(uploads.GetValueOrDefault(username)); - Assert.Equal(tx.Filename, uploads.GetValueOrDefault(username).First().Filename); + Assert.Equal(filename, uploads.GetValueOrDefault(username).First().Filename); // username2 should also have a list containing 1 file Assert.Single(uploads.GetValueOrDefault(username2)); - Assert.Equal(tx2.Filename, uploads.GetValueOrDefault(username2).First().Filename); + Assert.Equal(filename2, uploads.GetValueOrDefault(username2).First().Filename); } } @@ -351,9 +346,8 @@ public void Throws_If_No_Such_Username(string username, string filename) { var (queue, _) = GetFixture(); - var tx = GetTransfer(username, filename); - var ex = Record.Exception(() => queue.Complete(tx)); + var ex = Record.Exception(() => queue.Complete(username, filename)); Assert.NotNull(ex); Assert.IsType(ex); @@ -364,12 +358,10 @@ public void Throws_If_No_Such_Filename(string username, string filename) { var (queue, _) = GetFixture(); - var tx = GetTransfer(username, filename); - var badTx = GetTransfer(username, "foo"); - queue.Enqueue(tx); + queue.Enqueue(username, filename); - var ex = Record.Exception(() => queue.Complete(badTx)); + var ex = Record.Exception(() => queue.Complete(username, "foo")); Assert.NotNull(ex); Assert.IsType(ex); @@ -380,15 +372,13 @@ public async Task Removes_Filename(string username, string filename, string filename2) { var (queue, _) = GetFixture(); - var tx = GetTransfer(username, filename); - var tx2 = GetTransfer(username, filename2); - queue.Enqueue(tx); - await queue.AwaitStartAsync(tx); - queue.Enqueue(tx2); - await queue.AwaitStartAsync(tx2); + queue.Enqueue(username, filename); + await queue.AwaitStartAsync(username, filename); + queue.Enqueue(username, filename2); + await queue.AwaitStartAsync(username, filename2); - queue.Complete(tx); + queue.Complete(username, filename); var uploads = queue.GetProperty>>("Uploads"); @@ -402,20 +392,18 @@ public async Task Decrements_UsedSlots_For_Group(string username, string filename, string filename2) { var (queue, _) = GetFixture(); - var tx = GetTransfer(username, filename); - var tx2 = GetTransfer(username, filename2); - queue.Enqueue(tx); - await queue.AwaitStartAsync(tx); + queue.Enqueue(username, filename); + await queue.AwaitStartAsync(username, filename); - queue.Enqueue(tx2); - await queue.AwaitStartAsync(tx2); + queue.Enqueue(username, filename2); + await queue.AwaitStartAsync(username, filename2); var groups = queue.GetProperty>("Groups"); Assert.Equal(2, groups[Application.DefaultGroup].UsedSlots); - queue.Complete(tx); + queue.Complete(username, filename); groups = queue.GetProperty>("Groups"); @@ -426,18 +414,16 @@ public void Cleans_Up_If_User_Has_No_More_Files_Enqueued(string username, string filename, string filename2) { var (queue, _) = GetFixture(); - var tx = GetTransfer(username, filename); - var tx2 = GetTransfer(username, filename2); - queue.Enqueue(tx); - queue.Enqueue(tx2); + queue.Enqueue(username, filename); + queue.Enqueue(username, filename2); var uploads = queue.GetProperty>>("Uploads"); Assert.Single(uploads); - queue.Complete(tx); - queue.Complete(tx2); + queue.Complete(username, filename); + queue.Complete(username, filename2); uploads = queue.GetProperty>>("Uploads"); @@ -451,9 +437,8 @@ public async Task Throws_If_No_Such_Username(string username, string filename) { var (queue, _) = GetFixture(); - var tx = GetTransfer(username, filename); - - var ex = await Record.ExceptionAsync(() => queue.AwaitStartAsync(tx)); + + var ex = await Record.ExceptionAsync(() => queue.AwaitStartAsync(username, filename)); Assert.NotNull(ex); Assert.IsType(ex); @@ -464,12 +449,10 @@ public async Task Throws_If_No_Such_Filename(string username, string filename) { var (queue, _) = GetFixture(); - var tx = GetTransfer(username, filename); - var badTx = GetTransfer(username, "foo"); + + queue.Enqueue(username, filename); - queue.Enqueue(tx); - - var ex = await Record.ExceptionAsync(() => queue.AwaitStartAsync(badTx)); + var ex = await Record.ExceptionAsync(() => queue.AwaitStartAsync(username, "foo")); Assert.NotNull(ex); Assert.IsType(ex); @@ -480,13 +463,12 @@ public void Returns_Task_Associated_With_Upload(string username, string filename) { var (queue, _) = GetFixture(); - var tx = GetTransfer(username, filename); - - queue.Enqueue(tx); + + queue.Enqueue(username, filename); var uploads = queue.GetProperty>>("Uploads"); - var task = queue.AwaitStartAsync(tx); + var task = queue.AwaitStartAsync(username, filename); Assert.Equal(task, uploads[username][0].TaskCompletionSource.Task); } @@ -707,9 +689,6 @@ return (queue, mocks); } - private static Transfer GetTransfer(string username, string filename) - => new Transfer(TransferDirection.Upload, username, filename, 0, TransferStates.Queued, 0, 0); - private class Mocks { public Mocks(Options options = null) -- cgit v1.2.3 From 7896c91e3e8e68cf9600443977f7f721086a1170 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 17 Jul 2022 17:20:29 -0500 Subject: use string Exceptions, add flag for removed --- src/slskd/Transfers/Types/Transfer.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Types/Transfer.cs b/src/slskd/Transfers/Types/Transfer.cs index 514d2c12..420268bd 100644 --- a/src/slskd/Transfers/Types/Transfer.cs +++ b/src/slskd/Transfers/Types/Transfer.cs @@ -40,10 +40,12 @@ namespace slskd.Transfers public long BytesTransferred { get; set; } public double AverageSpeed { get; set; } - public Exception Exception { get; set; } + public string Exception { get; set; } + + public bool Removed { get; set; } [NotMapped] - public long BytesRemaining => Size - BytesTransferred : null; + public long BytesRemaining => Size - BytesTransferred; [NotMapped] public TimeSpan? ElapsedTime => StartedAt == null ? null : (EndedAt ?? DateTime.UtcNow) - StartedAt.Value; [NotMapped] -- cgit v1.2.3 From 48cb92f1fb683a88f769a6bb7c3cda9acba8a6c8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 17 Jul 2022 17:20:40 -0500 Subject: docs --- src/slskd/Transfers/Extensions.cs | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Extensions.cs b/src/slskd/Transfers/Extensions.cs index 9b8845f1..fea1aa68 100644 --- a/src/slskd/Transfers/Extensions.cs +++ b/src/slskd/Transfers/Extensions.cs @@ -1,4 +1,21 @@ -namespace slskd.Transfers +// +// 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 { public static class Extensions { @@ -19,7 +36,7 @@ EndedAt = t.EndTime, BytesTransferred = t.BytesTransferred, AverageSpeed = t.AverageSpeed, - Exception = t.Exception, + Exception = t.Exception?.Message, }; } } -- cgit v1.2.3 From 760827394b933a0631408e2030bb59aa047e30d4 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 17 Jul 2022 17:20:53 -0500 Subject: remove token, make size required --- src/slskd/Transfers/API/DTO/QueueDownloadRequest.cs | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/API/DTO/QueueDownloadRequest.cs b/src/slskd/Transfers/API/DTO/QueueDownloadRequest.cs index 5e8807c2..62e6316c 100644 --- a/src/slskd/Transfers/API/DTO/QueueDownloadRequest.cs +++ b/src/slskd/Transfers/API/DTO/QueueDownloadRequest.cs @@ -27,11 +27,6 @@ namespace slskd.Transfers.API /// /// Gets or sets the size of the file. /// - public long? Size { get; set; } - - /// - /// Gets or sets the optional transfer token. - /// - public int? Token { get; set; } + public long Size { get; set; } } } -- cgit v1.2.3 From 51ce1487e3e71ecd2f00813419b715e9fba20895 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 17 Jul 2022 17:21:12 -0500 Subject: store enums as strings --- src/slskd/Transfers/TransfersDbContext.cs | 11 +++++++++++ 1 file changed, 11 insertions(+) (limited to 'src') diff --git a/src/slskd/Transfers/TransfersDbContext.cs b/src/slskd/Transfers/TransfersDbContext.cs index 5feee8fd..a0fad4ee 100644 --- a/src/slskd/Transfers/TransfersDbContext.cs +++ b/src/slskd/Transfers/TransfersDbContext.cs @@ -19,6 +19,7 @@ namespace slskd.Transfers { using System; using Microsoft.EntityFrameworkCore; + using Microsoft.EntityFrameworkCore.Storage.ValueConversion; public class TransfersDbContext : DbContext { @@ -39,6 +40,16 @@ namespace slskd.Transfers .Entity() .Property(e => e.EndedAt) .HasConversion(v => v, v => v.HasValue ? DateTime.SpecifyKind(v.Value, DateTimeKind.Utc) : null); + + modelBuilder + .Entity() + .Property(d => d.Direction) + .HasConversion(new EnumToStringConverter()); + + modelBuilder + .Entity() + .Property(d => d.State) + .HasConversion(new EnumToStringConverter()); } } } -- 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') 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 576e33793c15a16e595b45d1c3abe29316553168 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 17 Jul 2022 17:21:53 -0500 Subject: finish rough implementation of transfer tracking --- src/slskd/Transfers/Downloads/DownloadService.cs | 90 +++++++++++++++++------- 1 file changed, 63 insertions(+), 27 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index bca7ca12..16be60ca 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -61,7 +61,7 @@ namespace slskd.Transfers.Downloads public class DownloadService : IDownloadService { public DownloadService( - IOptionsSnapshot options, + IOptionsMonitor optionsMonitor, ISoulseekClient soulseekClient, ITransferTracker tracker, IDbContextFactory contextFactory, @@ -69,12 +69,13 @@ namespace slskd.Transfers.Downloads { Client = soulseekClient; Tracker = tracker; - Options = options.Value; + OptionsMonitor = optionsMonitor; + ContextFactory = contextFactory; FTP = ftpClient; } private IDbContextFactory ContextFactory { get; } - private Options Options { get; } + private IOptionsMonitor OptionsMonitor { get; } private ISoulseekClient Client { get; } private ITransferTracker Tracker { get; } private IFTPService FTP { get; } @@ -122,39 +123,73 @@ namespace slskd.Transfers.Downloads RequestedAt = DateTime.UtcNow, }; + // persist the transfer to the database so we have a record that it was attempted using var context = ContextFactory.CreateDbContext(); context.Add(transfer); + await context.SaveChangesAsync(); var waitUntilEnqueue = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var cts = new CancellationTokenSource(); - var downloadTask = Task.Run(async () => + async Task UpdateAndSaveChangesAsync(Transfer transfer) { using var context = ContextFactory.CreateDbContext(); - using var rateLimiter = new RateLimiter(250); - - await Client.DownloadAsync(username, file.Filename, () => GetLocalFileStream(file.Filename, Options.Directories.Incomplete), file.Size, 0, token: null, new TransferOptions(disposeOutputStreamOnCompletion: true, stateChanged: (e) => - { - Log.Debug("Download of {Filename} from user {Username} changed state from {Previous} to {New}", file.Filename, username, e.PreviousState, e.Transfer.State); - - transfer.UpdateFromSoulseekTransfer(e.Transfer); - - 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); - - // TODO: transfer is complete. make sure a final broadcast is sent - // TODO: save final state in db + context.Update(transfer); + await context.SaveChangesAsync(); + } - MoveFile(file.Filename, Options.Directories.Incomplete, Options.Directories.Downloads); + // 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); - if (Options.Integration.Ftp.Enabled) + 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(Options.Directories.Downloads)); + _ = FTP.UploadAsync(file.Filename.ToLocalFilename(OptionsMonitor.CurrentValue.Directories.Downloads)); } }); @@ -162,7 +197,8 @@ namespace slskd.Transfers.Downloads // downloadTask throws due to an error prior to successfully queueing. var task = await Task.WhenAny(waitUntilEnqueue.Task, downloadTask); - // the download task finished first, meaning the transfer was stopped before it was enqueued (and therefore threw) + // 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; @@ -179,7 +215,7 @@ namespace slskd.Transfers.Downloads Log.Error("Failed to download {Filename} from {Username}: {Message}", file.Filename, username, ex.Message); thrownExceptions.Add(ex); - transfer.Exception = ex; + transfer.Exception = ex.Message; transfer.State = TransferStates.Completed | TransferStates.Errored; transfer.EndedAt = DateTime.UtcNow; } -- cgit v1.2.3 From 04149588c843f2a11dba5a07fb991bd723ab55d0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 17 Jul 2022 17:22:16 -0500 Subject: wire up DownloadsService --- src/slskd/Program.cs | 5 ++++- src/slskd/Transfers/TransferService.cs | 16 +++++++++++++++- 2 files changed, 19 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index c462ba52..1d845ab1 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -60,6 +60,7 @@ namespace slskd using slskd.Search.API; using slskd.Shares; using slskd.Transfers; + using slskd.Transfers.Downloads; using slskd.Users; using slskd.Validation; using Soulseek; @@ -461,7 +462,9 @@ namespace slskd services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); @@ -790,7 +793,7 @@ namespace slskd try { - services.AddDbContextFactory(options => + services.AddDbContextFactory(options => { options.UseSqlite($"Data Source={Path.Combine(AppDirectory, "data", filename)}"); }); diff --git a/src/slskd/Transfers/TransferService.cs b/src/slskd/Transfers/TransferService.cs index 714d85be..253dc318 100644 --- a/src/slskd/Transfers/TransferService.cs +++ b/src/slskd/Transfers/TransferService.cs @@ -19,6 +19,7 @@ using Microsoft.Extensions.Options; namespace slskd.Transfers { + using slskd.Transfers.Downloads; using slskd.Transfers.Uploads; using slskd.Users; @@ -31,6 +32,11 @@ namespace slskd.Transfers /// Gets the upload service. /// IUploadService Uploads { get; } + + /// + /// Gets the download service. + /// + IDownloadService Downloads { get; } } /// @@ -47,7 +53,8 @@ namespace slskd.Transfers public TransferService( IUserService userService, IOptionsMonitor optionsMonitor, - IUploadService uploadService = null) + IUploadService uploadService = null, + IDownloadService downloadService = null) { Users = userService; OptionsMonitor = optionsMonitor; @@ -57,6 +64,8 @@ namespace slskd.Transfers Governor = new UploadGovernor(userService: Users, optionsMonitor: OptionsMonitor), Queue = new UploadQueue(userService: Users, optionsMonitor: OptionsMonitor), }; + + Downloads = downloadService; } /// @@ -64,6 +73,11 @@ namespace slskd.Transfers /// public IUploadService Uploads { get; init; } + /// + /// Gets the download service. + /// + public IDownloadService Downloads { get; init; } + private IOptionsMonitor OptionsMonitor { get; init; } private IUserService Users { get; init; } } -- cgit v1.2.3 From a1216bec78d112ec443262429c03bef8f53b8072 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 18 Jul 2022 09:42:29 -0500 Subject: add Transfers DbSet --- src/slskd/Transfers/TransfersDbContext.cs | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src') diff --git a/src/slskd/Transfers/TransfersDbContext.cs b/src/slskd/Transfers/TransfersDbContext.cs index a0fad4ee..3b226016 100644 --- a/src/slskd/Transfers/TransfersDbContext.cs +++ b/src/slskd/Transfers/TransfersDbContext.cs @@ -29,6 +29,8 @@ namespace slskd.Transfers Database.EnsureCreated(); } + public DbSet Transfers { get; set;} + protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder -- cgit v1.2.3 From f9ab494734f139539aa1668e5fc0ca87a8e37525 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 18 Jul 2022 09:43:08 -0500 Subject: stub rest of the Downloads service --- src/slskd/Transfers/Downloads/DownloadService.cs | 194 ++++++++++++++++------- 1 file changed, 135 insertions(+), 59 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 16be60ca..0a9ef335 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -21,6 +21,7 @@ using Soulseek; namespace slskd.Transfers.Downloads { using System; + using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; @@ -49,8 +50,8 @@ namespace slskd.Transfers.Downloads /// 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); - Task RemoveAsync(Guid id, bool cancel = false); + Task CancelAsync(Guid id, bool remove = false); + Task RemoveAsync(Guid id); Task FindAsync(Expression> expression); Task> ListAsync(Expression> expression = null); } @@ -80,10 +81,23 @@ namespace slskd.Transfers.Downloads private ITransferTracker Tracker { get; } private IFTPService FTP { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); + private ConcurrentDictionary CancellationTokens { get; } = new ConcurrentDictionary(); - public Task CancelAsync(Guid id) + public async Task CancelAsync(Guid id, bool remove = false) { - throw new NotImplementedException(); + if (CancellationTokens.TryRemove(id, out var cts)) + { + cts.Cancel(); + + if (remove) + { + await RemoveAsync(id); + } + + return true; + } + + return false; } /// @@ -112,9 +126,11 @@ namespace slskd.Transfers.Downloads { Log.Debug("Attempting to enqueue {Filename} from user {Username}", file.Filename, username); + var id = Guid.NewGuid(); + var transfer = new Transfer() { - Id = Guid.NewGuid(), + Id = id, Username = username, Direction = TransferDirection.Download, Filename = file.Filename, @@ -124,16 +140,18 @@ namespace slskd.Transfers.Downloads }; // persist the transfer to the database so we have a record that it was attempted - using var context = ContextFactory.CreateDbContext(); + using var context = await ContextFactory.CreateDbContextAsync(); context.Add(transfer); await context.SaveChangesAsync(); - var waitUntilEnqueue = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var cts = new CancellationTokenSource(); + CancellationTokens.TryAdd(id, cts); + + var waitUntilEnqueue = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); async Task UpdateAndSaveChangesAsync(Transfer transfer) { - using var context = ContextFactory.CreateDbContext(); + using var context = await ContextFactory.CreateDbContextAsync(); context.Update(transfer); await context.SaveChangesAsync(); } @@ -145,51 +163,58 @@ namespace slskd.Transfers.Downloads { using var rateLimiter = new RateLimiter(250); - 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) + 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); + + 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(() => { - 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) + 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 { - _ = FTP.UploadAsync(file.Filename.ToLocalFilename(OptionsMonitor.CurrentValue.Directories.Downloads)); + CancellationTokens.TryRemove(id, out _); } }); @@ -242,24 +267,75 @@ namespace slskd.Transfers.Downloads } } - public Task FindAsync(Expression> expression) + public async Task FindAsync(Expression> expression) { - throw new NotImplementedException(); + try + { + var context = await ContextFactory.CreateDbContextAsync(); + return await context.Transfers.Where(expression).FirstOrDefaultAsync(); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to find download: {Message}", ex.Message); + throw; + } } - public Task GetPlaceInQueueAsync(Guid id) + public async Task GetPlaceInQueueAsync(Guid id) { - throw new NotImplementedException(); + try + { + var transfer = await FindAsync(tx => tx.Id == id); + + if (transfer == default) + { + throw new NotFoundException($"No download matching id ${id}"); + } + + return await Client.GetDownloadPlaceInQueueAsync(transfer.Username, transfer.Filename); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to get place in queue for download {Id}: {Message}", id, ex.Message); + throw; + } } - public Task> ListAsync(Expression> expression = null) + public async Task> ListAsync(Expression> expression = null) { - throw new NotImplementedException(); + try + { + var context = await ContextFactory.CreateDbContextAsync(); + return await context.Transfers.Where(expression).ToListAsync(); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to list downloads: {Message}", ex.Message); + throw; + } } - public Task RemoveAsync(Guid id, bool cancel = false) + public async Task RemoveAsync(Guid id) { - throw new NotImplementedException(); + using var context = await ContextFactory.CreateDbContextAsync(); + var transfer = await context.Transfers.FindAsync(id); + + if (transfer == default) + { + throw new NotFoundException($"No download matching id ${id}"); + } + + transfer.Removed = true; + + try + { + await context.SaveChangesAsync(); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to remove download {Id}: {Message}", id, ex.Message); + throw; + } } private static FileStream GetLocalFileStream(string remoteFilename, string saveDirectory) -- 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') 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 bd6431d76c397aa11f3055e376c8d7bb9404a939 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 19 Jul 2022 08:21:08 -0500 Subject: persist place in queue --- src/slskd/Transfers/Downloads/DownloadService.cs | 28 ++++++++++++++---------- 1 file changed, 17 insertions(+), 11 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 0a9ef335..f53c6004 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -285,14 +285,20 @@ namespace slskd.Transfers.Downloads { try { - var transfer = await FindAsync(tx => tx.Id == id); + var context = await ContextFactory.CreateDbContextAsync(); + var transfer = await context.Transfers.FindAsync(id); if (transfer == default) { throw new NotFoundException($"No download matching id ${id}"); } - return await Client.GetDownloadPlaceInQueueAsync(transfer.Username, transfer.Filename); + var place = await Client.GetDownloadPlaceInQueueAsync(transfer.Username, transfer.Filename); + + transfer.PlaceInQueue = place; + await context.SaveChangesAsync(); + + return place; } catch (Exception ex) { @@ -317,18 +323,18 @@ namespace slskd.Transfers.Downloads public async Task RemoveAsync(Guid id) { - using var context = await ContextFactory.CreateDbContextAsync(); - var transfer = await context.Transfers.FindAsync(id); - - if (transfer == default) + try { - throw new NotFoundException($"No download matching id ${id}"); - } + using var context = await ContextFactory.CreateDbContextAsync(); + var transfer = await context.Transfers.FindAsync(id); - transfer.Removed = true; + if (transfer == default) + { + throw new NotFoundException($"No download matching id ${id}"); + } + + transfer.Removed = true; - try - { await context.SaveChangesAsync(); } catch (Exception ex) -- cgit v1.2.3 From 944011175687fa932f1e123bafb45fa30b395fba Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 19 Jul 2022 08:21:40 -0500 Subject: add PlaceInQueue, ignore Removed when serializing --- src/slskd/Transfers/Types/Transfer.cs | 3 +++ 1 file changed, 3 insertions(+) (limited to 'src') diff --git a/src/slskd/Transfers/Types/Transfer.cs b/src/slskd/Transfers/Types/Transfer.cs index 420268bd..c55826d4 100644 --- a/src/slskd/Transfers/Types/Transfer.cs +++ b/src/slskd/Transfers/Types/Transfer.cs @@ -20,6 +20,7 @@ namespace slskd.Transfers using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; + using System.Text.Json.Serialization; using Soulseek; public class Transfer @@ -40,8 +41,10 @@ namespace slskd.Transfers public long BytesTransferred { get; set; } public double AverageSpeed { get; set; } + public int? PlaceInQueue { get; set; } public string Exception { get; set; } + [JsonIgnore] public bool Removed { get; set; } [NotMapped] -- cgit v1.2.3 From 4f62b41479c3d8c7052b594b228b1fb43ea5b9de Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 19 Jul 2022 08:21:56 -0500 Subject: remove Transfer DTO --- src/slskd/Transfers/API/DTO/Transfer.cs | 154 -------------------------------- 1 file changed, 154 deletions(-) delete mode 100644 src/slskd/Transfers/API/DTO/Transfer.cs (limited to 'src') diff --git a/src/slskd/Transfers/API/DTO/Transfer.cs b/src/slskd/Transfers/API/DTO/Transfer.cs deleted file mode 100644 index 9ceeb79b..00000000 --- a/src/slskd/Transfers/API/DTO/Transfer.cs +++ /dev/null @@ -1,154 +0,0 @@ -// -// 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.API -{ - using System; - using System.Net; - using Soulseek; - - /// - /// A single file transfer. - /// - public class Transfer - { - /// - /// Gets the current average transfer speed. - /// - public double AverageSpeed { get; set; } - - /// - /// Gets the number of remaining bytes to be transferred. - /// - public long BytesRemaining { get; set; } - - /// - /// Gets the total number of bytes transferred. - /// - public long BytesTransferred { get; set; } - - /// - /// Gets the transfer direction. - /// - public TransferDirection Direction { get; set; } - - /// - /// Gets the current duration of the transfer, if it has been started. - /// - public double? ElapsedTime { get; set; } - - /// - /// Gets the UTC time at which the transfer transitioned into the state. - /// - public DateTime? EndTime { get; set; } - - /// - /// Gets the filename of the file to be transferred. - /// - public string Filename { get; set; } - - /// - /// Gets the transfer id. - /// - public string Id => Compute.Sha1Hash(Filename); - - /// - /// Gets the ip endpoint of the remote transfer connection, if one has been established. - /// - public IPEndPoint IPEndPoint { get; set; } - - /// - /// Gets the current progress in percent. - /// - public double PercentComplete { get; set; } - - /// - /// Gets the current place in queue, if it has been fetched. - /// - public int? PlaceInQueue { get; set; } - - /// - /// Gets the projected remaining duration of the transfer. - /// - public double? RemainingTime { get; set; } - - /// - /// Gets the remote unique token for the transfer. - /// - public int? RemoteToken { get; set; } - - /// - /// Gets the size of the file to be transferred, in bytes. - /// - public long Size { get; set; } - - /// - /// Gets the starting offset of the transfer, in bytes. - /// - public long StartOffset { get; set; } - - /// - /// Gets the UTC time at which the transfer transitioned into the state. - /// - public DateTime? StartTime { get; set; } - - /// - /// Gets the state of the transfer. - /// - public TransferStates State { get; set; } - - /// - /// Gets the unique token for the transfer. - /// - public int Token { get; set; } - - /// - /// Gets the username of the peer to or from which the file is to be transferred. - /// - public string Username { get; set; } - - /// - /// Gets the Exception that caused the failure of the transfer, if applicable. - /// - public string Exception { get; set; } - - public static Transfer FromSoulseekTransfer(Soulseek.Transfer transfer) - { - return new Transfer() - { - AverageSpeed = transfer.AverageSpeed, - BytesRemaining = transfer.BytesRemaining, - BytesTransferred = transfer.BytesTransferred, - Direction = transfer.Direction, - ElapsedTime = transfer.ElapsedTime?.TotalMilliseconds, - EndTime = transfer.EndTime, - Filename = transfer.Filename, - IPEndPoint = transfer.IPEndPoint, - PercentComplete = transfer.PercentComplete, - RemainingTime = transfer.RemainingTime?.TotalMilliseconds, - RemoteToken = transfer.RemoteToken, - Size = transfer.Size, - StartOffset = transfer.StartOffset, - StartTime = transfer.StartTime, - State = transfer.State, - Token = transfer.Token, - Username = transfer.Username, - Exception = transfer.Exception?.Message, - }; - } - } -} \ No newline at end of file -- cgit v1.2.3 From ad6c2f676e47b909311b9c522c3d361e90697baf Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 19 Jul 2022 08:22:03 -0500 Subject: add grouping DTOs --- src/slskd/Transfers/API/DTO/DirectoryResponse.cs | 28 ++++++++++++++++++++++++ src/slskd/Transfers/API/DTO/UserResponse.cs | 27 +++++++++++++++++++++++ 2 files changed, 55 insertions(+) create mode 100644 src/slskd/Transfers/API/DTO/DirectoryResponse.cs create mode 100644 src/slskd/Transfers/API/DTO/UserResponse.cs (limited to 'src') diff --git a/src/slskd/Transfers/API/DTO/DirectoryResponse.cs b/src/slskd/Transfers/API/DTO/DirectoryResponse.cs new file mode 100644 index 00000000..ba7418b6 --- /dev/null +++ b/src/slskd/Transfers/API/DTO/DirectoryResponse.cs @@ -0,0 +1,28 @@ +// +// 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.API +{ + using System.Collections.Generic; + + public record DirectoryResponse + { + public string Name { get; init; } + public int FileCount { get; init; } + public IEnumerable Files { get; init; } + } +} diff --git a/src/slskd/Transfers/API/DTO/UserResponse.cs b/src/slskd/Transfers/API/DTO/UserResponse.cs new file mode 100644 index 00000000..92605161 --- /dev/null +++ b/src/slskd/Transfers/API/DTO/UserResponse.cs @@ -0,0 +1,27 @@ +// +// 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.API +{ + using System.Collections.Generic; + + public record UserResponse + { + public string Username { get; init; } + public IEnumerable Directories { get; init; } + } +} -- cgit v1.2.3 From dbf9a8742745708d7d9da8f1de12e726f06bd7fc Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 24 Jul 2022 13:12:07 -0500 Subject: docs --- src/slskd/Search/ISearchService.cs | 30 ++++----- src/slskd/Search/SearchService.cs | 131 ++++++++++++++++++------------------- 2 files changed, 79 insertions(+), 82 deletions(-) (limited to 'src') diff --git a/src/slskd/Search/ISearchService.cs b/src/slskd/Search/ISearchService.cs index 9a45280b..4fe15fae 100644 --- a/src/slskd/Search/ISearchService.cs +++ b/src/slskd/Search/ISearchService.cs @@ -21,25 +21,13 @@ namespace slskd.Search using System.Collections.Generic; using System.Linq.Expressions; using System.Threading.Tasks; - using SearchOptions = Soulseek.SearchOptions; - using SearchQuery = Soulseek.SearchQuery; - using SearchScope = Soulseek.SearchScope; + using Soulseek; /// /// Handles the lifecycle and persistence of searches. /// public interface ISearchService { - /// - /// Performs a search for the specified and . - /// - /// A unique identifier for the search. - /// The search query. - /// The search scope. - /// Search options. - /// The completed search. - Task StartAsync(Guid id, SearchQuery query, SearchScope scope, SearchOptions options = null); - /// /// Deletes the specified ssearch. /// @@ -53,16 +41,26 @@ namespace slskd.Search /// The expression to use to match searches. /// A value indicating whether to include search responses in the result. /// The found search, or default if not found. - /// Thrown an expression is not supplied. + /// Thrown when an expression is not supplied. Task FindAsync(Expression> expression, bool includeResponses = false); /// - /// Returns a list of all completed and in-progress searches, with responses omitted. + /// Returns a list of all completed and in-progress searches, with responses omitted, matching the optional . /// /// An optional expression used to match searches. - /// The list of searches matching the specified expression. + /// The list of searches matching the specified expression, or all searches if no expression is specified. Task> ListAsync(Expression> expression = null); + /// + /// Performs a search for the specified and . + /// + /// A unique identifier for the search. + /// The search query. + /// The search scope. + /// Search options. + /// The completed search. + Task StartAsync(Guid id, SearchQuery query, SearchScope scope, SearchOptions options = null); + /// /// Cancels the search matching the specified , if it is in progress. /// diff --git a/src/slskd/Search/SearchService.cs b/src/slskd/Search/SearchService.cs index 12c75fb1..54d8bac9 100644 --- a/src/slskd/Search/SearchService.cs +++ b/src/slskd/Search/SearchService.cs @@ -69,6 +69,68 @@ namespace slskd.Search private IOptionsMonitor OptionsMonitor { get; } private IHubContext SearchHub { get; set; } + /// + /// Deletes the specified ssearch. + /// + /// The search to delete. + /// The operation context. + public Task DeleteAsync(Search search) + { + if (search == default) + { + throw new ArgumentNullException(nameof(search)); + } + + return DoDeleteAsync(search); + + async Task DoDeleteAsync(Search search) + { + using var context = ContextFactory.CreateDbContext(); + context.Searches.Remove(search); + await context.SaveChangesAsync(); + + await SearchHub.BroadcastDeleteAsync(search); + } + } + + /// + /// Finds a single search matching the specified . + /// + /// The expression to use to match searches. + /// A value indicating whether to include search responses in the result. + /// The found search, or default if not found. + /// Thrown when an expression is not supplied. + public Task FindAsync(Expression> expression, bool includeResponses = false) + { + if (expression == default) + { + throw new ArgumentException("An expression must be supplied.", nameof(expression)); + } + + using var context = ContextFactory.CreateDbContext(); + + var selector = context.Searches.Where(expression); + + if (!includeResponses) + { + selector = selector.WithoutResponses(); + } + + return selector.FirstOrDefaultAsync(); + } + + /// + /// Returns a list of all completed and in-progress searches, with responses omitted, matching the optional . + /// + /// An optional expression used to match searches. + /// The list of searches matching the specified expression, or all searches if no expression is specified. + public Task> ListAsync(Expression> expression = null) + { + expression ??= s => true; + using var context = ContextFactory.CreateDbContext(); + return context.Searches.Where(expression).WithoutResponses().ToListAsync(); + } + /// /// Performs a search for the specified and . /// @@ -117,10 +179,9 @@ namespace slskd.Search }, responseReceived: (args) => rateLimiter.Invoke(() => { - // note: this is rate limited, but has the potential to update - // the database every 250ms (or whatever the interval is set to) - // for the duration of the search. any issues with disk i/o or performance - // while searches are running should investigate this as a cause + // note: this is rate limited, but has the potential to update the database every 250ms (or whatever the + // interval is set to) for the duration of the search. any issues with disk i/o or performance while searches + // are running should investigate this as a cause search.ResponseCount = args.Search.ResponseCount; search.FileCount = args.Search.FileCount; search.LockedFileCount = args.Search.LockedFileCount; @@ -173,68 +234,6 @@ namespace slskd.Search return search; } - /// - /// Deletes the specified ssearch. - /// - /// The search to delete. - /// The operation context. - public Task DeleteAsync(Search search) - { - if (search == default) - { - throw new ArgumentNullException(nameof(search)); - } - - return DoDeleteAsync(search); - - async Task DoDeleteAsync(Search search) - { - using var context = ContextFactory.CreateDbContext(); - context.Searches.Remove(search); - await context.SaveChangesAsync(); - - await SearchHub.BroadcastDeleteAsync(search); - } - } - - /// - /// Finds a single search matching the specified . - /// - /// The expression to use to match searches. - /// A value indicating whether to include search responses in the result. - /// The found search, or default if not found. - /// Thrown an expression is not supplied. - public Task FindAsync(Expression> expression, bool includeResponses = false) - { - if (expression == default) - { - throw new ArgumentException("An expression must be supplied.", nameof(expression)); - } - - using var context = ContextFactory.CreateDbContext(); - - var selector = context.Searches.Where(expression); - - if (!includeResponses) - { - selector = selector.WithoutResponses(); - } - - return selector.FirstOrDefaultAsync(); - } - - /// - /// Returns a list of all completed and in-progress searches, with responses omitted. - /// - /// An optional expression used to match searches. - /// The list of searches matching the specified expression. - public Task> ListAsync(Expression> expression = null) - { - expression ??= s => true; - using var context = ContextFactory.CreateDbContext(); - return context.Searches.Where(expression).WithoutResponses().ToListAsync(); - } - /// /// Cancels the search matching the specified , if it is in progress. /// -- cgit v1.2.3 From 1601d121ff4374e3e95d79d7fac3bf44b03d3783 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 24 Jul 2022 13:44:50 -0500 Subject: add Transfer DTO back (temporarily) --- src/slskd/Transfers/API/DTO/DirectoryResponse.cs | 2 +- src/slskd/Transfers/API/DTO/Transfer.cs | 154 +++++++++++++++++++++++ 2 files changed, 155 insertions(+), 1 deletion(-) create mode 100644 src/slskd/Transfers/API/DTO/Transfer.cs (limited to 'src') diff --git a/src/slskd/Transfers/API/DTO/DirectoryResponse.cs b/src/slskd/Transfers/API/DTO/DirectoryResponse.cs index ba7418b6..1f8b1df9 100644 --- a/src/slskd/Transfers/API/DTO/DirectoryResponse.cs +++ b/src/slskd/Transfers/API/DTO/DirectoryResponse.cs @@ -23,6 +23,6 @@ namespace slskd.Transfers.API { public string Name { get; init; } public int FileCount { get; init; } - public IEnumerable Files { get; init; } + public IEnumerable Files { get; init; } } } diff --git a/src/slskd/Transfers/API/DTO/Transfer.cs b/src/slskd/Transfers/API/DTO/Transfer.cs new file mode 100644 index 00000000..9ceeb79b --- /dev/null +++ b/src/slskd/Transfers/API/DTO/Transfer.cs @@ -0,0 +1,154 @@ +// +// 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.API +{ + using System; + using System.Net; + using Soulseek; + + /// + /// A single file transfer. + /// + public class Transfer + { + /// + /// Gets the current average transfer speed. + /// + public double AverageSpeed { get; set; } + + /// + /// Gets the number of remaining bytes to be transferred. + /// + public long BytesRemaining { get; set; } + + /// + /// Gets the total number of bytes transferred. + /// + public long BytesTransferred { get; set; } + + /// + /// Gets the transfer direction. + /// + public TransferDirection Direction { get; set; } + + /// + /// Gets the current duration of the transfer, if it has been started. + /// + public double? ElapsedTime { get; set; } + + /// + /// Gets the UTC time at which the transfer transitioned into the state. + /// + public DateTime? EndTime { get; set; } + + /// + /// Gets the filename of the file to be transferred. + /// + public string Filename { get; set; } + + /// + /// Gets the transfer id. + /// + public string Id => Compute.Sha1Hash(Filename); + + /// + /// Gets the ip endpoint of the remote transfer connection, if one has been established. + /// + public IPEndPoint IPEndPoint { get; set; } + + /// + /// Gets the current progress in percent. + /// + public double PercentComplete { get; set; } + + /// + /// Gets the current place in queue, if it has been fetched. + /// + public int? PlaceInQueue { get; set; } + + /// + /// Gets the projected remaining duration of the transfer. + /// + public double? RemainingTime { get; set; } + + /// + /// Gets the remote unique token for the transfer. + /// + public int? RemoteToken { get; set; } + + /// + /// Gets the size of the file to be transferred, in bytes. + /// + public long Size { get; set; } + + /// + /// Gets the starting offset of the transfer, in bytes. + /// + public long StartOffset { get; set; } + + /// + /// Gets the UTC time at which the transfer transitioned into the state. + /// + public DateTime? StartTime { get; set; } + + /// + /// Gets the state of the transfer. + /// + public TransferStates State { get; set; } + + /// + /// Gets the unique token for the transfer. + /// + public int Token { get; set; } + + /// + /// Gets the username of the peer to or from which the file is to be transferred. + /// + public string Username { get; set; } + + /// + /// Gets the Exception that caused the failure of the transfer, if applicable. + /// + public string Exception { get; set; } + + public static Transfer FromSoulseekTransfer(Soulseek.Transfer transfer) + { + return new Transfer() + { + AverageSpeed = transfer.AverageSpeed, + BytesRemaining = transfer.BytesRemaining, + BytesTransferred = transfer.BytesTransferred, + Direction = transfer.Direction, + ElapsedTime = transfer.ElapsedTime?.TotalMilliseconds, + EndTime = transfer.EndTime, + Filename = transfer.Filename, + IPEndPoint = transfer.IPEndPoint, + PercentComplete = transfer.PercentComplete, + RemainingTime = transfer.RemainingTime?.TotalMilliseconds, + RemoteToken = transfer.RemoteToken, + Size = transfer.Size, + StartOffset = transfer.StartOffset, + StartTime = transfer.StartTime, + State = transfer.State, + Token = transfer.Token, + Username = transfer.Username, + Exception = transfer.Exception?.Message, + }; + } + } +} \ No newline at end of file -- 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') 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 14473b6f37af70190c854f8e45fbf568b1677ab8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 25 Jul 2022 20:07:07 -0500 Subject: remove TransferTracker from DownloadService --- src/slskd/Transfers/Downloads/DownloadService.cs | 7 ------- 1 file changed, 7 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 87bf3023..8e2c3585 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -40,12 +40,10 @@ namespace slskd.Transfers.Downloads public DownloadService( IOptionsMonitor optionsMonitor, ISoulseekClient soulseekClient, - ITransferTracker tracker, IDbContextFactory contextFactory, IFTPService ftpClient) { Client = soulseekClient; - Tracker = tracker; OptionsMonitor = optionsMonitor; ContextFactory = contextFactory; FTP = ftpClient; @@ -57,7 +55,6 @@ namespace slskd.Transfers.Downloads private IFTPService FTP { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); private IOptionsMonitor OptionsMonitor { get; } - private ITransferTracker Tracker { get; } /// /// Enqueues the requested list of . @@ -155,8 +152,6 @@ namespace slskd.Transfers.Downloads { 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); @@ -171,8 +166,6 @@ namespace slskd.Transfers.Downloads transfer = transfer.WithSoulseekTransfer(args.Transfer); // todo: broadcast _ = UpdateAndSaveChangesAsync(transfer); - - Tracker.AddOrUpdate(args.Transfer, cts); }))); transfer = transfer.WithSoulseekTransfer(completedTransfer); -- cgit v1.2.3 From a85d1a5ba9b9aa02fc53db008426712394aa9f48 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 25 Jul 2022 21:11:50 -0500 Subject: extract IUploadService, prep for DbContext --- src/slskd/Program.cs | 2 ++ src/slskd/Transfers/TransferService.cs | 21 +--------------- src/slskd/Transfers/Uploads/IUploadService.cs | 35 +++++++++++++++++++++++++++ src/slskd/Transfers/Uploads/UploadService.cs | 33 +++++++++++++------------ 4 files changed, 56 insertions(+), 35 deletions(-) create mode 100644 src/slskd/Transfers/Uploads/IUploadService.cs (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 1d845ab1..ac5bf99b 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -61,6 +61,7 @@ namespace slskd using slskd.Shares; using slskd.Transfers; using slskd.Transfers.Downloads; + using slskd.Transfers.Uploads; using slskd.Users; using slskd.Validation; using Soulseek; @@ -465,6 +466,7 @@ namespace slskd services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); diff --git a/src/slskd/Transfers/TransferService.cs b/src/slskd/Transfers/TransferService.cs index 253dc318..20b9b8e3 100644 --- a/src/slskd/Transfers/TransferService.cs +++ b/src/slskd/Transfers/TransferService.cs @@ -15,13 +15,10 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // -using Microsoft.Extensions.Options; - namespace slskd.Transfers { using slskd.Transfers.Downloads; using slskd.Transfers.Uploads; - using slskd.Users; /// /// Manages transfers. @@ -47,24 +44,11 @@ namespace slskd.Transfers /// /// Initializes a new instance of the class. /// - /// The UserService instance to use. - /// The OptionsMonitor instance to use. - /// The optional UploadService instance to use. public TransferService( - IUserService userService, - IOptionsMonitor optionsMonitor, IUploadService uploadService = null, IDownloadService downloadService = null) { - Users = userService; - OptionsMonitor = optionsMonitor; - - Uploads = uploadService ?? new UploadService() - { - Governor = new UploadGovernor(userService: Users, optionsMonitor: OptionsMonitor), - Queue = new UploadQueue(userService: Users, optionsMonitor: OptionsMonitor), - }; - + Uploads = uploadService; Downloads = downloadService; } @@ -77,8 +61,5 @@ namespace slskd.Transfers /// Gets the download service. /// public IDownloadService Downloads { get; init; } - - private IOptionsMonitor OptionsMonitor { get; init; } - private IUserService Users { get; init; } } } \ No newline at end of file diff --git a/src/slskd/Transfers/Uploads/IUploadService.cs b/src/slskd/Transfers/Uploads/IUploadService.cs new file mode 100644 index 00000000..71fc6067 --- /dev/null +++ b/src/slskd/Transfers/Uploads/IUploadService.cs @@ -0,0 +1,35 @@ +// +// 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.Uploads +{ + /// + /// Manages uploads. + /// + public interface IUploadService + { + /// + /// Gets the upload governor. + /// + IUploadGovernor Governor { get; } + + /// + /// Gets the upload queue. + /// + IUploadQueue Queue { get; } + } +} \ No newline at end of file diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index f88e80a8..10e82d7f 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -15,29 +15,32 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // + +using Microsoft.Extensions.Options; + namespace slskd.Transfers.Uploads { - /// - /// Manages uploads. - /// - public interface IUploadService - { - /// - /// Gets the upload governor. - /// - IUploadGovernor Governor { get; } - - /// - /// Gets the upload queue. - /// - IUploadQueue Queue { get; } - } + using Microsoft.EntityFrameworkCore; + using slskd.Users; /// /// Manages uploads. /// public class UploadService : IUploadService { + public UploadService( + IUserService userService, + IOptionsMonitor optionsMonitor, + IDbContextFactory contextFactory) + { + ContextFactory = contextFactory; + + Governor = new UploadGovernor(userService, optionsMonitor); + Queue = new UploadQueue(userService, optionsMonitor); + } + + private IDbContextFactory ContextFactory { get; } + /// /// Gets the upload governor. /// -- cgit v1.2.3 From c246537d63049d08509938558e393da6d6b532d7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 25 Jul 2022 22:01:09 -0500 Subject: rough upload implementation --- src/slskd/Transfers/Downloads/DownloadService.cs | 10 +- src/slskd/Transfers/Uploads/IUploadService.cs | 35 +++++++ src/slskd/Transfers/Uploads/UploadService.cs | 112 +++++++++++++++++++++++ 3 files changed, 156 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 8e2c3585..5890d741 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -327,13 +327,21 @@ namespace slskd.Transfers.Downloads try { using var context = await ContextFactory.CreateDbContextAsync(); - var transfer = await context.Transfers.FindAsync(id); + var transfer = await context.Transfers + .Where(t => t.Direction == TransferDirection.Download) + .Where(t => t.Id == id) + .FirstOrDefaultAsync(); if (transfer == default) { throw new NotFoundException($"No download matching id ${id}"); } + if (!transfer.State.HasFlag(TransferStates.Completed)) + { + throw new InvalidOperationException($"Invalid attempt to remove a download before it is complete"); + } + transfer.Removed = true; await context.SaveChangesAsync(); diff --git a/src/slskd/Transfers/Uploads/IUploadService.cs b/src/slskd/Transfers/Uploads/IUploadService.cs index 71fc6067..12a2edaf 100644 --- a/src/slskd/Transfers/Uploads/IUploadService.cs +++ b/src/slskd/Transfers/Uploads/IUploadService.cs @@ -17,6 +17,11 @@ namespace slskd.Transfers.Uploads { + using System; + using System.Collections.Generic; + using System.Linq.Expressions; + using System.Threading.Tasks; + /// /// Manages uploads. /// @@ -31,5 +36,35 @@ namespace slskd.Transfers.Uploads /// Gets the upload queue. /// IUploadQueue Queue { get; } + + /// + /// Finds a single upload matching the specified . + /// + /// The expression to use to match uploads. + /// The found transfer, or default if not found. + Task FindAsync(Expression> expression); + + /// + /// Returns a list of all uploads matching the optional . + /// + /// 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); + + /// + /// 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); + + /// + /// 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); } } \ No newline at end of file diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 10e82d7f..c21e107d 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -17,11 +17,20 @@ using Microsoft.Extensions.Options; +using Soulseek; namespace slskd.Transfers.Uploads { + using System; + using System.Collections.Concurrent; + using System.Threading; + using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using slskd.Users; + using Serilog; + using System.Linq; + using System.Linq.Expressions; + using System.Collections.Generic; /// /// Manages uploads. @@ -39,7 +48,10 @@ namespace slskd.Transfers.Uploads Queue = new UploadQueue(userService, optionsMonitor); } + private ConcurrentDictionary CancellationTokens { get; } = new ConcurrentDictionary(); private IDbContextFactory ContextFactory { get; } + private ILogger Log { get; } = Serilog.Log.ForContext(); + /// /// Gets the upload governor. @@ -50,5 +62,105 @@ namespace slskd.Transfers.Uploads /// Gets the upload queue. /// public IUploadQueue Queue { get; init; } + + /// + /// Finds a single upload matching the specified . + /// + /// The expression to use to match uploads. + /// 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(t => t.Direction == TransferDirection.Upload) + .Where(expression).FirstOrDefaultAsync(); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to find upload: {Message}", ex.Message); + throw; + } + } + + /// + /// Returns a list of all uploads matching the optional . + /// + /// 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) + { + expression ??= t => true; + + try + { + var context = await ContextFactory.CreateDbContextAsync(); + return await context.Transfers + .Where(t => t.Direction == TransferDirection.Upload) + .Where(t => !t.Removed || includeRemoved) + .Where(expression) + .ToListAsync(); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to list uploads: {Message}", ex.Message); + throw; + } + } + + /// + /// Removes the upload matching the specified . + /// + /// This is a soft delete; the record is retained for historical retrieval. + /// The unique identifier of the upload. + /// + public async Task RemoveAsync(Guid id) + { + try + { + using var context = await ContextFactory.CreateDbContextAsync(); + var transfer = await context.Transfers + .Where(t => t.Direction == TransferDirection.Upload) + .Where(t => t.Id == id) + .FirstOrDefaultAsync(); + + if (transfer == default) + { + throw new NotFoundException($"No upload matching id ${id}"); + } + + if (!transfer.State.HasFlag(TransferStates.Completed)) + { + throw new InvalidOperationException($"Invalid attempt to remove an upload before it is complete"); + } + + transfer.Removed = true; + + await context.SaveChangesAsync(); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to remove upload {Id}: {Message}", id, 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(); + return true; + } + + return false; + } } } -- cgit v1.2.3 From f2dbd88678393a100e33d2d8c18264d761484a3a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 26 Jul 2022 09:54:50 -0500 Subject: docs --- src/slskd/Transfers/Downloads/DownloadService.cs | 2 +- src/slskd/Transfers/Downloads/IDownloadService.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 5890d741..e166b0f4 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -63,7 +63,7 @@ namespace slskd.Transfers.Downloads /// 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 username of the remote user. /// The list of files to enqueue. /// The operation context. /// Thrown when the username is null or an empty string. diff --git a/src/slskd/Transfers/Downloads/IDownloadService.cs b/src/slskd/Transfers/Downloads/IDownloadService.cs index 07475d31..f290acb5 100644 --- a/src/slskd/Transfers/Downloads/IDownloadService.cs +++ b/src/slskd/Transfers/Downloads/IDownloadService.cs @@ -34,7 +34,7 @@ namespace slskd.Transfers.Downloads /// 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 username of remote user. /// The list of files to enqueue. /// The operation context. /// Thrown when the username is null or an empty string. -- cgit v1.2.3 From e4935b167eb0e19e05765bbc44055c697cae712c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 26 Jul 2022 09:55:27 -0500 Subject: stub EnqueueAsync --- src/slskd/Application.cs | 2 +- src/slskd/Transfers/Uploads/IUploadService.cs | 15 ++++ src/slskd/Transfers/Uploads/UploadService.cs | 124 +++++++++++++++++++++++--- 3 files changed, 129 insertions(+), 12 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 249376fd..9239f4f6 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -599,7 +599,7 @@ namespace slskd { // remote clients might sometimes re-request downloads to check the status. don't try to add the download again // if it is already tracked. - if (tracker.Contains(TransferDirection.Upload, username, filename)) + if (await Transfers.Uploads.ExistsAsync(t => t.Username == username && t.Filename == filename)) { return; } diff --git a/src/slskd/Transfers/Uploads/IUploadService.cs b/src/slskd/Transfers/Uploads/IUploadService.cs index 12a2edaf..cfa980e8 100644 --- a/src/slskd/Transfers/Uploads/IUploadService.cs +++ b/src/slskd/Transfers/Uploads/IUploadService.cs @@ -37,6 +37,14 @@ namespace slskd.Transfers.Uploads /// IUploadQueue Queue { get; } + /// + /// Enqueues the requested file. + /// + /// The username of the requesting user. + /// The local filename of the requested file. + /// The operation context. + Task EnqueueAsync(string username, string filename); + /// /// Finds a single upload matching the specified . /// @@ -66,5 +74,12 @@ namespace slskd.Transfers.Uploads /// The unique identifier for the upload. /// A value indicating whether the upload was successfully cancelled. bool TryCancel(Guid id); + + /// + /// Returns a value indicating whether an upload matching the specified exists. + /// + /// The expression used to match uploads. + /// A value indicating whether an upload matching the specified expression exists. + Task ExistsAsync(Expression> expression); } } \ No newline at end of file diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index c21e107d..78542d6d 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -15,7 +15,6 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // - using Microsoft.Extensions.Options; using Soulseek; @@ -23,14 +22,16 @@ 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 slskd.Users; using Serilog; - using System.Linq; - using System.Linq.Expressions; - using System.Collections.Generic; + using slskd.Shares; + using slskd.Users; /// /// Manages uploads. @@ -39,20 +40,20 @@ namespace slskd.Transfers.Uploads { public UploadService( IUserService userService, + ISoulseekClient soulseekClient, IOptionsMonitor optionsMonitor, + IShareService shareService, IDbContextFactory contextFactory) { + Users = userService; + Client = soulseekClient; + Shares = shareService; ContextFactory = contextFactory; Governor = new UploadGovernor(userService, optionsMonitor); Queue = new UploadQueue(userService, optionsMonitor); } - private ConcurrentDictionary CancellationTokens { get; } = new ConcurrentDictionary(); - private IDbContextFactory ContextFactory { get; } - private ILogger Log { get; } = Serilog.Log.ForContext(); - - /// /// Gets the upload governor. /// @@ -63,6 +64,97 @@ namespace slskd.Transfers.Uploads /// public IUploadQueue Queue { get; init; } + private ConcurrentDictionary CancellationTokens { get; } = new ConcurrentDictionary(); + private IDbContextFactory ContextFactory { get; } + private ILogger Log { get; } = Serilog.Log.ForContext(); + private IShareService Shares { get; set; } + private IUserService Users { get; set; } + private ISoulseekClient Client { get; set; } + + /// + /// Enqueues the requested file. + /// + /// The username of the requesting user. + /// The local filename of the requested file. + /// The operation context. + public async Task EnqueueAsync(string username, string filename) + { + // remote clients might sometimes re-request downloads to check the status. don't try to add the download again + // if it is already tracked. + if (await ExistsAsync(t => t.Username == username && t.Filename == filename)) + { + return; + } + + string localFilename; + FileInfo fileInfo = default; + + Console.WriteLine($"[UPLOAD REQUESTED] [{username}/{filename}]"); + + try + { + localFilename = (await Shares.ResolveFilenameAsync(filename)).ToLocalOSPath(); + + fileInfo = new FileInfo(localFilename); + + if (!fileInfo.Exists) + { + throw new NotFoundException(); + } + } + catch (NotFoundException) + { + Console.WriteLine($"[UPLOAD REJECTED] File {filename} not found."); + throw new DownloadEnqueueException($"File not shared."); + } + + // todo: create record + + // create a new cancellation token source so that we can cancel the upload from the UI. + var cts = new CancellationTokenSource(); + var topts = new TransferOptions( + stateChanged: (e) => + { + // todo: update record + // todo: broadcast + tracker.AddOrUpdate(e.Transfer, cts); + + if (e.Transfer.State.HasFlag(TransferStates.Queued)) + { + Queue.Enqueue(e.Transfer.Username, e.Transfer.Filename); + } + }, + progressUpdated: (e) => + { + // todo: update record + // todo: broadcast + tracker.AddOrUpdate(e.Transfer, cts); + }, + 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(tx.Username, tx.Filename), + slotReleased: (tx) => Queue.Complete(tx.Username, tx.Filename)); + + // accept all download requests, and begin the upload immediately. normally there would be an internal queue, and + // uploads would be handled separately. + _ = Task.Run(async () => + { + // 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. + if (!Users.IsWatched(username)) + { + await Users.WatchAsync(username); + } + + using var stream = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read); + await Client.UploadAsync(username, filename, fileInfo.FullName, options: topts, cancellationToken: cts.Token); + }).ContinueWith(t => + { + Console.WriteLine($"[UPLOAD FAILED] {t.Exception}"); + }, TaskContinuationOptions.NotOnRanToCompletion); // fire and forget + } + /// /// Finds a single upload matching the specified . /// @@ -162,5 +254,15 @@ namespace slskd.Transfers.Uploads return false; } + + /// + /// Returns a value indicating whether an upload matching the specified exists. + /// + /// The expression used to match uploads. + /// A value indicating whether an upload matching the specified expression exists. + public async Task ExistsAsync(Expression> expression) + { + return (await FindAsync(expression)) != default; + } } -} +} \ No newline at end of file -- cgit v1.2.3 From ed448c21296219a35d3bf603c5a3f09a7a2d0a75 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 29 Jul 2022 21:16:34 -0500 Subject: use offset from soulseek transfer --- src/slskd/Transfers/Extensions.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Transfers/Extensions.cs b/src/slskd/Transfers/Extensions.cs index fea1aa68..7ec1b55c 100644 --- a/src/slskd/Transfers/Extensions.cs +++ b/src/slskd/Transfers/Extensions.cs @@ -28,7 +28,7 @@ namespace slskd.Transfers Direction = transfer.Direction, Filename = transfer.Filename, Size = transfer.Size, - StartOffset = transfer.StartOffset, + StartOffset = t.StartOffset, State = t.State, RequestedAt = transfer.RequestedAt, EnqueuedAt = transfer.EnqueuedAt, -- cgit v1.2.3 From 05bd0ce2d324b9b8670db14ebc0f88378b4c4fe0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 29 Jul 2022 21:17:04 -0500 Subject: update transfer records in flight --- src/slskd/Transfers/Uploads/UploadService.cs | 87 ++++++++++++++++++++-------- 1 file changed, 64 insertions(+), 23 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 78542d6d..5de8f885 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -43,12 +43,14 @@ namespace slskd.Transfers.Uploads ISoulseekClient soulseekClient, IOptionsMonitor optionsMonitor, IShareService shareService, + ITransferTracker transferTracker, IDbContextFactory contextFactory) { Users = userService; Client = soulseekClient; Shares = shareService; ContextFactory = contextFactory; + Tracker = transferTracker; Governor = new UploadGovernor(userService, optionsMonitor); Queue = new UploadQueue(userService, optionsMonitor); @@ -70,6 +72,7 @@ namespace slskd.Transfers.Uploads private IShareService Shares { get; set; } private IUserService Users { get; set; } private ISoulseekClient Client { get; set; } + private ITransferTracker Tracker { get; set; } /// /// Enqueues the requested file. @@ -108,37 +111,71 @@ namespace slskd.Transfers.Uploads throw new DownloadEnqueueException($"File not shared."); } - // todo: create record + var id = Guid.NewGuid(); + + var transfer = new Transfer() + { + Id = id, + Username = username, + Direction = TransferDirection.Upload, + Filename = localFilename, + Size = fileInfo.Length, + StartOffset = 0, // potentially updated later during handshaking + RequestedAt = DateTime.UtcNow, + EnqueuedAt = 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(); // create a new cancellation token source so that we can cancel the upload from the UI. var cts = new CancellationTokenSource(); - var topts = new TransferOptions( - stateChanged: (e) => - { - // todo: update record - // todo: broadcast - tracker.AddOrUpdate(e.Transfer, cts); + CancellationTokens.TryAdd(id, cts); - if (e.Transfer.State.HasFlag(TransferStates.Queued)) - { - Queue.Enqueue(e.Transfer.Username, e.Transfer.Filename); - } - }, - progressUpdated: (e) => - { - // todo: update record - // todo: broadcast - tracker.AddOrUpdate(e.Transfer, cts); - }, - 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(tx.Username, tx.Filename), - slotReleased: (tx) => Queue.Complete(tx.Username, tx.Filename)); + async Task UpdateAndSaveChangesAsync(Transfer transfer) + { + using var context = await ContextFactory.CreateDbContextAsync(); + context.Update(transfer); + await context.SaveChangesAsync(); + } // accept all download requests, and begin the upload immediately. normally there would be an internal queue, and // uploads would be handled separately. _ = Task.Run(async () => { + using var rateLimiter = new RateLimiter(250); + + var topts = new TransferOptions( + stateChanged: (args) => + { + Log.Debug("Upload of {Filename} to user {Username} changed state from {Previous} to {New}", localFilename, username, args.PreviousState, args.Transfer.State); + + transfer = transfer.WithSoulseekTransfer(args.Transfer); + // todo: broadcast + _ = UpdateAndSaveChangesAsync(transfer); + + Tracker.AddOrUpdate(args.Transfer, cts); + + if (args.Transfer.State.HasFlag(TransferStates.Queued)) + { + Queue.Enqueue(args.Transfer.Username, args.Transfer.Filename); + } + }, + progressUpdated: (args) => rateLimiter.Invoke(() => + { + Tracker.AddOrUpdate(args.Transfer, cts); + + transfer = transfer.WithSoulseekTransfer(args.Transfer); + // todo: broadcast + _ = UpdateAndSaveChangesAsync(transfer); + }), + 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(tx.Username, tx.Filename), + slotReleased: (tx) => Queue.Complete(tx.Username, tx.Filename)); + // 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. @@ -148,7 +185,11 @@ namespace slskd.Transfers.Uploads } using var stream = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read); - await Client.UploadAsync(username, filename, fileInfo.FullName, options: topts, cancellationToken: cts.Token); + var completedTransfer = await Client.UploadAsync(username, filename, fileInfo.FullName, options: topts, cancellationToken: cts.Token); + + transfer = transfer.WithSoulseekTransfer(completedTransfer); + //todo: broadcast + await UpdateAndSaveChangesAsync(transfer); }).ContinueWith(t => { Console.WriteLine($"[UPLOAD FAILED] {t.Exception}"); -- cgit v1.2.3 From abfcd30b520871b2fa12b156a42d27fd5494209f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 29 Jul 2022 21:17:26 -0500 Subject: use enqueueDownload action from service --- src/slskd/Application.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 9239f4f6..b4dfccaa 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -285,7 +285,7 @@ namespace slskd userInfoResolver: UserInfoResolver, browseResponseResolver: BrowseResponseResolver, directoryContentsResolver: DirectoryContentsResponseResolver, - enqueueDownload: (username, endpoint, filename) => EnqueueDownloadAction(username, endpoint, filename, TransferTracker), + enqueueDownload: (username, endpoint, filename) => Transfers.Uploads.EnqueueAsync(username, filename), searchResponseCache: new SearchResponseCache(), searchResponseResolver: SearchResponseResolver, placeInQueueResolver: PlaceInQueueResolver); -- cgit v1.2.3 From 21a14a4d8faf3b51e44e6f342a83a145e3929f8a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 30 Jul 2022 13:15:33 -0500 Subject: dispose context --- src/slskd/Transfers/Downloads/DownloadService.cs | 6 +++--- src/slskd/Transfers/Uploads/UploadService.cs | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index e166b0f4..a938e767 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -247,7 +247,7 @@ namespace slskd.Transfers.Downloads { try { - var context = await ContextFactory.CreateDbContextAsync(); + using var context = await ContextFactory.CreateDbContextAsync(); return await context.Transfers .Where(t => t.Direction == TransferDirection.Download) .Where(expression).FirstOrDefaultAsync(); @@ -268,7 +268,7 @@ namespace slskd.Transfers.Downloads { try { - var context = await ContextFactory.CreateDbContextAsync(); + using var context = await ContextFactory.CreateDbContextAsync(); var transfer = await context.Transfers.FindAsync(id); if (transfer == default) @@ -302,7 +302,7 @@ namespace slskd.Transfers.Downloads try { - var context = await ContextFactory.CreateDbContextAsync(); + using var context = await ContextFactory.CreateDbContextAsync(); return await context.Transfers .Where(t => t.Direction == TransferDirection.Download) .Where(t => !t.Removed || includeRemoved) diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 5de8f885..451afb09 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -205,7 +205,7 @@ namespace slskd.Transfers.Uploads { try { - var context = await ContextFactory.CreateDbContextAsync(); + using var context = await ContextFactory.CreateDbContextAsync(); return await context.Transfers .Where(t => t.Direction == TransferDirection.Upload) .Where(expression).FirstOrDefaultAsync(); @@ -229,7 +229,7 @@ namespace slskd.Transfers.Uploads try { - var context = await ContextFactory.CreateDbContextAsync(); + using var context = await ContextFactory.CreateDbContextAsync(); return await context.Transfers .Where(t => t.Direction == TransferDirection.Upload) .Where(t => !t.Removed || includeRemoved) -- 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') 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') 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 33f8a85161fcfc2f4af178973556de7cbbfd10d8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 30 Jul 2022 14:08:11 -0500 Subject: update place in queue call --- src/web/package-lock.json | 1 - src/web/src/lib/transfers.js | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) (limited to 'src') diff --git a/src/web/package-lock.json b/src/web/package-lock.json index 0b277f69..f91b2f40 100644 --- a/src/web/package-lock.json +++ b/src/web/package-lock.json @@ -5,7 +5,6 @@ "requires": true, "packages": { "": { - "name": "web", "version": "0.1.0", "hasInstallScript": true, "dependencies": { diff --git a/src/web/src/lib/transfers.js b/src/web/src/lib/transfers.js index e9d021e0..d78a0ee8 100644 --- a/src/web/src/lib/transfers.js +++ b/src/web/src/lib/transfers.js @@ -31,7 +31,7 @@ export const cancel = ({ direction, username, id, remove = false }) => { // 'Completed, Rejected' export const getPlaceInQueue = ({ username, id }) => { - return api.get(`/transfers/downloads/${username}/${id}`); + return api.get(`/transfers/downloads/${username}/${id}/position`); }; export const isStateRetryable = (state) => -- cgit v1.2.3 From 4748f9a320282900568da4db73d6d816fbc05412 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 30 Jul 2022 15:43:46 -0500 Subject: use tracking for RemoveAsync --- src/slskd/Transfers/Uploads/UploadService.cs | 1 - 1 file changed, 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 4f545827..af490174 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -257,7 +257,6 @@ 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 fbdd590393206d5fa6679a7b5c6e2ca6637bc724 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 30 Jul 2022 16:10:27 -0500 Subject: remove TransferTracker --- src/slskd/Application.cs | 88 ----------- src/slskd/Program.cs | 1 - src/slskd/Transfers/ITransferTracker.cs | 66 --------- src/slskd/Transfers/TransferTracker.cs | 209 --------------------------- src/slskd/Transfers/Uploads/UploadService.cs | 13 +- 5 files changed, 3 insertions(+), 374 deletions(-) delete mode 100644 src/slskd/Transfers/ITransferTracker.cs delete mode 100644 src/slskd/Transfers/TransferTracker.cs (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index b4dfccaa..409b9aaf 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -75,7 +75,6 @@ namespace slskd IManagedState state, ISoulseekClient soulseekClient, IConnectionWatchdog connectionWatchdog, - ITransferTracker transferTracker, ITransferService transferService, IBrowseTracker browseTracker, IConversationTracker conversationTracker, @@ -100,7 +99,6 @@ namespace slskd Shares = shareService; Shares.StateMonitor.OnChange(state => ShareState_OnChange(state)); - TransferTracker = transferTracker; Transfers = transferService; BrowseTracker = browseTracker; ConversationTracker = conversationTracker; @@ -157,7 +155,6 @@ namespace slskd private IPushbulletService Pushbullet { get; } private DateTime SharesRefreshStarted { get; set; } private IManagedState State { get; } - private ITransferTracker TransferTracker { get; set; } private ITransferService Transfers { get; init; } private IHubContext ApplicationHub { get; set; } private IHubContext LogHub { get; set; } @@ -580,91 +577,6 @@ namespace slskd return dir; } - /// - /// Invoked upon a remote request to download a file. - /// - /// The username of the requesting user. - /// The IP endpoint of the requesting user. - /// The filename of the requested file. - /// (for example purposes) the ITransferTracker used to track progress. - /// A Task representing the asynchronous operation. - /// - /// Thrown when the download is rejected. The Exception message will be passed to the remote user. - /// - /// - /// Thrown on any other Exception other than a rejection. A generic message will be passed to the remote user for - /// security reasons. - /// - private async Task EnqueueDownloadAction(string username, IPEndPoint endpoint, string filename, ITransferTracker tracker) - { - // remote clients might sometimes re-request downloads to check the status. don't try to add the download again - // if it is already tracked. - if (await Transfers.Uploads.ExistsAsync(t => t.Username == username && t.Filename == filename)) - { - return; - } - - _ = endpoint; - string localFilename; - FileInfo fileInfo = default; - - Console.WriteLine($"[UPLOAD REQUESTED] [{username}/{filename}]"); - - try - { - localFilename = (await Shares.ResolveFilenameAsync(filename)).ToLocalOSPath(); - - fileInfo = new FileInfo(localFilename); - - if (!fileInfo.Exists) - { - throw new NotFoundException(); - } - } - catch (NotFoundException) - { - Console.WriteLine($"[UPLOAD REJECTED] File {filename} not found."); - throw new DownloadEnqueueException($"File not shared."); - } - - // create a new cancellation token source so that we can cancel the upload from the UI. - var cts = new CancellationTokenSource(); - var topts = new TransferOptions( - stateChanged: (e) => - { - tracker.AddOrUpdate(e.Transfer, cts); - - if (e.Transfer.State.HasFlag(TransferStates.Queued)) - { - Transfers.Uploads.Queue.Enqueue(e.Transfer.Username, e.Transfer.Filename); - } - }, - progressUpdated: (e) => tracker.AddOrUpdate(e.Transfer, cts), - governor: (tx, req, ct) => Transfers.Uploads.Governor.GetBytesAsync(tx.Username, req, ct), - reporter: (tx, att, grant, act) => Transfers.Uploads.Governor.ReturnBytes(tx.Username, att, grant, act), - slotAwaiter: (tx, ct) => Transfers.Uploads.Queue.AwaitStartAsync(tx.Username, tx.Filename), - slotReleased: (tx) => Transfers.Uploads.Queue.Complete(tx.Username, tx.Filename)); - - // accept all download requests, and begin the upload immediately. normally there would be an internal queue, and - // uploads would be handled separately. - _ = Task.Run(async () => - { - // 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. - if (!Users.IsWatched(username)) - { - await Users.WatchAsync(username); - } - - using var stream = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read); - await Client.UploadAsync(username, filename, fileInfo.FullName, options: topts, cancellationToken: cts.Token); - }).ContinueWith(t => - { - Console.WriteLine($"[UPLOAD FAILED] {t.Exception}"); - }, TaskContinuationOptions.NotOnRanToCompletion); // fire and forget - } - private async Task OptionsMonitor_OnChange(Options newOptions) { // this code is known to fire more than once per update. i'm not sure whether these might be executed concurrently. diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index ac5bf99b..64a16076 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -453,7 +453,6 @@ namespace slskd services.AddDbContext("search.db"); services.AddDbContext("transfers.db"); - services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(_ => new RoomTracker(messageLimit: 250)); diff --git a/src/slskd/Transfers/ITransferTracker.cs b/src/slskd/Transfers/ITransferTracker.cs deleted file mode 100644 index e25539f7..00000000 --- a/src/slskd/Transfers/ITransferTracker.cs +++ /dev/null @@ -1,66 +0,0 @@ -// -// 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 -{ - using System.Collections.Concurrent; - using System.Threading; - using Soulseek; - - /// - /// Tracks transfers. - /// - public interface ITransferTracker - { - /// - /// Tracked transfers. - /// - ConcurrentDictionary>> Transfers { get; } - - /// - /// Adds or updates a tracked transfer. - /// - /// - /// - void AddOrUpdate(Soulseek.Transfer transfer, CancellationTokenSource cancellationTokenSource); - - /// - /// Removes a tracked transfer. - /// - /// Omitting an id will remove ALL transfers associated with the specified username. - void TryRemove(TransferDirection direction, string username, string id = null); - - /// - /// Gets the specified transfer. - /// - /// - /// - /// - /// - /// - bool TryGet(TransferDirection direction, string username, string id, out (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource) transfer); - - /// - /// Gets a value indicating whether a transfer matching the specified information is tracked. - /// - /// - /// - /// - /// - bool Contains(TransferDirection direction, string username, string filename); - } -} \ No newline at end of file diff --git a/src/slskd/Transfers/TransferTracker.cs b/src/slskd/Transfers/TransferTracker.cs deleted file mode 100644 index d809e792..00000000 --- a/src/slskd/Transfers/TransferTracker.cs +++ /dev/null @@ -1,209 +0,0 @@ -// -// 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 -{ - using System.Collections.Concurrent; - using System.Linq; - using System.Threading; - using Soulseek; - - /// - /// Transfer extensions. - /// - public static class TransferTrackerExtensions - { - /// - /// Filters a Transfer collection by user. - /// - /// - /// - /// - public static ConcurrentDictionary FromUser( - this ConcurrentDictionary> directedTransfers, - string username) - { - directedTransfers.TryGetValue(username, out var transfers); - return transfers ?? new ConcurrentDictionary(); - } - - /// - /// Maps a Transfer collection to a serializable object. - /// - /// - /// - public static object ToMap( - this ConcurrentDictionary> directedTransfers) - { - return directedTransfers.Select(u => new - { - Username = u.Key, - Directories = u.Value.Values - .GroupBy(f => f.Transfer.Filename.DirectoryName()) - .Select(d => new { Directory = d.Key, Files = d.Select(r => r.Transfer) }), - }); - } - - /// - /// Maps a Transfer collection to a serializable object. - /// - /// - /// - public static object ToMap( - this ConcurrentDictionary userTransfers) - { - return userTransfers.Values - .GroupBy(f => f.Transfer.Filename.DirectoryName()) - .Select(d => new { Directory = d.Key, Files = d.Select(r => r.Transfer) }); - } - - /// - /// Filters a Transfer collection by direction. - /// - /// - /// - /// - public static ConcurrentDictionary> WithDirection( - this ConcurrentDictionary>> allTransfers, - TransferDirection direction) - { - allTransfers.TryGetValue(direction, out var transfers); - return transfers ?? new ConcurrentDictionary>(); - } - - /// - /// Retrieves a Transfer from a Transfer collection by id. - /// - /// - /// - /// - public static (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource) WithId( - this ConcurrentDictionary userTransfers, - string id) - { - userTransfers.TryGetValue(id, out var transfer); - return transfer; - } - } - - /// - /// Tracks transfers. - /// - public class TransferTracker : ITransferTracker - { - /// - /// Initializes a new instance of the class. - /// - public TransferTracker() - { - Transfers.TryAdd(TransferDirection.Download, new ConcurrentDictionary>()); - Transfers.TryAdd(TransferDirection.Upload, new ConcurrentDictionary>()); - } - - /// - /// Gets tracked transfers. - /// - public ConcurrentDictionary>> Transfers { get; private set; } = - new ConcurrentDictionary>>(); - - /// - /// Adds or updates a tracked transfer. - /// - /// - /// - public void AddOrUpdate(Soulseek.Transfer transfer, CancellationTokenSource cancellationTokenSource) - { - Transfers.TryGetValue(transfer.Direction, out var direction); - - direction.AddOrUpdate(transfer.Username, GetNewDictionaryForUser(transfer, cancellationTokenSource), (user, dict) => - { - var xfer = API.Transfer.FromSoulseekTransfer(transfer); - dict.AddOrUpdate(xfer.Id, (xfer, cancellationTokenSource), (id, record) => (xfer, cancellationTokenSource)); - return dict; - }); - } - - /// - /// Gets the specified transfer. - /// - /// - /// - /// - /// - /// - public bool TryGet(TransferDirection direction, string username, string id, out (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource) transfer) - { - transfer = default; - - if (Transfers.TryGetValue(direction, out var transfers) && transfers.TryGetValue(username, out var user) && user.TryGetValue(id, out transfer)) - { - return true; - } - - return false; - } - - /// - /// Removes a tracked transfer. - /// - /// Omitting an id will remove ALL transfers associated with the specified username. - public void TryRemove(TransferDirection direction, string username, string id = null) - { - Transfers.TryGetValue(direction, out var directionDict); - - if (string.IsNullOrEmpty(id)) - { - directionDict.TryRemove(username, out _); - } - else - { - directionDict.TryGetValue(username, out var userDict); - userDict.TryRemove(id, out _); - - if (userDict.IsEmpty) - { - directionDict.TryRemove(username, out _); - } - } - } - - /// - /// Gets a value indicating whether a transfer matching the specified information is tracked. - /// - /// - /// - /// - /// - public bool Contains(TransferDirection direction, string username, string filename) - { - if (Transfers.TryGetValue(direction, out var directionDict) && directionDict.TryGetValue(username, out var userDict)) - { - return userDict.Values.Any(record => record.Transfer.Filename == filename); - } - - return false; - } - - private ConcurrentDictionary GetNewDictionaryForUser(Soulseek.Transfer transfer, CancellationTokenSource cancellationTokenSource) - { - var r = new ConcurrentDictionary(); - var xfer = API.Transfer.FromSoulseekTransfer(transfer); - r.AddOrUpdate(xfer.Id, (xfer, cancellationTokenSource), (id, record) => (xfer, record.CancellationTokenSource)); - return r; - } - } -} \ No newline at end of file diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index af490174..319b4306 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -43,14 +43,12 @@ namespace slskd.Transfers.Uploads ISoulseekClient soulseekClient, IOptionsMonitor optionsMonitor, IShareService shareService, - ITransferTracker transferTracker, IDbContextFactory contextFactory) { Users = userService; Client = soulseekClient; Shares = shareService; ContextFactory = contextFactory; - Tracker = transferTracker; Governor = new UploadGovernor(userService, optionsMonitor); Queue = new UploadQueue(userService, optionsMonitor); @@ -72,7 +70,6 @@ namespace slskd.Transfers.Uploads private IShareService Shares { get; set; } private IUserService Users { get; set; } private ISoulseekClient Client { get; set; } - private ITransferTracker Tracker { get; set; } /// /// Enqueues the requested file. @@ -92,7 +89,7 @@ namespace slskd.Transfers.Uploads string localFilename; FileInfo fileInfo = default; - Console.WriteLine($"[UPLOAD REQUESTED] [{username}/{filename}]"); + Log.Information("[{Context}] {Username} requested {Filename}]", "UPLOAD REQUESTED", username, filename); try { @@ -107,7 +104,7 @@ namespace slskd.Transfers.Uploads } catch (NotFoundException) { - Console.WriteLine($"[UPLOAD REJECTED] File {filename} not found."); + Log.Information("[{Context}] {Filename} for {Username}: file not found", "UPLOAD REJECTED", username, filename); throw new DownloadEnqueueException($"File not shared."); } @@ -156,8 +153,6 @@ namespace slskd.Transfers.Uploads // todo: broadcast _ = UpdateAndSaveChangesAsync(transfer); - Tracker.AddOrUpdate(args.Transfer, cts); - if (args.Transfer.State.HasFlag(TransferStates.Queued)) { Queue.Enqueue(args.Transfer.Username, args.Transfer.Filename); @@ -165,8 +160,6 @@ namespace slskd.Transfers.Uploads }, progressUpdated: (args) => rateLimiter.Invoke(() => { - Tracker.AddOrUpdate(args.Transfer, cts); - transfer = transfer.WithSoulseekTransfer(args.Transfer); // todo: broadcast _ = UpdateAndSaveChangesAsync(transfer); @@ -192,7 +185,7 @@ namespace slskd.Transfers.Uploads await UpdateAndSaveChangesAsync(transfer); }).ContinueWith(t => { - Console.WriteLine($"[UPLOAD FAILED] {t.Exception}"); + Log.Information("[{Context}] {Filename} for {Username}: {Message}", "UPLOAD FAILED", username, filename, t.Exception?.Message); }, TaskContinuationOptions.NotOnRanToCompletion); // fire and forget } -- cgit v1.2.3 From a2054cadc19d10dd49a860a1f4eded612c50b624 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 5 Aug 2022 12:41:31 -0500 Subject: add UpdateAsync() --- src/slskd/Transfers/Downloads/DownloadService.cs | 25 +++++++----- src/slskd/Transfers/Downloads/IDownloadService.cs | 7 ++++ src/slskd/Transfers/Uploads/IUploadService.cs | 15 ++++++-- src/slskd/Transfers/Uploads/UploadService.cs | 46 ++++++++++++----------- 4 files changed, 58 insertions(+), 35 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 27d7dfb5..80104593 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -122,13 +122,6 @@ namespace slskd.Transfers.Downloads var waitUntilEnqueue = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - async Task UpdateAndSaveChangesAsync(Transfer transfer) - { - using var context = await ContextFactory.CreateDbContextAsync(); - context.Update(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. @@ -154,7 +147,7 @@ namespace slskd.Transfers.Downloads transfer = transfer.WithSoulseekTransfer(args.Transfer); // todo: broadcast - _ = UpdateAndSaveChangesAsync(transfer); + _ = UpdateAsync(transfer); if (args.Transfer.State.HasFlag(TransferStates.Queued) || args.Transfer.State == TransferStates.Initializing) { @@ -165,12 +158,12 @@ namespace slskd.Transfers.Downloads { transfer = transfer.WithSoulseekTransfer(args.Transfer); // todo: broadcast - _ = UpdateAndSaveChangesAsync(transfer); + _ = UpdateAsync(transfer); }))); transfer = transfer.WithSoulseekTransfer(completedTransfer); // todo: broadcast - await UpdateAndSaveChangesAsync(transfer); + await UpdateAsync(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 @@ -372,6 +365,18 @@ namespace slskd.Transfers.Downloads return false; } + /// + /// Updates the specified . + /// + /// The transfer to update. + /// The operation context. + public async Task UpdateAsync(Transfer transfer) + { + using var context = await ContextFactory.CreateDbContextAsync(); + context.Update(transfer); + await context.SaveChangesAsync(); + } + private static FileStream GetLocalFileStream(string remoteFilename, string saveDirectory) { var localFilename = remoteFilename.ToLocalFilename(baseDirectory: saveDirectory); diff --git a/src/slskd/Transfers/Downloads/IDownloadService.cs b/src/slskd/Transfers/Downloads/IDownloadService.cs index f290acb5..df17391d 100644 --- a/src/slskd/Transfers/Downloads/IDownloadService.cs +++ b/src/slskd/Transfers/Downloads/IDownloadService.cs @@ -78,5 +78,12 @@ namespace slskd.Transfers.Downloads /// The unique identifier for the download. /// A value indicating whether the download was successfully cancelled. bool TryCancel(Guid id); + + /// + /// Updates the specified . + /// + /// The transfer to update. + /// The operation context. + Task UpdateAsync(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 cfa980e8..0d829227 100644 --- a/src/slskd/Transfers/Uploads/IUploadService.cs +++ b/src/slskd/Transfers/Uploads/IUploadService.cs @@ -45,6 +45,13 @@ namespace slskd.Transfers.Uploads /// The operation context. Task EnqueueAsync(string username, string filename); + /// + /// Returns a value indicating whether an upload matching the specified exists. + /// + /// The expression used to match uploads. + /// A value indicating whether an upload matching the specified expression exists. + Task ExistsAsync(Expression> expression); + /// /// Finds a single upload matching the specified . /// @@ -76,10 +83,10 @@ namespace slskd.Transfers.Uploads bool TryCancel(Guid id); /// - /// Returns a value indicating whether an upload matching the specified exists. + /// Updates the specified . /// - /// The expression used to match uploads. - /// A value indicating whether an upload matching the specified expression exists. - Task ExistsAsync(Expression> expression); + /// The transfer to update. + /// The operation context. + Task UpdateAsync(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 319b4306..8b530bc0 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -65,11 +65,11 @@ namespace slskd.Transfers.Uploads public IUploadQueue Queue { get; init; } private ConcurrentDictionary CancellationTokens { get; } = new ConcurrentDictionary(); + private ISoulseekClient Client { get; set; } private IDbContextFactory ContextFactory { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); private IShareService Shares { get; set; } private IUserService Users { get; set; } - private ISoulseekClient Client { get; set; } /// /// Enqueues the requested file. @@ -79,8 +79,8 @@ namespace slskd.Transfers.Uploads /// The operation context. public async Task EnqueueAsync(string username, string filename) { - // remote clients might sometimes re-request downloads to check the status. don't try to add the download again - // if it is already tracked. + // remote clients might sometimes re-request downloads to check the status. don't try to add the download again if it + // is already tracked. if (await ExistsAsync(t => t.Username == username && t.Filename == filename)) { return; @@ -131,13 +131,6 @@ namespace slskd.Transfers.Uploads var cts = new CancellationTokenSource(); CancellationTokens.TryAdd(id, cts); - async Task UpdateAndSaveChangesAsync(Transfer transfer) - { - using var context = await ContextFactory.CreateDbContextAsync(); - context.Update(transfer); - await context.SaveChangesAsync(); - } - // accept all download requests, and begin the upload immediately. normally there would be an internal queue, and // uploads would be handled separately. _ = Task.Run(async () => @@ -151,7 +144,7 @@ namespace slskd.Transfers.Uploads transfer = transfer.WithSoulseekTransfer(args.Transfer); // todo: broadcast - _ = UpdateAndSaveChangesAsync(transfer); + _ = UpdateAsync(transfer); if (args.Transfer.State.HasFlag(TransferStates.Queued)) { @@ -162,16 +155,15 @@ namespace slskd.Transfers.Uploads { transfer = transfer.WithSoulseekTransfer(args.Transfer); // todo: broadcast - _ = UpdateAndSaveChangesAsync(transfer); + _ = UpdateAsync(transfer); }), 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(tx.Username, tx.Filename), slotReleased: (tx) => Queue.Complete(tx.Username, tx.Filename)); - // 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. + // 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. if (!Users.IsWatched(username)) { await Users.WatchAsync(username); @@ -182,13 +174,23 @@ namespace slskd.Transfers.Uploads transfer = transfer.WithSoulseekTransfer(completedTransfer); //todo: broadcast - await UpdateAndSaveChangesAsync(transfer); + await UpdateAsync(transfer); }).ContinueWith(t => { Log.Information("[{Context}] {Filename} for {Username}: {Message}", "UPLOAD FAILED", username, filename, t.Exception?.Message); }, TaskContinuationOptions.NotOnRanToCompletion); // fire and forget } + /// + /// Returns a value indicating whether an upload matching the specified exists. + /// + /// The expression used to match uploads. + /// A value indicating whether an upload matching the specified expression exists. + public async Task ExistsAsync(Expression> expression) + { + return (await FindAsync(expression)) != default; + } + /// /// Finds a single upload matching the specified . /// @@ -292,13 +294,15 @@ namespace slskd.Transfers.Uploads } /// - /// Returns a value indicating whether an upload matching the specified exists. + /// Updates the specified . /// - /// The expression used to match uploads. - /// A value indicating whether an upload matching the specified expression exists. - public async Task ExistsAsync(Expression> expression) + /// The transfer to update. + /// The operation context. + public async Task UpdateAsync(Transfer transfer) { - return (await FindAsync(expression)) != default; + using var context = await ContextFactory.CreateDbContextAsync(); + context.Update(transfer); + await context.SaveChangesAsync(); } } } \ No newline at end of file -- cgit v1.2.3 From f7a0f60af8fe86c64c077f54d232d9617056bf12 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 5 Aug 2022 12:42:44 -0500 Subject: clean up dangling transfers at start --- src/slskd/Application.cs | 34 ++++++++++++++++++++++++++++++++++ src/web/package-lock.json | 1 + 2 files changed, 35 insertions(+) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 2597ac93..221f77da 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -228,6 +228,30 @@ namespace slskd async Task IHostedService.StartAsync(CancellationToken cancellationToken) { + // if the application shut down "uncleanly", transfers may need to be cleaned up. + // any upload that was in progress should be marked as errored; remote users should re-enqueue them on their own. + var activeUploads = await Transfers.Uploads.ListAsync(t => !t.State.HasFlag(TransferStates.Completed) && !t.Removed); + await Task.WhenAll(activeUploads.Select(async upload => + { + upload.State = TransferStates.Completed | TransferStates.Errored; + upload.Exception = "Application was shut down"; + await Transfers.Uploads.UpdateAsync(upload); + })); + + // any download that was queued or in progress should be marked as errored, but we also want to re-enqueue them if possible + var activeAndEnqueuedDownloads = await Transfers.Downloads.ListAsync(t => !t.State.HasFlag(TransferStates.Completed) && !t.Removed); + await Task.WhenAll(activeAndEnqueuedDownloads.Select(async download => + { + download.State = TransferStates.Completed | TransferStates.Errored; + download.Exception = "Application was shut down"; + await Transfers.Downloads.UpdateAsync(download); + })); + + if (activeUploads.Any() || activeAndEnqueuedDownloads.Any()) + { + Log.Information($"Cleaned up dangling transfers from improper shutdown"); + } + Log.Information("Configuring client"); ProxyOptions proxyOptions = default; @@ -322,6 +346,16 @@ namespace slskd else { await Client.ConnectAsync(OptionsAtStartup.Soulseek.Username, OptionsAtStartup.Soulseek.Password).ConfigureAwait(false); + + // experimental! + //foreach (var group in activeAndEnqueuedDownloads.GroupBy(t => t.Username)) + //{ + // Log.Information("Re-enqueueing {Count} file(s) from {Username}", group.Key, group.Count()); + + // await Transfers.Downloads.EnqueueAsync( + // username: group.Key, + // files: group.Select(t => (t.Filename, t.Size))); + //} } } diff --git a/src/web/package-lock.json b/src/web/package-lock.json index bb11e3ac..b58cfc3b 100644 --- a/src/web/package-lock.json +++ b/src/web/package-lock.json @@ -5,6 +5,7 @@ "requires": true, "packages": { "": { + "name": "web", "version": "0.1.0", "hasInstallScript": true, "dependencies": { -- cgit v1.2.3 From 60c78206b2f9abfd05aa4f7390fbb0546537440d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 6 Aug 2022 08:15:02 -0500 Subject: add AddOrSupersedeAsync() --- src/slskd/Transfers/Downloads/DownloadService.cs | 26 ++++++++++++++++++++--- src/slskd/Transfers/Downloads/IDownloadService.cs | 8 +++++++ src/slskd/Transfers/Uploads/IUploadService.cs | 8 +++++++ src/slskd/Transfers/Uploads/UploadService.cs | 26 ++++++++++++++++++++--- 4 files changed, 62 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 80104593..58b44c37 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -56,6 +56,28 @@ namespace slskd.Transfers.Downloads private ILogger Log { get; } = Serilog.Log.ForContext(); private IOptionsMonitor OptionsMonitor { get; } + /// + /// Adds the specified . Supersedes any existing record for the same file and username. + /// + /// This should generally not be called; use instead. + /// + /// + public async Task AddOrSupersedeAsync(Transfer transfer) + { + var existing = await FindAsync(t => t.Username == transfer.Username && t.Filename == transfer.Filename); + + using var context = await ContextFactory.CreateDbContextAsync(); + + if (existing != default) + { + existing.Removed = true; + context.Update(existing); + } + + context.Add(transfer); + await context.SaveChangesAsync(); + } + /// /// Enqueues the requested list of . /// @@ -113,9 +135,7 @@ namespace slskd.Transfers.Downloads }; // 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(); + await AddOrSupersedeAsync(transfer); var cts = new CancellationTokenSource(); CancellationTokens.TryAdd(id, cts); diff --git a/src/slskd/Transfers/Downloads/IDownloadService.cs b/src/slskd/Transfers/Downloads/IDownloadService.cs index df17391d..1c1d8202 100644 --- a/src/slskd/Transfers/Downloads/IDownloadService.cs +++ b/src/slskd/Transfers/Downloads/IDownloadService.cs @@ -27,6 +27,14 @@ namespace slskd.Transfers.Downloads /// public interface IDownloadService { + /// + /// Adds the specified . Supersedes any existing record for the same file and username. + /// + /// This should generally not be called; use instead. + /// + /// + Task AddOrSupersedeAsync(Transfer transfer); + /// /// Enqueues the requested list of . /// diff --git a/src/slskd/Transfers/Uploads/IUploadService.cs b/src/slskd/Transfers/Uploads/IUploadService.cs index 0d829227..b902f20c 100644 --- a/src/slskd/Transfers/Uploads/IUploadService.cs +++ b/src/slskd/Transfers/Uploads/IUploadService.cs @@ -37,6 +37,14 @@ namespace slskd.Transfers.Uploads /// IUploadQueue Queue { get; } + /// + /// Adds the specified . Supersedes any existing record for the same file and username. + /// + /// This should generally not be called; use instead. + /// + /// + Task AddOrSupersedeAsync(Transfer transfer); + /// /// Enqueues the requested file. /// diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 8b530bc0..bb2da3d1 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -71,6 +71,28 @@ namespace slskd.Transfers.Uploads private IShareService Shares { get; set; } private IUserService Users { get; set; } + /// + /// Adds the specified . Supersedes any existing record for the same file and username. + /// + /// This should generally not be called; use instead. + /// + /// + public async Task AddOrSupersedeAsync(Transfer transfer) + { + var existing = await FindAsync(t => t.Username == transfer.Username && t.Filename == transfer.Filename); + + using var context = await ContextFactory.CreateDbContextAsync(); + + if (existing != default) + { + existing.Removed = true; + context.Update(existing); + } + + context.Add(transfer); + await context.SaveChangesAsync(); + } + /// /// Enqueues the requested file. /// @@ -123,9 +145,7 @@ namespace slskd.Transfers.Uploads }; // 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(); + await AddOrSupersedeAsync(transfer); // create a new cancellation token source so that we can cancel the upload from the UI. var cts = new CancellationTokenSource(); -- cgit v1.2.3 From 5a5d4d06dc772bc4c78bfae9d66098f51c2e3c33 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 6 Aug 2022 16:53:59 -0500 Subject: properly supersede records, don't update if the app is shutting down --- src/slskd/Transfers/Downloads/DownloadService.cs | 27 ++++-- src/slskd/Transfers/Uploads/UploadService.cs | 100 ++++++++++++++--------- 2 files changed, 82 insertions(+), 45 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 58b44c37..608563f0 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -64,14 +64,19 @@ namespace slskd.Transfers.Downloads /// public async Task AddOrSupersedeAsync(Transfer transfer) { - var existing = await FindAsync(t => t.Username == transfer.Username && t.Filename == transfer.Filename); + using var context = await ContextFactory.CreateDbContextAsync(); - using var context = await ContextFactory.CreateDbContextAsync(); + var existing = await 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(); if (existing != default) { + Log.Debug("Superseding transfer record for {Filename} from {Username}", transfer.Filename, transfer.Username); existing.Removed = true; - context.Update(existing); } context.Add(transfer); @@ -165,6 +170,12 @@ namespace slskd.Transfers.Downloads { Log.Debug("Download of {Filename} from user {Username} changed state from {Previous} to {New}", file.Filename, username, args.PreviousState, args.Transfer.State); + if (Application.IsShuttingDown) + { + Log.Debug("Download update of {Filename} to {Username} not persisted; app is shutting down", file.Filename, username); + return; + } + transfer = transfer.WithSoulseekTransfer(args.Transfer); // todo: broadcast _ = UpdateAsync(transfer); @@ -194,6 +205,11 @@ namespace slskd.Transfers.Downloads _ = FTP.UploadAsync(file.Filename.ToLocalFilename(OptionsMonitor.CurrentValue.Directories.Downloads)); } } + catch (Exception ex) when (ex is not TaskCanceledException) + { + Log.Error(ex, "Download of {Filename} from user {Username} failed: {Message}", file.Filename, username, ex.Message); + throw; + } finally { CancellationTokens.TryRemove(id, out _); @@ -233,7 +249,8 @@ namespace slskd.Transfers.Downloads Log.Debug("Successfully enqueued {Filename} from user {Username}", file.Filename, username); } - await context.SaveChangesAsync(); + // todo: broadcast + await UpdateAsync(transfer); } if (thrownExceptions.Any()) @@ -241,7 +258,7 @@ namespace slskd.Transfers.Downloads throw new AggregateException(thrownExceptions); } - Log.Information("Successfully enqueued {Count} files from user {Username}", files.Count(), username); + Log.Information("Successfully enqueued {Count} file(s) from user {Username}", files.Count(), username); } catch (Exception ex) { diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index bb2da3d1..4dc6e30d 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -79,14 +79,19 @@ namespace slskd.Transfers.Uploads /// public async Task AddOrSupersedeAsync(Transfer transfer) { - var existing = await FindAsync(t => t.Username == transfer.Username && t.Filename == transfer.Filename); - using var context = await ContextFactory.CreateDbContextAsync(); + var existing = await 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(); + if (existing != default) { + Log.Debug("Superseding transfer record for {Filename} from {Username}", transfer.Filename, transfer.Username); existing.Removed = true; - context.Update(existing); } context.Add(transfer); @@ -157,48 +162,63 @@ namespace slskd.Transfers.Uploads { using var rateLimiter = new RateLimiter(250); - var topts = new TransferOptions( - stateChanged: (args) => + try + { + var topts = new TransferOptions( + stateChanged: (args) => + { + Log.Debug("Upload of {Filename} to user {Username} changed state from {Previous} to {New}", localFilename, username, args.PreviousState, args.Transfer.State); + + if (Application.IsShuttingDown) + { + Log.Debug("Upload update of {Filename} to {Username} not persisted; app is shutting down", filename, username); + return; + } + + transfer = transfer.WithSoulseekTransfer(args.Transfer); + // todo: broadcast + _ = UpdateAsync(transfer); + + if (args.Transfer.State.HasFlag(TransferStates.Queued)) + { + Queue.Enqueue(args.Transfer.Username, args.Transfer.Filename); + } + }, + progressUpdated: (args) => rateLimiter.Invoke(() => + { + transfer = transfer.WithSoulseekTransfer(args.Transfer); + // todo: broadcast + _ = UpdateAsync(transfer); + }), + 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(tx.Username, tx.Filename), + slotReleased: (tx) => Queue.Complete(tx.Username, tx.Filename)); + + // 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. + if (!Users.IsWatched(username)) { - Log.Debug("Upload of {Filename} to user {Username} changed state from {Previous} to {New}", localFilename, username, args.PreviousState, args.Transfer.State); + await Users.WatchAsync(username); + } - transfer = transfer.WithSoulseekTransfer(args.Transfer); - // todo: broadcast - _ = UpdateAsync(transfer); + using var stream = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read); + var completedTransfer = await Client.UploadAsync(username, filename, fileInfo.FullName, options: topts, cancellationToken: cts.Token); - if (args.Transfer.State.HasFlag(TransferStates.Queued)) - { - Queue.Enqueue(args.Transfer.Username, args.Transfer.Filename); - } - }, - progressUpdated: (args) => rateLimiter.Invoke(() => - { - transfer = transfer.WithSoulseekTransfer(args.Transfer); - // todo: broadcast - _ = UpdateAsync(transfer); - }), - 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(tx.Username, tx.Filename), - slotReleased: (tx) => Queue.Complete(tx.Username, tx.Filename)); - - // 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. - if (!Users.IsWatched(username)) + transfer = transfer.WithSoulseekTransfer(completedTransfer); + //todo: broadcast + await UpdateAsync(transfer); + } + catch (Exception ex) when (ex is not TaskCanceledException) { - await Users.WatchAsync(username); + Log.Error(ex, "Upload of {Filename} to user {Username} failed: {Message}", filename, username, ex.Message); + throw; } - - using var stream = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read); - var completedTransfer = await Client.UploadAsync(username, filename, fileInfo.FullName, options: topts, cancellationToken: cts.Token); - - transfer = transfer.WithSoulseekTransfer(completedTransfer); - //todo: broadcast - await UpdateAsync(transfer); - }).ContinueWith(t => - { - Log.Information("[{Context}] {Filename} for {Username}: {Message}", "UPLOAD FAILED", username, filename, t.Exception?.Message); - }, TaskContinuationOptions.NotOnRanToCompletion); // fire and forget + finally + { + CancellationTokens.TryRemove(id, out _); + } + }); } /// -- cgit v1.2.3 From c7578b0513c7c23db8ff1246d3f948b0b127c93e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 6 Aug 2022 16:54:38 -0500 Subject: stub logic to log EF SQL --- src/slskd/Program.cs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 42e9ffab..5ed6bf80 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -15,6 +15,8 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // +using Microsoft.Extensions.Logging; + namespace slskd { using System; @@ -790,13 +792,19 @@ namespace slskd private static IServiceCollection AddDbContext(this IServiceCollection services, string filename) where T : DbContext { - Log.Debug($"Initializing database context {typeof(T).Name}"); + Log.Debug("Initializing database context {Name}", typeof(T).Name); try { services.AddDbContextFactory(options => { options.UseSqlite($"Data Source={Path.Combine(AppDirectory, "data", filename)}"); + + // tweak this to enable Entity Framework SQL logging + if (OptionsAtStartup.Debug && false) + { + options.UseLoggerFactory(LoggerFactory.Create(builder => builder.AddConsole())); + } }); using var ctx = services -- cgit v1.2.3 From 7ba93b9a27a82b79ff1852b7c0bcd00f79bb02d3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 6 Aug 2022 16:55:51 -0500 Subject: listen for signals and ctrl+c --- src/slskd/Application.cs | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 221f77da..1c7bef18 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -86,6 +86,21 @@ namespace slskd IHubContext applicationHub, IHubContext logHub) { + Console.CancelKeyPress += (_, args) => + { + ShuttingDown = true; + Log.Warning("Received SIGINT"); + }; + + foreach (var signal in new[] { PosixSignal.SIGINT, PosixSignal.SIGQUIT, PosixSignal.SIGTERM }) + { + PosixSignalRegistration.Create(signal, context => + { + ShuttingDown = true; + Log.Fatal("Received {Signal}", signal); + }); + } + OptionsAtStartup = optionsAtStartup; OptionsMonitor = optionsMonitor; -- cgit v1.2.3 From c7adfdb29c4a0269193f3dca91bf0349226e7f69 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 6 Aug 2022 16:56:15 -0500 Subject: add IsShuttingDown --- src/slskd/Application.cs | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 1c7bef18..00b43fc8 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -155,6 +155,13 @@ namespace slskd ConnectionWatchdog = connectionWatchdog; } + /// + /// Gets a value indicating whether the application is in the process of shutting down. + /// + public static bool IsShuttingDown => Environment.HasShutdownStarted || ShuttingDown; + + private static bool ShuttingDown { get; set; } = false; + private ISoulseekClient Client { get; set; } private IRoomService RoomService { get; set; } private IBrowseTracker BrowseTracker { get; set; } -- cgit v1.2.3 From a85191b139933ffef827077a88cb1882e5d6dc83 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 6 Aug 2022 16:56:45 -0500 Subject: track and resume in-progress downloads --- src/slskd/Application.cs | 106 ++++++++++++++++++++++++++++++++++------------- 1 file changed, 78 insertions(+), 28 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 00b43fc8..debae8bb 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -1,4 +1,4 @@ -// +// // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -21,6 +21,7 @@ namespace slskd { using System; using System.Collections.Concurrent; + using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; @@ -28,6 +29,7 @@ namespace slskd using System.Net.Sockets; using System.Reflection; using System.Runtime; + using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.SignalR; @@ -69,6 +71,8 @@ namespace slskd /// public static readonly string LeecherGroup = "leechers"; + private static readonly string ApplicationShutdownTransferExceptionMessage = "Application shut down"; + public Application( OptionsAtStartup optionsAtStartup, IOptionsMonitor optionsMonitor, @@ -183,6 +187,7 @@ namespace slskd private IUserService Users { get; set; } private IShareService Shares { get; set; } private IMemoryCache Cache { get; set; } = new MemoryCache(new MemoryCacheOptions()); + private IEnumerable ActiveDownloadIdsAtPreviousShutdown { get; set; } = Enumerable.Empty(); public void CollectGarbage() { @@ -250,28 +255,43 @@ namespace slskd async Task IHostedService.StartAsync(CancellationToken cancellationToken) { - // if the application shut down "uncleanly", transfers may need to be cleaned up. - // any upload that was in progress should be marked as errored; remote users should re-enqueue them on their own. - var activeUploads = await Transfers.Uploads.ListAsync(t => !t.State.HasFlag(TransferStates.Completed) && !t.Removed); + // if the application shut down "uncleanly", transfers may need to be cleaned up. we deliberately don't allow these + // 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)) + .Where(t => !t.State.HasFlag(TransferStates.Completed)) // https://github.com/dotnet/efcore/issues/10434 + .ToList(); + await Task.WhenAll(activeUploads.Select(async upload => { + Log.Debug("Cleaning up dangling upload {Filename} to {Username}", upload.Filename, upload.Username); upload.State = TransferStates.Completed | TransferStates.Errored; - upload.Exception = "Application was shut down"; + upload.Exception = ApplicationShutdownTransferExceptionMessage; await Transfers.Uploads.UpdateAsync(upload); })); - // any download that was queued or in progress should be marked as errored, but we also want to re-enqueue them if possible - var activeAndEnqueuedDownloads = await Transfers.Downloads.ListAsync(t => !t.State.HasFlag(TransferStates.Completed) && !t.Removed); - await Task.WhenAll(activeAndEnqueuedDownloads.Select(async download => + var activeDownloads = (await Transfers.Downloads.ListAsync(t => !t.State.HasFlag(TransferStates.Completed) && !t.Removed)) + .Where(t => !t.State.HasFlag(TransferStates.Completed)) // https://github.com/dotnet/efcore/issues/10434 + .ToList(); + + await Task.WhenAll(activeDownloads.Select(async download => { + Log.Debug("Cleaning up dangling download {Filename} from {Username}", download.Filename, download.Username); download.State = TransferStates.Completed | TransferStates.Errored; - download.Exception = "Application was shut down"; + download.Exception = ApplicationShutdownTransferExceptionMessage; await Transfers.Downloads.UpdateAsync(download); })); - if (activeUploads.Any() || activeAndEnqueuedDownloads.Any()) + // save the ids of any downloads that were active, so we can re-enqueue them after we've connected and logged in. + // we need to check the database before we re-request to make sure the user didn't remove them from the UI while + // the application was running, but before it was logged in. so just save the ids. + ActiveDownloadIdsAtPreviousShutdown = activeDownloads.Select(d => d.Id); + Log.Debug("Downloads to resume upon connection: {Ids}", ActiveDownloadIdsAtPreviousShutdown.ToJson()); + + if (activeUploads.Any() || activeDownloads.Any()) { - Log.Information($"Cleaned up dangling transfers from improper shutdown"); + Log.Information($"Cleaned up dangling transfers from a previous shutdown"); } Log.Information("Configuring client"); @@ -368,21 +388,13 @@ namespace slskd else { await Client.ConnectAsync(OptionsAtStartup.Soulseek.Username, OptionsAtStartup.Soulseek.Password).ConfigureAwait(false); - - // experimental! - //foreach (var group in activeAndEnqueuedDownloads.GroupBy(t => t.Username)) - //{ - // Log.Information("Re-enqueueing {Count} file(s) from {Username}", group.Key, group.Count()); - - // await Transfers.Downloads.EnqueueAsync( - // username: group.Key, - // files: group.Select(t => (t.Filename, t.Size))); - //} } } Task IHostedService.StopAsync(CancellationToken cancellationToken) { + ShuttingDown = true; + Log.Warning("Application is shutting down"); Client.Disconnect("Shutting down", new ApplicationShutdownException("Shutting down")); Client.Dispose(); Log.Information("Client stopped"); @@ -416,7 +428,7 @@ namespace slskd BrowseTracker.AddOrUpdate(args.Username, args); } - private void Client_Connected(object sender, EventArgs e) + private async void Client_Connected(object sender, EventArgs e) { ConnectionWatchdog.Stop(); Log.Information("Connected to the Soulseek server"); @@ -499,16 +511,54 @@ namespace slskd } } - private void Client_LoggedIn(object sender, EventArgs e) + private async void Client_LoggedIn(object sender, EventArgs e) { Log.Information("Logged in to the Soulseek server as {Username}", Client.Username); - // send whatever counts we have currently. we'll probably connect before the cache is primed, so these will be zero - // initially, but we'll update them when the cache is filled. - _ = Client.SetSharedCountsAsync(State.CurrentValue.Shares.Directories, State.CurrentValue.Shares.Files); + try + { + // send whatever counts we have currently. we'll probably connect before the cache is primed, so these will be zero + // initially, but we'll update them when the cache is filled. + await Client.SetSharedCountsAsync(State.CurrentValue.Shares.Directories, State.CurrentValue.Shares.Files); + + // fetch our average upload speed from the server, so we can provide it along with search results + await RefreshUserStatistics(force: true); + + // 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)); + + if (resumeableDownloads.Any()) + { + Log.Information("Attempting to re-enqueue previously active downloads..."); + + var groups = resumeableDownloads.GroupBy(d => d.Username); - // fetch our average upload speed from the server, so we can provide it along with search results - _ = RefreshUserStatistics(force: true); + // re-request downloads. we use a try/catch here because there's a very good chance that the other user is offline. + foreach (var group in groups) + { + var username = group.Key; + var files = group.Select(f => (f.Filename, f.Size)); + + try + { + await Transfers.Downloads.EnqueueAsync(username, files); + } + catch (Exception ex) + { + Log.Warning("Failed to re-enqueue {Count} file(s) from {Username}: {Message}", files.Count(), username, ex.Message); + } + } + } + + // clear the ids we saved at startup; we don't want to re-request these again if the connection is cycled + ActiveDownloadIdsAtPreviousShutdown = Enumerable.Empty(); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to execute post-login actions"); + } } private void Client_PrivateMessageRecieved(object sender, PrivateMessageReceivedEventArgs args) -- cgit v1.2.3 From 50f1ae50e3d9e345e3b8f61cfff6207e43eba81d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 6 Aug 2022 17:04:26 -0500 Subject: fix broken removal --- src/slskd/Transfers/Downloads/DownloadService.cs | 1 - 1 file changed, 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 608563f0..b499baa4 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -360,7 +360,6 @@ 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(); -- cgit v1.2.3 From 9a51c7fcc0f7a0394b7c3e5cdc01322652743470 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 7 Aug 2022 15:50:11 -0500 Subject: tweak logging --- src/slskd/Application.cs | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index debae8bb..3e501cdc 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -289,12 +289,7 @@ namespace slskd ActiveDownloadIdsAtPreviousShutdown = activeDownloads.Select(d => d.Id); Log.Debug("Downloads to resume upon connection: {Ids}", ActiveDownloadIdsAtPreviousShutdown.ToJson()); - if (activeUploads.Any() || activeDownloads.Any()) - { - Log.Information($"Cleaned up dangling transfers from a previous shutdown"); - } - - Log.Information("Configuring client"); + Log.Debug("Configuring client"); ProxyOptions proxyOptions = default; @@ -355,8 +350,8 @@ namespace slskd await Client.ReconfigureOptionsAsync(patch); - Log.Information("Client configured"); - Log.Information("Listening on port {Port}", OptionsAtStartup.Soulseek.ListenPort); + Log.Debug("Client configured"); + Log.Information("Listening for incoming connections on port {Port}", OptionsAtStartup.Soulseek.ListenPort); if (OptionsAtStartup.Soulseek.Connection.Proxy.Enabled) { -- cgit v1.2.3