From 854f3155f1d77907e77573ecfa7e836b0ae202ae Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 19 Feb 2022 13:07:24 -0600 Subject: fix spelling --- docs/config.md | 240 ++++++++++----------- src/slskd/Application.cs | 4 +- src/slskd/Options.cs | 4 +- src/slskd/Transfers/Uploads/UploadGovernor.cs | 2 +- src/slskd/Transfers/Uploads/UploadQueue.cs | 8 +- .../Transfers/Uploads/UploadGovernorTests.cs | 4 +- .../Transfers/Uploads/UploadQueueTests.cs | 16 +- 7 files changed, 139 insertions(+), 139 deletions(-) diff --git a/docs/config.md b/docs/config.md index ec682b43..4f56e49f 100644 --- a/docs/config.md +++ b/docs/config.md @@ -64,9 +64,9 @@ The application contains APIs for retrieving and updating the YAML configuration If an attacker were to gain access to the application and retrieve the YAML file, any secrets contained within it will be exposed. -|Command Line|Environment Variable|Description| -|----|-----|-----------| -|`--remote-configuration`|`REMOTE_CONFIGURATION`|Determines whether remote configuration of options is allowed| +| Command Line | Environment Variable | Description | +| ------------------------ | ---------------------- | ------------------------------------------------------------- | +| `--remote-configuration` | `REMOTE_CONFIGURATION` | Determines whether remote configuration of options is allowed | #### **YAML** ```yaml @@ -91,10 +91,10 @@ By default, incomplete and downloaded files are saved in `APP_DIR/incomplete` an Alternative locations can be specified for each directory. Directories must exist and must be writable by the application; the application will not attempt create them. -|Command Line|Environment Variable|Description| -|----|-----|-----------| -|`-o\|--downloads`|`DOWNLOADS_DIR`|The path where downloaded files are saved| -|`--incomplete`|`INCOMPLETE_DIR`|The path where incomplete downloads are saved| +| Command Line | Environment Variable | Description | +| ----------------- | -------------------- | --------------------------------------------- | +| `-o\|--downloads` | `DOWNLOADS_DIR` | The path where downloaded files are saved | +| `--incomplete` | `INCOMPLETE_DIR` | The path where incomplete downloads are saved | #### **YAML** ```yaml @@ -133,9 +133,9 @@ Aliases: * Must be at least 1 character in length * Must not contain path separators (`\` or `/`) -|Command Line|Environment Variable|Description| -|----|-----|-----------| -|`-s\|--shared`|`SHARED_DIR`|The list of paths to shared files| +| Command Line | Environment Variable | Description | +| -------------- | -------------------- | --------------------------------- | +| `-s\|--shared` | `SHARED_DIR` | The list of paths to shared files | #### **YAML** ```yaml @@ -152,12 +152,12 @@ Global limits behave as a hard limit, additive across all groups. These values A change to slot limits require an application restart to take effect, while speed limits can be adjusted at runtime. -|Command Line|Environment Variable|Description| -|----|-----|-----------| -|`--upload-slots`|`UPLOAD_SLOTS`|The limit for the total number of upload slots| -|`--upload-speed-limit`|`UPLOAD_SPEED_LIMIT`|The total upload speed limit| -|`--download-slots`|`DOWNLOAD_SLOTS`|The limit for the total number of download slots| -|`--download-speed-limit`|`DOWNLOAD_SPEED_LIMIT`|The total download speed limit| +| Command Line | Environment Variable | Description | +| ------------------------ | ---------------------- | ------------------------------------------------ | +| `--upload-slots` | `UPLOAD_SLOTS` | The limit for the total number of upload slots | +| `--upload-speed-limit` | `UPLOAD_SPEED_LIMIT` | The total upload speed limit | +| `--download-slots` | `DOWNLOAD_SLOTS` | The limit for the total number of download slots | +| `--download-speed-limit` | `DOWNLOAD_SPEED_LIMIT` | The total download speed limit | #### **YAML** ```yaml @@ -193,13 +193,13 @@ upload: ## Built-In Groups -The `default` built-in group contains all users that have not been explicitly added to a user defined group, are not priviledged, and that haven't been identified as leechers. +The `default` built-in group contains all users that have not been explicitly added to a user defined group, are not privileged, and that haven't been identified as leechers. The `leechers` built-in group contains users that have been identified as leechers. -The `priviledged` built-in is used to prioritize users who have purchased priviledges on the Soulseek network. This groups is not configurable, has a priority of 0 (the highest), a strategy of `FirstInFirstOut`, and can use any number of slots, up to the global limit. +The `privileged` built-in is used to prioritize users who have purchased privileges on the Soulseek network. This groups is not configurable, has a priority of 0 (the highest), a strategy of `FirstInFirstOut`, and can use any number of slots, up to the global limit. -It is not possible to explicitly assign users to built-in groups, but the priority, number of slots, speed and queue strategy can be adjusted (excluding `priviledged`). +It is not possible to explicitly assign users to built-in groups, but the priority, number of slots, speed and queue strategy can be adjusted (excluding `privileged`). #### **YAML** ```yaml @@ -224,7 +224,7 @@ Any number of user defined groups can be added under the `user_defined` key in t User defined groups use the same configuration as built-in groups, but additionally allow a list of `members` containing the usernames of the users assigned to the group. -Users can be assigned to multiple groups, with their effective group being the highest priority (lowest numbered) group. If a user has priviledges on the network, any explicit group membership is superceded, and their effective group is the built-in `priviledged` group. If a user is explcitly assigned to a group, they will not be identified as a leecher. +Users can be assigned to multiple groups, with their effective group being the highest priority (lowest numbered) group. If a user has privileges on the network, any explicit group membership is superceded, and their effective group is the built-in `privileged` group. If a user is explcitly assigned to a group, they will not be identified as a leecher. #### **YAML*** ```yaml @@ -292,10 +292,10 @@ Changing either of these values requires the server connection to be reset. The password field is not included when serializing options to Json or YAML to avoid inadvertently exposing the value. -|Command Line|Environment Variable|Description| -|----|-----|-----------| -|`--slsk-username`|`SLSK_USERNAME`|The username for the Soulseek network| -|`--slsk-password`|`SLSK_PASSWORD`|The password for the Soulseek network| +| Command Line | Environment Variable | Description | +| ----------------- | -------------------- | ------------------------------------- | +| `--slsk-username` | `SLSK_USERNAME` | The username for the Soulseek network | +| `--slsk-password` | `SLSK_PASSWORD` | The password for the Soulseek network | #### **YAML** ```yaml @@ -314,11 +314,11 @@ Child connections should generally only be disabled on low spec systems or situa Changing these values may require the server connection to be reset, depending on the current state. -|Command Line|Environment Variable|Description| -|----|-----|-----------| -|`--slsk-no-dnet`|`SLSK_NO_DNET`|Determines whether the distributed network is disabled. If disabled, the client will not obtain a parent or any child connections, and will not receive distributed search requests.| -|`--slsk-dnet-no-children`|`SLSK_DNET_NO_CHILDREN`|Determines whether to disallow distributed children| -|`--slsk-dnet-children`|`SLSK_DNET_CHILDREN`|The maximum number of distributed children to accept| +| Command Line | Environment Variable | Description | +| ------------------------- | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `--slsk-no-dnet` | `SLSK_NO_DNET` | Determines whether the distributed network is disabled. If disabled, the client will not obtain a parent or any child connections, and will not receive distributed search requests. | +| `--slsk-dnet-no-children` | `SLSK_DNET_NO_CHILDREN` | Determines whether to disallow distributed children | +| `--slsk-dnet-children` | `SLSK_DNET_CHILDREN` | The maximum number of distributed children to accept | #### **YAML** ```yaml @@ -337,9 +337,9 @@ As with any other Soulseek client, properly configuring the listen port and port Symptoms of a misconfigured listen port include poor search results and inability to browse or retrieve user information for some users. -|Command Line|Environment Variable|Description| -|----|-----|-----------| -|`--slsk-listen-port`|`SLSK_LISTEN_PORT`|The port on which to listen for incoming connections| +| Command Line | Environment Variable | Description | +| -------------------- | -------------------- | ---------------------------------------------------- | +| `--slsk-listen-port` | `SLSK_LISTEN_PORT` | The port on which to listen for incoming connections | #### **YAML** ```yaml @@ -357,10 +357,10 @@ Higher connect timeout values will help ensure that operations (browse, download Inactivity timeouts help the application determine when a distributed parent connection has stopped sending data, and when connections that have delivered search results (and are unlikely to be used further) from remaining open longer than needed. Reducing this timeout can help on low spec systems if port exhaustion is a concern, but may result in the application "hunting" for a distributed parent connection needlessly. -|Command Line|Environment Variable|Description| -|----|-----|-----------| -|`--slsk-connection-timeout`|`SLSK_CONNECTION_TIMEOUT`|The connection timeout value, in milliseconds| -|`--slsk-inactivity-timeout`|`SLSK_INACTIVITY_TIMEOUT`|The connection inactivity value, in milliseconds| +| Command Line | Environment Variable | Description | +| --------------------------- | ------------------------- | ------------------------------------------------ | +| `--slsk-connection-timeout` | `SLSK_CONNECTION_TIMEOUT` | The connection timeout value, in milliseconds | +| `--slsk-inactivity-timeout` | `SLSK_INACTIVITY_TIMEOUT` | The connection inactivity value, in milliseconds | #### **YAML** ```yaml @@ -381,12 +381,12 @@ The transfer buffer size is used for file transfers (both read and write), and t The write queue option is the hard limit for the number of concurrent writes for a connection. This generally only applies to distributed child connections, and prevents a memory leak if the application continues to try and send data after a connection has gone "bad". This value can be set as low as 5 if memory is a constraint, though the default has been tested extensively and should be good for most scenarios, including low spec. -|Command Line|Environment Variable|Description| -|----|-----|-----------| -|`--slsk-read-buffer`|`SLSK_READ_BUFFER`|The connection read buffer size, in bytes| -|`--slsk-write-buffer`|`SLSK_WRITE_BUFFER`|The connection write buffer size, in bytes| -|`--slsk-transfer-buffer`|`SLSK_TRANSFER_BUFFER`|The read/write buffer size for transfers, in bytes| -|`--slsk-write-queue`|`SLSK_WRITE_QUEUE`|The connection write buffer size, in bytes| +| Command Line | Environment Variable | Description | +| ------------------------ | ---------------------- | -------------------------------------------------- | +| `--slsk-read-buffer` | `SLSK_READ_BUFFER` | The connection read buffer size, in bytes | +| `--slsk-write-buffer` | `SLSK_WRITE_BUFFER` | The connection write buffer size, in bytes | +| `--slsk-transfer-buffer` | `SLSK_TRANSFER_BUFFER` | The read/write buffer size for transfers, in bytes | +| `--slsk-write-queue` | `SLSK_WRITE_QUEUE` | The connection write buffer size, in bytes | #### **YAML** ```yaml @@ -405,13 +405,13 @@ Connections can optionally use a SOCKS5 proxy, with or without username and pass If the proxy is enabled, an address and port must also be specified. -|Command Line|Environment Variable|Description| -|----|-----|-----------| -|`--slsk-proxy`|`SLSK_PROXY`|Determines whether a proxy is to be used| -|`--slsk-proxy-address`|`SLSK_PROXY_ADDRESS`|The proxy address| -|`--slsk-proxy-port`|`SLSK_PROXY_PORT`|The proxy port| -|`--slsk-proxy-username`|`SLSK_PROXY_USERNAME`|The proxy username, if applicable| -|`--slsk-proxy-password`|`SLSK_PROXY_PASSWORD`|The proxy password, if applicable| +| Command Line | Environment Variable | Description | +| ----------------------- | --------------------- | ---------------------------------------- | +| `--slsk-proxy` | `SLSK_PROXY` | Determines whether a proxy is to be used | +| `--slsk-proxy-address` | `SLSK_PROXY_ADDRESS` | The proxy address | +| `--slsk-proxy-port` | `SLSK_PROXY_PORT` | The proxy port | +| `--slsk-proxy-username` | `SLSK_PROXY_USERNAME` | The proxy username, if applicable | +| `--slsk-proxy-password` | `SLSK_PROXY_PASSWORD` | The proxy password, if applicable | #### **YAML** ```yaml @@ -429,9 +429,9 @@ soulseek: The diagnostic level option is passed to the Soulseek.NET configuration, and determines the level of detail at which the library produces diagnostic messages. This should generally be left set to `Info` or `Warning`, but can be set to `Debug` if more verbose logging is desired. -|Command Line|Environment Variable|Description| -|----|-----|-----------| -|`--slsk-diag-level`|`SLSK_DIAG_LEVEL`|The minimum diagnostic level (None, Warning, Info, Debug)| +| Command Line | Environment Variable | Description | +| ------------------- | -------------------- | --------------------------------------------------------- | +| `--slsk-diag-level` | `SLSK_DIAG_LEVEL` | The minimum diagnostic level (None, Warning, Info, Debug) | #### **YAML** ```yaml @@ -451,12 +451,12 @@ The content path can be used to force the application to serve static web conten Logging of HTTP requests is disabled by default. -|Command Line|Environment Variable|Description| -|----|-----|-----------| -|`-l\|--http-port`|`HTTP_PORT`|The HTTP listen port| -|`--url-base`|`URL_BASE`|The base url for web requests| -|`--content-path`|`CONTENT_PATH`|The path to static web content| -|`--http-logging`|`HTTP_LOGGING`|Determines whether HTTP requests are to be logged| +| Command Line | Environment Variable | Description | +| ----------------- | -------------------- | ------------------------------------------------- | +| `-l\|--http-port` | `HTTP_PORT` | The HTTP listen port | +| `--url-base` | `URL_BASE` | The base url for web requests | +| `--content-path` | `CONTENT_PATH` | The path to static web content | +| `--http-logging` | `HTTP_LOGGING` | Determines whether HTTP requests are to be logged | #### **YAML** ```yaml @@ -475,12 +475,12 @@ By default, the application generates a new, self-signed X509 certificate at eac The application can produce a self-signed `.pfx` file and random password using the `--generate-cert` command. -|Command Line|Environment Variable|Description| -|----|-----|-----------| -|`-L\|--https-port`|`HTTPS_PORT`|The HTTPS listen port| -|`-f\|--force-https`|`HTTPS_FORCE`|Determines whether HTTP requests are to be redirected to HTTPS| -|`--https-cert-pfx`|`HTTPS_CERT_PFX`|The path to the X509 certificate .pfx file| -|`--https-cert-password`|`HTTPS_CERT_PASSWORD`|The password for the X509 certificate| +| Command Line | Environment Variable | Description | +| ----------------------- | --------------------- | -------------------------------------------------------------- | +| `-L\|--https-port` | `HTTPS_PORT` | The HTTPS listen port | +| `-f\|--force-https` | `HTTPS_FORCE` | Determines whether HTTP requests are to be redirected to HTTPS | +| `--https-cert-pfx` | `HTTPS_CERT_PFX` | The path to the X509 certificate .pfx file | +| `--https-cert-password` | `HTTPS_CERT_PASSWORD` | The password for the X509 certificate | #### **YAML** ```yaml @@ -501,13 +501,13 @@ By default, a random JWT secret key is generated at each start. This is conveni The JWT TTL option determines how long issued JWTs are valid, defaulting to 7 days. -|Command Line|Environment Variable|Description| -|----|-----|-----------| -|`-X\|--no-auth`|`NO_AUTH`|Determines whether authentication is to be disabled| -|`-u\|--username`|`USERNAME`|The username for the web UI| -|`-p\|--password`|`PASSWORD`|The password for the web UI| -|`--jwt-key`|`JWT_KEY`|The secret key used to sign JWTs| -|`--jwt-ttl`|`JWT_TTL`|The TTL (duration) of JWTs, in milliseconds| +| Command Line | Environment Variable | Description | +| ---------------- | -------------------- | --------------------------------------------------- | +| `-X\|--no-auth` | `NO_AUTH` | Determines whether authentication is to be disabled | +| `-u\|--username` | `USERNAME` | The username for the web UI | +| `-p\|--password` | `PASSWORD` | The password for the web UI | +| `--jwt-key` | `JWT_KEY` | The secret key used to sign JWTs | +| `--jwt-ttl` | `JWT_TTL` | The TTL (duration) of JWTs, in milliseconds | #### **YAML** ```yaml @@ -527,9 +527,9 @@ A number of filters can be configured to control various aspects of how the appl The share filters can be used to prevent certain types of files from being shared. This option is an array that can take any number of filters. Filters must be a valid regular expression; a few examples are included below and in the example configuration included with the application, but the list is empty by default. -|Command Line|Environment Variable|Description| -|----|-----|-----------| -|`--share-filter`|`SHARE_FILTER`|A list of regular expressions used to filter files from shares| +| Command Line | Environment Variable | Description | +| ---------------- | -------------------- | -------------------------------------------------------------- | +| `--share-filter` | `SHARE_FILTER` | A list of regular expressions used to filter files from shares | #### **YAML** ```yaml @@ -548,19 +548,19 @@ Files can be uploaded to a remote FTP server upon completion. Files are uploade Uploads are attempted up to the maximum configured retry count, and then discarded. -|Command Line|Environment Variable|Description| -|----|-----|-----------| -|`--ftp`|`FTP`|Determines whether FTP integration is enabled| -|`--ftp-address`|`FTP_ADDRESS`|The FTP address| -|`--ftp-port`|`FTP_PORT`|The FTP port| -|`--ftp-username`|`FTP_USERNAME`|The FTP username| -|`--ftp-password`|`FTP_PASSWORD`|The FTP password| -|`--ftp-remote-path`|`FTP_REMOTE_PATH`|The remote path for uploads| -|`--ftp-encryption-mode`|`FTP_ENCRYPTION_MODE`|The FTP encryption mode (none, implicit, explicit, auto)| -|`--ftp-ignore-certificate-errors`|`FTP_IGNORE_CERTIFICATE_ERRORS`|Determines whether to ignore FTP certificate errors| -|`--ftp-overwrite-existing`|`FTP_OVERWRITE_EXISTING`|Determines whether existing files should be overwritten| -|`--ftp-connection-timeout`|`FTP_CONNECTION_TIMEOUT`|The connection timeout value, in milliseconds| -|`--ftp-retry-attempts`|`FTP_RETRY_ATTEMPTS`|The number of times failing uploads will be retried| +| Command Line | Environment Variable | Description | +| --------------------------------- | ------------------------------- | -------------------------------------------------------- | +| `--ftp` | `FTP` | Determines whether FTP integration is enabled | +| `--ftp-address` | `FTP_ADDRESS` | The FTP address | +| `--ftp-port` | `FTP_PORT` | The FTP port | +| `--ftp-username` | `FTP_USERNAME` | The FTP username | +| `--ftp-password` | `FTP_PASSWORD` | The FTP password | +| `--ftp-remote-path` | `FTP_REMOTE_PATH` | The remote path for uploads | +| `--ftp-encryption-mode` | `FTP_ENCRYPTION_MODE` | The FTP encryption mode (none, implicit, explicit, auto) | +| `--ftp-ignore-certificate-errors` | `FTP_IGNORE_CERTIFICATE_ERRORS` | Determines whether to ignore FTP certificate errors | +| `--ftp-overwrite-existing` | `FTP_OVERWRITE_EXISTING` | Determines whether existing files should be overwritten | +| `--ftp-connection-timeout` | `FTP_CONNECTION_TIMEOUT` | The connection timeout value, in milliseconds | +| `--ftp-retry-attempts` | `FTP_RETRY_ATTEMPTS` | The number of times failing uploads will be retried | #### **YAML** ```yaml @@ -589,15 +589,15 @@ The Pushbullet integration is one-way, meaning the application has no way of kno Notification API calls are made up to the maximum configured retry count, and then discarded. -|Command Line|Environment Variable|Description| -|----|-----|-----------| -|`--pushbullet`|`PUSHBULLET`|Determines whether Pushbullet integration is enabled| -|`--pushbullet-token`|`PUSHBULLET_TOKEN`|The Pushbullet API access token| -|`--pushbullet-prefix`|`PUSHBULLET_PREFIX`|The prefix for notification titles| -|`--pushbullet-notify-on-pm`|`PUSHBULLET_NOTIFY_ON_PRIVATE_MESSAGE`|Determines whether to send a notification when a private message is received| -|`--pushbullet-notify-on-room-mention`|`PUSHBULLET_NOTIFY_ON_ROOM_MENTION`|Determines whether to send a notification when the current user's name is mentioned in a chat room| -|`--pushbullet-retry-attempts`|`PUSHBULLET_RETRY_ATTEMPTS`|The number of times failing API calls will be retried| -|`--pushbullet-cooldown`|`PUSHBULLET_COOLDOWN_TIME`|The cooldown time for notifications, in milliseconds| +| Command Line | Environment Variable | Description | +| ------------------------------------- | -------------------------------------- | -------------------------------------------------------------------------------------------------- | +| `--pushbullet` | `PUSHBULLET` | Determines whether Pushbullet integration is enabled | +| `--pushbullet-token` | `PUSHBULLET_TOKEN` | The Pushbullet API access token | +| `--pushbullet-prefix` | `PUSHBULLET_PREFIX` | The prefix for notification titles | +| `--pushbullet-notify-on-pm` | `PUSHBULLET_NOTIFY_ON_PRIVATE_MESSAGE` | Determines whether to send a notification when a private message is received | +| `--pushbullet-notify-on-room-mention` | `PUSHBULLET_NOTIFY_ON_ROOM_MENTION` | Determines whether to send a notification when the current user's name is mentioned in a chat room | +| `--pushbullet-retry-attempts` | `PUSHBULLET_RETRY_ATTEMPTS` | The number of times failing API calls will be retried | +| `--pushbullet-cooldown` | `PUSHBULLET_COOLDOWN_TIME` | The cooldown time for notifications, in milliseconds | #### **YAML** ```yaml @@ -618,9 +618,9 @@ integration: The instance name uniquely identifies the running instance of the application. This is primarily useful for structured logging in cases where multiple instances are logging to the same remote source. -|Command Line|Environment Variable|Description| -|----|-----|-----------| -|`-i\|--instance-name`|`INSTANCE_NAME`|The unique name for the running instance| +| Command Line | Environment Variable | Description | +| --------------------- | -------------------- | ---------------------------------------- | +| `-i\|--instance-name` | `INSTANCE_NAME` | The unique name for the running instance | #### **YAML** ```yaml @@ -633,9 +633,9 @@ The application logs to disk (`/logs` in the application directory) by default. The current list of available targets is: -|Command Line|Environment Variable|Description| -|----|-----|-----------| -|`--loki`|`LOKI`|The URL to a Grafana Loki instance| +| Command Line | Environment Variable | Description | +| ------------ | -------------------- | ---------------------------------- | +| `--loki` | `LOKI` | The URL to a Grafana Loki instance | #### **YAML** ```yaml @@ -651,10 +651,10 @@ The application can publish Prometheus metrics to `/metrics` using [prometheus-n The application can publish a Swagger (OpenAPI) definition and host SwaggerUI at `/swagger` using [Swashbuckle](https://github.com/domaindrivendev/Swashbuckle.AspNetCore). This is useful for anyone developing against the application API and/or creating a new web interface. -|Command Line|Environment Variable|Description| -|----|-----|-----------| -|`--prometheus`|`PROMETHEUS`|Determines whether Prometheus metrics are published to `/metrics`| -|`--swagger`|`SWAGGER`|Determines whether Swagger (OpenAPI) definitions and UI should be available at `/swagger`| +| Command Line | Environment Variable | Description | +| -------------- | -------------------- | ----------------------------------------------------------------------------------------- | +| `--prometheus` | `PROMETHEUS` | Determines whether Prometheus metrics are published to `/metrics` | +| `--swagger` | `SWAGGER` | Determines whether Swagger (OpenAPI) definitions and UI should be available at `/swagger` | #### **YAML** ```yaml @@ -667,22 +667,22 @@ feature: A number of additional feature flags are provided to change the runtime behavior of the application, which is useful during development. Available feature flags are: -|Flag|Environment Variable|Description| -|----|-----|-----------| -|`-d\|--debug`|`DEBUG`|Run the application in debug mode. Produces verbose log output.| -|`-n\|--no-logo`|`NO_LOGO`|Don't show the application logo on startup| -|`-x\|--no-start`|`NO_START`|Bootstrap the application, but don't start| -|`--no-connect`|`NO_CONNECT`|Start the application, but don't connect to the server| -|`--no-share-scan`|`NO_SHARE_SCAN`|Don't perform a scan of shared directories on startup| -|`--no-version-check`|`NO_VERSION_CHECK`|Don't perform a version check on startup| +| Flag | Environment Variable | Description | +| -------------------- | -------------------- | ---------------------------------------------------------------- | +| `-d\|--debug` | `DEBUG` | Run the application in debug mode. Produces verbose log output. | +| `-n\|--no-logo` | `NO_LOGO` | Don't show the application logo on startup | +| `-x\|--no-start` | `NO_START` | Bootstrap the application, but don't start | +| `--no-connect` | `NO_CONNECT` | Start the application, but don't connect to the server | +| `--no-share-scan` | `NO_SHARE_SCAN` | Don't perform a scan of shared directories on startup | +| `--no-version-check` | `NO_VERSION_CHECK` | Don't perform a version check on startup | # Commands The application can be run in "command mode", causing it to execute a command and then quit immediately. Available commands are: -|Command|Description| -|-------|-----------| -|`-v\|--version`|Display the current application version| -|`-h\|--help`|Display available command-line arguments| -|`-e\|--envars`|Display available environment variables| -|`-g\|--generate-cert`|Generate an X509 certificate and password for HTTPS| \ No newline at end of file +| Command | Description | +| --------------------- | --------------------------------------------------- | +| `-v\|--version` | Display the current application version | +| `-h\|--help` | Display available command-line arguments | +| `-e\|--envars` | Display available environment variables | +| `-g\|--generate-cert` | Generate an X509 certificate and password for HTTPS | \ No newline at end of file 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() diff --git a/tests/slskd.Tests.Unit/Transfers/Uploads/UploadGovernorTests.cs b/tests/slskd.Tests.Unit/Transfers/Uploads/UploadGovernorTests.cs index 0e030f27..6824f55e 100644 --- a/tests/slskd.Tests.Unit/Transfers/Uploads/UploadGovernorTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/Uploads/UploadGovernorTests.cs @@ -20,7 +20,7 @@ var buckets = governor.GetProperty>("TokenBuckets"); Assert.Equal(3, buckets.Count); - Assert.True(buckets.ContainsKey(Application.PriviledgedGroup)); + Assert.True(buckets.ContainsKey(Application.PrivilegedGroup)); Assert.True(buckets.ContainsKey(Application.DefaultGroup)); Assert.True(buckets.ContainsKey(Application.LeecherGroup)); } @@ -126,7 +126,7 @@ // mock the default bucket var bucket = new Mock(); governor.SetProperty("TokenBuckets", new Dictionary() - { + { { Application.DefaultGroup, bucket.Object }, }); diff --git a/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs b/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs index 9b0fba72..4722906f 100644 --- a/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs @@ -23,7 +23,7 @@ var groups = queue.GetProperty>("Groups"); Assert.Equal(3, groups.Count); - Assert.True(groups.ContainsKey(Application.PriviledgedGroup)); + Assert.True(groups.ContainsKey(Application.PrivilegedGroup)); Assert.True(groups.ContainsKey(Application.DefaultGroup)); Assert.True(groups.ContainsKey(Application.LeecherGroup)); } @@ -35,9 +35,9 @@ var groups = queue.GetProperty>("Groups"); - var p = groups[Application.PriviledgedGroup]; + var p = groups[Application.PrivilegedGroup]; - Assert.Equal(Application.PriviledgedGroup, p.Name); + Assert.Equal(Application.PrivilegedGroup, p.Name); Assert.Equal(0, p.Priority); Assert.Equal(new Options().Global.Upload.Slots, p.Slots); Assert.Equal(0, p.UsedSlots); @@ -522,7 +522,7 @@ { var (queue, mocks) = GetFixture(); - mocks.UserService.Setup(m => m.GetGroup(user1)).Returns(Application.PriviledgedGroup); + mocks.UserService.Setup(m => m.GetGroup(user1)).Returns(Application.PrivilegedGroup); var uploads = new ConcurrentDictionary>(); @@ -538,7 +538,7 @@ Assert.Equal(user1, result.Username); Assert.Equal(file1, result.Filename); Assert.NotNull(result.Started); - Assert.Equal(Application.PriviledgedGroup, result.Group); + Assert.Equal(Application.PrivilegedGroup, result.Group); } [Theory, AutoData] @@ -546,7 +546,7 @@ { var (queue, mocks) = GetFixture(); - mocks.UserService.Setup(m => m.GetGroup(user1)).Returns(Application.PriviledgedGroup); + mocks.UserService.Setup(m => m.GetGroup(user1)).Returns(Application.PrivilegedGroup); var uploads = new ConcurrentDictionary>(); @@ -561,7 +561,7 @@ var groups = queue.GetProperty>("Groups"); - Assert.Equal(1, groups[Application.PriviledgedGroup].UsedSlots); + Assert.Equal(1, groups[Application.PrivilegedGroup].UsedSlots); } [Theory, AutoData] @@ -569,7 +569,7 @@ { var (queue, mocks) = GetFixture(); - mocks.UserService.Setup(m => m.GetGroup(user1)).Returns(Application.PriviledgedGroup); + mocks.UserService.Setup(m => m.GetGroup(user1)).Returns(Application.PrivilegedGroup); mocks.UserService.Setup(m => m.GetGroup(user2)).Returns(Application.DefaultGroup); var uploads = new ConcurrentDictionary>(); -- 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(-) 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(+) 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(+) 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(-) 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(-) 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 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(+) 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(-) 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(-) 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 ec45797a56752852d0ff8acba64efe7a48618e50 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 21 Feb 2022 15:06:51 -0600 Subject: fix tests --- tests/slskd.Tests.Unit/Users/UserServiceTests.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/slskd.Tests.Unit/Users/UserServiceTests.cs b/tests/slskd.Tests.Unit/Users/UserServiceTests.cs index 49f1f530..8e8f6106 100644 --- a/tests/slskd.Tests.Unit/Users/UserServiceTests.cs +++ b/tests/slskd.Tests.Unit/Users/UserServiceTests.cs @@ -125,6 +125,7 @@ var mocks = new Mocks(options); var service = new UserService( mocks.SoulseekClient.Object, + mocks.StateMutator.Object, mocks.ContextFactory.Object, mocks.OptionsMonitor); @@ -139,6 +140,7 @@ } public Mock SoulseekClient { get; } = new Mock(); + public Mock> StateMutator { get; } = new Mock>(); public Mock> ContextFactory { get; } = new Mock>(); public TestOptionsMonitor OptionsMonitor { get; init; } } -- 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(-) 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(-) 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(-) 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 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(+) 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(-) 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(-) 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(-) 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