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/UserService.cs | 46 +++++++++++++++++++++++++++++++++++++++--- 1 file changed, 43 insertions(+), 3 deletions(-) (limited to 'src/slskd/Users/UserService.cs') 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 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/slskd/Users/UserService.cs') 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 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/slskd/Users/UserService.cs') 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/slskd/Users/UserService.cs') 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/slskd/Users/UserService.cs') 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/slskd/Users/UserService.cs') 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 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/slskd/Users/UserService.cs') 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 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/slskd/Users/UserService.cs') 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