aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorJP Dillingham <jpdillingham@gmail.com>2022-07-30 16:10:27 -0500
committerJP Dillingham <jpdillingham@gmail.com>2022-07-30 16:10:27 -0500
commitfbdd590393206d5fa6679a7b5c6e2ca6637bc724 (patch)
treefbee2c9b7f8390763f113499080d8fb340c1adde
parent4748f9a320282900568da4db73d6d816fbc05412 (diff)
downloadslskd-fbdd590393206d5fa6679a7b5c6e2ca6637bc724.tar.gz
remove TransferTracker
-rw-r--r--src/slskd/Application.cs88
-rw-r--r--src/slskd/Program.cs1
-rw-r--r--src/slskd/Transfers/ITransferTracker.cs66
-rw-r--r--src/slskd/Transfers/TransferTracker.cs209
-rw-r--r--src/slskd/Transfers/Uploads/UploadService.cs13
5 files changed, 3 insertions, 374 deletions
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> 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> State { get; }
- private ITransferTracker TransferTracker { get; set; }
private ITransferService Transfers { get; init; }
private IHubContext<ApplicationHub> ApplicationHub { get; set; }
private IHubContext<LogsHub> LogHub { get; set; }
@@ -580,91 +577,6 @@ namespace slskd
return dir;
}
- /// <summary>
- /// Invoked upon a remote request to download a file.
- /// </summary>
- /// <param name="username">The username of the requesting user.</param>
- /// <param name="endpoint">The IP endpoint of the requesting user.</param>
- /// <param name="filename">The filename of the requested file.</param>
- /// <param name="tracker">(for example purposes) the ITransferTracker used to track progress.</param>
- /// <returns>A Task representing the asynchronous operation.</returns>
- /// <exception cref="DownloadEnqueueException">
- /// Thrown when the download is rejected. The Exception message will be passed to the remote user.
- /// </exception>
- /// <exception cref="Exception">
- /// Thrown on any other Exception other than a rejection. A generic message will be passed to the remote user for
- /// security reasons.
- /// </exception>
- 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<SearchDbContext>("search.db");
services.AddDbContext<TransfersDbContext>("transfers.db");
- services.AddSingleton<ITransferTracker, TransferTracker>();
services.AddSingleton<IBrowseTracker, BrowseTracker>();
services.AddSingleton<IConversationTracker, ConversationTracker>();
services.AddSingleton<IRoomTracker, RoomTracker>(_ => 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 file="ITransferTracker.cs" company="slskd Team">
-// 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/.
-// </copyright>
-
-namespace slskd.Transfers
-{
- using System.Collections.Concurrent;
- using System.Threading;
- using Soulseek;
-
- /// <summary>
- /// Tracks transfers.
- /// </summary>
- public interface ITransferTracker
- {
- /// <summary>
- /// Tracked transfers.
- /// </summary>
- ConcurrentDictionary<TransferDirection, ConcurrentDictionary<string, ConcurrentDictionary<string, (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>>> Transfers { get; }
-
- /// <summary>
- /// Adds or updates a tracked transfer.
- /// </summary>
- /// <param name="transfer"></param>
- /// <param name="cancellationTokenSource"></param>
- void AddOrUpdate(Soulseek.Transfer transfer, CancellationTokenSource cancellationTokenSource);
-
- /// <summary>
- /// Removes a tracked transfer.
- /// </summary>
- /// <remarks>Omitting an id will remove ALL transfers associated with the specified username.</remarks>
- void TryRemove(TransferDirection direction, string username, string id = null);
-
- /// <summary>
- /// Gets the specified transfer.
- /// </summary>
- /// <param name="direction"></param>
- /// <param name="username"></param>
- /// <param name="id"></param>
- /// <param name="transfer"></param>
- /// <returns></returns>
- bool TryGet(TransferDirection direction, string username, string id, out (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource) transfer);
-
- /// <summary>
- /// Gets a value indicating whether a transfer matching the specified information is tracked.
- /// </summary>
- /// <param name="direction"></param>
- /// <param name="username"></param>
- /// <param name="filename"></param>
- /// <returns></returns>
- 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 file="TransferTracker.cs" company="slskd Team">
-// 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/.
-// </copyright>
-
-namespace slskd.Transfers
-{
- using System.Collections.Concurrent;
- using System.Linq;
- using System.Threading;
- using Soulseek;
-
- /// <summary>
- /// Transfer extensions.
- /// </summary>
- public static class TransferTrackerExtensions
- {
- /// <summary>
- /// Filters a Transfer collection by user.
- /// </summary>
- /// <param name="directedTransfers"></param>
- /// <param name="username"></param>
- /// <returns></returns>
- public static ConcurrentDictionary<string, (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource)> FromUser(
- this ConcurrentDictionary<string, ConcurrentDictionary<string, (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>> directedTransfers,
- string username)
- {
- directedTransfers.TryGetValue(username, out var transfers);
- return transfers ?? new ConcurrentDictionary<string, (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>();
- }
-
- /// <summary>
- /// Maps a Transfer collection to a serializable object.
- /// </summary>
- /// <param name="directedTransfers"></param>
- /// <returns></returns>
- public static object ToMap(
- this ConcurrentDictionary<string, ConcurrentDictionary<string, (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>> 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) }),
- });
- }
-
- /// <summary>
- /// Maps a Transfer collection to a serializable object.
- /// </summary>
- /// <param name="userTransfers"></param>
- /// <returns></returns>
- public static object ToMap(
- this ConcurrentDictionary<string, (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource)> userTransfers)
- {
- return userTransfers.Values
- .GroupBy(f => f.Transfer.Filename.DirectoryName())
- .Select(d => new { Directory = d.Key, Files = d.Select(r => r.Transfer) });
- }
-
- /// <summary>
- /// Filters a Transfer collection by direction.
- /// </summary>
- /// <param name="allTransfers"></param>
- /// <param name="direction"></param>
- /// <returns></returns>
- public static ConcurrentDictionary<string, ConcurrentDictionary<string, (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>> WithDirection(
- this ConcurrentDictionary<TransferDirection, ConcurrentDictionary<string, ConcurrentDictionary<string, (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>>> allTransfers,
- TransferDirection direction)
- {
- allTransfers.TryGetValue(direction, out var transfers);
- return transfers ?? new ConcurrentDictionary<string, ConcurrentDictionary<string, (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>>();
- }
-
- /// <summary>
- /// Retrieves a Transfer from a Transfer collection by id.
- /// </summary>
- /// <param name="userTransfers"></param>
- /// <param name="id"></param>
- /// <returns></returns>
- public static (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource) WithId(
- this ConcurrentDictionary<string, (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource)> userTransfers,
- string id)
- {
- userTransfers.TryGetValue(id, out var transfer);
- return transfer;
- }
- }
-
- /// <summary>
- /// Tracks transfers.
- /// </summary>
- public class TransferTracker : ITransferTracker
- {
- /// <summary>
- /// Initializes a new instance of the <see cref="TransferTracker"/> class.
- /// </summary>
- public TransferTracker()
- {
- Transfers.TryAdd(TransferDirection.Download, new ConcurrentDictionary<string, ConcurrentDictionary<string, (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>>());
- Transfers.TryAdd(TransferDirection.Upload, new ConcurrentDictionary<string, ConcurrentDictionary<string, (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>>());
- }
-
- /// <summary>
- /// Gets tracked transfers.
- /// </summary>
- public ConcurrentDictionary<TransferDirection, ConcurrentDictionary<string, ConcurrentDictionary<string, (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>>> Transfers { get; private set; } =
- new ConcurrentDictionary<TransferDirection, ConcurrentDictionary<string, ConcurrentDictionary<string, (API.Transfer, CancellationTokenSource)>>>();
-
- /// <summary>
- /// Adds or updates a tracked transfer.
- /// </summary>
- /// <param name="transfer"></param>
- /// <param name="cancellationTokenSource"></param>
- 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;
- });
- }
-
- /// <summary>
- /// Gets the specified transfer.
- /// </summary>
- /// <param name="direction"></param>
- /// <param name="username"></param>
- /// <param name="id"></param>
- /// <param name="transfer"></param>
- /// <returns></returns>
- 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;
- }
-
- /// <summary>
- /// Removes a tracked transfer.
- /// </summary>
- /// <remarks>Omitting an id will remove ALL transfers associated with the specified username.</remarks>
- 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 _);
- }
- }
- }
-
- /// <summary>
- /// Gets a value indicating whether a transfer matching the specified information is tracked.
- /// </summary>
- /// <param name="direction"></param>
- /// <param name="username"></param>
- /// <param name="filename"></param>
- /// <returns></returns>
- 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<string, (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource)> GetNewDictionaryForUser(Soulseek.Transfer transfer, CancellationTokenSource cancellationTokenSource)
- {
- var r = new ConcurrentDictionary<string, (API.Transfer Transfer, CancellationTokenSource CancellationTokenSource)>();
- 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<Options> optionsMonitor,
IShareService shareService,
- ITransferTracker transferTracker,
IDbContextFactory<TransfersDbContext> 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; }
/// <summary>
/// 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
}