diff options
| author | JP Dillingham <jp@dillingham.me> | 2024-03-04 07:12:01 -0600 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2024-03-04 07:12:01 -0600 |
| commit | 3af712067a03640fd251f804ca532bd4cd5f7b10 (patch) | |
| tree | 5e0ce1932f9d959b17d49fbc0a32b27434f13419 | |
| parent | b39be34b05d6dd8e8d57e06512263d30634b9e1a (diff) | |
| parent | 264019f11042fbffd789560635bf8943d4de9aa2 (diff) | |
| download | slskd-3af712067a03640fd251f804ca532bd4cd5f7b10.tar.gz | |
Merge branch 'master' into chore/codestyle
| -rw-r--r-- | config/slskd.example.yml | 18 | ||||
| -rw-r--r-- | docs/config.md | 91 | ||||
| -rw-r--r-- | src/slskd/Application.cs | 82 | ||||
| -rw-r--r-- | src/slskd/Common/TokenBucket.cs | 2 | ||||
| -rw-r--r-- | src/slskd/Core/Options.cs | 110 | ||||
| -rw-r--r-- | src/slskd/Program.cs | 11 | ||||
| -rw-r--r-- | src/slskd/Shares/SqliteShareRepository.cs | 11 | ||||
| -rw-r--r-- | src/slskd/Transfers/Uploads/UploadGovernor.cs | 18 | ||||
| -rw-r--r-- | src/slskd/slskd.csproj | 16 |
9 files changed, 236 insertions, 123 deletions
diff --git a/config/slskd.example.yml b/config/slskd.example.yml index a1f19194..4e34098b 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -51,7 +51,19 @@ # global: # upload: # slots: 20 -# speed_limit: 1000 +# speed_limit: 1000 # in kibibytes +# limits: +# queued: +# files: 500 +# megabytes: 5000 +# daily: +# files: 1000 +# megabytes: 10000 +# failures: 200 +# weekly: +# files: 5000 +# megabytes: 50000 +# failures: 1000 # download: # slots: 500 # speed_limit: 1000 @@ -102,7 +114,9 @@ # priority: 250 # strategy: firstinfirstout # slots: 10 -# limits: ~ # no limits for buddies +# limits: +# queued: +# files: 1000 # override global default # members: # - alice # - bob diff --git a/docs/config.md b/docs/config.md index 15a4c817..924e4de9 100644 --- a/docs/config.md +++ b/docs/config.md @@ -274,30 +274,59 @@ relay: # Limits and User Groups -## Global +## Global Slot and Speed Limits -Global limits behave as a hard limit, additive across all groups. These values should be set as high as practical for the application's environment; more granular controls should be defined at the group level. +Global slot and speed behave as a hard limit, additive across all groups. These values should be set as high as practical for the application's environment; more granular controls should be defined at the group level. A change to slot limits requires an application restart to take effect, while speed limits can be adjusted at runtime. | Command-Line | Environment Variable | Description | | ------------------------ | ---------------------------- | ------------------------------------------------ | | `--upload-slots` | `SLSKD_UPLOAD_SLOTS` | The limit for the total number of upload slots | -| `--upload-speed-limit` | `SLSKD_UPLOAD_SPEED_LIMIT` | The total upload speed limit | +| `--upload-speed-limit` | `SLSKD_UPLOAD_SPEED_LIMIT` | The total upload speed limit, in kibibytes | | `--download-slots` | `SLSKD_DOWNLOAD_SLOTS` | The limit for the total number of download slots | -| `--download-speed-limit` | `SLSKD_DOWNLOAD_SPEED_LIMIT` | The total download speed limit | +| `--download-speed-limit` | `SLSKD_DOWNLOAD_SPEED_LIMIT` | The total download speed limit, in kibibytes | #### **YAML** ```yaml global: upload: slots: 20 - speed_limit: 1000 + speed_limit: 1000 # kibibytes download: slots: 500 speed_limit: 1000 ``` +## Global Upload Limits + +Global upload limits define the number of queued, daily, and weekly uploads on a _per user_ basis. These limits behave as defaults and are applied if limits for a user's group have not been set. + +Limits are evaluated when a user attempts to enqueue a file. Queued limits behave exactly as those in other clients; if a limit would be exceeded if the requested file were accepted the request is rejected with the standard messages `Too many files` or `Too many megabytes`, depending on which limit was hit. These messages are used by other clients to determine whether to retry the transfer later. + +If a daily or weekly limit would be exceeded, the request is rejected with a message like `Too many files this week` or `Too many failures today`, depending on which limit is hit. Transfers rejected with one of these messages should not be retried by other clients (at least, that's the goal!). + +The transfers database for the application is used to calculate the statistics used to make limit decisions. If this database is deleted, moved, cleared, or if the 'volatile' option is set (preventing the database from being persisted to disk), these limits won't work reliably. Because of the asynchronous nature of the application it's possible for limits to be exceeded if the requests are 'in flight' while data is being persisted, but the number of excess transfers should never be significant. + +Note that while it's possible to set the `failures` option for `queued`, it has no effect. + +#### **YAML** +```yaml +global: + limits: + queued: + files: 500 + megabytes: 5000 + daily: + files: 1000 + megabytes: 10000 + failures: 200 + weekly: + files: 5000 + megabytes: 50000 + failures: 1000 +``` + ## Groups User groups are used to control upload slots, speed limits, and queue behavior on a per-user basis. @@ -306,17 +335,31 @@ Each group has a priority, starting from 1, determining the order in which group Groups have a queue strategy, either `FirstInFirstOut` or `RoundRobin`. This setting determines how uploads from multiple users in the same group are processed; `FirstInFirstOut` processes uploads in the order in which they were enqueued, while `RoundRobin` processes uploads in the order in which the user was ready to receive the upload. -Upload slots and speed limits configured at the group level can be used to create constraints in addition to global settings. If group-level limits exceed global settings, global settings become the constraint. Slots and speed limit settings default to `int.MaxValue`, effectively deferring to the global limits. +[Upload slots and speed limits](#global-slot-and-speed-limits) configured at the group level can be used to create constraints in addition to global settings. If group-level limits exceed global settings, global settings become the constraint. Slots and speed limit settings default to `int.MaxValue`, effectively deferring to the global limits. + +[Upload limits](#global-upload-limits) can be configured at the group level to override the global defaults. If neither global defaults nor group limits are set, uploads are unlimited. If global defaults are set and unlimited uploads for a group are desired, set values to `int.MaxValue` or `2147483647`. While not technically unlimited, this number translates to over 2 petabytes, which would be an impressive amount of data to move peer to peer in a week. The general configuration for a group is as follows: #### **YAML** ```yaml upload: - priority: 500 # 1 to int.MaxValue + priority: 500 # 1 to 2147483647 strategy: roundrobin # roundrobin or firstinfirstout - slots: 10 # 1 to int.MaxValue - speed_limit: 100 # in KiB/s, 1 to int.MaxValue + slots: 10 # 1 to 2147483647 + speed_limit: 100 # in KiB/s, 1 to 2147483647 +limits: + queued: + files: 500 # 1 to 2147483647 + megabytes: 5000 # 1 to 2147483647 + daily: + files: 1000 + megabytes: 10000 + failures: 200 # 1 to 2147483647 + weekly: + files: 5000 + megabytes: 50000 + failures: 1000 ``` ## Built-In Groups @@ -325,7 +368,7 @@ The `default` built-in group contains all users who have not been explicitly add The `leechers` built-in group contains users that have not been explicitly added to a user-defined group, are not privileged, and have shared file and/or directory counts less than the configured `thresholds` for the group. By default, users must share at least one directory with one file to avoid being identified as leechers. -The `privileged` built-in is used to prioritize users who have purchased privileges on the Soulseek network. This groups is not configurable, has a priority of 0 (the highest), a strategy of `FirstInFirstOut`, and can use any number of slots up to the global limit. +The `privileged` built-in is used to prioritize users who have purchased privileges on the Soulseek network. This groups is not configurable, has a priority of 0 (the highest), a strategy of `FirstInFirstOut`, and can use any number of slots up to the global limit. Users in this group are also not subject to any limits; they can enqueue any number of files they wish. It is impossible to explicitly assign users to these built-in groups, but the priority, number of slots, speed, and queue strategy can be adjusted (excluding `privileged`). @@ -337,7 +380,18 @@ groups: priority: 1 strategy: roundrobin slots: 10 - speed_limit: 50000 + speed_limit: 50000 # kibibytes + limits: + queued: + files: 150 + megabytes: 1500 + daily: + files: 2147483647 # effectively unlimited, weekly still applies + megabytes: 2147483647 + weekly: + files: 1500 + megabytes: 15000 + failures: 150 leechers: thresholds: files: 1 @@ -347,6 +401,18 @@ groups: strategy: roundrobin slots: 1 speed_limit: 100 + limits: + queued: + files: 15 + megabytes: 150 + daily: + files: 30 + megabytes: 300 + failures: 10 + weekly: + files: 150 + megabytes: 1500 + failures: 30 ``` ## Blacklist @@ -391,6 +457,9 @@ groups: strategy: roundrobin slots: 10 speed_limit: 100 + limits: + queued: + files: 1000 # override global default members: - bob - alice diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index b105cb56..75b2eee6 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -181,6 +181,8 @@ namespace slskd Client.DownloadDenied += (e, args) => Log.Information("Download of {Filename} from {Username} was denied: {Message}", args.Filename, args.Username, args.Message); Client.DownloadFailed += (e, args) => Log.Information("Download of {Filename} from {Username} failed", args.Filename, args.Username); + Client.ExcludedSearchPhrasesReceived += Client_ExcludedSearchPhrasesReceived; + ConnectionWatchdog = connectionWatchdog; Clock.EveryMinute += Clock_EveryMinute; @@ -221,6 +223,7 @@ namespace slskd private IEnumerable<Regex> CompiledSearchResponseFilters { get; set; } private IEnumerable<Guid> ActiveDownloadIdsAtPreviousShutdown { get; set; } = Enumerable.Empty<Guid>(); private Options.FlagsOptions Flags { get; set; } + private IReadOnlyCollection<string> ExcludedSearchPhrases { get; set; } = Enumerable.Empty<string>().ToList(); public void CollectGarbage() { @@ -511,9 +514,11 @@ namespace slskd return; } - // resolve the limits for this user's group. there's no 'fallthrough' here, if limits for a group - // are unset, then that group is unlimited. - Options.GroupsOptions.LimitsOptions limits; + // we'll fall back to global limits for any limit that isn't set at the group level + var global = Options.Global.Limits; + + // resolve the limits for this user's group. + Options.LimitsOptions limits; if (Options.Groups.UserDefined.TryGetValue(group, out var userDefinedOptions)) { @@ -525,22 +530,12 @@ namespace slskd { DefaultGroup => Options.Groups.Default.Limits, LeecherGroup => Options.Groups.Leechers.Limits, - _ => Options.Groups.Default.Limits, + _ => Options.Groups.Default.Limits, // that's weird! we'll just go with defaults.. }; } - bool IsNull(Options.GroupsOptions.LimitsExtendedOptions l) => l is null || (l?.Files is null && l?.Megabytes is null); - - // if no limits are set, we're good to go; just enqueue the file. - if (limits is null || (IsNull(limits.Daily) && IsNull(limits.Weekly) && IsNull(limits.Queued))) - { - Log.Debug("Limits bypassed for {Username} and {File}; no limits are set", username, filename); - await Transfers.Uploads.EnqueueAsync(username, filename); - return; - } - - var sw = new Stopwatch(); - sw.Start(); + bool IsNull(Options.LimitsOptions.Limits lim, Options.LimitsOptions.Limits global) + => (lim is null && global is null) || ((lim?.Files ?? global?.Files ?? lim?.Megabytes ?? global?.Megabytes ?? lim.Failures ?? global.Failures) is null); /* * we have limits set, so now we have to fetch the data and compare to see if any would be hit if we allow this transfer to be enqueued. @@ -549,38 +544,47 @@ namespace slskd * 2) that were started within the time period * 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, Options.GroupsOptions.LimitsExtendedOptions options, long size) + (bool Files, bool Megabytes) OverLimits( + (int Files, long Bytes) stats, + Options.LimitsOptions.Limits options, + Options.LimitsOptions.Limits defaults, + long size) { var files = false; var megabytes = false; - var byteLimit = (options?.Megabytes ?? 0) * 1000 * 1000; + var byteLimit = options?.Megabytes ?? defaults?.Megabytes; - if (options?.Megabytes is not null && (stats.Bytes + size) > byteLimit) + if (byteLimit is not null && (stats.Bytes + size) > (byteLimit * 1000 * 1000)) { - Log.Debug("Projected bytes {Bytes} exceeds limit {Limit}", stats.Bytes + size, byteLimit); + Log.Debug("Projected bytes {Bytes} exceeds limit {Limit}", stats.Bytes + size, byteLimit * 1000 * 1000); megabytes = true; } - if (options?.Files is not null && (stats.Files + 1) > options.Files) + var fileLimit = options?.Files ?? defaults?.Files; + + if (fileLimit is not null && (stats.Files + 1) > fileLimit) { - Log.Debug("Projected file count {Files} exceeds limit {Limit}", stats.Files + 1, options.Files); + Log.Debug("Projected file count {Files} exceeds limit {Limit}", stats.Files + 1, fileLimit); files = true; } return (files, megabytes); } + var sw = new Stopwatch(); + sw.Start(); + // 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)) + 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, sw.ElapsedMilliseconds); - var over = OverLimits(queued, limits!.Queued, resolved.Size); + var over = OverLimits(queued, limits?.Queued, global?.Queued, resolved.Size); if (over.Files || over.Megabytes) { @@ -588,7 +592,7 @@ namespace slskd // note: return exactly 'Too many files' or 'Too many megabytes' to ensure interop with other clients. // these messages are retryable, while anything else is not - throw new DownloadEnqueueException($"Too many {(over.Files ? "files" : "megabytes")}"); + throw new DownloadEnqueueException($"Too many {(over.Megabytes ? "megabytes" : "files")}"); } } @@ -597,7 +601,7 @@ namespace slskd // * started within the last week // * which have or have not ended (assuming queued files will complete) // * that were not errored - if (!IsNull(limits.Weekly)) + if (!IsNull(limits?.Weekly, global?.Weekly)) { var erroredState = TransferStates.Completed | TransferStates.Errored; var cutoffDateTime = DateTime.UtcNow.AddDays(-7); @@ -610,7 +614,9 @@ namespace slskd Log.Debug("Fetched weekly failures: {Failures} ({Time}ms)", failures.Files, sw.ElapsedMilliseconds); - if (failures.Files >= limits.Weekly.Failures) + var failureLimit = limits?.Weekly?.Failures ?? global?.Weekly?.Failures; + + if (failureLimit is not null && failures.Files >= 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"); @@ -625,7 +631,7 @@ namespace slskd Log.Debug("Fetched weekly stats: files: {Files}, bytes: {Bytes} ({Time}ms)", weekly.Files, weekly.Bytes, sw.ElapsedMilliseconds); - var over = OverLimits(weekly, limits!.Weekly, resolved.Size); + var over = OverLimits(weekly, limits?.Weekly, global?.Weekly, resolved.Size); if (over.Files || over.Megabytes) { @@ -636,7 +642,7 @@ namespace slskd // lastly, check daily limits. the criteria for this is the same as weekly, just looking over the previous day instead // of the previous 7. - if (!IsNull(limits.Daily)) + if (!IsNull(limits?.Daily, global?.Daily)) { var erroredState = TransferStates.Completed | TransferStates.Errored; var cutoffDateTime = DateTime.UtcNow.AddDays(-1); @@ -649,7 +655,9 @@ namespace slskd Log.Debug("Fetched daily failures: {Failures} ({Time}ms)", failures.Files, sw.ElapsedMilliseconds); - if (failures.Files >= limits.Daily.Failures) + var failureLimit = limits?.Daily?.Failures ?? global?.Daily?.Failures; + + if (failureLimit is not null && failures.Files >= failureLimit) { Log.Information("Rejected enqueue request for user {Username}: Daily failure limit met or exceeded", username); throw new DownloadEnqueueException("Too many failed transfers today"); @@ -664,7 +672,7 @@ namespace slskd Log.Debug("Fetched daily stats: files: {Files}, bytes: {Bytes} ({Time}ms)", daily.Files, daily.Bytes, sw.ElapsedMilliseconds); - var over = OverLimits(daily, limits!.Daily, resolved.Size); + var over = OverLimits(daily, limits?.Daily, global?.Daily, resolved.Size); if (over.Files || over.Megabytes) { @@ -1088,6 +1096,12 @@ namespace slskd } } + private void Client_ExcludedSearchPhrasesReceived(object sender, IReadOnlyCollection<string> e) + { + Log.Debug("Excluded search phrases: {Phrases}", string.Join(", ", e)); + ExcludedSearchPhrases = e; + } + private void Client_TransferProgressUpdated(object sender, TransferProgressUpdatedEventArgs args) { // no-op. this is really verbose, use for troubleshooting. @@ -1361,11 +1375,15 @@ namespace slskd // sometimes clients send search queries consisting only of exclusions; drop them. // no other clients send search results for these, even though it is technically possible. - if (!query.Terms.Any()) + if (query.Terms.Count == 0) { return null; } + // append the list of excluded search phrases supplied by the server + // see https://github.com/jpdillingham/Soulseek.NET/issues/803 + query = new SearchQuery(terms: query.Terms, exclusions: query.Exclusions.Concat(ExcludedSearchPhrases).Distinct()); + try { var sw = new Stopwatch(); diff --git a/src/slskd/Common/TokenBucket.cs b/src/slskd/Common/TokenBucket.cs index bce2e913..edd6ca7f 100644 --- a/src/slskd/Common/TokenBucket.cs +++ b/src/slskd/Common/TokenBucket.cs @@ -83,7 +83,7 @@ namespace slskd /// Initializes a new instance of the <see cref="TokenBucket"/> class. /// </summary> /// <param name="capacity">The bucket capacity.</param> - /// <param name="interval">The interval at which tokens are replenished.</param> + /// <param name="interval">The interval at which tokens are replenished, in milliseconds.</param> public TokenBucket(long capacity, int interval) { if (capacity < 1) diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 68f3c3dc..cfe78eb1 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -787,6 +787,12 @@ namespace slskd public GlobalUploadOptions Upload { get; init; } = new GlobalUploadOptions(); /// <summary> + /// Gets global limits. + /// </summary> + [Validate] + public LimitsOptions Limits { get; init; } = new LimitsOptions(); + + /// <summary> /// Gets global download options. /// </summary> [Validate] @@ -808,7 +814,7 @@ namespace slskd public int Slots { get; init; } = 10; /// <summary> - /// Gets the total upload speed limit. + /// Gets the total upload speed limit, in kibibytes. /// </summary> [Argument(default, "upload-speed-limit")] [EnvironmentVariable("UPLOAD_SPEED_LIMIT")] @@ -833,7 +839,7 @@ namespace slskd public int Slots { get; init; } = int.MaxValue; /// <summary> - /// Gets the total download speed limit. + /// Gets the total download speed limit, in kibibytes. /// </summary> [Argument(default, "download-speed-limit")] [EnvironmentVariable("DOWNLOAD_SPEED_LIMIT")] @@ -844,6 +850,54 @@ namespace slskd } /// <summary> + /// Limit options. + /// </summary> + public class LimitsOptions + { + /// <summary> + /// Gets limits for queued transfers. + /// </summary> + [Validate] + public Limits Queued { get; init; } = new Limits(); + + /// <summary> + /// Gets daily limits for transfers. + /// </summary> + [Validate] + public Limits Daily { get; init; } = new Limits(); + + /// <summary> + /// Gets weekly limits for transfers. + /// </summary> + [Validate] + public Limits Weekly { get; init; } = new Limits(); + + /// <summary> + /// Limits. + /// </summary> + public class Limits + { + /// <summary> + /// Gets the limit for number of files. + /// </summary> + [Range(1, int.MaxValue)] + public int? Files { get; init; } = null; + + /// <summary> + /// Gets the limit for number of megabytes. + /// </summary> + [Range(1, int.MaxValue)] + public int? Megabytes { get; init; } = null; + + /// <summary> + /// Gets the limit for number of failures. + /// </summary> + [Range(1, int.MaxValue)] + public int? Failures { get; init; } = null; + } + } + + /// <summary> /// User groups. /// </summary> public class GroupsOptions : IValidatableObject @@ -1022,59 +1076,11 @@ namespace slskd public int Slots { get; init; } = int.MaxValue; /// <summary> - /// Gets the total upload speed limit for the group. + /// Gets the total upload speed limit for the group, in kibibytes. /// </summary> [Range(1, int.MaxValue)] public int SpeedLimit { get; init; } = int.MaxValue; } - - /// <summary> - /// Upload limit options. - /// </summary> - public class LimitsOptions - { - /// <summary> - /// Gets limits for queued transfers. - /// </summary> - [Validate] - public LimitsExtendedOptions Queued { get; init; } = new LimitsExtendedOptions(); - - /// <summary> - /// Gets daily limits for transfers. - /// </summary> - [Validate] - public LimitsExtendedOptions Daily { get; init; } = new LimitsExtendedOptions(); - - /// <summary> - /// Gets weekly limits for transfers. - /// </summary> - [Validate] - public LimitsExtendedOptions Weekly { get; init; } = new LimitsExtendedOptions(); - } - - /// <summary> - /// Extended limit options. - /// </summary> - public class LimitsExtendedOptions - { - /// <summary> - /// Gets the limit for number of files. - /// </summary> - [Range(1, int.MaxValue)] - public int? Files { get; init; } = null; - - /// <summary> - /// Gets the limit for number of megabytes. - /// </summary> - [Range(1, int.MaxValue)] - public int? Megabytes { get; init; } = null; - - /// <summary> - /// Gets the limit for number of failures. - /// </summary> - [Range(1, int.MaxValue)] - public int? Failures { get; init; } = null; - } } /// <summary> @@ -1719,7 +1725,7 @@ namespace slskd [Argument(default, "jwt-key")] [EnvironmentVariable("JWT_KEY")] [Description("JWT signing key")] - [StringLength(255, MinimumLength = 16)] + [StringLength(255, MinimumLength = 32)] [Secret] [RequiresRestart] public string Key { get; init; } = Cryptography.Random.GetBytes(32).ToBase62(); diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index ad50dccd..d7f6caca 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -634,16 +634,7 @@ namespace slskd services.AddDataProtection() .PersistKeysToFileSystem(new DirectoryInfo(Path.Combine(DataDirectory, "misc", ".DataProtection-Keys"))); - var adjustedJwtKey = OptionsAtStartup.Web.Authentication.Jwt.Key; - - // the JWT key must be at least 256 bits in length, due to the HMACSHA256 algorithm being used for signing. - if (adjustedJwtKey.Length < 32) - { - adjustedJwtKey = adjustedJwtKey.PadRight(32, ' '); - Log.Warning("The configured JWT signing key is less than the required 32 characters and has been padded with spaces to make up the difference. The minimum length will be raised from 16 to 32 in a future release, and this will become an error."); - } - - var jwtSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(adjustedJwtKey)); + var jwtSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(OptionsAtStartup.Web.Authentication.Jwt.Key)); services.AddSingleton(jwtSigningKey); services.AddSingleton<ISecurityService, SecurityService>(); diff --git a/src/slskd/Shares/SqliteShareRepository.cs b/src/slskd/Shares/SqliteShareRepository.cs index 882ede74..029d74b8 100644 --- a/src/slskd/Shares/SqliteShareRepository.cs +++ b/src/slskd/Shares/SqliteShareRepository.cs @@ -539,6 +539,17 @@ namespace slskd.Shares while (reader.Read()) { var filename = reader.GetString(0); + + // SQLite takes care of matching on tokens, but unfortunately doesn't work in cases where an exclusion appears as a substring. + // example: the token matching works to exclude the result "foo bar baz" given a "bar" exclusion, but does not exclude "foo xbarx baz" + // for this reason we must iterate over the exclusion list and ensure none appear as substrings + // **CAUTION** performance of this will degrade exponentially as the list of exclusions grows + if (query.Exclusions.Any(x => filename.Contains(x, StringComparison.OrdinalIgnoreCase))) + { + Log.Debug("Dropping excluded filename {File}", filename); + continue; + } + var code = reader.GetInt32(1); var size = reader.GetInt64(2); var extension = reader.GetString(3); diff --git a/src/slskd/Transfers/Uploads/UploadGovernor.cs b/src/slskd/Transfers/Uploads/UploadGovernor.cs index 0f481e69..11fc4dcf 100644 --- a/src/slskd/Transfers/Uploads/UploadGovernor.cs +++ b/src/slskd/Transfers/Uploads/UploadGovernor.cs @@ -129,11 +129,15 @@ namespace slskd.Transfers private void Configure(Options options) { - static long ComputeBucketCapacity(int speed) - => speed * 1024L / 10; + static TokenBucket CreateBucket(int speedInKiB) + { + var speedInBytes = speedInKiB * 1024L; + var intervalInMs = 100; + var bucketRefreshesPerSecond = 1000 / intervalInMs; + var capacity = speedInBytes / bucketRefreshesPerSecond; - static TokenBucket CreateBucket(int speed) - => new(ComputeBucketCapacity(speed), 100); + return new(capacity, interval: intervalInMs); + } var optionsHash = Compute.Sha1Hash(options.Groups.ToJson()); @@ -149,9 +153,9 @@ namespace slskd.Transfers // also, so transfers in progress will briefly exceed the intended speeds. var tokenBuckets = new Dictionary<string, ITokenBucket>() { - { Application.PrivilegedGroup, CreateBucket(options.Global.Upload.SpeedLimit) }, - { Application.DefaultGroup, CreateBucket(options.Groups.Default.Upload.SpeedLimit) }, - { Application.LeecherGroup, CreateBucket(options.Groups.Leechers.Upload.SpeedLimit) }, + { Application.PrivilegedGroup, CreateBucket(speedInKiB: options.Global.Upload.SpeedLimit) }, + { Application.DefaultGroup, CreateBucket(speedInKiB: options.Groups.Default.Upload.SpeedLimit) }, + { Application.LeecherGroup, CreateBucket(speedInKiB: options.Groups.Leechers.Upload.SpeedLimit) }, }; foreach (var group in options.Groups.UserDefined) diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj index e32be5d6..2283804f 100644 --- a/src/slskd/slskd.csproj +++ b/src/slskd/slskd.csproj @@ -43,17 +43,17 @@ <ItemGroup> <PackageReference Include="Asp.Versioning.Mvc.ApiExplorer" Version="8.0.0" /> - <PackageReference Include="FluentFTP" Version="49.0.1" /> + <PackageReference Include="FluentFTP" Version="49.0.2" /> <PackageReference Include="IPAddressRange" Version="6.0.0" /> - <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.1" /> - <PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="8.0.1" /> + <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.2" /> + <PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="8.0.2" /> <PackageReference Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="8.0.0"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> </PackageReference> - <PackageReference Include="Microsoft.Data.Sqlite" Version="8.0.1" /> - <PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.1" /> - <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite.Core" Version="8.0.1" /> + <PackageReference Include="Microsoft.Data.Sqlite" Version="8.0.2" /> + <PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.2" /> + <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite.Core" Version="8.0.2" /> <PackageReference Include="OneOf" Version="3.0.263" /> <PackageReference Include="prometheus-net" Version="8.2.1" /> <PackageReference Include="prometheus-net.AspNetCore" Version="8.2.1" /> @@ -67,7 +67,7 @@ <PackageReference Include="Serilog.Sinks.File" Version="5.0.0" /> <PackageReference Include="Serilog.Sinks.Grafana.Loki" Version="7.1.1" /> <PackageReference Include="Serilog.Sinks.Http" Version="8.0.0" /> - <PackageReference Include="Soulseek" Version="6.3.0" /> + <PackageReference Include="Soulseek" Version="6.4.1" /> <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.435"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> @@ -76,6 +76,6 @@ <PackageReference Include="TagLibSharp" Version="2.3.0" /> <PackageReference Include="Utility.CommandLine.Arguments" Version="6.0.0" /> <PackageReference Include="Utility.EnvironmentVariables" Version="1.0.5" /> - <PackageReference Include="YamlDotNet" Version="13.7.1" /> + <PackageReference Include="YamlDotNet" Version="15.1.1" /> </ItemGroup> </Project> |
