aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2023-12-31 16:45:44 -0600
committerJP Dillingham <jp@dillingham.me>2023-12-31 16:45:44 -0600
commitb42d1fea954ebc93ecd5a8451db469af1cc76795 (patch)
tree6eafea9da08a5209cbd1c59c1579ce2e5777246a
parente01ead54fab085b8cf8d6f4bf92592a57b6b2d65 (diff)
downloadslskd-b42d1fea954ebc93ecd5a8451db469af1cc76795.tar.gz
rename GetGroup to ResolveGroup, allow stats and status to be passed in
-rw-r--r--src/slskd/Transfers/Uploads/UploadQueue.cs10
-rw-r--r--src/slskd/Users/IUserService.cs21
-rw-r--r--src/slskd/Users/UserService.cs159
3 files changed, 115 insertions, 75 deletions
diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs
index 53e135e8..0b5f51b1 100644
--- a/src/slskd/Transfers/Uploads/UploadQueue.cs
+++ b/src/slskd/Transfers/Uploads/UploadQueue.cs
@@ -254,11 +254,11 @@ namespace slskd.Transfers
/// <exception cref="NotFoundException">Thrown if the specified filename is not enqueued.</exception>
public int EstimatePosition(string username, string filename)
{
- var groupName = Users.GetGroup(username);
+ var groupName = Users.ResolveGroup(username);
var groupRecord = Groups.GetValueOrDefault(groupName);
// the Uploads dictionary is keyed by username; gather all of the users that belong to the same group as the requested user
- var uploadsForGroup = Uploads.Where(kvp => Users.GetGroup(kvp.Key) == groupName);
+ var uploadsForGroup = Uploads.Where(kvp => Users.ResolveGroup(kvp.Key) == groupName);
// the RoundRobin queue implementation is not strictly fair to all users; only uploads that are ready are candidates
// for selection. this means that if Bob downloads files twice as fast as Alice, Bob is going to advance through the
@@ -337,7 +337,7 @@ namespace slskd.Transfers
/// </returns>
public int ForecastPosition(string username)
{
- var groupName = Users.GetGroup(username);
+ var groupName = Users.ResolveGroup(username);
// if there's a slot available, the user will enter the queue at position 0 (will start immediately)
if (Groups.TryGetValue(groupName, out var groupRecord) && groupRecord.SlotAvailable)
@@ -346,7 +346,7 @@ namespace slskd.Transfers
}
// the Uploads dictionary is keyed by username; gather all of the users that belong to the same group as the requested user
- var uploadsForGroup = Uploads.Where(kvp => Users.GetGroup(kvp.Key) == groupName);
+ var uploadsForGroup = Uploads.Where(kvp => Users.ResolveGroup(kvp.Key) == groupName);
// assuming that the queue will be processed in a true round-robin fashion and that the user will be the last in the
// rotation (worst case), the user's start position will be equal to the number of users downloading or waiting, + 1.
@@ -462,7 +462,7 @@ namespace slskd.Transfers
if (ready.Any())
{
- var group = Users.GetGroup(user.Key);
+ var group = Users.ResolveGroup(user.Key);
groups.AddOrUpdate(
key: group,
diff --git a/src/slskd/Users/IUserService.cs b/src/slskd/Users/IUserService.cs
index 88090f9f..885b00e5 100644
--- a/src/slskd/Users/IUserService.cs
+++ b/src/slskd/Users/IUserService.cs
@@ -37,13 +37,6 @@ namespace slskd.Users
IReadOnlyList<string> WatchedUsernames { get; }
/// <summary>
- /// Gets the name of the group for the specified <paramref name="username"/>.
- /// </summary>
- /// <param name="username">The username of the peer.</param>
- /// <returns>The group for the specified username.</returns>
- string GetGroup(string username);
-
- /// <summary>
/// Retrieves peer <see cref="Info"/>.
/// </summary>
/// <param name="username">The username of the peer.</param>
@@ -87,6 +80,20 @@ namespace slskd.Users
bool IsWatched(string username);
/// <summary>
+ /// Resolves the name of the group for the specified <paramref name="username"/>.
+ /// </summary>
+ /// <remarks>
+ /// If the user is watched, and therefore the application is tracking their status and statistics, leech and privilege
+ /// detection works as expected. If the user is not watched, their status and statistics can be specified. If the user
+ /// is neither watched nor status and statistics are supplied, leech and privilege detection will not work.
+ /// </remarks>
+ /// <param name="username">The username of the peer.</param>
+ /// <param name="status">The optional status for the user.</param>
+ /// <param name="statistics">The optional statistics for the user.</param>
+ /// <returns>The group for the specified username.</returns>
+ string ResolveGroup(string username, Status status = null, Statistics statistics = null);
+
+ /// <summary>
/// Adds the specified username to the server-side user list.
/// </summary>
/// <param name="username">The username of the peer.</param>
diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs
index 95fed12d..ebd85d24 100644
--- a/src/slskd/Users/UserService.cs
+++ b/src/slskd/Users/UserService.cs
@@ -50,9 +50,9 @@ namespace slskd.Users
OptionsMonitor = optionsMonitor;
OptionsMonitor.OnChange(options => Configure(options));
- // updates may be sent unsolicited from the server, so update when we get them.
- // binding these events will cause multiple redundant round trips when initially watching a user
- // or when explicitly requesting via GetStatus/GetStatistics. this is wasteful, but there's no functional side effect.
+ // updates may be sent unsolicited from the server, so update when we get them. binding these events will cause
+ // multiple redundant round trips when initially watching a user or when explicitly requesting via
+ // GetStatus/GetStatistics. this is wasteful, but there's no functional side effect.
Client.UserStatisticsChanged += (_, userStatistics) => UpdateStatistics(userStatistics.Username, userStatistics.ToStatistics());
Client.UserStatusChanged += (sender, userStatus) =>
{
@@ -87,37 +87,6 @@ namespace slskd.Users
private ConcurrentDictionary<string, bool> WatchedUsernamesDictionary { get; set; } = new ConcurrentDictionary<string, bool>();
/// <summary>
- /// Gets the name of the group for the specified <paramref name="username"/>.
- /// </summary>
- /// <param name="username">The username of the peer.</param>
- /// <returns>The group for the specified username.</returns>
- public string GetGroup(string username)
- {
- // note: this is an extremely hot path; keep the work done to an absolute minimum.
- if (UserDictionary.TryGetValue(username ?? string.Empty, out var user))
- {
- if (user.Status?.IsPrivileged ?? false)
- {
- return Application.PrivilegedGroup;
- }
-
- if (user.Group != null)
- {
- return user.Group;
- }
-
- var thresholds = OptionsMonitor.CurrentValue.Groups.Leechers.Thresholds;
-
- if (user.Statistics?.FileCount < thresholds.Files || user.Statistics?.DirectoryCount < thresholds.Directories)
- {
- return Application.LeecherGroup;
- }
- }
-
- return Application.DefaultGroup;
- }
-
- /// <summary>
/// Retrieves peer <see cref="Info"/>.
/// </summary>
/// <param name="username">The username of the peer.</param>
@@ -196,50 +165,86 @@ namespace slskd.Users
public bool IsWatched(string username) => WatchedUsernamesDictionary.ContainsKey(username);
/// <summary>
- /// Adds the specified username to the server-side user list.
+ /// Resolves the name of the group for the specified <paramref name="username"/>.
/// </summary>
+ /// <remarks>
+ /// If the user is watched, and therefore the application is tracking their status and statistics, leech and privilege
+ /// detection works as expected. If the user is not watched, their status and statistics can be specified. If the user
+ /// is neither watched nor status and statistics are supplied, leech and privilege detection will not work.
+ /// </remarks>
/// <param name="username">The username of the peer.</param>
- /// <returns>The operation context.</returns>
- public async Task WatchAsync(string username)
+ /// <param name="status">The optional status for the user.</param>
+ /// <param name="statistics">The optional statistics for the user.</param>
+ /// <returns>The group for the specified username.</returns>
+ public string ResolveGroup(string username, Status status = null, Statistics statistics = null)
{
- await Client.AddUserAsync(username);
- WatchedUsernamesDictionary.TryAdd(username, true);
+ /*
+ * note: this is an extremely hot path; keep the work done to an absolute minimum.
+ */
- Log.Information("Added user {Username} to watch list", username);
+ // we shouldn't be asking, but this could happen in some scenarios.
+ if (OptionsMonitor.CurrentValue.Groups.Blacklisted.Members.Contains(username))
+ {
+ return Application.BlacklistedGroup;
+ }
+
+ var thresholds = OptionsMonitor.CurrentValue.Groups.Leechers.Thresholds;
- // the server does not automatically send status and statistics information
- // when watching a user initially. explicitly fetch both, so that the user has been
- // watched and all information populated when this method returns.
- await GetStatusAsync(username);
- await GetStatisticsAsync(username);
+ // any user that's been explicitly added to a group is "watched" and will be in this dictionary,
+ // along with their latest status and statistics. we *need* to do this lookup to expedite the
+ // resolution of their group from configuration quickly.
+ if (UserDictionary.TryGetValue(username ?? string.Empty, out var user))
+ {
+ if (user.Status?.IsPrivileged ?? false)
+ {
+ return Application.PrivilegedGroup;
}
- private void UpdateStatistics(string username, Statistics statistics)
+ if (user.Group != null)
{
- UserDictionary.AddOrUpdate(
- key: username,
- addValue: new User() { Statistics = statistics },
- updateValueFactory: (key, user) => user with { Username = username, Statistics = statistics });
+ return user.Group;
+ }
- StateMutator.SetValue(state => state with { Users = Users.ToArray() });
+ if (user.Statistics?.FileCount < thresholds.Files || user.Statistics?.DirectoryCount < thresholds.Directories)
+ {
+ return Application.LeecherGroup;
}
+ }
- private void UpdateStatus(string username, Status status)
+ // the user hasn't been added to the dictionary, so we know they aren't part of a user defined group
+ // the caller may have specified status and statistics. check and see.
+ if (status?.IsPrivileged ?? false)
{
- UserDictionary.AddOrUpdate(
- key: username,
- addValue: new User() { Status = status },
- updateValueFactory: (key, user) => user with { Username = username, Status = status });
+ return Application.PrivilegedGroup;
+ }
- StateMutator.SetValue(state => state with { Users = Users.ToArray() });
+ if (statistics?.FileCount < thresholds.Files || statistics?.DirectoryCount < thresholds.Directories)
+ {
+ return Application.LeecherGroup;
}
- private void Reset()
+ return Application.DefaultGroup;
+ }
+
+ /// <summary>
+ /// Adds the specified username to the server-side user list.
+ /// </summary>
+ /// <param name="username">The username of the peer.</param>
+ /// <returns>The operation context.</returns>
+ public async Task WatchAsync(string username)
{
- WatchedUsernamesDictionary.Clear();
- UserDictionary.Clear();
+ await Client.AddUserAsync(username);
+ WatchedUsernamesDictionary.TryAdd(username, true);
- StateMutator.SetValue(state => state with { Users = Users.ToArray() });
+ Log.Information("Added user {Username} to watch list", username);
+
+ // the server does not automatically send status and statistics information when watching a user initially. explicitly
+ // fetch both, so that the user has been watched and all information populated when this method returns.
+ var status = await GetStatusAsync(username);
+ UpdateStatus(username, status);
+
+ var statistics = await GetStatisticsAsync(username);
+ UpdateStatistics(username, statistics);
}
private void Configure(Options options, bool force = false)
@@ -251,8 +256,8 @@ namespace slskd.Users
return;
}
- // get a list of tracked names that haven't been explicitly added to any group, including
- // those that were previlously configured but have now been removed
+ // get a list of tracked names that haven't been explicitly added to any group, including those that were previlously
+ // configured but have now been removed
var usernamesBeforeUpdate = UserDictionary.Keys.ToList();
var usernamesAfterUpdate = options.Groups.UserDefined.SelectMany(g => g.Value.Members);
var usernamesRemoved = usernamesBeforeUpdate.Except(usernamesAfterUpdate);
@@ -286,6 +291,34 @@ namespace slskd.Users
LastOptionsHash = optionsHash;
}
+ private void Reset()
+ {
+ WatchedUsernamesDictionary.Clear();
+ UserDictionary.Clear();
+
+ StateMutator.SetValue(state => state with { Users = Users.ToArray() });
+ }
+
+ private void UpdateStatistics(string username, Statistics statistics)
+ {
+ UserDictionary.AddOrUpdate(
+ key: username,
+ addValue: new User() { Statistics = statistics },
+ updateValueFactory: (key, user) => user with { Username = username, Statistics = statistics });
+
+ StateMutator.SetValue(state => state with { Users = Users.ToArray() });
+ }
+
+ private void UpdateStatus(string username, Status status)
+ {
+ UserDictionary.AddOrUpdate(
+ key: username,
+ addValue: new User() { Status = status },
+ updateValueFactory: (key, user) => user with { Username = username, Status = status });
+
+ StateMutator.SetValue(state => state with { Users = Users.ToArray() });
+ }
+
private void WatchAllUsers()
{
if (Client.State.HasFlag(SoulseekClientStates.Connected) && Client.State.HasFlag(SoulseekClientStates.LoggedIn))