From a73633f5fc421b4f3f14536867aa2f24914cd4c4 Mon Sep 17 00:00:00 2001 From: WinnerWind Date: Mon, 3 Nov 2025 17:05:32 +0530 Subject: Add reverse proxy instructions to README --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index ab6a2485..e23bea3f 100644 --- a/README.md +++ b/README.md @@ -97,3 +97,6 @@ An application directory will be created in either `~/.local/share/slskd` (on Li Once running, log in to the web UI using the default username `slskd` and password `slskd` to complete the configuration. Detailed documentation for configuration options can be found [here](https://github.com/slskd/slskd/blob/master/docs/config.md), and an example of the YAML configuration file can be reviewed [here](https://github.com/slskd/slskd/blob/master/config/slskd.example.yml). + +## Reverse Proxy +SLSKD may require extra configuration when running it behind a reverse proxy. Refer [here](https://github.com/slskd/slskd/blob/master/docs/reverse_proxy.md) for a short guide. -- cgit v1.2.3 From 865fcbc4fed85e9eac58125092838f08dbd55430 Mon Sep 17 00:00:00 2001 From: xovi Date: Wed, 26 Nov 2025 15:23:43 +0100 Subject: Added configurable ip address for the Web GUI (useful for ipv6 only users) --- config/slskd.example.yml | 2 ++ src/slskd/Core/Options.cs | 22 +++++++++++++++++++++- src/slskd/Program.cs | 10 ++++++---- 3 files changed, 29 insertions(+), 5 deletions(-) diff --git a/config/slskd.example.yml b/config/slskd.example.yml index a0ca4f3f..f923afbf 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -137,10 +137,12 @@ # - ^.{1,2}$ # web: # port: 5030 +# listen_ip_address: 0.0.0.0 # socket: ~ # https: # disabled: false # port: 5031 +# listen_ip_address: 0.0.0.0 # force: false # certificate: # pfx: ~ diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 254adcab..ab08be04 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1832,6 +1832,16 @@ namespace slskd [RequiresRestart] public int Port { get; init; } = 5030; + /// + /// Gets the IP address on which to listen for HTTP requests. + /// + [Argument(default, "http-listen-ip-address")] + [EnvironmentVariable("HTTP_LISTEN_IP_ADDRESS")] + [Description("IP address on which to listen for HTTP requests")] + [IPAddress] + [RequiresRestart] + public string ListenIpAddress { get; init; } = "0.0.0.0"; + /// /// Gets the HTTP listen unix domain socket (UDS) path. /// @@ -2032,7 +2042,17 @@ namespace slskd [Range(1, 65535)] [RequiresRestart] public int Port { get; init; } = 5031; - + + /// + /// Gets the IP address on which to listen for HTTPS requests. + /// + [Argument(default, "https-listen-ip-address")] + [EnvironmentVariable("HTTPS_LISTEN_IP_ADDRESS")] + [Description("IP address on which to listen for HTTPS requests")] + [IPAddress] + [RequiresRestart] + public string ListenIpAddress { get; init; } = "0.0.0.0"; + /// /// Gets a value indicating whether HTTP requests should be redirected to HTTPS. /// diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 6b50aedb..e693db63 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -474,8 +474,9 @@ namespace slskd .UseUrls() .UseKestrel(options => { - Log.Information($"Listening for HTTP requests at http://{IPAddress.Any}:{OptionsAtStartup.Web.Port}/"); - options.Listen(IPAddress.Any, OptionsAtStartup.Web.Port); + var httpIpAddress = IPAddress.Parse(OptionsAtStartup.Web.ListenIpAddress); + Log.Information($"Listening for HTTP requests at http://{httpIpAddress}:{OptionsAtStartup.Web.Port}/"); + options.Listen(httpIpAddress, OptionsAtStartup.Web.Port); if (OptionsAtStartup.Web.Socket != null) { @@ -485,8 +486,9 @@ namespace slskd if (!OptionsAtStartup.Web.Https.Disabled) { - Log.Information($"Listening for HTTPS requests at https://{IPAddress.Any}:{OptionsAtStartup.Web.Https.Port}/"); - options.Listen(IPAddress.Any, OptionsAtStartup.Web.Https.Port, listenOptions => + var httpsIpAddress = IPAddress.Parse(OptionsAtStartup.Web.Https.ListenIpAddress); + Log.Information($"Listening for HTTPS requests at https://{httpsIpAddress}:{OptionsAtStartup.Web.Https.Port}/"); + options.Listen(httpsIpAddress, OptionsAtStartup.Web.Https.Port, listenOptions => { var cert = OptionsAtStartup.Web.Https.Certificate; -- cgit v1.2.3 From 90779a98863f95672841451febbf22b0e119ee41 Mon Sep 17 00:00:00 2001 From: xovi Date: Wed, 3 Dec 2025 12:14:37 +0100 Subject: Added Documentation --- docs/config.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/config.md b/docs/config.md index 2646dd94..55505111 100644 --- a/docs/config.md +++ b/docs/config.md @@ -809,6 +809,7 @@ Logging of HTTP requests is disabled by default. | Command-Line | Environment Variable | Description | | ----------------- | -------------------------- | ------------------------------------------------- | | `-l\|--http-port` | `SLSKD_HTTP_PORT` | The HTTP listen port | +| `--http-listen-ip-address` | `SLSKD_HTTP_LISTEN_IP_ADDRESS` | The IP address on which to listen for HTTP requests | | `--http-socket` | `SLSKD_HTTP_SOCKET` | The HTTP listen unix domain socket (UDS) path | | `--url-base` | `SLSKD_URL_BASE` | The base url for web requests | | `--content-path` | `SLSKD_CONTENT_PATH` | The path to static web content | @@ -835,6 +836,7 @@ The application can produce a self-signed `.pfx` file and random password using | Command-Line | Environment Variable | Description | | ----------------------- | --------------------------- | -------------------------------------------------------------- | | `-L\|--https-port` | `SLSKD_HTTPS_PORT` | The HTTPS listen port | +| `--https-listen-ip-address` | `SLSKD_HTTPS_LISTEN_IP_ADDRESS` | The IP address on which to listen for HTTPS requests | | `-f\|--force-https` | `SLSKD_HTTPS_FORCE` | Determines whether HTTP requests are to be redirected to HTTPS | | `--https-cert-pfx` | `SLSKD_HTTPS_CERT_PFX` | The path to the X509 certificate .pfx file | | `--https-cert-password` | `SLSKD_HTTPS_CERT_PASSWORD` | The password for the X509 certificate | -- cgit v1.2.3 From 49514db326bef9cf21a1e84f3c1e13934b4c3a9a Mon Sep 17 00:00:00 2001 From: xovi Date: Wed, 3 Dec 2025 12:21:10 +0100 Subject: Corrected markdown tables alignment --- docs/config.md | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/docs/config.md b/docs/config.md index 55505111..c0a545f9 100644 --- a/docs/config.md +++ b/docs/config.md @@ -806,14 +806,14 @@ 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` | `SLSKD_HTTP_PORT` | The HTTP listen port | +| Command-Line | Environment Variable | Description | +| -------------------------- | ------------------------------ | --------------------------------------------------- | +| `-l\|--http-port` | `SLSKD_HTTP_PORT` | The HTTP listen port | | `--http-listen-ip-address` | `SLSKD_HTTP_LISTEN_IP_ADDRESS` | The IP address on which to listen for HTTP requests | -| `--http-socket` | `SLSKD_HTTP_SOCKET` | The HTTP listen unix domain socket (UDS) path | -| `--url-base` | `SLSKD_URL_BASE` | The base url for web requests | -| `--content-path` | `SLSKD_CONTENT_PATH` | The path to static web content | -| `--http-logging` | `SLSKD_HTTP_LOGGING` | Determines whether HTTP requests are to be logged | +| `--http-socket` | `SLSKD_HTTP_SOCKET` | The HTTP listen unix domain socket (UDS) path | +| `--url-base` | `SLSKD_URL_BASE` | The base url for web requests | +| `--content-path` | `SLSKD_CONTENT_PATH` | The path to static web content | +| `--http-logging` | `SLSKD_HTTP_LOGGING` | Determines whether HTTP requests are to be logged | #### **YAML** ```yaml @@ -833,14 +833,14 @@ 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` | `SLSKD_HTTPS_PORT` | The HTTPS listen port | -| `--https-listen-ip-address` | `SLSKD_HTTPS_LISTEN_IP_ADDRESS` | The IP address on which to listen for HTTPS requests | -| `-f\|--force-https` | `SLSKD_HTTPS_FORCE` | Determines whether HTTP requests are to be redirected to HTTPS | -| `--https-cert-pfx` | `SLSKD_HTTPS_CERT_PFX` | The path to the X509 certificate .pfx file | -| `--https-cert-password` | `SLSKD_HTTPS_CERT_PASSWORD` | The password for the X509 certificate | -| `--no-https` | `SLSKD_NO_HTTPS` | Determines whether HTTPS is to be disabled | +| Command-Line | Environment Variable | Description | +| --------------------------- | ------------------------------- | -------------------------------------------------------------- | +| `-L\|--https-port` | `SLSKD_HTTPS_PORT` | The HTTPS listen port | +| `--https-listen-ip-address` | `SLSKD_HTTPS_LISTEN_IP_ADDRESS` | The IP address on which to listen for HTTPS requests | +| `-f\|--force-https` | `SLSKD_HTTPS_FORCE` | Determines whether HTTP requests are to be redirected to HTTPS | +| `--https-cert-pfx` | `SLSKD_HTTPS_CERT_PFX` | The path to the X509 certificate .pfx file | +| `--https-cert-password` | `SLSKD_HTTPS_CERT_PASSWORD` | The password for the X509 certificate | +| `--no-https` | `SLSKD_NO_HTTPS` | Determines whether HTTPS is to be disabled | #### **YAML** ```yaml -- cgit v1.2.3 -- cgit v1.2.3 From 736970deaf13b14ed7141558faee56f7200ab62a Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sun, 7 Dec 2025 00:13:45 +0000 Subject: Add graceful handling for Mutex creation failures in Program.cs Co-authored-by: jpdillingham <17145758+jpdillingham@users.noreply.github.com> --- src/slskd/Program.cs | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 6b50aedb..c51d07d8 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -237,7 +237,7 @@ namespace slskd private static IConfigurationRoot Configuration { get; set; } private static OptionsAtStartup OptionsAtStartup { get; } = new OptionsAtStartup(); private static ILogger Log { get; set; } = new ConsoleWriteLineLogger(); - private static Mutex Mutex { get; } = new Mutex(initiallyOwned: true, Compute.Sha256Hash(AppName)); + private static Mutex Mutex { get; set; } private static IDisposable DotNetRuntimeStats { get; set; } [Argument('g', "generate-cert", "generate X509 certificate and password for HTTPs")] @@ -335,10 +335,21 @@ namespace slskd // the application isn't being run in command mode. check the mutex to ensure // only one long-running instance. - if (!Mutex.WaitOne(millisecondsTimeout: 0, exitContext: false)) + try { - Log.Fatal($"An instance of {AppName} is already running"); - return; + Mutex = new Mutex(initiallyOwned: true, Compute.Sha256Hash(AppName)); + + if (!Mutex.WaitOne(millisecondsTimeout: 0, exitContext: false)) + { + Log.Fatal($"An instance of {AppName} is already running"); + return; + } + } + catch (Exception ex) + { + Log.Fatal($"Failed to acquire the application singleton mutex: {ex.Message}"); + Log.Warning("This can happen when running in a restricted environment (e.g., Kubernetes with readOnlyRootFilesystem)"); + Log.Warning("The application will continue, but multiple instances may be able to run simultaneously"); } // derive the application directory value and defaults that are dependent upon it -- cgit v1.2.3 From 1d09aef10a03fb4263a0e312c979d5a153fc9b31 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sun, 7 Dec 2025 00:16:04 +0000 Subject: Address code review feedback: use specific exceptions and dispose Mutex Co-authored-by: jpdillingham <17145758+jpdillingham@users.noreply.github.com> --- src/slskd/Program.cs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index c51d07d8..29783216 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -345,12 +345,18 @@ namespace slskd return; } } - catch (Exception ex) + catch (IOException ex) { Log.Fatal($"Failed to acquire the application singleton mutex: {ex.Message}"); Log.Warning("This can happen when running in a restricted environment (e.g., Kubernetes with readOnlyRootFilesystem)"); Log.Warning("The application will continue, but multiple instances may be able to run simultaneously"); } + catch (UnauthorizedAccessException ex) + { + Log.Fatal($"Failed to acquire the application singleton mutex: {ex.Message}"); + Log.Warning("This can happen when running with insufficient permissions"); + Log.Warning("The application will continue, but multiple instances may be able to run simultaneously"); + } // derive the application directory value and defaults that are dependent upon it AppDirectory ??= DefaultAppDirectory; @@ -551,6 +557,7 @@ namespace slskd } finally { + Mutex?.Dispose(); Serilog.Log.CloseAndFlush(); } } -- cgit v1.2.3 From 1f98acd90622a66f0ec4a88f5c0c60c8a1cdd332 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sun, 7 Dec 2025 00:17:24 +0000 Subject: Use Warning log level instead of Fatal for Mutex creation failures Co-authored-by: jpdillingham <17145758+jpdillingham@users.noreply.github.com> --- src/slskd/Program.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 29783216..098cc324 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -347,13 +347,13 @@ namespace slskd } catch (IOException ex) { - Log.Fatal($"Failed to acquire the application singleton mutex: {ex.Message}"); + Log.Warning($"Failed to acquire the application singleton mutex: {ex.Message}"); Log.Warning("This can happen when running in a restricted environment (e.g., Kubernetes with readOnlyRootFilesystem)"); Log.Warning("The application will continue, but multiple instances may be able to run simultaneously"); } catch (UnauthorizedAccessException ex) { - Log.Fatal($"Failed to acquire the application singleton mutex: {ex.Message}"); + Log.Warning($"Failed to acquire the application singleton mutex: {ex.Message}"); Log.Warning("This can happen when running with insufficient permissions"); Log.Warning("The application will continue, but multiple instances may be able to run simultaneously"); } -- cgit v1.2.3 From 4e02b95eeac1cdd3d49f0ca0177f9d59a76e9ce4 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sun, 7 Dec 2025 00:19:04 +0000 Subject: Add handling for AbandonedMutexException from WaitOne call Co-authored-by: jpdillingham <17145758+jpdillingham@users.noreply.github.com> --- src/slskd/Program.cs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 098cc324..bafac8b1 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -357,6 +357,13 @@ namespace slskd Log.Warning("This can happen when running with insufficient permissions"); Log.Warning("The application will continue, but multiple instances may be able to run simultaneously"); } + catch (AbandonedMutexException ex) + { + Log.Warning($"Acquired an abandoned mutex: {ex.Message}"); + Log.Warning("A previous instance may have terminated unexpectedly"); + + // The mutex is now owned by this thread, so we can continue + } // derive the application directory value and defaults that are dependent upon it AppDirectory ??= DefaultAppDirectory; -- cgit v1.2.3 From 0a66469fd81446b5d54becd049f8da90898cc85c Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sun, 7 Dec 2025 00:21:06 +0000 Subject: Fix Mutex logic and protect disposal from throwing exceptions Co-authored-by: jpdillingham <17145758+jpdillingham@users.noreply.github.com> --- src/slskd/Program.cs | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index bafac8b1..85cc4a3a 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -337,9 +337,10 @@ namespace slskd // only one long-running instance. try { - Mutex = new Mutex(initiallyOwned: true, Compute.Sha256Hash(AppName)); + bool createdNew; + Mutex = new Mutex(initiallyOwned: true, Compute.Sha256Hash(AppName), out createdNew); - if (!Mutex.WaitOne(millisecondsTimeout: 0, exitContext: false)) + if (!createdNew) { Log.Fatal($"An instance of {AppName} is already running"); return; @@ -564,7 +565,15 @@ namespace slskd } finally { - Mutex?.Dispose(); + try + { + Mutex?.Dispose(); + } + catch + { + // Ignore disposal errors to prevent masking other exceptions + } + Serilog.Log.CloseAndFlush(); } } -- cgit v1.2.3 From 4792270460293b4810e2e2a34f8deede39008502 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sun, 7 Dec 2025 00:22:19 +0000 Subject: Use explicit Exception type in Mutex disposal catch block Co-authored-by: jpdillingham <17145758+jpdillingham@users.noreply.github.com> --- src/slskd/Program.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 85cc4a3a..3bd0798b 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -569,7 +569,7 @@ namespace slskd { Mutex?.Dispose(); } - catch + catch (Exception) { // Ignore disposal errors to prevent masking other exceptions } -- cgit v1.2.3 -- cgit v1.2.3 From bb76ae9d10273d03fb9d4ae32ff618bb73f7d54d Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sun, 7 Dec 2025 00:43:52 +0000 Subject: Initial plan for adding sort functionality to Files view Co-authored-by: jpdillingham <17145758+jpdillingham@users.noreply.github.com> --- src/web/package-lock.json | 38 +------------------------------------- 1 file changed, 1 insertion(+), 37 deletions(-) diff --git a/src/web/package-lock.json b/src/web/package-lock.json index 5d0ae3d2..0fdcae0d 100644 --- a/src/web/package-lock.json +++ b/src/web/package-lock.json @@ -180,7 +180,6 @@ "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.23.9.tgz", "integrity": "sha512-5q0175NOjddqpvvzU+kDiSOAk4PfdO6FvwCWoQ6RO7rTzEe8vlo+4HVfcnAREhD4npMs0e9uZypjTwzZPCf/cw==", "dev": true, - "peer": true, "dependencies": { "@ampproject/remapping": "^2.2.0", "@babel/code-frame": "^7.23.5", @@ -226,7 +225,6 @@ "resolved": "https://registry.npmjs.org/@babel/eslint-parser/-/eslint-parser-7.23.10.tgz", "integrity": "sha512-3wSYDPZVnhseRnxRJH6ZVTNknBz76AEnyC+AYYhasjP3Yy23qz0ERR7Fcd2SHmYuSFJ2kY9gaaDd3vyqU09eSw==", "dev": true, - "peer": true, "dependencies": { "@nicolo-ribaudo/eslint-scope-5-internals": "5.1.1-v1", "eslint-visitor-keys": "^2.1.0", @@ -1005,7 +1003,6 @@ "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-flow/-/plugin-syntax-flow-7.22.5.tgz", "integrity": "sha512-9RdCl0i+q0QExayk2nOS7853w08yLucnnPML6EN9S8fgMPVtdLDCdx/cOQ/i44Lb9UeQX9A35yaqBBOMMZxPxQ==", "dev": true, - "peer": true, "dependencies": { "@babel/helper-plugin-utils": "^7.22.5" }, @@ -1880,7 +1877,6 @@ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx/-/plugin-transform-react-jsx-7.22.5.tgz", "integrity": "sha512-rog5gZaVbUip5iWDMTYbVM15XQq+RkUKhET/IHR6oizR+JEoN6CAfTTuHcK4vwUyzca30qqHqEpzBOnaRMWYMA==", "dev": true, - "peer": true, "dependencies": { "@babel/helper-annotate-as-pure": "^7.22.5", "@babel/helper-module-imports": "^7.22.5", @@ -2509,7 +2505,6 @@ "version": "6.13.0", "resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.13.0.tgz", "integrity": "sha512-oXTfJzHJ5Tl7f6T8ZO0HKf981zubxgKohjddLobbntbNZHlOZGMRL+pPZGtclDWFaFJWtGBYRGyNdjQ6Xsx5yA==", - "peer": true, "dependencies": { "@codemirror/state": "^6.1.4", "style-mod": "^4.0.0", @@ -2521,7 +2516,6 @@ "resolved": "https://registry.npmjs.org/@craco/craco/-/craco-7.1.0.tgz", "integrity": "sha512-oRAcPIKYrfPXp9rSzlsDNeOaVtDiKhoyqSXUoqiK24jCkHr4T8m/a2f74yXIzCbIheoUWDOIfWZyRgFgT+cpqA==", "dev": true, - "peer": true, "dependencies": { "autoprefixer": "^10.4.12", "cosmiconfig": "^7.0.1", @@ -4138,7 +4132,6 @@ "version": "2.11.8", "resolved": "https://registry.npmjs.org/@popperjs/core/-/core-2.11.8.tgz", "integrity": "sha512-P1st0aksCrn9sGZhp8GMYwBnQsbvAWsZAX44oXNNvLHGqAOcoVxmjZiohstwQ7SqKnbR47akdNi+uleWD8+g6A==", - "peer": true, "funding": { "type": "opencollective", "url": "https://opencollective.com/popperjs" @@ -4663,7 +4656,6 @@ "resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-8.40.1.tgz", "integrity": "sha512-vRb792M4mF1FBT+eoLecmkpLXwxsBHvWWRGJjzbYANBM6DtiJc6yETyv4rqDA6QNjF1pkj1U7LMA6dGb3VYlHw==", "dev": true, - "peer": true, "dependencies": { "@types/estree": "*", "@types/json-schema": "*" @@ -4907,7 +4899,6 @@ "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-5.59.9.tgz", "integrity": "sha512-4uQIBq1ffXd2YvF7MAvehWKW3zVv/w+mSfRAu+8cKbfj3nwzyqJLNcZJpQ/WZ1HLbJDiowwmQ6NO+63nCA+fqA==", "dev": true, - "peer": true, "dependencies": { "@eslint-community/regexpp": "^4.4.0", "@typescript-eslint/scope-manager": "5.59.9", @@ -4961,7 +4952,6 @@ "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-5.59.9.tgz", "integrity": "sha512-FsPkRvBtcLQ/eVK1ivDiNYBjn3TGJdXy2fhXX+rc7czWl4ARwnpArwbihSOHI2Peg9WbtGHrbThfBUkZZGTtvQ==", "dev": true, - "peer": true, "dependencies": { "@typescript-eslint/scope-manager": "5.59.9", "@typescript-eslint/types": "5.59.9", @@ -5409,7 +5399,6 @@ "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.11.3.tgz", "integrity": "sha512-Y9rRfJG5jcKOE0CLisYbojUjIrIEE7AGMzA/Sm4BslANhbS+cDMpgBdcPT91oJ7OuJ9hYJBx59RjbhxVnrF8Xg==", "dev": true, - "peer": true, "bin": { "acorn": "bin/acorn" }, @@ -5505,7 +5494,6 @@ "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", "dev": true, - "peer": true, "dependencies": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", @@ -6440,7 +6428,6 @@ "url": "https://github.com/sponsors/ai" } ], - "peer": true, "dependencies": { "caniuse-lite": "^1.0.30001646", "electron-to-chromium": "^1.5.4", @@ -7378,7 +7365,6 @@ "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.12.0.tgz", "integrity": "sha512-sRu1kpcO9yLtYxBKvqfTeh9KzZEwO3STyX1HT+4CaDzC6HpTGYhIhPIzj9XuKU7KYDwnaeh5hcOwjy1QuJzBPA==", "dev": true, - "peer": true, "dependencies": { "fast-deep-equal": "^3.1.1", "json-schema-traverse": "^1.0.0", @@ -8521,7 +8507,6 @@ "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.56.0.tgz", "integrity": "sha512-Go19xM6T9puCOWntie1/P997aXxFsOi37JIHRWI514Hc6ZnaHGKY9xFhrU65RT6CcBEzZoGG1e6Nq+DT04ZtZQ==", "dev": true, - "peer": true, "dependencies": { "@eslint-community/eslint-utils": "^4.2.0", "@eslint-community/regexpp": "^4.6.1", @@ -8719,7 +8704,6 @@ "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-6.21.0.tgz", "integrity": "sha512-tbsV1jPne5CkFQCgPBcDOt30ItF7aJoZL997JSF7MhGQqOeT3svWRYxiqlfA5RUdlHN6Fi+EI9bxqbdyAUZjYQ==", "dev": true, - "peer": true, "dependencies": { "@typescript-eslint/scope-manager": "6.21.0", "@typescript-eslint/types": "6.21.0", @@ -8969,7 +8953,6 @@ "resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-9.1.0.tgz", "integrity": "sha512-NSWl5BFQWEPi1j4TjVNItzYV7dZXZ+wP6I6ZhrBGpChQhZRUaElihE9uRRkcbRnNb76UMKDF3r+WTmNcGPKsqw==", "dev": true, - "peer": true, "bin": { "eslint-config-prettier": "bin/cli.js" }, @@ -9382,7 +9365,6 @@ "resolved": "https://registry.npmjs.org/eslint-plugin-import/-/eslint-plugin-import-2.27.5.tgz", "integrity": "sha512-LmEt3GVofgiGuiE+ORpnvP+kAm3h6MLZJ4Q5HCyHADofsb4VzXFsRiWj3c0OFiV+3DWFh0qg3v9gcPlfc3zRow==", "dev": true, - "peer": true, "dependencies": { "array-includes": "^3.1.6", "array.prototype.flat": "^1.3.1", @@ -10143,7 +10125,6 @@ "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.12.0.tgz", "integrity": "sha512-sRu1kpcO9yLtYxBKvqfTeh9KzZEwO3STyX1HT+4CaDzC6HpTGYhIhPIzj9XuKU7KYDwnaeh5hcOwjy1QuJzBPA==", "dev": true, - "peer": true, "dependencies": { "fast-deep-equal": "^3.1.1", "json-schema-traverse": "^1.0.0", @@ -12785,7 +12766,6 @@ "resolved": "https://registry.npmjs.org/jest/-/jest-27.5.1.tgz", "integrity": "sha512-Yn0mADZB89zTtjkPJEXwrac3LHudkQMR+Paqa8uxJHCBr9agxztUifWCyiYrjhMPBoUVBjyny0I7XH6ozDr7QQ==", "dev": true, - "peer": true, "dependencies": { "@jest/core": "^27.5.1", "import-local": "^3.0.2", @@ -14230,7 +14210,6 @@ "resolved": "https://registry.npmjs.org/less/-/less-4.1.3.tgz", "integrity": "sha512-w16Xk/Ta9Hhyei0Gpz9m7VS8F28nieJaL/VyShID7cYvP6IL5oHeL6p4TXSDJqZE/lNv0oJ2pGVjJsRkfwm5FA==", "dev": true, - "peer": true, "dependencies": { "copy-anything": "^2.0.1", "parse-node-version": "^1.0.1", @@ -14770,7 +14749,6 @@ "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.12.0.tgz", "integrity": "sha512-sRu1kpcO9yLtYxBKvqfTeh9KzZEwO3STyX1HT+4CaDzC6HpTGYhIhPIzj9XuKU7KYDwnaeh5hcOwjy1QuJzBPA==", "dev": true, - "peer": true, "dependencies": { "fast-deep-equal": "^3.1.1", "json-schema-traverse": "^1.0.0", @@ -15721,7 +15699,6 @@ "url": "https://github.com/sponsors/ai" } ], - "peer": true, "dependencies": { "nanoid": "^3.3.6", "picocolors": "^1.0.0", @@ -16856,7 +16833,6 @@ "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.0.13.tgz", "integrity": "sha512-EaV1Gl4mUEV4ddhDnv/xtj7sxwrwxdetHdWUGnT4VJQf+4d05v6lHYZr8N573k5Z0BViss7BDhfWtKS3+sfAqQ==", "dev": true, - "peer": true, "dependencies": { "cssesc": "^3.0.0", "util-deprecate": "^1.0.2" @@ -16981,7 +16957,6 @@ "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.2.5.tgz", "integrity": "sha512-3/GWa9aOC0YeD7LUfvOG2NiDyhOWRvt1k+rcKhOuYnMY24iiCphgneUfJDyFXd6rZCAnuLBv6UeAULtrhT/F4A==", "dev": true, - "peer": true, "bin": { "prettier": "bin/prettier.cjs" }, @@ -17295,7 +17270,6 @@ "version": "16.14.0", "resolved": "https://registry.npmjs.org/react/-/react-16.14.0.tgz", "integrity": "sha512-0X2CImDkJGApiAlcf0ODKIneSwBPhqJawOa5wCtKbu7ZECrmS26NvtSILynQ66cgkT/RJ4LidJOc3bUESwmU8g==", - "peer": true, "dependencies": { "loose-envify": "^1.1.0", "object-assign": "^4.1.1", @@ -17386,7 +17360,6 @@ "version": "16.14.0", "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-16.14.0.tgz", "integrity": "sha512-1gCeQXDLoIqMgqD3IO2Ah9bnf0w9kzhwN5q4FGnHZ67hBm9yePzB5JJAIQCc8x3pFnNlwFq4RidZggNAAkzWWw==", - "peer": true, "dependencies": { "loose-envify": "^1.1.0", "object-assign": "^4.1.1", @@ -17432,7 +17405,6 @@ "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.11.0.tgz", "integrity": "sha512-F27qZr8uUqwhWZboondsPx8tnC3Ct3SxZA3V5WyEvujRyyNv0VYPhoBg1gZ8/MV5tubQp76Trw8lTv9hzRBa+A==", "dev": true, - "peer": true, "engines": { "node": ">=0.10.0" } @@ -17495,7 +17467,6 @@ "resolved": "https://registry.npmjs.org/react-scripts/-/react-scripts-5.0.1.tgz", "integrity": "sha512-8VAmEm/ZAwQzJ+GOMLbBsTdDKOpuZh7RPs0UymvBR2vRk4iZWCskjbFnxqjrzoIvlNNRZ3QJFx6/qDSi6zSnaQ==", "dev": true, - "peer": true, "dependencies": { "@babel/core": "^7.16.0", "@pmmmwh/react-refresh-webpack-plugin": "^0.5.3", @@ -18158,7 +18129,6 @@ "resolved": "https://registry.npmjs.org/rollup/-/rollup-2.79.2.tgz", "integrity": "sha512-fS6iqSPZDs3dr/y7Od6y5nha8dW1YnbgtsyotCVvoFGKbERG++CVRFv1meyGDE1SNItQA8BrnCw7ScdAhRJ3XQ==", "dev": true, - "peer": true, "bin": { "rollup": "dist/bin/rollup" }, @@ -19982,7 +19952,6 @@ "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", "dev": true, - "peer": true, "engines": { "node": ">=10" }, @@ -20082,6 +20051,7 @@ "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.9.5.tgz", "integrity": "sha512-1FXk9E2Hm+QzZQ7z+McJiHL4NW1F2EzMu9Nq9i3zAaGqibafqYwCVU6WyWAuyQRRzOlxou8xZSyXLEN8oKj24g==", "dev": true, + "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -20500,7 +20470,6 @@ "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.94.0.tgz", "integrity": "sha512-KcsGn50VT+06JH/iunZJedYGUJS5FGjow8wb9c0v5n1Om8O1g4L6LjtfxwlXIATopoQu+vOXXa7gYisWxCoPyg==", "dev": true, - "peer": true, "dependencies": { "@types/estree": "^1.0.5", "@webassemblyjs/ast": "^1.12.1", @@ -20570,7 +20539,6 @@ "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.12.0.tgz", "integrity": "sha512-sRu1kpcO9yLtYxBKvqfTeh9KzZEwO3STyX1HT+4CaDzC6HpTGYhIhPIzj9XuKU7KYDwnaeh5hcOwjy1QuJzBPA==", "dev": true, - "peer": true, "dependencies": { "fast-deep-equal": "^3.1.1", "json-schema-traverse": "^1.0.0", @@ -20624,7 +20592,6 @@ "resolved": "https://registry.npmjs.org/webpack-dev-server/-/webpack-dev-server-4.15.1.tgz", "integrity": "sha512-5hbAst3h3C3L8w6W4P96L5vaV0PxSmJhxZvWKYIdgxOQm8pNZ5dEOmmSLBVpP85ReeyRt6AS1QJNyo/oFFPeVA==", "dev": true, - "peer": true, "dependencies": { "@types/bonjour": "^3.5.9", "@types/connect-history-api-fallback": "^1.3.5", @@ -20684,7 +20651,6 @@ "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.12.0.tgz", "integrity": "sha512-sRu1kpcO9yLtYxBKvqfTeh9KzZEwO3STyX1HT+4CaDzC6HpTGYhIhPIzj9XuKU7KYDwnaeh5hcOwjy1QuJzBPA==", "dev": true, - "peer": true, "dependencies": { "fast-deep-equal": "^3.1.1", "json-schema-traverse": "^1.0.0", @@ -21099,7 +21065,6 @@ "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.12.0.tgz", "integrity": "sha512-sRu1kpcO9yLtYxBKvqfTeh9KzZEwO3STyX1HT+4CaDzC6HpTGYhIhPIzj9XuKU7KYDwnaeh5hcOwjy1QuJzBPA==", "dev": true, - "peer": true, "dependencies": { "fast-deep-equal": "^3.1.1", "json-schema-traverse": "^1.0.0", @@ -21364,7 +21329,6 @@ "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.10.tgz", "integrity": "sha512-+dbF1tHwZpXcbOJdVOkzLDxZP1ailvSxM6ZweXTegylPny803bFhA+vqBYw4s31NSAk4S2Qz+AKXK9a4wkdjcQ==", "license": "MIT", - "peer": true, "engines": { "node": ">=8.3.0" }, -- cgit v1.2.3 From 68118cb83c6993eae0f46d92ea29861bf5d7679c Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sun, 7 Dec 2025 00:46:31 +0000 Subject: Add sorting functionality to System Files view Co-authored-by: jpdillingham <17145758+jpdillingham@users.noreply.github.com> --- src/web/src/components/System/Files/Explorer.jsx | 70 ++++++++++++++++++++++-- 1 file changed, 66 insertions(+), 4 deletions(-) diff --git a/src/web/src/components/System/Files/Explorer.jsx b/src/web/src/components/System/Files/Explorer.jsx index e577b31c..543c0744 100644 --- a/src/web/src/components/System/Files/Explorer.jsx +++ b/src/web/src/components/System/Files/Explorer.jsx @@ -126,6 +126,8 @@ const Explorer = ({ remoteFileManagement, root }) => { const [directory, setDirectory] = useState({ directories: [], files: [] }); const [subdirectory, setSubdirectory] = useState([]); const [loading, setLoading] = useState(false); + const [sortColumn, setSortColumn] = useState('name'); + const [sortDirection, setSortDirection] = useState('ascending'); const fetch = async () => { setLoading(true); @@ -155,11 +157,45 @@ const Explorer = ({ remoteFileManagement, root }) => { setSubdirectory(copy); }; + const handleSort = (column) => { + if (sortColumn === column) { + setSortDirection( + sortDirection === 'ascending' ? 'descending' : 'ascending', + ); + } else { + setSortColumn(column); + setSortDirection('ascending'); + } + }; + + const sortItems = (items) => { + if (!items || items.length === 0) return items; + + return [...items].sort((a, b) => { + let compareValue = 0; + + if (sortColumn === 'name') { + compareValue = a.name.localeCompare(b.name, undefined, { + numeric: true, + sensitivity: 'base', + }); + } else if (sortColumn === 'date') { + const dateA = new Date(a.modifiedAt); + const dateB = new Date(b.modifiedAt); + compareValue = dateA - dateB; + } + + return sortDirection === 'ascending' ? compareValue : -compareValue; + }); + }; + if (loading) { return ; } const total = directory?.directories?.length + directory?.files?.length ?? 0; + const sortedDirectories = sortItems(directory?.directories); + const sortedFiles = sortItems(directory?.files); return ( <> @@ -176,11 +212,37 @@ const Explorer = ({ remoteFileManagement, root }) => { > - + handleSort('name')} + style={{ cursor: 'pointer' }} + > Name + {sortColumn === 'name' && ( + + )} - + handleSort('date')} + style={{ cursor: 'pointer' }} + > Date Modified + {sortColumn === 'date' && ( + + )} Size @@ -215,7 +277,7 @@ const Explorer = ({ remoteFileManagement, root }) => { subdirectory={subdirectory} /> )} - {directory?.directories?.map((d) => ( + {sortedDirectories?.map((d) => ( select({ path: d.name })} @@ -225,7 +287,7 @@ const Explorer = ({ remoteFileManagement, root }) => { {...d} /> ))} - {directory?.files?.map((f) => ( + {sortedFiles?.map((f) => ( Date: Sun, 7 Dec 2025 00:51:13 +0000 Subject: Handle null/undefined dates in sorting logic Co-authored-by: jpdillingham <17145758+jpdillingham@users.noreply.github.com> --- src/web/src/components/System/Files/Explorer.jsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/web/src/components/System/Files/Explorer.jsx b/src/web/src/components/System/Files/Explorer.jsx index 543c0744..ca0bdba1 100644 --- a/src/web/src/components/System/Files/Explorer.jsx +++ b/src/web/src/components/System/Files/Explorer.jsx @@ -180,8 +180,8 @@ const Explorer = ({ remoteFileManagement, root }) => { sensitivity: 'base', }); } else if (sortColumn === 'date') { - const dateA = new Date(a.modifiedAt); - const dateB = new Date(b.modifiedAt); + const dateA = a.modifiedAt ? new Date(a.modifiedAt) : new Date(0); + const dateB = b.modifiedAt ? new Date(b.modifiedAt) : new Date(0); compareValue = dateA - dateB; } -- cgit v1.2.3 From 0fadbff23d1c8074aa47d4ab2c98fbf27719d251 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sun, 7 Dec 2025 00:53:35 +0000 Subject: Initial plan for adding transfer details popup Co-authored-by: jpdillingham <17145758+jpdillingham@users.noreply.github.com> --- src/web/package-lock.json | 38 +------------------------------------- 1 file changed, 1 insertion(+), 37 deletions(-) diff --git a/src/web/package-lock.json b/src/web/package-lock.json index 5d0ae3d2..0fdcae0d 100644 --- a/src/web/package-lock.json +++ b/src/web/package-lock.json @@ -180,7 +180,6 @@ "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.23.9.tgz", "integrity": "sha512-5q0175NOjddqpvvzU+kDiSOAk4PfdO6FvwCWoQ6RO7rTzEe8vlo+4HVfcnAREhD4npMs0e9uZypjTwzZPCf/cw==", "dev": true, - "peer": true, "dependencies": { "@ampproject/remapping": "^2.2.0", "@babel/code-frame": "^7.23.5", @@ -226,7 +225,6 @@ "resolved": "https://registry.npmjs.org/@babel/eslint-parser/-/eslint-parser-7.23.10.tgz", "integrity": "sha512-3wSYDPZVnhseRnxRJH6ZVTNknBz76AEnyC+AYYhasjP3Yy23qz0ERR7Fcd2SHmYuSFJ2kY9gaaDd3vyqU09eSw==", "dev": true, - "peer": true, "dependencies": { "@nicolo-ribaudo/eslint-scope-5-internals": "5.1.1-v1", "eslint-visitor-keys": "^2.1.0", @@ -1005,7 +1003,6 @@ "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-flow/-/plugin-syntax-flow-7.22.5.tgz", "integrity": "sha512-9RdCl0i+q0QExayk2nOS7853w08yLucnnPML6EN9S8fgMPVtdLDCdx/cOQ/i44Lb9UeQX9A35yaqBBOMMZxPxQ==", "dev": true, - "peer": true, "dependencies": { "@babel/helper-plugin-utils": "^7.22.5" }, @@ -1880,7 +1877,6 @@ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx/-/plugin-transform-react-jsx-7.22.5.tgz", "integrity": "sha512-rog5gZaVbUip5iWDMTYbVM15XQq+RkUKhET/IHR6oizR+JEoN6CAfTTuHcK4vwUyzca30qqHqEpzBOnaRMWYMA==", "dev": true, - "peer": true, "dependencies": { "@babel/helper-annotate-as-pure": "^7.22.5", "@babel/helper-module-imports": "^7.22.5", @@ -2509,7 +2505,6 @@ "version": "6.13.0", "resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.13.0.tgz", "integrity": "sha512-oXTfJzHJ5Tl7f6T8ZO0HKf981zubxgKohjddLobbntbNZHlOZGMRL+pPZGtclDWFaFJWtGBYRGyNdjQ6Xsx5yA==", - "peer": true, "dependencies": { "@codemirror/state": "^6.1.4", "style-mod": "^4.0.0", @@ -2521,7 +2516,6 @@ "resolved": "https://registry.npmjs.org/@craco/craco/-/craco-7.1.0.tgz", "integrity": "sha512-oRAcPIKYrfPXp9rSzlsDNeOaVtDiKhoyqSXUoqiK24jCkHr4T8m/a2f74yXIzCbIheoUWDOIfWZyRgFgT+cpqA==", "dev": true, - "peer": true, "dependencies": { "autoprefixer": "^10.4.12", "cosmiconfig": "^7.0.1", @@ -4138,7 +4132,6 @@ "version": "2.11.8", "resolved": "https://registry.npmjs.org/@popperjs/core/-/core-2.11.8.tgz", "integrity": "sha512-P1st0aksCrn9sGZhp8GMYwBnQsbvAWsZAX44oXNNvLHGqAOcoVxmjZiohstwQ7SqKnbR47akdNi+uleWD8+g6A==", - "peer": true, "funding": { "type": "opencollective", "url": "https://opencollective.com/popperjs" @@ -4663,7 +4656,6 @@ "resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-8.40.1.tgz", "integrity": "sha512-vRb792M4mF1FBT+eoLecmkpLXwxsBHvWWRGJjzbYANBM6DtiJc6yETyv4rqDA6QNjF1pkj1U7LMA6dGb3VYlHw==", "dev": true, - "peer": true, "dependencies": { "@types/estree": "*", "@types/json-schema": "*" @@ -4907,7 +4899,6 @@ "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-5.59.9.tgz", "integrity": "sha512-4uQIBq1ffXd2YvF7MAvehWKW3zVv/w+mSfRAu+8cKbfj3nwzyqJLNcZJpQ/WZ1HLbJDiowwmQ6NO+63nCA+fqA==", "dev": true, - "peer": true, "dependencies": { "@eslint-community/regexpp": "^4.4.0", "@typescript-eslint/scope-manager": "5.59.9", @@ -4961,7 +4952,6 @@ "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-5.59.9.tgz", "integrity": "sha512-FsPkRvBtcLQ/eVK1ivDiNYBjn3TGJdXy2fhXX+rc7czWl4ARwnpArwbihSOHI2Peg9WbtGHrbThfBUkZZGTtvQ==", "dev": true, - "peer": true, "dependencies": { "@typescript-eslint/scope-manager": "5.59.9", "@typescript-eslint/types": "5.59.9", @@ -5409,7 +5399,6 @@ "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.11.3.tgz", "integrity": "sha512-Y9rRfJG5jcKOE0CLisYbojUjIrIEE7AGMzA/Sm4BslANhbS+cDMpgBdcPT91oJ7OuJ9hYJBx59RjbhxVnrF8Xg==", "dev": true, - "peer": true, "bin": { "acorn": "bin/acorn" }, @@ -5505,7 +5494,6 @@ "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", "dev": true, - "peer": true, "dependencies": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", @@ -6440,7 +6428,6 @@ "url": "https://github.com/sponsors/ai" } ], - "peer": true, "dependencies": { "caniuse-lite": "^1.0.30001646", "electron-to-chromium": "^1.5.4", @@ -7378,7 +7365,6 @@ "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.12.0.tgz", "integrity": "sha512-sRu1kpcO9yLtYxBKvqfTeh9KzZEwO3STyX1HT+4CaDzC6HpTGYhIhPIzj9XuKU7KYDwnaeh5hcOwjy1QuJzBPA==", "dev": true, - "peer": true, "dependencies": { "fast-deep-equal": "^3.1.1", "json-schema-traverse": "^1.0.0", @@ -8521,7 +8507,6 @@ "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.56.0.tgz", "integrity": "sha512-Go19xM6T9puCOWntie1/P997aXxFsOi37JIHRWI514Hc6ZnaHGKY9xFhrU65RT6CcBEzZoGG1e6Nq+DT04ZtZQ==", "dev": true, - "peer": true, "dependencies": { "@eslint-community/eslint-utils": "^4.2.0", "@eslint-community/regexpp": "^4.6.1", @@ -8719,7 +8704,6 @@ "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-6.21.0.tgz", "integrity": "sha512-tbsV1jPne5CkFQCgPBcDOt30ItF7aJoZL997JSF7MhGQqOeT3svWRYxiqlfA5RUdlHN6Fi+EI9bxqbdyAUZjYQ==", "dev": true, - "peer": true, "dependencies": { "@typescript-eslint/scope-manager": "6.21.0", "@typescript-eslint/types": "6.21.0", @@ -8969,7 +8953,6 @@ "resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-9.1.0.tgz", "integrity": "sha512-NSWl5BFQWEPi1j4TjVNItzYV7dZXZ+wP6I6ZhrBGpChQhZRUaElihE9uRRkcbRnNb76UMKDF3r+WTmNcGPKsqw==", "dev": true, - "peer": true, "bin": { "eslint-config-prettier": "bin/cli.js" }, @@ -9382,7 +9365,6 @@ "resolved": "https://registry.npmjs.org/eslint-plugin-import/-/eslint-plugin-import-2.27.5.tgz", "integrity": "sha512-LmEt3GVofgiGuiE+ORpnvP+kAm3h6MLZJ4Q5HCyHADofsb4VzXFsRiWj3c0OFiV+3DWFh0qg3v9gcPlfc3zRow==", "dev": true, - "peer": true, "dependencies": { "array-includes": "^3.1.6", "array.prototype.flat": "^1.3.1", @@ -10143,7 +10125,6 @@ "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.12.0.tgz", "integrity": "sha512-sRu1kpcO9yLtYxBKvqfTeh9KzZEwO3STyX1HT+4CaDzC6HpTGYhIhPIzj9XuKU7KYDwnaeh5hcOwjy1QuJzBPA==", "dev": true, - "peer": true, "dependencies": { "fast-deep-equal": "^3.1.1", "json-schema-traverse": "^1.0.0", @@ -12785,7 +12766,6 @@ "resolved": "https://registry.npmjs.org/jest/-/jest-27.5.1.tgz", "integrity": "sha512-Yn0mADZB89zTtjkPJEXwrac3LHudkQMR+Paqa8uxJHCBr9agxztUifWCyiYrjhMPBoUVBjyny0I7XH6ozDr7QQ==", "dev": true, - "peer": true, "dependencies": { "@jest/core": "^27.5.1", "import-local": "^3.0.2", @@ -14230,7 +14210,6 @@ "resolved": "https://registry.npmjs.org/less/-/less-4.1.3.tgz", "integrity": "sha512-w16Xk/Ta9Hhyei0Gpz9m7VS8F28nieJaL/VyShID7cYvP6IL5oHeL6p4TXSDJqZE/lNv0oJ2pGVjJsRkfwm5FA==", "dev": true, - "peer": true, "dependencies": { "copy-anything": "^2.0.1", "parse-node-version": "^1.0.1", @@ -14770,7 +14749,6 @@ "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.12.0.tgz", "integrity": "sha512-sRu1kpcO9yLtYxBKvqfTeh9KzZEwO3STyX1HT+4CaDzC6HpTGYhIhPIzj9XuKU7KYDwnaeh5hcOwjy1QuJzBPA==", "dev": true, - "peer": true, "dependencies": { "fast-deep-equal": "^3.1.1", "json-schema-traverse": "^1.0.0", @@ -15721,7 +15699,6 @@ "url": "https://github.com/sponsors/ai" } ], - "peer": true, "dependencies": { "nanoid": "^3.3.6", "picocolors": "^1.0.0", @@ -16856,7 +16833,6 @@ "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.0.13.tgz", "integrity": "sha512-EaV1Gl4mUEV4ddhDnv/xtj7sxwrwxdetHdWUGnT4VJQf+4d05v6lHYZr8N573k5Z0BViss7BDhfWtKS3+sfAqQ==", "dev": true, - "peer": true, "dependencies": { "cssesc": "^3.0.0", "util-deprecate": "^1.0.2" @@ -16981,7 +16957,6 @@ "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.2.5.tgz", "integrity": "sha512-3/GWa9aOC0YeD7LUfvOG2NiDyhOWRvt1k+rcKhOuYnMY24iiCphgneUfJDyFXd6rZCAnuLBv6UeAULtrhT/F4A==", "dev": true, - "peer": true, "bin": { "prettier": "bin/prettier.cjs" }, @@ -17295,7 +17270,6 @@ "version": "16.14.0", "resolved": "https://registry.npmjs.org/react/-/react-16.14.0.tgz", "integrity": "sha512-0X2CImDkJGApiAlcf0ODKIneSwBPhqJawOa5wCtKbu7ZECrmS26NvtSILynQ66cgkT/RJ4LidJOc3bUESwmU8g==", - "peer": true, "dependencies": { "loose-envify": "^1.1.0", "object-assign": "^4.1.1", @@ -17386,7 +17360,6 @@ "version": "16.14.0", "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-16.14.0.tgz", "integrity": "sha512-1gCeQXDLoIqMgqD3IO2Ah9bnf0w9kzhwN5q4FGnHZ67hBm9yePzB5JJAIQCc8x3pFnNlwFq4RidZggNAAkzWWw==", - "peer": true, "dependencies": { "loose-envify": "^1.1.0", "object-assign": "^4.1.1", @@ -17432,7 +17405,6 @@ "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.11.0.tgz", "integrity": "sha512-F27qZr8uUqwhWZboondsPx8tnC3Ct3SxZA3V5WyEvujRyyNv0VYPhoBg1gZ8/MV5tubQp76Trw8lTv9hzRBa+A==", "dev": true, - "peer": true, "engines": { "node": ">=0.10.0" } @@ -17495,7 +17467,6 @@ "resolved": "https://registry.npmjs.org/react-scripts/-/react-scripts-5.0.1.tgz", "integrity": "sha512-8VAmEm/ZAwQzJ+GOMLbBsTdDKOpuZh7RPs0UymvBR2vRk4iZWCskjbFnxqjrzoIvlNNRZ3QJFx6/qDSi6zSnaQ==", "dev": true, - "peer": true, "dependencies": { "@babel/core": "^7.16.0", "@pmmmwh/react-refresh-webpack-plugin": "^0.5.3", @@ -18158,7 +18129,6 @@ "resolved": "https://registry.npmjs.org/rollup/-/rollup-2.79.2.tgz", "integrity": "sha512-fS6iqSPZDs3dr/y7Od6y5nha8dW1YnbgtsyotCVvoFGKbERG++CVRFv1meyGDE1SNItQA8BrnCw7ScdAhRJ3XQ==", "dev": true, - "peer": true, "bin": { "rollup": "dist/bin/rollup" }, @@ -19982,7 +19952,6 @@ "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", "dev": true, - "peer": true, "engines": { "node": ">=10" }, @@ -20082,6 +20051,7 @@ "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.9.5.tgz", "integrity": "sha512-1FXk9E2Hm+QzZQ7z+McJiHL4NW1F2EzMu9Nq9i3zAaGqibafqYwCVU6WyWAuyQRRzOlxou8xZSyXLEN8oKj24g==", "dev": true, + "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -20500,7 +20470,6 @@ "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.94.0.tgz", "integrity": "sha512-KcsGn50VT+06JH/iunZJedYGUJS5FGjow8wb9c0v5n1Om8O1g4L6LjtfxwlXIATopoQu+vOXXa7gYisWxCoPyg==", "dev": true, - "peer": true, "dependencies": { "@types/estree": "^1.0.5", "@webassemblyjs/ast": "^1.12.1", @@ -20570,7 +20539,6 @@ "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.12.0.tgz", "integrity": "sha512-sRu1kpcO9yLtYxBKvqfTeh9KzZEwO3STyX1HT+4CaDzC6HpTGYhIhPIzj9XuKU7KYDwnaeh5hcOwjy1QuJzBPA==", "dev": true, - "peer": true, "dependencies": { "fast-deep-equal": "^3.1.1", "json-schema-traverse": "^1.0.0", @@ -20624,7 +20592,6 @@ "resolved": "https://registry.npmjs.org/webpack-dev-server/-/webpack-dev-server-4.15.1.tgz", "integrity": "sha512-5hbAst3h3C3L8w6W4P96L5vaV0PxSmJhxZvWKYIdgxOQm8pNZ5dEOmmSLBVpP85ReeyRt6AS1QJNyo/oFFPeVA==", "dev": true, - "peer": true, "dependencies": { "@types/bonjour": "^3.5.9", "@types/connect-history-api-fallback": "^1.3.5", @@ -20684,7 +20651,6 @@ "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.12.0.tgz", "integrity": "sha512-sRu1kpcO9yLtYxBKvqfTeh9KzZEwO3STyX1HT+4CaDzC6HpTGYhIhPIzj9XuKU7KYDwnaeh5hcOwjy1QuJzBPA==", "dev": true, - "peer": true, "dependencies": { "fast-deep-equal": "^3.1.1", "json-schema-traverse": "^1.0.0", @@ -21099,7 +21065,6 @@ "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.12.0.tgz", "integrity": "sha512-sRu1kpcO9yLtYxBKvqfTeh9KzZEwO3STyX1HT+4CaDzC6HpTGYhIhPIzj9XuKU7KYDwnaeh5hcOwjy1QuJzBPA==", "dev": true, - "peer": true, "dependencies": { "fast-deep-equal": "^3.1.1", "json-schema-traverse": "^1.0.0", @@ -21364,7 +21329,6 @@ "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.10.tgz", "integrity": "sha512-+dbF1tHwZpXcbOJdVOkzLDxZP1ailvSxM6ZweXTegylPny803bFhA+vqBYw4s31NSAk4S2Qz+AKXK9a4wkdjcQ==", "license": "MIT", - "peer": true, "engines": { "node": ">=8.3.0" }, -- cgit v1.2.3 From 68d0b046479c118529ccf5ccd7b22f66e0be2695 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sun, 7 Dec 2025 01:01:28 +0000 Subject: Add info icon with transfer details popup to Size column Co-authored-by: jpdillingham <17145758+jpdillingham@users.noreply.github.com> --- src/web/src/components/Transfers/TransferList.jsx | 134 +++++++++++++++++++++- 1 file changed, 129 insertions(+), 5 deletions(-) diff --git a/src/web/src/components/Transfers/TransferList.jsx b/src/web/src/components/Transfers/TransferList.jsx index b81049ec..963d7333 100644 --- a/src/web/src/components/Transfers/TransferList.jsx +++ b/src/web/src/components/Transfers/TransferList.jsx @@ -1,4 +1,9 @@ -import { formatBytes, formatBytesAsUnit, getFileName } from '../../lib/util'; +import { + formatBytes, + formatBytesAsUnit, + formatDate, + getFileName, +} from '../../lib/util'; import React, { Component } from 'react'; import { Button, @@ -6,6 +11,7 @@ import { Header, Icon, List, + Popup, Progress, Table, } from 'semantic-ui-react'; @@ -38,6 +44,53 @@ const formatBytesTransferred = ({ size, transferred }) => { return `${t}/${s} ${sExtension}`; }; +// Convert camelCase to Title Case with spaces +const formatFieldName = (fieldName) => { + return fieldName + .replaceAll(/([A-Z])/gu, ' $1') + .replace(/^./u, (string) => string.toUpperCase()) + .trim(); +}; + +// Format value based on field type +const formatValue = (key, value) => { + if (value === null || value === undefined) { + return 'N/A'; + } + + // Format datetime fields + if ( + (key.toLowerCase().includes('at') || key.toLowerCase().includes('time')) && + typeof value === 'string' && + value.includes(':') + ) { + // Check if it's a duration (HH:MM:SS format) + if (/^\d{2}:\d{2}:\d{2}/u.test(value)) { + return value; + } + + // Otherwise it's a datetime + return formatDate(value); + } + + // Format byte-related fields + if (key.toLowerCase().includes('bytes') || key === 'size') { + return formatBytes(value); + } + + // Format speed + if (key.toLowerCase().includes('speed')) { + return `${formatBytes(value)}/s`; + } + + // Format percentage + if (key.toLowerCase().includes('percent')) { + return `${value.toFixed(2)}%`; + } + + return value.toString(); +}; + class TransferList extends Component { constructor(props) { super(props); @@ -67,6 +120,52 @@ class TransferList extends Component { this.setState((previousState) => ({ isFolded: !previousState.isFolded })); }; + renderTransferDetails = (file) => { + // Fields to display in the popup + const fields = [ + 'id', + 'username', + 'direction', + 'filename', + 'size', + 'startOffset', + 'state', + 'stateDescription', + 'requestedAt', + 'enqueuedAt', + 'startedAt', + 'endedAt', + 'bytesTransferred', + 'averageSpeed', + 'bytesRemaining', + 'elapsedTime', + 'percentComplete', + 'remainingTime', + ]; + + return ( + + + {fields.map((field) => { + const value = file[field]; + return ( + + + {formatFieldName(field)} + + {formatValue(field, value)} + + ); + })} + +
+ ); + }; + render() { const { directoryName, files, onSelectionChange } = this.props; const { isFolded } = this.state; @@ -172,10 +271,35 @@ class TransferList extends Component { )} - {formatBytesTransferred({ - size: f.size, - transferred: f.bytesTransferred, - })} +
+ + {formatBytesTransferred({ + size: f.size, + transferred: f.bytesTransferred, + })} + + + } + wide="very" + /> +
))} -- cgit v1.2.3 From 74bf3fdab0f8915915da85cf69efa4e1d96d99d6 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sun, 7 Dec 2025 01:04:46 +0000 Subject: Address code review feedback: improve performance and safety Co-authored-by: jpdillingham <17145758+jpdillingham@users.noreply.github.com> --- src/web/src/components/Transfers/TransferList.jsx | 29 ++++++++++++++++------- 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/src/web/src/components/Transfers/TransferList.jsx b/src/web/src/components/Transfers/TransferList.jsx index 963d7333..62072e63 100644 --- a/src/web/src/components/Transfers/TransferList.jsx +++ b/src/web/src/components/Transfers/TransferList.jsx @@ -44,11 +44,16 @@ const formatBytesTransferred = ({ size, transferred }) => { return `${t}/${s} ${sExtension}`; }; +// Regex patterns for field name formatting +const UPPERCASE_PATTERN = /([A-Z])/gu; +const FIRST_CHAR_PATTERN = /^./u; +const DURATION_PATTERN = /^\d{2}:\d{2}:\d{2}/u; + // Convert camelCase to Title Case with spaces const formatFieldName = (fieldName) => { return fieldName - .replaceAll(/([A-Z])/gu, ' $1') - .replace(/^./u, (string) => string.toUpperCase()) + .replaceAll(UPPERCASE_PATTERN, ' $1') + .replace(FIRST_CHAR_PATTERN, (string) => string.toUpperCase()) .trim(); }; @@ -58,14 +63,16 @@ const formatValue = (key, value) => { return 'N/A'; } + const lowerKey = key.toLowerCase(); + // Format datetime fields if ( - (key.toLowerCase().includes('at') || key.toLowerCase().includes('time')) && + (lowerKey.includes('at') || lowerKey.includes('time')) && typeof value === 'string' && value.includes(':') ) { // Check if it's a duration (HH:MM:SS format) - if (/^\d{2}:\d{2}:\d{2}/u.test(value)) { + if (DURATION_PATTERN.test(value)) { return value; } @@ -74,21 +81,25 @@ const formatValue = (key, value) => { } // Format byte-related fields - if (key.toLowerCase().includes('bytes') || key === 'size') { + if (lowerKey.includes('bytes') || key === 'size') { return formatBytes(value); } // Format speed - if (key.toLowerCase().includes('speed')) { + if (lowerKey.includes('speed')) { return `${formatBytes(value)}/s`; } // Format percentage - if (key.toLowerCase().includes('percent')) { - return `${value.toFixed(2)}%`; + if (lowerKey.includes('percent')) { + if (typeof value === 'number') { + return `${value.toFixed(2)}%`; + } + + return String(value); } - return value.toString(); + return String(value); }; class TransferList extends Component { -- cgit v1.2.3 From d21c315572505e04f3713b69cf71863047fc7706 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 7 Dec 2025 22:00:40 -0600 Subject: Update README with important project notices Added warnings about disabled contributions and security risks. --- README.md | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 3dc6d79f..d0da6fe7 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,17 @@ -> [!IMPORTANT] -> **Issues, Pull Requests, Discussions, And Comments Are Temporarily Disabled Until 1/5/26** +> [!WARNING] +> This is the only official repository for slskd. > -> The maintainers need some quiet time to enjoy the holidays, work through old and stale issues and PRs, and establish better contribution guidelines. +> Official releases are published via: +> * Build artifacts from the [GitHub Actions](github.com/slskd/slskd/actions) of this repository +> * Platform-specific archives located in [Releases](https://github.com/slskd/slskd/releases/) +> * Docker images published to [Docker Hub](https://hub.docker.com/r/slskd/slskd) and [GitHub Container Registry](https://github.com/slskd/slskd/pkgs/container/slskd) > -> In the meantime, enjoy the free software. Or don't. +> The name associated with official releases `slskd`. Any change to this will be clearly communicated here. +> +> If you encounter binaries with different names claiming to be slskd or an alternative, they are not affiliated with this project. +> +> Be cautious of unaffiliated forks that automatically mirror this repository and re-release binaries under different names. These forks are not reviewed, endorsed, or supported by the slskd maintainers, and may introduce changes that compromise security, privacy, or network integrity. +> As with any software, verify the source of binaries before running them. Supply chain attacks via unofficial forks are a real risk—if you didn't get it from this repository, you can't be certain what you're running. # slskd -- cgit v1.2.3 From f80fbac5eeda5901a106975446d0a11b7cbc38d6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 7 Dec 2025 22:04:30 -0600 Subject: Fix grammar in README release name statement --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d0da6fe7..2d9897c1 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ > * Platform-specific archives located in [Releases](https://github.com/slskd/slskd/releases/) > * Docker images published to [Docker Hub](https://hub.docker.com/r/slskd/slskd) and [GitHub Container Registry](https://github.com/slskd/slskd/pkgs/container/slskd) > -> The name associated with official releases `slskd`. Any change to this will be clearly communicated here. +> The name associated with official releases is `slskd`. Any change to this will be clearly communicated here. > > If you encounter binaries with different names claiming to be slskd or an alternative, they are not affiliated with this project. > -- cgit v1.2.3 From 500f28500bba531b29e971d37699d342602ab0e8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 8 Dec 2025 18:02:18 -0600 Subject: move details to dedicated component --- .../src/components/Transfers/TransferDetails.jsx | 107 +++++++++++++++++++ src/web/src/components/Transfers/TransferList.jsx | 114 +-------------------- 2 files changed, 110 insertions(+), 111 deletions(-) create mode 100644 src/web/src/components/Transfers/TransferDetails.jsx diff --git a/src/web/src/components/Transfers/TransferDetails.jsx b/src/web/src/components/Transfers/TransferDetails.jsx new file mode 100644 index 00000000..256ddcac --- /dev/null +++ b/src/web/src/components/Transfers/TransferDetails.jsx @@ -0,0 +1,107 @@ +import { formatBytes, formatDate } from '../../lib/util'; +import { Table } from 'semantic-ui-react'; + +// Regex patterns for field name formatting +const UPPERCASE_PATTERN = /([A-Z])/gu; +const FIRST_CHAR_PATTERN = /^./u; +const DURATION_PATTERN = /^\d{2}:\d{2}:\d{2}/u; + +// Convert camelCase to Title Case with spaces +const formatFieldName = (fieldName) => { + return fieldName + .replaceAll(UPPERCASE_PATTERN, ' $1') + .replace(FIRST_CHAR_PATTERN, (string) => string.toUpperCase()) + .trim(); +}; + +// Format value based on field type +const formatValue = (key, value) => { + if (value === null || value === undefined) { + return 'N/A'; + } + + const lowerKey = key.toLowerCase(); + + // Format datetime fields + if ( + (lowerKey.includes('at') || lowerKey.includes('time')) && + typeof value === 'string' && + value.includes(':') + ) { + // Check if it's a duration (HH:MM:SS format) + if (DURATION_PATTERN.test(value)) { + return value; + } + + // Otherwise it's a datetime + return formatDate(value); + } + + // Format byte-related fields + if (lowerKey.includes('bytes') || key === 'size') { + return formatBytes(value); + } + + // Format speed + if (lowerKey.includes('speed')) { + return `${formatBytes(value)}/s`; + } + + // Format percentage + if (lowerKey.includes('percent')) { + if (typeof value === 'number') { + return `${value.toFixed(2)}%`; + } + + return String(value); + } + + return String(value); +}; + +const TransferDetails = ({ file }) => { + // Fields to display in the popup + const fields = [ + 'id', + 'username', + 'direction', + 'filename', + 'size', + 'startOffset', + 'state', + 'requestedAt', + 'enqueuedAt', + 'startedAt', + 'endedAt', + 'bytesTransferred', + 'averageSpeed', + 'bytesRemaining', + 'elapsedTime', + 'percentComplete', + 'remainingTime', + ]; + + return ( + + + {fields.map((field) => { + const value = file[field]; + return ( + + + {formatFieldName(field)} + + {formatValue(field, value)} + + ); + })} + +
+ ); +}; + +export default TransferDetails; diff --git a/src/web/src/components/Transfers/TransferList.jsx b/src/web/src/components/Transfers/TransferList.jsx index 62072e63..01bd35df 100644 --- a/src/web/src/components/Transfers/TransferList.jsx +++ b/src/web/src/components/Transfers/TransferList.jsx @@ -1,9 +1,5 @@ -import { - formatBytes, - formatBytesAsUnit, - formatDate, - getFileName, -} from '../../lib/util'; +import { formatBytes, formatBytesAsUnit, getFileName } from '../../lib/util'; +import TransferDetails from './TransferDetails'; import React, { Component } from 'react'; import { Button, @@ -44,64 +40,6 @@ const formatBytesTransferred = ({ size, transferred }) => { return `${t}/${s} ${sExtension}`; }; -// Regex patterns for field name formatting -const UPPERCASE_PATTERN = /([A-Z])/gu; -const FIRST_CHAR_PATTERN = /^./u; -const DURATION_PATTERN = /^\d{2}:\d{2}:\d{2}/u; - -// Convert camelCase to Title Case with spaces -const formatFieldName = (fieldName) => { - return fieldName - .replaceAll(UPPERCASE_PATTERN, ' $1') - .replace(FIRST_CHAR_PATTERN, (string) => string.toUpperCase()) - .trim(); -}; - -// Format value based on field type -const formatValue = (key, value) => { - if (value === null || value === undefined) { - return 'N/A'; - } - - const lowerKey = key.toLowerCase(); - - // Format datetime fields - if ( - (lowerKey.includes('at') || lowerKey.includes('time')) && - typeof value === 'string' && - value.includes(':') - ) { - // Check if it's a duration (HH:MM:SS format) - if (DURATION_PATTERN.test(value)) { - return value; - } - - // Otherwise it's a datetime - return formatDate(value); - } - - // Format byte-related fields - if (lowerKey.includes('bytes') || key === 'size') { - return formatBytes(value); - } - - // Format speed - if (lowerKey.includes('speed')) { - return `${formatBytes(value)}/s`; - } - - // Format percentage - if (lowerKey.includes('percent')) { - if (typeof value === 'number') { - return `${value.toFixed(2)}%`; - } - - return String(value); - } - - return String(value); -}; - class TransferList extends Component { constructor(props) { super(props); @@ -131,52 +69,6 @@ class TransferList extends Component { this.setState((previousState) => ({ isFolded: !previousState.isFolded })); }; - renderTransferDetails = (file) => { - // Fields to display in the popup - const fields = [ - 'id', - 'username', - 'direction', - 'filename', - 'size', - 'startOffset', - 'state', - 'stateDescription', - 'requestedAt', - 'enqueuedAt', - 'startedAt', - 'endedAt', - 'bytesTransferred', - 'averageSpeed', - 'bytesRemaining', - 'elapsedTime', - 'percentComplete', - 'remainingTime', - ]; - - return ( - - - {fields.map((field) => { - const value = file[field]; - return ( - - - {formatFieldName(field)} - - {formatValue(field, value)} - - ); - })} - -
- ); - }; - render() { const { directoryName, files, onSelectionChange } = this.props; const { isFolded } = this.state; @@ -296,7 +188,7 @@ class TransferList extends Component { })} } on="click" position="left center" style={{ maxWidth: '600px' }} -- cgit v1.2.3 From 6a1e3ada4224d9abb8d987eb5db022e01601c92a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 8 Dec 2025 18:18:23 -0600 Subject: add dedicated cell --- src/web/src/components/Transfers/TransferList.jsx | 38 ++++++++++++++--------- src/web/src/components/Transfers/Transfers.css | 5 +++ 2 files changed, 28 insertions(+), 15 deletions(-) diff --git a/src/web/src/components/Transfers/TransferList.jsx b/src/web/src/components/Transfers/TransferList.jsx index 01bd35df..4bd1e14e 100644 --- a/src/web/src/components/Transfers/TransferList.jsx +++ b/src/web/src/components/Transfers/TransferList.jsx @@ -116,6 +116,12 @@ class TransferList extends Component { Size + + +
@@ -187,23 +193,25 @@ class TransferList extends Component { transferred: f.bytesTransferred, })} - } - on="click" - position="left center" - style={{ maxWidth: '600px' }} - trigger={ - - } - wide="very" - /> + + } + on="click" + position="left center" + style={{ maxWidth: '600px' }} + trigger={ + + } + wide="very" + /> + ))} diff --git a/src/web/src/components/Transfers/Transfers.css b/src/web/src/components/Transfers/Transfers.css index 0b787f5f..2b16d32f 100644 --- a/src/web/src/components/Transfers/Transfers.css +++ b/src/web/src/components/Transfers/Transfers.css @@ -43,6 +43,11 @@ min-width: 150px; } +.transferlist-detail { + width: 5px; + min-width: 5px; +} + .transferlist-filename { word-wrap: break-word !important; } -- cgit v1.2.3 From 35a8023360d444021167022970bff1a85ed4e9b7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 9 Dec 2025 19:28:21 -0600 Subject: update options to allow comma separated lists --- src/slskd/Core/Options.cs | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index d3e302a5..afeb1797 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1839,14 +1839,14 @@ namespace slskd public int Port { get; init; } = 5030; /// - /// Gets the IP address on which to listen for HTTP requests. + /// Gets the comma separated list of IPv4 or IPv6 IP addresses on which to listen for HTTP requests. /// - [Argument(default, "http-listen-ip-address")] - [EnvironmentVariable("HTTP_LISTEN_IP_ADDRESS")] - [Description("IP address on which to listen for HTTP requests")] + [Argument(default, "http-ip-address")] + [EnvironmentVariable("HTTP_IP_ADDRESS")] + [Description("IP addresses on which to listen for HTTP requests")] [IPAddress] [RequiresRestart] - public string ListenIpAddress { get; init; } = "0.0.0.0"; + public string IpAddress { get; init; } /// /// Gets the HTTP listen unix domain socket (UDS) path. @@ -2048,17 +2048,17 @@ namespace slskd [Range(1, 65535)] [RequiresRestart] public int Port { get; init; } = 5031; - + /// - /// Gets the IP address on which to listen for HTTPS requests. + /// Gets the comma separated list of IPv4 or IPv6 IP addresses on which to listen for HTTPS requests. /// - [Argument(default, "https-listen-ip-address")] - [EnvironmentVariable("HTTPS_LISTEN_IP_ADDRESS")] - [Description("IP address on which to listen for HTTPS requests")] - [IPAddress] + [Argument(default, "https-ip-address")] + [EnvironmentVariable("HTTPS_IP_ADDRESS")] + [Description("IP addresses on which to listen for HTTPS requests")] + [IPAddress(allowCommaSeparatedValues: true)] [RequiresRestart] - public string ListenIpAddress { get; init; } = "0.0.0.0"; - + public string IpAddress { get; init; } + /// /// Gets a value indicating whether HTTP requests should be redirected to HTTPS. /// -- cgit v1.2.3 From c026b58c435372b7042d5a1ddf911dd4429ba993 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 9 Dec 2025 19:28:43 -0600 Subject: allow lists --- src/slskd/Core/Options.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index afeb1797..1739f5fb 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1844,7 +1844,7 @@ namespace slskd [Argument(default, "http-ip-address")] [EnvironmentVariable("HTTP_IP_ADDRESS")] [Description("IP addresses on which to listen for HTTP requests")] - [IPAddress] + [IPAddress(allowCommaSeparatedValues: true)] [RequiresRestart] public string IpAddress { get; init; } -- cgit v1.2.3 From b90b5a96654727c7ded4a5b926bc315aa99014ee Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 9 Dec 2025 19:33:24 -0600 Subject: add support for commaa separated lists of IPs --- src/slskd/Common/Validation/IPAddressAttribute.cs | 31 +++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/src/slskd/Common/Validation/IPAddressAttribute.cs b/src/slskd/Common/Validation/IPAddressAttribute.cs index 6e53df57..17ae5f08 100644 --- a/src/slskd/Common/Validation/IPAddressAttribute.cs +++ b/src/slskd/Common/Validation/IPAddressAttribute.cs @@ -25,6 +25,13 @@ namespace slskd.Validation /// public class IPAddressAttribute : ValidationAttribute { + public IPAddressAttribute(bool allowCommaSeparatedValues = false) + { + AllowCommaSeparatedValues = allowCommaSeparatedValues; + } + + private bool AllowCommaSeparatedValues { get; set; } + protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (value != null) @@ -36,9 +43,29 @@ namespace slskd.Validation return fail; } - if (!IPAddress.TryParse(valueAsString, out _)) + if (!valueAsString.Contains(',')) { - return fail; + if (!IPAddress.TryParse(valueAsString, out _)) + { + return fail; + } + } + else + { + if (!AllowCommaSeparatedValues) + { + return new ValidationResult($"The {validationContext.DisplayName} field accepts a single value only (a comma separated list was specified)"); + } + + var values = valueAsString.Split(','); + + foreach (var currentValue in values) + { + if (!IPAddress.TryParse(currentValue, out _)) + { + return new ValidationResult($"The {validationContext.DisplayName} field contains one or more invalid IPv4 or IPv6 IP addresses."); + } + } } } -- cgit v1.2.3 From cf6f43d9225a996d376ea1ae21b3f52e2a06a8fe Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 10 Dec 2025 19:06:14 -0600 Subject: add support for multiple IPs --- src/slskd/Program.cs | 49 ++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 42 insertions(+), 7 deletions(-) diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index a56c8afc..d5e593b3 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -40,6 +40,7 @@ namespace slskd using Microsoft.AspNetCore.Diagnostics; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; + using Microsoft.AspNetCore.Server.Kestrel.Core; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; @@ -478,21 +479,36 @@ namespace slskd .UseUrls() .UseKestrel(options => { - var httpIpAddress = IPAddress.Parse(OptionsAtStartup.Web.ListenIpAddress); - Log.Information($"Listening for HTTP requests at http://{httpIpAddress}:{OptionsAtStartup.Web.Port}/"); - options.Listen(httpIpAddress, OptionsAtStartup.Web.Port); + // configure HTTP, either by listening at any IP or by each of the IPs provided in the + // config (note: they've already been validated at this point!) + if (string.IsNullOrWhiteSpace(OptionsAtStartup.Web.IpAddress)) + { + Log.Information("Listening for HTTP requests at http://{IP}:{Port}/", IPAddress.IPv6Any, OptionsAtStartup.Web.Port); + options.Listen(IPAddress.IPv6Any, OptionsAtStartup.Web.Port); // [::]; any IPv4 or IPv6 address + } + else + { + var httpIps = OptionsAtStartup.Web.IpAddress.Split(',').Select(ip => IPAddress.Parse(ip)); + + foreach (var ip in httpIps) + { + Log.Information("Listening for HTTP requests at http://{IP}:{Port}/", ip, OptionsAtStartup.Web.Port); + options.Listen(ip, OptionsAtStartup.Web.Port); + } + } + // configure UDS, if supplied if (OptionsAtStartup.Web.Socket != null) { Log.Information($"Listening for HTTP requests on unix domain socket (UDS) {OptionsAtStartup.Web.Socket}"); options.ListenUnixSocket(OptionsAtStartup.Web.Socket); } - if (!OptionsAtStartup.Web.Https.Disabled) + // configure HTTPS, again listening on any IP or on a list of supplied IPs + // use a local function because Microsoft can't get enough of the obtuse builder pattern + void ListenHttps(KestrelServerOptions o, IPAddress ip) { - var httpsIpAddress = IPAddress.Parse(OptionsAtStartup.Web.Https.ListenIpAddress); - Log.Information($"Listening for HTTPS requests at https://{httpsIpAddress}:{OptionsAtStartup.Web.Https.Port}/"); - options.Listen(httpsIpAddress, OptionsAtStartup.Web.Https.Port, listenOptions => + o.Listen(ip, OptionsAtStartup.Web.Https.Port, listenOptions => { var cert = OptionsAtStartup.Web.Https.Certificate; @@ -508,6 +524,25 @@ namespace slskd } }); } + + if (!OptionsAtStartup.Web.Https.Disabled) + { + if (string.IsNullOrWhiteSpace(OptionsAtStartup.Web.Https.IpAddress)) + { + Log.Information("Listening for HTTPS requests at https://{IP}:{Port}/", IPAddress.IPv6Any, OptionsAtStartup.Web.Https.Port); + ListenHttps(options, IPAddress.IPv6Any); + } + else + { + var httpsIps = OptionsAtStartup.Web.Https.IpAddress.Split(',').Select(ip => IPAddress.Parse(ip)); + + foreach (var ip in httpsIps) + { + Log.Information("Listening for HTTPS requests at https://{IP}:{Port}/", ip, OptionsAtStartup.Web.Https.Port); + ListenHttps(options, ip); + } + } + } }); builder.Services -- cgit v1.2.3 From bae7d457d930ede4c54ca538d72ca0f7cbcf3430 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 11 Dec 2025 09:03:47 -0600 Subject: update example --- config/slskd.example.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/config/slskd.example.yml b/config/slskd.example.yml index f923afbf..66379626 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -137,12 +137,12 @@ # - ^.{1,2}$ # web: # port: 5030 -# listen_ip_address: 0.0.0.0 +# ip_address: 0.0.0.0,[::] # socket: ~ # https: # disabled: false # port: 5031 -# listen_ip_address: 0.0.0.0 +# ip_address: 0.0.0.0,[::] # force: false # certificate: # pfx: ~ -- cgit v1.2.3 From 22e8ebec9534150f8d04309bd7855ef60644e030 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 11 Dec 2025 09:03:59 -0600 Subject: trim ips --- src/slskd/Program.cs | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index d5e593b3..288fa0e3 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -488,7 +488,10 @@ namespace slskd } else { - var httpIps = OptionsAtStartup.Web.IpAddress.Split(',').Select(ip => IPAddress.Parse(ip)); + var httpIps = OptionsAtStartup.Web.IpAddress + .Split(',') + .Select(ip => ip.Trim()) + .Select(ip => IPAddress.Parse(ip)); foreach (var ip in httpIps) { @@ -506,7 +509,7 @@ namespace slskd // configure HTTPS, again listening on any IP or on a list of supplied IPs // use a local function because Microsoft can't get enough of the obtuse builder pattern - void ListenHttps(KestrelServerOptions o, IPAddress ip) + static void ListenHttps(KestrelServerOptions o, IPAddress ip) { o.Listen(ip, OptionsAtStartup.Web.Https.Port, listenOptions => { @@ -534,7 +537,10 @@ namespace slskd } else { - var httpsIps = OptionsAtStartup.Web.Https.IpAddress.Split(',').Select(ip => IPAddress.Parse(ip)); + var httpsIps = OptionsAtStartup.Web.Https.IpAddress + .Split(',') + .Select(ip => ip.Trim()) + .Select(ip => IPAddress.Parse(ip)); foreach (var ip in httpsIps) { -- cgit v1.2.3 From 57a56cf2d009ebd0a67c404332ed01a338d4fe37 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 11 Dec 2025 09:04:10 -0600 Subject: trim ips --- src/slskd/Common/Validation/IPAddressAttribute.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/slskd/Common/Validation/IPAddressAttribute.cs b/src/slskd/Common/Validation/IPAddressAttribute.cs index 17ae5f08..b9075808 100644 --- a/src/slskd/Common/Validation/IPAddressAttribute.cs +++ b/src/slskd/Common/Validation/IPAddressAttribute.cs @@ -18,6 +18,7 @@ namespace slskd.Validation { using System.ComponentModel.DataAnnotations; + using System.Linq; using System.Net; /// @@ -57,7 +58,7 @@ namespace slskd.Validation return new ValidationResult($"The {validationContext.DisplayName} field accepts a single value only (a comma separated list was specified)"); } - var values = valueAsString.Split(','); + var values = valueAsString.Split(',').Select(v => v.Trim()); foreach (var currentValue in values) { -- cgit v1.2.3 From dccf744efc462775957879bb8b5e1df8732a21ac Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 11 Dec 2025 09:20:16 -0600 Subject: docs --- docs/config.md | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/docs/config.md b/docs/config.md index c0a545f9..36f57e89 100644 --- a/docs/config.md +++ b/docs/config.md @@ -798,6 +798,8 @@ soulseek: The default HTTP listen port is 5030, but can be anything between 1 and 65535. +The default HTTP IP address is `[::]` which corresponds to any IPv4 or IPv6 IP address; all network interfaces on the host. Specifying an IP address will cause the application to listen only on the specified network interface. Multiple IP addresses can be supplied in a comma-separated list, and both IPv4 and IPv6 formats can be supplied. + A [unix domain socket](https://en.wikipedia.org/wiki/Unix_domain_socket) can be used on both unix-like operating systems and Windows. The specified socket file path must be absolute, and must point to a file that does not exist (slskd will manage it automatically). The URL base option allows the application to operate behind a reverse proxy. Setting a base of "slskd" would make the web UI accessible at `http://:/slskd`. @@ -809,7 +811,7 @@ Logging of HTTP requests is disabled by default. | Command-Line | Environment Variable | Description | | -------------------------- | ------------------------------ | --------------------------------------------------- | | `-l\|--http-port` | `SLSKD_HTTP_PORT` | The HTTP listen port | -| `--http-listen-ip-address` | `SLSKD_HTTP_LISTEN_IP_ADDRESS` | The IP address on which to listen for HTTP requests | +| `--http-listen-ip-address` | `SLSKD_HTTP_IP_ADDRESS` | The IP address on which to listen for HTTP requests | | `--http-socket` | `SLSKD_HTTP_SOCKET` | The HTTP listen unix domain socket (UDS) path | | `--url-base` | `SLSKD_URL_BASE` | The base url for web requests | | `--content-path` | `SLSKD_CONTENT_PATH` | The path to static web content | @@ -819,6 +821,7 @@ Logging of HTTP requests is disabled by default. ```yaml web: port: 5030 + ip_address: "[::]" // any IPv4 or IPv6 address socket: ~ url_base: / content_path: wwwroot @@ -829,6 +832,8 @@ web: The default HTTPS port is 5031, but can be anything between 1 and 65535. +The default HTTPS IP address is `[::]` which corresponds to any IPv4 or IPv6 IP address; all network interfaces on the host. Specifying an IP address will cause the application to listen only on the specified network interface. Multiple IP addresses can be supplied in a comma-separated list, and both IPv4 and IPv6 formats can be supplied. + By default, the application generates a new, self-signed X509 certificate at each startup. If, for whatever reason, a self-signed certificate isn't sufficient, or if the certificate needs to be shared among systems or applications, a certificate `.pfx` and password can be defined. The application can produce a self-signed `.pfx` file and random password using the `--generate-cert` command. @@ -836,7 +841,7 @@ The application can produce a self-signed `.pfx` file and random password using | Command-Line | Environment Variable | Description | | --------------------------- | ------------------------------- | -------------------------------------------------------------- | | `-L\|--https-port` | `SLSKD_HTTPS_PORT` | The HTTPS listen port | -| `--https-listen-ip-address` | `SLSKD_HTTPS_LISTEN_IP_ADDRESS` | The IP address on which to listen for HTTPS requests | +| `--https-ip-address` | `SLSKD_HTTPS_IP_ADDRESS` | The IP address on which to listen for HTTPS requests | | `-f\|--force-https` | `SLSKD_HTTPS_FORCE` | Determines whether HTTP requests are to be redirected to HTTPS | | `--https-cert-pfx` | `SLSKD_HTTPS_CERT_PFX` | The path to the X509 certificate .pfx file | | `--https-cert-password` | `SLSKD_HTTPS_CERT_PASSWORD` | The password for the X509 certificate | @@ -848,6 +853,7 @@ web: https: disabled: false port: 5031 + ip_address: "[::]" // any IPv4 or IPv6 address force: false certificate: pfx: ~ -- cgit v1.2.3 From 08b20cd73d1fed6100649d3d0f4886a1c4362823 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 12 Dec 2025 09:34:01 -0600 Subject: remove single character cli args for envars and cert/secret gen --- src/slskd/Core/Options.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 1739f5fb..cca7e01d 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -115,7 +115,7 @@ namespace slskd /// /// Gets a value indicating whether to display a list of configuration environment variables. /// - [Argument('e', "envars")] + [Argument(default, "envars")] [Description("display environment variables")] [Obsolete("Used only for documentation; see Program for actual implementation")] [JsonIgnore] @@ -125,7 +125,7 @@ namespace slskd /// /// Gets a value indicating whether to generate an X509 certificate and password. /// - [Argument('g', "generate-cert")] + [Argument(default, "generate-cert")] [Description("generate X509 certificate and password for HTTPS")] [Obsolete("Used only for documentation; see Program for actual implementation")] [JsonIgnore] @@ -135,7 +135,7 @@ namespace slskd /// /// Gets a value indicating whether to generate a random secret. /// - [Argument('k', "generate-secret")] + [Argument(default, "generate-secret")] [Description("generate random secret of the specified length")] [Obsolete("Used only for documentation; see Program for actual implementation")] [JsonIgnore] -- cgit v1.2.3 From 3ec80e2cec7ebfda86493d76f3af0932197a5c98 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 12 Dec 2025 09:36:02 -0600 Subject: docs --- docs/config.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/config.md b/docs/config.md index 36f57e89..40f186f6 100644 --- a/docs/config.md +++ b/docs/config.md @@ -870,7 +870,7 @@ The JWT TTL option determines how long issued JWTs are valid, defaulting to 7 da API keys can be configured to allow for secure communication without requiring the caller to obtain a JWT by signing in with a username and password. Each key must be given a name and a key with a length between 16 and 255 characters (inclusive). Callers may then supply one of the configured keys in the `X-API-Key` header when making web requests. Remember that API keys are secrets, so keep them safe. -You can generate a random, 32 bit API key by starting the application with `-k` or `--generate-secret` at the command line. +You can generate a random, 32 bit API key by starting the application with `--generate-secret` at the command line. An optional comma separated list of [CIDRs](https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing) can be defined for each key, which will restrict usage of the key to callers with a remote IP address that falls within one of the defined CIDRs. The default CIDR list for each key is `0.0.0.0/0,::0`, which applies to any IP address (IPv4 or IPv6). @@ -1306,6 +1306,6 @@ The application can be run in "command mode", causing it to execute a command an | -------------------------------- | --------------------------------------------------- | | `-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 | -| `-k\|--generate-secret ` | Generate a random secret of the specified length | +| `--envars` | Display available environment variables | +| `--generate-cert` | Generate an X509 certificate and password for HTTPS | +| `--generate-secret ` | Generate a random secret of the specified length | -- cgit v1.2.3 From eaab0b09e0e23ca661163fe7da6ccbab64a24cc8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 12 Dec 2025 19:10:36 -0600 Subject: add validation of admin api key --- src/slskd/Core/Options.cs | 69 ++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 68 insertions(+), 1 deletion(-) diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index cca7e01d..fc367578 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1903,7 +1903,7 @@ namespace slskd /// /// Authentication options. /// - public class WebAuthenticationOptions + public class WebAuthenticationOptions : IValidatableObject { /// /// Gets a value indicating whether authentication should be disabled. @@ -1940,12 +1940,79 @@ namespace slskd [RequiresRestart] public JwtOptions Jwt { get; init; } = new JwtOptions(); + /// + /// Gets the primary API key. Defaults to 'Administrator' role and CIDR '0.0.0.0/0,::/0'. + /// role and CIDR can be supplied by prefixing the key with 'role=[role];cidr=[cidrs];[key]'. + /// + [Description("Administrative API key value")] + [Secret] + [RequiresRestart] + public string ApiKey { get; init; } + /// /// Gets API keys. /// [Validate] public Dictionary ApiKeys { get; init; } = new Dictionary(); + public IEnumerable Validate(ValidationContext validationContext) + { + var results = new List(); + + if (string.IsNullOrWhiteSpace(ApiKey)) + { + return results; + } + + var tuples = ApiKey.Split(';'); + + // if only one tuple is supplied, it's just the key, no role or list of CIDRs + if (tuples.Length == 1) + { + var key = tuples.FirstOrDefault(); + + if (key?.Length < 16 || key?.Length > 255) + { + results.Add(new ValidationResult("API key must be between 16 and 255 characters")); + } + } + + foreach (var tuple in tuples) + { + if (tuple.StartsWith("role=", StringComparison.OrdinalIgnoreCase)) + { + var role = tuple.Split('=').LastOrDefault(); + + if (!Enum.TryParse(typeof(Role), role, out _)) + { + results.Add(new ValidationResult($"API key role must be one of: {string.Join(", ", Enum.GetNames(typeof(Role)))}")); + } + } + else if (tuple.StartsWith("cidr=", StringComparison.OrdinalIgnoreCase)) + { + var cidrs = tuple.Split('=').LastOrDefault(); + + foreach (var cidr in cidrs.Split(',')) + { + try + { + _ = IPAddressRange.Parse(cidr); + } + catch (Exception ex) + { + results.Add(new ValidationResult($"API key CIDR {cidr} is invalid: {ex.Message}")); + } + } + } + else if (tuple?.Length < 16 || tuple?.Length > 255) + { + results.Add(new ValidationResult("API key must be between 16 and 255 characters")); + } + } + + return results; + } + /// /// JWT options. /// -- cgit v1.2.3 From 8892dfa4eaffcc1cbc3b1f74127911fe056188d9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 12 Dec 2025 19:11:01 -0600 Subject: auth with admin api key --- src/slskd/Core/Security/SecurityService.cs | 56 ++++++++++++++++++++++++++++-- 1 file changed, 54 insertions(+), 2 deletions(-) diff --git a/src/slskd/Core/Security/SecurityService.cs b/src/slskd/Core/Security/SecurityService.cs index 6da88571..871e6e95 100644 --- a/src/slskd/Core/Security/SecurityService.cs +++ b/src/slskd/Core/Security/SecurityService.cs @@ -45,16 +45,68 @@ namespace slskd JwtSigningKey = jwtSigningKey; OptionsAtStartup = optionsAtStartup; OptionsMonitor = optionsMonitor; + + var adminApiKeyString = OptionsMonitor.CurrentValue.Web.Authentication.ApiKey; + + if (!string.IsNullOrWhiteSpace(adminApiKeyString)) + { + if (!adminApiKeyString.Contains(';')) + { + AdministrativeApiKey = new Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions + { + Key = adminApiKeyString, + }; + } + + var tuples = adminApiKeyString.Split(';'); + + string key = null; + string role = null; + string cidr = null; + + foreach (var tuple in tuples) + { + if (tuple.StartsWith("role=", StringComparison.OrdinalIgnoreCase)) + { + role = tuple.Split('=').LastOrDefault(); + } + else if (tuple.StartsWith("cidr=", StringComparison.OrdinalIgnoreCase)) + { + cidr = tuple.Split('=').LastOrDefault(); + } + else + { + key = tuple; + } + } + + if (!string.IsNullOrEmpty(key)) + { + AdministrativeApiKey = new Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions + { + Key = key, + Role = role, + Cidr = cidr, + }; + } + } } private SymmetricSecurityKey JwtSigningKey { get; } private OptionsAtStartup OptionsAtStartup { get; } private IOptionsMonitor OptionsMonitor { get; } + private Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions AdministrativeApiKey { get; } = null; public (string Name, Role Role) AuthenticateWithApiKey(string key, IPAddress callerIpAddress) { - var record = OptionsMonitor.CurrentValue.Web.Authentication.ApiKeys - .FirstOrDefault(k => k.Value.Key == key); + var keys = OptionsMonitor.CurrentValue.Web.Authentication.ApiKeys.AsEnumerable(); + + if (AdministrativeApiKey is not null) + { + keys = keys.Prepend(new KeyValuePair(nameof(AdministrativeApiKey), AdministrativeApiKey)); + } + + var record = keys.FirstOrDefault(k => k.Value.Key == key); if (record.Key == null) { -- cgit v1.2.3 From c6f912f4df7cba8abc947f4ed57a23ed0e58d995 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 12 Dec 2025 19:13:15 -0600 Subject: todos --- src/slskd/Core/Options.cs | 1 + src/slskd/Core/Security/SecurityService.cs | 5 +++++ 2 files changed, 6 insertions(+) diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index fc367578..ced7c96f 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1957,6 +1957,7 @@ namespace slskd public IEnumerable Validate(ValidationContext validationContext) { + // TODO: test me! var results = new List(); if (string.IsNullOrWhiteSpace(ApiKey)) diff --git a/src/slskd/Core/Security/SecurityService.cs b/src/slskd/Core/Security/SecurityService.cs index 871e6e95..c5531a35 100644 --- a/src/slskd/Core/Security/SecurityService.cs +++ b/src/slskd/Core/Security/SecurityService.cs @@ -46,6 +46,10 @@ namespace slskd OptionsAtStartup = optionsAtStartup; OptionsMonitor = optionsMonitor; + // parse the configured string into an instance of ApiKeyOptions and assign it to + // AdministrativeApiKey, if a string is provided. + // this is kind of expensive in terms of allocations, so do it once at instantiation + // and mark the option with [RequiresRestart] var adminApiKeyString = OptionsMonitor.CurrentValue.Web.Authentication.ApiKey; if (!string.IsNullOrWhiteSpace(adminApiKeyString)) @@ -101,6 +105,7 @@ namespace slskd { var keys = OptionsMonitor.CurrentValue.Web.Authentication.ApiKeys.AsEnumerable(); + // TODO: test me! if (AdministrativeApiKey is not null) { keys = keys.Prepend(new KeyValuePair(nameof(AdministrativeApiKey), AdministrativeApiKey)); -- cgit v1.2.3 From 8fadf7bdd6b253895a273fe6ffc8bd4943f07ee9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 13 Dec 2025 11:48:45 -0600 Subject: tweak validation --- src/slskd/Core/Options.cs | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index ced7c96f..43363654 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1944,6 +1944,8 @@ namespace slskd /// Gets the primary API key. Defaults to 'Administrator' role and CIDR '0.0.0.0/0,::/0'. /// role and CIDR can be supplied by prefixing the key with 'role=[role];cidr=[cidrs];[key]'. /// + [Argument('k', "api-key")] + [EnvironmentVariable("API_KEY")] [Description("Administrative API key value")] [Secret] [RequiresRestart] @@ -1957,7 +1959,6 @@ namespace slskd public IEnumerable Validate(ValidationContext validationContext) { - // TODO: test me! var results = new List(); if (string.IsNullOrWhiteSpace(ApiKey)) @@ -1976,15 +1977,24 @@ namespace slskd { results.Add(new ValidationResult("API key must be between 16 and 255 characters")); } + + return results; } + /* + if multiple tuples are supplied, verify that: + + * if a tuple starts with 'role=', it's defining a role and it must match one of the Role enum values + * if a tuple starts with 'cidr=', it's defining a list of CIDRs which need to be valid + * if a tuple doesn't start with a prefix, it's the API key itself and it must be between 16 and 255 characters + */ foreach (var tuple in tuples) { if (tuple.StartsWith("role=", StringComparison.OrdinalIgnoreCase)) { var role = tuple.Split('=').LastOrDefault(); - if (!Enum.TryParse(typeof(Role), role, out _)) + if (!Enum.TryParse(typeof(Role), value: role, ignoreCase: true, out _)) { results.Add(new ValidationResult($"API key role must be one of: {string.Join(", ", Enum.GetNames(typeof(Role)))}")); } -- cgit v1.2.3 From 1c2983723e4c683f101bb9988844a2812aab749d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 13 Dec 2025 13:02:35 -0600 Subject: add logger, use file scoped namespace --- src/slskd/Core/Security/SecurityService.cs | 218 ++++++++++++++--------------- 1 file changed, 107 insertions(+), 111 deletions(-) diff --git a/src/slskd/Core/Security/SecurityService.cs b/src/slskd/Core/Security/SecurityService.cs index c5531a35..9a87449e 100644 --- a/src/slskd/Core/Security/SecurityService.cs +++ b/src/slskd/Core/Security/SecurityService.cs @@ -17,141 +17,137 @@ using Microsoft.Extensions.Options; -namespace slskd +namespace slskd; + +using System; +using System.Collections.Generic; +using System.IdentityModel.Tokens.Jwt; +using System.Linq; +using System.Net; +using System.Security.Claims; +using Microsoft.IdentityModel.Tokens; +using NetTools; +using Serilog; +using slskd.Authentication; + +public class SecurityService { - using System; - using System.Collections.Generic; - using System.IdentityModel.Tokens.Jwt; - using System.Linq; - using System.Net; - using System.Security.Claims; - using Microsoft.IdentityModel.Tokens; - using NetTools; - using slskd.Authentication; - - public interface ISecurityService + public SecurityService( + SymmetricSecurityKey jwtSigningKey, + OptionsAtStartup optionsAtStartup, + IOptionsMonitor optionsMonitor) { - JwtSecurityToken GenerateJwt(string username, Role role, int? ttl = null); - (string Name, Role Role) AuthenticateWithApiKey(string key, IPAddress callerIpAddress); - } + JwtSigningKey = jwtSigningKey; + OptionsAtStartup = optionsAtStartup; + OptionsMonitor = optionsMonitor; - public class SecurityService : ISecurityService - { - public SecurityService( - SymmetricSecurityKey jwtSigningKey, - OptionsAtStartup optionsAtStartup, - IOptionsMonitor optionsMonitor) - { - JwtSigningKey = jwtSigningKey; - OptionsAtStartup = optionsAtStartup; - OptionsMonitor = optionsMonitor; + // parse the configured string into an instance of ApiKeyOptions and assign it to + // AdministrativeApiKey, if a string is provided. + // this is kind of expensive in terms of allocations, so do it once at instantiation + // and mark the option with [RequiresRestart] + var adminApiKeyString = OptionsMonitor.CurrentValue.Web.Authentication.ApiKey; - // parse the configured string into an instance of ApiKeyOptions and assign it to - // AdministrativeApiKey, if a string is provided. - // this is kind of expensive in terms of allocations, so do it once at instantiation - // and mark the option with [RequiresRestart] - var adminApiKeyString = OptionsMonitor.CurrentValue.Web.Authentication.ApiKey; - - if (!string.IsNullOrWhiteSpace(adminApiKeyString)) + if (!string.IsNullOrWhiteSpace(adminApiKeyString)) + { + if (!adminApiKeyString.Contains(';')) { - if (!adminApiKeyString.Contains(';')) + AdministrativeApiKey = new Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions { - AdministrativeApiKey = new Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions - { - Key = adminApiKeyString, - }; - } + Key = adminApiKeyString, + }; + } - var tuples = adminApiKeyString.Split(';'); + var tuples = adminApiKeyString.Split(';'); - string key = null; - string role = null; - string cidr = null; + string key = null; + string role = null; + string cidr = null; - foreach (var tuple in tuples) + foreach (var tuple in tuples) + { + if (tuple.StartsWith("role=", StringComparison.OrdinalIgnoreCase)) { - if (tuple.StartsWith("role=", StringComparison.OrdinalIgnoreCase)) - { - role = tuple.Split('=').LastOrDefault(); - } - else if (tuple.StartsWith("cidr=", StringComparison.OrdinalIgnoreCase)) - { - cidr = tuple.Split('=').LastOrDefault(); - } - else - { - key = tuple; - } + role = tuple.Split('=').LastOrDefault(); } - - if (!string.IsNullOrEmpty(key)) + else if (tuple.StartsWith("cidr=", StringComparison.OrdinalIgnoreCase)) { - AdministrativeApiKey = new Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions - { - Key = key, - Role = role, - Cidr = cidr, - }; + cidr = tuple.Split('=').LastOrDefault(); + } + else + { + key = tuple; } } - } - private SymmetricSecurityKey JwtSigningKey { get; } - private OptionsAtStartup OptionsAtStartup { get; } - private IOptionsMonitor OptionsMonitor { get; } - private Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions AdministrativeApiKey { get; } = null; - - public (string Name, Role Role) AuthenticateWithApiKey(string key, IPAddress callerIpAddress) - { - var keys = OptionsMonitor.CurrentValue.Web.Authentication.ApiKeys.AsEnumerable(); - - // TODO: test me! - if (AdministrativeApiKey is not null) + if (!string.IsNullOrEmpty(key)) { - keys = keys.Prepend(new KeyValuePair(nameof(AdministrativeApiKey), AdministrativeApiKey)); + AdministrativeApiKey = new Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions + { + Key = key, + Role = role, + Cidr = cidr, + }; } + } + } - var record = keys.FirstOrDefault(k => k.Value.Key == key); - - if (record.Key == null) - { - throw new NotFoundException($"The provided API key does not match an existing key"); - } + private ILogger Log { get; } = Serilog.Log.ForContext(); + private SymmetricSecurityKey JwtSigningKey { get; } + private OptionsAtStartup OptionsAtStartup { get; } + private IOptionsMonitor OptionsMonitor { get; } + private Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions AdministrativeApiKey { get; } = null; - if (!record.Value.Cidr.Split(',') - .Select(cidr => IPAddressRange.Parse(cidr)) - .Any(range => range.Contains(callerIpAddress))) - { - throw new OutOfRangeException("The remote IP address is not within the range specified for the key"); - } + public (string Name, Role Role) AuthenticateWithApiKey(string key, IPAddress callerIpAddress) + { + var keys = OptionsMonitor.CurrentValue.Web.Authentication.ApiKeys.AsEnumerable(); - return (record.Key, record.Value.Role.ToEnum()); + if (AdministrativeApiKey is not null) + { + keys = keys.Prepend(new KeyValuePair(nameof(AdministrativeApiKey), AdministrativeApiKey)); } - public JwtSecurityToken GenerateJwt(string username, Role role, int? ttl = null) + var record = keys.FirstOrDefault(k => k.Value.Key == key); + + if (record.Key == null) { - var issuedUtc = DateTime.UtcNow; - var expiresUtc = DateTime.UtcNow.AddMilliseconds(ttl ?? OptionsAtStartup.Web.Authentication.Jwt.Ttl); + Log.Warning("Unauthorized access attempt: unknown API key beginning with {FirstFourCharacters}", key.Substring(0, 4)); + throw new NotFoundException($"The provided API key does not match an existing key"); + } - var claims = new List() - { - new Claim(ClaimTypes.Name, username), - new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString()), - new Claim(ClaimTypes.Role, role.ToString()), - new Claim("name", username), - new Claim("iat", ((DateTimeOffset)issuedUtc).ToUnixTimeSeconds().ToString()), - }; - - var credentials = new SigningCredentials(JwtSigningKey, SecurityAlgorithms.HmacSha256); - - var token = new JwtSecurityToken( - issuer: Program.AppName, - claims: claims, - notBefore: issuedUtc, - expires: expiresUtc, - signingCredentials: credentials); - - return token; + if (!record.Value.Cidr.Split(',') + .Select(cidr => IPAddressRange.Parse(cidr)) + .Any(range => range.Contains(callerIpAddress))) + { + Log.Warning("Unauthorized access attempt: IP Address {IP} not included in CIDR(s) for API key {Name}: {CIDR}", callerIpAddress, record.Key, record.Value.Cidr); + throw new OutOfRangeException("The remote IP address is not within the range specified for the key"); } + + return (record.Key, record.Value.Role.ToEnum()); + } + + public JwtSecurityToken GenerateJwt(string username, Role role, int? ttl = null) + { + var issuedUtc = DateTime.UtcNow; + var expiresUtc = DateTime.UtcNow.AddMilliseconds(ttl ?? OptionsAtStartup.Web.Authentication.Jwt.Ttl); + + var claims = new List() + { + new Claim(ClaimTypes.Name, username), + new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString()), + new Claim(ClaimTypes.Role, role.ToString()), + new Claim("name", username), + new Claim("iat", ((DateTimeOffset)issuedUtc).ToUnixTimeSeconds().ToString()), + }; + + var credentials = new SigningCredentials(JwtSigningKey, SecurityAlgorithms.HmacSha256); + + var token = new JwtSecurityToken( + issuer: Program.AppName, + claims: claims, + notBefore: issuedUtc, + expires: expiresUtc, + signingCredentials: credentials); + + return token; } } -- cgit v1.2.3 From 942eeb1eeb535dbaa99e3701ffea39cadcabc4db Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 13 Dec 2025 14:19:13 -0600 Subject: remove serilog --- src/slskd/Core/Security/SecurityService.cs | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/src/slskd/Core/Security/SecurityService.cs b/src/slskd/Core/Security/SecurityService.cs index 9a87449e..8b3afa44 100644 --- a/src/slskd/Core/Security/SecurityService.cs +++ b/src/slskd/Core/Security/SecurityService.cs @@ -27,7 +27,6 @@ using System.Net; using System.Security.Claims; using Microsoft.IdentityModel.Tokens; using NetTools; -using Serilog; using slskd.Authentication; public class SecurityService @@ -91,7 +90,6 @@ public class SecurityService } } - private ILogger Log { get; } = Serilog.Log.ForContext(); private SymmetricSecurityKey JwtSigningKey { get; } private OptionsAtStartup OptionsAtStartup { get; } private IOptionsMonitor OptionsMonitor { get; } @@ -110,16 +108,14 @@ public class SecurityService if (record.Key == null) { - Log.Warning("Unauthorized access attempt: unknown API key beginning with {FirstFourCharacters}", key.Substring(0, 4)); - throw new NotFoundException($"The provided API key does not match an existing key"); + throw new NotFoundException($"Unknown API key beginning with: {key.Substring(0, 4)}"); } if (!record.Value.Cidr.Split(',') .Select(cidr => IPAddressRange.Parse(cidr)) .Any(range => range.Contains(callerIpAddress))) { - Log.Warning("Unauthorized access attempt: IP Address {IP} not included in CIDR(s) for API key {Name}: {CIDR}", callerIpAddress, record.Key, record.Value.Cidr); - throw new OutOfRangeException("The remote IP address is not within the range specified for the key"); + throw new OutOfRangeException($"IP Address {callerIpAddress} not included in CIDR(s) for API key {record.Key}: {record.Value.Cidr}"); } return (record.Key, record.Value.Role.ToEnum()); -- cgit v1.2.3 From 848262831fe6281d448afd3bdcf802bbc643fbd1 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 13 Dec 2025 14:19:52 -0600 Subject: remove ISecurityService interface, add logging to api key handler --- src/slskd/Common/Authentication/ApiKeyAuthentication.cs | 9 ++++++--- src/slskd/Core/API/Controllers/SessionController.cs | 4 ++-- src/slskd/Program.cs | 4 ++-- 3 files changed, 10 insertions(+), 7 deletions(-) diff --git a/src/slskd/Common/Authentication/ApiKeyAuthentication.cs b/src/slskd/Common/Authentication/ApiKeyAuthentication.cs index 1aaa4a4f..fb209478 100644 --- a/src/slskd/Common/Authentication/ApiKeyAuthentication.cs +++ b/src/slskd/Common/Authentication/ApiKeyAuthentication.cs @@ -15,6 +15,7 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // +using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace slskd.Authentication @@ -24,7 +25,7 @@ namespace slskd.Authentication using System.Text.Encodings.Web; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; - using Microsoft.Extensions.Logging; + using Serilog; /// /// API key authentication. @@ -51,7 +52,7 @@ namespace slskd.Authentication /// A url encoder. public ApiKeyAuthenticationHandler( IOptionsMonitor apiKeyOptionsMonitor, - ISecurityService securityService, + SecurityService securityService, ILoggerFactory logger, UrlEncoder urlEncoder) : base(apiKeyOptionsMonitor, logger, urlEncoder) @@ -59,7 +60,8 @@ namespace slskd.Authentication Security = securityService; } - private ISecurityService Security { get; } + private ILogger Log { get; } = Serilog.Log.ForContext(); + private SecurityService Security { get; } /// /// Authenticates via API key. @@ -86,6 +88,7 @@ namespace slskd.Authentication } catch (Exception ex) { + Log.Warning(ex, "Unauthorized: {Message}", ex.Message); return AuthenticateResult.Fail(ex); } } diff --git a/src/slskd/Core/API/Controllers/SessionController.cs b/src/slskd/Core/API/Controllers/SessionController.cs index 861fd468..cfcb3f23 100644 --- a/src/slskd/Core/API/Controllers/SessionController.cs +++ b/src/slskd/Core/API/Controllers/SessionController.cs @@ -36,7 +36,7 @@ namespace slskd.Core.API public class SessionController : ControllerBase { public SessionController( - ISecurityService securityService, + SecurityService securityService, IOptionsSnapshot optionsSnapshot, OptionsAtStartup optionsAtStartup) { @@ -47,7 +47,7 @@ namespace slskd.Core.API private IOptionsSnapshot OptionsSnapshot { get; set; } private OptionsAtStartup OptionsAtStartup { get; set; } - private ISecurityService Security { get; } + private SecurityService Security { get; } private ILogger Log { get; } = Serilog.Log.ForContext(); /// diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 288fa0e3..cb1961a2 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -768,7 +768,7 @@ namespace slskd var jwtSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(OptionsAtStartup.Web.Authentication.Jwt.Key)); services.AddSingleton(jwtSigningKey); - services.AddSingleton(); + services.AddSingleton(); if (!OptionsAtStartup.Web.Authentication.Disabled) { @@ -835,7 +835,7 @@ namespace slskd try { // check to see if the provided value is a valid API key - var service = services.BuildServiceProvider().GetRequiredService(); + var service = services.BuildServiceProvider().GetRequiredService(); var (name, role) = service.AuthenticateWithApiKey(token, callerIpAddress: context.HttpContext.Connection.RemoteIpAddress); // the API key is valid. create a new, short lived jwt for the key name and role -- cgit v1.2.3 From fc1aecbe54b0077d0fde20f9f8e6350312344692 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 13 Dec 2025 14:36:09 -0600 Subject: tweak logging --- src/slskd/Common/Authentication/ApiKeyAuthentication.cs | 2 +- src/slskd/Core/Security/SecurityService.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/slskd/Common/Authentication/ApiKeyAuthentication.cs b/src/slskd/Common/Authentication/ApiKeyAuthentication.cs index fb209478..e2733442 100644 --- a/src/slskd/Common/Authentication/ApiKeyAuthentication.cs +++ b/src/slskd/Common/Authentication/ApiKeyAuthentication.cs @@ -88,7 +88,7 @@ namespace slskd.Authentication } catch (Exception ex) { - Log.Warning(ex, "Unauthorized: {Message}", ex.Message); + Log.Warning("Unauthorized request from IP address {IP}: {Message}", Request.HttpContext.Connection.RemoteIpAddress, ex.Message); return AuthenticateResult.Fail(ex); } } diff --git a/src/slskd/Core/Security/SecurityService.cs b/src/slskd/Core/Security/SecurityService.cs index 8b3afa44..e98dd5eb 100644 --- a/src/slskd/Core/Security/SecurityService.cs +++ b/src/slskd/Core/Security/SecurityService.cs @@ -115,7 +115,7 @@ public class SecurityService .Select(cidr => IPAddressRange.Parse(cidr)) .Any(range => range.Contains(callerIpAddress))) { - throw new OutOfRangeException($"IP Address {callerIpAddress} not included in CIDR(s) for API key {record.Key}: {record.Value.Cidr}"); + throw new OutOfRangeException($"IP address {callerIpAddress} not included in CIDR range(s) for API key {record.Key}; allowed: {record.Value.Cidr}"); } return (record.Key, record.Value.Role.ToEnum()); -- cgit v1.2.3 From 0b06e03e7091b486b99c74d71609fe1caa9e1093 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 13 Dec 2025 16:00:33 -0600 Subject: default to administrator and all CIDRs --- src/slskd/Core/Security/SecurityService.cs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/slskd/Core/Security/SecurityService.cs b/src/slskd/Core/Security/SecurityService.cs index e98dd5eb..254b3081 100644 --- a/src/slskd/Core/Security/SecurityService.cs +++ b/src/slskd/Core/Security/SecurityService.cs @@ -41,7 +41,7 @@ public class SecurityService OptionsMonitor = optionsMonitor; // parse the configured string into an instance of ApiKeyOptions and assign it to - // AdministrativeApiKey, if a string is provided. + // PrimaryApiKey, if a string is provided. // this is kind of expensive in terms of allocations, so do it once at instantiation // and mark the option with [RequiresRestart] var adminApiKeyString = OptionsMonitor.CurrentValue.Web.Authentication.ApiKey; @@ -50,7 +50,7 @@ public class SecurityService { if (!adminApiKeyString.Contains(';')) { - AdministrativeApiKey = new Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions + PrimaryApiKey = new Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions { Key = adminApiKeyString, }; @@ -80,11 +80,11 @@ public class SecurityService if (!string.IsNullOrEmpty(key)) { - AdministrativeApiKey = new Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions + PrimaryApiKey = new Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions { Key = key, - Role = role, - Cidr = cidr, + Role = string.IsNullOrWhiteSpace(role) ? Role.Administrator.ToString() : role, + Cidr = string.IsNullOrWhiteSpace(cidr) ? "0.0.0.0/0,::/0" : cidr, }; } } @@ -93,15 +93,15 @@ public class SecurityService private SymmetricSecurityKey JwtSigningKey { get; } private OptionsAtStartup OptionsAtStartup { get; } private IOptionsMonitor OptionsMonitor { get; } - private Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions AdministrativeApiKey { get; } = null; + private Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions PrimaryApiKey { get; } = null; public (string Name, Role Role) AuthenticateWithApiKey(string key, IPAddress callerIpAddress) { var keys = OptionsMonitor.CurrentValue.Web.Authentication.ApiKeys.AsEnumerable(); - if (AdministrativeApiKey is not null) + if (PrimaryApiKey is not null) { - keys = keys.Prepend(new KeyValuePair(nameof(AdministrativeApiKey), AdministrativeApiKey)); + keys = keys.Prepend(new KeyValuePair(nameof(PrimaryApiKey), PrimaryApiKey)); } var record = keys.FirstOrDefault(k => k.Value.Key == key); -- cgit v1.2.3 From 9296ec4295a7d6a2371e19d38d6a32ef285eb373 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 13 Dec 2025 16:00:53 -0600 Subject: administrative -> primary --- src/slskd/Core/Options.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 43363654..20b53f6c 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1946,7 +1946,7 @@ namespace slskd /// [Argument('k', "api-key")] [EnvironmentVariable("API_KEY")] - [Description("Administrative API key value")] + [Description("primary API key value")] [Secret] [RequiresRestart] public string ApiKey { get; init; } -- cgit v1.2.3 From 804f661ab5d0e3b6ffdfd6a5b38959ac1b1690be Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 13 Dec 2025 16:11:45 -0600 Subject: docs for API keys --- docs/config.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/docs/config.md b/docs/config.md index 40f186f6..6ba5bd2a 100644 --- a/docs/config.md +++ b/docs/config.md @@ -864,10 +864,16 @@ web: Authentication for the web UI (and underlying API) is enabled by default, and the default username and password are both `slskd`. Changing both the username and password during the initial configuration is highly recommended. +### JWT (Json Web Token) + +JWTs are used to authenticate the UI, and are generated by making an API call and supplying a username and password. + By default, a random JWT secret key is generated at each start. It is convenient and secure, but restarting the application will invalidate any issued JWTs, causing users to sign in again. To avoid this, supply a custom secret at least 16 characters in length. Note that the secret can be used to generate valid JWTs for the application, so keep this value secret. The JWT TTL option determines how long issued JWTs are valid, defaulting to 7 days. +### API Keys + API keys can be configured to allow for secure communication without requiring the caller to obtain a JWT by signing in with a username and password. Each key must be given a name and a key with a length between 16 and 255 characters (inclusive). Callers may then supply one of the configured keys in the `X-API-Key` header when making web requests. Remember that API keys are secrets, so keep them safe. You can generate a random, 32 bit API key by starting the application with `--generate-secret` at the command line. @@ -876,6 +882,15 @@ An optional comma separated list of [CIDRs](https://en.wikipedia.org/wiki/Classl A common use case for CIDR filtering might be to restrict API access to clients within your home network. Assuming your network uses the common `192.168.1.x` addressing, you could specify a `cidr` of `192.168.1.0/24`, which would apply to any IP between `192.168.1.1` and `192.168.1.254`, inclusive. +An optional 'primary' API key can be configured by passiing it via `-k` or `--api-key` on the command line, or by setting the `SLSKD_API_KEY` environment variable. As with other API keys, a role and list of CIDRs can be supplied, but because the command line and environment variables are limited to a simple string, the role and CIDRs must be passed via tuples separated by semicolons: + +``` +role=ReadOnly;cidr=0.0.0.0/0,::/0;<16 to 255 character string> +``` + +By default, the role associated with the 'primary' API key is `Administrator` (other API keys default to `ReadOnly`) and list of CIDRs is `0.0.0.0/0,::0` (same as other API keys). + +#### Cautions Note that CIDR filtering may not work as expected behind a reverse proxy, ingress controller, or load balancer, because the remote IP address will be that of the device that's handling ingress. This application doesn't support the `X-Forwarded-For` header (or anything like it) because a bad actor can easily fake it. If you wish to use CIDR filtering in this scenario, you'll need to do it at the point of ingress to your network. Please also note that using API key authentication without HTTPS is **NOT RECOMMENDED**. API keys are sent in HTTP headers (and in the case of SignalR, in query parameters) and will be easily accessible to anyone eavesdropping on the network. This is a risk with JWTs as well, but JWTs expire and API keys don't. If you choose to use API keys over plain HTTP, seriously consider using CIDR filtering. @@ -885,6 +900,7 @@ Please also note that using API key authentication without HTTPS is **NOT RECOMM | `-X\|--no-auth` | `SLSKD_NO_AUTH` | Determines whether authentication is to be disabled | | `-u\|--username` | `SLSKD_USERNAME` | The username for the web UI | | `-p\|--password` | `SLSKD_PASSWORD` | The password for the web UI | +| `-k\|--api-key` | `SLSKD_API_KEY` | The primary API key | | `--jwt-key` | `SLSKD_JWT_KEY` | The secret key used to sign JWTs | | `--jwt-ttl` | `SLSKD_JWT_TTL` | The TTL (duration) of JWTs, in milliseconds | -- cgit v1.2.3 From 0d548ed62517ed1807d3c13f96772f33a9a3c1d1 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 13 Dec 2025 16:33:37 -0600 Subject: warning about ipv6 --- docs/config.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/config.md b/docs/config.md index 6ba5bd2a..1ab7daec 100644 --- a/docs/config.md +++ b/docs/config.md @@ -891,6 +891,9 @@ role=ReadOnly;cidr=0.0.0.0/0,::/0;<16 to 255 character string> By default, the role associated with the 'primary' API key is `Administrator` (other API keys default to `ReadOnly`) and list of CIDRs is `0.0.0.0/0,::0` (same as other API keys). #### Cautions + +When using CIDR filtering, you *must* supply both IPv4 and IPv6 ranges. + Note that CIDR filtering may not work as expected behind a reverse proxy, ingress controller, or load balancer, because the remote IP address will be that of the device that's handling ingress. This application doesn't support the `X-Forwarded-For` header (or anything like it) because a bad actor can easily fake it. If you wish to use CIDR filtering in this scenario, you'll need to do it at the point of ingress to your network. Please also note that using API key authentication without HTTPS is **NOT RECOMMENDED**. API keys are sent in HTTP headers (and in the case of SignalR, in query parameters) and will be easily accessible to anyone eavesdropping on the network. This is a risk with JWTs as well, but JWTs expire and API keys don't. If you choose to use API keys over plain HTTP, seriously consider using CIDR filtering. -- cgit v1.2.3 From 1e0eb94a16fd6b8a3204bc14e11c0c5d47617d0c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 13 Dec 2025 16:35:06 -0600 Subject: on second thought, remove caution --- docs/config.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/docs/config.md b/docs/config.md index 1ab7daec..3efe2e8a 100644 --- a/docs/config.md +++ b/docs/config.md @@ -892,8 +892,6 @@ By default, the role associated with the 'primary' API key is `Administrator` (o #### Cautions -When using CIDR filtering, you *must* supply both IPv4 and IPv6 ranges. - Note that CIDR filtering may not work as expected behind a reverse proxy, ingress controller, or load balancer, because the remote IP address will be that of the device that's handling ingress. This application doesn't support the `X-Forwarded-For` header (or anything like it) because a bad actor can easily fake it. If you wish to use CIDR filtering in this scenario, you'll need to do it at the point of ingress to your network. Please also note that using API key authentication without HTTPS is **NOT RECOMMENDED**. API keys are sent in HTTP headers (and in the case of SignalR, in query parameters) and will be easily accessible to anyone eavesdropping on the network. This is a risk with JWTs as well, but JWTs expire and API keys don't. If you choose to use API keys over plain HTTP, seriously consider using CIDR filtering. -- cgit v1.2.3 From e08479ee8d91952fee13b009f861912a92a2dbae Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 13 Dec 2025 17:15:16 -0600 Subject: tweak --- src/slskd/Program.cs | 25 +++++++++---------------- 1 file changed, 9 insertions(+), 16 deletions(-) diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 3bd0798b..db4f7c6c 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -23,8 +23,6 @@ namespace slskd using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; - using System.Diagnostics; - using System.IO; using System.Linq; using System.Net; @@ -337,10 +335,9 @@ namespace slskd // only one long-running instance. try { - bool createdNew; - Mutex = new Mutex(initiallyOwned: true, Compute.Sha256Hash(AppName), out createdNew); + Mutex = new Mutex(initiallyOwned: true, Compute.Sha256Hash(AppName), out bool created); - if (!createdNew) + if (!created) { Log.Fatal($"An instance of {AppName} is already running"); return; @@ -348,22 +345,18 @@ namespace slskd } catch (IOException ex) { - Log.Warning($"Failed to acquire the application singleton mutex: {ex.Message}"); - Log.Warning("This can happen when running in a restricted environment (e.g., Kubernetes with readOnlyRootFilesystem)"); - Log.Warning("The application will continue, but multiple instances may be able to run simultaneously"); + Log.Fatal($"I/O exception attempting to acquire the application singleton mutex; this can happen when running in a restricted environment (such as a read-only filesystem or container). Exception: {ex.Message}"); + return; } catch (UnauthorizedAccessException ex) { - Log.Warning($"Failed to acquire the application singleton mutex: {ex.Message}"); - Log.Warning("This can happen when running with insufficient permissions"); - Log.Warning("The application will continue, but multiple instances may be able to run simultaneously"); + Log.Fatal($"Unauthorized access attempting to acquire the application singleton mutex; this can happen when running with insuffucent permissions. Exception: {ex.Message}"); + return; } - catch (AbandonedMutexException ex) + catch (Exception ex) { - Log.Warning($"Acquired an abandoned mutex: {ex.Message}"); - Log.Warning("A previous instance may have terminated unexpectedly"); - - // The mutex is now owned by this thread, so we can continue + Log.Fatal($"Failed to acquire the application singleton mutex: {ex.Message}"); + return; } // derive the application directory value and defaults that are dependent upon it -- cgit v1.2.3 From 7b754893dd0fdf775346c9a0a6ccd20399c50bea Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 18 Dec 2025 08:42:36 -0600 Subject: add enqueue metrics --- src/slskd/Telemetry/Metrics.cs | 58 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 57 insertions(+), 1 deletion(-) diff --git a/src/slskd/Telemetry/Metrics.cs b/src/slskd/Telemetry/Metrics.cs index 7bc6fd25..33d2bc40 100644 --- a/src/slskd/Telemetry/Metrics.cs +++ b/src/slskd/Telemetry/Metrics.cs @@ -83,7 +83,7 @@ public static class Metrics "The time taken to resolve a response to an incoming browse request, in milliseconds", new HistogramConfiguration { - Buckets = Histogram.ExponentialBuckets(1, 2, 10), + Buckets = Histogram.ExponentialBuckets(start: 1, factor: 2, count: 10), }); /// @@ -104,6 +104,62 @@ public static class Metrics private static Gauge CurrentResponseLatencyGauge { get; } = Prometheus.Metrics.CreateGauge("slskd_browse_response_latency_current", "The average time taken to resolve a response to an incoming browse request, in milliseconds"); } + /// + /// Metrics related to incoming enqueue requests and responses. + /// + public static class Enqueue + { + /// + /// Gets a histogram representing the time taken to evaluate an incoming request to enqueue a file against configured limits, in milliseconds. + /// + public static Histogram DecisionLatency { get; } = Prometheus.Metrics.CreateHistogram( + "slskd_enqueue_decision_latency", + "The time taken to evaluate an incoming request to enqueue a file against configured limits, in milliseconds", + new HistogramConfiguration + { + Buckets = Histogram.ExponentialBuckets(start: 1, factor: 2, count: 16), // up to ~2 seconds + }); + + /// + /// Gets an EMA representing the average time taken to evaluate an incoming request to enqueue a file against configured limits, in milliseconds. + /// + public static ExponentialMovingAverage CurrentDecisionLatency { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentDecisionLatencyGauge.Set(value)); + + /// + /// Gets a histogram representing the total time taken to resolve a response to an incoming request to enqueue a file, in milliseconds. + /// + public static Histogram ResponseLatency { get; } = Prometheus.Metrics.CreateHistogram( + "slskd_enqueue_response_latency", + "The total time taken to resolve a response to an incoming request to enqueue a file, in milliseconds", + new HistogramConfiguration + { + Buckets = Histogram.ExponentialBuckets(start: 1, factor: 2, count: 16), // up to ~2 seconds + }); + + /// + /// Gets an EMA representing the average total time taken to resolve a response to an incoming request to enqueue a file, in milliseconds. + /// + public static ExponentialMovingAverage CurrentResponseLatency { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentResponseLatencyGauge.Set(value)); + + /// + /// Gets a counter representing the total number of incoming enqueue requests received. + /// + public static Counter RequestsReceived { get; } = Prometheus.Metrics.CreateCounter("slskd_enqueue_requests_received", "Total number of incoming enqueue requests received"); + + /// + /// Gets a counter representing the total number of incoming enqueue requests accepted. + /// + public static Counter RequestsAccepted { get; } = Prometheus.Metrics.CreateCounter("slskd_enqueue_requests_accepted", "Total number of incoming enqueue requests accepted"); + + /// + /// Gets a gauge representing the number of incoming enqueue requests waiting to be processed. + /// + public static Gauge CurrentRequestQueueDepth { get; } = Prometheus.Metrics.CreateGauge("slskd_enqueue_request_queue_depth_current", "The number of incoming enqueue requests waiting to be processed"); + + private static Gauge CurrentDecisionLatencyGauge { get; } = Prometheus.Metrics.CreateGauge("slskd_enqueue_decision_latency_current", "The average time taken to evaluate an incoming request to enqueue a file against configured limits, in milliseconds"); + private static Gauge CurrentResponseLatencyGauge { get; } = Prometheus.Metrics.CreateGauge("slskd_enqueue_response_latency_current", "The average total time taken to resolve a response to an incoming request to enqueue a file, in milliseconds"); + } + /// /// Metrics related to the distributed network. /// -- cgit v1.2.3 From 1378c0498a2206ebc0cc39045f6f1bc330a22ce6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 18 Dec 2025 08:47:03 -0600 Subject: emit enqueue metrics --- src/slskd/Application.cs | 42 ++++++++++++++++++++++++++++++++---------- 1 file changed, 32 insertions(+), 10 deletions(-) diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 1a18790f..97d3392c 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -40,7 +40,6 @@ namespace slskd using Serilog.Events; using slskd.Configuration; using slskd.Core.API; - using slskd.Events; using slskd.Files; using slskd.Integrations.Pushbullet; using slskd.Messaging; @@ -83,6 +82,12 @@ namespace slskd private static readonly string ApplicationShutdownTransferExceptionMessage = "Application shut down"; +#pragma warning disable SA1306 // Field names should begin with lower-case letter + + private static int EnqueueRequestQueueDepth = 0; +#pragma warning restore SA1306 // Field names should begin with lower-case letter + + public Application( OptionsAtStartup optionsAtStartup, IOptionsMonitor optionsMonitor, @@ -537,20 +542,28 @@ namespace slskd // todo: consider moving this somewhere else; it's pretty long and complicated private async Task EnqueueDownload(string username, IPEndPoint endpoint, string filename) { + Metrics.Enqueue.RequestsReceived.Inc(1); + + if (Users.IsBlacklisted(username, endpoint.Address)) + { + Log.Information("Rejected enqueue request for blacklisted user {Username} ({IP})", username, endpoint.Address); + throw new DownloadEnqueueException("File not shared."); + } + var stopwatch = new Stopwatch(); var decisionStopwatch = new Stopwatch(); + Interlocked.Increment(ref EnqueueRequestQueueDepth); + await EnqueueRequestRateLimiter.WaitAsync(); try { - stopwatch.Start(); + Interlocked.Decrement(ref EnqueueRequestQueueDepth); - if (Users.IsBlacklisted(username, endpoint.Address)) - { - Log.Information("Rejected enqueue request for blacklisted user {Username} ({IP})", username, endpoint.Address); - throw new DownloadEnqueueException("File not shared."); - } + Metrics.Enqueue.CurrentRequestQueueDepth.Set(EnqueueRequestQueueDepth); + + stopwatch.Start(); // in order to properly determine if the requested file would exceed any limits, we need to know the size of the file // it helps, too, that this will tell us whether the file is even shared. @@ -747,12 +760,21 @@ namespace slskd } await Transfers.Uploads.EnqueueAsync(username, filename); - } - finally - { + + Metrics.Enqueue.RequestsAccepted.Inc(1); + decisionStopwatch.Stop(); + + Metrics.Enqueue.DecisionLatency.Observe(decisionStopwatch.ElapsedMilliseconds); + Metrics.Enqueue.CurrentDecisionLatency.Update(decisionStopwatch.ElapsedMilliseconds); + stopwatch.Stop(); + Metrics.Enqueue.ResponseLatency.Observe(stopwatch.ElapsedMilliseconds); + Metrics.Enqueue.CurrentResponseLatency.Update(stopwatch.ElapsedMilliseconds); + } + finally + { EnqueueRequestRateLimiter.Release(); Log.Debug("EnqueueDownload for {Username}/{Filename} completed in {ElapsedOverall}ms, decision made in {ElapsedDecision}ms", username, filename, stopwatch.ElapsedMilliseconds, decisionStopwatch.ElapsedMilliseconds); -- cgit v1.2.3 From 0262d64300bb246a7da0037bc016724a8f003677 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 21 Dec 2025 17:30:35 -0600 Subject: add indexes to cover timestamps on share (pruning mostly) --- src/slskd/Shares/SqliteShareRepository.cs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/slskd/Shares/SqliteShareRepository.cs b/src/slskd/Shares/SqliteShareRepository.cs index 711bb21e..cb0c331a 100644 --- a/src/slskd/Shares/SqliteShareRepository.cs +++ b/src/slskd/Shares/SqliteShareRepository.cs @@ -177,6 +177,10 @@ namespace slskd.Shares conn.ExecuteNonQuery("CREATE TABLE IF NOT EXISTS files " + "(maskedFilename TEXT PRIMARY KEY, originalFilename TEXT NOT NULL, size BIGINT NOT NULL, touchedAt TEXT NOT NULL, code INTEGER DEFAULT 1 NOT NULL, " + "extension TEXT, attributeJson TEXT NOT NULL, timestamp INTEGER NOT NULL);"); + + conn.ExecuteNonQuery("CREATE INDEX IF NOT EXISTS idx_files_timestamp ON files(timestamp)"); + conn.ExecuteNonQuery("CREATE INDEX IF NOT EXISTS idx_directories_timestamp ON directories(timestamp)"); + conn.ExecuteNonQuery("CREATE INDEX IF NOT EXISTS idx_scans_timestamp ON scans(timestamp DESC)"); } /// -- cgit v1.2.3 From b88da4223defea838dee153a0dc464773e31e737 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 25 Dec 2025 18:46:25 -0600 Subject: add TransferStateCategories --- .../Transfers/Types/TransferStateCategories.cs | 91 ++++++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 src/slskd/Transfers/Types/TransferStateCategories.cs diff --git a/src/slskd/Transfers/Types/TransferStateCategories.cs b/src/slskd/Transfers/Types/TransferStateCategories.cs new file mode 100644 index 00000000..71f8e962 --- /dev/null +++ b/src/slskd/Transfers/Types/TransferStateCategories.cs @@ -0,0 +1,91 @@ +// +// 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.Transfers; + +using System.Collections.Generic; +using Soulseek; + +/// +/// A collection of transfer state integers, collected into arrays that represent common states. +/// +/// +/// SQLite can't take advantage of indexes when using bitwise operations, which is what Entity Franework +/// turns HasFlag() expressions into. These arrays allow us to use IN expressions instead of bitwise. +/// +public static class TransferStateCategories +{ + /// + /// All states representing a successful transfer: + /// + /// + /// + /// + /// + public static readonly HashSet Successful = [(int)(TransferStates.Completed | TransferStates.Succeeded)]; + + /// + /// All states representing a failed transfer: + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static readonly HashSet Failed = [ + (int)(TransferStates.Completed | TransferStates.Cancelled), + (int)(TransferStates.Completed | TransferStates.TimedOut), + (int)(TransferStates.Completed | TransferStates.Errored), + (int)(TransferStates.Completed | TransferStates.Rejected), + (int)(TransferStates.Completed | TransferStates.Aborted), + ]; + + /// + /// All states containing the flag. + /// + public static readonly HashSet Completed = [.. Successful, .. Failed]; + + /// + /// All states representing a queued transfer: + /// + /// + /// + /// + /// + /// + public static readonly HashSet Queued = [ + (int)TransferStates.Queued, + (int)(TransferStates.Queued | TransferStates.Locally), + (int)(TransferStates.Queued | TransferStates.Remotely), + ]; + + /// + /// All states representing a transfer that is in progress: + /// + /// + /// + /// + /// + /// + public static readonly HashSet InProgress = [ + (int)TransferStates.Initializing, + (int)TransferStates.InProgress, + ]; +} \ No newline at end of file -- cgit v1.2.3 From b5c0c10a992081ad16e711bdeff69dad19ced62c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 25 Dec 2025 18:46:39 -0600 Subject: change clear expressions to use categories --- src/slskd/Transfers/API/Controllers/TransfersController.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index 6be11b2d..d2da8caf 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -115,7 +115,7 @@ namespace slskd.Transfers.API return Forbid(); } - var transfers = Transfers.Downloads.List(t => t.State.HasFlag(Soulseek.TransferStates.Completed)); + var transfers = Transfers.Downloads.List(t => TransferStateCategories.Completed.Contains((int)t.State)); foreach (var id in transfers.Select(t => t.Id)) { @@ -184,7 +184,7 @@ namespace slskd.Transfers.API // get all the transfers that aren't removed var transfers = Transfers.Uploads - .List(t => t.State.HasFlag(Soulseek.TransferStates.Completed), includeRemoved: false); + .List(t => TransferStateCategories.Completed.Contains((int)t.State), includeRemoved: false); foreach (var id in transfers.Select(t => t.Id)) { -- cgit v1.2.3 From d36b9703df5cbd498540ee941c1149b0ae851a8f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 25 Dec 2025 18:47:02 -0600 Subject: use categories for pruning --- src/slskd/Application.cs | 4 ++-- src/slskd/Transfers/Downloads/DownloadService.cs | 18 ++++++++++-------- src/slskd/Transfers/Uploads/UploadService.cs | 18 ++++++++++-------- 3 files changed, 22 insertions(+), 18 deletions(-) diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 97d3392c..31b99e3b 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -1178,7 +1178,7 @@ namespace slskd { if (age.HasValue) { - Transfers.Uploads.Prune(age.Value, TransferStates.Completed | state); + Transfers.Uploads.Prune(age.Value, (int)(TransferStates.Completed | state)); } } @@ -1186,7 +1186,7 @@ namespace slskd { if (age.HasValue) { - Transfers.Downloads.Prune(age.Value, TransferStates.Completed | state); + Transfers.Downloads.Prune(age.Value, (int)(TransferStates.Completed | state)); } } diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 9bc25373..54fed035 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -89,9 +89,9 @@ namespace slskd.Transfers.Downloads /// Removes downloads older than the specified . /// /// The age after which downloads are eligible for pruning, in hours. - /// An optional, additional state by which downloads are filtered for pruning. + /// One or more states by which downloads are filtered for pruning. /// The number of pruned downloads. - int Prune(int age, TransferStates stateHasFlag = TransferStates.Completed); + int Prune(int age, params int[] states); /// /// Removes the download matching the specified . @@ -663,13 +663,15 @@ namespace slskd.Transfers.Downloads /// Removes downloads older than the specified . /// /// The age after which downloads are eligible for pruning, in hours. - /// An optional, additional state by which downloads are filtered for pruning. + /// One or more states by which downloads are filtered for pruning. /// The number of pruned downloads. - public int Prune(int age, TransferStates stateHasFlag = TransferStates.Completed) + public int Prune(int age, params int[] states) { - if (!stateHasFlag.HasFlag(TransferStates.Completed)) + var statesSet = new HashSet(states); + + if (!statesSet.All(s => ((TransferStates)s).HasFlag(TransferStates.Completed))) { - throw new ArgumentException($"State must include {TransferStates.Completed}", nameof(stateHasFlag)); + throw new ArgumentException($"Each state must include {TransferStates.Completed}", nameof(states)); } try @@ -682,7 +684,7 @@ namespace slskd.Transfers.Downloads .Where(t => t.Direction == TransferDirection.Download) .Where(t => !t.Removed) .Where(t => t.EndedAt.HasValue && t.EndedAt.Value < cutoffDateTime) - .Where(t => t.State == stateHasFlag) + .Where(t => statesSet.Contains((int)t.State)) .ToList(); foreach (var tx in expired) @@ -694,7 +696,7 @@ namespace slskd.Transfers.Downloads if (pruned > 0) { - Log.Debug("Pruned {Count} expired downloads with state {State}", pruned, stateHasFlag); + Log.Debug("Pruned {Count} expired downloads with states {States}", pruned, statesSet); } return pruned; diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index c96d1131..e6988ce0 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -107,9 +107,9 @@ namespace slskd.Transfers.Uploads /// Removes uploads older than the specified . /// /// The age after which uploads are eligible for pruning, in minutes. - /// An optional, additional state by which uploads are filtered for pruning. + /// One or more states by which uploads are filtered for pruning. /// The number of pruned uploads. - int Prune(int age, TransferStates stateHasFlag = TransferStates.Completed); + int Prune(int age, params int[] states); /// /// Removes the upload matching the specified . @@ -780,13 +780,15 @@ namespace slskd.Transfers.Uploads /// Removes uploads older than the specified . /// /// The age after which uploads are eligible for pruning, in minutes. - /// An optional, additional state by which uploads are filtered for pruning. + /// One or more states by which uploads are filtered for pruning. /// The number of pruned uploads. - public int Prune(int age, TransferStates stateHasFlag = TransferStates.Completed) + public int Prune(int age, params int[] states) { - if (!stateHasFlag.HasFlag(TransferStates.Completed)) + var statesSet = new HashSet(states); + + if (!statesSet.All(s => ((TransferStates)s).HasFlag(TransferStates.Completed))) { - throw new ArgumentException($"State must include {TransferStates.Completed}", nameof(stateHasFlag)); + throw new ArgumentException($"Each state must include {TransferStates.Completed}", nameof(states)); } try @@ -799,7 +801,7 @@ namespace slskd.Transfers.Uploads .Where(t => t.Direction == TransferDirection.Upload) .Where(t => !t.Removed) .Where(t => t.EndedAt.HasValue && t.EndedAt.Value < cutoffDateTime) - .Where(t => t.State.HasFlag(stateHasFlag)) + .Where(t => statesSet.Contains((int)t.State)) .ToList(); foreach (var tx in expired) @@ -811,7 +813,7 @@ namespace slskd.Transfers.Uploads if (pruned > 0) { - Log.Debug("Pruned {Count} expired uploads with state {State}", pruned, stateHasFlag); + Log.Debug("Pruned {Count} expired uploads with states {States}", pruned, statesSet); } return pruned; -- cgit v1.2.3 From d051daf9290479cc1a2117341587f563b88534af Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 25 Dec 2025 19:07:18 -0600 Subject: improve pruning --- src/slskd/Transfers/Downloads/DownloadService.cs | 11 ++--------- src/slskd/Transfers/Uploads/UploadService.cs | 11 ++--------- 2 files changed, 4 insertions(+), 18 deletions(-) diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 54fed035..a22d489f 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -680,19 +680,12 @@ namespace slskd.Transfers.Downloads var cutoffDateTime = DateTime.UtcNow.AddMinutes(-age); - var expired = context.Transfers + var pruned = context.Transfers .Where(t => t.Direction == TransferDirection.Download) .Where(t => !t.Removed) .Where(t => t.EndedAt.HasValue && t.EndedAt.Value < cutoffDateTime) .Where(t => statesSet.Contains((int)t.State)) - .ToList(); - - foreach (var tx in expired) - { - tx.Removed = true; - } - - var pruned = context.SaveChanges(); + .ExecuteUpdate(r => r.SetProperty(c => c.Removed, true)); if (pruned > 0) { diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index e6988ce0..6657a28f 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -797,19 +797,12 @@ namespace slskd.Transfers.Uploads var cutoffDateTime = DateTime.UtcNow.AddMinutes(-age); - var expired = context.Transfers + var pruned = context.Transfers .Where(t => t.Direction == TransferDirection.Upload) .Where(t => !t.Removed) .Where(t => t.EndedAt.HasValue && t.EndedAt.Value < cutoffDateTime) .Where(t => statesSet.Contains((int)t.State)) - .ToList(); - - foreach (var tx in expired) - { - tx.Removed = true; - } - - var pruned = context.SaveChanges(); + .ExecuteUpdate(r => r.SetProperty(c => c.Removed, true)); if (pruned > 0) { -- cgit v1.2.3 From 65d33809bfd4a3d9da23b029b5fd34fe8cf0f3c5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 26 Dec 2025 14:18:32 -0600 Subject: add Incomplete category --- src/slskd/Transfers/Types/TransferStateCategories.cs | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/src/slskd/Transfers/Types/TransferStateCategories.cs b/src/slskd/Transfers/Types/TransferStateCategories.cs index 71f8e962..3812b285 100644 --- a/src/slskd/Transfers/Types/TransferStateCategories.cs +++ b/src/slskd/Transfers/Types/TransferStateCategories.cs @@ -36,7 +36,10 @@ public static class TransferStateCategories /// /// /// - public static readonly HashSet Successful = [(int)(TransferStates.Completed | TransferStates.Succeeded)]; + public static readonly HashSet Successful = [ + (int)TransferStates.Completed, + (int)(TransferStates.Completed | TransferStates.Succeeded) + ]; /// /// All states representing a failed transfer: @@ -88,4 +91,14 @@ public static class TransferStateCategories (int)TransferStates.Initializing, (int)TransferStates.InProgress, ]; + + /// + /// All states lacking the flag; the inverse of . + /// + public static readonly HashSet Incomplete = [ + .. Queued, + .. InProgress, + (int)TransferStates.None, + (int)TransferStates.Requested + ]; } \ No newline at end of file -- cgit v1.2.3 From 69472f600013b4c39d3dcfd7222adf9c3227aab1 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 26 Dec 2025 14:19:13 -0600 Subject: optimize fetch of existing records --- src/slskd/Transfers/Downloads/DownloadService.cs | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index a22d489f..fad6712b 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -307,17 +307,22 @@ namespace slskd.Transfers.Downloads using var context = ContextFactory.CreateDbContext(); /* - get all past downloads from this user. this list will remain stable throughout this process because + get existing downloads from this user. this list will remain stable throughout this process because we have exclusive access for this user. we'll be adding new records, but we've already deduplicated them so we don't have to worry about duplicate records being created in the critical section + + we are looking for: + 1. anything that's not yet complete (we need to disallow the enqueue) + 2. anything complete, but not yet removed from the UI (we need to supersede it) */ - var existingRecords = context.Transfers + var existingRecordsNotYetRemoved = context.Transfers .Where(t => t.Direction == TransferDirection.Download) .Where(t => t.Username == username) + .Where(t => !t.Removed || TransferStateCategories.Incomplete.Contains((int)t.State)) .AsNoTracking() .ToList(); - var existingInProgressRecords = existingRecords + var existingInProgressRecords = existingRecordsNotYetRemoved .Where(t => t.EndedAt == null || !t.State.HasFlag(TransferStates.Completed)) .ToDictionary(t => t.Filename, t => t); @@ -401,7 +406,7 @@ namespace slskd.Transfers.Downloads Log.Debug("Added Transfer record for download of {Filename} from {Username} (id: {Id})", transfer.Filename, transfer.Username, transfer.Id); - foreach (var record in existingRecords.Where(t => t.Filename == file.Filename && !t.Removed)) + foreach (var record in existingRecordsNotYetRemoved.Where(t => t.Filename == file.Filename && !t.Removed)) { record.Removed = true; context.Update(record); -- cgit v1.2.3 From e2789eb6f131d859f501017dd2877b4f0ae4d328 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 26 Dec 2025 17:31:51 -0600 Subject: remove incomplete in favor of negating completed --- src/slskd/Transfers/Types/TransferStateCategories.cs | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/src/slskd/Transfers/Types/TransferStateCategories.cs b/src/slskd/Transfers/Types/TransferStateCategories.cs index 3812b285..7a2ca4e7 100644 --- a/src/slskd/Transfers/Types/TransferStateCategories.cs +++ b/src/slskd/Transfers/Types/TransferStateCategories.cs @@ -91,14 +91,4 @@ public static class TransferStateCategories (int)TransferStates.Initializing, (int)TransferStates.InProgress, ]; - - /// - /// All states lacking the flag; the inverse of . - /// - public static readonly HashSet Incomplete = [ - .. Queued, - .. InProgress, - (int)TransferStates.None, - (int)TransferStates.Requested - ]; } \ No newline at end of file -- cgit v1.2.3 From 9adc7ddbe387627ae7195927aa09340f3fec5e87 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 26 Dec 2025 17:32:18 -0600 Subject: add remove overload accepting an expression --- src/slskd/Transfers/Downloads/DownloadService.cs | 50 ++++++++++++++---------- src/slskd/Transfers/Uploads/UploadService.cs | 48 ++++++++++++++--------- 2 files changed, 59 insertions(+), 39 deletions(-) diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index fad6712b..289bcb40 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -98,7 +98,16 @@ namespace slskd.Transfers.Downloads /// /// This is a soft delete; the record is retained for historical retrieval. /// The unique identifier of the download. - void Remove(Guid id); + /// A value indicating whether the record was removed. + bool Remove(Guid id); + + /// + /// Removes all downloads matching the specified . + /// + /// This is a soft delete; the record is retained for historical retrieval. + /// The expression used to match downloads. + /// The number of records removed. + int Remove(Expression> expression); /// /// Cancels the download matching the specified , if it is in progress. @@ -318,7 +327,7 @@ namespace slskd.Transfers.Downloads var existingRecordsNotYetRemoved = context.Transfers .Where(t => t.Direction == TransferDirection.Download) .Where(t => t.Username == username) - .Where(t => !t.Removed || TransferStateCategories.Incomplete.Contains((int)t.State)) + .Where(t => !t.Removed || !TransferStateCategories.Completed.Contains((int)t.State)) .AsNoTracking() .ToList(); @@ -711,34 +720,35 @@ namespace slskd.Transfers.Downloads /// /// This is a soft delete; the record is retained for historical retrieval. /// The unique identifier of the download. - public void Remove(Guid id) + /// A value indicating whether the record was removed. + public bool Remove(Guid id) + { + return Remove(t => t.Id == id) > 0; + } + + /// + /// Removes all downloads matching the specified . + /// + /// This is a soft delete; the record is retained for historical retrieval. + /// The expression used to match downloads. + /// The number of records removed. + public int Remove(Expression> expression) { try { using var context = ContextFactory.CreateDbContext(); - var transfer = context.Transfers + var count = context.Transfers .Where(t => t.Direction == TransferDirection.Download) - .Where(t => t.Id == id) - .FirstOrDefault(); - - if (transfer == default) - { - throw new NotFoundException($"No download matching id ${id}"); - } - - if (!transfer.State.HasFlag(TransferStates.Completed)) - { - throw new InvalidOperationException($"Invalid attempt to remove a download before it is complete"); - } - - transfer.Removed = true; + .Where(expression) + .ExecuteUpdate(r => r.SetProperty(c => c.Removed, true)); - context.SaveChanges(); + Log.Debug("Removed {Count} downloads by expression", count); + return count; } catch (Exception ex) { - Log.Error(ex, "Failed to remove download {Id}: {Message}", id, ex.Message); + Log.Error(ex, "Failed to remove downloads by expression: {Message}", ex.Message); throw; } } diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 6657a28f..87899d78 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -116,7 +116,16 @@ namespace slskd.Transfers.Uploads /// /// This is a soft delete; the record is retained for historical retrieval. /// The unique identifier of the upload. - void Remove(Guid id); + /// A value indicating whether the record was removed. + bool Remove(Guid id); + + /// + /// Removes all uploads matching the specified . + /// + /// This is a soft delete; the record is retained for historical retrieval. + /// The expression used to match uploads. + /// The number of records removed. + int Remove(Expression> expression); /// /// Cancels the upload matching the specified , if it is in progress. @@ -823,34 +832,35 @@ namespace slskd.Transfers.Uploads /// /// This is a soft delete; the record is retained for historical retrieval. /// The unique identifier of the upload. - public void Remove(Guid id) + /// A value indicating whether the record was removed. + public bool Remove(Guid id) + { + return Remove(t => t.Id == id) > 0; + } + + /// + /// Removes all uploads matching the specified . + /// + /// This is a soft delete; the record is retained for historical retrieval. + /// The expression used to match uploads. + /// The number of records removed. + public int Remove(Expression> expression) { try { using var context = ContextFactory.CreateDbContext(); - var transfer = context.Transfers + var count = context.Transfers .Where(t => t.Direction == TransferDirection.Upload) - .Where(t => t.Id == id) - .FirstOrDefault(); - - if (transfer == default) - { - throw new NotFoundException($"No upload matching id ${id}"); - } - - if (!transfer.State.HasFlag(TransferStates.Completed)) - { - throw new InvalidOperationException($"Invalid attempt to remove an upload before it is complete"); - } - - transfer.Removed = true; + .Where(expression) + .ExecuteUpdate(r => r.SetProperty(c => c.Removed, true)); - context.SaveChanges(); + Log.Debug("Removed {Count} uploads by expression", count); + return count; } catch (Exception ex) { - Log.Error(ex, "Failed to remove upload {Id}: {Message}", id, ex.Message); + Log.Error(ex, "Failed to remove uploads by expression: {Message}", ex.Message); throw; } } -- cgit v1.2.3 From 8084742782a2d1dacbbb84b615fb37109e5b7b3c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 26 Dec 2025 17:32:38 -0600 Subject: use faster remove overload --- .../API/Controllers/TransfersController.cs | 30 ++++++++++++---------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index d2da8caf..3e380000 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -115,14 +115,16 @@ namespace slskd.Transfers.API return Forbid(); } - var transfers = Transfers.Downloads.List(t => TransferStateCategories.Completed.Contains((int)t.State)); - - foreach (var id in transfers.Select(t => t.Id)) + try { - Transfers.Downloads.Remove(id); + Transfers.Downloads.Remove(t => !t.Removed && TransferStateCategories.Completed.Contains((int)t.State)); + return NoContent(); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to remove completed downloads: {Message}", ex.Message); + return StatusCode(500, ex.Message); } - - return NoContent(); } /// @@ -182,16 +184,16 @@ namespace slskd.Transfers.API return Forbid(); } - // get all the transfers that aren't removed - var transfers = Transfers.Uploads - .List(t => TransferStateCategories.Completed.Contains((int)t.State), includeRemoved: false); - - foreach (var id in transfers.Select(t => t.Id)) + try { - Transfers.Uploads.Remove(id); + Transfers.Uploads.Remove(t => !t.Removed && TransferStateCategories.Completed.Contains((int)t.State)); + return NoContent(); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to remove completed uploads: {Message}", ex.Message); + return StatusCode(500, ex.Message); } - - return NoContent(); } /// -- cgit v1.2.3 From 35453533cfc25be782f0d1111af3fb67edff90ee Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 26 Dec 2025 18:20:06 -0600 Subject: move cast down --- src/slskd/Application.cs | 5 ++--- src/slskd/Transfers/Downloads/DownloadService.cs | 6 +++--- src/slskd/Transfers/Uploads/UploadService.cs | 6 +++--- 3 files changed, 8 insertions(+), 9 deletions(-) diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 31b99e3b..6b66ec6e 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -87,7 +87,6 @@ namespace slskd private static int EnqueueRequestQueueDepth = 0; #pragma warning restore SA1306 // Field names should begin with lower-case letter - public Application( OptionsAtStartup optionsAtStartup, IOptionsMonitor optionsMonitor, @@ -1178,7 +1177,7 @@ namespace slskd { if (age.HasValue) { - Transfers.Uploads.Prune(age.Value, (int)(TransferStates.Completed | state)); + Transfers.Uploads.Prune(age.Value, TransferStates.Completed | state); } } @@ -1186,7 +1185,7 @@ namespace slskd { if (age.HasValue) { - Transfers.Downloads.Prune(age.Value, (int)(TransferStates.Completed | state)); + Transfers.Downloads.Prune(age.Value, TransferStates.Completed | state); } } diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 289bcb40..f62af711 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -91,7 +91,7 @@ namespace slskd.Transfers.Downloads /// The age after which downloads are eligible for pruning, in hours. /// One or more states by which downloads are filtered for pruning. /// The number of pruned downloads. - int Prune(int age, params int[] states); + int Prune(int age, params TransferStates[] states); /// /// Removes the download matching the specified . @@ -679,9 +679,9 @@ namespace slskd.Transfers.Downloads /// The age after which downloads are eligible for pruning, in hours. /// One or more states by which downloads are filtered for pruning. /// The number of pruned downloads. - public int Prune(int age, params int[] states) + public int Prune(int age, params TransferStates[] states) { - var statesSet = new HashSet(states); + var statesSet = new HashSet(states.Select(s => (int)s)); if (!statesSet.All(s => ((TransferStates)s).HasFlag(TransferStates.Completed))) { diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 87899d78..a30bb87f 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -109,7 +109,7 @@ namespace slskd.Transfers.Uploads /// The age after which uploads are eligible for pruning, in minutes. /// One or more states by which uploads are filtered for pruning. /// The number of pruned uploads. - int Prune(int age, params int[] states); + int Prune(int age, params TransferStates[] states); /// /// Removes the upload matching the specified . @@ -791,9 +791,9 @@ namespace slskd.Transfers.Uploads /// The age after which uploads are eligible for pruning, in minutes. /// One or more states by which uploads are filtered for pruning. /// The number of pruned uploads. - public int Prune(int age, params int[] states) + public int Prune(int age, params TransferStates[] states) { - var statesSet = new HashSet(states); + var statesSet = new HashSet(states.Select(s => (int)s)); if (!statesSet.All(s => ((TransferStates)s).HasFlag(TransferStates.Completed))) { -- cgit v1.2.3 From 528971a362af3dbc1654b204687eeab671f5451f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 26 Dec 2025 18:20:45 -0600 Subject: Update src/slskd/Transfers/Types/TransferStateCategories.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- src/slskd/Transfers/Types/TransferStateCategories.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/slskd/Transfers/Types/TransferStateCategories.cs b/src/slskd/Transfers/Types/TransferStateCategories.cs index 7a2ca4e7..858e6dce 100644 --- a/src/slskd/Transfers/Types/TransferStateCategories.cs +++ b/src/slskd/Transfers/Types/TransferStateCategories.cs @@ -21,11 +21,11 @@ using System.Collections.Generic; using Soulseek; /// -/// A collection of transfer state integers, collected into arrays that represent common states. +/// A collection of transfer state integers, grouped into sets that represent common states. /// /// /// SQLite can't take advantage of indexes when using bitwise operations, which is what Entity Franework -/// turns HasFlag() expressions into. These arrays allow us to use IN expressions instead of bitwise. +/// turns HasFlag() expressions into. These hash sets allow us to use IN expressions instead of bitwise. /// public static class TransferStateCategories { -- cgit v1.2.3 From 52d60a8d790703819b6ff20ab2a7fb5117c65958 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 26 Dec 2025 18:20:56 -0600 Subject: Update src/slskd/Transfers/Types/TransferStateCategories.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- src/slskd/Transfers/Types/TransferStateCategories.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/slskd/Transfers/Types/TransferStateCategories.cs b/src/slskd/Transfers/Types/TransferStateCategories.cs index 858e6dce..d3e12f2e 100644 --- a/src/slskd/Transfers/Types/TransferStateCategories.cs +++ b/src/slskd/Transfers/Types/TransferStateCategories.cs @@ -24,7 +24,7 @@ using Soulseek; /// A collection of transfer state integers, grouped into sets that represent common states. /// /// -/// SQLite can't take advantage of indexes when using bitwise operations, which is what Entity Franework +/// SQLite can't take advantage of indexes when using bitwise operations, which is what Entity Framework /// turns HasFlag() expressions into. These hash sets allow us to use IN expressions instead of bitwise. /// public static class TransferStateCategories -- cgit v1.2.3 From 56c3f612e9216607f0c1513dde7646ffb329c6b2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 26 Dec 2025 18:22:29 -0600 Subject: refine successful definition --- src/slskd/Transfers/Types/TransferStateCategories.cs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/slskd/Transfers/Types/TransferStateCategories.cs b/src/slskd/Transfers/Types/TransferStateCategories.cs index 7a2ca4e7..449f6c2e 100644 --- a/src/slskd/Transfers/Types/TransferStateCategories.cs +++ b/src/slskd/Transfers/Types/TransferStateCategories.cs @@ -37,7 +37,6 @@ public static class TransferStateCategories /// /// public static readonly HashSet Successful = [ - (int)TransferStates.Completed, (int)(TransferStates.Completed | TransferStates.Succeeded) ]; @@ -63,7 +62,11 @@ public static class TransferStateCategories /// /// All states containing the flag. /// - public static readonly HashSet Completed = [.. Successful, .. Failed]; + public static readonly HashSet Completed = [ + (int)TransferStates.Completed, // in case some sort of a malfunction or regression + .. Successful, + .. Failed + ]; /// /// All states representing a queued transfer: -- cgit v1.2.3 From 92bbb7c7e856a9084f6838e36f3e8ff7fb677022 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 26 Dec 2025 18:26:25 -0600 Subject: only remove completed transfers --- src/slskd/Transfers/Downloads/DownloadService.cs | 9 +++++---- src/slskd/Transfers/Uploads/UploadService.cs | 9 +++++---- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index f62af711..f1f39fba 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -94,7 +94,7 @@ namespace slskd.Transfers.Downloads int Prune(int age, params TransferStates[] states); /// - /// Removes the download matching the specified . + /// Removes the completed download matching the specified . /// /// This is a soft delete; the record is retained for historical retrieval. /// The unique identifier of the download. @@ -102,7 +102,7 @@ namespace slskd.Transfers.Downloads bool Remove(Guid id); /// - /// Removes all downloads matching the specified . + /// Removes all completed downloads matching the specified . /// /// This is a soft delete; the record is retained for historical retrieval. /// The expression used to match downloads. @@ -716,7 +716,7 @@ namespace slskd.Transfers.Downloads } /// - /// Removes the download matching the specified . + /// Removes the completed download matching the specified . /// /// This is a soft delete; the record is retained for historical retrieval. /// The unique identifier of the download. @@ -727,7 +727,7 @@ namespace slskd.Transfers.Downloads } /// - /// Removes all downloads matching the specified . + /// Removes all completed downloads matching the specified . /// /// This is a soft delete; the record is retained for historical retrieval. /// The expression used to match downloads. @@ -740,6 +740,7 @@ namespace slskd.Transfers.Downloads var count = context.Transfers .Where(t => t.Direction == TransferDirection.Download) + .Where(t => TransferStateCategories.Completed.Contains((int)t.State)) .Where(expression) .ExecuteUpdate(r => r.SetProperty(c => c.Removed, true)); diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index a30bb87f..d75ccea3 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -112,7 +112,7 @@ namespace slskd.Transfers.Uploads int Prune(int age, params TransferStates[] states); /// - /// Removes the upload matching the specified . + /// Removes the completed upload matching the specified . /// /// This is a soft delete; the record is retained for historical retrieval. /// The unique identifier of the upload. @@ -120,7 +120,7 @@ namespace slskd.Transfers.Uploads bool Remove(Guid id); /// - /// Removes all uploads matching the specified . + /// Removes all completed uploads matching the specified . /// /// This is a soft delete; the record is retained for historical retrieval. /// The expression used to match uploads. @@ -828,7 +828,7 @@ namespace slskd.Transfers.Uploads } /// - /// Removes the upload matching the specified . + /// Removes the completed upload matching the specified . /// /// This is a soft delete; the record is retained for historical retrieval. /// The unique identifier of the upload. @@ -839,7 +839,7 @@ namespace slskd.Transfers.Uploads } /// - /// Removes all uploads matching the specified . + /// Removes all completed uploads matching the specified . /// /// This is a soft delete; the record is retained for historical retrieval. /// The expression used to match uploads. @@ -852,6 +852,7 @@ namespace slskd.Transfers.Uploads var count = context.Transfers .Where(t => t.Direction == TransferDirection.Upload) + .Where(t => TransferStateCategories.Completed.Contains((int)t.State)) .Where(expression) .ExecuteUpdate(r => r.SetProperty(c => c.Removed, true)); -- cgit v1.2.3 From b471a8619ed6ef631794ef7ef9db05f00d1c2f26 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 27 Dec 2025 17:28:42 -0600 Subject: document numeric values --- .../Transfers/Types/TransferStateCategories.cs | 63 ++++++++++++++-------- 1 file changed, 41 insertions(+), 22 deletions(-) diff --git a/src/slskd/Transfers/Types/TransferStateCategories.cs b/src/slskd/Transfers/Types/TransferStateCategories.cs index 02065714..bd3c83de 100644 --- a/src/slskd/Transfers/Types/TransferStateCategories.cs +++ b/src/slskd/Transfers/Types/TransferStateCategories.cs @@ -33,37 +33,55 @@ public static class TransferStateCategories /// All states representing a successful transfer: /// /// - /// + /// (16 | 32 = 48) /// /// public static readonly HashSet Successful = [ - (int)(TransferStates.Completed | TransferStates.Succeeded) + (int)(TransferStates.Completed | TransferStates.Succeeded) // 16 | 32 = 48 ]; /// /// All states representing a failed transfer: /// /// - /// - /// - /// - /// - /// + /// (16 | 64 = 80) + /// (16 | 128 = 144) + /// (16 | 256 = 272) + /// (16 | 512 = 528) + /// (16 | 1024 = 1040) /// /// public static readonly HashSet Failed = [ - (int)(TransferStates.Completed | TransferStates.Cancelled), - (int)(TransferStates.Completed | TransferStates.TimedOut), - (int)(TransferStates.Completed | TransferStates.Errored), - (int)(TransferStates.Completed | TransferStates.Rejected), - (int)(TransferStates.Completed | TransferStates.Aborted), + (int)(TransferStates.Completed | TransferStates.Cancelled), // 16 | 64 = 80 + (int)(TransferStates.Completed | TransferStates.TimedOut), // 16 | 128 = 144 + (int)(TransferStates.Completed | TransferStates.Errored), // 16 | 256 = 272 + (int)(TransferStates.Completed | TransferStates.Rejected), // 16 | 512 = 528 + (int)(TransferStates.Completed | TransferStates.Aborted), // 16 | 1024 = 1040 ]; /// /// All states containing the flag. + /// + /// + /// (16) + /// + /// + /// Successful: + /// + /// (16 | 32 = 48) + /// + /// + /// Failed: + /// + /// (16 | 64 = 80) + /// (16 | 128 = 144) + /// (16 | 256 = 272) + /// (16 | 512 = 528) + /// (16 | 1024 = 1040) + /// /// public static readonly HashSet Completed = [ - (int)TransferStates.Completed, // in case some sort of a malfunction or regression + (int)TransferStates.Completed, // 16, in case of some sort of a malfunction or regression .. Successful, .. Failed ]; @@ -72,26 +90,27 @@ public static class TransferStateCategories /// All states representing a queued transfer: /// /// - /// - /// + /// (2) + /// (2 | 2048 = 2050) + /// (2 | 4096 = 4098) /// /// public static readonly HashSet Queued = [ - (int)TransferStates.Queued, - (int)(TransferStates.Queued | TransferStates.Locally), - (int)(TransferStates.Queued | TransferStates.Remotely), + (int)TransferStates.Queued, // 2, in case of some sort of a malfunction or regression + (int)(TransferStates.Queued | TransferStates.Locally), // 2 | 2048 = 2050 + (int)(TransferStates.Queued | TransferStates.Remotely), // 2 | 4096 = 4098 ]; /// /// All states representing a transfer that is in progress: /// /// - /// - /// + /// (4) + /// (8) /// /// public static readonly HashSet InProgress = [ - (int)TransferStates.Initializing, - (int)TransferStates.InProgress, + (int)TransferStates.Initializing, // 4 + (int)TransferStates.InProgress, // 8 ]; } \ No newline at end of file -- cgit v1.2.3 From 37fd4e0a28de6249abd4e4dec15e22e10cf44936 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 28 Dec 2025 16:38:52 -0600 Subject: use enums with categories instead of ints to avoid SQLite casting --- src/slskd/Application.cs | 4 +-- .../API/Controllers/TransfersController.cs | 4 +-- src/slskd/Transfers/Downloads/DownloadService.cs | 4 +-- .../Transfers/Types/TransferStateCategories.cs | 34 +++++++++++----------- src/slskd/Transfers/Uploads/UploadService.cs | 2 +- 5 files changed, 24 insertions(+), 24 deletions(-) diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 6b66ec6e..c740bbad 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -316,7 +316,7 @@ namespace slskd // records to be updated if the application has started to shut down so that we can do this cleanup and properly // disposition them as having failed due to an application shutdown, instead of some random exception thrown while // things are being disposed. - var activeUploads = Transfers.Uploads.List(t => t.EndedAt == null || !t.State.HasFlag(TransferStates.Completed), includeRemoved: true); + var activeUploads = Transfers.Uploads.List(t => t.EndedAt == null || !TransferStateCategories.Completed.Contains(t.State), includeRemoved: true); foreach (var upload in activeUploads) { @@ -327,7 +327,7 @@ namespace slskd Transfers.Uploads.Update(upload); } - var activeDownloads = Transfers.Downloads.List(t => t.EndedAt == null || !t.State.HasFlag(TransferStates.Completed), includeRemoved: true); + var activeDownloads = Transfers.Downloads.List(t => t.EndedAt == null || !TransferStateCategories.Completed.Contains(t.State), includeRemoved: true); foreach (var download in activeDownloads) { diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index 3e380000..5d2fc274 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -117,7 +117,7 @@ namespace slskd.Transfers.API try { - Transfers.Downloads.Remove(t => !t.Removed && TransferStateCategories.Completed.Contains((int)t.State)); + Transfers.Downloads.Remove(t => !t.Removed && TransferStateCategories.Completed.Contains(t.State)); return NoContent(); } catch (Exception ex) @@ -186,7 +186,7 @@ namespace slskd.Transfers.API try { - Transfers.Uploads.Remove(t => !t.Removed && TransferStateCategories.Completed.Contains((int)t.State)); + Transfers.Uploads.Remove(t => !t.Removed && TransferStateCategories.Completed.Contains(t.State)); return NoContent(); } catch (Exception ex) diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index f1f39fba..beeab755 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -327,7 +327,7 @@ namespace slskd.Transfers.Downloads var existingRecordsNotYetRemoved = context.Transfers .Where(t => t.Direction == TransferDirection.Download) .Where(t => t.Username == username) - .Where(t => !t.Removed || !TransferStateCategories.Completed.Contains((int)t.State)) + .Where(t => !t.Removed || !TransferStateCategories.Completed.Contains(t.State)) .AsNoTracking() .ToList(); @@ -740,7 +740,7 @@ namespace slskd.Transfers.Downloads var count = context.Transfers .Where(t => t.Direction == TransferDirection.Download) - .Where(t => TransferStateCategories.Completed.Contains((int)t.State)) + .Where(t => TransferStateCategories.Completed.Contains(t.State)) .Where(expression) .ExecuteUpdate(r => r.SetProperty(c => c.Removed, true)); diff --git a/src/slskd/Transfers/Types/TransferStateCategories.cs b/src/slskd/Transfers/Types/TransferStateCategories.cs index bd3c83de..f894b963 100644 --- a/src/slskd/Transfers/Types/TransferStateCategories.cs +++ b/src/slskd/Transfers/Types/TransferStateCategories.cs @@ -36,8 +36,8 @@ public static class TransferStateCategories /// (16 | 32 = 48) /// /// - public static readonly HashSet Successful = [ - (int)(TransferStates.Completed | TransferStates.Succeeded) // 16 | 32 = 48 + public static readonly HashSet Successful = [ + TransferStates.Completed | TransferStates.Succeeded // 16 | 32 = 48 ]; /// @@ -51,12 +51,12 @@ public static class TransferStateCategories /// (16 | 1024 = 1040) /// /// - public static readonly HashSet Failed = [ - (int)(TransferStates.Completed | TransferStates.Cancelled), // 16 | 64 = 80 - (int)(TransferStates.Completed | TransferStates.TimedOut), // 16 | 128 = 144 - (int)(TransferStates.Completed | TransferStates.Errored), // 16 | 256 = 272 - (int)(TransferStates.Completed | TransferStates.Rejected), // 16 | 512 = 528 - (int)(TransferStates.Completed | TransferStates.Aborted), // 16 | 1024 = 1040 + public static readonly HashSet Failed = [ + TransferStates.Completed | TransferStates.Cancelled, // 16 | 64 = 80 + TransferStates.Completed | TransferStates.TimedOut, // 16 | 128 = 144 + TransferStates.Completed | TransferStates.Errored, // 16 | 256 = 272 + TransferStates.Completed | TransferStates.Rejected, // 16 | 512 = 528 + TransferStates.Completed | TransferStates.Aborted, // 16 | 1024 = 1040 ]; /// @@ -80,8 +80,8 @@ public static class TransferStateCategories /// (16 | 1024 = 1040) /// /// - public static readonly HashSet Completed = [ - (int)TransferStates.Completed, // 16, in case of some sort of a malfunction or regression + public static readonly HashSet Completed = [ + TransferStates.Completed, // 16, in case of some sort of a malfunction or regression .. Successful, .. Failed ]; @@ -95,10 +95,10 @@ public static class TransferStateCategories /// (2 | 4096 = 4098) /// /// - public static readonly HashSet Queued = [ - (int)TransferStates.Queued, // 2, in case of some sort of a malfunction or regression - (int)(TransferStates.Queued | TransferStates.Locally), // 2 | 2048 = 2050 - (int)(TransferStates.Queued | TransferStates.Remotely), // 2 | 4096 = 4098 + public static readonly HashSet Queued = [ + TransferStates.Queued, // 2, in case of some sort of a malfunction or regression + TransferStates.Queued | TransferStates.Locally, // 2 | 2048 = 2050 + TransferStates.Queued | TransferStates.Remotely, // 2 | 4096 = 4098 ]; /// @@ -109,8 +109,8 @@ public static class TransferStateCategories /// (8) /// /// - public static readonly HashSet InProgress = [ - (int)TransferStates.Initializing, // 4 - (int)TransferStates.InProgress, // 8 + public static readonly HashSet InProgress = [ + TransferStates.Initializing, // 4 + TransferStates.InProgress, // 8 ]; } \ No newline at end of file diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index d75ccea3..67f71647 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -852,7 +852,7 @@ namespace slskd.Transfers.Uploads var count = context.Transfers .Where(t => t.Direction == TransferDirection.Upload) - .Where(t => TransferStateCategories.Completed.Contains((int)t.State)) + .Where(t => TransferStateCategories.Completed.Contains(t.State)) .Where(expression) .ExecuteUpdate(r => r.SetProperty(c => c.Removed, true)); -- cgit v1.2.3 From 7b2deffc16b632b084750cd0be535a509ff3d253 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 28 Dec 2025 16:39:13 -0600 Subject: log parameters and detailed errors when logging SQL --- src/slskd/Program.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 770c6746..9203dd37 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -1295,7 +1295,10 @@ namespace slskd if (OptionsAtStartup.Debug && OptionsAtStartup.Flags.LogSQL) { - options.LogTo(Log.Debug, LogLevel.Information); + options + .EnableSensitiveDataLogging() + .EnableDetailedErrors() + .LogTo(Log.Debug, LogLevel.Information); } }); -- cgit v1.2.3 From 130449908748762449b41b93af45b884b5265255 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 28 Dec 2025 16:39:39 -0600 Subject: add UserUploadStatistics and method to derive --- src/slskd/Transfers/Types/UserUploadStatistics.cs | 35 ++++++++++++++++ src/slskd/Transfers/Uploads/UploadService.cs | 51 +++++++++++++++++++++++ 2 files changed, 86 insertions(+) create mode 100644 src/slskd/Transfers/Types/UserUploadStatistics.cs diff --git a/src/slskd/Transfers/Types/UserUploadStatistics.cs b/src/slskd/Transfers/Types/UserUploadStatistics.cs new file mode 100644 index 00000000..945964f5 --- /dev/null +++ b/src/slskd/Transfers/Types/UserUploadStatistics.cs @@ -0,0 +1,35 @@ +// +// 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.Transfers; + +/// +/// Upload statistics, for use when evaluating incoming enqueue requests against configured limits. +/// +public record UserUploadStatistics +{ + public int QueuedFiles { get; set; } + public long QueuedBytes { get; set; } + + public int WeeklyFailedFiles { get; set; } + public int WeeklySucceededFiles { get; set; } + public long WeeklySucceededBytes { get; set; } + + public int DailyFailedFiles { get; set; } + public int DailySucceededFiles { get; set; } + public long DailySucceededBytes { get; set; } +} \ No newline at end of file diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 67f71647..fe2621c8 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -95,6 +95,14 @@ namespace slskd.Transfers.Uploads /// (int Files, long Bytes) Summarize(Expression> expression); + /// + /// Gets upload statistics for the specified . + /// + /// The username of the user. + /// An optional timestamp representing the current time in UTC. + /// The gathered statistics. + UserUploadStatistics GetUserStatistics(string username, DateTime? utcNow = null); + /// /// Returns a list of all uploads matching the optional . /// @@ -919,6 +927,49 @@ namespace slskd.Transfers.Uploads context.SaveChanges(); } + /// + /// Gets upload statistics for the specified . + /// + /// The username of the user. + /// An optional timestamp representing the current time in UTC. + /// The gathered statistics. + public UserUploadStatistics GetUserStatistics(string username, DateTime? utcNow = null) + { + utcNow ??= DateTime.UtcNow; + var dailyCutoff = utcNow.Value.AddDays(-1); + var weeklyCutoff = utcNow.Value.AddDays(-7); + + var failedStateIds = TransferStateCategories.Failed.ToList(); + var successState = TransferStates.Completed | TransferStates.Succeeded; + + using var context = ContextFactory.CreateDbContext(); + + var stats = context.Transfers + .AsNoTracking() + .Where(t => t.Username == username) + .Where(t => t.Direction == TransferDirection.Upload) + .Where(t => t.EndedAt == null || t.StartedAt >= weeklyCutoff) + .GroupBy(t => 1) // aggregate everything into one row + .Select(g => new UserUploadStatistics + { + QueuedFiles = g.Count(t => t.EndedAt == null), + QueuedBytes = g.Where(t => t.EndedAt == null).Sum(t => (long?)t.Size) ?? 0, + + WeeklyFailedFiles = g.Count(t => t.StartedAt >= weeklyCutoff && failedStateIds.Contains(t.State)), + + WeeklySucceededFiles = g.Count(t => t.StartedAt >= weeklyCutoff && (t.State == successState)), + WeeklySucceededBytes = g.Where(t => t.StartedAt >= weeklyCutoff && (t.State == successState)).Sum(t => (long?)t.Size) ?? 0, + + DailyFailedFiles = g.Count(t => t.StartedAt >= dailyCutoff && failedStateIds.Contains(t.State)), + + DailySucceededFiles = g.Count(t => t.StartedAt >= dailyCutoff && t.State == successState), + DailySucceededBytes = g.Where(t => t.StartedAt >= dailyCutoff && t.State == successState).Sum(t => (long?)t.Size) ?? 0, + }) + .FirstOrDefault(); + + return stats ?? new UserUploadStatistics(); + } + private bool TryFail(Guid id, string exception, TransferStates state) { var t = Find(t => t.Id == id); -- cgit v1.2.3 From f857168bdeb8a5607c2374f2aea47b506524a4c8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 28 Dec 2025 18:31:25 -0600 Subject: final tweaks of GetUserStatistics --- src/slskd/Transfers/Uploads/UploadService.cs | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index fe2621c8..bcc1dd90 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -939,11 +939,11 @@ namespace slskd.Transfers.Uploads var dailyCutoff = utcNow.Value.AddDays(-1); var weeklyCutoff = utcNow.Value.AddDays(-7); - var failedStateIds = TransferStateCategories.Failed.ToList(); - var successState = TransferStates.Completed | TransferStates.Succeeded; - using var context = ContextFactory.CreateDbContext(); + var failedStates = TransferStateCategories.Failed.ToList(); + var successState = TransferStates.Completed | TransferStates.Succeeded; + var stats = context.Transfers .AsNoTracking() .Where(t => t.Username == username) @@ -955,15 +955,20 @@ namespace slskd.Transfers.Uploads QueuedFiles = g.Count(t => t.EndedAt == null), QueuedBytes = g.Where(t => t.EndedAt == null).Sum(t => (long?)t.Size) ?? 0, - WeeklyFailedFiles = g.Count(t => t.StartedAt >= weeklyCutoff && failedStateIds.Contains(t.State)), + // note: this generates some funky json_each() expression under the hood; it's an EF optimization + // that helps with optimization of query plans. i've tried expanding this out to force an IN + // and there's either no difference, or there's a slight improvement with the json_each method. + WeeklyFailedFiles = g.Count(t => t.StartedAt >= weeklyCutoff && failedStates.Contains(t.State)), - WeeklySucceededFiles = g.Count(t => t.StartedAt >= weeklyCutoff && (t.State == successState)), - WeeklySucceededBytes = g.Where(t => t.StartedAt >= weeklyCutoff && (t.State == successState)).Sum(t => (long?)t.Size) ?? 0, + WeeklySucceededFiles = g.Count(t => t.StartedAt >= weeklyCutoff && t.State == successState), + WeeklySucceededBytes = g.Where(t => t.StartedAt >= weeklyCutoff && t.State == successState) + .Sum(t => (long?)t.Size) ?? 0, - DailyFailedFiles = g.Count(t => t.StartedAt >= dailyCutoff && failedStateIds.Contains(t.State)), + DailyFailedFiles = g.Count(t => t.StartedAt >= dailyCutoff && failedStates.Contains(t.State)), DailySucceededFiles = g.Count(t => t.StartedAt >= dailyCutoff && t.State == successState), - DailySucceededBytes = g.Where(t => t.StartedAt >= dailyCutoff && t.State == successState).Sum(t => (long?)t.Size) ?? 0, + DailySucceededBytes = g.Where(t => t.StartedAt >= dailyCutoff && t.State == successState) + .Sum(t => (long?)t.Size) ?? 0, }) .FirstOrDefault(); -- cgit v1.2.3 From c807ee96e997b904419a95089365cb17ac372f9d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 28 Dec 2025 18:34:41 -0600 Subject: add new indexes --- src/slskd/Transfers/TransfersDbContext.cs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/slskd/Transfers/TransfersDbContext.cs b/src/slskd/Transfers/TransfersDbContext.cs index eac4935b..8c0b0eb5 100644 --- a/src/slskd/Transfers/TransfersDbContext.cs +++ b/src/slskd/Transfers/TransfersDbContext.cs @@ -70,6 +70,21 @@ namespace slskd.Transfers .Entity() .HasIndex(t => t.State) .HasDatabaseName("IDX_Transfers_State"); + + modelBuilder + .Entity() + .HasIndex(t => t.Username) + .HasDatabaseName("IDX_Transfers_Username"); + + modelBuilder + .Entity() + .HasIndex(t => t.Removed) + .HasDatabaseName("IDX_Transfers_Removed"); + + modelBuilder + .Entity() + .HasIndex(e => new { e.Username, e.Direction, e.EndedAt, e.StartedAt, e.State, e.Size }) + .HasDatabaseName("IDX_Transfers_UserUploadStatistics"); } } } -- cgit v1.2.3 From 1144e602347277cc2abca3a4301dda5fb95a3346 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 28 Dec 2025 18:34:56 -0600 Subject: tweak sql logging so debug isn't required --- src/slskd/Program.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 9203dd37..2b2d2840 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -1293,12 +1293,12 @@ namespace slskd options.UseSqlite(connectionString); options.AddInterceptors(new SqliteConnectionOpenedInterceptor()); - if (OptionsAtStartup.Debug && OptionsAtStartup.Flags.LogSQL) + if (OptionsAtStartup.Flags.LogSQL) { options .EnableSensitiveDataLogging() .EnableDetailedErrors() - .LogTo(Log.Debug, LogLevel.Information); + .LogTo(OptionsAtStartup.Debug ? Log.Debug : Log.Information, LogLevel.Information); } }); -- cgit v1.2.3 From 2e4411eb00e8192f41e92d57f500b56ced4dcc3f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 28 Dec 2025 18:35:39 -0600 Subject: reduce enqueue semaphore to 10 (from 20) --- src/slskd/Application.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index c740bbad..0ac92e31 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -224,7 +224,7 @@ namespace slskd private OptionsAtStartup OptionsAtStartup { get; set; } private IOptionsMonitor OptionsMonitor { get; set; } private SemaphoreSlim OptionsSyncRoot { get; } = new SemaphoreSlim(1, 1); - private SemaphoreSlim EnqueueRequestRateLimiter { get; } = new SemaphoreSlim(20, 20); + private SemaphoreSlim EnqueueRequestRateLimiter { get; } = new SemaphoreSlim(10, 10); private Options PreviousOptions { get; set; } private IPushbulletService Pushbullet { get; } private DateTime SharesRefreshStarted { get; set; } -- cgit v1.2.3 From b082e89226234d00b73dcd753b301a70e2ac58bb Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 28 Dec 2025 18:40:42 -0600 Subject: use stats query --- src/slskd/Application.cs | 101 +++++++++++++++++------------------------------ 1 file changed, 36 insertions(+), 65 deletions(-) diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 0ac92e31..c462ca45 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -538,7 +538,6 @@ namespace slskd } } - // todo: consider moving this somewhere else; it's pretty long and complicated private async Task EnqueueDownload(string username, IPEndPoint endpoint, string filename) { Metrics.Enqueue.RequestsReceived.Inc(1); @@ -623,45 +622,48 @@ namespace slskd * 3) that did not end due to an error (state includes errored, exception column is set) */ (bool Files, bool Megabytes) OverLimits( - (int Files, long Bytes) stats, + int files, + long bytes, Options.LimitsOptions.Limits options, Options.LimitsOptions.Limits defaults, long size) { - var files = false; - var megabytes = false; + var filesOver = false; + var megabytesOver = false; var byteLimitInMegabytes = options?.Megabytes ?? defaults?.Megabytes; - if (byteLimitInMegabytes is not null && (stats.Bytes + size) > (byteLimitInMegabytes * 1000L * 1000L)) + if (byteLimitInMegabytes is not null && (bytes + size) > (byteLimitInMegabytes * 1000L * 1000L)) { - Log.Debug("Projected bytes {Bytes} exceeds limit {Limit}", stats.Bytes + size, byteLimitInMegabytes * 1000L * 1000L); - megabytes = true; + Log.Debug("Projected bytes {Bytes} exceeds limit {Limit}", bytes + size, byteLimitInMegabytes * 1000L * 1000L); + megabytesOver = true; } var fileLimit = options?.Files ?? defaults?.Files; - if (fileLimit is not null && (stats.Files + 1) > fileLimit) + if (fileLimit is not null && (files + 1) > fileLimit) { - Log.Debug("Projected file count {Files} exceeds limit {Limit}", stats.Files + 1, fileLimit); - files = true; + Log.Debug("Projected file count {Files} exceeds limit {Limit}", files + 1, fileLimit); + filesOver = true; } - return (files, megabytes); + return (filesOver, megabytesOver); } decisionStopwatch.Start(); + var stats = Transfers.Uploads.GetUserStatistics(username, DateTime.UtcNow); + // start with the queue, since that should contain the fewest files and should be the least expensive to check // "queued" includes both queued and in progress; records with a null EndedAt property, which is guaranteed to be set // for terminal transfers. if (!IsNull(limits?.Queued, global?.Queued)) { - var queued = Transfers.Uploads.Summarize( - expression: t => t.Username == username && t.EndedAt == null); - - Log.Debug("Fetched queue stats: files: {Files}, bytes: {Bytes} ({Time}ms)", queued.Files, queued.Bytes, decisionStopwatch.ElapsedMilliseconds); - - var over = OverLimits(queued, limits?.Queued, global?.Queued, resolved.Size); + var over = OverLimits( + files: stats.QueuedFiles, + bytes: stats.QueuedBytes, + options: limits?.Queued, + defaults: global?.Queued, + size: resolved.Size); if (over.Files || over.Megabytes) { @@ -680,35 +682,20 @@ namespace slskd // * that were not errored if (!IsNull(limits?.Weekly, global?.Weekly)) { - var erroredState = TransferStates.Completed | TransferStates.Errored; - var cutoffDateTime = DateTime.UtcNow.AddDays(-7); - - var failures = Transfers.Uploads.Summarize( - expression: t => - t.Username == username - && t.StartedAt >= cutoffDateTime - && (t.State.HasFlag(erroredState) || t.Exception != null)); - - Log.Debug("Fetched weekly failures: {Failures} ({Time}ms)", failures.Files, decisionStopwatch.ElapsedMilliseconds); - var failureLimit = limits?.Weekly?.Failures ?? global?.Weekly?.Failures; - if (failureLimit is not null && failures.Files >= failureLimit) + if (failureLimit is not null && stats.WeeklyFailedFiles >= failureLimit) { Log.Information("Rejected enqueue request for user {Username}: Weekly failure limit met or exceeded", username); throw new DownloadEnqueueException("Too many failed transfers this week"); } - var weekly = Transfers.Uploads.Summarize( - expression: t => - t.Username == username - && t.StartedAt >= cutoffDateTime - && !t.State.HasFlag(erroredState) - && t.Exception == null); - - Log.Debug("Fetched weekly stats: files: {Files}, bytes: {Bytes} ({Time}ms)", weekly.Files, weekly.Bytes, decisionStopwatch.ElapsedMilliseconds); - - var over = OverLimits(weekly, limits?.Weekly, global?.Weekly, resolved.Size); + var over = OverLimits( + files: stats.WeeklySucceededFiles, + bytes: stats.WeeklySucceededBytes, + options: limits?.Weekly, + defaults: global?.Weekly, + size: resolved.Size); if (over.Files || over.Megabytes) { @@ -721,35 +708,20 @@ namespace slskd // of the previous 7. if (!IsNull(limits?.Daily, global?.Daily)) { - var erroredState = TransferStates.Completed | TransferStates.Errored; - var cutoffDateTime = DateTime.UtcNow.AddDays(-1); - - var failures = Transfers.Uploads.Summarize( - expression: t => - t.Username == username - && t.StartedAt >= cutoffDateTime - && (t.State.HasFlag(erroredState) || t.Exception != null)); - - Log.Debug("Fetched daily failures: {Failures} ({Time}ms)", failures.Files, decisionStopwatch.ElapsedMilliseconds); - var failureLimit = limits?.Daily?.Failures ?? global?.Daily?.Failures; - if (failureLimit is not null && failures.Files >= failureLimit) + if (failureLimit is not null && stats.DailyFailedFiles >= failureLimit) { Log.Information("Rejected enqueue request for user {Username}: Daily failure limit met or exceeded", username); throw new DownloadEnqueueException("Too many failed transfers today"); } - var daily = Transfers.Uploads.Summarize( - expression: t => - t.Username == username - && t.StartedAt >= cutoffDateTime - && !t.State.HasFlag(erroredState) - && t.Exception == null); - - Log.Debug("Fetched daily stats: files: {Files}, bytes: {Bytes} ({Time}ms)", daily.Files, daily.Bytes, decisionStopwatch.ElapsedMilliseconds); - - var over = OverLimits(daily, limits?.Daily, global?.Daily, resolved.Size); + var over = OverLimits( + files: stats.DailySucceededFiles, + bytes: stats.DailySucceededBytes, + options: limits?.Daily, + defaults: global?.Daily, + size: resolved.Size); if (over.Files || over.Megabytes) { @@ -758,17 +730,16 @@ namespace slskd } } - await Transfers.Uploads.EnqueueAsync(username, filename); - - Metrics.Enqueue.RequestsAccepted.Inc(1); - decisionStopwatch.Stop(); Metrics.Enqueue.DecisionLatency.Observe(decisionStopwatch.ElapsedMilliseconds); Metrics.Enqueue.CurrentDecisionLatency.Update(decisionStopwatch.ElapsedMilliseconds); + await Transfers.Uploads.EnqueueAsync(username, filename); + stopwatch.Stop(); + Metrics.Enqueue.RequestsAccepted.Inc(1); Metrics.Enqueue.ResponseLatency.Observe(stopwatch.ElapsedMilliseconds); Metrics.Enqueue.CurrentResponseLatency.Update(stopwatch.ElapsedMilliseconds); } -- cgit v1.2.3 From d29e74c2eafa0f97d12c33be1e22e444a7618bd4 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 28 Dec 2025 18:44:56 -0600 Subject: stub migration for new indexes --- ...Z12282025_AdditionalTransferIndexesMigration.cs | 98 ++++++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs diff --git a/src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs b/src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs new file mode 100644 index 00000000..6beec9d3 --- /dev/null +++ b/src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs @@ -0,0 +1,98 @@ +// +// 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.Migrations; + +using System; +using System.Linq; +using Microsoft.Data.Sqlite; +using Serilog; + +/// +/// Updates the Transfers table to add indexes on the Direction and State columns. +/// +public class Z12282025_AdditionalTransferIndexesMigration : IMigration +{ + public Z12282025_AdditionalTransferIndexesMigration(ConnectionStringDictionary connectionStrings) + { + ConnectionString = connectionStrings[Database.Transfers]; + } + + private ILogger Log { get; } = Serilog.Log.ForContext(); + private string ConnectionString { get; } + + public bool NeedsToBeApplied() + { + // check to see if *BOTH* of the indexes are in place. if one or both are missing, we must apply + var idxes = SchemaInspector.GetDatabaseIndexes(ConnectionString); + var txfers = idxes["Transfers"]; + + var usernameExists = txfers.Any(c => c.Name.Equals("IDX_Transfers_Username", StringComparison.OrdinalIgnoreCase)); + var removedExists = txfers.Any(c => c.Name.Equals("IDX_Transfers_Removed", StringComparison.OrdinalIgnoreCase)); + var statsExist = txfers.Any(c => c.Name.Equals("IDX_Transfers_UserUploadStatistics", StringComparison.OrdinalIgnoreCase)); + + if (usernameExists && removedExists && statsExist) + { + return false; + } + + return true; + } + + public void Apply() + { + if (!NeedsToBeApplied()) + { + Log.Information("> Migration {Name} is not necessary or has already been applied", nameof(Z12282025_AdditionalTransferIndexesMigration)); + return; + } + + using var connection = new SqliteConnection(ConnectionString); + connection.Open(); + + using var transaction = connection.BeginTransaction(); + + try + { + Log.Information("> Adding missing index(es) on the Transfers table..."); + + var usernameCommand = new SqliteCommand(@" + CREATE INDEX IF NOT EXISTS IDX_Transfers_Username ON Transfers (Username) + ", connection, transaction); + usernameCommand.ExecuteNonQuery(); + + var removedCommand = new SqliteCommand(@" + CREATE INDEX IF NOT EXISTS IDX_Transfers_Removed ON Transfers (Removed) + ", connection, transaction); + removedCommand.ExecuteNonQuery(); + + var statsCommand = new SqliteCommand(@" + CREATE INDEX IF NOT EXISTS IDX_Transfers_UserUploadStatistics ON Transfers (Username, Direction, EndedAt, StartedAt, State, Size) + ", connection, transaction); + statsCommand.ExecuteNonQuery(); + + Log.Information("> Index(es) created"); + transaction.Commit(); + Log.Information("> Done!"); + } + catch (Exception) + { + transaction.Rollback(); + throw; + } + } +} -- cgit v1.2.3 From 05714b25d7f802e9d495bf179af2e19fb7750797 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 29 Dec 2025 18:29:33 -0600 Subject: tweak logging --- src/slskd/Application.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index c462ca45..ae6b7c0b 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -742,12 +742,12 @@ namespace slskd Metrics.Enqueue.RequestsAccepted.Inc(1); Metrics.Enqueue.ResponseLatency.Observe(stopwatch.ElapsedMilliseconds); Metrics.Enqueue.CurrentResponseLatency.Update(stopwatch.ElapsedMilliseconds); + + Log.Information("Enqueue of {Filename} to {Username} completed in {ElapsedOverall}ms, decision made in {ElapsedDecision}ms", filename, username, stopwatch.ElapsedMilliseconds, decisionStopwatch.ElapsedMilliseconds); } finally { EnqueueRequestRateLimiter.Release(); - - Log.Debug("EnqueueDownload for {Username}/{Filename} completed in {ElapsedOverall}ms, decision made in {ElapsedDecision}ms", username, filename, stopwatch.ElapsedMilliseconds, decisionStopwatch.ElapsedMilliseconds); } } -- cgit v1.2.3 From 4af4974dbc5add4e3e66e9b9d7744f5d2bebec20 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 29 Dec 2025 18:29:47 -0600 Subject: add username, filename index --- src/slskd/Transfers/TransfersDbContext.cs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/slskd/Transfers/TransfersDbContext.cs b/src/slskd/Transfers/TransfersDbContext.cs index 8c0b0eb5..f89530df 100644 --- a/src/slskd/Transfers/TransfersDbContext.cs +++ b/src/slskd/Transfers/TransfersDbContext.cs @@ -81,6 +81,14 @@ namespace slskd.Transfers .HasIndex(t => t.Removed) .HasDatabaseName("IDX_Transfers_Removed"); + // covers the ckeck for existing records when enqueueing uploads and downloads + modelBuilder + .Entity() + .HasIndex(t => new { t.Username, t.Filename }) + .HasDatabaseName("IDX_Transfers_UsernameFilename"); + + // covers the GetUserStatistics method that backs limit checks + // check every so often with EXPLAIN to make sure it's being shown as a covering index modelBuilder .Entity() .HasIndex(e => new { e.Username, e.Direction, e.EndedAt, e.StartedAt, e.State, e.Size }) -- cgit v1.2.3 From 97a5ee6aa304ce645f0bf97a26c07cb35c873431 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 29 Dec 2025 18:43:59 -0600 Subject: add new index --- ...Z12282025_AdditionalTransferIndexesMigration.cs | 27 ++++++++++------------ 1 file changed, 12 insertions(+), 15 deletions(-) diff --git a/src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs b/src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs index 6beec9d3..0c8d8b0c 100644 --- a/src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs +++ b/src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs @@ -43,9 +43,10 @@ public class Z12282025_AdditionalTransferIndexesMigration : IMigration var usernameExists = txfers.Any(c => c.Name.Equals("IDX_Transfers_Username", StringComparison.OrdinalIgnoreCase)); var removedExists = txfers.Any(c => c.Name.Equals("IDX_Transfers_Removed", StringComparison.OrdinalIgnoreCase)); + var usernameFilenameExists = txfers.Any(c => c.Name.Equals("IDX_Transfers_UsernameFilename", StringComparison.OrdinalIgnoreCase)); var statsExist = txfers.Any(c => c.Name.Equals("IDX_Transfers_UserUploadStatistics", StringComparison.OrdinalIgnoreCase)); - if (usernameExists && removedExists && statsExist) + if (usernameExists && removedExists && usernameFilenameExists && statsExist) { return false; } @@ -68,22 +69,18 @@ public class Z12282025_AdditionalTransferIndexesMigration : IMigration try { - Log.Information("> Adding missing index(es) on the Transfers table..."); - - var usernameCommand = new SqliteCommand(@" - CREATE INDEX IF NOT EXISTS IDX_Transfers_Username ON Transfers (Username) - ", connection, transaction); - usernameCommand.ExecuteNonQuery(); + void Exec(string sql) + { + using var command = new SqliteCommand(sql, connection, transaction); + command.ExecuteNonQuery(); + } - var removedCommand = new SqliteCommand(@" - CREATE INDEX IF NOT EXISTS IDX_Transfers_Removed ON Transfers (Removed) - ", connection, transaction); - removedCommand.ExecuteNonQuery(); + Log.Information("> Adding missing index(es) on the Transfers table..."); - var statsCommand = new SqliteCommand(@" - CREATE INDEX IF NOT EXISTS IDX_Transfers_UserUploadStatistics ON Transfers (Username, Direction, EndedAt, StartedAt, State, Size) - ", connection, transaction); - statsCommand.ExecuteNonQuery(); + Exec("CREATE INDEX IF NOT EXISTS IDX_Transfers_Username ON Transfers (Username)"); + Exec("CREATE INDEX IF NOT EXISTS IDX_Transfers_Removed ON Transfers (Removed)"); + Exec("CREATE INDEX IF NOT EXISTS IDX_Transfers_UsernameFilename ON Transfers (Username, Filename)"); + Exec("CREATE INDEX IF NOT EXISTS IDX_Transfers_UserUploadStatistics ON Transfers (Username, Direction, EndedAt, StartedAt, State, Size)"); Log.Information("> Index(es) created"); transaction.Commit(); -- cgit v1.2.3 From 9d868062e86f761f16d36a48a7a5f4951149114a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 29 Dec 2025 18:48:15 -0600 Subject: wire up new migration --- src/slskd/Core/Data/Migrator.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/slskd/Core/Data/Migrator.cs b/src/slskd/Core/Data/Migrator.cs index b8a7ce10..5561de4b 100644 --- a/src/slskd/Core/Data/Migrator.cs +++ b/src/slskd/Core/Data/Migrator.cs @@ -43,6 +43,7 @@ public class Migrator { nameof(Z04012025_TransferStateMigration), new Z04012025_TransferStateMigration(connectionStrings: Databases) }, { nameof(Z07062025_TransferIndexesMigration), new Z07062025_TransferIndexesMigration(connectionStrings: Databases) }, { nameof(Z07262025_PrivateMessageWasReplayedMigration), new Z07262025_PrivateMessageWasReplayedMigration(connectionStrings: Databases) }, + { nameof(Z12282025_AdditionalTransferIndexesMigration), new Z12282025_AdditionalTransferIndexesMigration(connectionStrings: Databases) }, }; } -- cgit v1.2.3 From e8f533d87e58bbeca71468c97f5ec67598726bb4 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 1 Jan 2026 13:42:26 +0000 Subject: Bump qs and express in /src/web Bumps [qs](https://github.com/ljharb/qs) and [express](https://github.com/expressjs/express). These dependencies needed to be updated together. Updates `qs` from 6.13.0 to 6.14.1 - [Changelog](https://github.com/ljharb/qs/blob/main/CHANGELOG.md) - [Commits](https://github.com/ljharb/qs/compare/v6.13.0...v6.14.1) Updates `express` from 4.21.1 to 4.22.1 - [Release notes](https://github.com/expressjs/express/releases) - [Changelog](https://github.com/expressjs/express/blob/v4.22.1/History.md) - [Commits](https://github.com/expressjs/express/compare/4.21.1...v4.22.1) --- updated-dependencies: - dependency-name: qs dependency-version: 6.14.1 dependency-type: indirect - dependency-name: express dependency-version: 4.22.1 dependency-type: indirect ... Signed-off-by: dependabot[bot] --- src/web/package-lock.json | 197 +++++++++++++++++++++++++++++++++++++++------- 1 file changed, 167 insertions(+), 30 deletions(-) diff --git a/src/web/package-lock.json b/src/web/package-lock.json index 0fdcae0d..88c9c5da 100644 --- a/src/web/package-lock.json +++ b/src/web/package-lock.json @@ -180,6 +180,7 @@ "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.23.9.tgz", "integrity": "sha512-5q0175NOjddqpvvzU+kDiSOAk4PfdO6FvwCWoQ6RO7rTzEe8vlo+4HVfcnAREhD4npMs0e9uZypjTwzZPCf/cw==", "dev": true, + "peer": true, "dependencies": { "@ampproject/remapping": "^2.2.0", "@babel/code-frame": "^7.23.5", @@ -225,6 +226,7 @@ "resolved": "https://registry.npmjs.org/@babel/eslint-parser/-/eslint-parser-7.23.10.tgz", "integrity": "sha512-3wSYDPZVnhseRnxRJH6ZVTNknBz76AEnyC+AYYhasjP3Yy23qz0ERR7Fcd2SHmYuSFJ2kY9gaaDd3vyqU09eSw==", "dev": true, + "peer": true, "dependencies": { "@nicolo-ribaudo/eslint-scope-5-internals": "5.1.1-v1", "eslint-visitor-keys": "^2.1.0", @@ -1003,6 +1005,7 @@ "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-flow/-/plugin-syntax-flow-7.22.5.tgz", "integrity": "sha512-9RdCl0i+q0QExayk2nOS7853w08yLucnnPML6EN9S8fgMPVtdLDCdx/cOQ/i44Lb9UeQX9A35yaqBBOMMZxPxQ==", "dev": true, + "peer": true, "dependencies": { "@babel/helper-plugin-utils": "^7.22.5" }, @@ -1877,6 +1880,7 @@ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx/-/plugin-transform-react-jsx-7.22.5.tgz", "integrity": "sha512-rog5gZaVbUip5iWDMTYbVM15XQq+RkUKhET/IHR6oizR+JEoN6CAfTTuHcK4vwUyzca30qqHqEpzBOnaRMWYMA==", "dev": true, + "peer": true, "dependencies": { "@babel/helper-annotate-as-pure": "^7.22.5", "@babel/helper-module-imports": "^7.22.5", @@ -2505,6 +2509,7 @@ "version": "6.13.0", "resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.13.0.tgz", "integrity": "sha512-oXTfJzHJ5Tl7f6T8ZO0HKf981zubxgKohjddLobbntbNZHlOZGMRL+pPZGtclDWFaFJWtGBYRGyNdjQ6Xsx5yA==", + "peer": true, "dependencies": { "@codemirror/state": "^6.1.4", "style-mod": "^4.0.0", @@ -2516,6 +2521,7 @@ "resolved": "https://registry.npmjs.org/@craco/craco/-/craco-7.1.0.tgz", "integrity": "sha512-oRAcPIKYrfPXp9rSzlsDNeOaVtDiKhoyqSXUoqiK24jCkHr4T8m/a2f74yXIzCbIheoUWDOIfWZyRgFgT+cpqA==", "dev": true, + "peer": true, "dependencies": { "autoprefixer": "^10.4.12", "cosmiconfig": "^7.0.1", @@ -4132,6 +4138,7 @@ "version": "2.11.8", "resolved": "https://registry.npmjs.org/@popperjs/core/-/core-2.11.8.tgz", "integrity": "sha512-P1st0aksCrn9sGZhp8GMYwBnQsbvAWsZAX44oXNNvLHGqAOcoVxmjZiohstwQ7SqKnbR47akdNi+uleWD8+g6A==", + "peer": true, "funding": { "type": "opencollective", "url": "https://opencollective.com/popperjs" @@ -4656,6 +4663,7 @@ "resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-8.40.1.tgz", "integrity": "sha512-vRb792M4mF1FBT+eoLecmkpLXwxsBHvWWRGJjzbYANBM6DtiJc6yETyv4rqDA6QNjF1pkj1U7LMA6dGb3VYlHw==", "dev": true, + "peer": true, "dependencies": { "@types/estree": "*", "@types/json-schema": "*" @@ -4899,6 +4907,7 @@ "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-5.59.9.tgz", "integrity": "sha512-4uQIBq1ffXd2YvF7MAvehWKW3zVv/w+mSfRAu+8cKbfj3nwzyqJLNcZJpQ/WZ1HLbJDiowwmQ6NO+63nCA+fqA==", "dev": true, + "peer": true, "dependencies": { "@eslint-community/regexpp": "^4.4.0", "@typescript-eslint/scope-manager": "5.59.9", @@ -4952,6 +4961,7 @@ "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-5.59.9.tgz", "integrity": "sha512-FsPkRvBtcLQ/eVK1ivDiNYBjn3TGJdXy2fhXX+rc7czWl4ARwnpArwbihSOHI2Peg9WbtGHrbThfBUkZZGTtvQ==", "dev": true, + "peer": true, "dependencies": { "@typescript-eslint/scope-manager": "5.59.9", "@typescript-eslint/types": "5.59.9", @@ -5399,6 +5409,7 @@ "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.11.3.tgz", "integrity": "sha512-Y9rRfJG5jcKOE0CLisYbojUjIrIEE7AGMzA/Sm4BslANhbS+cDMpgBdcPT91oJ7OuJ9hYJBx59RjbhxVnrF8Xg==", "dev": true, + "peer": true, "bin": { "acorn": "bin/acorn" }, @@ -5494,6 +5505,7 @@ "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", "dev": true, + "peer": true, "dependencies": { "fast-deep-equal": "^3.1.1", "fast-json-stable-stringify": "^2.0.0", @@ -6428,6 +6440,7 @@ "url": "https://github.com/sponsors/ai" } ], + "peer": true, "dependencies": { "caniuse-lite": "^1.0.30001646", "electron-to-chromium": "^1.5.4", @@ -6531,6 +6544,23 @@ "node": ">= 0.4" } }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/callsites": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", @@ -7365,6 +7395,7 @@ "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.12.0.tgz", "integrity": "sha512-sRu1kpcO9yLtYxBKvqfTeh9KzZEwO3STyX1HT+4CaDzC6HpTGYhIhPIzj9XuKU7KYDwnaeh5hcOwjy1QuJzBPA==", "dev": true, + "peer": true, "dependencies": { "fast-deep-equal": "^3.1.1", "json-schema-traverse": "^1.0.0", @@ -8507,6 +8538,7 @@ "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.56.0.tgz", "integrity": "sha512-Go19xM6T9puCOWntie1/P997aXxFsOi37JIHRWI514Hc6ZnaHGKY9xFhrU65RT6CcBEzZoGG1e6Nq+DT04ZtZQ==", "dev": true, + "peer": true, "dependencies": { "@eslint-community/eslint-utils": "^4.2.0", "@eslint-community/regexpp": "^4.6.1", @@ -8704,6 +8736,7 @@ "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-6.21.0.tgz", "integrity": "sha512-tbsV1jPne5CkFQCgPBcDOt30ItF7aJoZL997JSF7MhGQqOeT3svWRYxiqlfA5RUdlHN6Fi+EI9bxqbdyAUZjYQ==", "dev": true, + "peer": true, "dependencies": { "@typescript-eslint/scope-manager": "6.21.0", "@typescript-eslint/types": "6.21.0", @@ -8953,6 +8986,7 @@ "resolved": "https://registry.npmjs.org/eslint-config-prettier/-/eslint-config-prettier-9.1.0.tgz", "integrity": "sha512-NSWl5BFQWEPi1j4TjVNItzYV7dZXZ+wP6I6ZhrBGpChQhZRUaElihE9uRRkcbRnNb76UMKDF3r+WTmNcGPKsqw==", "dev": true, + "peer": true, "bin": { "eslint-config-prettier": "bin/cli.js" }, @@ -9365,6 +9399,7 @@ "resolved": "https://registry.npmjs.org/eslint-plugin-import/-/eslint-plugin-import-2.27.5.tgz", "integrity": "sha512-LmEt3GVofgiGuiE+ORpnvP+kAm3h6MLZJ4Q5HCyHADofsb4VzXFsRiWj3c0OFiV+3DWFh0qg3v9gcPlfc3zRow==", "dev": true, + "peer": true, "dependencies": { "array-includes": "^3.1.6", "array.prototype.flat": "^1.3.1", @@ -10125,6 +10160,7 @@ "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.12.0.tgz", "integrity": "sha512-sRu1kpcO9yLtYxBKvqfTeh9KzZEwO3STyX1HT+4CaDzC6HpTGYhIhPIzj9XuKU7KYDwnaeh5hcOwjy1QuJzBPA==", "dev": true, + "peer": true, "dependencies": { "fast-deep-equal": "^3.1.1", "json-schema-traverse": "^1.0.0", @@ -10395,45 +10431,50 @@ } }, "node_modules/express": { - "version": "4.21.1", - "resolved": "https://registry.npmjs.org/express/-/express-4.21.1.tgz", - "integrity": "sha512-YSFlK1Ee0/GC8QaO91tHcDxJiE/X4FbpAyQWkxAvG6AXCuR65YzK8ua6D9hvi/TzUfZMpc+BwuM1IPw8fmQBiQ==", + "version": "4.22.1", + "resolved": "https://registry.npmjs.org/express/-/express-4.22.1.tgz", + "integrity": "sha512-F2X8g9P1X7uCPZMA3MVf9wcTqlyNp7IhH5qPCI0izhaOIYXaW9L535tGA3qmjRzpH+bZczqq7hVKxTR4NWnu+g==", "dev": true, + "license": "MIT", "dependencies": { "accepts": "~1.3.8", "array-flatten": "1.1.1", - "body-parser": "1.20.3", - "content-disposition": "0.5.4", + "body-parser": "~1.20.3", + "content-disposition": "~0.5.4", "content-type": "~1.0.4", - "cookie": "0.7.1", - "cookie-signature": "1.0.6", + "cookie": "~0.7.1", + "cookie-signature": "~1.0.6", "debug": "2.6.9", "depd": "2.0.0", "encodeurl": "~2.0.0", "escape-html": "~1.0.3", "etag": "~1.8.1", - "finalhandler": "1.3.1", - "fresh": "0.5.2", - "http-errors": "2.0.0", + "finalhandler": "~1.3.1", + "fresh": "~0.5.2", + "http-errors": "~2.0.0", "merge-descriptors": "1.0.3", "methods": "~1.1.2", - "on-finished": "2.4.1", + "on-finished": "~2.4.1", "parseurl": "~1.3.3", - "path-to-regexp": "0.1.10", + "path-to-regexp": "~0.1.12", "proxy-addr": "~2.0.7", - "qs": "6.13.0", + "qs": "~6.14.0", "range-parser": "~1.2.1", "safe-buffer": "5.2.1", - "send": "0.19.0", - "serve-static": "1.16.2", + "send": "~0.19.0", + "serve-static": "~1.16.2", "setprototypeof": "1.2.0", - "statuses": "2.0.1", + "statuses": "~2.0.1", "type-is": "~1.6.18", "utils-merge": "1.0.1", "vary": "~1.1.2" }, "engines": { "node": ">= 0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" } }, "node_modules/express/node_modules/array-flatten": { @@ -10458,10 +10499,27 @@ "dev": true }, "node_modules/express/node_modules/path-to-regexp": { - "version": "0.1.10", - "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.10.tgz", - "integrity": "sha512-7lf7qcQidTku0Gu3YDPc8DJ1q7OOucfa/BSsIwjuh56VU7katFvuM8hULfkwB3Fns/rsVF7PwPKVw1sl5KQS9w==", - "dev": true + "version": "0.1.12", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.12.tgz", + "integrity": "sha512-RA1GjUVMnvYFxuqovrEqZoxxW5NUZqbwKtYz/Tt7nXerk0LbLblQmrsgdeOxV5SFHf0UDggjS/bSeOZwt1pmEQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/express/node_modules/qs": { + "version": "6.14.1", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.1.tgz", + "integrity": "sha512-4EK3+xJl8Ts67nLYNwqw/dsFVnCf+qR7RgXSK9jEEm9unao3njwMDdmsdvoKBKHzxd7tCYz5e5M+SnMjdtXGQQ==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } }, "node_modules/extract-files": { "version": "11.0.0", @@ -12766,6 +12824,7 @@ "resolved": "https://registry.npmjs.org/jest/-/jest-27.5.1.tgz", "integrity": "sha512-Yn0mADZB89zTtjkPJEXwrac3LHudkQMR+Paqa8uxJHCBr9agxztUifWCyiYrjhMPBoUVBjyny0I7XH6ozDr7QQ==", "dev": true, + "peer": true, "dependencies": { "@jest/core": "^27.5.1", "import-local": "^3.0.2", @@ -14210,6 +14269,7 @@ "resolved": "https://registry.npmjs.org/less/-/less-4.1.3.tgz", "integrity": "sha512-w16Xk/Ta9Hhyei0Gpz9m7VS8F28nieJaL/VyShID7cYvP6IL5oHeL6p4TXSDJqZE/lNv0oJ2pGVjJsRkfwm5FA==", "dev": true, + "peer": true, "dependencies": { "copy-anything": "^2.0.1", "parse-node-version": "^1.0.1", @@ -14749,6 +14809,7 @@ "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.12.0.tgz", "integrity": "sha512-sRu1kpcO9yLtYxBKvqfTeh9KzZEwO3STyX1HT+4CaDzC6HpTGYhIhPIzj9XuKU7KYDwnaeh5hcOwjy1QuJzBPA==", "dev": true, + "peer": true, "dependencies": { "fast-deep-equal": "^3.1.1", "json-schema-traverse": "^1.0.0", @@ -15098,10 +15159,14 @@ } }, "node_modules/object-inspect": { - "version": "1.13.1", - "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.1.tgz", - "integrity": "sha512-5qoj1RUiKOMsCCNLV1CBiPYE10sziTsnmNxkAI/rZhiD63CF7IqdFGC/XzjWjpSgLf0LxXX3bDFIh0E18f6UhQ==", + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, "funding": { "url": "https://github.com/sponsors/ljharb" } @@ -15699,6 +15764,7 @@ "url": "https://github.com/sponsors/ai" } ], + "peer": true, "dependencies": { "nanoid": "^3.3.6", "picocolors": "^1.0.0", @@ -16833,6 +16899,7 @@ "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.0.13.tgz", "integrity": "sha512-EaV1Gl4mUEV4ddhDnv/xtj7sxwrwxdetHdWUGnT4VJQf+4d05v6lHYZr8N573k5Z0BViss7BDhfWtKS3+sfAqQ==", "dev": true, + "peer": true, "dependencies": { "cssesc": "^3.0.0", "util-deprecate": "^1.0.2" @@ -16957,6 +17024,7 @@ "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.2.5.tgz", "integrity": "sha512-3/GWa9aOC0YeD7LUfvOG2NiDyhOWRvt1k+rcKhOuYnMY24iiCphgneUfJDyFXd6rZCAnuLBv6UeAULtrhT/F4A==", "dev": true, + "peer": true, "bin": { "prettier": "bin/prettier.cjs" }, @@ -17270,6 +17338,7 @@ "version": "16.14.0", "resolved": "https://registry.npmjs.org/react/-/react-16.14.0.tgz", "integrity": "sha512-0X2CImDkJGApiAlcf0ODKIneSwBPhqJawOa5wCtKbu7ZECrmS26NvtSILynQ66cgkT/RJ4LidJOc3bUESwmU8g==", + "peer": true, "dependencies": { "loose-envify": "^1.1.0", "object-assign": "^4.1.1", @@ -17360,6 +17429,7 @@ "version": "16.14.0", "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-16.14.0.tgz", "integrity": "sha512-1gCeQXDLoIqMgqD3IO2Ah9bnf0w9kzhwN5q4FGnHZ67hBm9yePzB5JJAIQCc8x3pFnNlwFq4RidZggNAAkzWWw==", + "peer": true, "dependencies": { "loose-envify": "^1.1.0", "object-assign": "^4.1.1", @@ -17405,6 +17475,7 @@ "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.11.0.tgz", "integrity": "sha512-F27qZr8uUqwhWZboondsPx8tnC3Ct3SxZA3V5WyEvujRyyNv0VYPhoBg1gZ8/MV5tubQp76Trw8lTv9hzRBa+A==", "dev": true, + "peer": true, "engines": { "node": ">=0.10.0" } @@ -17467,6 +17538,7 @@ "resolved": "https://registry.npmjs.org/react-scripts/-/react-scripts-5.0.1.tgz", "integrity": "sha512-8VAmEm/ZAwQzJ+GOMLbBsTdDKOpuZh7RPs0UymvBR2vRk4iZWCskjbFnxqjrzoIvlNNRZ3QJFx6/qDSi6zSnaQ==", "dev": true, + "peer": true, "dependencies": { "@babel/core": "^7.16.0", "@pmmmwh/react-refresh-webpack-plugin": "^0.5.3", @@ -18129,6 +18201,7 @@ "resolved": "https://registry.npmjs.org/rollup/-/rollup-2.79.2.tgz", "integrity": "sha512-fS6iqSPZDs3dr/y7Od6y5nha8dW1YnbgtsyotCVvoFGKbERG++CVRFv1meyGDE1SNItQA8BrnCw7ScdAhRJ3XQ==", "dev": true, + "peer": true, "bin": { "rollup": "dist/bin/rollup" }, @@ -18715,15 +18788,73 @@ } }, "node_modules/side-channel": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.6.tgz", - "integrity": "sha512-fDW/EZ6Q9RiO8eFG8Hj+7u/oW+XrPTIChwCOM2+th2A6OblDtYYIpve9m+KvI9Z4C9qSEXlaGR6bTEYHReuglA==", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", + "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", "dev": true, + "license": "MIT", "dependencies": { - "call-bind": "^1.0.7", "es-errors": "^1.3.0", - "get-intrinsic": "^1.2.4", - "object-inspect": "^1.13.1" + "object-inspect": "^1.13.3", + "side-channel-list": "^1.0.0", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz", + "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" }, "engines": { "node": ">= 0.4" @@ -19952,6 +20083,7 @@ "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", "dev": true, + "peer": true, "engines": { "node": ">=10" }, @@ -20051,7 +20183,6 @@ "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.9.5.tgz", "integrity": "sha512-1FXk9E2Hm+QzZQ7z+McJiHL4NW1F2EzMu9Nq9i3zAaGqibafqYwCVU6WyWAuyQRRzOlxou8xZSyXLEN8oKj24g==", "dev": true, - "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -20470,6 +20601,7 @@ "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.94.0.tgz", "integrity": "sha512-KcsGn50VT+06JH/iunZJedYGUJS5FGjow8wb9c0v5n1Om8O1g4L6LjtfxwlXIATopoQu+vOXXa7gYisWxCoPyg==", "dev": true, + "peer": true, "dependencies": { "@types/estree": "^1.0.5", "@webassemblyjs/ast": "^1.12.1", @@ -20539,6 +20671,7 @@ "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.12.0.tgz", "integrity": "sha512-sRu1kpcO9yLtYxBKvqfTeh9KzZEwO3STyX1HT+4CaDzC6HpTGYhIhPIzj9XuKU7KYDwnaeh5hcOwjy1QuJzBPA==", "dev": true, + "peer": true, "dependencies": { "fast-deep-equal": "^3.1.1", "json-schema-traverse": "^1.0.0", @@ -20592,6 +20725,7 @@ "resolved": "https://registry.npmjs.org/webpack-dev-server/-/webpack-dev-server-4.15.1.tgz", "integrity": "sha512-5hbAst3h3C3L8w6W4P96L5vaV0PxSmJhxZvWKYIdgxOQm8pNZ5dEOmmSLBVpP85ReeyRt6AS1QJNyo/oFFPeVA==", "dev": true, + "peer": true, "dependencies": { "@types/bonjour": "^3.5.9", "@types/connect-history-api-fallback": "^1.3.5", @@ -20651,6 +20785,7 @@ "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.12.0.tgz", "integrity": "sha512-sRu1kpcO9yLtYxBKvqfTeh9KzZEwO3STyX1HT+4CaDzC6HpTGYhIhPIzj9XuKU7KYDwnaeh5hcOwjy1QuJzBPA==", "dev": true, + "peer": true, "dependencies": { "fast-deep-equal": "^3.1.1", "json-schema-traverse": "^1.0.0", @@ -21065,6 +21200,7 @@ "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.12.0.tgz", "integrity": "sha512-sRu1kpcO9yLtYxBKvqfTeh9KzZEwO3STyX1HT+4CaDzC6HpTGYhIhPIzj9XuKU7KYDwnaeh5hcOwjy1QuJzBPA==", "dev": true, + "peer": true, "dependencies": { "fast-deep-equal": "^3.1.1", "json-schema-traverse": "^1.0.0", @@ -21329,6 +21465,7 @@ "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.10.tgz", "integrity": "sha512-+dbF1tHwZpXcbOJdVOkzLDxZP1ailvSxM6ZweXTegylPny803bFhA+vqBYw4s31NSAk4S2Qz+AKXK9a4wkdjcQ==", "license": "MIT", + "peer": true, "engines": { "node": ">=8.3.0" }, -- cgit v1.2.3 From 3e04ab2c3c81ebee11178c1767d70476bfa3575f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 1 Jan 2026 18:10:40 -0600 Subject: add counters for dropped and rejected requests, rename latency --- src/slskd/Telemetry/Metrics.cs | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/src/slskd/Telemetry/Metrics.cs b/src/slskd/Telemetry/Metrics.cs index 33d2bc40..610ab9c6 100644 --- a/src/slskd/Telemetry/Metrics.cs +++ b/src/slskd/Telemetry/Metrics.cs @@ -128,8 +128,8 @@ public static class Metrics /// /// Gets a histogram representing the total time taken to resolve a response to an incoming request to enqueue a file, in milliseconds. /// - public static Histogram ResponseLatency { get; } = Prometheus.Metrics.CreateHistogram( - "slskd_enqueue_response_latency", + public static Histogram Latency { get; } = Prometheus.Metrics.CreateHistogram( + "slskd_enqueue_latency", "The total time taken to resolve a response to an incoming request to enqueue a file, in milliseconds", new HistogramConfiguration { @@ -139,13 +139,23 @@ public static class Metrics /// /// Gets an EMA representing the average total time taken to resolve a response to an incoming request to enqueue a file, in milliseconds. /// - public static ExponentialMovingAverage CurrentResponseLatency { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentResponseLatencyGauge.Set(value)); + public static ExponentialMovingAverage CurrentLatency { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentResponseLatencyGauge.Set(value)); /// /// Gets a counter representing the total number of incoming enqueue requests received. /// public static Counter RequestsReceived { get; } = Prometheus.Metrics.CreateCounter("slskd_enqueue_requests_received", "Total number of incoming enqueue requests received"); + /// + /// Gets a counter representing the total number of incoming enqueue requests dropped due to processing pressure. + /// + public static Counter RequestsDropped { get; } = Prometheus.Metrics.CreateCounter("slskd_enqueue_requests_dropped", "Total number of incoming enqueue requests dropped due to processing pressure"); + + /// + /// Gets a counter representing the total number of incoming enqueue requests rejected. + /// + public static Counter RequestsRejected { get; } = Prometheus.Metrics.CreateCounter("slskd_enqueue_requests_rejected", "Total number of incoming enqueue requests rejected"); + /// /// Gets a counter representing the total number of incoming enqueue requests accepted. /// @@ -154,10 +164,10 @@ public static class Metrics /// /// Gets a gauge representing the number of incoming enqueue requests waiting to be processed. /// - public static Gauge CurrentRequestQueueDepth { get; } = Prometheus.Metrics.CreateGauge("slskd_enqueue_request_queue_depth_current", "The number of incoming enqueue requests waiting to be processed"); + public static Gauge CurrentQueueDepth { get; } = Prometheus.Metrics.CreateGauge("slskd_enqueue_queue_depth_current", "The number of incoming enqueue requests waiting to be processed"); private static Gauge CurrentDecisionLatencyGauge { get; } = Prometheus.Metrics.CreateGauge("slskd_enqueue_decision_latency_current", "The average time taken to evaluate an incoming request to enqueue a file against configured limits, in milliseconds"); - private static Gauge CurrentResponseLatencyGauge { get; } = Prometheus.Metrics.CreateGauge("slskd_enqueue_response_latency_current", "The average total time taken to resolve a response to an incoming request to enqueue a file, in milliseconds"); + private static Gauge CurrentLatencyGauge { get; } = Prometheus.Metrics.CreateGauge("slskd_enqueue_latency_current", "The average total time taken to resolve a response to an incoming request to enqueue a file, in milliseconds"); } /// -- cgit v1.2.3 From 870324657b842412a9af8268c65fac3ff56aa278 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 1 Jan 2026 18:26:07 -0600 Subject: oops --- src/slskd/Telemetry/Metrics.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/slskd/Telemetry/Metrics.cs b/src/slskd/Telemetry/Metrics.cs index 610ab9c6..33550577 100644 --- a/src/slskd/Telemetry/Metrics.cs +++ b/src/slskd/Telemetry/Metrics.cs @@ -139,7 +139,7 @@ public static class Metrics /// /// Gets an EMA representing the average total time taken to resolve a response to an incoming request to enqueue a file, in milliseconds. /// - public static ExponentialMovingAverage CurrentLatency { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentResponseLatencyGauge.Set(value)); + public static ExponentialMovingAverage CurrentLatency { get; } = new ExponentialMovingAverage(smoothingFactor: 0.5, onUpdate: value => CurrentLatencyGauge.Set(value)); /// /// Gets a counter representing the total number of incoming enqueue requests received. -- cgit v1.2.3 From 1adae6abf5035ac6271b124b106c6b386a3aaa83 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 1 Jan 2026 18:26:28 -0600 Subject: toss checkpointer in --- src/slskd/Common/Logging/Checkpointer.cs | 94 ++++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 src/slskd/Common/Logging/Checkpointer.cs diff --git a/src/slskd/Common/Logging/Checkpointer.cs b/src/slskd/Common/Logging/Checkpointer.cs new file mode 100644 index 00000000..08a6f2d9 --- /dev/null +++ b/src/slskd/Common/Logging/Checkpointer.cs @@ -0,0 +1,94 @@ +// +// 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; + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using Serilog; + +public static class CheckpointerExtensions +{ + public static Checkpointer Checkpointer(this ILogger logger, string context = null, [CallerMemberName] string memberName = "") + { + return new Checkpointer(context, memberName, logger); + } +} + +public sealed class Checkpointer : IDisposable +{ + public Checkpointer( + string context = null, + [CallerMemberName] string memberName = "", + ILogger logger = null) + { + Stopwatch = Stopwatch.StartNew(); + Context = $"{context ?? memberName}"; + Logger = logger ?? Log.ForContext().ForContext("CheckpointerContext", Context); + Checkpoints = new List<(string, long)>(); + LastCheckpointMs = 0; + + Logger.Debug("[{Context}] Started", Context); + } + + private Stopwatch Stopwatch { get; } + private string Context { get; } + private ILogger Logger { get; } + private List<(string Name, long ElapsedMs)> Checkpoints { get; } + private long LastCheckpointMs { get; set; } + + public void Capture( + string name, + [CallerLineNumber] int lineNumber = 0) + { + var currentMs = Stopwatch.ElapsedMilliseconds; + var deltaMs = currentMs - LastCheckpointMs; + + Checkpoints.Add((name, currentMs)); + + Logger.Warning( + "📌[{Context}] [+{Delta}ms] {Checkpoint} ({Total}ms)", + Context, + currentMs.ToString().PadLeft(5), + name, + deltaMs); + + LastCheckpointMs = currentMs; + } + + public void Summary() + { + Stopwatch.Stop(); + var totalMs = Stopwatch.ElapsedMilliseconds; + + Logger.Information( + "[{Context}] Completed in {Total}ms with {Count} checkpoints", + Context, + totalMs, + Checkpoints.Count); + } + + public void Dispose() + { + if (Stopwatch.IsRunning) + { + Summary(); + } + } +} \ No newline at end of file -- cgit v1.2.3 From d4bdc5be05c68288955ebc96bfd50d06ac8ca0d3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 1 Jan 2026 18:26:50 -0600 Subject: remove redundant username --- .../Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs b/src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs index 0c8d8b0c..1e85ee60 100644 --- a/src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs +++ b/src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs @@ -41,12 +41,11 @@ public class Z12282025_AdditionalTransferIndexesMigration : IMigration var idxes = SchemaInspector.GetDatabaseIndexes(ConnectionString); var txfers = idxes["Transfers"]; - var usernameExists = txfers.Any(c => c.Name.Equals("IDX_Transfers_Username", StringComparison.OrdinalIgnoreCase)); var removedExists = txfers.Any(c => c.Name.Equals("IDX_Transfers_Removed", StringComparison.OrdinalIgnoreCase)); var usernameFilenameExists = txfers.Any(c => c.Name.Equals("IDX_Transfers_UsernameFilename", StringComparison.OrdinalIgnoreCase)); var statsExist = txfers.Any(c => c.Name.Equals("IDX_Transfers_UserUploadStatistics", StringComparison.OrdinalIgnoreCase)); - if (usernameExists && removedExists && usernameFilenameExists && statsExist) + if (removedExists && usernameFilenameExists && statsExist) { return false; } @@ -77,7 +76,6 @@ public class Z12282025_AdditionalTransferIndexesMigration : IMigration Log.Information("> Adding missing index(es) on the Transfers table..."); - Exec("CREATE INDEX IF NOT EXISTS IDX_Transfers_Username ON Transfers (Username)"); Exec("CREATE INDEX IF NOT EXISTS IDX_Transfers_Removed ON Transfers (Removed)"); Exec("CREATE INDEX IF NOT EXISTS IDX_Transfers_UsernameFilename ON Transfers (Username, Filename)"); Exec("CREATE INDEX IF NOT EXISTS IDX_Transfers_UserUploadStatistics ON Transfers (Username, Direction, EndedAt, StartedAt, State, Size)"); -- cgit v1.2.3 From 42d1647f0ec495ee8afa986d9061603c70be7374 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 1 Jan 2026 18:31:10 -0600 Subject: add latency field --- src/slskd/Application.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index ae6b7c0b..d2bb1f3e 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -83,8 +83,8 @@ namespace slskd private static readonly string ApplicationShutdownTransferExceptionMessage = "Application shut down"; #pragma warning disable SA1306 // Field names should begin with lower-case letter - - private static int EnqueueRequestQueueDepth = 0; + private static int EnqueueQueueDepth = 0; + private static double CurrentEnqueueLatency = 0; #pragma warning restore SA1306 // Field names should begin with lower-case letter public Application( -- cgit v1.2.3 From 8b4a4d1d4c000192e068e5c78f3f9c18eb24d492 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 1 Jan 2026 18:31:57 -0600 Subject: add semaphores --- src/slskd/Application.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index d2bb1f3e..c5b6450c 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -224,7 +224,9 @@ namespace slskd private OptionsAtStartup OptionsAtStartup { get; set; } private IOptionsMonitor OptionsMonitor { get; set; } private SemaphoreSlim OptionsSyncRoot { get; } = new SemaphoreSlim(1, 1); - private SemaphoreSlim EnqueueRequestRateLimiter { get; } = new SemaphoreSlim(10, 10); + private SemaphoreSlim EnqueueSemaphore { get; } = new SemaphoreSlim(10, 10); + private SemaphoreSlim tUserEnqueueSemaphoreSyncRoot { get; } = new SemaphoreSlim(1, 1); + private ConcurrentDictionary UserEnqueueSemaphores { get; } = new ConcurrentDictionary(); private Options PreviousOptions { get; set; } private IPushbulletService Pushbullet { get; } private DateTime SharesRefreshStarted { get; set; } -- cgit v1.2.3 From 1bb14575e70e5fd61091d8f1b94cec8de68c4461 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 1 Jan 2026 18:38:24 -0600 Subject: acquire semaphores --- src/slskd/Application.cs | 101 ++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 92 insertions(+), 9 deletions(-) diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index c5b6450c..a08822da 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -224,8 +224,8 @@ namespace slskd private OptionsAtStartup OptionsAtStartup { get; set; } private IOptionsMonitor OptionsMonitor { get; set; } private SemaphoreSlim OptionsSyncRoot { get; } = new SemaphoreSlim(1, 1); - private SemaphoreSlim EnqueueSemaphore { get; } = new SemaphoreSlim(10, 10); - private SemaphoreSlim tUserEnqueueSemaphoreSyncRoot { get; } = new SemaphoreSlim(1, 1); + private SemaphoreSlim GlobalEnqueueSemaphore { get; } = new SemaphoreSlim(10, 10); + private SemaphoreSlim UserEnqueueSemaphoreSyncRoot { get; } = new SemaphoreSlim(1, 1); private ConcurrentDictionary UserEnqueueSemaphores { get; } = new ConcurrentDictionary(); private Options PreviousOptions { get; set; } private IPushbulletService Pushbullet { get; } @@ -544,24 +544,78 @@ namespace slskd { Metrics.Enqueue.RequestsReceived.Inc(1); - if (Users.IsBlacklisted(username, endpoint.Address)) + /* + circuit breaker/failsafe: + + if it would take longer than three minutes to process this request based on the number of waiting requests + and the average processing latency, reject the request automatically to alleviate pressure on the system. + + the requesting client will almost certainly consider any file for which it hasn't gotten confirmation + in over a minute to be failed, over 3 minutes is a safety buffer. + */ + if (EnqueueQueueDepth * CurrentEnqueueLatency > 180_000) { - Log.Information("Rejected enqueue request for blacklisted user {Username} ({IP})", username, endpoint.Address); - throw new DownloadEnqueueException("File not shared."); + Metrics.Enqueue.RequestsDropped.Inc(1); + throw new DownloadEnqueueException("Overwhelmed with requests; try again later."); } var stopwatch = new Stopwatch(); var decisionStopwatch = new Stopwatch(); - Interlocked.Increment(ref EnqueueRequestQueueDepth); + SemaphoreSlim userSemaphore = null; + Task userSemaphoreWaitTask; + bool userSemaphoreAcquired = false; - await EnqueueRequestRateLimiter.WaitAsync(); + bool enqueueRequestsSemaphoreAcquired = false; try { - Interlocked.Decrement(ref EnqueueRequestQueueDepth); + if (Users.IsBlacklisted(username, endpoint.Address)) + { + Log.Information("Rejected enqueue request for blacklisted user {Username} ({IP})", username, endpoint.Address); + throw new DownloadEnqueueException("File not shared."); + } + + /* + for limits to work properly (and to help alleviate strain from the db, make incoming requests 'fair' among competing users), + we need to ensure that we process only one request per user at a time. + + it's important that we obtain the user semaphore FIRST (before the global semaphore) to prevent one user + from monopolizing the request queue; users must 'go to the back of the line' for each request + + hopefully this process takes < 10ms on most systems, but on low-spec systems with high traffic, this + round-robin approach helps guarantee the best QoS for peers + */ + Interlocked.Increment(ref EnqueueQueueDepth); // any request waiting on any semaphore counts + + try + { + // obtain exclusive access over the user dictionary. if this blocks it'll only be for a few ns + // we should also only be holding it for a few ns per request + await UserEnqueueSemaphoreSyncRoot.WaitAsync(); + + try + { + // get the user's semaphore and START waiting; if we wait we'll tie up the sync root + userSemaphore = UserEnqueueSemaphores.GetOrAdd(username, new SemaphoreSlim(initialCount: 1, maxCount: 1)); + userSemaphoreWaitTask = userSemaphore.WaitAsync(); + } + finally + { + UserEnqueueSemaphoreSyncRoot.Release(); + } + + await userSemaphoreWaitTask; + userSemaphoreAcquired = true; - Metrics.Enqueue.CurrentRequestQueueDepth.Set(EnqueueRequestQueueDepth); + await GlobalEnqueueSemaphore.WaitAsync(); + enqueueRequestsSemaphoreAcquired = true; + } + finally + { + Interlocked.Decrement(ref EnqueueQueueDepth); + Metrics.Enqueue.CurrentQueueDepth.Set(EnqueueQueueDepth); + } stopwatch.Start(); @@ -1034,6 +1088,9 @@ namespace slskd { Metrics.DistributedNetwork.BroadcastLatency.Observe(Client.DistributedNetwork.AverageBroadcastLatency ?? 0); Metrics.DistributedNetwork.CurrentBroadcastLatency.Set(Client.DistributedNetwork.AverageBroadcastLatency ?? 0); + + _ = Task.Run(() => CleanupUserEnqueueSemaphoresAsync()) + .ContinueWith(task => Log.Error(task.Exception, "Failed to clean up user enqueue semaphore(s): {Message}", task.Exception?.Message), TaskContinuationOptions.OnlyOnFaulted); } private void Clock_EveryFiveMinutes(object sender, ClockEventArgs e) @@ -1744,5 +1801,31 @@ namespace slskd throw; } } + + private async Task CleanupUserEnqueueSemaphoresAsync() + { + // don't wait if we can't get exclusive access immediately; we'll get it eventually + if (await UserEnqueueSemaphoreSyncRoot.WaitAsync(0).ConfigureAwait(false)) + { + try + { + foreach (var kvp in UserEnqueueSemaphores) + { + // if we're able to obtain the semaphore immediately, there's nothing waiting on it + // and we're safe to dispose of it. the sync root saves us from concurrency issues here + if (await kvp.Value.WaitAsync(0).ConfigureAwait(false)) + { + UserEnqueueSemaphores.TryRemove(kvp.Key, out var removed); + removed.Dispose(); + Log.Debug($"Cleaned up enqueue semaphore for user {kvp.Key}"); + } + } + } + finally + { + UserEnqueueSemaphoreSyncRoot.Release(); + } + } + } } } \ No newline at end of file -- cgit v1.2.3 From 2100d773a653bf2bd49e5cb53d649744fc44c387 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 1 Jan 2026 18:39:12 -0600 Subject: release semaphores if they were acquired --- src/slskd/Application.cs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index a08822da..f5a15be1 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -803,7 +803,15 @@ namespace slskd } finally { - EnqueueRequestRateLimiter.Release(); + if (userSemaphoreAcquired) + { + userSemaphore.Release(); + } + + if (enqueueRequestsSemaphoreAcquired) + { + GlobalEnqueueSemaphore.Release(); + } } } -- cgit v1.2.3 From be5bd15dad2fb849b8c7358a87ed04f86b861730 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 1 Jan 2026 18:39:30 -0600 Subject: report decision stats in finally --- src/slskd/Application.cs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index f5a15be1..df01206f 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -803,6 +803,16 @@ namespace slskd } finally { + if (decisionStopwatch.IsRunning) + { + decisionStopwatch.Stop(); + } + + // decision latency is reported here so that we can track both successes and failures; they do the same + // work so lumping them together gives us the clearest picture + Metrics.Enqueue.DecisionLatency.Observe(decisionStopwatch.ElapsedMilliseconds); + Metrics.Enqueue.CurrentDecisionLatency.Update(decisionStopwatch.ElapsedMilliseconds); + if (userSemaphoreAcquired) { userSemaphore.Release(); -- cgit v1.2.3 From 9609f2555ad62ffa18590bd4a59dce49de991cb7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 1 Jan 2026 18:39:47 -0600 Subject: report rejected metric in catch --- src/slskd/Application.cs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index df01206f..61a72b4e 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -801,6 +801,11 @@ namespace slskd Log.Information("Enqueue of {Filename} to {Username} completed in {ElapsedOverall}ms, decision made in {ElapsedDecision}ms", filename, username, stopwatch.ElapsedMilliseconds, decisionStopwatch.ElapsedMilliseconds); } + catch (DownloadEnqueueException) + { + Metrics.Enqueue.RequestsRejected.Inc(1); + throw; + } finally { if (decisionStopwatch.IsRunning) -- cgit v1.2.3 From 048e15393491fb2514c83c098c150e4527f97df7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 1 Jan 2026 18:40:16 -0600 Subject: update full metrics --- src/slskd/Application.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 61a72b4e..52ca4f86 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -788,16 +788,16 @@ namespace slskd decisionStopwatch.Stop(); - Metrics.Enqueue.DecisionLatency.Observe(decisionStopwatch.ElapsedMilliseconds); - Metrics.Enqueue.CurrentDecisionLatency.Update(decisionStopwatch.ElapsedMilliseconds); - await Transfers.Uploads.EnqueueAsync(username, filename); stopwatch.Stop(); + // we only report metrics for successes so that each value is guaranteed to include the enqueue latency Metrics.Enqueue.RequestsAccepted.Inc(1); - Metrics.Enqueue.ResponseLatency.Observe(stopwatch.ElapsedMilliseconds); - Metrics.Enqueue.CurrentResponseLatency.Update(stopwatch.ElapsedMilliseconds); + Metrics.Enqueue.Latency.Observe(stopwatch.ElapsedMilliseconds); + Metrics.Enqueue.CurrentLatency.Update(stopwatch.ElapsedMilliseconds); + + Interlocked.Exchange(ref CurrentEnqueueLatency, Metrics.Enqueue.CurrentLatency.Value); Log.Information("Enqueue of {Filename} to {Username} completed in {ElapsedOverall}ms, decision made in {ElapsedDecision}ms", filename, username, stopwatch.ElapsedMilliseconds, decisionStopwatch.ElapsedMilliseconds); } -- cgit v1.2.3 From 9e7744c2507ef46d897741621f65e4f7b7de77f1 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 2 Jan 2026 18:24:54 -0600 Subject: remove Username index --- src/slskd/Transfers/TransfersDbContext.cs | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/slskd/Transfers/TransfersDbContext.cs b/src/slskd/Transfers/TransfersDbContext.cs index f89530df..b67bd47a 100644 --- a/src/slskd/Transfers/TransfersDbContext.cs +++ b/src/slskd/Transfers/TransfersDbContext.cs @@ -71,11 +71,6 @@ namespace slskd.Transfers .HasIndex(t => t.State) .HasDatabaseName("IDX_Transfers_State"); - modelBuilder - .Entity() - .HasIndex(t => t.Username) - .HasDatabaseName("IDX_Transfers_Username"); - modelBuilder .Entity() .HasIndex(t => t.Removed) -- cgit v1.2.3 From a3605e662815002085a5ab2c51ea459508d2c77f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 2 Jan 2026 18:44:03 -0600 Subject: Update src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- .../Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs b/src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs index 1e85ee60..2deffeb3 100644 --- a/src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs +++ b/src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs @@ -23,7 +23,7 @@ using Microsoft.Data.Sqlite; using Serilog; /// -/// Updates the Transfers table to add indexes on the Direction and State columns. +/// Adds additional indexes to the Transfers table for Removed, Username/Filename, and user upload statistics. /// public class Z12282025_AdditionalTransferIndexesMigration : IMigration { -- cgit v1.2.3 From 52d5509119d8c83bc96adc0205ecc7c1692cbb56 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 2 Jan 2026 18:45:23 -0600 Subject: Update src/slskd/Transfers/TransfersDbContext.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- src/slskd/Transfers/TransfersDbContext.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/slskd/Transfers/TransfersDbContext.cs b/src/slskd/Transfers/TransfersDbContext.cs index b67bd47a..422595e9 100644 --- a/src/slskd/Transfers/TransfersDbContext.cs +++ b/src/slskd/Transfers/TransfersDbContext.cs @@ -76,7 +76,7 @@ namespace slskd.Transfers .HasIndex(t => t.Removed) .HasDatabaseName("IDX_Transfers_Removed"); - // covers the ckeck for existing records when enqueueing uploads and downloads + // covers the check for existing records when enqueueing uploads and downloads modelBuilder .Entity() .HasIndex(t => new { t.Username, t.Filename }) -- cgit v1.2.3 From e340124d58d08785d8ef046b9374ca1413b73d3b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 2 Jan 2026 18:45:36 -0600 Subject: Update src/slskd/Transfers/Types/TransferStateCategories.cs Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- src/slskd/Transfers/Types/TransferStateCategories.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/slskd/Transfers/Types/TransferStateCategories.cs b/src/slskd/Transfers/Types/TransferStateCategories.cs index f894b963..5ccbe572 100644 --- a/src/slskd/Transfers/Types/TransferStateCategories.cs +++ b/src/slskd/Transfers/Types/TransferStateCategories.cs @@ -92,7 +92,7 @@ public static class TransferStateCategories /// /// (2) /// (2 | 2048 = 2050) - /// (2 | 4096 = 4098) + /// (2 | 4096 = 4098) /// /// public static readonly HashSet Queued = [ -- cgit v1.2.3 From 07d33d57d6af59699d5ef322b7710d214f69d3cc Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 Jan 2026 13:21:52 -0600 Subject: add security policy --- SECURITY.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 SECURITY.md diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 00000000..f186b0db --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,5 @@ +# Security Policy + +## Reporting a Vulnerability + +Please report security vulnerabilities via email to security@slskd.org. \ No newline at end of file -- cgit v1.2.3 From f2d6e478a443e813ff2b31a199b93e44e71a0cd7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 Jan 2026 13:40:06 -0600 Subject: update CONTRIBUTING --- CONTRIBUTING.md | 28 +++++++++++++++------------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 1c65af07..9ffedd08 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,26 +1,28 @@ # Contributing -When contributing to this repository, please first discuss the change you wish to make via issue, -email, or any other method with the owners of this repository before making a change. +All contributions must first have been discussed within an Issue or Discussion. -We don't maintain a Contributor License Agreement (CLA) but we do require that anyone that wishes to contribute agrees to the following: +Pull Requests opened without an accompanying Issue are considered to be unsolicited, and unsolicited Pull Requests may be rejected without review or converted into an Issue. -* You have the right to assign the copyright of your contribution. -* By making your contribution, you are giving up copyright of your contribution. +## Copyright -This application is released under the [AGPL 3.0](https://github.com/slskd/slskd/blob/master/LICENSE) license, and no single individual or entity owns -or will ever own the copyright. +By submitting a contribution to this project, you agree to the following: + +* You have the legal right to make this contribution and to assign its copyright. +* You irrevocably assign all copyright and related rights in your contribution to the project maintainer(s). +* You grant the project maintainer(s) the right to use, modify, distribute, and relicense your contribution under any license of their choosing. + +This application is currently released under the [AGPL 3.0](https://github.com/slskd/slskd/blob/master/LICENSE) license. ## Contribution Workflow -1. Assign yourself to the issue that you'll be working on. If you'd like to contribute something for which there is no - existing issue, consider creating one before you start so we can discuss. -1. Clone the repository and `git checkout master` to ensure you are on the master branch. +1. Comment on the Issue you'll be working on so others know you're working on it. You may also ask a maintainer to assign it to you. +1. Fork the repository, then clone it and run `git checkout master` to ensure you are on the master branch. 1. Create a new branch for your change with `git checkout -b ` be descriptive, but terse. 1. Make your changes. When finished, push your branch with `git push origin --set-upstream `. -1. Create a pull request to merge `` into `master`. -1. A maintainer will review your pull request and may make comments, ask questions, or request changes. When all - feedback has been addressed the pull request will be approved, and after all checks have passed it will be merged by +1. Create a Pull Request in the source repository to merge `` into `master`. +1. A maintainer will review your Pull Request and may make comments, ask questions, or request changes. When all + feedback has been addressed the Pull Request will be approved, and after all checks have passed it will be merged by a maintainer, or you may merge it yourself if you have the necessary access. 1. Delete your branch, unless you plan to submit additional pull request from it. -- cgit v1.2.3 From 91eb4a950965c95adeeb98b60d31ad32164adc4c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 Jan 2026 13:51:21 -0600 Subject: add AI clause --- .github/ISSUE_TEMPLATE/bug_report.yml | 54 ++++++++++++++++++++++++++++++ .github/ISSUE_TEMPLATE/config.yml | 5 +++ .github/ISSUE_TEMPLATE/feature_request.yml | 24 +++++++++++++ CONTRIBUTING.md | 14 ++++++-- 4 files changed, 94 insertions(+), 3 deletions(-) create mode 100644 .github/ISSUE_TEMPLATE/bug_report.yml create mode 100644 .github/ISSUE_TEMPLATE/config.yml create mode 100644 .github/ISSUE_TEMPLATE/feature_request.yml diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 00000000..e857f7ca --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,54 @@ +name: Bug Report +description: Something is broken or doesn't work as expected +labels: ['needs triage'] +body: +- type: checkboxes + attributes: + label: Is there an existing issue for this? + options: + - label: I have searched for existing issues (both open and closed) + required: true +- type: textarea + attributes: + label: Describe the Bug + description: A concise description of what you're experiencing. + validations: + required: true +- type: textarea + attributes: + label: Steps To Reproduce + description: Steps to reproduce the behavior. + placeholder: | + 1. In this environment... + 2. With this config... + 3. Run '...' + 4. See error... + validations: + required: false +- type: textarea + attributes: + label: Environment + description: | + examples: + - **OS**: Ubuntu 22.04 + - **slskd**: 0.24.0 + - **Docker Install?**: Yes + - **Filesystem**: ext4 + - **Hardware**: Raspberry Pi 5 4gb + value: | + - OS: + - slskd: + - Docker Install?: + - Filesystem: + - Hardware: + render: markdown + validations: + required: true +- type: textarea + attributes: + label: Anything else? + description: | + Links? Screenshots? References? Anything that will give us more context about the issue you are encountering! + Tip: You can attach images or log files by clicking this area to highlight it and then dragging files in. + validations: + required: false diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 00000000..8bec6cd6 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: false +contact_links: + - name: Support via Discord + url: https://discord.gg/GjDW5r8u + about: Chat with users and devs on support and setup related topics. \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 00000000..f01bcb25 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,24 @@ +name: Feature Request +description: Suggest a feature for slskd +labels: ['needs triage'] +body: +- type: checkboxes + attributes: + label: Is there an existing issue for this? + options: + - label: I have searched for existing issues (both open and closed) + required: true +- type: textarea + attributes: + label: Describe the Feature + description: A concise description of the feature you'd like to be added. + validations: + required: true +- type: textarea + attributes: + label: Anything else? + description: | + Links? Screenshots? References? Anything that will give us more context about the feature you are suggesting! + Tip: You can attach images or log files by clicking this area to highlight it and then dragging files in. + validations: + required: false diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9ffedd08..73ebce45 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,8 +1,6 @@ # Contributing -All contributions must first have been discussed within an Issue or Discussion. - -Pull Requests opened without an accompanying Issue are considered to be unsolicited, and unsolicited Pull Requests may be rejected without review or converted into an Issue. +All contributions must have first been discussed within an Issue or Discussion. Pull Requests opened without an accompanying Issue are considered to be unsolicited, and unsolicited Pull Requests may be rejected without review and/or converted into an Issue. ## Copyright @@ -14,6 +12,16 @@ By submitting a contribution to this project, you agree to the following: This application is currently released under the [AGPL 3.0](https://github.com/slskd/slskd/blob/master/LICENSE) license. +## Use of AI in Contributions + +If you used AI tools (such as ChatGPT, Copilot, Claude, etc.) to assist with your contribution, you must clearly disclose this in your Pull Request, including: + +* Which AI tool(s) you used +* How you used them (e.g., code generation, refactoring suggestions, documentation help) +* Which parts of your contribution were AI-assisted + +Contributors are expected to fully understand and take responsibility for all code they submit, regardless of how it was produced. Contributions made entirely by AI are not welcome and will be rejected. + ## Contribution Workflow 1. Comment on the Issue you'll be working on so others know you're working on it. You may also ask a maintainer to assign it to you. -- cgit v1.2.3 From 8d27bf1c9b4498b8808159c5525f603ab7faa38d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 Jan 2026 13:58:43 -0600 Subject: add coc --- CODE_OF_CONDUCT.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 CODE_OF_CONDUCT.md diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 00000000..2c7b7aa6 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,5 @@ +# Code of Conduct + +[Be excellent to each other](https://www.youtube.com/watch?v=rph_1DODXDU), and especially to maintainers. + +The definition of excellence is at the sole discretion of the maintainers. \ No newline at end of file -- cgit v1.2.3 From a1ca1bb0b2e0635999739aed6b1fcd2329c28b2a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 Jan 2026 14:12:40 -0600 Subject: add PR template --- .github/PULL_REQUEST_TEMPLATE.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 .github/PULL_REQUEST_TEMPLATE.md diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 00000000..a46d48d6 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,29 @@ + \ No newline at end of file -- cgit v1.2.3 From 02df53f215a57c58d78df20a03497f03cce12185 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 Jan 2026 14:13:51 -0600 Subject: remove disclaimer --- README.md | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/README.md b/README.md index 2d9897c1..e23bea3f 100644 --- a/README.md +++ b/README.md @@ -1,18 +1,3 @@ -> [!WARNING] -> This is the only official repository for slskd. -> -> Official releases are published via: -> * Build artifacts from the [GitHub Actions](github.com/slskd/slskd/actions) of this repository -> * Platform-specific archives located in [Releases](https://github.com/slskd/slskd/releases/) -> * Docker images published to [Docker Hub](https://hub.docker.com/r/slskd/slskd) and [GitHub Container Registry](https://github.com/slskd/slskd/pkgs/container/slskd) -> -> The name associated with official releases is `slskd`. Any change to this will be clearly communicated here. -> -> If you encounter binaries with different names claiming to be slskd or an alternative, they are not affiliated with this project. -> -> Be cautious of unaffiliated forks that automatically mirror this repository and re-release binaries under different names. These forks are not reviewed, endorsed, or supported by the slskd maintainers, and may introduce changes that compromise security, privacy, or network integrity. -> As with any software, verify the source of binaries before running them. Supply chain attacks via unofficial forks are a real risk—if you didn't get it from this repository, you can't be certain what you're running. - # slskd [![Build](https://img.shields.io/github/actions/workflow/status/slskd/slskd/ci.yml?branch=master&logo=github)](https://github.com/slskd/slskd/actions/workflows/ci.yml) -- cgit v1.2.3 From 4f28547419971338afe679e129da87fbd39aa35a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 9 Jan 2026 08:40:41 -0600 Subject: add Failed retention setting, add more states to errored cleanup --- config/slskd.example.yml | 2 ++ src/slskd/Application.cs | 14 ++++++++------ src/slskd/Core/Options.cs | 6 ++++++ 3 files changed, 16 insertions(+), 6 deletions(-) diff --git a/config/slskd.example.yml b/config/slskd.example.yml index 66379626..b8723f4d 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -169,10 +169,12 @@ # succeeded: 1440 # 1 day, in minutes # errored: 30 # cancelled: 5 +# failed: 180 # any unsuccessful transfer, including errored and cancelled # download: # succeeded: 1440 # 1 day, in minutes # errored: 20160 # 2 weeks, in minutes # cancelled: 5 +# failed: 180 # any unsuccessful transfer, including errored and cancelled # files: # complete: 20160 # 2 weeks, in minutes # incomplete: 43200 # 30 days, in minutes diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index 52ca4f86..a93afafe 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -1226,19 +1226,19 @@ namespace slskd { var options = OptionsMonitor.CurrentValue.Retention; - void PruneUpload(int? age, TransferStates state) + void PruneUpload(int? age, params TransferStates[] states) { if (age.HasValue) { - Transfers.Uploads.Prune(age.Value, TransferStates.Completed | state); + Transfers.Uploads.Prune(age.Value, [.. states.Select(s => TransferStates.Completed | s)]); } } - void PruneDownload(int? age, TransferStates state) + void PruneDownload(int? age, params TransferStates[] states) { if (age.HasValue) { - Transfers.Downloads.Prune(age.Value, TransferStates.Completed | state); + Transfers.Downloads.Prune(age.Value, [.. states.Select(s => TransferStates.Completed | s)]); } } @@ -1246,11 +1246,13 @@ namespace slskd { PruneUpload(options.Transfers.Upload.Succeeded, TransferStates.Succeeded); PruneUpload(options.Transfers.Upload.Cancelled, TransferStates.Cancelled); - PruneUpload(options.Transfers.Upload.Errored, TransferStates.Errored); + PruneUpload(options.Transfers.Upload.Errored, TransferStates.Errored, TransferStates.Aborted, TransferStates.Rejected, TransferStates.TimedOut); + PruneUpload(options.Transfers.Upload.Failed, [.. TransferStateCategories.Failed]); PruneDownload(options.Transfers.Download.Succeeded, TransferStates.Succeeded); PruneDownload(options.Transfers.Download.Cancelled, TransferStates.Cancelled); - PruneDownload(options.Transfers.Download.Errored, TransferStates.Errored); + PruneDownload(options.Transfers.Download.Errored, TransferStates.Errored, TransferStates.Aborted, TransferStates.TimedOut); + PruneDownload(options.Transfers.Download.Failed, [.. TransferStateCategories.Failed]); } catch { diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 20b53f6c..a1d9953c 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1423,6 +1423,12 @@ namespace slskd /// [Range(5, maximum: int.MaxValue)] public int? Cancelled { get; init; } = null; + + /// + /// Gets the time to retain unsuccessful (including errored and cancelled) transfers, in minutes. + /// + [Range(5, maximum: int.MaxValue)] + public int? Failed { get; init; } = null; } } -- cgit v1.2.3 From cb31a68a6e7f6d195281a7a480af539ddd945688 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 9 Jan 2026 08:43:38 -0600 Subject: update retention docs --- docs/config.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/config.md b/docs/config.md index 3efe2e8a..c47235af 100644 --- a/docs/config.md +++ b/docs/config.md @@ -950,7 +950,7 @@ By default, most things created by the application are retained indefinitely; th Completed searches can be configured to be removed from the UI and 'hard' deleted from the database. It's a good idea to set this to something relatively short, as old searches have diminishing value as they age and the records contain a lot of data. -Transfers can be configured to be removed from the UI after they are complete by specifying retention periods for uploads and downloads separately, and by transfer state; succeeded, errored, and cancelled. +Transfers can be configured to be removed from the UI after they are complete by specifying retention periods for uploads and downloads separately, and by transfer state; succeeded, errored, and cancelled. The 'failed' setting can be used instead of 'errored' and 'cancelled' to clean up all transfers that were not successful, regardless of reason. Files (on disk) can be configured to be deleted after the age of their last access time exceeds the configured time. Completed and incomplete files can be configured separately. @@ -967,10 +967,12 @@ retention: succeeded: 1440 # 1 day errored: 30 cancelled: 5 + failed: 180 download: succeeded: 1440 # 1 day errored: 20160 # 2 weeks cancelled: 5 + failed: 180 files: complete: 20160 # 2 weeks incomplete: 43200 # 30 days -- cgit v1.2.3