aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2026-01-09 08:51:27 -0600
committerGitHub <noreply@github.com>2026-01-09 08:51:27 -0600
commit8c3051a07910a2af0145f2ac89b905f139ce8f6b (patch)
tree38a3fa22afd1348b3bb4e4c4f31f3f5d9df6dfcb
parente8f533d87e58bbeca71468c97f5ec67598726bb4 (diff)
parentb8d0dab8a70c38b981fa6a299acd76140a59400a (diff)
downloadslskd-8c3051a07910a2af0145f2ac89b905f139ce8f6b.tar.gz
Merge branch 'master' into dependabot/npm_and_yarn/src/web/multi-c8afcbbcd8
-rw-r--r--.github/ISSUE_TEMPLATE/bug_report.yml54
-rw-r--r--.github/ISSUE_TEMPLATE/config.yml5
-rw-r--r--.github/ISSUE_TEMPLATE/feature_request.yml24
-rw-r--r--.github/PULL_REQUEST_TEMPLATE.md29
-rw-r--r--CODE_OF_CONDUCT.md5
-rw-r--r--CONTRIBUTING.md36
-rw-r--r--README.md15
-rw-r--r--SECURITY.md5
-rw-r--r--config/slskd.example.yml2
-rw-r--r--docs/config.md4
-rw-r--r--src/slskd/Application.cs259
-rw-r--r--src/slskd/Common/Logging/Checkpointer.cs94
-rw-r--r--src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs93
-rw-r--r--src/slskd/Core/Data/Migrator.cs1
-rw-r--r--src/slskd/Core/Options.cs6
-rw-r--r--src/slskd/Program.cs7
-rw-r--r--src/slskd/Telemetry/Metrics.cs20
-rw-r--r--src/slskd/Transfers/API/Controllers/TransfersController.cs4
-rw-r--r--src/slskd/Transfers/Downloads/DownloadService.cs4
-rw-r--r--src/slskd/Transfers/TransfersDbContext.cs18
-rw-r--r--src/slskd/Transfers/Types/TransferStateCategories.cs73
-rw-r--r--src/slskd/Transfers/Types/UserUploadStatistics.cs35
-rw-r--r--src/slskd/Transfers/Uploads/UploadService.cs58
23 files changed, 694 insertions, 157 deletions
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/.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 @@
+<!--
+
+Per CONTRIBUTING.md:
+
+# Contributing
+
+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
+
+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.
+
+## 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.
+
+--> \ No newline at end of file
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
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 1c65af07..73ebce45 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -1,26 +1,36 @@
# 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 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.
-We don't maintain a Contributor License Agreement (CLA) but we do require that anyone that wishes to contribute agrees to the following:
+## Copyright
-* You have the right to assign the copyright of your contribution.
-* By making your contribution, you are giving up copyright of your contribution.
+By submitting a contribution to this project, you agree to the following:
-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.
+* 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.
+
+## 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. 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 <your-branch-name>` be descriptive, but terse.
1. Make your changes. When finished, push your branch with `git push origin --set-upstream <your-branch-name>`.
-1. Create a pull request to merge `<your-branch-name>` 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 `<your-branch-name>` 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.
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)
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
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/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
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs
index 6b66ec6e..a93afafe 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(
@@ -224,7 +224,9 @@ namespace slskd
private OptionsAtStartup OptionsAtStartup { get; set; }
private IOptionsMonitor<Options> OptionsMonitor { get; set; }
private SemaphoreSlim OptionsSyncRoot { get; } = new SemaphoreSlim(1, 1);
- private SemaphoreSlim EnqueueRequestRateLimiter { get; } = new SemaphoreSlim(20, 20);
+ private SemaphoreSlim GlobalEnqueueSemaphore { get; } = new SemaphoreSlim(10, 10);
+ private SemaphoreSlim UserEnqueueSemaphoreSyncRoot { get; } = new SemaphoreSlim(1, 1);
+ private ConcurrentDictionary<string, SemaphoreSlim> UserEnqueueSemaphores { get; } = new ConcurrentDictionary<string, SemaphoreSlim>();
private Options PreviousOptions { get; set; }
private IPushbulletService Pushbullet { get; }
private DateTime SharesRefreshStarted { get; set; }
@@ -316,7 +318,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 +329,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)
{
@@ -538,29 +540,82 @@ 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))
+ /*
+ 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
- Metrics.Enqueue.CurrentRequestQueueDepth.Set(EnqueueRequestQueueDepth);
+ 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;
+
+ await GlobalEnqueueSemaphore.WaitAsync();
+ enqueueRequestsSemaphoreAcquired = true;
+ }
+ finally
+ {
+ Interlocked.Decrement(ref EnqueueQueueDepth);
+ Metrics.Enqueue.CurrentQueueDepth.Set(EnqueueQueueDepth);
+ }
stopwatch.Start();
@@ -623,45 +678,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 +738,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 +764,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,25 +786,47 @@ 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.ResponseLatency.Observe(stopwatch.ElapsedMilliseconds);
- Metrics.Enqueue.CurrentResponseLatency.Update(stopwatch.ElapsedMilliseconds);
+ // we only report metrics for successes so that each value is guaranteed to include the enqueue latency
+ Metrics.Enqueue.RequestsAccepted.Inc(1);
+ 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);
+ }
+ catch (DownloadEnqueueException)
+ {
+ Metrics.Enqueue.RequestsRejected.Inc(1);
+ throw;
}
finally
{
- EnqueueRequestRateLimiter.Release();
+ 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();
+ }
- Log.Debug("EnqueueDownload for {Username}/{Filename} completed in {ElapsedOverall}ms, decision made in {ElapsedDecision}ms", username, filename, stopwatch.ElapsedMilliseconds, decisionStopwatch.ElapsedMilliseconds);
+ if (enqueueRequestsSemaphoreAcquired)
+ {
+ GlobalEnqueueSemaphore.Release();
+ }
}
}
@@ -1061,6 +1111,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)
@@ -1173,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)]);
}
}
@@ -1193,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
{
@@ -1771,5 +1826,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
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 file="Checkpointer.cs" company="slskd Team">
+// 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/.
+// </copyright>
+
+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<Checkpointer>().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
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..2deffeb3
--- /dev/null
+++ b/src/slskd/Core/Data/Migrations/Z12282025_AdditionalTransferIndexesMigration.cs
@@ -0,0 +1,93 @@
+// <copyright file="Z12282025_AdditionalTransferIndexesMigration.cs" company="slskd Team">
+// 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/.
+// </copyright>
+
+namespace slskd.Migrations;
+
+using System;
+using System.Linq;
+using Microsoft.Data.Sqlite;
+using Serilog;
+
+/// <summary>
+/// Adds additional indexes to the Transfers table for Removed, Username/Filename, and user upload statistics.
+/// </summary>
+public class Z12282025_AdditionalTransferIndexesMigration : IMigration
+{
+ public Z12282025_AdditionalTransferIndexesMigration(ConnectionStringDictionary connectionStrings)
+ {
+ ConnectionString = connectionStrings[Database.Transfers];
+ }
+
+ private ILogger Log { get; } = Serilog.Log.ForContext<Z12282025_AdditionalTransferIndexesMigration>();
+ 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 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 (removedExists && usernameFilenameExists && 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
+ {
+ void Exec(string sql)
+ {
+ using var command = new SqliteCommand(sql, connection, transaction);
+ command.ExecuteNonQuery();
+ }
+
+ Log.Information("> Adding missing index(es) on the Transfers table...");
+
+ 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();
+ Log.Information("> Done!");
+ }
+ catch (Exception)
+ {
+ transaction.Rollback();
+ throw;
+ }
+ }
+}
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) },
};
}
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
/// </summary>
[Range(5, maximum: int.MaxValue)]
public int? Cancelled { get; init; } = null;
+
+ /// <summary>
+ /// Gets the time to retain unsuccessful (including errored and cancelled) transfers, in minutes.
+ /// </summary>
+ [Range(5, maximum: int.MaxValue)]
+ public int? Failed { get; init; } = null;
}
}
diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs
index 770c6746..2b2d2840 100644
--- a/src/slskd/Program.cs
+++ b/src/slskd/Program.cs
@@ -1293,9 +1293,12 @@ namespace slskd
options.UseSqlite(connectionString);
options.AddInterceptors(new SqliteConnectionOpenedInterceptor());
- if (OptionsAtStartup.Debug && OptionsAtStartup.Flags.LogSQL)
+ if (OptionsAtStartup.Flags.LogSQL)
{
- options.LogTo(Log.Debug, LogLevel.Information);
+ options
+ .EnableSensitiveDataLogging()
+ .EnableDetailedErrors()
+ .LogTo(OptionsAtStartup.Debug ? Log.Debug : Log.Information, LogLevel.Information);
}
});
diff --git a/src/slskd/Telemetry/Metrics.cs b/src/slskd/Telemetry/Metrics.cs
index 33d2bc40..33550577 100644
--- a/src/slskd/Telemetry/Metrics.cs
+++ b/src/slskd/Telemetry/Metrics.cs
@@ -128,8 +128,8 @@ public static class Metrics
/// <summary>
/// Gets a histogram representing the total time taken to resolve a response to an incoming request to enqueue a file, in milliseconds.
/// </summary>
- 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,7 +139,7 @@ public static class Metrics
/// <summary>
/// Gets an EMA representing the average total time taken to resolve a response to an incoming request to enqueue a file, in milliseconds.
/// </summary>
- 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 => CurrentLatencyGauge.Set(value));
/// <summary>
/// Gets a counter representing the total number of incoming enqueue requests received.
@@ -147,6 +147,16 @@ public static class Metrics
public static Counter RequestsReceived { get; } = Prometheus.Metrics.CreateCounter("slskd_enqueue_requests_received", "Total number of incoming enqueue requests received");
/// <summary>
+ /// Gets a counter representing the total number of incoming enqueue requests dropped due to processing pressure.
+ /// </summary>
+ public static Counter RequestsDropped { get; } = Prometheus.Metrics.CreateCounter("slskd_enqueue_requests_dropped", "Total number of incoming enqueue requests dropped due to processing pressure");
+
+ /// <summary>
+ /// Gets a counter representing the total number of incoming enqueue requests rejected.
+ /// </summary>
+ public static Counter RequestsRejected { get; } = Prometheus.Metrics.CreateCounter("slskd_enqueue_requests_rejected", "Total number of incoming enqueue requests rejected");
+
+ /// <summary>
/// Gets a counter representing the total number of incoming enqueue requests accepted.
/// </summary>
public static Counter RequestsAccepted { get; } = Prometheus.Metrics.CreateCounter("slskd_enqueue_requests_accepted", "Total number of incoming enqueue requests accepted");
@@ -154,10 +164,10 @@ public static class Metrics
/// <summary>
/// Gets a gauge representing the number of incoming enqueue requests waiting to be processed.
/// </summary>
- 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");
}
/// <summary>
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/TransfersDbContext.cs b/src/slskd/Transfers/TransfersDbContext.cs
index eac4935b..422595e9 100644
--- a/src/slskd/Transfers/TransfersDbContext.cs
+++ b/src/slskd/Transfers/TransfersDbContext.cs
@@ -70,6 +70,24 @@ namespace slskd.Transfers
.Entity<Transfer>()
.HasIndex(t => t.State)
.HasDatabaseName("IDX_Transfers_State");
+
+ modelBuilder
+ .Entity<Transfer>()
+ .HasIndex(t => t.Removed)
+ .HasDatabaseName("IDX_Transfers_Removed");
+
+ // covers the check for existing records when enqueueing uploads and downloads
+ modelBuilder
+ .Entity<Transfer>()
+ .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<Transfer>()
+ .HasIndex(e => new { e.Username, e.Direction, e.EndedAt, e.StartedAt, e.State, e.Size })
+ .HasDatabaseName("IDX_Transfers_UserUploadStatistics");
}
}
}
diff --git a/src/slskd/Transfers/Types/TransferStateCategories.cs b/src/slskd/Transfers/Types/TransferStateCategories.cs
index 02065714..5ccbe572 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:
///
/// <list type="bullet">
- /// <item><see cref="TransferStates.Succeeded"/></item>
+ /// <item><see cref="TransferStates.Succeeded"/> (16 | 32 = 48)</item>
/// </list>
/// </summary>
- public static readonly HashSet<int> Successful = [
- (int)(TransferStates.Completed | TransferStates.Succeeded)
+ public static readonly HashSet<TransferStates> Successful = [
+ TransferStates.Completed | TransferStates.Succeeded // 16 | 32 = 48
];
/// <summary>
/// All states representing a failed transfer:
///
/// <list type="bullet">
- /// <item><see cref="TransferStates.Cancelled"/></item>
- /// <item><see cref="TransferStates.TimedOut"/></item>
- /// <item><see cref="TransferStates.Errored"/></item>
- /// <item><see cref="TransferStates.Rejected"/></item>
- /// <item><see cref="TransferStates.Aborted"/></item>
+ /// <item><see cref="TransferStates.Cancelled"/> (16 | 64 = 80)</item>
+ /// <item><see cref="TransferStates.TimedOut"/> (16 | 128 = 144)</item>
+ /// <item><see cref="TransferStates.Errored"/> (16 | 256 = 272)</item>
+ /// <item><see cref="TransferStates.Rejected"/> (16 | 512 = 528)</item>
+ /// <item><see cref="TransferStates.Aborted"/> (16 | 1024 = 1040)</item>
/// </list>
/// </summary>
- public static readonly HashSet<int> 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),
+ public static readonly HashSet<TransferStates> 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
];
/// <summary>
/// All states containing the <see cref="TransferStates.Completed"/> flag.
+ ///
+ /// <list type="bullet">
+ /// <item><see cref="TransferStates.Completed"/> (16)</item>
+ /// </list>
+ ///
+ /// Successful:
+ /// <list type="bullet">
+ /// <item><see cref="TransferStates.Succeeded"/> (16 | 32 = 48)</item>
+ /// </list>
+ ///
+ /// Failed:
+ /// <list type="bullet">
+ /// <item><see cref="TransferStates.Cancelled"/> (16 | 64 = 80)</item>
+ /// <item><see cref="TransferStates.TimedOut"/> (16 | 128 = 144)</item>
+ /// <item><see cref="TransferStates.Errored"/> (16 | 256 = 272)</item>
+ /// <item><see cref="TransferStates.Rejected"/> (16 | 512 = 528)</item>
+ /// <item><see cref="TransferStates.Aborted"/> (16 | 1024 = 1040)</item>
+ /// </list>
/// </summary>
- public static readonly HashSet<int> Completed = [
- (int)TransferStates.Completed, // in case some sort of a malfunction or regression
+ public static readonly HashSet<TransferStates> Completed = [
+ 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:
///
/// <list type="bullet">
- /// <item><see cref="TransferStates.Locally"/></item>
- /// <item><see cref="TransferStates.Remotely"/></item>
+ /// <item><see cref="TransferStates.Queued"/> (2)</item>
+ /// <item><see cref="TransferStates.Locally"/> (2 | 2048 = 2050)</item>
+ /// <item><see cref="TransferStates.Remotely"/> (2 | 4096 = 4098)</item>
/// </list>
/// </summary>
- public static readonly HashSet<int> Queued = [
- (int)TransferStates.Queued,
- (int)(TransferStates.Queued | TransferStates.Locally),
- (int)(TransferStates.Queued | TransferStates.Remotely),
+ public static readonly HashSet<TransferStates> 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
];
/// <summary>
/// All states representing a transfer that is in progress:
///
/// <list type="bullet">
- /// <item><see cref="TransferStates.Initializing"/></item>
- /// <item><see cref="TransferStates.InProgress"/></item>
+ /// <item><see cref="TransferStates.Initializing"/> (4)</item>
+ /// <item><see cref="TransferStates.InProgress"/> (8)</item>
/// </list>
/// </summary>
- public static readonly HashSet<int> InProgress = [
- (int)TransferStates.Initializing,
- (int)TransferStates.InProgress,
+ public static readonly HashSet<TransferStates> InProgress = [
+ TransferStates.Initializing, // 4
+ TransferStates.InProgress, // 8
];
} \ No newline at end of file
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 file="UserUploadStatistics.cs" company="slskd Team">
+// 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/.
+// </copyright>
+
+namespace slskd.Transfers;
+
+/// <summary>
+/// Upload statistics, for use when evaluating incoming enqueue requests against configured limits.
+/// </summary>
+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 d75ccea3..bcc1dd90 100644
--- a/src/slskd/Transfers/Uploads/UploadService.cs
+++ b/src/slskd/Transfers/Uploads/UploadService.cs
@@ -96,6 +96,14 @@ namespace slskd.Transfers.Uploads
(int Files, long Bytes) Summarize(Expression<Func<Transfer, bool>> expression);
/// <summary>
+ /// Gets upload statistics for the specified <paramref name="username"/>.
+ /// </summary>
+ /// <param name="username">The username of the user.</param>
+ /// <param name="utcNow">An optional timestamp representing the current time in UTC.</param>
+ /// <returns>The gathered statistics.</returns>
+ UserUploadStatistics GetUserStatistics(string username, DateTime? utcNow = null);
+
+ /// <summary>
/// Returns a list of all uploads matching the optional <paramref name="expression"/>.
/// </summary>
/// <param name="expression">An optional expression used to match uploads.</param>
@@ -852,7 +860,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));
@@ -919,6 +927,54 @@ namespace slskd.Transfers.Uploads
context.SaveChanges();
}
+ /// <summary>
+ /// Gets upload statistics for the specified <paramref name="username"/>.
+ /// </summary>
+ /// <param name="username">The username of the user.</param>
+ /// <param name="utcNow">An optional timestamp representing the current time in UTC.</param>
+ /// <returns>The gathered statistics.</returns>
+ public UserUploadStatistics GetUserStatistics(string username, DateTime? utcNow = null)
+ {
+ utcNow ??= DateTime.UtcNow;
+ var dailyCutoff = utcNow.Value.AddDays(-1);
+ var weeklyCutoff = utcNow.Value.AddDays(-7);
+
+ 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)
+ .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,
+
+ // 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,
+
+ 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,
+ })
+ .FirstOrDefault();
+
+ return stats ?? new UserUploadStatistics();
+ }
+
private bool TryFail(Guid id, string exception, TransferStates state)
{
var t = Find(t => t.Id == id);