aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2024-01-05 18:31:11 -0600
committerJP Dillingham <jp@dillingham.me>2024-01-05 18:31:11 -0600
commiteb14f632df9f8f487335db643fdea4b9c1547be1 (patch)
tree4db8ae5133d7e31eb5e144a03e3e1491700b3ebb
parent1cd4b10a25052e4e82c1f86a9bc92f06f5605114 (diff)
downloadslskd-eb14f632df9f8f487335db643fdea4b9c1547be1.tar.gz
finish refactor of UserService
-rw-r--r--src/slskd/Users/IUserService.cs79
-rw-r--r--src/slskd/Users/UserService.cs229
-rw-r--r--tests/slskd.Tests.Unit/Users/UserServiceTests.cs2
3 files changed, 206 insertions, 104 deletions
diff --git a/src/slskd/Users/IUserService.cs b/src/slskd/Users/IUserService.cs
index 04ef1527..2d30949b 100644
--- a/src/slskd/Users/IUserService.cs
+++ b/src/slskd/Users/IUserService.cs
@@ -24,6 +24,38 @@ namespace slskd.Users
/// <summary>
/// Provides information and operations for network peers.
/// </summary>
+ /// <remarks>
+ /// <para>
+ /// This class maintains a <see cref="UserDictionary"/> that acts as a non-expiring cache of information
+ /// collected about a user. This includes their statistics (share counts, speed, etc), their status (privileged, etc)
+ /// and, if they are a member of a user-defined group, their group.
+ /// </para>
+ /// <para>
+ /// This class also maintains a <see cref="WatchedUsernamesDictionary"/> to keep track of which usernames have been
+ /// "watched" server side and for which we will therefore receive events when their status changes.
+ /// </para>
+ /// <para>
+ /// If a user's information is in the <see cref="UserDictionary"/>, it's because we requested it at some point. If that user
+ /// is also "watched", we can assume that the data in the dictionary is up to date and will be kept so.
+ /// </para>
+ /// <para>
+ /// The data in the <see cref="UserDictionary"/> can continue to grow until -- unlikely -- it contains a record for every
+ /// user on or that was on the network at any point since the last client connect. This is a calculated risk, roughly
+ /// knowing the size of the network, the size of the data being stored, and balanced against the consequences of not having
+ /// a user's data when it is needed (for queue positioning, speed limits, etc)
+ /// </para>
+ /// <para>
+ /// The <see cref="GetGroup(string)"/> method acts on cached data _only_. This method should be called within hot paths,
+ /// such as a transfer governor or from the upload queue. We care more that it is fast than if it is stale. If no data for the
+ /// requested user is cached, that user is assumed to be in the default group.
+ /// </para>
+ /// <para>
+ /// The <see cref="GetOrFetchGroupAsync(string, bool)"/> method is similar to <see cref="GetGroup(string)"/>, except that if
+ /// the requested user is not cached, it will fetch the user's data and cache it before returning. This method accepts an optional
+ /// parameter that can be used to force a "refresh" of the requested user's data, useful for times when we want the latest data,
+ /// and can afford to wait for it.
+ /// </para>
+ /// </remarks>
public interface IUserService
{
/// <summary>
@@ -39,28 +71,12 @@ namespace slskd.Users
/// <summary>
/// Gets the name of the group for the specified <paramref name="username"/>.
/// </summary>
- /// <remarks>
- /// The group name is fetched from cached data, and lookups should always be fast.
- /// </remarks>
+ /// <remarks>The group name is fetched from cached data, and lookups should always be fast.</remarks>
/// <param name="username">The username of the peer.</param>
/// <returns>The group for the specified username.</returns>
string GetGroup(string username);
/// <summary>
- /// Gets the name of the group for the specified <paramref name="username"/>.
- /// </summary>
- /// <remarks>
- /// An alternative to <see cref="GetGroup(string)"/> that does not rely on the
- /// internal cache. This method allows privilege and leech detection for users
- /// that are not watched.
- /// </remarks>
- /// <param name="username">The username of the peer.</param>
- /// <param name="status">The peer's status.</param>
- /// <param name="statistics">The peer's statistics</param>
- /// <returns>The group for the specified username.</returns>
- string GetGroup(string username, Status status, Statistics statistics);
-
- /// <summary>
/// Retrieves peer <see cref="Info"/>.
/// </summary>
/// <param name="username">The username of the peer.</param>
@@ -75,7 +91,26 @@ namespace slskd.Users
Task<IPEndPoint> GetIPEndPointAsync(string username);
/// <summary>
- /// Retrieves the current <see cref="Status"/> of a peer.
+ /// Gets the name of the group for the specified <paramref name="username"/>, or, if the user's information isn't
+ /// cached, fetches and caches the user's information from the server, then returns the group.
+ /// </summary>
+ /// <remarks>The fetch of fresh data can be forced by specifying <paramref name="forceFetch"/> = true.</remarks>
+ /// <param name="username">The username of the peer.</param>
+ /// <param name="forceFetch">
+ /// A value determining whether the user's information should be fetched from the server, regardless of local cache.
+ /// </param>
+ /// <returns>The group for the specified username.</returns>
+ Task<string> GetOrFetchGroupAsync(string username, bool forceFetch = false);
+
+ /// <summary>
+ /// Retrieves the current <see cref="Statistics"/> of a peer, and caches the result.
+ /// </summary>
+ /// <param name="username">The username of the peer.</param>
+ /// <returns>The retrieved statistics.</returns>
+ Task<Statistics> GetStatisticsAsync(string username);
+
+ /// <summary>
+ /// Retrieves the current <see cref="Status"/> of a peer, and caches the result.
/// </summary>
/// <param name="username">The username of the peer.</param>
/// <returns>The retrieved status.</returns>
@@ -90,6 +125,14 @@ namespace slskd.Users
Task GrantPrivilegesAsync(string username, int days);
/// <summary>
+ /// Gets a value indicating whether the specified <paramref name="username"/> and/or <paramref name="ipAddress"/> are blacklisted.
+ /// </summary>
+ /// <param name="username">The username to check.</param>
+ /// <param name="ipAddress">The IPAddress to check, if available.</param>
+ /// <returns>A value indicating whether the specified user and/or IP are blacklisted.</returns>
+ bool IsBlacklisted(string username, IPAddress ipAddress = null);
+
+ /// <summary>
/// Retrieves a value indicating whether the specified peer is privileged.
/// </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 4ab3840c..434d357c 100644
--- a/src/slskd/Users/UserService.cs
+++ b/src/slskd/Users/UserService.cs
@@ -24,6 +24,7 @@ namespace slskd.Users
using System.Linq;
using System.Net;
using System.Threading.Tasks;
+ using NetTools;
using Serilog;
using Soulseek;
@@ -31,11 +32,36 @@ namespace slskd.Users
/// Provides information and operations for network peers.
/// </summary>
/// <remarks>
- /// The <see cref="WatchAsync(string)"/> method should be called to 'watch' users prior to any call to
- /// <see cref="GetGroup(string)"/>. <see cref="GetGroup(string)"/> relies *only* on information stored in
- /// the internal <see cref="UserDictionary"/>, and this dictionary is only populated for users that have been
- /// watched. Prior to calling <see cref="WatchAsync(string)"/>, check <see cref="IsWatched(string)"/> to
- /// reduce round trips to the server.
+ /// <para>
+ /// This class maintains a <see cref="UserDictionary"/> that acts as a non-expiring cache of information
+ /// collected about a user. This includes their statistics (share counts, speed, etc), their status (privileged, etc)
+ /// and, if they are a member of a user-defined group, their group.
+ /// </para>
+ /// <para>
+ /// This class also maintains a <see cref="WatchedUsernamesDictionary"/> to keep track of which usernames have been
+ /// "watched" server side and for which we will therefore receive events when their status changes.
+ /// </para>
+ /// <para>
+ /// If a user's information is in the <see cref="UserDictionary"/>, it's because we requested it at some point. If that user
+ /// is also "watched", we can assume that the data in the dictionary is up to date and will be kept so.
+ /// </para>
+ /// <para>
+ /// The data in the <see cref="UserDictionary"/> can continue to grow until -- unlikely -- it contains a record for every
+ /// user on or that was on the network at any point since the last client connect. This is a calculated risk, roughly
+ /// knowing the size of the network, the size of the data being stored, and balanced against the consequences of not having
+ /// a user's data when it is needed (for queue positioning, speed limits, etc)
+ /// </para>
+ /// <para>
+ /// The <see cref="GetGroup(string)"/> method acts on cached data _only_. This method should be called within hot paths,
+ /// such as a transfer governor or from the upload queue. We care more that it is fast than if it is stale. If no data for the
+ /// requested user is cached, that user is assumed to be in the default group.
+ /// </para>
+ /// <para>
+ /// The <see cref="GetOrFetchGroupAsync(string, bool)"/> method is similar to <see cref="GetGroup(string)"/>, except that if
+ /// the requested user is not cached, it will fetch the user's data and cache it before returning. This method accepts an optional
+ /// parameter that can be used to force a "refresh" of the requested user's data, useful for times when we want the latest data,
+ /// and can afford to wait for it.
+ /// </para>
/// </remarks>
public class UserService : IUserService
{
@@ -43,23 +69,19 @@ namespace slskd.Users
/// Initializes a new instance of the <see cref="UserService"/> class.
/// </summary>
/// <param name="soulseekClient"></param>
- /// <param name="stateMutator"></param>
/// <param name="optionsMonitor"></param>
public UserService(
ISoulseekClient soulseekClient,
- IStateMutator<State> stateMutator,
IOptionsMonitor<Options> optionsMonitor)
{
Client = soulseekClient;
- StateMutator = stateMutator;
-
OptionsMonitor = optionsMonitor;
OptionsMonitor.OnChange(options => Configure(options));
- // updates may be sent unsolicited from the server, so update when we get them.
- // binding these events will cause multiple redundant round trips when initially watching a user
- // or when explicitly requesting via GetStatus/GetStatistics. this is wasteful, but there's no functional side effect.
+ // updates may be sent unsolicited from the server, so update when we get them. binding these events will cause
+ // multiple redundant round trips when initially watching a user or when explicitly requesting via
+ // GetStatus/GetStatistics. this is wasteful, but there's no functional side effect.
Client.UserStatisticsChanged += (_, userStatistics) => UpdateStatistics(userStatistics.Username, userStatistics.ToStatistics());
Client.UserStatusChanged += (sender, userStatus) =>
{
@@ -71,6 +93,7 @@ namespace slskd.Users
Client.Connected += (_, _) => Reset();
Client.LoggedIn += (_, _) => Configure(OptionsMonitor.CurrentValue, force: true);
+ Client.PrivilegedUserListReceived += (_, list) => Client_PrivilegedUserListReceived(list);
Configure(OptionsMonitor.CurrentValue);
}
@@ -89,37 +112,34 @@ namespace slskd.Users
private string LastOptionsHash { get; set; }
private ILogger Log { get; set; } = Serilog.Log.ForContext<UserService>();
private IOptionsMonitor<Options> OptionsMonitor { get; }
- private IStateMutator<State> StateMutator { get; }
- private ConcurrentDictionary<string, bool> WatchedUsernamesDictionary { get; set; } = new ConcurrentDictionary<string, bool>();
/// <summary>
/// Gets or sets the internal cache of User data.
/// </summary>
/// <remarks>
/// <para>
- /// This method retrieves the requested user's information from a dictionary, and
- /// is therefore a 'get'. This information is needed to control who can do what,
- /// who is subject to what limits, how to control the upload queue, and how to
- /// govern speeds. The logic in this method is the 'hottest' in the application
- /// and *must* remain very simple and _fast_.
+ /// This method retrieves the requested user's information from a dictionary, and is therefore a 'get'. This
+ /// information is needed to control who can do what, who is subject to what limits, how to control the upload
+ /// queue, and how to govern speeds. The logic in this method is the 'hottest' in the application and *must*
+ /// remain very simple and _fast_.
/// </para>
/// <para>
- /// If this method is called for a user who has not previously been cached, it
- /// will return the default group, meaning leech, privilege, and user defined group
- /// discrimination will not work. For this reason it is critical that user information
- /// is retrieved and cached upon first interaction with that user.
+ /// If this method is called for a user who has not previously been cached, it will return the default group,
+ /// meaning leech, privilege, and user defined group discrimination will not work. For this reason it is critical
+ /// that user information is retrieved and cached upon first interaction with that user.
/// </para>
/// <para>
- /// Uploads can be cached indefinitely, and for that reason the user data cache must be
- /// filled indefinitely; meaning there is no invalidation and that user data will accrue
- /// for the lifetime of the application (instance).
+ /// Uploads can be cached indefinitely, and for that reason the user data cache must be filled indefinitely;
+ /// meaning there is no invalidation and that user data will accrue for the lifetime of the application (instance).
/// </para>
/// </remarks>
private ConcurrentDictionary<string, User> UserDictionary { get; set; } = new ConcurrentDictionary<string, User>();
+ 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>
+ /// <remarks>The group name is fetched from cached data, and lookups should always be fast.</remarks>
/// <param name="username">The username of the peer.</param>
/// <returns>The group for the specified username.</returns>
public string GetGroup(string username)
@@ -127,6 +147,11 @@ namespace slskd.Users
// note: this is an extremely hot path; keep the work done to an absolute minimum.
if (UserDictionary.TryGetValue(username ?? string.Empty, out var user))
{
+ if (IsBlacklisted(user.Username))
+ {
+ return Application.BlacklistedGroup;
+ }
+
if (user.Status?.IsPrivileged ?? false)
{
return Application.PrivilegedGroup;
@@ -170,7 +195,32 @@ namespace slskd.Users
}
/// <summary>
- /// Retrieves the current <see cref="Statistics"/> of a peer.
+ /// Gets the name of the group for the specified <paramref name="username"/>, or, if the user's information isn't
+ /// cached, fetches and caches the user's information from the server, then returns the group.
+ /// </summary>
+ /// <remarks>The fetch of fresh data can be forced by specifying <paramref name="forceFetch"/> = true.</remarks>
+ /// <param name="username">The username of the peer.</param>
+ /// <param name="forceFetch">
+ /// A value determining whether the user's information should be fetched from the server, regardless of local cache.
+ /// </param>
+ /// <returns>The group for the specified username.</returns>
+ public async Task<string> GetOrFetchGroupAsync(string username, bool forceFetch = false)
+ {
+ if (!UserDictionary.ContainsKey(username) || forceFetch)
+ {
+ // ensure the record will exist
+ UserDictionary.TryAdd(username, new User { Username = username });
+
+ // try to populate the user's info
+ await GetStatisticsAsync(username);
+ await GetStatusAsync(username);
+ }
+
+ return GetGroup(username);
+ }
+
+ /// <summary>
+ /// Retrieves the current <see cref="Statistics"/> of a peer, and caches the result.
/// </summary>
/// <param name="username">The username of the peer.</param>
/// <returns>The retrieved statistics.</returns>
@@ -185,7 +235,7 @@ namespace slskd.Users
}
/// <summary>
- /// Retrieves the current <see cref="Status"/> of a peer.
+ /// Retrieves the current <see cref="Status"/> of a peer, and caches the result.
/// </summary>
/// <param name="username">The username of the peer.</param>
/// <returns>The retrieved status.</returns>
@@ -209,6 +259,29 @@ namespace slskd.Users
=> Client.GrantUserPrivilegesAsync(username, days);
/// <summary>
+ /// Gets a value indicating whether the specified <paramref name="username"/> and/or <paramref name="ipAddress"/> are blacklisted.
+ /// </summary>
+ /// <param name="username">The username to check.</param>
+ /// <param name="ipAddress">The IPAddress to check, if available.</param>
+ /// <returns>A value indicating whether the specified user and/or IP are blacklisted.</returns>
+ public bool IsBlacklisted(string username, IPAddress ipAddress = null)
+ {
+ var blacklist = OptionsMonitor.CurrentValue.Groups.Blacklisted;
+
+ if (blacklist.Members.Contains(username))
+ {
+ return true;
+ }
+
+ if (ipAddress is not null && blacklist.Cidrs.Select(c => IPAddressRange.Parse(c)).Any(range => range.Contains(ipAddress)))
+ {
+ return true;
+ }
+
+ return false;
+ }
+
+ /// <summary>
/// Retrieves a value indicating whether the specified peer is privileged.
/// </summary>
/// <param name="username">The username of the peer.</param>
@@ -230,68 +303,44 @@ namespace slskd.Users
/// Adds the specified username to the server-side user list.
/// </summary>
/// <remarks>
+ /// <para>Idempotent; if a user is already watched, subsequent calls will only update their status and statistics.</para>
/// <para>
- /// Idempotent; if a user is already watched, subsequent calls will
- /// only update their status and statistics.
- /// </para>
- /// <para>
- /// Any user we want to track in any way needs to be watched so that
- /// their statistics and status are updated properly via server side events.
- /// This seems extreme and wasteful, but the only alternative is to periodically
- /// spam the server for the information instead of letting the server spam the client
- /// when things change.
+ /// Any user we want to track in any way needs to be watched so that their statistics and status are updated
+ /// properly via server side events. This seems extreme and wasteful, but the only alternative is to periodically
+ /// spam the server for the information instead of letting the server spam the client when things change.
/// </para>
/// </remarks>
/// <param name="username">The username of the peer.</param>
/// <returns>The operation context.</returns>
public async Task WatchAsync(string username)
{
+ // watch the user, server side
await Client.AddUserAsync(username);
UserDictionary.TryAdd(username, new User { Username = username });
Log.Information("Added user {Username} to watch list", username);
- // the server does not automatically send status and statistics information
- // when watching a user initially. explicitly fetch both, so that the user has been
- // watched and all information populated when this method returns.
+ // the server does not automatically send status and statistics information when watching a user initially. explicitly
+ // fetch both, so that the user has been watched and all information populated when this method returns.
await GetStatusAsync(username);
await GetStatisticsAsync(username);
- // delay the add until last, so that IsWatched won't return true until stats
- // and status are populated. this may result in several unecessary calls to
- // WatchAsync (if someone is checking IsWatched() and WatchAsync()ing if false),
- // but we can be sure that if IsWatched() is true, we have valid stats and status.
- // if we can't ensure this, the application will have non-deterministic behavior
- // when it makes decisions about user groups, limits, governance etc.
+ // delay the add until last, so that IsWatched won't return true until stats and status are populated. this may result
+ // in several unecessary calls to WatchAsync (if someone is checking IsWatched() and WatchAsync()ing if false), but we
+ // can be sure that if IsWatched() is true, we have valid stats and status. if we can't ensure this, the application
+ // will have non-deterministic behavior when it makes decisions about user groups, limits, governance etc.
WatchedUsernamesDictionary.TryAdd(username, true);
}
- private void UpdateStatistics(string username, Statistics statistics)
- {
- UserDictionary.AddOrUpdate(
- key: username,
- addValue: new User() { Statistics = statistics },
- updateValueFactory: (key, user) => user with { Username = username, Statistics = statistics });
-
- StateMutator.SetValue(state => state with { Users = Users.ToArray() });
- }
-
- private void UpdateStatus(string username, Status status)
+ private void Client_PrivilegedUserListReceived(IEnumerable<string> list)
{
- UserDictionary.AddOrUpdate(
- key: username,
- addValue: new User() { Status = status },
- updateValueFactory: (key, user) => user with { Username = username, Status = status });
-
- StateMutator.SetValue(state => state with { Users = Users.ToArray() });
- }
-
- private void Reset()
- {
- WatchedUsernamesDictionary.Clear();
- UserDictionary.Clear();
-
- StateMutator.SetValue(state => state with { Users = Users.ToArray() });
+ foreach (var username in list)
+ {
+ UserDictionary.AddOrUpdate(
+ key: username,
+ addValue: new User() { Status = new Status { IsPrivileged = true } },
+ updateValueFactory: (key, user) => user with { Username = username, Status = user.Status with { IsPrivileged = true } });
+ }
}
private void Configure(Options options, bool force = false)
@@ -303,8 +352,8 @@ namespace slskd.Users
return;
}
- // get a list of tracked names that haven't been explicitly added to any group, including
- // those that were previlously configured but have now been removed
+ // get a list of tracked names that haven't been explicitly added to any group, including those that were previlously
+ // configured but have now been removed
var usernamesBeforeUpdate = UserDictionary.Keys.ToList();
var usernamesAfterUpdate = options.Groups.UserDefined.SelectMany(g => g.Value.Members);
var usernamesRemoved = usernamesBeforeUpdate.Except(usernamesAfterUpdate);
@@ -328,25 +377,37 @@ namespace slskd.Users
key: username,
addValue: new User() { Username = username, Group = group.Key },
updateValueFactory: (key, user) => user with { Username = username, Group = group.Key });
+
+ if (Client.State.HasFlag(SoulseekClientStates.Connected) && Client.State.HasFlag(SoulseekClientStates.LoggedIn))
+ {
+ _ = WatchAsync(username);
+ }
}
}
- StateMutator.SetValue(state => state with { Users = Users.ToArray() });
+ LastOptionsHash = optionsHash;
+ }
- WatchAllUsers();
+ private void Reset()
+ {
+ WatchedUsernamesDictionary.Clear();
+ UserDictionary.Clear();
+ }
- LastOptionsHash = optionsHash;
+ private void UpdateStatistics(string username, Statistics statistics)
+ {
+ UserDictionary.AddOrUpdate(
+ key: username,
+ addValue: new User() { Statistics = statistics },
+ updateValueFactory: (key, user) => user with { Username = username, Statistics = statistics });
}
- private void WatchAllUsers()
+ private void UpdateStatus(string username, Status status)
{
- if (Client.State.HasFlag(SoulseekClientStates.Connected) && Client.State.HasFlag(SoulseekClientStates.LoggedIn))
- {
- foreach (var username in UserDictionary.Keys.ToList())
- {
- _ = WatchAsync(username);
- }
- }
+ UserDictionary.AddOrUpdate(
+ key: username,
+ addValue: new User() { Status = status },
+ updateValueFactory: (key, user) => user with { Username = username, Status = status });
}
}
} \ No newline at end of file
diff --git a/tests/slskd.Tests.Unit/Users/UserServiceTests.cs b/tests/slskd.Tests.Unit/Users/UserServiceTests.cs
index 16b1c5fe..0bf11580 100644
--- a/tests/slskd.Tests.Unit/Users/UserServiceTests.cs
+++ b/tests/slskd.Tests.Unit/Users/UserServiceTests.cs
@@ -125,7 +125,6 @@
var mocks = new Mocks(options);
var service = new UserService(
mocks.SoulseekClient.Object,
- mocks.StateMutator.Object,
mocks.OptionsMonitor);
return (service, mocks);
@@ -139,7 +138,6 @@
}
public Mock<ISoulseekClient> SoulseekClient { get; } = new Mock<ISoulseekClient>();
- public Mock<IStateMutator<State>> StateMutator { get; } = new Mock<IStateMutator<State>>();
public TestOptionsMonitor<Options> OptionsMonitor { get; init; }
}
}