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 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'src/slskd/Application.cs') 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. -- 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/slskd/Application.cs') 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 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/slskd/Application.cs') 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 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/slskd/Application.cs') 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 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/slskd/Application.cs') 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 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/slskd/Application.cs') 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/slskd/Application.cs') 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/slskd/Application.cs') 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 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/slskd/Application.cs') 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