From 71d8972ecda9664cfeb4788609e23d7dd9752f92 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 30 Dec 2023 18:43:03 -0600 Subject: add limits options --- src/slskd/Core/Options.cs | 66 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 94f8618d..8c4be6ef 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -891,6 +891,12 @@ namespace slskd /// [Validate] public UploadOptions Upload { get; init; } = new UploadOptions(); + + /// + /// Gets limit options. + /// + [Validate] + public LimitsOptions Limits { get; init; } = new LimitsOptions(); } /// @@ -949,6 +955,12 @@ namespace slskd /// [Validate] public UploadOptions Upload { get; init; } = new UploadOptions(); + + /// + /// Gets limit options. + /// + [Validate] + public LimitsOptions Limits { get; init; } = new LimitsOptions(); } /// @@ -980,6 +992,12 @@ namespace slskd [Validate] public UploadOptions Upload { get; init; } = new UploadOptions(); + /// + /// Gets limit options. + /// + [Validate] + public LimitsOptions Limits { get; init; } = new LimitsOptions(); + /// /// Gets the list of group member usernames. /// @@ -1015,6 +1033,54 @@ namespace slskd [Range(1, int.MaxValue)] public int SpeedLimit { get; init; } = int.MaxValue; } + + /// + /// Upload limit options. + /// + public class LimitsOptions + { + /// + /// Gets limits for queued transfers. + /// + [Validate] + public LimitsExtendedOptions Queued { get; init; } = new LimitsExtendedOptions(); + + /// + /// Gets daily limits for transfers. + /// + [Validate] + public LimitsExtendedOptions Daily { get; init; } = new LimitsExtendedOptions(); + + /// + /// Gets weekly limits for transfers. + /// + [Validate] + public LimitsExtendedOptions Weekly { get; init; } = new LimitsExtendedOptions(); + } + + /// + /// Extended limit options. + /// + public class LimitsExtendedOptions + { + /// + /// Gets the limit for number of files. + /// + [Range(1, int.MaxValue)] + public int? Files { get; init; } = null; + + /// + /// Gets the limit for number of directories. + /// + [Range(1, int.MaxValue)] + public int? Directories { get; init; } = null; + + /// + /// Gets the limit for number of megabytes. + /// + [Range(1, int.MaxValue)] + public int? Megabytes { get; init; } = null; + } } /// -- cgit v1.2.3 From 6c196882bb95b2216c81adb47fda91193f1d8ad8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 30 Dec 2023 18:47:10 -0600 Subject: add todos --- src/slskd/Application.cs | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 5c926644..59aa1d40 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -478,6 +478,12 @@ namespace slskd return Task.FromException(new DownloadEnqueueException($"File not shared.")); } + // todo: determine the user's group + // todo: get limit config for that group + // todo: if limits have been set, retrieve all of the user's transfers for the last week, including those currently in the queue + // todo: determine if any of the configured limits have been met or exceeded + // todo: if limits met or exceeded, return Task.FromException(new DownloadEnqueueException($"Limit(s) exceeded."); + return Transfers.Uploads.EnqueueAsync(username, filename); } -- cgit v1.2.3 From e01ead54fab085b8cf8d6f4bf92592a57b6b2d65 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 31 Dec 2023 16:42:37 -0600 Subject: add common GroupOptions --- src/slskd/Core/Options.cs | 39 +++++++++++---------------------------- 1 file changed, 11 insertions(+), 28 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 8c4be6ef..a3437bf4 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -882,9 +882,9 @@ namespace slskd } /// - /// Built in user group options. + /// Options that are common to all groups. /// - public class BuiltInOptions + public class GroupOptions { /// /// Gets upload options. @@ -899,6 +899,13 @@ namespace slskd public LimitsOptions Limits { get; init; } = new LimitsOptions(); } + /// + /// Built in user group options. + /// + public class BuiltInOptions : GroupOptions + { + } + /// /// Built in blacklisted group options. /// @@ -942,25 +949,13 @@ namespace slskd /// /// Built in leecher group options. /// - public class LeecherOptions + public class LeecherOptions : GroupOptions { /// /// Gets leecher threshold options. /// [Validate] public ThresholdOptions Thresholds { get; init; } = new ThresholdOptions(); - - /// - /// Gets upload options. - /// - [Validate] - public UploadOptions Upload { get; init; } = new UploadOptions(); - - /// - /// Gets limit options. - /// - [Validate] - public LimitsOptions Limits { get; init; } = new LimitsOptions(); } /// @@ -984,20 +979,8 @@ namespace slskd /// /// User defined user group options. /// - public class UserDefinedOptions + public class UserDefinedOptions : GroupOptions { - /// - /// Gets upload options. - /// - [Validate] - public UploadOptions Upload { get; init; } = new UploadOptions(); - - /// - /// Gets limit options. - /// - [Validate] - public LimitsOptions Limits { get; init; } = new LimitsOptions(); - /// /// Gets the list of group member usernames. /// -- cgit v1.2.3 From b42d1fea954ebc93ecd5a8451db469af1cc76795 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 31 Dec 2023 16:45:44 -0600 Subject: rename GetGroup to ResolveGroup, allow stats and status to be passed in --- src/slskd/Transfers/Uploads/UploadQueue.cs | 10 +- src/slskd/Users/IUserService.cs | 21 ++-- src/slskd/Users/UserService.cs | 159 +++++++++++++++++------------ 3 files changed, 115 insertions(+), 75 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index 53e135e8..0b5f51b1 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -254,11 +254,11 @@ namespace slskd.Transfers /// Thrown if the specified filename is not enqueued. public int EstimatePosition(string username, string filename) { - var groupName = Users.GetGroup(username); + var groupName = Users.ResolveGroup(username); var groupRecord = Groups.GetValueOrDefault(groupName); // the Uploads dictionary is keyed by username; gather all of the users that belong to the same group as the requested user - var uploadsForGroup = Uploads.Where(kvp => Users.GetGroup(kvp.Key) == groupName); + var uploadsForGroup = Uploads.Where(kvp => Users.ResolveGroup(kvp.Key) == groupName); // the RoundRobin queue implementation is not strictly fair to all users; only uploads that are ready are candidates // for selection. this means that if Bob downloads files twice as fast as Alice, Bob is going to advance through the @@ -337,7 +337,7 @@ namespace slskd.Transfers /// public int ForecastPosition(string username) { - var groupName = Users.GetGroup(username); + var groupName = Users.ResolveGroup(username); // if there's a slot available, the user will enter the queue at position 0 (will start immediately) if (Groups.TryGetValue(groupName, out var groupRecord) && groupRecord.SlotAvailable) @@ -346,7 +346,7 @@ namespace slskd.Transfers } // the Uploads dictionary is keyed by username; gather all of the users that belong to the same group as the requested user - var uploadsForGroup = Uploads.Where(kvp => Users.GetGroup(kvp.Key) == groupName); + var uploadsForGroup = Uploads.Where(kvp => Users.ResolveGroup(kvp.Key) == groupName); // assuming that the queue will be processed in a true round-robin fashion and that the user will be the last in the // rotation (worst case), the user's start position will be equal to the number of users downloading or waiting, + 1. @@ -462,7 +462,7 @@ namespace slskd.Transfers if (ready.Any()) { - var group = Users.GetGroup(user.Key); + var group = Users.ResolveGroup(user.Key); groups.AddOrUpdate( key: group, diff --git a/src/slskd/Users/IUserService.cs b/src/slskd/Users/IUserService.cs index 88090f9f..885b00e5 100644 --- a/src/slskd/Users/IUserService.cs +++ b/src/slskd/Users/IUserService.cs @@ -36,13 +36,6 @@ namespace slskd.Users /// IReadOnlyList WatchedUsernames { get; } - /// - /// Gets the name of the group for the specified . - /// - /// The username of the peer. - /// The group for the specified username. - string GetGroup(string username); - /// /// Retrieves peer . /// @@ -86,6 +79,20 @@ namespace slskd.Users /// A value indicating whether the username is watched. bool IsWatched(string username); + /// + /// Resolves the name of the group for the specified . + /// + /// + /// If the user is watched, and therefore the application is tracking their status and statistics, leech and privilege + /// detection works as expected. If the user is not watched, their status and statistics can be specified. If the user + /// is neither watched nor status and statistics are supplied, leech and privilege detection will not work. + /// + /// The username of the peer. + /// The optional status for the user. + /// The optional statistics for the user. + /// The group for the specified username. + string ResolveGroup(string username, Status status = null, Statistics statistics = null); + /// /// Adds the specified username to the server-side user list. /// diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index 95fed12d..ebd85d24 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -50,9 +50,9 @@ namespace slskd.Users OptionsMonitor = optionsMonitor; OptionsMonitor.OnChange(options => Configure(options)); - // updates may be sent unsolicited from the server, so update when we get them. - // binding these events will cause multiple redundant round trips when initially watching a user - // or when explicitly requesting via GetStatus/GetStatistics. this is wasteful, but there's no functional side effect. + // updates may be sent unsolicited from the server, so update when we get them. binding these events will cause + // multiple redundant round trips when initially watching a user or when explicitly requesting via + // GetStatus/GetStatistics. this is wasteful, but there's no functional side effect. Client.UserStatisticsChanged += (_, userStatistics) => UpdateStatistics(userStatistics.Username, userStatistics.ToStatistics()); Client.UserStatusChanged += (sender, userStatus) => { @@ -86,37 +86,6 @@ namespace slskd.Users private ConcurrentDictionary UserDictionary { get; set; } = new ConcurrentDictionary(); private ConcurrentDictionary WatchedUsernamesDictionary { get; set; } = new ConcurrentDictionary(); - /// - /// Gets the name of the group for the specified . - /// - /// The username of the peer. - /// The group for the specified username. - public string GetGroup(string username) - { - // note: this is an extremely hot path; keep the work done to an absolute minimum. - if (UserDictionary.TryGetValue(username ?? string.Empty, out var user)) - { - if (user.Status?.IsPrivileged ?? false) - { - return Application.PrivilegedGroup; - } - - if (user.Group != null) - { - return user.Group; - } - - var thresholds = OptionsMonitor.CurrentValue.Groups.Leechers.Thresholds; - - if (user.Statistics?.FileCount < thresholds.Files || user.Statistics?.DirectoryCount < thresholds.Directories) - { - return Application.LeecherGroup; - } - } - - return Application.DefaultGroup; - } - /// /// Retrieves peer . /// @@ -196,50 +165,86 @@ namespace slskd.Users public bool IsWatched(string username) => WatchedUsernamesDictionary.ContainsKey(username); /// - /// Adds the specified username to the server-side user list. + /// Resolves the name of the group for the specified . /// + /// + /// If the user is watched, and therefore the application is tracking their status and statistics, leech and privilege + /// detection works as expected. If the user is not watched, their status and statistics can be specified. If the user + /// is neither watched nor status and statistics are supplied, leech and privilege detection will not work. + /// /// The username of the peer. - /// The operation context. - public async Task WatchAsync(string username) + /// The optional status for the user. + /// The optional statistics for the user. + /// The group for the specified username. + public string ResolveGroup(string username, Status status = null, Statistics statistics = null) { - await Client.AddUserAsync(username); - WatchedUsernamesDictionary.TryAdd(username, true); + /* + * note: this is an extremely hot path; keep the work done to an absolute minimum. + */ - Log.Information("Added user {Username} to watch list", username); + // we shouldn't be asking, but this could happen in some scenarios. + if (OptionsMonitor.CurrentValue.Groups.Blacklisted.Members.Contains(username)) + { + return Application.BlacklistedGroup; + } + + var thresholds = OptionsMonitor.CurrentValue.Groups.Leechers.Thresholds; - // the server does not automatically send status and statistics information - // when watching a user initially. explicitly fetch both, so that the user has been - // watched and all information populated when this method returns. - await GetStatusAsync(username); - await GetStatisticsAsync(username); + // any user that's been explicitly added to a group is "watched" and will be in this dictionary, + // along with their latest status and statistics. we *need* to do this lookup to expedite the + // resolution of their group from configuration quickly. + if (UserDictionary.TryGetValue(username ?? string.Empty, out var user)) + { + if (user.Status?.IsPrivileged ?? false) + { + return Application.PrivilegedGroup; } - private void UpdateStatistics(string username, Statistics statistics) + if (user.Group != null) { - UserDictionary.AddOrUpdate( - key: username, - addValue: new User() { Statistics = statistics }, - updateValueFactory: (key, user) => user with { Username = username, Statistics = statistics }); + return user.Group; + } - StateMutator.SetValue(state => state with { Users = Users.ToArray() }); + if (user.Statistics?.FileCount < thresholds.Files || user.Statistics?.DirectoryCount < thresholds.Directories) + { + return Application.LeecherGroup; } + } - private void UpdateStatus(string username, Status status) + // the user hasn't been added to the dictionary, so we know they aren't part of a user defined group + // the caller may have specified status and statistics. check and see. + if (status?.IsPrivileged ?? false) { - UserDictionary.AddOrUpdate( - key: username, - addValue: new User() { Status = status }, - updateValueFactory: (key, user) => user with { Username = username, Status = status }); + return Application.PrivilegedGroup; + } - StateMutator.SetValue(state => state with { Users = Users.ToArray() }); + if (statistics?.FileCount < thresholds.Files || statistics?.DirectoryCount < thresholds.Directories) + { + return Application.LeecherGroup; } - private void Reset() + return Application.DefaultGroup; + } + + /// + /// Adds the specified username to the server-side user list. + /// + /// The username of the peer. + /// The operation context. + public async Task WatchAsync(string username) { - WatchedUsernamesDictionary.Clear(); - UserDictionary.Clear(); + await Client.AddUserAsync(username); + WatchedUsernamesDictionary.TryAdd(username, true); - StateMutator.SetValue(state => state with { Users = Users.ToArray() }); + Log.Information("Added user {Username} to watch list", username); + + // the server does not automatically send status and statistics information when watching a user initially. explicitly + // fetch both, so that the user has been watched and all information populated when this method returns. + var status = await GetStatusAsync(username); + UpdateStatus(username, status); + + var statistics = await GetStatisticsAsync(username); + UpdateStatistics(username, statistics); } private void Configure(Options options, bool force = false) @@ -251,8 +256,8 @@ namespace slskd.Users return; } - // get a list of tracked names that haven't been explicitly added to any group, including - // those that were previlously configured but have now been removed + // get a list of tracked names that haven't been explicitly added to any group, including those that were previlously + // configured but have now been removed var usernamesBeforeUpdate = UserDictionary.Keys.ToList(); var usernamesAfterUpdate = options.Groups.UserDefined.SelectMany(g => g.Value.Members); var usernamesRemoved = usernamesBeforeUpdate.Except(usernamesAfterUpdate); @@ -286,6 +291,34 @@ namespace slskd.Users LastOptionsHash = optionsHash; } + private void Reset() + { + WatchedUsernamesDictionary.Clear(); + UserDictionary.Clear(); + + StateMutator.SetValue(state => state with { Users = Users.ToArray() }); + } + + private void UpdateStatistics(string username, Statistics statistics) + { + UserDictionary.AddOrUpdate( + key: username, + addValue: new User() { Statistics = statistics }, + updateValueFactory: (key, user) => user with { Username = username, Statistics = statistics }); + + StateMutator.SetValue(state => state with { Users = Users.ToArray() }); + } + + private void UpdateStatus(string username, Status status) + { + UserDictionary.AddOrUpdate( + key: username, + addValue: new User() { Status = status }, + updateValueFactory: (key, user) => user with { Username = username, Status = status }); + + StateMutator.SetValue(state => state with { Users = Users.ToArray() }); + } + private void WatchAllUsers() { if (Client.State.HasFlag(SoulseekClientStates.Connected) && Client.State.HasFlag(SoulseekClientStates.LoggedIn)) -- cgit v1.2.3 From bb84c7b1e83765ce03626b12368f11b611ecb8c9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 31 Dec 2023 16:46:02 -0600 Subject: add missing GetStatisticsAsync def --- src/slskd/Users/IUserService.cs | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'src') diff --git a/src/slskd/Users/IUserService.cs b/src/slskd/Users/IUserService.cs index 885b00e5..1d19277c 100644 --- a/src/slskd/Users/IUserService.cs +++ b/src/slskd/Users/IUserService.cs @@ -57,6 +57,13 @@ namespace slskd.Users /// The retrieved status. Task GetStatusAsync(string username); + /// + /// Retrieves the current of a peer. + /// + /// The username of the peer. + /// The retrieved statistics. + Task GetStatisticsAsync(string username); + /// /// Grants the specified peer the specified number of privilege days. /// -- cgit v1.2.3 From c25d2ab037850d6bc1f84b52ad89213f6682f9f2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 31 Dec 2023 16:51:46 -0600 Subject: wip --- src/slskd/Users/UserService.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index ebd85d24..91435766 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -198,30 +198,30 @@ namespace slskd.Users if (user.Status?.IsPrivileged ?? false) { return Application.PrivilegedGroup; - } + } if (user.Group != null) - { + { return user.Group; } if (user.Statistics?.FileCount < thresholds.Files || user.Statistics?.DirectoryCount < thresholds.Directories) { return Application.LeecherGroup; - } + } } // the user hasn't been added to the dictionary, so we know they aren't part of a user defined group // the caller may have specified status and statistics. check and see. if (status?.IsPrivileged ?? false) - { + { return Application.PrivilegedGroup; } if (statistics?.FileCount < thresholds.Files || statistics?.DirectoryCount < thresholds.Directories) { return Application.LeecherGroup; - } + } return Application.DefaultGroup; } -- cgit v1.2.3 From 69b3cab94cdd446627ec86e81232d0e2cc810734 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 1 Jan 2024 14:42:40 -0600 Subject: add MemoryCacheFactory --- src/slskd/Common/MemoryCacheFactory.cs | 37 ++++++++++++++++++++++++++++++++++ src/slskd/Program.cs | 4 ++++ 2 files changed, 41 insertions(+) create mode 100644 src/slskd/Common/MemoryCacheFactory.cs (limited to 'src') diff --git a/src/slskd/Common/MemoryCacheFactory.cs b/src/slskd/Common/MemoryCacheFactory.cs new file mode 100644 index 00000000..782a64c4 --- /dev/null +++ b/src/slskd/Common/MemoryCacheFactory.cs @@ -0,0 +1,37 @@ +// +// 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 +{ + using Microsoft.Extensions.Caching.Memory; + + /// + /// Factory for . + /// + /// + /// Avoids lifetime issues with the built in instance of . + /// + public class MemoryCacheFactory + { + /// + /// Creates a new instance of with the specified . + /// + /// The optionally specified options for the new cache. + /// The created instance. + public virtual IMemoryCache Create(MemoryCacheOptions options = null) => new MemoryCache(options ?? new MemoryCacheOptions()); + } +} diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index f652385e..f697e82f 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -524,6 +524,10 @@ namespace slskd // IManagedState should be used where state is being mutated and accessed in the same context services.AddManagedState(); + // avoid injecting IMemoryCache unless the use case is super simple. use the factory to create + // use-case-specific instances and to enable things like destruction/recreation at runtime. + services.AddSingleton(new MemoryCacheFactory()); + // add IHttpClientFactory // use through 'using var http = HttpClientFactory.CreateClient()' wherever HTTP calls will be made // this is important to prevent memory leaks -- cgit v1.2.3 From 0a54bc4d58c2400bc9cad1ec227c9b951a6b6bd3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 1 Jan 2024 14:43:02 -0600 Subject: remove users from state --- src/slskd/Core/State.cs | 24 ------------------------ 1 file changed, 24 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/State.cs b/src/slskd/Core/State.cs index 9ae6df6b..3a0c8c11 100644 --- a/src/slskd/Core/State.cs +++ b/src/slskd/Core/State.cs @@ -23,7 +23,6 @@ namespace slskd using System.Net; using System.Text.Json.Serialization; using slskd.Relay; - using slskd.Users; using Soulseek; /// @@ -36,11 +35,9 @@ namespace slskd public bool PendingRestart { get; init; } public ServerState Server { get; init; } = new ServerState(); public RelayState Relay { get; init; } = new RelayState(); - public UserState User { get; init; } = new UserState(); public DistributedNetworkState DistributedNetwork { get; init; } = new DistributedNetworkState(); public ShareState Shares { get; init; } = new ShareState(); public string[] Rooms { get; init; } = Array.Empty(); - public User[] Users { get; init; } = Array.Empty(); } public record VersionState @@ -78,27 +75,6 @@ namespace slskd public RelayClientState State { get; init; } = RelayClientState.Disconnected; } - public record UserState - { - public string Username { get; init; } - public UserPrivilegeState Privileges { get; init; } = new UserPrivilegeState(); - public UserStatisticsState Statistics { get; init; } = new UserStatisticsState(); - } - - public record UserPrivilegeState - { - public bool IsPrivileged { get; init; } - public int PrivilegesRemaining { get; init; } - } - - public record UserStatisticsState - { - public int AverageSpeed { get; init; } - public int DirectoryCount { get; init; } - public int FileCount { get; init; } - public long UploadCount { get; init; } - } - public record DistributedNetworkState { public int BranchLevel { get; init; } -- cgit v1.2.3 From aa5d96cae4e38f7617a38b15f234d671d8fd4ba6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 1 Jan 2024 14:46:00 -0600 Subject: on second thought, don't remove users from state --- src/slskd/Application.cs | 5 +++++ src/slskd/Core/State.cs | 24 ++++++++++++++++++++++++ 2 files changed, 29 insertions(+) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 59aa1d40..d0e34880 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -74,6 +74,11 @@ namespace slskd /// public static readonly string LeecherGroup = "leechers"; + /// + /// The name of the blacklisted user group. + /// + public static readonly string BlacklistedGroup = "blacklisted"; + private static readonly string ApplicationShutdownTransferExceptionMessage = "Application shut down"; public Application( diff --git a/src/slskd/Core/State.cs b/src/slskd/Core/State.cs index 3a0c8c11..9ae6df6b 100644 --- a/src/slskd/Core/State.cs +++ b/src/slskd/Core/State.cs @@ -23,6 +23,7 @@ namespace slskd using System.Net; using System.Text.Json.Serialization; using slskd.Relay; + using slskd.Users; using Soulseek; /// @@ -35,9 +36,11 @@ namespace slskd public bool PendingRestart { get; init; } public ServerState Server { get; init; } = new ServerState(); public RelayState Relay { get; init; } = new RelayState(); + public UserState User { get; init; } = new UserState(); public DistributedNetworkState DistributedNetwork { get; init; } = new DistributedNetworkState(); public ShareState Shares { get; init; } = new ShareState(); public string[] Rooms { get; init; } = Array.Empty(); + public User[] Users { get; init; } = Array.Empty(); } public record VersionState @@ -75,6 +78,27 @@ namespace slskd public RelayClientState State { get; init; } = RelayClientState.Disconnected; } + public record UserState + { + public string Username { get; init; } + public UserPrivilegeState Privileges { get; init; } = new UserPrivilegeState(); + public UserStatisticsState Statistics { get; init; } = new UserStatisticsState(); + } + + public record UserPrivilegeState + { + public bool IsPrivileged { get; init; } + public int PrivilegesRemaining { get; init; } + } + + public record UserStatisticsState + { + public int AverageSpeed { get; init; } + public int DirectoryCount { get; init; } + public int FileCount { get; init; } + public long UploadCount { get; init; } + } + public record DistributedNetworkState { public int BranchLevel { get; init; } -- cgit v1.2.3 From a72a394f57a90f3c59e73701eeeaa7a89c2a53d5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 1 Jan 2024 14:50:08 -0600 Subject: add note about privilege detection when returning user info --- src/slskd/Application.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index d0e34880..29323938 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -1359,7 +1359,10 @@ namespace slskd { try { - var groupName = Users.GetGroup(username); + // note: users must first be watched or cached for leech and privilege detection to work. + // we are deliberately skipping it here; if the username is watched + // leech detection works and they get accurate info, if not, they won't + var groupName = Users.ResolveGroup(username); var group = Transfers.Uploads.Queue.GetGroupInfo(groupName); // forecast the position at which this user would enter the queue if they were to request -- cgit v1.2.3 From 8bb4c683335f95926729ec473b54d07dd631548b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 1 Jan 2024 14:52:34 -0600 Subject: add another note --- src/slskd/Application.cs | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 29323938..6e430fe5 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -1362,6 +1362,7 @@ namespace slskd // note: users must first be watched or cached for leech and privilege detection to work. // we are deliberately skipping it here; if the username is watched // leech detection works and they get accurate info, if not, they won't + // todo: add a fetch of user info to ensure group accuracy var groupName = Users.ResolveGroup(username); var group = Transfers.Uploads.Queue.GetGroupInfo(groupName); -- cgit v1.2.3 From d409b1e3e371cfe8fd1e59e9ad53b0f7e4edafca Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 1 Jan 2024 14:54:57 -0600 Subject: revert all the changes to User --- src/slskd/Users/IUserService.cs | 28 ++----- src/slskd/Users/UserService.cs | 167 ++++++++++++++++------------------------ 2 files changed, 74 insertions(+), 121 deletions(-) (limited to 'src') diff --git a/src/slskd/Users/IUserService.cs b/src/slskd/Users/IUserService.cs index 1d19277c..88090f9f 100644 --- a/src/slskd/Users/IUserService.cs +++ b/src/slskd/Users/IUserService.cs @@ -36,6 +36,13 @@ namespace slskd.Users /// IReadOnlyList WatchedUsernames { get; } + /// + /// Gets the name of the group for the specified . + /// + /// The username of the peer. + /// The group for the specified username. + string GetGroup(string username); + /// /// Retrieves peer . /// @@ -57,13 +64,6 @@ namespace slskd.Users /// The retrieved status. Task GetStatusAsync(string username); - /// - /// Retrieves the current of a peer. - /// - /// The username of the peer. - /// The retrieved statistics. - Task GetStatisticsAsync(string username); - /// /// Grants the specified peer the specified number of privilege days. /// @@ -86,20 +86,6 @@ namespace slskd.Users /// A value indicating whether the username is watched. bool IsWatched(string username); - /// - /// Resolves the name of the group for the specified . - /// - /// - /// If the user is watched, and therefore the application is tracking their status and statistics, leech and privilege - /// detection works as expected. If the user is not watched, their status and statistics can be specified. If the user - /// is neither watched nor status and statistics are supplied, leech and privilege detection will not work. - /// - /// The username of the peer. - /// The optional status for the user. - /// The optional statistics for the user. - /// The group for the specified username. - string ResolveGroup(string username, Status status = null, Statistics statistics = null); - /// /// Adds the specified username to the server-side user list. /// diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index 91435766..95fed12d 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -50,9 +50,9 @@ namespace slskd.Users OptionsMonitor = optionsMonitor; OptionsMonitor.OnChange(options => Configure(options)); - // updates may be sent unsolicited from the server, so update when we get them. binding these events will cause - // multiple redundant round trips when initially watching a user or when explicitly requesting via - // GetStatus/GetStatistics. this is wasteful, but there's no functional side effect. + // updates may be sent unsolicited from the server, so update when we get them. + // binding these events will cause multiple redundant round trips when initially watching a user + // or when explicitly requesting via GetStatus/GetStatistics. this is wasteful, but there's no functional side effect. Client.UserStatisticsChanged += (_, userStatistics) => UpdateStatistics(userStatistics.Username, userStatistics.ToStatistics()); Client.UserStatusChanged += (sender, userStatus) => { @@ -86,6 +86,37 @@ namespace slskd.Users private ConcurrentDictionary UserDictionary { get; set; } = new ConcurrentDictionary(); private ConcurrentDictionary WatchedUsernamesDictionary { get; set; } = new ConcurrentDictionary(); + /// + /// Gets the name of the group for the specified . + /// + /// The username of the peer. + /// The group for the specified username. + public string GetGroup(string username) + { + // note: this is an extremely hot path; keep the work done to an absolute minimum. + if (UserDictionary.TryGetValue(username ?? string.Empty, out var user)) + { + if (user.Status?.IsPrivileged ?? false) + { + return Application.PrivilegedGroup; + } + + if (user.Group != null) + { + return user.Group; + } + + var thresholds = OptionsMonitor.CurrentValue.Groups.Leechers.Thresholds; + + if (user.Statistics?.FileCount < thresholds.Files || user.Statistics?.DirectoryCount < thresholds.Directories) + { + return Application.LeecherGroup; + } + } + + return Application.DefaultGroup; + } + /// /// Retrieves peer . /// @@ -165,86 +196,50 @@ namespace slskd.Users public bool IsWatched(string username) => WatchedUsernamesDictionary.ContainsKey(username); /// - /// Resolves the name of the group for the specified . + /// Adds the specified username to the server-side user list. /// - /// - /// If the user is watched, and therefore the application is tracking their status and statistics, leech and privilege - /// detection works as expected. If the user is not watched, their status and statistics can be specified. If the user - /// is neither watched nor status and statistics are supplied, leech and privilege detection will not work. - /// /// The username of the peer. - /// The optional status for the user. - /// The optional statistics for the user. - /// The group for the specified username. - public string ResolveGroup(string username, Status status = null, Statistics statistics = null) + /// The operation context. + public async Task WatchAsync(string username) { - /* - * note: this is an extremely hot path; keep the work done to an absolute minimum. - */ - - // we shouldn't be asking, but this could happen in some scenarios. - if (OptionsMonitor.CurrentValue.Groups.Blacklisted.Members.Contains(username)) - { - return Application.BlacklistedGroup; - } - - var thresholds = OptionsMonitor.CurrentValue.Groups.Leechers.Thresholds; - - // any user that's been explicitly added to a group is "watched" and will be in this dictionary, - // along with their latest status and statistics. we *need* to do this lookup to expedite the - // resolution of their group from configuration quickly. - if (UserDictionary.TryGetValue(username ?? string.Empty, out var user)) - { - if (user.Status?.IsPrivileged ?? false) - { - return Application.PrivilegedGroup; - } - - if (user.Group != null) - { - return user.Group; - } + await Client.AddUserAsync(username); + WatchedUsernamesDictionary.TryAdd(username, true); - if (user.Statistics?.FileCount < thresholds.Files || user.Statistics?.DirectoryCount < thresholds.Directories) - { - return Application.LeecherGroup; - } - } + Log.Information("Added user {Username} to watch list", username); - // the user hasn't been added to the dictionary, so we know they aren't part of a user defined group - // the caller may have specified status and statistics. check and see. - if (status?.IsPrivileged ?? false) - { - return Application.PrivilegedGroup; - } + // the server does not automatically send status and statistics information + // when watching a user initially. explicitly fetch both, so that the user has been + // watched and all information populated when this method returns. + await GetStatusAsync(username); + await GetStatisticsAsync(username); + } - if (statistics?.FileCount < thresholds.Files || statistics?.DirectoryCount < thresholds.Directories) - { - return Application.LeecherGroup; - } + private void UpdateStatistics(string username, Statistics statistics) + { + UserDictionary.AddOrUpdate( + key: username, + addValue: new User() { Statistics = statistics }, + updateValueFactory: (key, user) => user with { Username = username, Statistics = statistics }); - return Application.DefaultGroup; + StateMutator.SetValue(state => state with { Users = Users.ToArray() }); } - /// - /// Adds the specified username to the server-side user list. - /// - /// The username of the peer. - /// The operation context. - public async Task WatchAsync(string username) + private void UpdateStatus(string username, Status status) { - await Client.AddUserAsync(username); - WatchedUsernamesDictionary.TryAdd(username, true); + UserDictionary.AddOrUpdate( + key: username, + addValue: new User() { Status = status }, + updateValueFactory: (key, user) => user with { Username = username, Status = status }); - Log.Information("Added user {Username} to watch list", username); + StateMutator.SetValue(state => state with { Users = Users.ToArray() }); + } - // the server does not automatically send status and statistics information when watching a user initially. explicitly - // fetch both, so that the user has been watched and all information populated when this method returns. - var status = await GetStatusAsync(username); - UpdateStatus(username, status); + private void Reset() + { + WatchedUsernamesDictionary.Clear(); + UserDictionary.Clear(); - var statistics = await GetStatisticsAsync(username); - UpdateStatistics(username, statistics); + StateMutator.SetValue(state => state with { Users = Users.ToArray() }); } private void Configure(Options options, bool force = false) @@ -256,8 +251,8 @@ namespace slskd.Users return; } - // get a list of tracked names that haven't been explicitly added to any group, including those that were previlously - // configured but have now been removed + // get a list of tracked names that haven't been explicitly added to any group, including + // those that were previlously configured but have now been removed var usernamesBeforeUpdate = UserDictionary.Keys.ToList(); var usernamesAfterUpdate = options.Groups.UserDefined.SelectMany(g => g.Value.Members); var usernamesRemoved = usernamesBeforeUpdate.Except(usernamesAfterUpdate); @@ -291,34 +286,6 @@ namespace slskd.Users LastOptionsHash = optionsHash; } - private void Reset() - { - WatchedUsernamesDictionary.Clear(); - UserDictionary.Clear(); - - StateMutator.SetValue(state => state with { Users = Users.ToArray() }); - } - - private void UpdateStatistics(string username, Statistics statistics) - { - UserDictionary.AddOrUpdate( - key: username, - addValue: new User() { Statistics = statistics }, - updateValueFactory: (key, user) => user with { Username = username, Statistics = statistics }); - - StateMutator.SetValue(state => state with { Users = Users.ToArray() }); - } - - private void UpdateStatus(string username, Status status) - { - UserDictionary.AddOrUpdate( - key: username, - addValue: new User() { Status = status }, - updateValueFactory: (key, user) => user with { Username = username, Status = status }); - - StateMutator.SetValue(state => state with { Users = Users.ToArray() }); - } - private void WatchAllUsers() { if (Client.State.HasFlag(SoulseekClientStates.Connected) && Client.State.HasFlag(SoulseekClientStates.LoggedIn)) -- cgit v1.2.3 From 1cd4b10a25052e4e82c1f86a9bc92f06f5605114 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 1 Jan 2024 18:43:18 -0600 Subject: wip --- src/slskd/Application.cs | 12 +++++-- src/slskd/Transfers/Uploads/UploadQueue.cs | 10 +++--- src/slskd/Users/IUserService.cs | 17 +++++++++ src/slskd/Users/UserService.cs | 56 ++++++++++++++++++++++++++++-- 4 files changed, 86 insertions(+), 9 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 6e430fe5..506f08ac 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -1357,13 +1357,21 @@ namespace slskd /// A Task resolving the UserInfo instance. private Task UserInfoResolver(string username, IPEndPoint endpoint) { + if (IsBlacklisted(username, endpoint.Address)) + { + return Task.FromResult(new UserInfo( + description: Options.Soulseek.Description, + uploadSlots: 0, + queueLength: int.MaxValue, + hasFreeUploadSlot: false)); + } + try { // note: users must first be watched or cached for leech and privilege detection to work. // we are deliberately skipping it here; if the username is watched // leech detection works and they get accurate info, if not, they won't - // todo: add a fetch of user info to ensure group accuracy - var groupName = Users.ResolveGroup(username); + var groupName = Users.GetGroup(username); var group = Transfers.Uploads.Queue.GetGroupInfo(groupName); // forecast the position at which this user would enter the queue if they were to request diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index 0b5f51b1..53e135e8 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -254,11 +254,11 @@ namespace slskd.Transfers /// Thrown if the specified filename is not enqueued. public int EstimatePosition(string username, string filename) { - var groupName = Users.ResolveGroup(username); + var groupName = Users.GetGroup(username); var groupRecord = Groups.GetValueOrDefault(groupName); // the Uploads dictionary is keyed by username; gather all of the users that belong to the same group as the requested user - var uploadsForGroup = Uploads.Where(kvp => Users.ResolveGroup(kvp.Key) == groupName); + var uploadsForGroup = Uploads.Where(kvp => Users.GetGroup(kvp.Key) == groupName); // the RoundRobin queue implementation is not strictly fair to all users; only uploads that are ready are candidates // for selection. this means that if Bob downloads files twice as fast as Alice, Bob is going to advance through the @@ -337,7 +337,7 @@ namespace slskd.Transfers /// public int ForecastPosition(string username) { - var groupName = Users.ResolveGroup(username); + var groupName = Users.GetGroup(username); // if there's a slot available, the user will enter the queue at position 0 (will start immediately) if (Groups.TryGetValue(groupName, out var groupRecord) && groupRecord.SlotAvailable) @@ -346,7 +346,7 @@ namespace slskd.Transfers } // the Uploads dictionary is keyed by username; gather all of the users that belong to the same group as the requested user - var uploadsForGroup = Uploads.Where(kvp => Users.ResolveGroup(kvp.Key) == groupName); + var uploadsForGroup = Uploads.Where(kvp => Users.GetGroup(kvp.Key) == groupName); // assuming that the queue will be processed in a true round-robin fashion and that the user will be the last in the // rotation (worst case), the user's start position will be equal to the number of users downloading or waiting, + 1. @@ -462,7 +462,7 @@ namespace slskd.Transfers if (ready.Any()) { - var group = Users.ResolveGroup(user.Key); + var group = Users.GetGroup(user.Key); groups.AddOrUpdate( key: group, diff --git a/src/slskd/Users/IUserService.cs b/src/slskd/Users/IUserService.cs index 88090f9f..04ef1527 100644 --- a/src/slskd/Users/IUserService.cs +++ b/src/slskd/Users/IUserService.cs @@ -39,10 +39,27 @@ namespace slskd.Users /// /// Gets the name of the group for the specified . /// + /// + /// The group name is fetched from cached data, and lookups should always be fast. + /// /// The username of the peer. /// The group for the specified username. string GetGroup(string username); + /// + /// Gets the name of the group for the specified . + /// + /// + /// An alternative to that does not rely on the + /// internal cache. This method allows privilege and leech detection for users + /// that are not watched. + /// + /// The username of the peer. + /// The peer's status. + /// The peer's statistics + /// The group for the specified username. + string GetGroup(string username, Status status, Statistics statistics); + /// /// Retrieves peer . /// diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index 95fed12d..4ab3840c 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -30,6 +30,13 @@ namespace slskd.Users /// /// Provides information and operations for network peers. /// + /// + /// The method should be called to 'watch' users prior to any call to + /// . relies *only* on information stored in + /// the internal , and this dictionary is only populated for users that have been + /// watched. Prior to calling , check to + /// reduce round trips to the server. + /// public class UserService : IUserService { /// @@ -83,9 +90,33 @@ namespace slskd.Users private ILogger Log { get; set; } = Serilog.Log.ForContext(); private IOptionsMonitor OptionsMonitor { get; } private IStateMutator StateMutator { get; } - private ConcurrentDictionary UserDictionary { get; set; } = new ConcurrentDictionary(); private ConcurrentDictionary WatchedUsernamesDictionary { get; set; } = new ConcurrentDictionary(); + /// + /// Gets or sets the internal cache of User data. + /// + /// + /// + /// This method retrieves the requested user's information from a dictionary, and + /// is therefore a 'get'. This information is needed to control who can do what, + /// who is subject to what limits, how to control the upload queue, and how to + /// govern speeds. The logic in this method is the 'hottest' in the application + /// and *must* remain very simple and _fast_. + /// + /// + /// If this method is called for a user who has not previously been cached, it + /// will return the default group, meaning leech, privilege, and user defined group + /// discrimination will not work. For this reason it is critical that user information + /// is retrieved and cached upon first interaction with that user. + /// + /// + /// Uploads can be cached indefinitely, and for that reason the user data cache must be + /// filled indefinitely; meaning there is no invalidation and that user data will accrue + /// for the lifetime of the application (instance). + /// + /// + private ConcurrentDictionary UserDictionary { get; set; } = new ConcurrentDictionary(); + /// /// Gets the name of the group for the specified . /// @@ -198,12 +229,25 @@ namespace slskd.Users /// /// Adds the specified username to the server-side user list. /// + /// + /// + /// Idempotent; if a user is already watched, subsequent calls will + /// only update their status and statistics. + /// + /// + /// Any user we want to track in any way needs to be watched so that + /// their statistics and status are updated properly via server side events. + /// This seems extreme and wasteful, but the only alternative is to periodically + /// spam the server for the information instead of letting the server spam the client + /// when things change. + /// + /// /// The username of the peer. /// The operation context. public async Task WatchAsync(string username) { await Client.AddUserAsync(username); - WatchedUsernamesDictionary.TryAdd(username, true); + UserDictionary.TryAdd(username, new User { Username = username }); Log.Information("Added user {Username} to watch list", username); @@ -212,6 +256,14 @@ namespace slskd.Users // watched and all information populated when this method returns. await GetStatusAsync(username); await GetStatisticsAsync(username); + + // delay the add until last, so that IsWatched won't return true until stats + // and status are populated. this may result in several unecessary calls to + // WatchAsync (if someone is checking IsWatched() and WatchAsync()ing if false), + // but we can be sure that if IsWatched() is true, we have valid stats and status. + // if we can't ensure this, the application will have non-deterministic behavior + // when it makes decisions about user groups, limits, governance etc. + WatchedUsernamesDictionary.TryAdd(username, true); } private void UpdateStatistics(string username, Statistics statistics) -- cgit v1.2.3 From eb14f632df9f8f487335db643fdea4b9c1547be1 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 5 Jan 2024 18:31:11 -0600 Subject: finish refactor of UserService --- src/slskd/Users/IUserService.cs | 79 ++++++-- src/slskd/Users/UserService.cs | 229 ++++++++++++++--------- tests/slskd.Tests.Unit/Users/UserServiceTests.cs | 2 - 3 files changed, 206 insertions(+), 104 deletions(-) (limited to 'src') diff --git a/src/slskd/Users/IUserService.cs b/src/slskd/Users/IUserService.cs index 04ef1527..2d30949b 100644 --- a/src/slskd/Users/IUserService.cs +++ b/src/slskd/Users/IUserService.cs @@ -24,6 +24,38 @@ namespace slskd.Users /// /// Provides information and operations for network peers. /// + /// + /// + /// This class maintains a that acts as a non-expiring cache of information + /// collected about a user. This includes their statistics (share counts, speed, etc), their status (privileged, etc) + /// and, if they are a member of a user-defined group, their group. + /// + /// + /// This class also maintains a to keep track of which usernames have been + /// "watched" server side and for which we will therefore receive events when their status changes. + /// + /// + /// If a user's information is in the , it's because we requested it at some point. If that user + /// is also "watched", we can assume that the data in the dictionary is up to date and will be kept so. + /// + /// + /// The data in the can continue to grow until -- unlikely -- it contains a record for every + /// user on or that was on the network at any point since the last client connect. This is a calculated risk, roughly + /// knowing the size of the network, the size of the data being stored, and balanced against the consequences of not having + /// a user's data when it is needed (for queue positioning, speed limits, etc) + /// + /// + /// The method acts on cached data _only_. This method should be called within hot paths, + /// such as a transfer governor or from the upload queue. We care more that it is fast than if it is stale. If no data for the + /// requested user is cached, that user is assumed to be in the default group. + /// + /// + /// The method is similar to , except that if + /// the requested user is not cached, it will fetch the user's data and cache it before returning. This method accepts an optional + /// parameter that can be used to force a "refresh" of the requested user's data, useful for times when we want the latest data, + /// and can afford to wait for it. + /// + /// public interface IUserService { /// @@ -39,27 +71,11 @@ namespace slskd.Users /// /// Gets the name of the group for the specified . /// - /// - /// The group name is fetched from cached data, and lookups should always be fast. - /// + /// The group name is fetched from cached data, and lookups should always be fast. /// The username of the peer. /// The group for the specified username. string GetGroup(string username); - /// - /// Gets the name of the group for the specified . - /// - /// - /// An alternative to that does not rely on the - /// internal cache. This method allows privilege and leech detection for users - /// that are not watched. - /// - /// The username of the peer. - /// The peer's status. - /// The peer's statistics - /// The group for the specified username. - string GetGroup(string username, Status status, Statistics statistics); - /// /// Retrieves peer . /// @@ -75,7 +91,26 @@ namespace slskd.Users Task GetIPEndPointAsync(string username); /// - /// Retrieves the current of a peer. + /// Gets the name of the group for the specified , or, if the user's information isn't + /// cached, fetches and caches the user's information from the server, then returns the group. + /// + /// The fetch of fresh data can be forced by specifying = true. + /// The username of the peer. + /// + /// A value determining whether the user's information should be fetched from the server, regardless of local cache. + /// + /// The group for the specified username. + Task GetOrFetchGroupAsync(string username, bool forceFetch = false); + + /// + /// Retrieves the current of a peer, and caches the result. + /// + /// The username of the peer. + /// The retrieved statistics. + Task GetStatisticsAsync(string username); + + /// + /// Retrieves the current of a peer, and caches the result. /// /// The username of the peer. /// The retrieved status. @@ -89,6 +124,14 @@ namespace slskd.Users /// The operation context. Task GrantPrivilegesAsync(string username, int days); + /// + /// Gets a value indicating whether the specified and/or are blacklisted. + /// + /// The username to check. + /// The IPAddress to check, if available. + /// A value indicating whether the specified user and/or IP are blacklisted. + bool IsBlacklisted(string username, IPAddress ipAddress = null); + /// /// Retrieves a value indicating whether the specified peer is privileged. /// diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index 4ab3840c..434d357c 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -24,6 +24,7 @@ namespace slskd.Users using System.Linq; using System.Net; using System.Threading.Tasks; + using NetTools; using Serilog; using Soulseek; @@ -31,11 +32,36 @@ namespace slskd.Users /// Provides information and operations for network peers. /// /// - /// The method should be called to 'watch' users prior to any call to - /// . relies *only* on information stored in - /// the internal , and this dictionary is only populated for users that have been - /// watched. Prior to calling , check to - /// reduce round trips to the server. + /// + /// This class maintains a that acts as a non-expiring cache of information + /// collected about a user. This includes their statistics (share counts, speed, etc), their status (privileged, etc) + /// and, if they are a member of a user-defined group, their group. + /// + /// + /// This class also maintains a to keep track of which usernames have been + /// "watched" server side and for which we will therefore receive events when their status changes. + /// + /// + /// If a user's information is in the , it's because we requested it at some point. If that user + /// is also "watched", we can assume that the data in the dictionary is up to date and will be kept so. + /// + /// + /// The data in the can continue to grow until -- unlikely -- it contains a record for every + /// user on or that was on the network at any point since the last client connect. This is a calculated risk, roughly + /// knowing the size of the network, the size of the data being stored, and balanced against the consequences of not having + /// a user's data when it is needed (for queue positioning, speed limits, etc) + /// + /// + /// The method acts on cached data _only_. This method should be called within hot paths, + /// such as a transfer governor or from the upload queue. We care more that it is fast than if it is stale. If no data for the + /// requested user is cached, that user is assumed to be in the default group. + /// + /// + /// The method is similar to , except that if + /// the requested user is not cached, it will fetch the user's data and cache it before returning. This method accepts an optional + /// parameter that can be used to force a "refresh" of the requested user's data, useful for times when we want the latest data, + /// and can afford to wait for it. + /// /// public class UserService : IUserService { @@ -43,23 +69,19 @@ namespace slskd.Users /// Initializes a new instance of the class. /// /// - /// /// public UserService( ISoulseekClient soulseekClient, - IStateMutator stateMutator, IOptionsMonitor optionsMonitor) { Client = soulseekClient; - StateMutator = stateMutator; - OptionsMonitor = optionsMonitor; OptionsMonitor.OnChange(options => Configure(options)); - // updates may be sent unsolicited from the server, so update when we get them. - // binding these events will cause multiple redundant round trips when initially watching a user - // or when explicitly requesting via GetStatus/GetStatistics. this is wasteful, but there's no functional side effect. + // updates may be sent unsolicited from the server, so update when we get them. binding these events will cause + // multiple redundant round trips when initially watching a user or when explicitly requesting via + // GetStatus/GetStatistics. this is wasteful, but there's no functional side effect. Client.UserStatisticsChanged += (_, userStatistics) => UpdateStatistics(userStatistics.Username, userStatistics.ToStatistics()); Client.UserStatusChanged += (sender, userStatus) => { @@ -71,6 +93,7 @@ namespace slskd.Users Client.Connected += (_, _) => Reset(); Client.LoggedIn += (_, _) => Configure(OptionsMonitor.CurrentValue, force: true); + Client.PrivilegedUserListReceived += (_, list) => Client_PrivilegedUserListReceived(list); Configure(OptionsMonitor.CurrentValue); } @@ -89,37 +112,34 @@ namespace slskd.Users private string LastOptionsHash { get; set; } private ILogger Log { get; set; } = Serilog.Log.ForContext(); private IOptionsMonitor OptionsMonitor { get; } - private IStateMutator StateMutator { get; } - private ConcurrentDictionary WatchedUsernamesDictionary { get; set; } = new ConcurrentDictionary(); /// /// Gets or sets the internal cache of User data. /// /// /// - /// This method retrieves the requested user's information from a dictionary, and - /// is therefore a 'get'. This information is needed to control who can do what, - /// who is subject to what limits, how to control the upload queue, and how to - /// govern speeds. The logic in this method is the 'hottest' in the application - /// and *must* remain very simple and _fast_. + /// This method retrieves the requested user's information from a dictionary, and is therefore a 'get'. This + /// information is needed to control who can do what, who is subject to what limits, how to control the upload + /// queue, and how to govern speeds. The logic in this method is the 'hottest' in the application and *must* + /// remain very simple and _fast_. /// /// - /// If this method is called for a user who has not previously been cached, it - /// will return the default group, meaning leech, privilege, and user defined group - /// discrimination will not work. For this reason it is critical that user information - /// is retrieved and cached upon first interaction with that user. + /// If this method is called for a user who has not previously been cached, it will return the default group, + /// meaning leech, privilege, and user defined group discrimination will not work. For this reason it is critical + /// that user information is retrieved and cached upon first interaction with that user. /// /// - /// Uploads can be cached indefinitely, and for that reason the user data cache must be - /// filled indefinitely; meaning there is no invalidation and that user data will accrue - /// for the lifetime of the application (instance). + /// Uploads can be cached indefinitely, and for that reason the user data cache must be filled indefinitely; + /// meaning there is no invalidation and that user data will accrue for the lifetime of the application (instance). /// /// private ConcurrentDictionary UserDictionary { get; set; } = new ConcurrentDictionary(); + private ConcurrentDictionary WatchedUsernamesDictionary { get; set; } = new ConcurrentDictionary(); /// /// Gets the name of the group for the specified . /// + /// The group name is fetched from cached data, and lookups should always be fast. /// The username of the peer. /// The group for the specified username. public string GetGroup(string username) @@ -127,6 +147,11 @@ namespace slskd.Users // note: this is an extremely hot path; keep the work done to an absolute minimum. if (UserDictionary.TryGetValue(username ?? string.Empty, out var user)) { + if (IsBlacklisted(user.Username)) + { + return Application.BlacklistedGroup; + } + if (user.Status?.IsPrivileged ?? false) { return Application.PrivilegedGroup; @@ -170,7 +195,32 @@ namespace slskd.Users } /// - /// Retrieves the current of a peer. + /// Gets the name of the group for the specified , or, if the user's information isn't + /// cached, fetches and caches the user's information from the server, then returns the group. + /// + /// The fetch of fresh data can be forced by specifying = true. + /// The username of the peer. + /// + /// A value determining whether the user's information should be fetched from the server, regardless of local cache. + /// + /// The group for the specified username. + public async Task GetOrFetchGroupAsync(string username, bool forceFetch = false) + { + if (!UserDictionary.ContainsKey(username) || forceFetch) + { + // ensure the record will exist + UserDictionary.TryAdd(username, new User { Username = username }); + + // try to populate the user's info + await GetStatisticsAsync(username); + await GetStatusAsync(username); + } + + return GetGroup(username); + } + + /// + /// Retrieves the current of a peer, and caches the result. /// /// The username of the peer. /// The retrieved statistics. @@ -185,7 +235,7 @@ namespace slskd.Users } /// - /// Retrieves the current of a peer. + /// Retrieves the current of a peer, and caches the result. /// /// The username of the peer. /// The retrieved status. @@ -208,6 +258,29 @@ namespace slskd.Users public Task GrantPrivilegesAsync(string username, int days) => Client.GrantUserPrivilegesAsync(username, days); + /// + /// Gets a value indicating whether the specified and/or are blacklisted. + /// + /// The username to check. + /// The IPAddress to check, if available. + /// A value indicating whether the specified user and/or IP are blacklisted. + public bool IsBlacklisted(string username, IPAddress ipAddress = null) + { + var blacklist = OptionsMonitor.CurrentValue.Groups.Blacklisted; + + if (blacklist.Members.Contains(username)) + { + return true; + } + + if (ipAddress is not null && blacklist.Cidrs.Select(c => IPAddressRange.Parse(c)).Any(range => range.Contains(ipAddress))) + { + return true; + } + + return false; + } + /// /// Retrieves a value indicating whether the specified peer is privileged. /// @@ -230,68 +303,44 @@ namespace slskd.Users /// Adds the specified username to the server-side user list. /// /// + /// Idempotent; if a user is already watched, subsequent calls will only update their status and statistics. /// - /// Idempotent; if a user is already watched, subsequent calls will - /// only update their status and statistics. - /// - /// - /// Any user we want to track in any way needs to be watched so that - /// their statistics and status are updated properly via server side events. - /// This seems extreme and wasteful, but the only alternative is to periodically - /// spam the server for the information instead of letting the server spam the client - /// when things change. + /// Any user we want to track in any way needs to be watched so that their statistics and status are updated + /// properly via server side events. This seems extreme and wasteful, but the only alternative is to periodically + /// spam the server for the information instead of letting the server spam the client when things change. /// /// /// The username of the peer. /// The operation context. public async Task WatchAsync(string username) { + // watch the user, server side await Client.AddUserAsync(username); UserDictionary.TryAdd(username, new User { Username = username }); Log.Information("Added user {Username} to watch list", username); - // the server does not automatically send status and statistics information - // when watching a user initially. explicitly fetch both, so that the user has been - // watched and all information populated when this method returns. + // the server does not automatically send status and statistics information when watching a user initially. explicitly + // fetch both, so that the user has been watched and all information populated when this method returns. await GetStatusAsync(username); await GetStatisticsAsync(username); - // delay the add until last, so that IsWatched won't return true until stats - // and status are populated. this may result in several unecessary calls to - // WatchAsync (if someone is checking IsWatched() and WatchAsync()ing if false), - // but we can be sure that if IsWatched() is true, we have valid stats and status. - // if we can't ensure this, the application will have non-deterministic behavior - // when it makes decisions about user groups, limits, governance etc. + // delay the add until last, so that IsWatched won't return true until stats and status are populated. this may result + // in several unecessary calls to WatchAsync (if someone is checking IsWatched() and WatchAsync()ing if false), but we + // can be sure that if IsWatched() is true, we have valid stats and status. if we can't ensure this, the application + // will have non-deterministic behavior when it makes decisions about user groups, limits, governance etc. WatchedUsernamesDictionary.TryAdd(username, true); } - private void UpdateStatistics(string username, Statistics statistics) - { - UserDictionary.AddOrUpdate( - key: username, - addValue: new User() { Statistics = statistics }, - updateValueFactory: (key, user) => user with { Username = username, Statistics = statistics }); - - StateMutator.SetValue(state => state with { Users = Users.ToArray() }); - } - - private void UpdateStatus(string username, Status status) + private void Client_PrivilegedUserListReceived(IEnumerable list) { - UserDictionary.AddOrUpdate( - key: username, - addValue: new User() { Status = status }, - updateValueFactory: (key, user) => user with { Username = username, Status = status }); - - StateMutator.SetValue(state => state with { Users = Users.ToArray() }); - } - - private void Reset() - { - WatchedUsernamesDictionary.Clear(); - UserDictionary.Clear(); - - StateMutator.SetValue(state => state with { Users = Users.ToArray() }); + foreach (var username in list) + { + UserDictionary.AddOrUpdate( + key: username, + addValue: new User() { Status = new Status { IsPrivileged = true } }, + updateValueFactory: (key, user) => user with { Username = username, Status = user.Status with { IsPrivileged = true } }); + } } private void Configure(Options options, bool force = false) @@ -303,8 +352,8 @@ namespace slskd.Users return; } - // get a list of tracked names that haven't been explicitly added to any group, including - // those that were previlously configured but have now been removed + // get a list of tracked names that haven't been explicitly added to any group, including those that were previlously + // configured but have now been removed var usernamesBeforeUpdate = UserDictionary.Keys.ToList(); var usernamesAfterUpdate = options.Groups.UserDefined.SelectMany(g => g.Value.Members); var usernamesRemoved = usernamesBeforeUpdate.Except(usernamesAfterUpdate); @@ -328,25 +377,37 @@ namespace slskd.Users key: username, addValue: new User() { Username = username, Group = group.Key }, updateValueFactory: (key, user) => user with { Username = username, Group = group.Key }); + + if (Client.State.HasFlag(SoulseekClientStates.Connected) && Client.State.HasFlag(SoulseekClientStates.LoggedIn)) + { + _ = WatchAsync(username); + } } } - StateMutator.SetValue(state => state with { Users = Users.ToArray() }); + LastOptionsHash = optionsHash; + } - WatchAllUsers(); + private void Reset() + { + WatchedUsernamesDictionary.Clear(); + UserDictionary.Clear(); + } - LastOptionsHash = optionsHash; + private void UpdateStatistics(string username, Statistics statistics) + { + UserDictionary.AddOrUpdate( + key: username, + addValue: new User() { Statistics = statistics }, + updateValueFactory: (key, user) => user with { Username = username, Statistics = statistics }); } - private void WatchAllUsers() + private void UpdateStatus(string username, Status status) { - if (Client.State.HasFlag(SoulseekClientStates.Connected) && Client.State.HasFlag(SoulseekClientStates.LoggedIn)) - { - foreach (var username in UserDictionary.Keys.ToList()) - { - _ = WatchAsync(username); - } - } + UserDictionary.AddOrUpdate( + key: username, + addValue: new User() { Status = status }, + updateValueFactory: (key, user) => user with { Username = username, Status = status }); } } } \ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Users/UserServiceTests.cs b/tests/slskd.Tests.Unit/Users/UserServiceTests.cs index 16b1c5fe..0bf11580 100644 --- a/tests/slskd.Tests.Unit/Users/UserServiceTests.cs +++ b/tests/slskd.Tests.Unit/Users/UserServiceTests.cs @@ -125,7 +125,6 @@ var mocks = new Mocks(options); var service = new UserService( mocks.SoulseekClient.Object, - mocks.StateMutator.Object, mocks.OptionsMonitor); return (service, mocks); @@ -139,7 +138,6 @@ } public Mock SoulseekClient { get; } = new Mock(); - public Mock> StateMutator { get; } = new Mock>(); public TestOptionsMonitor OptionsMonitor { get; init; } } } -- cgit v1.2.3 From 805e1ed565a1898c158931b322a8d0db5a83ef05 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 5 Jan 2024 18:40:43 -0600 Subject: move IsBlacklisted, fetch user info if they request our info --- src/slskd/Application.cs | 24 ++++++------------------ 1 file changed, 6 insertions(+), 18 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 506f08ac..fd2a2487 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -1162,7 +1162,7 @@ namespace slskd { Metrics.Search.RequestsReceived.Inc(1); - if (IsBlacklisted(username)) + if (Users.IsBlacklisted(username)) { Log.Information("Returned empty search response for blacklisted user {Username}", username); return new SearchResponse(username, token, hasFreeUploadSlot: false, uploadSpeed: 0, queueLength: int.MaxValue, fileList: Enumerable.Empty()); @@ -1197,6 +1197,9 @@ namespace slskd // make sure our average speed (as reported by the server) is reasonably up to date await RefreshUserStatistics(); + // note: the following uses cached user data to determine group, so if the user's data + // isn't cached they may get a forecast based on the wrong group. this is a hot path though, + // and we don't want to incur the massive penalties that would caching data for each request. var forecastedPosition = Transfers.Uploads.Queue.ForecastPosition(username); Log.Information("[{Context}]: Sending {Count} records to {Username} for query '{Query}'", "SEARCH RESULT SENT", results.Count(), username, query.SearchText); @@ -1357,7 +1360,7 @@ namespace slskd /// A Task resolving the UserInfo instance. private Task UserInfoResolver(string username, IPEndPoint endpoint) { - if (IsBlacklisted(username, endpoint.Address)) + if (Users.IsBlacklisted(username, endpoint.Address)) { return Task.FromResult(new UserInfo( description: Options.Soulseek.Description, @@ -1371,7 +1374,7 @@ namespace slskd // note: users must first be watched or cached for leech and privilege detection to work. // we are deliberately skipping it here; if the username is watched // leech detection works and they get accurate info, if not, they won't - var groupName = Users.GetGroup(username); + var groupName = Users.GetOrFetchGroup(username); var group = Transfers.Uploads.Queue.GetGroupInfo(groupName); // forecast the position at which this user would enter the queue if they were to request @@ -1397,20 +1400,5 @@ namespace slskd throw; } } - - private bool IsBlacklisted(string username, IPAddress ipAddress = null) - { - if (Options.Groups.Blacklisted.Members.Contains(username)) - { - return true; - } - - if (ipAddress is not null && Options.Groups.Blacklisted.Cidrs.Select(c => IPAddressRange.Parse(c)).Any(range => range.Contains(ipAddress))) - { - return true; - } - - return false; - } } } -- cgit v1.2.3 From 05f0864ded4c0d5b2944da460db49564f9e88322 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 6 Jan 2024 14:55:42 -0600 Subject: oops --- src/slskd/Application.cs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index fd2a2487..fe754220 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -477,7 +477,7 @@ namespace slskd private Task EnqueueDownload(string username, IPEndPoint endpoint, string filename) { - if (IsBlacklisted(username, endpoint.Address)) + if (Users.IsBlacklisted(username, endpoint.Address)) { Log.Information("Rejected enqueue request for blacklisted user {Username} ({IP})", username, endpoint.Address); return Task.FromException(new DownloadEnqueueException($"File not shared.")); @@ -502,7 +502,7 @@ namespace slskd { Metrics.Browse.RequestsReceived.Inc(1); - if (IsBlacklisted(username, endpoint.Address)) + if (Users.IsBlacklisted(username, endpoint.Address)) { Log.Information("Returned empty browse listing for blacklisted user {Username} ({IP})", username, endpoint.Address); return new BrowseResponse(); @@ -965,7 +965,7 @@ namespace slskd /// A Task resolving an instance of Soulseek.Directory containing the contents of the requested directory. private async Task DirectoryContentsResponseResolver(string username, IPEndPoint endpoint, int token, string directory) { - if (IsBlacklisted(username, endpoint.Address)) + if (Users.IsBlacklisted(username, endpoint.Address)) { Log.Information("Returned empty directory listing for blacklisted user {Username} ({IP})", username, endpoint.Address); return new Soulseek.Directory(directory); @@ -1358,15 +1358,15 @@ namespace slskd /// The username of the requesting user. /// The IP endpoint of the requesting user. /// A Task resolving the UserInfo instance. - private Task UserInfoResolver(string username, IPEndPoint endpoint) + private async Task UserInfoResolver(string username, IPEndPoint endpoint) { if (Users.IsBlacklisted(username, endpoint.Address)) { - return Task.FromResult(new UserInfo( + return new UserInfo( description: Options.Soulseek.Description, uploadSlots: 0, queueLength: int.MaxValue, - hasFreeUploadSlot: false)); + hasFreeUploadSlot: false); } try @@ -1374,7 +1374,7 @@ namespace slskd // note: users must first be watched or cached for leech and privilege detection to work. // we are deliberately skipping it here; if the username is watched // leech detection works and they get accurate info, if not, they won't - var groupName = Users.GetOrFetchGroup(username); + var groupName = await Users.GetOrFetchGroupAsync(username); var group = Transfers.Uploads.Queue.GetGroupInfo(groupName); // forecast the position at which this user would enter the queue if they were to request @@ -1392,7 +1392,7 @@ namespace slskd queueLength: forecastedPosition, hasFreeUploadSlot: forecastedPosition == 0); - return Task.FromResult(info); + return info; } catch (Exception ex) { -- cgit v1.2.3 From 0da0c1413c78ea4b63b0ec1bd356f4801d0f4991 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 6 Jan 2024 17:00:33 -0600 Subject: remove MemoryCacheFactory --- src/slskd/Common/MemoryCacheFactory.cs | 37 ---------------------------------- src/slskd/Program.cs | 4 ---- 2 files changed, 41 deletions(-) delete mode 100644 src/slskd/Common/MemoryCacheFactory.cs (limited to 'src') diff --git a/src/slskd/Common/MemoryCacheFactory.cs b/src/slskd/Common/MemoryCacheFactory.cs deleted file mode 100644 index 782a64c4..00000000 --- a/src/slskd/Common/MemoryCacheFactory.cs +++ /dev/null @@ -1,37 +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 -{ - using Microsoft.Extensions.Caching.Memory; - - /// - /// Factory for . - /// - /// - /// Avoids lifetime issues with the built in instance of . - /// - public class MemoryCacheFactory - { - /// - /// Creates a new instance of with the specified . - /// - /// The optionally specified options for the new cache. - /// The created instance. - public virtual IMemoryCache Create(MemoryCacheOptions options = null) => new MemoryCache(options ?? new MemoryCacheOptions()); - } -} diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index f697e82f..f652385e 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -524,10 +524,6 @@ namespace slskd // IManagedState should be used where state is being mutated and accessed in the same context services.AddManagedState(); - // avoid injecting IMemoryCache unless the use case is super simple. use the factory to create - // use-case-specific instances and to enable things like destruction/recreation at runtime. - services.AddSingleton(new MemoryCacheFactory()); - // add IHttpClientFactory // use through 'using var http = HttpClientFactory.CreateClient()' wherever HTTP calls will be made // this is important to prevent memory leaks -- cgit v1.2.3 From 720cdf6d6157d8fc08a2d2348b04c25bebdb30e4 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 6 Jan 2024 17:00:42 -0600 Subject: fix docs --- src/slskd/Users/IUserService.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/slskd/Users/IUserService.cs b/src/slskd/Users/IUserService.cs index 2d30949b..75afd442 100644 --- a/src/slskd/Users/IUserService.cs +++ b/src/slskd/Users/IUserService.cs @@ -26,23 +26,23 @@ namespace slskd.Users /// /// /// - /// This class maintains a that acts as a non-expiring cache of information + /// This class maintains a UserDictionary that acts as a non-expiring cache of information /// collected about a user. This includes their statistics (share counts, speed, etc), their status (privileged, etc) /// and, if they are a member of a user-defined group, their group. /// /// - /// This class also maintains a to keep track of which usernames have been + /// This class also maintains a WatchedUsernamesDictionary to keep track of which usernames have been /// "watched" server side and for which we will therefore receive events when their status changes. /// /// - /// If a user's information is in the , it's because we requested it at some point. If that user + /// If a user's information is in the UserDictionary, it's because we requested it at some point. If that user /// is also "watched", we can assume that the data in the dictionary is up to date and will be kept so. /// /// - /// The data in the can continue to grow until -- unlikely -- it contains a record for every + /// The data in the UserDictionary can continue to grow until -- unlikely -- it contains a record for every /// user on or that was on the network at any point since the last client connect. This is a calculated risk, roughly /// knowing the size of the network, the size of the data being stored, and balanced against the consequences of not having - /// a user's data when it is needed (for queue positioning, speed limits, etc) + /// a user's data when it is needed (for queue positioning, speed limits, etc). /// /// /// The method acts on cached data _only_. This method should be called within hot paths, -- cgit v1.2.3 From 8538d22cd30ff51f7641fc07b3793534874fa18f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 6 Jan 2024 17:03:47 -0600 Subject: suppress warning --- src/slskd/Common/Authentication/ApiKeyAuthentication.cs | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src') diff --git a/src/slskd/Common/Authentication/ApiKeyAuthentication.cs b/src/slskd/Common/Authentication/ApiKeyAuthentication.cs index 7c6c9235..b27c4c05 100644 --- a/src/slskd/Common/Authentication/ApiKeyAuthentication.cs +++ b/src/slskd/Common/Authentication/ApiKeyAuthentication.cs @@ -96,7 +96,9 @@ namespace slskd.Authentication /// /// API key authentication options. /// +#pragma warning disable S2094 // Classes should not be empty public class ApiKeyAuthenticationOptions : AuthenticationSchemeOptions +#pragma warning restore S2094 // Classes should not be empty { } } -- cgit v1.2.3 From 9659015d025fb0d4276106e8bcc8333942c094fd Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 6 Jan 2024 17:19:31 -0600 Subject: resolve more warnings --- src/slskd/Core/Options.cs | 2 ++ src/slskd/Relay/RelayClient.cs | 4 ++++ src/slskd/Relay/RelayService.cs | 2 +- src/slskd/Shares/Types/Share.cs | 2 ++ src/slskd/Users/UserService.cs | 2 +- src/slskd/slskd.csproj | 4 ++-- 6 files changed, 12 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index a3437bf4..e34a86b0 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -682,7 +682,9 @@ namespace slskd return (share, matches[0].Groups[2].Value, matches[0].Groups[3].Value); } +#pragma warning disable S3878 // Arrays should not be created for params parameters return (share, share.Split(new[] { '/', '\\' }).Last(), share); +#pragma warning restore S3878 // Arrays should not be created for params parameters } var digestedShared = directories diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs index f3880c97..b54a04f3 100644 --- a/src/slskd/Relay/RelayClient.cs +++ b/src/slskd/Relay/RelayClient.cs @@ -259,7 +259,9 @@ namespace slskd.Relay { if (message is HttpClientHandler clientHandler && options.Relay.Controller.IgnoreCertificateErrors) { +#pragma warning disable S4830 // Enable server certificate validation on this SSL/TLS connection clientHandler.ServerCertificateCustomValidationCallback += (_, _, _, _) => true; +#pragma warning restore S4830 // Enable server certificate validation on this SSL/TLS connection } return message; @@ -304,7 +306,9 @@ namespace slskd.Relay client = new HttpClient(new HttpClientHandler() { ClientCertificateOptions = ClientCertificateOption.Manual, +#pragma warning disable S4830 // Enable server certificate validation on this SSL/TLS connection ServerCertificateCustomValidationCallback = (_, _, _, _) => true, +#pragma warning restore S4830 // Enable server certificate validation on this SSL/TLS connection }); } else diff --git a/src/slskd/Relay/RelayService.cs b/src/slskd/Relay/RelayService.cs index 6cbbb0a2..d3f35693 100644 --- a/src/slskd/Relay/RelayService.cs +++ b/src/slskd/Relay/RelayService.cs @@ -624,7 +624,7 @@ namespace slskd.Relay // ensure filename is relative to the local download directory and make sure it doesn't start with a slash filename = filename .ReplaceFirst(OptionsMonitor.CurrentValue.Directories.Downloads, string.Empty) - .TrimStart(new[] { '/', '\\' }); + .TrimStart('/', '\\'); async Task Notify((string ConnectionId, Agent Agent) record) { diff --git a/src/slskd/Shares/Types/Share.cs b/src/slskd/Shares/Types/Share.cs index d60998f6..2911cf83 100644 --- a/src/slskd/Shares/Types/Share.cs +++ b/src/slskd/Shares/Types/Share.cs @@ -76,7 +76,9 @@ namespace slskd.Shares } else { +#pragma warning disable S3878 // Arrays should not be created for params parameters Alias = share.Split(new[] { '/', '\\' }).Last(); +#pragma warning restore S3878 // Arrays should not be created for params parameters LocalPath = share; } diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index 434d357c..5b15b671 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -49,7 +49,7 @@ namespace slskd.Users /// The data in the can continue to grow until -- unlikely -- it contains a record for every /// user on or that was on the network at any point since the last client connect. This is a calculated risk, roughly /// knowing the size of the network, the size of the data being stored, and balanced against the consequences of not having - /// a user's data when it is needed (for queue positioning, speed limits, etc) + /// a user's data when it is needed (for queue positioning, speed limits, etc). /// /// /// The method acts on cached data _only_. This method should be called within hot paths, diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj index 82108d47..9ca072a0 100644 --- a/src/slskd/slskd.csproj +++ b/src/slskd/slskd.csproj @@ -17,11 +17,11 @@ - 1701;1702;1591 + 1701;1702;1591;S1133;S2094;S1135 - 1591 + 1591;S1133;S2094;S1135 -- cgit v1.2.3 From 10663be47df87cdd7e6668c32321e13696902c4f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 6 Jan 2024 18:10:01 -0600 Subject: fetch group limits --- src/slskd/Application.cs | 56 +++++++++++++++++++++++++++++++++++++----------- 1 file changed, 44 insertions(+), 12 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index fe754220..19e86d1a 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -36,7 +36,6 @@ namespace slskd using Microsoft.AspNetCore.SignalR; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Hosting; - using NetTools; using Serilog; using Serilog.Events; using slskd.Configuration; @@ -62,22 +61,22 @@ namespace slskd /// /// The name of the default user group. /// - public static readonly string DefaultGroup = "default"; + public const string DefaultGroup = "default"; /// /// The name of the privileged user group. /// - public static readonly string PrivilegedGroup = "privileged"; + public const string PrivilegedGroup = "privileged"; /// /// The name of the leecher user group. /// - public static readonly string LeecherGroup = "leechers"; + public const string LeecherGroup = "leechers"; /// /// The name of the blacklisted user group. /// - public static readonly string BlacklistedGroup = "blacklisted"; + public const string BlacklistedGroup = "blacklisted"; private static readonly string ApplicationShutdownTransferExceptionMessage = "Application shut down"; @@ -475,21 +474,54 @@ namespace slskd return Task.CompletedTask; } - private Task EnqueueDownload(string username, IPEndPoint endpoint, string filename) + private async Task EnqueueDownload(string username, IPEndPoint endpoint, string filename) { if (Users.IsBlacklisted(username, endpoint.Address)) { Log.Information("Rejected enqueue request for blacklisted user {Username} ({IP})", username, endpoint.Address); - return Task.FromException(new DownloadEnqueueException($"File not shared.")); + throw new DownloadEnqueueException($"File not shared."); } - // todo: determine the user's group - // todo: get limit config for that group - // todo: if limits have been set, retrieve all of the user's transfers for the last week, including those currently in the queue + // get the user's group. this will be the name of the user's group, if they have been added to a + // user defined group, or one of the built-ins; 'default', 'privileged', 'leecher', or 'blacklisted' + var group = await Users.GetOrFetchGroupAsync(username); + + // privileged users aren't subject to limits (for now) + // i'm putting this off because 1) limits are unique to slskd, so all other clients are "unlimited" + // and 2) i can't figure out what the limits would be, if not unlimited. users should get some level + // of control, but i'd need to figure out a lower bound + if (string.Equals(group, PrivilegedGroup)) + { + await Transfers.Uploads.EnqueueAsync(username, filename); + } + + Options.GroupsOptions.LimitsOptions limits; + + if (Options.Groups.UserDefined.TryGetValue(group, out var userDefinedOptions)) + { + limits = userDefinedOptions.Limits; + } + else + { + limits = group switch + { + DefaultGroup => Options.Groups.Default.Limits, + LeecherGroup => Options.Groups.Leechers.Limits, + _ => Options.Groups.Default.Limits, + }; + } + + // if no limits are set, we're good to go + if (limits is null || (limits.Daily is null && limits.Weekly is null && limits.Queued is null)) + { + await Transfers.Uploads.EnqueueAsync(username, filename); + } + + // todo: retrieve all of the user's transfers for the last week, including those currently in the queue // todo: determine if any of the configured limits have been met or exceeded - // todo: if limits met or exceeded, return Task.FromException(new DownloadEnqueueException($"Limit(s) exceeded."); + // todo: if limits met or exceeded, throw new DownloadEnqueueException($"Limit(s) exceeded."); - return Transfers.Uploads.EnqueueAsync(username, filename); + await Transfers.Uploads.EnqueueAsync(username, filename); } /// -- cgit v1.2.3 From c47249fcd34fb40f05c68bfb7719ef7b191ae83d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 7 Jan 2024 18:39:26 -0600 Subject: clarify list usage --- src/slskd/Transfers/API/Controllers/TransfersController.cs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index aea815af..ad984a4c 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -180,8 +180,9 @@ namespace slskd.Transfers.API return Forbid(); } + // get all the transfers that aren't removed var transfers = Transfers.Uploads - .List() // https://github.com/dotnet/efcore/issues/10434 + .List(t => true, includeRemoved: false) // https://github.com/dotnet/efcore/issues/10434 .Where(t => t.State.HasFlag(Soulseek.TransferStates.Completed)); foreach (var id in transfers.Select(t => t.Id)) @@ -373,7 +374,9 @@ namespace slskd.Transfers.API return Forbid(); } - var uploads = Transfers.Uploads.List(includeRemoved: includeRemoved); + // todo: refactor this so it doesn't return the world. start and end time params + // should be required. consider pagination. + var uploads = Transfers.Uploads.List(t => true, includeRemoved: includeRemoved); var response = uploads.GroupBy(t => t.Username).Select(grouping => new UserResponse() { @@ -405,7 +408,7 @@ namespace slskd.Transfers.API return Forbid(); } - var uploads = Transfers.Uploads.List(d => d.Username == username); + var uploads = Transfers.Uploads.List(d => d.Username == username, includeRemoved: false); if (!uploads.Any()) { -- cgit v1.2.3 From 65777f07088b8241e13b25cc56ea3719d5104ccd Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 7 Jan 2024 18:39:38 -0600 Subject: document EndedAt --- src/slskd/Transfers/Types/Transfer.cs | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'src') diff --git a/src/slskd/Transfers/Types/Transfer.cs b/src/slskd/Transfers/Types/Transfer.cs index c55826d4..1797adcd 100644 --- a/src/slskd/Transfers/Types/Transfer.cs +++ b/src/slskd/Transfers/Types/Transfer.cs @@ -37,6 +37,13 @@ namespace slskd.Transfers public DateTime RequestedAt { get; set; } public DateTime? EnqueuedAt { get; set; } public DateTime? StartedAt { get; set; } + + /// + /// The time at which the transfer ended, or null if the transfer has not yet started or is in progress. + /// + /// + /// Guaranteed to be set for transfers in a terminal state. + /// public DateTime? EndedAt { get; set; } public long BytesTransferred { get; set; } public double AverageSpeed { get; set; } -- cgit v1.2.3 From f41badad5074668ac36f07a58bbf971e01678ce6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 7 Jan 2024 18:40:56 -0600 Subject: make list params more explicit --- src/slskd/Transfers/Uploads/UploadService.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 04e6a431..56bf3751 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -75,9 +75,9 @@ namespace slskd.Transfers.Uploads /// Returns a list of all uploads matching the optional . /// /// An optional expression used to match uploads. - /// Optionally include uploads that have been removed previously. + /// A value indicating whether to include uploads that have been removed previously. /// The list of uploads matching the specified expression, or all uploads if no expression is specified. - List List(Expression> expression = null, bool includeRemoved = false); + List List(Expression> expression, bool includeRemoved); /// /// Removes uploads older than the specified . @@ -233,7 +233,7 @@ namespace slskd.Transfers.Uploads Log.Information("Resolved {Remote} to physical file {Physical} on host '{Host}'", filename, localFilename, host); // find existing records for this username and file that haven't been removed from the UI - var existingRecords = List(t => t.Username == username && t.Filename == localFilename && !t.Removed); + var existingRecords = List(t => t.Username == username && t.Filename == localFilename, includeRemoved: false); // check whether any of these records is in a non-complete state and bail out if so if (existingRecords.Any(t => !t.State.HasFlag(TransferStates.Completed))) @@ -428,9 +428,9 @@ namespace slskd.Transfers.Uploads /// Returns a list of all uploads matching the optional . /// /// An optional expression used to match uploads. - /// Optionally include uploads that have been removed previously. + /// A value indicating whether to include uploads that have been removed previously. /// The list of uploads matching the specified expression, or all uploads if no expression is specified. - public List List(Expression> expression = null, bool includeRemoved = false) + public List List(Expression> expression, bool includeRemoved) { expression ??= t => true; -- cgit v1.2.3 From 9f4b853959435b69df02f703f95fa112e571896e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 7 Jan 2024 18:41:27 -0600 Subject: implement Summarize() --- src/slskd/Transfers/Uploads/UploadService.cs | 59 +++++++++++++++++++++++++--- 1 file changed, 53 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 56bf3751..ba3dea77 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -94,6 +94,17 @@ namespace slskd.Transfers.Uploads /// The unique identifier of the upload. void Remove(Guid id); + /// + /// Returns a summary of the uploads matching the specified . This can be expensive; + /// consider caching. + /// + /// The expression used to select uploads for summarization. + /// + /// The generated summary, including the total number of transfers, the number of unique files and directories, and + /// total size in bytes. + /// + (int Transfers, int Files, int Directories, long Bytes) Summarize(Expression> expression); + /// /// Cancels the upload matching the specified , if it is in progress. /// @@ -146,10 +157,10 @@ namespace slskd.Transfers.Uploads 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 IOptionsMonitor OptionsMonitor { get; } private IRelayService Relay { get; } + private IShareService Shares { get; set; } + private IUserService Users { get; set; } /// /// Adds the specified . Supersedes any existing record for the same file and username. @@ -199,8 +210,8 @@ namespace slskd.Transfers.Uploads if (host == Program.LocalHostName) { - // if it's local, do a quick check to see if it exists to spare the caller from - // queueing up if the transfer is doomed to fail. for remote files, take a leap of faith. + // if it's local, do a quick check to see if it exists to spare the caller from queueing up if the transfer is + // doomed to fail. for remote files, take a leap of faith. var info = new FileInfo(localFilename); if (!info.Exists) @@ -360,8 +371,8 @@ namespace slskd.Transfers.Uploads transfer = transfer.WithSoulseekTransfer(completedTransfer); } - // explicitly dispose the rate limiter to prevent updates from it - // beyond this point, which may overwrite the final state + // explicitly dispose the rate limiter to prevent updates from it beyond this point, which may overwrite the + // final state rateLimiter.Dispose(); // todo: broadcast @@ -536,6 +547,42 @@ namespace slskd.Transfers.Uploads } } + /// + /// Returns a summary of the uploads matching the specified . This can be expensive; + /// consider caching. + /// + /// The expression used to select uploads for summarization. + /// + /// The generated summary, including the total number of transfers, the number of unique files and directories, and + /// total size in bytes. + /// + public (int Transfers, int Files, int Directories, long Bytes) Summarize(Expression> expression) + { + // get all matching transfers, regardless of whether they have been removed from the UI + // note that this could be a raw SQL query, and if it were the performance would be much better + // however, passing an expression wouldn't work. if performance becomes an issue, consider passing in + // a query object instead of an expression and then converting this to a raw query. + var records = List(expression, includeRemoved: true); + + int transfers = 0; + long bytes = 0; + var files = new HashSet(); + var directories = new HashSet(); + + foreach (var t in records) + { + transfers++; + bytes += t.Size; + files.Add(t.Filename); + + // this sucks, but this ensures history works even in cases where someone moves the app + data between windows and + // linux. if this causes a huge performance problem, i'll revisit. + directories.Add(t.Filename.NormalizePathForSoulseek().GetNormalizedDirectoryName()); + } + + return (transfers, files.Count, directories.Count, bytes); + } + /// /// Cancels the upload matching the specified , if it is in progress. /// -- cgit v1.2.3 From 9ef591cd6c8220d9b7fde529bc0554b9b104a180 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 7 Jan 2024 18:41:49 -0600 Subject: implement limit checks --- src/slskd/Application.cs | 88 +++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 83 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 19e86d1a..a8e7bf10 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -294,7 +294,7 @@ namespace slskd // records to be updated if the application has started to shut down so that we can do this cleanup and properly // disposition them as having failed due to an application shutdown, instead of some random exception thrown while // things are being disposed. - var activeUploads = Transfers.Uploads.List(t => !t.State.HasFlag(TransferStates.Completed) && !t.Removed) + var activeUploads = Transfers.Uploads.List(t => !t.State.HasFlag(TransferStates.Completed), includeRemoved: false) .Where(t => !t.State.HasFlag(TransferStates.Completed)) // https://github.com/dotnet/efcore/issues/10434 .ToList(); @@ -511,15 +511,93 @@ namespace slskd }; } - // if no limits are set, we're good to go + // if no limits are set, we're good to go; just enqueue the file. if (limits is null || (limits.Daily is null && limits.Weekly is null && limits.Queued is null)) { await Transfers.Uploads.EnqueueAsync(username, filename); } - // todo: retrieve all of the user's transfers for the last week, including those currently in the queue - // todo: determine if any of the configured limits have been met or exceeded - // todo: if limits met or exceeded, throw new DownloadEnqueueException($"Limit(s) exceeded."); + var sw = new Stopwatch(); + sw.Start(); + + /* + * we have limits set, so now we have to fetch the data and compare to see if any would be hit if we allow this transfer to be enqueued. + * the strategy here is to summarize all uploads: + * 1) belonging to this user + * 2) that were started within the time period + * 3) that did not end due to an error (state includes errored, exception column is set) + */ + bool OverLimits((int Transfers, int Files, int Directories, long Bytes) stats, Options.GroupsOptions.LimitsExtendedOptions options, out string reason) + { + reason = null; + var byteLimit = options.Megabytes * 1000 * 1000; + + if (stats.Bytes >= byteLimit) + { + reason = $"bytes {stats.Bytes} exceeds limit of {byteLimit}"; + return true; + } + + if (stats.Files >= options.Files) + { + reason = $"files {stats.Files} exceeds limit of {options.Files}"; + return true; + } + + if (stats.Directories >= options.Directories) + { + reason = $"directories {stats.Directories} exceeds limit of {options.Directories}"; + return true; + } + + return false; + } + + // start with the queue, since that should contain the fewest files and should be the least expensive to check + // "queued" includes both queued and in progress; records with a null EndedAt property, which is guaranteed to be set + // for terminal transfers. + var queued = Transfers.Uploads.Summarize(t => t.Username == username && t.EndedAt == null); + + Log.Debug("Fetched queue stats: {@Stats} ({Time}ms)", queued, sw.ElapsedMilliseconds); + + if (OverLimits(queued, limits.Queued, out var queuedReason)) + { + Log.Information("Rejected enqueue request for user {Username}: Queued {Reason}", queuedReason); + throw new DownloadEnqueueException($"Queued {queuedReason}"); + } + + // start with weekly, as this is the most likely limit to be hit and we want to keep the work to a minimum + var erroredState = (TransferStates.Completed | TransferStates.Errored).ToString(); + var weekly = Transfers.Uploads.Summarize(t => + t.Username == username + && t.StartedAt >= DateTime.UtcNow.AddDays(-7) + && t.State.ToString() != erroredState + && t.Exception == null); + + Log.Debug("Fetched weekly stats: {Stats} ({Time}ms)", weekly, sw.ElapsedMilliseconds); + + if (OverLimits(weekly, limits.Weekly, out var weeklyReason)) + { + Log.Information("Rejected enqueue request for user {Username}: Weekly {Reason}", weeklyReason); + throw new DownloadEnqueueException($"Weekly {weeklyReason}"); + } + + var daily = Transfers.Uploads.Summarize(t => + t.Username == username + && t.StartedAt >= DateTime.UtcNow.AddDays(-1) + && t.State.ToString() != erroredState + && t.Exception == null); + + Log.Debug("Fetched daily stats: {Stats} ({Time}ms)", weekly, sw.ElapsedMilliseconds); + + if (OverLimits(daily, limits.Daily, out var dailyReason)) + { + Log.Information("Rejected enqueue request for user {Username}: Daily {Reason}", dailyReason); + throw new DownloadEnqueueException($"Daily {dailyReason}"); + } + + sw.Stop(); + Log.Debug("Enqueue decision made in {Duration}ms", sw.ElapsedMilliseconds); await Transfers.Uploads.EnqueueAsync(username, filename); } -- cgit v1.2.3 From 2180570c8f2b58f8aa58f3147ac8ea5dc3c9dcf2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 11 Jan 2024 16:31:15 -0600 Subject: fix typo --- 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 a8e7bf10..9016bd34 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -387,7 +387,7 @@ namespace slskd await Client.ReconfigureOptionsAsync(patch); Log.Debug("Client configured"); - Log.Information("Listening for incoming connections son {IP}:{Port}", OptionsAtStartup.Soulseek.ListenIpAddress, OptionsAtStartup.Soulseek.ListenPort); + Log.Information("Listening for incoming connections on {IP}:{Port}", OptionsAtStartup.Soulseek.ListenIpAddress, OptionsAtStartup.Soulseek.ListenPort); if (OptionsAtStartup.Soulseek.Connection.Proxy.Enabled) { -- cgit v1.2.3 From a8eef8065fb7fcd4297bd152dd9a3333af76acbf Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 11 Jan 2024 20:49:23 -0600 Subject: fix linq expressions --- src/slskd/Application.cs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 9016bd34..f7427612 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -567,11 +567,12 @@ namespace slskd } // start with weekly, as this is the most likely limit to be hit and we want to keep the work to a minimum - var erroredState = (TransferStates.Completed | TransferStates.Errored).ToString(); + var erroredState = TransferStates.Completed | TransferStates.Errored; + var cutoffDateTime = DateTime.UtcNow.AddDays(-7); var weekly = Transfers.Uploads.Summarize(t => t.Username == username - && t.StartedAt >= DateTime.UtcNow.AddDays(-7) - && t.State.ToString() != erroredState + && t.StartedAt >= cutoffDateTime + && !t.State.HasFlag(erroredState) && t.Exception == null); Log.Debug("Fetched weekly stats: {Stats} ({Time}ms)", weekly, sw.ElapsedMilliseconds); @@ -582,10 +583,11 @@ namespace slskd throw new DownloadEnqueueException($"Weekly {weeklyReason}"); } + cutoffDateTime = DateTime.UtcNow.AddDays(-1); var daily = Transfers.Uploads.Summarize(t => t.Username == username - && t.StartedAt >= DateTime.UtcNow.AddDays(-1) - && t.State.ToString() != erroredState + && t.StartedAt >= cutoffDateTime + && !t.State.HasFlag(erroredState) && t.Exception == null); Log.Debug("Fetched daily stats: {Stats} ({Time}ms)", weekly, sw.ElapsedMilliseconds); -- cgit v1.2.3 From 11f19fa6892a4f20b98025b82a9928b8098a3e09 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 11 Jan 2024 20:49:48 -0600 Subject: fix log --- 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 f7427612..99540f5e 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -562,7 +562,7 @@ namespace slskd if (OverLimits(queued, limits.Queued, out var queuedReason)) { - Log.Information("Rejected enqueue request for user {Username}: Queued {Reason}", queuedReason); + Log.Information("Rejected enqueue request for user {Username}: Queued {Reason}", username, queuedReason); throw new DownloadEnqueueException($"Queued {queuedReason}"); } -- cgit v1.2.3 From 30b7722784c16394698ff89047e0829b40016d2c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 11 Jan 2024 22:00:31 -0600 Subject: summarize -> hypothesize --- src/slskd/Transfers/Uploads/UploadService.cs | 98 +++++++++++++++------------- 1 file changed, 51 insertions(+), 47 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index ba3dea77..f83cc05f 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -71,6 +71,18 @@ namespace slskd.Transfers.Uploads /// The found transfer, or default if not found. Transfer Find(Expression> expression); + /// + /// Returns a summary of the uploads matching the specified . This can be expensive; + /// consider caching. + /// + /// The expression used to select uploads for summarization. + /// The hypotheticaly new transfer. + /// + /// The generated summary, including the total number of transfers, the number of unique files and directories, and + /// total size in bytes. + /// + (int Transfers, int Files, int Directories, long Bytes) Hypothesize(Expression> expression, Transfer hypothetical); + /// /// Returns a list of all uploads matching the optional . /// @@ -94,17 +106,6 @@ namespace slskd.Transfers.Uploads /// The unique identifier of the upload. void Remove(Guid id); - /// - /// Returns a summary of the uploads matching the specified . This can be expensive; - /// consider caching. - /// - /// The expression used to select uploads for summarization. - /// - /// The generated summary, including the total number of transfers, the number of unique files and directories, and - /// total size in bytes. - /// - (int Transfers, int Files, int Directories, long Bytes) Summarize(Expression> expression); - /// /// Cancels the upload matching the specified , if it is in progress. /// @@ -435,6 +436,45 @@ namespace slskd.Transfers.Uploads } } + /// + /// Returns a summary of the uploads matching the specified . This can be expensive; + /// consider caching. + /// + /// The expression used to select uploads for summarization. + /// The hypotheticaly new transfer. + /// + /// The generated summary, including the total number of transfers, the number of unique files and directories, and + /// total size in bytes. + /// + public (int Transfers, int Files, int Directories, long Bytes) Hypothesize(Expression> expression, Transfer hypothetical) + { + // get all matching transfers, regardless of whether they have been removed from the UI note that this could be a raw + // SQL query, and if it were the performance would be much better however, passing an expression wouldn't work. if + // performance becomes an issue, consider passing in a query object instead of an expression and then converting this + // to a raw query. + var records = List(expression, includeRemoved: true); + + records.Add(hypothetical); + + int transfers = 0; + long bytes = 0; + var files = new HashSet(); + var directories = new HashSet(); + + foreach (var t in records) + { + transfers++; + bytes += t.Size; + files.Add(t.Filename); + + // this sucks, but this ensures history works even in cases where someone moves the app + data between windows and + // linux. if this causes a huge performance problem, i'll revisit. + directories.Add(t.Filename.NormalizePathForSoulseek().GetNormalizedDirectoryName()); + } + + return (transfers, files.Count, directories.Count, bytes); + } + /// /// Returns a list of all uploads matching the optional . /// @@ -547,42 +587,6 @@ namespace slskd.Transfers.Uploads } } - /// - /// Returns a summary of the uploads matching the specified . This can be expensive; - /// consider caching. - /// - /// The expression used to select uploads for summarization. - /// - /// The generated summary, including the total number of transfers, the number of unique files and directories, and - /// total size in bytes. - /// - public (int Transfers, int Files, int Directories, long Bytes) Summarize(Expression> expression) - { - // get all matching transfers, regardless of whether they have been removed from the UI - // note that this could be a raw SQL query, and if it were the performance would be much better - // however, passing an expression wouldn't work. if performance becomes an issue, consider passing in - // a query object instead of an expression and then converting this to a raw query. - var records = List(expression, includeRemoved: true); - - int transfers = 0; - long bytes = 0; - var files = new HashSet(); - var directories = new HashSet(); - - foreach (var t in records) - { - transfers++; - bytes += t.Size; - files.Add(t.Filename); - - // this sucks, but this ensures history works even in cases where someone moves the app + data between windows and - // linux. if this causes a huge performance problem, i'll revisit. - directories.Add(t.Filename.NormalizePathForSoulseek().GetNormalizedDirectoryName()); - } - - return (transfers, files.Count, directories.Count, bytes); - } - /// /// Cancels the upload matching the specified , if it is in progress. /// -- cgit v1.2.3 From 4ca32b4701dbf2bd862b58d0500f033ed87f3288 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 11 Jan 2024 22:01:43 -0600 Subject: get file size to hypothesize --- src/slskd/Application.cs | 122 +++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 107 insertions(+), 15 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 99540f5e..aa6e2a61 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -46,6 +46,7 @@ namespace slskd using slskd.Search; using slskd.Shares; using slskd.Transfers; + using slskd.Transfers.API; using slskd.Users; using Soulseek; using Soulseek.Diagnostics; @@ -479,7 +480,7 @@ namespace slskd if (Users.IsBlacklisted(username, endpoint.Address)) { Log.Information("Rejected enqueue request for blacklisted user {Username} ({IP})", username, endpoint.Address); - throw new DownloadEnqueueException($"File not shared."); + throw new DownloadEnqueueException("File not shared."); } // get the user's group. this will be the name of the user's group, if they have been added to a @@ -520,6 +521,47 @@ namespace slskd var sw = new Stopwatch(); sw.Start(); + // in order to properly determine if the requested file would exceed any limits, we need to know the size of the file + // this is unfortunately not very straightforward; the size depends on which share repository the file is in and which + // host is hosting the file. figure all that out here + long size; + + try + { + var (host, localFilename) = await Shares.ResolveFileAsync(filename); + + Log.Debug("Resolved file {RemoteFilename} to host {Host} and file {LocalFilename}", filename, host, localFilename); + + if (host == Program.LocalHostName) + { + // if it's local, do a quick check to see if it exists to spare the caller from queueing up if the transfer is + // doomed to fail. for remote files, take a leap of faith. + var info = new FileInfo(localFilename); + + if (!info.Exists) + { + Shares.RequestScan(); + throw new NotFoundException($"The file '{localFilename}' could not be located on disk. A share scan should be performed."); + } + + size = info.Length; + } + + var (exists, length) = await Relay.GetFileInfoAsync(agentName: host, filename); + + if (!exists || length <= 0) + { + // todo: force a remote scan + throw new NotFoundException($"The file '{localFilename}' could not be located on Agent {host}. A share scan should be performed."); + } + + size = length; + } + catch (NotFoundException) + { + throw new DownloadEnqueueException("File not shared."); + } + /* * we have limits set, so now we have to fetch the data and compare to see if any would be hit if we allow this transfer to be enqueued. * the strategy here is to summarize all uploads: @@ -532,19 +574,19 @@ namespace slskd reason = null; var byteLimit = options.Megabytes * 1000 * 1000; - if (stats.Bytes >= byteLimit) + if (stats.Bytes > byteLimit) { reason = $"bytes {stats.Bytes} exceeds limit of {byteLimit}"; return true; } - if (stats.Files >= options.Files) + if (stats.Files > options.Files) { reason = $"files {stats.Files} exceeds limit of {options.Files}"; return true; } - if (stats.Directories >= options.Directories) + if (stats.Directories > options.Directories) { reason = $"directories {stats.Directories} exceeds limit of {options.Directories}"; return true; @@ -556,7 +598,13 @@ namespace slskd // start with the queue, since that should contain the fewest files and should be the least expensive to check // "queued" includes both queued and in progress; records with a null EndedAt property, which is guaranteed to be set // for terminal transfers. - var queued = Transfers.Uploads.Summarize(t => t.Username == username && t.EndedAt == null); + var queued = Transfers.Uploads.Hypothesize( + expression: t => t.Username == username && t.EndedAt == null, + hypothetical: new Transfers.Transfer() + { + Filename = filename, + Size = size, + }); Log.Debug("Fetched queue stats: {@Stats} ({Time}ms)", queued, sw.ElapsedMilliseconds); @@ -569,11 +617,17 @@ namespace slskd // start with weekly, as this is the most likely limit to be hit and we want to keep the work to a minimum var erroredState = TransferStates.Completed | TransferStates.Errored; var cutoffDateTime = DateTime.UtcNow.AddDays(-7); - var weekly = Transfers.Uploads.Summarize(t => - t.Username == username - && t.StartedAt >= cutoffDateTime - && !t.State.HasFlag(erroredState) - && t.Exception == null); + var weekly = Transfers.Uploads.Hypothesize( + expression: t => + t.Username == username + && t.StartedAt >= cutoffDateTime + && !t.State.HasFlag(erroredState) + && t.Exception == null, + hypothetical: new Transfers.Transfer() + { + Filename = filename, + Size = size, + }); Log.Debug("Fetched weekly stats: {Stats} ({Time}ms)", weekly, sw.ElapsedMilliseconds); @@ -584,11 +638,17 @@ namespace slskd } cutoffDateTime = DateTime.UtcNow.AddDays(-1); - var daily = Transfers.Uploads.Summarize(t => - t.Username == username - && t.StartedAt >= cutoffDateTime - && !t.State.HasFlag(erroredState) - && t.Exception == null); + var daily = Transfers.Uploads.Hypothesize( + expression: t => + t.Username == username + && t.StartedAt >= cutoffDateTime + && !t.State.HasFlag(erroredState) + && t.Exception == null, + hypothetical: new Transfers.Transfer() + { + Filename = filename, + Size = size, + }); Log.Debug("Fetched daily stats: {Stats} ({Time}ms)", weekly, sw.ElapsedMilliseconds); @@ -1512,5 +1572,37 @@ namespace slskd throw; } } + + private async Task GetSharedFileLengthAsync(string filename) + { + var (host, localFilename) = await Shares.ResolveFileAsync(filename); + + Log.Debug("Resolved file {RemoteFilename} to host {Host} and file {LocalFilename}", filename, host, localFilename); + + if (host == Program.LocalHostName) + { + // if it's local, do a quick check to see if it exists to spare the caller from queueing up if the transfer is + // doomed to fail. for remote files, take a leap of faith. + var info = new FileInfo(localFilename); + + if (!info.Exists) + { + Shares.RequestScan(); + throw new NotFoundException($"The file '{localFilename}' could not be located on disk. A share scan should be performed."); + } + + return info.Length; + } + + var (exists, length) = await Relay.GetFileInfoAsync(agentName: host, filename); + + if (!exists || length <= 0) + { + // todo: force a remote scan + throw new NotFoundException($"The file '{localFilename}' could not be located on Agent {host}. A share scan should be performed."); + } + + return length; + } } } -- cgit v1.2.3 From ce0dfefb9bcaf6f7752d55cd544a17257e67aee6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 11 Jan 2024 22:16:29 -0600 Subject: FindFilename -> FindFileInfo --- src/slskd/Shares/IShareRepository.cs | 4 ++-- src/slskd/Shares/SqliteShareRepository.cs | 13 +++++++------ 2 files changed, 9 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/slskd/Shares/IShareRepository.cs b/src/slskd/Shares/IShareRepository.cs index 41b0fe32..c721fa40 100644 --- a/src/slskd/Shares/IShareRepository.cs +++ b/src/slskd/Shares/IShareRepository.cs @@ -74,11 +74,11 @@ namespace slskd.Shares void EnableKeepalive(bool enable); /// - /// Finds the filename of the file matching the specified . + /// Finds the filename and length of the file matching the specified . /// /// The fully qualified remote path of the file. /// The filename, if found. - string FindFilename(string maskedFilename); + (string Filename, long Size) FindFileInfo(string maskedFilename); /// /// Finds and returns the most recent scan record. diff --git a/src/slskd/Shares/SqliteShareRepository.cs b/src/slskd/Shares/SqliteShareRepository.cs index 57a76177..882ede74 100644 --- a/src/slskd/Shares/SqliteShareRepository.cs +++ b/src/slskd/Shares/SqliteShareRepository.cs @@ -210,10 +210,10 @@ namespace slskd.Shares /// /// The fully qualified remote path of the file. /// The filename, if found. - public string FindFilename(string maskedFilename) + public (string Filename, long Size) FindFileInfo(string maskedFilename) { using var conn = GetConnection(); - using var cmd = new SqliteCommand("SELECT originalFilename FROM files WHERE maskedFilename = @maskedFilename;", conn); + using var cmd = new SqliteCommand("SELECT originalFilename, size FROM files WHERE maskedFilename = @maskedFilename;", conn); cmd.Parameters.AddWithValue("maskedFilename", maskedFilename); var reader = cmd.ExecuteReader(); @@ -221,12 +221,13 @@ namespace slskd.Shares if (!reader.Read()) { Log.Warning("Failed to resolve shared file {Filename}", maskedFilename); - return null; + return default; } - var resolved = reader.GetString(0); - Log.Debug($"Resolved requested shared file {maskedFilename} to {resolved}"); - return resolved; + var filename = (string)reader["originalFilename"]; + var size = (long)reader["size"]; + Log.Debug($"Resolved requested shared file {maskedFilename} to {filename} ({size} bytes)"); + return (filename, size); } /// -- cgit v1.2.3 From 66ac937336d6e1dce0f2c20f4d603933dd718326 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 11 Jan 2024 22:17:06 -0600 Subject: return file size when resolving --- src/slskd/Shares/IShareService.cs | 4 ++-- src/slskd/Shares/ShareService.cs | 10 +++++----- 2 files changed, 7 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/slskd/Shares/IShareService.cs b/src/slskd/Shares/IShareService.cs index 7e1352e9..7db9671b 100644 --- a/src/slskd/Shares/IShareService.cs +++ b/src/slskd/Shares/IShareService.cs @@ -88,7 +88,7 @@ namespace slskd.Shares void RequestScan(); /// - /// Resolves the local filename of the specified , if the mask is associated with a + /// Resolves the local filename and size of the specified , if the mask is associated with a /// configured share. /// /// The fully qualified filename to resolve. @@ -96,7 +96,7 @@ namespace slskd.Shares /// /// Thrown when the specified remote filename can not be associated with a configured share. /// - Task<(string Host, string Filename)> ResolveFileAsync(string remoteFilename); + Task<(string Host, string Filename, long Size)> ResolveFileAsync(string remoteFilename); /// /// Scans the configured shares on the local host. diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index 97867cde..4f409705 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -267,9 +267,9 @@ namespace slskd.Shares /// /// Thrown when the specified remote filename can not be associated with a configured share. /// - public Task<(string Host, string Filename)> ResolveFileAsync(string remoteFilename) + public Task<(string Host, string Filename, long Size)> ResolveFileAsync(string remoteFilename) { - string resolvedFilename = Local.Repository.FindFilename(remoteFilename); + var (resolvedFilename, size) = Local.Repository.FindFileInfo(remoteFilename); // when we're debugging the relay (running as both controller and agent on the same instance) // always resolve files from remote hosts, ignoring local. this is a crappy hack, but it is the @@ -281,7 +281,7 @@ namespace slskd.Shares else if (!string.IsNullOrEmpty(resolvedFilename)) { Log.Debug("Resolved remote file to {ResolvedFilename} on local host", resolvedFilename); - return Task.FromResult((Program.LocalHostName, resolvedFilename)); + return Task.FromResult((Program.LocalHostName, resolvedFilename, size)); } else { @@ -292,12 +292,12 @@ namespace slskd.Shares // this is the slow, dumb way to do this, but it's plenty fast in this context. foreach (var host in HostDictionary.Values) { - resolvedFilename = host.Repository.FindFilename(remoteFilename); + (resolvedFilename, size) = host.Repository.FindFileInfo(remoteFilename); if (!string.IsNullOrEmpty(resolvedFilename)) { Log.Debug("Resolved remote file to {ResolvedFilename} on host {Host}", remoteFilename, host.Host.Name); - return Task.FromResult((host.Host.Name, resolvedFilename)); + return Task.FromResult((host.Host.Name, resolvedFilename, size)); } Log.Debug("Failed to resolve remote file on host {Host}", host.Host.Name); -- cgit v1.2.3 From 570d65da43ffbc3638502e1ac428dcdb96d5137d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 11 Jan 2024 22:17:25 -0600 Subject: use resolved size --- src/slskd/Application.cs | 69 ++++-------------------------------------------- 1 file changed, 5 insertions(+), 64 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index aa6e2a61..cdea14e1 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -524,38 +524,11 @@ namespace slskd // in order to properly determine if the requested file would exceed any limits, we need to know the size of the file // this is unfortunately not very straightforward; the size depends on which share repository the file is in and which // host is hosting the file. figure all that out here - long size; + (string Host, string Filename, long Size) resolved; try { - var (host, localFilename) = await Shares.ResolveFileAsync(filename); - - Log.Debug("Resolved file {RemoteFilename} to host {Host} and file {LocalFilename}", filename, host, localFilename); - - if (host == Program.LocalHostName) - { - // if it's local, do a quick check to see if it exists to spare the caller from queueing up if the transfer is - // doomed to fail. for remote files, take a leap of faith. - var info = new FileInfo(localFilename); - - if (!info.Exists) - { - Shares.RequestScan(); - throw new NotFoundException($"The file '{localFilename}' could not be located on disk. A share scan should be performed."); - } - - size = info.Length; - } - - var (exists, length) = await Relay.GetFileInfoAsync(agentName: host, filename); - - if (!exists || length <= 0) - { - // todo: force a remote scan - throw new NotFoundException($"The file '{localFilename}' could not be located on Agent {host}. A share scan should be performed."); - } - - size = length; + resolved = await Shares.ResolveFileAsync(filename); } catch (NotFoundException) { @@ -603,7 +576,7 @@ namespace slskd hypothetical: new Transfers.Transfer() { Filename = filename, - Size = size, + Size = resolved.Size, }); Log.Debug("Fetched queue stats: {@Stats} ({Time}ms)", queued, sw.ElapsedMilliseconds); @@ -626,7 +599,7 @@ namespace slskd hypothetical: new Transfers.Transfer() { Filename = filename, - Size = size, + Size = resolved.Size, }); Log.Debug("Fetched weekly stats: {Stats} ({Time}ms)", weekly, sw.ElapsedMilliseconds); @@ -647,7 +620,7 @@ namespace slskd hypothetical: new Transfers.Transfer() { Filename = filename, - Size = size, + Size = resolved.Size, }); Log.Debug("Fetched daily stats: {Stats} ({Time}ms)", weekly, sw.ElapsedMilliseconds); @@ -1572,37 +1545,5 @@ namespace slskd throw; } } - - private async Task GetSharedFileLengthAsync(string filename) - { - var (host, localFilename) = await Shares.ResolveFileAsync(filename); - - Log.Debug("Resolved file {RemoteFilename} to host {Host} and file {LocalFilename}", filename, host, localFilename); - - if (host == Program.LocalHostName) - { - // if it's local, do a quick check to see if it exists to spare the caller from queueing up if the transfer is - // doomed to fail. for remote files, take a leap of faith. - var info = new FileInfo(localFilename); - - if (!info.Exists) - { - Shares.RequestScan(); - throw new NotFoundException($"The file '{localFilename}' could not be located on disk. A share scan should be performed."); - } - - return info.Length; - } - - var (exists, length) = await Relay.GetFileInfoAsync(agentName: host, filename); - - if (!exists || length <= 0) - { - // todo: force a remote scan - throw new NotFoundException($"The file '{localFilename}' could not be located on Agent {host}. A share scan should be performed."); - } - - return length; - } } } -- cgit v1.2.3 From 9b68f1c412b26cfedd37d79ea9c7fa0b2c883ba2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 11 Jan 2024 22:29:47 -0600 Subject: tuple --- src/slskd/Relay/RelayClient.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs index b54a04f3..e7a1cc76 100644 --- a/src/slskd/Relay/RelayClient.cs +++ b/src/slskd/Relay/RelayClient.cs @@ -358,7 +358,7 @@ namespace slskd.Relay try { - var (_, localFilename) = await Shares.ResolveFileAsync(filename); + var (_, localFilename, _) = await Shares.ResolveFileAsync(filename); var localFileInfo = new FileInfo(localFilename); @@ -379,7 +379,7 @@ namespace slskd.Relay try { - var (_, localFilename) = await Shares.ResolveFileAsync(filename); + var (_, localFilename, _) = await Shares.ResolveFileAsync(filename); var localFileInfo = new FileInfo(localFilename); -- cgit v1.2.3 From d57ce7016d0845b9b908e355ccc95e728f960346 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 11 Jan 2024 22:31:14 -0600 Subject: warn on file size mismatch --- src/slskd/Transfers/Uploads/UploadService.cs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index f83cc05f..6a735696 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -199,13 +199,14 @@ namespace slskd.Transfers.Uploads { string host = default; string localFilename = default; + long resolvedFileLength = default; long localFileLength = default; Log.Information("[{Context}] {Username} requested {Filename}", "UPLOAD REQUESTED", username, filename); try { - (host, localFilename) = await Shares.ResolveFileAsync(filename); + (host, localFilename, resolvedFileLength) = await Shares.ResolveFileAsync(filename); Log.Debug("Resolved file {RemoteFilename} to host {Host} and file {LocalFilename}", filename, host, localFilename); @@ -244,6 +245,13 @@ namespace slskd.Transfers.Uploads Log.Information("Resolved {Remote} to physical file {Physical} on host '{Host}'", filename, localFilename, host); + if (localFileLength != resolvedFileLength) + { + // todo: should we fail the transfer? the file changed on disk since the last scan. i guess not? since the caller doesn't provide a size + Shares.RequestScan(); + Log.Warning("Resolved size for {Remote} of {Resolved} doesn't match actual size {Actual}", filename, resolvedFileLength, localFileLength); + } + // find existing records for this username and file that haven't been removed from the UI var existingRecords = List(t => t.Username == username && t.Filename == localFilename, includeRemoved: false); -- cgit v1.2.3 From 1efd59f43312b33e8db62d4e0fed339bda462dde Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 11 Jan 2024 22:31:33 -0600 Subject: use resolved filename --- src/slskd/Application.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index cdea14e1..67c6dc85 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -575,7 +575,7 @@ namespace slskd expression: t => t.Username == username && t.EndedAt == null, hypothetical: new Transfers.Transfer() { - Filename = filename, + Filename = resolved.Filename, Size = resolved.Size, }); @@ -598,7 +598,7 @@ namespace slskd && t.Exception == null, hypothetical: new Transfers.Transfer() { - Filename = filename, + Filename = resolved.Filename, Size = resolved.Size, }); @@ -619,7 +619,7 @@ namespace slskd && t.Exception == null, hypothetical: new Transfers.Transfer() { - Filename = filename, + Filename = resolved.Filename, Size = resolved.Size, }); -- cgit v1.2.3 From 37693e0e4fabef5395bb7644ce0c014e1efc3084 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 11 Jan 2024 22:38:00 -0600 Subject: wip --- src/slskd/Application.cs | 86 ++++++++++++++-------------- src/slskd/Transfers/Uploads/UploadService.cs | 3 + 2 files changed, 46 insertions(+), 43 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 67c6dc85..4c794179 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -587,49 +587,49 @@ namespace slskd throw new DownloadEnqueueException($"Queued {queuedReason}"); } - // start with weekly, as this is the most likely limit to be hit and we want to keep the work to a minimum - var erroredState = TransferStates.Completed | TransferStates.Errored; - var cutoffDateTime = DateTime.UtcNow.AddDays(-7); - var weekly = Transfers.Uploads.Hypothesize( - expression: t => - t.Username == username - && t.StartedAt >= cutoffDateTime - && !t.State.HasFlag(erroredState) - && t.Exception == null, - hypothetical: new Transfers.Transfer() - { - Filename = resolved.Filename, - Size = resolved.Size, - }); - - Log.Debug("Fetched weekly stats: {Stats} ({Time}ms)", weekly, sw.ElapsedMilliseconds); - - if (OverLimits(weekly, limits.Weekly, out var weeklyReason)) - { - Log.Information("Rejected enqueue request for user {Username}: Weekly {Reason}", weeklyReason); - throw new DownloadEnqueueException($"Weekly {weeklyReason}"); - } - - cutoffDateTime = DateTime.UtcNow.AddDays(-1); - var daily = Transfers.Uploads.Hypothesize( - expression: t => - t.Username == username - && t.StartedAt >= cutoffDateTime - && !t.State.HasFlag(erroredState) - && t.Exception == null, - hypothetical: new Transfers.Transfer() - { - Filename = resolved.Filename, - Size = resolved.Size, - }); - - Log.Debug("Fetched daily stats: {Stats} ({Time}ms)", weekly, sw.ElapsedMilliseconds); - - if (OverLimits(daily, limits.Daily, out var dailyReason)) - { - Log.Information("Rejected enqueue request for user {Username}: Daily {Reason}", dailyReason); - throw new DownloadEnqueueException($"Daily {dailyReason}"); - } + //// start with weekly, as this is the most likely limit to be hit and we want to keep the work to a minimum + //var erroredState = TransferStates.Completed | TransferStates.Errored; + //var cutoffDateTime = DateTime.UtcNow.AddDays(-7); + //var weekly = Transfers.Uploads.Hypothesize( + // expression: t => + // t.Username == username + // && t.StartedAt >= cutoffDateTime + // && !t.State.HasFlag(erroredState) + // && t.Exception == null, + // hypothetical: new Transfers.Transfer() + // { + // Filename = resolved.Filename, + // Size = resolved.Size, + // }); + + //Log.Debug("Fetched weekly stats: {Stats} ({Time}ms)", weekly, sw.ElapsedMilliseconds); + + //if (OverLimits(weekly, limits.Weekly, out var weeklyReason)) + //{ + // Log.Information("Rejected enqueue request for user {Username}: Weekly {Reason}", weeklyReason); + // throw new DownloadEnqueueException($"Weekly {weeklyReason}"); + //} + + //cutoffDateTime = DateTime.UtcNow.AddDays(-1); + //var daily = Transfers.Uploads.Hypothesize( + // expression: t => + // t.Username == username + // && t.StartedAt >= cutoffDateTime + // && !t.State.HasFlag(erroredState) + // && t.Exception == null, + // hypothetical: new Transfers.Transfer() + // { + // Filename = resolved.Filename, + // Size = resolved.Size, + // }); + + //Log.Debug("Fetched daily stats: {Stats} ({Time}ms)", weekly, sw.ElapsedMilliseconds); + + //if (OverLimits(daily, limits.Daily, out var dailyReason)) + //{ + // Log.Information("Rejected enqueue request for user {Username}: Daily {Reason}", dailyReason); + // throw new DownloadEnqueueException($"Daily {dailyReason}"); + //} sw.Stop(); Log.Debug("Enqueue decision made in {Duration}ms", sw.ElapsedMilliseconds); diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 6a735696..6f01219e 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -480,6 +480,9 @@ namespace slskd.Transfers.Uploads directories.Add(t.Filename.NormalizePathForSoulseek().GetNormalizedDirectoryName()); } + Log.Warning("Directories: {@Directories}", directories); + Log.Warning("Files: {@Files}", files); + return (transfers, files.Count, directories.Count, bytes); } -- cgit v1.2.3 From b427be45760c693bb7e0b39237e78183968f8eac Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 15 Jan 2024 18:45:22 -0600 Subject: remove directory limit --- config/slskd.example.yml | 5 ----- src/slskd/Core/Options.cs | 6 ------ 2 files changed, 11 deletions(-) (limited to 'src') diff --git a/config/slskd.example.yml b/config/slskd.example.yml index 66a6f0ff..b1f4ce08 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -62,12 +62,10 @@ # limits: # queued: # files: 150 -# directories: 10 # megabytes: 1500 # daily: ~ # no daily limits (weekly still apply) # weekly: # files: 1500 -# directories: 100 # megabytes: 15000 # leechers: # thresholds: @@ -81,15 +79,12 @@ # limits: # queued: # files: 15 -# directories: 1 # megabytes: 150 # daily: # files: 30 -# directories: 2 # megabytes: 300 # weekly: # files: 150 -# directories: 10 # megabytes: 1500 # blacklisted: # members: diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index e34a86b0..c1f4d558 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1054,12 +1054,6 @@ namespace slskd [Range(1, int.MaxValue)] public int? Files { get; init; } = null; - /// - /// Gets the limit for number of directories. - /// - [Range(1, int.MaxValue)] - public int? Directories { get; init; } = null; - /// /// Gets the limit for number of megabytes. /// -- cgit v1.2.3 From 9c76af6ec66ccc16c6e956203fbdfb8fc2a4a05f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 15 Jan 2024 18:45:50 -0600 Subject: go back to summary, simplify greatly --- src/slskd/Transfers/Uploads/UploadService.cs | 55 ++++++++++++---------------- 1 file changed, 24 insertions(+), 31 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 6f01219e..6f03526c 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -76,12 +76,10 @@ namespace slskd.Transfers.Uploads /// consider caching. /// /// The expression used to select uploads for summarization. - /// The hypotheticaly new transfer. /// - /// The generated summary, including the total number of transfers, the number of unique files and directories, and - /// total size in bytes. + /// The generated summary, including the number of files and total size in bytes. /// - (int Transfers, int Files, int Directories, long Bytes) Hypothesize(Expression> expression, Transfer hypothetical); + (int Files, long Bytes) Summarize(Expression> expression); /// /// Returns a list of all uploads matching the optional . @@ -449,41 +447,36 @@ namespace slskd.Transfers.Uploads /// consider caching. /// /// The expression used to select uploads for summarization. - /// The hypotheticaly new transfer. /// - /// The generated summary, including the total number of transfers, the number of unique files and directories, and - /// total size in bytes. + /// The generated summary, including the number of files and total size in bytes. /// - public (int Transfers, int Files, int Directories, long Bytes) Hypothesize(Expression> expression, Transfer hypothetical) + public (int Files, long Bytes) Summarize(Expression> expression) { - // get all matching transfers, regardless of whether they have been removed from the UI note that this could be a raw - // SQL query, and if it were the performance would be much better however, passing an expression wouldn't work. if - // performance becomes an issue, consider passing in a query object instead of an expression and then converting this - // to a raw query. - var records = List(expression, includeRemoved: true); + expression ??= t => true; - records.Add(hypothetical); + try + { + using var context = ContextFactory.CreateDbContext(); - int transfers = 0; - long bytes = 0; - var files = new HashSet(); - var directories = new HashSet(); + var stats = context.Transfers + .AsNoTracking() + .Where(t => t.Direction == TransferDirection.Upload) + .Where(expression) + .GroupBy(t => true) // https://stackoverflow.com/a/25489456 + .Select(t => new + { + Files = t.Count(), + Bytes = t.Sum(x => x.Size), + }) + .FirstOrDefault(); - foreach (var t in records) + return (stats?.Files ?? 0, stats?.Bytes ?? 0); + } + catch (Exception ex) { - transfers++; - bytes += t.Size; - files.Add(t.Filename); - - // this sucks, but this ensures history works even in cases where someone moves the app + data between windows and - // linux. if this causes a huge performance problem, i'll revisit. - directories.Add(t.Filename.NormalizePathForSoulseek().GetNormalizedDirectoryName()); + Log.Error(ex, "Failed to list uploads: {Message}", ex.Message); + throw; } - - Log.Warning("Directories: {@Directories}", directories); - Log.Warning("Files: {@Files}", files); - - return (transfers, files.Count, directories.Count, bytes); } /// -- cgit v1.2.3 From 115940f252f5a3dc625441579c182017c802a6b7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 15 Jan 2024 18:46:09 -0600 Subject: move resolve up --- src/slskd/Application.cs | 12 ++++++++++++ 1 file changed, 12 insertions(+) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 4c794179..46c21ff7 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -483,6 +483,18 @@ namespace slskd throw new DownloadEnqueueException("File not shared."); } + // in order to properly determine if the requested file would exceed any limits, we need to know the size of the file + (string Host, string Filename, long Size) resolved; + + try + { + resolved = await Shares.ResolveFileAsync(filename); + } + catch (NotFoundException) + { + throw new DownloadEnqueueException("File not shared."); + } + // get the user's group. this will be the name of the user's group, if they have been added to a // user defined group, or one of the built-ins; 'default', 'privileged', 'leecher', or 'blacklisted' var group = await Users.GetOrFetchGroupAsync(username); -- cgit v1.2.3 From 28c9599776794a752248e4f1382efd61fce66c40 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 15 Jan 2024 18:46:37 -0600 Subject: implement queued checks --- src/slskd/Application.cs | 64 +++++++++++++++++++----------------------------- 1 file changed, 25 insertions(+), 39 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 46c21ff7..a065470d 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -505,9 +505,13 @@ namespace slskd // of control, but i'd need to figure out a lower bound if (string.Equals(group, PrivilegedGroup)) { + Log.Debug("Limits bypassed for {Username} and {File}; user is privileged", username, filename); await Transfers.Uploads.EnqueueAsync(username, filename); + return; } + // resolve the limits for this user's group. there's no 'fallthrough' here, if limits for a group + // are unset, then that group is unlimited. Options.GroupsOptions.LimitsOptions limits; if (Options.Groups.UserDefined.TryGetValue(group, out var userDefinedOptions)) @@ -524,29 +528,19 @@ namespace slskd }; } + bool IsNull(Options.GroupsOptions.LimitsExtendedOptions l) => l is null || (l?.Files is null && l?.Megabytes is null); + // if no limits are set, we're good to go; just enqueue the file. - if (limits is null || (limits.Daily is null && limits.Weekly is null && limits.Queued is null)) + if (limits is null || (IsNull(limits.Daily) && IsNull(limits.Weekly) && IsNull(limits.Queued))) { + Log.Debug("Limits bypassed for {Username} and {File}; limits are all null", username, filename); await Transfers.Uploads.EnqueueAsync(username, filename); + return; } var sw = new Stopwatch(); sw.Start(); - // in order to properly determine if the requested file would exceed any limits, we need to know the size of the file - // this is unfortunately not very straightforward; the size depends on which share repository the file is in and which - // host is hosting the file. figure all that out here - (string Host, string Filename, long Size) resolved; - - try - { - resolved = await Shares.ResolveFileAsync(filename); - } - catch (NotFoundException) - { - throw new DownloadEnqueueException("File not shared."); - } - /* * we have limits set, so now we have to fetch the data and compare to see if any would be hit if we allow this transfer to be enqueued. * the strategy here is to summarize all uploads: @@ -554,26 +548,20 @@ namespace slskd * 2) that were started within the time period * 3) that did not end due to an error (state includes errored, exception column is set) */ - bool OverLimits((int Transfers, int Files, int Directories, long Bytes) stats, Options.GroupsOptions.LimitsExtendedOptions options, out string reason) + bool OverLimits((int Files, long Bytes) stats, Options.GroupsOptions.LimitsExtendedOptions options, long size, out string reason) { reason = null; - var byteLimit = options.Megabytes * 1000 * 1000; - - if (stats.Bytes > byteLimit) - { - reason = $"bytes {stats.Bytes} exceeds limit of {byteLimit}"; - return true; - } + var byteLimit = (options?.Megabytes ?? 0) * 1000 * 1000; - if (stats.Files > options.Files) + if (options?.Megabytes is not null && (stats.Bytes + size) > byteLimit) { - reason = $"files {stats.Files} exceeds limit of {options.Files}"; + reason = $"bytes {stats.Bytes + size} would exceed limit of {byteLimit}"; return true; } - if (stats.Directories > options.Directories) + if (options?.Files is not null && (stats.Files + 1) > options.Files) { - reason = $"directories {stats.Directories} exceeds limit of {options.Directories}"; + reason = $"file would exceed limit of {options.Files}"; return true; } @@ -583,20 +571,18 @@ namespace slskd // start with the queue, since that should contain the fewest files and should be the least expensive to check // "queued" includes both queued and in progress; records with a null EndedAt property, which is guaranteed to be set // for terminal transfers. - var queued = Transfers.Uploads.Hypothesize( - expression: t => t.Username == username && t.EndedAt == null, - hypothetical: new Transfers.Transfer() - { - Filename = resolved.Filename, - Size = resolved.Size, - }); + if (!IsNull(limits.Queued)) + { + var queued = Transfers.Uploads.Summarize( + expression: t => t.Username == username && t.EndedAt == null); - Log.Debug("Fetched queue stats: {@Stats} ({Time}ms)", queued, sw.ElapsedMilliseconds); + Log.Debug("Fetched queue stats: files: {Files}, bytes: {Bytes} ({Time}ms)", queued.Files, queued.Bytes, sw.ElapsedMilliseconds); - if (OverLimits(queued, limits.Queued, out var queuedReason)) - { - Log.Information("Rejected enqueue request for user {Username}: Queued {Reason}", username, queuedReason); - throw new DownloadEnqueueException($"Queued {queuedReason}"); + if (OverLimits(queued, limits!.Queued, resolved.Size, out var queuedReason)) + { + Log.Information("Rejected enqueue request for user {Username}: Queued {Reason}", username, queuedReason); + throw new DownloadEnqueueException($"Queued {queuedReason}"); + } } //// start with weekly, as this is the most likely limit to be hit and we want to keep the work to a minimum -- cgit v1.2.3 From eb552e0d8118642f08289c239f02b08bd0bed735 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 17 Jan 2024 08:13:39 -0600 Subject: log sql --- src/slskd/Transfers/Uploads/UploadService.cs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 6f03526c..55b6b39a 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -458,7 +458,7 @@ namespace slskd.Transfers.Uploads { using var context = ContextFactory.CreateDbContext(); - var stats = context.Transfers + var query = context.Transfers .AsNoTracking() .Where(t => t.Direction == TransferDirection.Upload) .Where(expression) @@ -467,8 +467,11 @@ namespace slskd.Transfers.Uploads { Files = t.Count(), Bytes = t.Sum(x => x.Size), - }) - .FirstOrDefault(); + }); + + Log.Verbose("{Method} SQL: {@Query}", nameof(Summarize), query.ToQueryString()); + + var stats = query.FirstOrDefault(); return (stats?.Files ?? 0, stats?.Bytes ?? 0); } -- cgit v1.2.3 From d4edf6432ae7b4e8c46f0861a155e464f152b4c9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 17 Jan 2024 08:28:44 -0600 Subject: implement weekly limits --- src/slskd/Application.cs | 45 +++++++++++++++++++++++---------------------- 1 file changed, 23 insertions(+), 22 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index a065470d..a85cbff7 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -585,28 +585,29 @@ namespace slskd } } - //// start with weekly, as this is the most likely limit to be hit and we want to keep the work to a minimum - //var erroredState = TransferStates.Completed | TransferStates.Errored; - //var cutoffDateTime = DateTime.UtcNow.AddDays(-7); - //var weekly = Transfers.Uploads.Hypothesize( - // expression: t => - // t.Username == username - // && t.StartedAt >= cutoffDateTime - // && !t.State.HasFlag(erroredState) - // && t.Exception == null, - // hypothetical: new Transfers.Transfer() - // { - // Filename = resolved.Filename, - // Size = resolved.Size, - // }); - - //Log.Debug("Fetched weekly stats: {Stats} ({Time}ms)", weekly, sw.ElapsedMilliseconds); - - //if (OverLimits(weekly, limits.Weekly, out var weeklyReason)) - //{ - // Log.Information("Rejected enqueue request for user {Username}: Weekly {Reason}", weeklyReason); - // throw new DownloadEnqueueException($"Weekly {weeklyReason}"); - //} + // start with weekly, as this is the most likely limit to be hit and we want to keep the work to a minimum + // transfers that 'count' for the weekly limit are uploads that started within the last week, which have ended, + // that were not errored + if (!IsNull(limits.Weekly)) + { + var erroredState = TransferStates.Completed | TransferStates.Errored; + var cutoffDateTime = DateTime.UtcNow.AddDays(-7); + var weekly = Transfers.Uploads.Summarize( + expression: t => + t.Username == username + && t.StartedAt >= cutoffDateTime + && t.EndedAt != null + && !t.State.HasFlag(erroredState) + && t.Exception == null); + + Log.Debug("Fetched weekly stats: files: {Files}, bytes: {Bytes} ({Time}ms)", weekly.Files, weekly.Bytes, sw.ElapsedMilliseconds); + + if (OverLimits(weekly, limits!.Weekly, resolved.Size, out var weeklyReason)) + { + Log.Information("Rejected enqueue request for user {Username}: Weekly {Reason}", username, weeklyReason); + throw new DownloadEnqueueException($"Weekly {weeklyReason}"); + } + } //cutoffDateTime = DateTime.UtcNow.AddDays(-1); //var daily = Transfers.Uploads.Hypothesize( -- cgit v1.2.3 From 899d62a990db36492fc1ed7537faea578ef509a6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 17 Jan 2024 08:29:35 -0600 Subject: implement weekly --- src/slskd/Application.cs | 43 +++++++++++++++++++++++-------------------- 1 file changed, 23 insertions(+), 20 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index a85cbff7..4bbd03c7 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -484,6 +484,7 @@ namespace slskd } // in order to properly determine if the requested file would exceed any limits, we need to know the size of the file + // it helps, too, that this will tell us whether the file is even shared. (string Host, string Filename, long Size) resolved; try @@ -609,26 +610,28 @@ namespace slskd } } - //cutoffDateTime = DateTime.UtcNow.AddDays(-1); - //var daily = Transfers.Uploads.Hypothesize( - // expression: t => - // t.Username == username - // && t.StartedAt >= cutoffDateTime - // && !t.State.HasFlag(erroredState) - // && t.Exception == null, - // hypothetical: new Transfers.Transfer() - // { - // Filename = resolved.Filename, - // Size = resolved.Size, - // }); - - //Log.Debug("Fetched daily stats: {Stats} ({Time}ms)", weekly, sw.ElapsedMilliseconds); - - //if (OverLimits(daily, limits.Daily, out var dailyReason)) - //{ - // Log.Information("Rejected enqueue request for user {Username}: Daily {Reason}", dailyReason); - // throw new DownloadEnqueueException($"Daily {dailyReason}"); - //} + // lastly, check daily limits. the criteria for this is the same as weekly, just looking over the previous day instead + // of the previous 7. + if (!IsNull(limits.Daily)) + { + var erroredState = TransferStates.Completed | TransferStates.Errored; + var cutoffDateTime = DateTime.UtcNow.AddDays(-1); + var daily = Transfers.Uploads.Summarize( + expression: t => + t.Username == username + && t.StartedAt >= cutoffDateTime + && t.EndedAt != null + && !t.State.HasFlag(erroredState) + && t.Exception == null); + + Log.Debug("Fetched daily stats: files: {Files}, bytes: {Bytes} ({Time}ms)", daily.Files, daily.Bytes, sw.ElapsedMilliseconds); + + if (OverLimits(daily, limits!.Daily, resolved.Size, out var dailyReason)) + { + Log.Information("Rejected enqueue request for user {Username}: Daily {Reason}", username, dailyReason); + throw new DownloadEnqueueException($"Daily {dailyReason}"); + } + } sw.Stop(); Log.Debug("Enqueue decision made in {Duration}ms", sw.ElapsedMilliseconds); -- cgit v1.2.3 From 45f03de8d5fc1b97396062b6dc478ccce0d195e4 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 17 Jan 2024 09:09:54 -0600 Subject: tweak messages --- src/slskd/Application.cs | 41 ++++++++++++++++++++++++----------------- 1 file changed, 24 insertions(+), 17 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 4bbd03c7..a8e03823 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -534,7 +534,7 @@ namespace slskd // if no limits are set, we're good to go; just enqueue the file. if (limits is null || (IsNull(limits.Daily) && IsNull(limits.Weekly) && IsNull(limits.Queued))) { - Log.Debug("Limits bypassed for {Username} and {File}; limits are all null", username, filename); + Log.Debug("Limits bypassed for {Username} and {File}; no limits are set", username, filename); await Transfers.Uploads.EnqueueAsync(username, filename); return; } @@ -549,24 +549,25 @@ namespace slskd * 2) that were started within the time period * 3) that did not end due to an error (state includes errored, exception column is set) */ - bool OverLimits((int Files, long Bytes) stats, Options.GroupsOptions.LimitsExtendedOptions options, long size, out string reason) + (bool Files, bool Megabytes) OverLimits((int Files, long Bytes) stats, Options.GroupsOptions.LimitsExtendedOptions options, long size) { - reason = null; + var files = false; + var megabytes = false; var byteLimit = (options?.Megabytes ?? 0) * 1000 * 1000; if (options?.Megabytes is not null && (stats.Bytes + size) > byteLimit) { - reason = $"bytes {stats.Bytes + size} would exceed limit of {byteLimit}"; - return true; + Log.Debug("Projected bytes {Bytes} exceeds limit {Limit}", stats.Bytes + size, byteLimit); + megabytes = true; } if (options?.Files is not null && (stats.Files + 1) > options.Files) { - reason = $"file would exceed limit of {options.Files}"; - return true; + Log.Debug("Projected file count {Files} exceeds limit {Limit}", stats.Files + 1, options.Files); + files = true; } - return false; + return (files, megabytes); } // start with the queue, since that should contain the fewest files and should be the least expensive to check @@ -579,10 +580,12 @@ namespace slskd Log.Debug("Fetched queue stats: files: {Files}, bytes: {Bytes} ({Time}ms)", queued.Files, queued.Bytes, sw.ElapsedMilliseconds); - if (OverLimits(queued, limits!.Queued, resolved.Size, out var queuedReason)) + var over = OverLimits(queued, limits!.Queued, resolved.Size); + + if (over.Files || over.Megabytes) { - Log.Information("Rejected enqueue request for user {Username}: Queued {Reason}", username, queuedReason); - throw new DownloadEnqueueException($"Queued {queuedReason}"); + Log.Information("Rejected enqueue request for user {Username}: Queued limits exceeded", username); + throw new DownloadEnqueueException($"Too many queued {(over.Files ? "files" : "megabytes")}"); } } @@ -603,10 +606,12 @@ namespace slskd Log.Debug("Fetched weekly stats: files: {Files}, bytes: {Bytes} ({Time}ms)", weekly.Files, weekly.Bytes, sw.ElapsedMilliseconds); - if (OverLimits(weekly, limits!.Weekly, resolved.Size, out var weeklyReason)) + var over = OverLimits(weekly, limits!.Weekly, resolved.Size); + + if (over.Files || over.Megabytes) { - Log.Information("Rejected enqueue request for user {Username}: Weekly {Reason}", username, weeklyReason); - throw new DownloadEnqueueException($"Weekly {weeklyReason}"); + Log.Information("Rejected enqueue request for user {Username}: Weekly limits exceeded", username); + throw new DownloadEnqueueException($"Too many weekly {(over.Files ? "files" : "megabytes")}"); } } @@ -626,10 +631,12 @@ namespace slskd Log.Debug("Fetched daily stats: files: {Files}, bytes: {Bytes} ({Time}ms)", daily.Files, daily.Bytes, sw.ElapsedMilliseconds); - if (OverLimits(daily, limits!.Daily, resolved.Size, out var dailyReason)) + var over = OverLimits(daily, limits!.Daily, resolved.Size); + + if (over.Files || over.Megabytes) { - Log.Information("Rejected enqueue request for user {Username}: Daily {Reason}", username, dailyReason); - throw new DownloadEnqueueException($"Daily {dailyReason}"); + Log.Information("Rejected enqueue request for user {Username}: Daily limits exceeded", username); + throw new DownloadEnqueueException($"Too many daily {(over.Files ? "files" : "megabytes")}"); } } -- cgit v1.2.3 From 84acaed78564bed6c251de7b0d94bea43fecc7dc Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 18 Jan 2024 07:05:16 -0600 Subject: tweak messages, include queued in daily and weekly stats --- src/slskd/Application.cs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index a8e03823..70d726ab 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -585,13 +585,15 @@ namespace slskd if (over.Files || over.Megabytes) { Log.Information("Rejected enqueue request for user {Username}: Queued limits exceeded", username); - throw new DownloadEnqueueException($"Too many queued {(over.Files ? "files" : "megabytes")}"); + throw new DownloadEnqueueException($"Too many {(over.Files ? "files" : "megabytes")} queued"); } } // start with weekly, as this is the most likely limit to be hit and we want to keep the work to a minimum - // transfers that 'count' for the weekly limit are uploads that started within the last week, which have ended, - // that were not errored + // transfers that 'count' for the weekly limit are uploads that: + // * started within the last week + // * which have or have not ended (assuming queued files will complete) + // * that were not errored if (!IsNull(limits.Weekly)) { var erroredState = TransferStates.Completed | TransferStates.Errored; @@ -600,7 +602,6 @@ namespace slskd expression: t => t.Username == username && t.StartedAt >= cutoffDateTime - && t.EndedAt != null && !t.State.HasFlag(erroredState) && t.Exception == null); @@ -611,7 +612,7 @@ namespace slskd if (over.Files || over.Megabytes) { Log.Information("Rejected enqueue request for user {Username}: Weekly limits exceeded", username); - throw new DownloadEnqueueException($"Too many weekly {(over.Files ? "files" : "megabytes")}"); + throw new DownloadEnqueueException($"Too many {(over.Files ? "files" : "megabytes")} this week"); } } @@ -625,7 +626,6 @@ namespace slskd expression: t => t.Username == username && t.StartedAt >= cutoffDateTime - && t.EndedAt != null && !t.State.HasFlag(erroredState) && t.Exception == null); @@ -636,7 +636,7 @@ namespace slskd if (over.Files || over.Megabytes) { Log.Information("Rejected enqueue request for user {Username}: Daily limits exceeded", username); - throw new DownloadEnqueueException($"Too many daily {(over.Files ? "files" : "megabytes")}"); + throw new DownloadEnqueueException($"Too many {(over.Files ? "files" : "megabytes")} today"); } } -- cgit v1.2.3