From 854f3155f1d77907e77573ecfa7e836b0ae202ae Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 19 Feb 2022 13:07:24 -0600 Subject: fix spelling --- src/slskd/Application.cs | 4 ++-- src/slskd/Options.cs | 4 ++-- src/slskd/Transfers/Uploads/UploadGovernor.cs | 2 +- src/slskd/Transfers/Uploads/UploadQueue.cs | 8 ++++---- 4 files changed, 9 insertions(+), 9 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index b03f1abd..83f18a52 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -60,9 +60,9 @@ namespace slskd public static readonly string DefaultGroup = "default"; /// - /// The name of the priviledged user group. + /// The name of the privileged user group. /// - public static readonly string PriviledgedGroup = "priviledged"; + public static readonly string PrivilegedGroup = "privileged"; /// /// The name of the leecher user group. diff --git a/src/slskd/Options.cs b/src/slskd/Options.cs index 2313ce69..5bebeb68 100644 --- a/src/slskd/Options.cs +++ b/src/slskd/Options.cs @@ -467,7 +467,7 @@ namespace slskd /// Gets options for the default user group. /// /// - /// These options apply to users that are not priviledged, have not been identified as leechers, + /// These options apply to users that are not privileged, have not been identified as leechers, /// and have not been added as a member of any group. /// [Validate] @@ -495,7 +495,7 @@ namespace slskd /// public IEnumerable Validate(ValidationContext validationContext) { - var builtInGroups = new[] { Application.PriviledgedGroup, Application.DefaultGroup, Application.LeecherGroup }; + var builtInGroups = new[] { Application.PrivilegedGroup, Application.DefaultGroup, Application.LeecherGroup }; var intersection = UserDefined.Keys.Intersect(builtInGroups); return intersection.Select(group => new ValidationResult($"User defined group '{group}' collides with a built in group. Choose a different name.")); diff --git a/src/slskd/Transfers/Uploads/UploadGovernor.cs b/src/slskd/Transfers/Uploads/UploadGovernor.cs index 9221d686..a806815f 100644 --- a/src/slskd/Transfers/Uploads/UploadGovernor.cs +++ b/src/slskd/Transfers/Uploads/UploadGovernor.cs @@ -150,7 +150,7 @@ namespace slskd.Transfers // also, so transfers in progress will briefly exceed the intended speeds. var tokenBuckets = new Dictionary() { - { Application.PriviledgedGroup, CreateBucket(options.Global.Upload.SpeedLimit) }, + { Application.PrivilegedGroup, CreateBucket(options.Global.Upload.SpeedLimit) }, { Application.DefaultGroup, CreateBucket(options.Groups.Default.Upload.SpeedLimit) }, { Application.LeecherGroup, CreateBucket(options.Groups.Leechers.Upload.SpeedLimit) }, }; diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index 44aa8af4..e5b8c5f5 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -296,15 +296,15 @@ namespace slskd.Transfers { // the priority group is hard-coded with priority 0, slot count equivalent to the overall max, // and a FIFO strategy. all other groups have a minimum priority of 1 (enforced by options validation) - // to ensure that priviledged users always take priority, regardless of user configuration. - // the strategy is fixed to FIFO because that gives priviledged users the closest experience + // to ensure that privileged users always take priority, regardless of user configuration. + // the strategy is fixed to FIFO because that gives privileged users the closest experience // to the official client, as well as the appearance of fairness once the first upload begins. new Group() { - Name = Application.PriviledgedGroup, + Name = Application.PrivilegedGroup, Priority = 0, Slots = MaxSlots, - UsedSlots = GetExistingUsedSlotsOrDefault(Application.PriviledgedGroup), + UsedSlots = GetExistingUsedSlotsOrDefault(Application.PrivilegedGroup), Strategy = QueueStrategy.FirstInFirstOut, }, new Group() -- cgit v1.2.3 From 50b22754dc63a993d1b7e7cbfc6809d39a8935c4 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 19 Feb 2022 14:32:56 -0600 Subject: cache user privileges --- src/slskd/Users/IUserService.cs | 2 +- src/slskd/Users/UserService.cs | 46 ++++++++++++++++++++++++++++++++++++++--- 2 files changed, 44 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Users/IUserService.cs b/src/slskd/Users/IUserService.cs index ad368c65..b1e98a19 100644 --- a/src/slskd/Users/IUserService.cs +++ b/src/slskd/Users/IUserService.cs @@ -30,7 +30,7 @@ namespace slskd.Users /// /// The username of the peer. /// The group for the specified username. - string GetGroup(string username); + Task GetGroupAsync(string username); /// /// Retrieves peer . diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index cb56e6dd..8de2abea 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -24,8 +24,10 @@ namespace slskd.Users using System.Collections.Generic; using System.Linq; using System.Net; + using System.Threading; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; + using Microsoft.Extensions.Caching.Memory; using Serilog; using Soulseek; @@ -48,6 +50,15 @@ namespace slskd.Users IOptionsMonitor optionsMonitor) { Client = soulseekClient; + Client.PrivilegedUserListReceived += (_, usernames) => + { + foreach (var username in usernames) + { + CachePrivilegedUser(username, privileged: true); + } + }; + Client.PrivilegeNotificationReceived += (_, e) => CachePrivilegedUser(e.Username, privileged: true); + ContextFactory = contextFactory; OptionsMonitor = optionsMonitor; @@ -61,6 +72,7 @@ namespace slskd.Users private string LastOptionsHash { get; set; } private ILogger Log { get; set; } = Serilog.Log.ForContext(); private ConcurrentDictionary Map { get; set; } = new ConcurrentDictionary(); + private IMemoryCache PrivilegedUserCache { get; set; } = new MemoryCache(new MemoryCacheOptions()); private IOptionsMonitor OptionsMonitor { get; } /// @@ -68,8 +80,16 @@ namespace slskd.Users /// /// The username of the peer. /// The group for the specified username. - public string GetGroup(string username) + public async Task GetGroupAsync(string username) { + if (await IsPrivilegedAsync(username)) + { + Console.WriteLine($"{username} is privileged"); + return Application.PrivilegedGroup; + } + + Console.WriteLine($"{username} is not privileged"); + return Map.GetValueOrDefault(username ?? string.Empty, Application.DefaultGroup); } @@ -144,8 +164,19 @@ namespace slskd.Users /// /// The username of the peer. /// A value indicating whether the specified peer is privileged. - public Task IsPrivilegedAsync(string username) - => Client.GetUserPrivilegedAsync(username); + public async Task IsPrivilegedAsync(string username) + { + if (PrivilegedUserCache.TryGetValue(username, out var cachedValue)) + { + return (bool)cachedValue; + } + + var privileged = await Client.GetUserPrivilegedAsync(username); + + CachePrivilegedUser(username, privileged: privileged); + + return privileged; + } /// /// Adds the specified username to the server-side user list. @@ -157,6 +188,15 @@ namespace slskd.Users await Client.AddUserAsync(username); } + private void CachePrivilegedUser(string username, bool privileged = true) + { + _ = PrivilegedUserCache.GetOrCreate(username, entry => + { + entry.AbsoluteExpiration = DateTimeOffset.Now.AddHours(24); + return privileged; + }); + } + private void Configure(Options options) { var optionsHash = Compute.Sha1Hash(options.Groups.UserDefined.ToJson()); -- cgit v1.2.3 From 136204584f16c5abc5e8dede8b68e1c162d2febc Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 19 Feb 2022 16:52:02 -0600 Subject: check user privileges prior to upload --- src/slskd/Application.cs | 11 +++++++++++ 1 file changed, 11 insertions(+) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 83f18a52..840ed1ba 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -82,6 +82,7 @@ namespace slskd IConversationTracker conversationTracker, IRoomTracker roomTracker, IRoomService roomService, + IUserService userService, ISharedFileCache sharedFileCache, IPushbulletService pushbulletService, IHubContext applicationHub, @@ -107,6 +108,7 @@ namespace slskd Pushbullet = pushbulletService; RoomService = roomService; + Users = userService; ApplicationHub = applicationHub; LogHub = logHub; @@ -157,6 +159,7 @@ namespace slskd private ITransferService Transfers { get; init; } private IHubContext ApplicationHub { get; set; } private IHubContext LogHub { get; set; } + private IUserService Users { get; set; } public void CollectGarbage() { @@ -587,6 +590,14 @@ namespace slskd // uploads would be handled separately. Task.Run(async () => { + // prime the privileges cache for this user + // this must be done prior to each upload, or we risk not correctly categorizing + // privileged users as such. + if (await Users.IsPrivilegedAsync(username)) + { + Log.Debug("User {Username} is privileged; upload will be prioritized", username); + } + using var stream = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read); await Client.UploadAsync(username, filename, fileInfo.FullName, options: topts, cancellationToken: cts.Token); }).ContinueWith(t => -- cgit v1.2.3 From de185440272729fc726d8ca26a6030a683365582 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 19 Feb 2022 16:53:01 -0600 Subject: periodically refresh privileges for users in the queue --- src/slskd/Transfers/Uploads/UploadQueue.cs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index e5b8c5f5..80f5b6e7 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -75,6 +75,20 @@ namespace slskd.Transfers OptionsMonitor.OnChange(Configure); Configure(OptionsMonitor.CurrentValue); + + // periodically check the privileged status of users with uploads in the queue + // privileges are cached for 24 hours; forcing an update every 4 hours ensures we always + // have a relatively fresh value available. the server won't tell us when users gain + // or lose privileged status, so we want to be fairly up to date. + PrivilegeWatchdog = new System.Timers.Timer(TimeSpan.FromHours(4).TotalMilliseconds); + PrivilegeWatchdog.Elapsed += (sender, e) => + { + foreach (var username in Uploads.Keys.ToList()) + { + _ = Users.IsPrivilegedAsync(username, bypassCache: true); + } + }; + PrivilegeWatchdog.Start(); } private ILogger Log { get; } = Serilog.Log.ForContext(); @@ -86,6 +100,7 @@ namespace slskd.Transfers private int MaxSlots { get; set; } = 0; private Dictionary Groups { get; set; } = new Dictionary(); private ConcurrentDictionary> Uploads { get; set; } = new ConcurrentDictionary>(); + private System.Timers.Timer PrivilegeWatchdog { get; set; } /// /// Enqueues an upload. -- cgit v1.2.3 From 9afffed3a7a95c875d4b40b472c8403c98948a26 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 19 Feb 2022 16:54:11 -0600 Subject: cache privileges --- src/slskd/Users/IUserService.cs | 5 ++-- src/slskd/Users/UserService.cs | 59 ++++++++++++++++++++++++++--------------- 2 files changed, 41 insertions(+), 23 deletions(-) (limited to 'src') diff --git a/src/slskd/Users/IUserService.cs b/src/slskd/Users/IUserService.cs index b1e98a19..f7a03a33 100644 --- a/src/slskd/Users/IUserService.cs +++ b/src/slskd/Users/IUserService.cs @@ -30,7 +30,7 @@ namespace slskd.Users /// /// The username of the peer. /// The group for the specified username. - Task GetGroupAsync(string username); + string GetGroup(string username); /// /// Retrieves peer . @@ -66,8 +66,9 @@ namespace slskd.Users /// Retrieves a value indicating whether the specified peer is privileged. /// /// The username of the peer. + /// A value indicating whether to bypass the cache and query the server. /// A value indicating whether the specified peer is privileged. - Task IsPrivilegedAsync(string username); + Task IsPrivilegedAsync(string username, bool bypassCache = false); /// /// 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 8de2abea..7db1f25f 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -24,7 +24,6 @@ namespace slskd.Users using System.Collections.Generic; using System.Linq; using System.Net; - using System.Threading; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Caching.Memory; @@ -57,7 +56,15 @@ namespace slskd.Users CachePrivilegedUser(username, privileged: true); } }; - Client.PrivilegeNotificationReceived += (_, e) => CachePrivilegedUser(e.Username, privileged: true); + Client.PrivilegeNotificationReceived += (_, e) => + { + // note: in testing i wasn't able to get this to fire by gifting privileges + // to other users. it isn't harming anything so i'll leave it, but this most + // likely means that the initial list we get at login is all the information + // the server is going to offer unsolicited. + CachePrivilegedUser(e.Username, privileged: true); + }; + Client.Disconnected += (_, _) => ResetPrivilegedUserCache(); ContextFactory = contextFactory; @@ -65,14 +72,15 @@ namespace slskd.Users OptionsMonitor.OnChange(Configure); Configure(OptionsMonitor.CurrentValue); + ResetPrivilegedUserCache(); } private ISoulseekClient Client { get; } private IDbContextFactory ContextFactory { get; } private string LastOptionsHash { get; set; } private ILogger Log { get; set; } = Serilog.Log.ForContext(); - private ConcurrentDictionary Map { get; set; } = new ConcurrentDictionary(); - private IMemoryCache PrivilegedUserCache { get; set; } = new MemoryCache(new MemoryCacheOptions()); + private ConcurrentDictionary UserGroupMap { get; set; } = new ConcurrentDictionary(); + private IMemoryCache PrivilegedUserCache { get; set; } private IOptionsMonitor OptionsMonitor { get; } /// @@ -80,17 +88,19 @@ namespace slskd.Users /// /// The username of the peer. /// The group for the specified username. - public async Task GetGroupAsync(string username) + public string GetGroup(string username) { - if (await IsPrivilegedAsync(username)) + // this is a hot path used for upload speed governance and upload orchestration. as such, + // check the cache synchronously, instead of looking for stale values and re-querying the server. + // consumers of this method are responsible for invoking IsPrivilegedAsync with the bypassCache flag + // set to true at least every 12 hours for any usernames that need to be actively tracked in order to + // keep this cache warm. + if (PrivilegedUserCache.TryGetValue(username, out var privileged) && (bool)privileged) { - Console.WriteLine($"{username} is privileged"); return Application.PrivilegedGroup; } - Console.WriteLine($"{username} is not privileged"); - - return Map.GetValueOrDefault(username ?? string.Empty, Application.DefaultGroup); + return UserGroupMap.GetValueOrDefault(username ?? string.Empty, Application.DefaultGroup); } /// @@ -163,14 +173,24 @@ namespace slskd.Users /// Retrieves a value indicating whether the specified peer is privileged. /// /// The username of the peer. + /// A value indicating whether to bypass the cache and query the server. /// A value indicating whether the specified peer is privileged. - public async Task IsPrivilegedAsync(string username) + public async Task IsPrivilegedAsync(string username, bool bypassCache = false) { - if (PrivilegedUserCache.TryGetValue(username, out var cachedValue)) + if (!bypassCache) { - return (bool)cachedValue; + if (PrivilegedUserCache.TryGetValue(username, out var cachedValue)) + { + Log.Debug("Cache HIT for user {Username} privileges (privileged: {Privileged})", username, cachedValue); + return (bool)cachedValue; + } + else + { + Log.Debug("Cache MISS for user {Username} privileges"); + } } + Log.Debug("Checking privileged status for user {Username}", username); var privileged = await Client.GetUserPrivilegedAsync(username); CachePrivilegedUser(username, privileged: privileged); @@ -189,13 +209,10 @@ namespace slskd.Users } private void CachePrivilegedUser(string username, bool privileged = true) - { - _ = PrivilegedUserCache.GetOrCreate(username, entry => - { - entry.AbsoluteExpiration = DateTimeOffset.Now.AddHours(24); - return privileged; - }); - } + => PrivilegedUserCache.Set(username, privileged, new MemoryCacheEntryOptions() { AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(24) }); + + private void ResetPrivilegedUserCache() + => PrivilegedUserCache = new MemoryCache(new MemoryCacheOptions()); private void Configure(Options options) { @@ -219,7 +236,7 @@ namespace slskd.Users } } - Map = map; + UserGroupMap = map; LastOptionsHash = optionsHash; } } -- cgit v1.2.3 From eda8be06134387537bb89c350cd3a68612fd6758 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 21 Feb 2022 15:04:29 -0600 Subject: don't use a timer to check privileges --- src/slskd/Transfers/Uploads/UploadQueue.cs | 15 --------------- 1 file changed, 15 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index 80f5b6e7..e5b8c5f5 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -75,20 +75,6 @@ namespace slskd.Transfers OptionsMonitor.OnChange(Configure); Configure(OptionsMonitor.CurrentValue); - - // periodically check the privileged status of users with uploads in the queue - // privileges are cached for 24 hours; forcing an update every 4 hours ensures we always - // have a relatively fresh value available. the server won't tell us when users gain - // or lose privileged status, so we want to be fairly up to date. - PrivilegeWatchdog = new System.Timers.Timer(TimeSpan.FromHours(4).TotalMilliseconds); - PrivilegeWatchdog.Elapsed += (sender, e) => - { - foreach (var username in Uploads.Keys.ToList()) - { - _ = Users.IsPrivilegedAsync(username, bypassCache: true); - } - }; - PrivilegeWatchdog.Start(); } private ILogger Log { get; } = Serilog.Log.ForContext(); @@ -100,7 +86,6 @@ namespace slskd.Transfers private int MaxSlots { get; set; } = 0; private Dictionary Groups { get; set; } = new Dictionary(); private ConcurrentDictionary> Uploads { get; set; } = new ConcurrentDictionary>(); - private System.Timers.Timer PrivilegeWatchdog { get; set; } /// /// Enqueues an upload. -- cgit v1.2.3 From 4318b7bc5b83f744eab45ce43d7dd2e2e6aa07ed Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 21 Feb 2022 15:04:45 -0600 Subject: add User and Statistics types --- src/slskd/Users/Domain/Statistics.cs | 55 ++++++++++++++++++++++++++++++++++++ src/slskd/Users/Domain/User.cs | 27 ++++++++++++++++++ 2 files changed, 82 insertions(+) create mode 100644 src/slskd/Users/Domain/Statistics.cs create mode 100644 src/slskd/Users/Domain/User.cs (limited to 'src') diff --git a/src/slskd/Users/Domain/Statistics.cs b/src/slskd/Users/Domain/Statistics.cs new file mode 100644 index 00000000..8dbcaaef --- /dev/null +++ b/src/slskd/Users/Domain/Statistics.cs @@ -0,0 +1,55 @@ +// +// 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.Users +{ + using Soulseek; + + public class Statistics + { + /// + /// Gets the average upload speed of the user. + /// + public int AverageSpeed { get; init; } + + /// + /// Gets the number of directories shared by the user. + /// + public int DirectoryCount { get; init; } + + /// + /// Gets the number of files shared by the user. + /// + public int FileCount { get; init; } + + /// + /// Gets the number of uploads tracked by the server for this user. + /// + public long UploadCount { get; init; } + + public static Statistics FromSoulseekUserStatistics(UserStatistics statistics) + { + return new Statistics() + { + AverageSpeed = statistics.AverageSpeed, + DirectoryCount = statistics.DirectoryCount, + FileCount = statistics.FileCount, + UploadCount = statistics.UploadCount, + }; + } + } +} diff --git a/src/slskd/Users/Domain/User.cs b/src/slskd/Users/Domain/User.cs new file mode 100644 index 00000000..cbf49eea --- /dev/null +++ b/src/slskd/Users/Domain/User.cs @@ -0,0 +1,27 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +namespace slskd.Users +{ + public record User + { + public string Username { get; init; } + public string Group { get; init; } + public Statistics Statistics { get; init; } + public Status Status { get; init; } + } +} -- cgit v1.2.3 From 4ac1a5207967d5fd34a91cd257a60401df696706 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 21 Feb 2022 15:04:57 -0600 Subject: add User list to state --- src/slskd/State.cs | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src') diff --git a/src/slskd/State.cs b/src/slskd/State.cs index 4c3deff8..bd82f8d7 100644 --- a/src/slskd/State.cs +++ b/src/slskd/State.cs @@ -20,6 +20,7 @@ namespace slskd using System; using System.Net; using System.Text.Json.Serialization; + using slskd.Users; using Soulseek; /// @@ -34,6 +35,7 @@ namespace slskd public ServerState Server { get; init; } = new ServerState(); public SharedFileCacheState SharedFileCache { get; init; } = new SharedFileCacheState(); public string[] Rooms { get; init; } = Array.Empty(); + public User[] Users { get; init; } = Array.Empty(); } public record VersionState -- cgit v1.2.3 From d3f4c1d58101b0288c3caa70b3114e0da599daf9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 21 Feb 2022 15:05:19 -0600 Subject: expose Users, remove bypassCache flag --- src/slskd/Users/IUserService.cs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Users/IUserService.cs b/src/slskd/Users/IUserService.cs index f7a03a33..3c716116 100644 --- a/src/slskd/Users/IUserService.cs +++ b/src/slskd/Users/IUserService.cs @@ -17,6 +17,7 @@ namespace slskd.Users { + using System.Collections.Generic; using System.Net; using System.Threading.Tasks; @@ -25,6 +26,11 @@ namespace slskd.Users /// public interface IUserService { + /// + /// Gets the list of tracked users. + /// + IReadOnlyList Users { get; } + /// /// Gets the name of the group for the specified . /// @@ -66,9 +72,8 @@ namespace slskd.Users /// Retrieves a value indicating whether the specified peer is privileged. /// /// The username of the peer. - /// A value indicating whether to bypass the cache and query the server. /// A value indicating whether the specified peer is privileged. - Task IsPrivilegedAsync(string username, bool bypassCache = false); + Task IsPrivilegedAsync(string username); /// /// Adds the specified username to the server-side user list. -- cgit v1.2.3 From 78de996773715bcd5ade7e6176bf29913d1df03e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 21 Feb 2022 15:06:43 -0600 Subject: watch users prior to uploads --- src/slskd/Application.cs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 840ed1ba..47bcd6c9 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -590,12 +590,12 @@ namespace slskd // uploads would be handled separately. Task.Run(async () => { - // prime the privileges cache for this user - // this must be done prior to each upload, or we risk not correctly categorizing - // privileged users as such. - if (await Users.IsPrivilegedAsync(username)) + // users with uploads must be watched so that we can keep informed of their + // online status, privileges, and statistics. this is so that we can accurately + // determine their effective group. + if (Users.Users.Any(u => u.Username == username)) { - Log.Debug("User {Username} is privileged; upload will be prioritized", username); + await Users.WatchAsync(username); } using var stream = new FileStream(fileInfo.FullName, FileMode.Open, FileAccess.Read); @@ -857,7 +857,7 @@ namespace slskd private void State_OnChange((State Previous, State Current) state) { - Log.Debug("State changed from {Previous} to {Current}", state.Previous.ToJson(), state.Current.ToJson()); + //Log.Debug("State changed from {Previous} to {Current}", state.Previous.ToJson(), state.Current.ToJson()); _ = ApplicationHub.BroadcastStateAsync(state.Current); } -- cgit v1.2.3 From fe71947b9dc9f95422a0660421511f9f0e6154a1 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 21 Feb 2022 15:07:20 -0600 Subject: track watched users internally --- src/slskd/Users/UserService.cs | 183 +++++++++++++++++++++++++++-------------- 1 file changed, 121 insertions(+), 62 deletions(-) (limited to 'src') diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index 7db1f25f..7532e2a7 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -26,7 +26,6 @@ namespace slskd.Users using System.Net; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; - using Microsoft.Extensions.Caching.Memory; using Serilog; using Soulseek; @@ -41,46 +40,39 @@ namespace slskd.Users /// Initializes a new instance of the class. /// /// + /// /// The database context to use. /// public UserService( ISoulseekClient soulseekClient, + IStateMutator stateMutator, IDbContextFactory contextFactory, IOptionsMonitor optionsMonitor) { Client = soulseekClient; - Client.PrivilegedUserListReceived += (_, usernames) => - { - foreach (var username in usernames) - { - CachePrivilegedUser(username, privileged: true); - } - }; - Client.PrivilegeNotificationReceived += (_, e) => - { - // note: in testing i wasn't able to get this to fire by gifting privileges - // to other users. it isn't harming anything so i'll leave it, but this most - // likely means that the initial list we get at login is all the information - // the server is going to offer unsolicited. - CachePrivilegedUser(e.Username, privileged: true); - }; - Client.Disconnected += (_, _) => ResetPrivilegedUserCache(); + + StateMutator = stateMutator; ContextFactory = contextFactory; OptionsMonitor = optionsMonitor; OptionsMonitor.OnChange(Configure); + BindClientEvents(); Configure(OptionsMonitor.CurrentValue); - ResetPrivilegedUserCache(); } + /// + /// Gets the list of tracked users. + /// + public IReadOnlyList Users => UserDictionary.Values.ToList().AsReadOnly(); + private ISoulseekClient Client { get; } + private IStateMutator StateMutator { get; } private IDbContextFactory ContextFactory { get; } private string LastOptionsHash { get; set; } private ILogger Log { get; set; } = Serilog.Log.ForContext(); - private ConcurrentDictionary UserGroupMap { get; set; } = new ConcurrentDictionary(); - private IMemoryCache PrivilegedUserCache { get; set; } + private ConcurrentDictionary UserDictionary { get; set; } = new ConcurrentDictionary(); private IOptionsMonitor OptionsMonitor { get; } /// @@ -90,17 +82,13 @@ namespace slskd.Users /// The group for the specified username. public string GetGroup(string username) { - // this is a hot path used for upload speed governance and upload orchestration. as such, - // check the cache synchronously, instead of looking for stale values and re-querying the server. - // consumers of this method are responsible for invoking IsPrivilegedAsync with the bypassCache flag - // set to true at least every 12 hours for any usernames that need to be actively tracked in order to - // keep this cache warm. - if (PrivilegedUserCache.TryGetValue(username, out var privileged) && (bool)privileged) + // note: this is an extremely hot path; keep the work done to an absolute minimum. + if (UserDictionary.TryGetValue(username ?? string.Empty, out var user)) { - return Application.PrivilegedGroup; + return user.Group ?? Application.DefaultGroup; } - return UserGroupMap.GetValueOrDefault(username ?? string.Empty, Application.DefaultGroup); + return Application.DefaultGroup; } /// @@ -156,8 +144,36 @@ namespace slskd.Users public async Task GetStatusAsync(string username) { var soulseekStatus = await Client.GetUserStatusAsync(username); + var status = Status.FromSoulseekUserStatus(soulseekStatus); + + 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() }); + + return status; + } - return Status.FromSoulseekUserStatus(soulseekStatus); + /// + /// Retrieves the current of a peer. + /// + /// The username of the peer. + /// The retrieved statistics. + public async Task GetStatisticsAsync(string username) + { + var soulseekStatistics = await Client.GetUserStatisticsAsync(username); + var statistics = Statistics.FromSoulseekUserStatistics(soulseekStatistics); + + 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() }); + + return statistics; } /// @@ -173,29 +189,11 @@ namespace slskd.Users /// Retrieves a value indicating whether the specified peer is privileged. /// /// The username of the peer. - /// A value indicating whether to bypass the cache and query the server. /// A value indicating whether the specified peer is privileged. - public async Task IsPrivilegedAsync(string username, bool bypassCache = false) + public async Task IsPrivilegedAsync(string username) { - if (!bypassCache) - { - if (PrivilegedUserCache.TryGetValue(username, out var cachedValue)) - { - Log.Debug("Cache HIT for user {Username} privileges (privileged: {Privileged})", username, cachedValue); - return (bool)cachedValue; - } - else - { - Log.Debug("Cache MISS for user {Username} privileges"); - } - } - - Log.Debug("Checking privileged status for user {Username}", username); - var privileged = await Client.GetUserPrivilegedAsync(username); - - CachePrivilegedUser(username, privileged: privileged); - - return privileged; + var status = await GetStatusAsync(username); + return status.IsPrivileged; } /// @@ -206,13 +204,47 @@ namespace slskd.Users public async Task WatchAsync(string username) { await Client.AddUserAsync(username); + await GetStatusAsync(username); + + UserDictionary.TryAdd(username, new User()); + StateMutator.SetValue(state => state with { Users = Users.ToArray() }); + Log.Information("Added user {Username} to watch list", username); } - private void CachePrivilegedUser(string username, bool privileged = true) - => PrivilegedUserCache.Set(username, privileged, new MemoryCacheEntryOptions() { AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(24) }); + private void BindClientEvents() + { + Client.UserStatisticsChanged += (_, e) => + { + var statistics = Statistics.FromSoulseekUserStatistics(e); + + UserDictionary.AddOrUpdate( + key: e.Username, + addValue: new User() { Statistics = statistics }, + updateValueFactory: (key, user) => user with { Username = e.Username, Statistics = statistics }); + + StateMutator.SetValue(state => state with { Users = Users.ToArray() }); + }; + + Client.UserStatusChanged += (_, e) => + { + var status = Status.FromSoulseekUserStatus(e); + + Console.WriteLine(e.ToJson()); + + UserDictionary.AddOrUpdate( + key: e.Username, + addValue: new User() { Status = status }, + updateValueFactory: (key, user) => user with { Username = e.Username, Status = status }); + + StateMutator.SetValue(state => state with { Users = Users.ToArray() }); + + // the server doesn't send statistics events by itself, so + // when a user status changes, fetch stats at the same time. + _ = GetStatisticsAsync(e.Username); + }; - private void ResetPrivilegedUserCache() - => PrivilegedUserCache = new MemoryCache(new MemoryCacheOptions()); + Client.LoggedIn += (_, _) => WatchAllUsers(); + } private void Configure(Options options) { @@ -223,21 +255,48 @@ namespace slskd.Users return; } - var map = new ConcurrentDictionary(); + var usernamesBeforeUpdate = UserDictionary.Keys.ToList(); + var usernamesAfterUpdate = options.Groups.UserDefined.SelectMany(g => g.Value.Members); + var usernamesRemoved = usernamesBeforeUpdate.Except(usernamesAfterUpdate); - // sort by priority, ascending - foreach (var group in options.Groups.UserDefined.OrderBy(kvp => kvp.Value.Upload.Priority)) + foreach (var username in usernamesRemoved) { - foreach (var user in group.Value.Members) + UserDictionary.AddOrUpdate( + key: username, + addValue: new User() { Username = username }, + updateValueFactory: (key, user) => user with { Username = username, Group = null }); + } + + // sort by priority, descending. this will cause the highest priority group for the user + // to be persisted when the operation is complete. + foreach (var group in options.Groups.UserDefined.OrderByDescending(kvp => kvp.Value.Upload.Priority)) + { + foreach (var username in group.Value.Members) { - // if the key already exists, leave the existing entry. if a user appears in more than one group, the higher - // priority (lower numbered) group is their effective group. - map.TryAdd(user, group.Key); + UserDictionary.AddOrUpdate( + key: username, + addValue: new User() { Username = username, Group = group.Key }, + updateValueFactory: (key, user) => user with { Username = username, Group = group.Key }); } } - UserGroupMap = map; + Console.WriteLine($"Updating user state: {Users.ToArray().ToJson()}"); + StateMutator.SetValue(state => state with { Users = Users.ToArray() }); + + WatchAllUsers(); + LastOptionsHash = optionsHash; } + + private void WatchAllUsers() + { + if (Client.State.HasFlag(SoulseekClientStates.Connected) && Client.State.HasFlag(SoulseekClientStates.LoggedIn)) + { + foreach (var username in UserDictionary.Keys.ToList()) + { + _ = WatchAsync(username); + } + } + } } } \ No newline at end of file -- cgit v1.2.3 From 979acc196f01bf53bf0141cf80f684172433d472 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 22 Feb 2022 09:39:23 -0600 Subject: track and expose watched usernames --- src/slskd/Application.cs | 2 +- src/slskd/Users/IUserService.cs | 12 ++++++ src/slskd/Users/UserService.cs | 93 ++++++++++++++++++++++------------------- 3 files changed, 64 insertions(+), 43 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 47bcd6c9..56d17808 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -593,7 +593,7 @@ namespace slskd // users with uploads must be watched so that we can keep informed of their // online status, privileges, and statistics. this is so that we can accurately // determine their effective group. - if (Users.Users.Any(u => u.Username == username)) + if (!Users.IsWatched(username)) { await Users.WatchAsync(username); } diff --git a/src/slskd/Users/IUserService.cs b/src/slskd/Users/IUserService.cs index 3c716116..e78b1b1c 100644 --- a/src/slskd/Users/IUserService.cs +++ b/src/slskd/Users/IUserService.cs @@ -31,6 +31,11 @@ namespace slskd.Users /// IReadOnlyList Users { get; } + /// + /// Gets the list of watched usernames. + /// + IReadOnlyList WatchedUsernames { get; } + /// /// Gets the name of the group for the specified . /// @@ -75,6 +80,13 @@ namespace slskd.Users /// A value indicating whether the specified peer is privileged. Task IsPrivilegedAsync(string username); + /// + /// Gets a value indicating whether the specified is watched. + /// + /// The username of the peer. + /// A value indicating whether the username is watched. + bool IsWatched(string username); + /// /// 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 7532e2a7..39647e0a 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -67,13 +67,19 @@ namespace slskd.Users /// public IReadOnlyList Users => UserDictionary.Values.ToList().AsReadOnly(); + /// + /// Gets the list of watched usernames. + /// + public IReadOnlyList WatchedUsernames => WatchedUsernamesDictionary.Keys.ToList().AsReadOnly(); + private ISoulseekClient Client { get; } - private IStateMutator StateMutator { get; } private IDbContextFactory ContextFactory { get; } private string LastOptionsHash { get; set; } private ILogger Log { get; set; } = Serilog.Log.ForContext(); - private ConcurrentDictionary UserDictionary { get; set; } = new ConcurrentDictionary(); private IOptionsMonitor OptionsMonitor { get; } + private IStateMutator StateMutator { get; } + private ConcurrentDictionary UserDictionary { get; set; } = new ConcurrentDictionary(); + private ConcurrentDictionary WatchedUsernamesDictionary { get; set; } = new ConcurrentDictionary(); /// /// Gets the name of the group for the specified . @@ -85,6 +91,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 (user.Status?.IsPrivileged ?? false) + { + return Application.PrivilegedGroup; + } + return user.Group ?? Application.DefaultGroup; } @@ -137,43 +148,25 @@ namespace slskd.Users } /// - /// Retrieves the current of a peer. + /// Retrieves the current of a peer. /// /// The username of the peer. - /// The retrieved status. - public async Task GetStatusAsync(string username) + /// The retrieved statistics. + public async Task GetStatisticsAsync(string username) { - var soulseekStatus = await Client.GetUserStatusAsync(username); - var status = Status.FromSoulseekUserStatus(soulseekStatus); - - 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() }); - - return status; + var soulseekStatistics = await Client.GetUserStatisticsAsync(username); + return Statistics.FromSoulseekUserStatistics(soulseekStatistics); } /// - /// Retrieves the current of a peer. + /// Retrieves the current of a peer. /// /// The username of the peer. - /// The retrieved statistics. - public async Task GetStatisticsAsync(string username) + /// The retrieved status. + public async Task GetStatusAsync(string username) { - var soulseekStatistics = await Client.GetUserStatisticsAsync(username); - var statistics = Statistics.FromSoulseekUserStatistics(soulseekStatistics); - - 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() }); - - return statistics; + var soulseekStatus = await Client.GetUserStatusAsync(username); + return Status.FromSoulseekUserStatus(soulseekStatus); } /// @@ -196,6 +189,13 @@ namespace slskd.Users return status.IsPrivileged; } + /// + /// Gets a value indicating whether the specified is watched. + /// + /// The username of the peer. + /// A value indicating whether the username is watched. + public bool IsWatched(string username) => WatchedUsernamesDictionary.ContainsKey(username); + /// /// Adds the specified username to the server-side user list. /// @@ -203,16 +203,26 @@ namespace slskd.Users /// The operation context. public async Task WatchAsync(string username) { - await Client.AddUserAsync(username); - await GetStatusAsync(username); + // note that this isn't strictly synchronized, and this may be executed more than once per user. this is acceptable, + // and has no side effects other than increased round trips to the server. + if (!WatchedUsernamesDictionary.ContainsKey(username)) + { + await Client.AddUserAsync(username); + WatchedUsernamesDictionary.TryAdd(username, true); - UserDictionary.TryAdd(username, new User()); - StateMutator.SetValue(state => state with { Users = Users.ToArray() }); - Log.Information("Added user {Username} to watch list", username); + Log.Information("Added user {Username} to watch list", username); + + // the server does not send a status update when a user is added, but does when that user's status changes. + // request the status explicitly to get the current status. + await GetStatusAsync(username); + } } private void BindClientEvents() { + // it isn't completely clear what all causes the server to send this message. we know it is sent following an explicit + // request, but it may be sent in an unsolicited manner as well. to be safe, we update internal stats for this user + // only on this event, which should cover all bases (both solicited and unsolicited). Client.UserStatisticsChanged += (_, e) => { var statistics = Statistics.FromSoulseekUserStatistics(e); @@ -225,12 +235,12 @@ namespace slskd.Users StateMutator.SetValue(state => state with { Users = Users.ToArray() }); }; + // the server sends this message in both solicited (we request status), and unsolicited (the user's status changes and + // the server informs us without asking). we handle updates in this event handler to cover both cases. Client.UserStatusChanged += (_, e) => { var status = Status.FromSoulseekUserStatus(e); - Console.WriteLine(e.ToJson()); - UserDictionary.AddOrUpdate( key: e.Username, addValue: new User() { Status = status }, @@ -238,12 +248,12 @@ namespace slskd.Users StateMutator.SetValue(state => state with { Users = Users.ToArray() }); - // the server doesn't send statistics events by itself, so - // when a user status changes, fetch stats at the same time. + // the server doesn't send statistics events by itself, so when a user status changes, fetch stats at the same time. _ = GetStatisticsAsync(e.Username); }; Client.LoggedIn += (_, _) => WatchAllUsers(); + Client.Disconnected += (_, _) => WatchedUsernamesDictionary.Clear(); } private void Configure(Options options) @@ -267,8 +277,8 @@ namespace slskd.Users updateValueFactory: (key, user) => user with { Username = username, Group = null }); } - // sort by priority, descending. this will cause the highest priority group for the user - // to be persisted when the operation is complete. + // sort by priority, descending. this will cause the highest priority group for the user to be persisted when the + // operation is complete. foreach (var group in options.Groups.UserDefined.OrderByDescending(kvp => kvp.Value.Upload.Priority)) { foreach (var username in group.Value.Members) @@ -280,7 +290,6 @@ namespace slskd.Users } } - Console.WriteLine($"Updating user state: {Users.ToArray().ToJson()}"); StateMutator.SetValue(state => state with { Users = Users.ToArray() }); WatchAllUsers(); -- cgit v1.2.3 From ec21875fb748bc91b4df85ea62c4813815e25b4a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 22 Feb 2022 21:26:27 -0600 Subject: purge transient users on disconnect --- src/slskd/Users/UserService.cs | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index 39647e0a..4e252f40 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -253,7 +253,21 @@ namespace slskd.Users }; Client.LoggedIn += (_, _) => WatchAllUsers(); - Client.Disconnected += (_, _) => WatchedUsernamesDictionary.Clear(); + Client.Disconnected += (_, _) => + { + // when the client is disconnected, the watched user list resets server-side, + // so clear the watched dictionary to reflect this + WatchedUsernamesDictionary.Clear(); + + // over the course of operation the application will watch users which are not explicitly + // configured as they enqueue uploads. these are considered transiently-tracked users, + // and we want to discard them upon disconnect to avoid re-watching them when the client + // is reconnected. to do this, purge the user dictionary of any entry lacking an explicit group. + foreach (var user in UserDictionary.Values.Where(user => user.Group == null)) + { + UserDictionary.TryRemove(user.Username, out _); + } + }; } private void Configure(Options options) -- cgit v1.2.3 From a6508a390021f82ffd3c81f8001c914889f23f28 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 23 Feb 2022 09:28:32 -0600 Subject: use extensions over static factory methods --- src/slskd/Users/Domain/Statistics.cs | 15 +---------- src/slskd/Users/Domain/Status.cs | 21 ++++++++------- src/slskd/Users/Extensions.cs | 51 ++++++++++++++++++++++++++++++++++++ src/slskd/Users/UserService.cs | 22 ++++++++-------- 4 files changed, 74 insertions(+), 35 deletions(-) create mode 100644 src/slskd/Users/Extensions.cs (limited to 'src') diff --git a/src/slskd/Users/Domain/Statistics.cs b/src/slskd/Users/Domain/Statistics.cs index 8dbcaaef..a415d3d5 100644 --- a/src/slskd/Users/Domain/Statistics.cs +++ b/src/slskd/Users/Domain/Statistics.cs @@ -17,9 +17,7 @@ namespace slskd.Users { - using Soulseek; - - public class Statistics + public record Statistics { /// /// Gets the average upload speed of the user. @@ -40,16 +38,5 @@ namespace slskd.Users /// Gets the number of uploads tracked by the server for this user. /// public long UploadCount { get; init; } - - public static Statistics FromSoulseekUserStatistics(UserStatistics statistics) - { - return new Statistics() - { - AverageSpeed = statistics.AverageSpeed, - DirectoryCount = statistics.DirectoryCount, - FileCount = statistics.FileCount, - UploadCount = statistics.UploadCount, - }; - } } } diff --git a/src/slskd/Users/Domain/Status.cs b/src/slskd/Users/Domain/Status.cs index 41452e66..890afb74 100644 --- a/src/slskd/Users/Domain/Status.cs +++ b/src/slskd/Users/Domain/Status.cs @@ -19,18 +19,19 @@ namespace slskd.Users { using Soulseek; - public class Status + /// + /// User status. + /// + public record Status { + /// + /// Gets a value indicating whether the user is privileged. + /// public bool IsPrivileged { get; init; } - public UserPresence Presence { get; init; } - public static Status FromSoulseekUserStatus(UserStatus status) - { - return new Status() - { - IsPrivileged = status.IsPrivileged, - Presence = status.Presence, - }; - } + /// + /// Gets the user's presence. + /// + public UserPresence Presence { get; init; } } } diff --git a/src/slskd/Users/Extensions.cs b/src/slskd/Users/Extensions.cs new file mode 100644 index 00000000..f485df34 --- /dev/null +++ b/src/slskd/Users/Extensions.cs @@ -0,0 +1,51 @@ +// +// 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.Users +{ + using Soulseek; + + /// + /// Users extensions. + /// + public static class Extensions + { + /// + /// Converts to . + /// + /// The UserStatistics instance to convert. + /// The converted instance. + public static Statistics AsStatistics(this UserStatistics u) => new() + { + AverageSpeed = u.AverageSpeed, + DirectoryCount = u.DirectoryCount, + FileCount = u.FileCount, + UploadCount = u.UploadCount, + }; + + /// + /// Converts to . + /// + /// The UserStatus instance to convert. + /// The converted instance. + public static Status AsStatus(this UserStatus s) => new() + { + IsPrivileged = s.IsPrivileged, + Presence = s.Presence, + }; + } +} diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index 4e252f40..58b14cec 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -155,7 +155,7 @@ namespace slskd.Users public async Task GetStatisticsAsync(string username) { var soulseekStatistics = await Client.GetUserStatisticsAsync(username); - return Statistics.FromSoulseekUserStatistics(soulseekStatistics); + return soulseekStatistics.AsStatistics(); } /// @@ -166,7 +166,7 @@ namespace slskd.Users public async Task GetStatusAsync(string username) { var soulseekStatus = await Client.GetUserStatusAsync(username); - return Status.FromSoulseekUserStatus(soulseekStatus); + return soulseekStatus.AsStatus(); } /// @@ -223,33 +223,33 @@ namespace slskd.Users // it isn't completely clear what all causes the server to send this message. we know it is sent following an explicit // request, but it may be sent in an unsolicited manner as well. to be safe, we update internal stats for this user // only on this event, which should cover all bases (both solicited and unsolicited). - Client.UserStatisticsChanged += (_, e) => + Client.UserStatisticsChanged += (_, userStatistics) => { - var statistics = Statistics.FromSoulseekUserStatistics(e); + var statistics = userStatistics.AsStatistics(); UserDictionary.AddOrUpdate( - key: e.Username, + key: userStatistics.Username, addValue: new User() { Statistics = statistics }, - updateValueFactory: (key, user) => user with { Username = e.Username, Statistics = statistics }); + updateValueFactory: (key, user) => user with { Username = userStatistics.Username, Statistics = statistics }); StateMutator.SetValue(state => state with { Users = Users.ToArray() }); }; // the server sends this message in both solicited (we request status), and unsolicited (the user's status changes and // the server informs us without asking). we handle updates in this event handler to cover both cases. - Client.UserStatusChanged += (_, e) => + Client.UserStatusChanged += (_, userStatus) => { - var status = Status.FromSoulseekUserStatus(e); + var status = userStatus.AsStatus(); UserDictionary.AddOrUpdate( - key: e.Username, + key: userStatus.Username, addValue: new User() { Status = status }, - updateValueFactory: (key, user) => user with { Username = e.Username, Status = status }); + updateValueFactory: (key, user) => user with { Username = userStatus.Username, Status = status }); StateMutator.SetValue(state => state with { Users = Users.ToArray() }); // the server doesn't send statistics events by itself, so when a user status changes, fetch stats at the same time. - _ = GetStatisticsAsync(e.Username); + _ = GetStatisticsAsync(userStatus.Username); }; Client.LoggedIn += (_, _) => WatchAllUsers(); -- cgit v1.2.3 From 2b850c11f8f7e18ed35afa6344743decc82f7faf Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 23 Feb 2022 09:30:30 -0600 Subject: docs for User --- src/slskd/Users/Domain/User.cs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) (limited to 'src') diff --git a/src/slskd/Users/Domain/User.cs b/src/slskd/Users/Domain/User.cs index cbf49eea..2913620c 100644 --- a/src/slskd/Users/Domain/User.cs +++ b/src/slskd/Users/Domain/User.cs @@ -19,9 +19,24 @@ namespace slskd.Users { public record User { + /// + /// Gets the username of the user. + /// public string Username { get; init; } + + /// + /// Gets the user's configured group. + /// public string Group { get; init; } + + /// + /// Gets the user's statistics. + /// public Statistics Statistics { get; init; } + + /// + /// Gets the user's status. + /// public Status Status { get; init; } } } -- cgit v1.2.3 From 1955417f467bf9eda4ec9c897dcefb50b43c99ff Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 23 Feb 2022 09:53:16 -0600 Subject: drop tracked users on disconnect, force reconfig on login --- src/slskd/Users/UserService.cs | 20 +++++++------------- 1 file changed, 7 insertions(+), 13 deletions(-) (limited to 'src') diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index 58b14cec..3c3b6508 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -56,7 +56,7 @@ namespace slskd.Users ContextFactory = contextFactory; OptionsMonitor = optionsMonitor; - OptionsMonitor.OnChange(Configure); + OptionsMonitor.OnChange(options => Configure(options)); BindClientEvents(); Configure(OptionsMonitor.CurrentValue); @@ -252,29 +252,23 @@ namespace slskd.Users _ = GetStatisticsAsync(userStatus.Username); }; - Client.LoggedIn += (_, _) => WatchAllUsers(); + Client.LoggedIn += (_, _) => Configure(OptionsMonitor.CurrentValue, force: true); Client.Disconnected += (_, _) => { // when the client is disconnected, the watched user list resets server-side, - // so clear the watched dictionary to reflect this + // so clear the state to reflect this WatchedUsernamesDictionary.Clear(); + UserDictionary.Clear(); - // over the course of operation the application will watch users which are not explicitly - // configured as they enqueue uploads. these are considered transiently-tracked users, - // and we want to discard them upon disconnect to avoid re-watching them when the client - // is reconnected. to do this, purge the user dictionary of any entry lacking an explicit group. - foreach (var user in UserDictionary.Values.Where(user => user.Group == null)) - { - UserDictionary.TryRemove(user.Username, out _); - } + StateMutator.SetValue(state => state with { Users = Users.ToArray() }); }; } - private void Configure(Options options) + private void Configure(Options options, bool force = false) { var optionsHash = Compute.Sha1Hash(options.Groups.UserDefined.ToJson()); - if (optionsHash == LastOptionsHash) + if (optionsHash == LastOptionsHash && !force) { return; } -- cgit v1.2.3 From d4211527a2221ed6fae55b28f7107fbb4c5f224f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 24 Feb 2022 09:11:42 -0600 Subject: rename AsX() to ToX() --- src/slskd/Users/Extensions.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Users/Extensions.cs b/src/slskd/Users/Extensions.cs index f485df34..846fd125 100644 --- a/src/slskd/Users/Extensions.cs +++ b/src/slskd/Users/Extensions.cs @@ -29,7 +29,7 @@ namespace slskd.Users /// /// The UserStatistics instance to convert. /// The converted instance. - public static Statistics AsStatistics(this UserStatistics u) => new() + public static Statistics ToStatistics(this UserStatistics u) => new() { AverageSpeed = u.AverageSpeed, DirectoryCount = u.DirectoryCount, @@ -42,7 +42,7 @@ namespace slskd.Users /// /// The UserStatus instance to convert. /// The converted instance. - public static Status AsStatus(this UserStatus s) => new() + public static Status ToStatus(this UserStatus s) => new() { IsPrivileged = s.IsPrivileged, Presence = s.Presence, -- cgit v1.2.3 From 734f0725673b0ceadbd764b8742082592b620ba3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 24 Feb 2022 09:12:08 -0600 Subject: refactor user updates to explicitly update within async methods --- src/slskd/Users/UserService.cs | 92 ++++++++++++++++++++++-------------------- 1 file changed, 49 insertions(+), 43 deletions(-) (limited to 'src') diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index 3c3b6508..5adc7c71 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -58,7 +58,21 @@ namespace slskd.Users OptionsMonitor = optionsMonitor; OptionsMonitor.OnChange(options => Configure(options)); - BindClientEvents(); + // 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 += (_, userStatus) => + { + UpdateStatus(userStatus.Username, userStatus.ToStatus()); + + // the server doesn't send statistics events by itself, so when a user status changes, fetch stats at the same time. + _ = GetStatisticsAsync(userStatus.Username); + }; + + Client.LoggedIn += (_, _) => Configure(OptionsMonitor.CurrentValue, force: true); + Client.Disconnected += (_, _) => Reset(); + Configure(OptionsMonitor.CurrentValue); } @@ -155,7 +169,11 @@ namespace slskd.Users public async Task GetStatisticsAsync(string username) { var soulseekStatistics = await Client.GetUserStatisticsAsync(username); - return soulseekStatistics.AsStatistics(); + var statistics = soulseekStatistics.ToStatistics(); + + UpdateStatistics(username, statistics); + + return statistics; } /// @@ -166,7 +184,11 @@ namespace slskd.Users public async Task GetStatusAsync(string username) { var soulseekStatus = await Client.GetUserStatusAsync(username); - return soulseekStatus.AsStatus(); + var status = soulseekStatus.ToStatus(); + + UpdateStatus(username, status); + + return status; } /// @@ -212,56 +234,40 @@ namespace slskd.Users Log.Information("Added user {Username} to watch list", username); - // the server does not send a status update when a user is added, but does when that user's status changes. - // request the status explicitly to get the current status. + // 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); } } - private void BindClientEvents() + private void UpdateStatistics(string username, Statistics statistics) { - // it isn't completely clear what all causes the server to send this message. we know it is sent following an explicit - // request, but it may be sent in an unsolicited manner as well. to be safe, we update internal stats for this user - // only on this event, which should cover all bases (both solicited and unsolicited). - Client.UserStatisticsChanged += (_, userStatistics) => - { - var statistics = userStatistics.AsStatistics(); - - UserDictionary.AddOrUpdate( - key: userStatistics.Username, - addValue: new User() { Statistics = statistics }, - updateValueFactory: (key, user) => user with { Username = userStatistics.Username, Statistics = statistics }); - - StateMutator.SetValue(state => state with { Users = Users.ToArray() }); - }; + UserDictionary.AddOrUpdate( + key: username, + addValue: new User() { Statistics = statistics }, + updateValueFactory: (key, user) => user with { Username = username, Statistics = statistics }); - // the server sends this message in both solicited (we request status), and unsolicited (the user's status changes and - // the server informs us without asking). we handle updates in this event handler to cover both cases. - Client.UserStatusChanged += (_, userStatus) => - { - var status = userStatus.AsStatus(); - - UserDictionary.AddOrUpdate( - key: userStatus.Username, - addValue: new User() { Status = status }, - updateValueFactory: (key, user) => user with { Username = userStatus.Username, Status = status }); + StateMutator.SetValue(state => state with { Users = Users.ToArray() }); + } - 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 }); - // the server doesn't send statistics events by itself, so when a user status changes, fetch stats at the same time. - _ = GetStatisticsAsync(userStatus.Username); - }; + StateMutator.SetValue(state => state with { Users = Users.ToArray() }); + } - Client.LoggedIn += (_, _) => Configure(OptionsMonitor.CurrentValue, force: true); - Client.Disconnected += (_, _) => - { - // when the client is disconnected, the watched user list resets server-side, - // so clear the state to reflect this - WatchedUsernamesDictionary.Clear(); - UserDictionary.Clear(); + private void Reset() + { + WatchedUsernamesDictionary.Clear(); + UserDictionary.Clear(); - StateMutator.SetValue(state => state with { Users = Users.ToArray() }); - }; + StateMutator.SetValue(state => state with { Users = Users.ToArray() }); } private void Configure(Options options, bool force = false) -- cgit v1.2.3