From 8e54514ba244f7acd3ad0a74dd9690421aff91b9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 Oct 2026 14:38:17 -0500 Subject: fix bug that could throw if list changes during SelectMany --- src/slskd/Transfers/Uploads/UploadQueue.cs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index 2dca0d9e..7491034a 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -413,9 +413,7 @@ namespace slskd.Transfers.Uploads // for FIFO queues, the user will enter the queue at the very back. return the total number of uploads in progress and // enqueued, + 1. - return uploadsForGroup - .SelectMany(group => group.Value) - .Count() + 1; + return uploadsForGroup.Sum(kvp => kvp.Value.Count) + 1; } private void Configure(Options options) -- cgit v1.2.3 From 9d77c403e002e46679c66586067fd040b56b420d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 Oct 2026 14:40:26 -0500 Subject: accept cancellationtoken in AwaitStartAsync --- src/slskd/Transfers/Uploads/UploadQueue.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index 7491034a..d0f2815f 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -54,8 +54,9 @@ namespace slskd.Transfers.Uploads /// /// The username of the remote user. /// The filename for which to await the start. + /// The token to monitor for cancellation requests. /// The operation context. - Task AwaitStartAsync(string username, string filename); + Task AwaitStartAsync(string username, string filename, CancellationToken cancellationToken = default); /// /// Signals the completion of an upload. @@ -150,8 +151,9 @@ namespace slskd.Transfers.Uploads /// /// The username of the remote user. /// The filename for which to await the start. + /// The token to monitor for cancellation requests. /// The operation context. - public Task AwaitStartAsync(string username, string filename) + public Task AwaitStartAsync(string username, string filename, CancellationToken cancellationToken = default) { SyncRoot.Wait(); -- cgit v1.2.3 From 767221c5ba23d49778b5aba478ade61b264dbe31 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 Oct 2026 14:40:41 -0500 Subject: pass cancellation token to AwaitStartAsync --- src/slskd/Transfers/Uploads/UploadService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 5f98afac..7bc889ba 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -430,7 +430,7 @@ namespace slskd.Transfers.Uploads disposeInputStreamOnCompletion: true, // note: don't set this to false! governor: (tx, req, ct) => Governor.GetBytesAsync(tx.Username, req, ct), reporter: (tx, att, grant, act) => Governor.ReturnBytes(tx.Username, att, grant, act), - slotAwaiter: (tx, ct) => Queue.AwaitStartAsync(tx.Username, tx.Filename), + slotAwaiter: (tx, ct) => Queue.AwaitStartAsync(tx.Username, tx.Filename, ct), slotReleased: (tx) => Queue.Complete(tx.Username, tx.Filename)); // register the cancellation token -- cgit v1.2.3 From 4e40b1935624a1ff4d436544cc44cdf64aefbaf9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 Oct 2026 16:16:34 -0500 Subject: add remark about position estimation --- src/slskd/Transfers/Uploads/UploadQueue.cs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index d0f2815f..fa3bb68c 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -306,6 +306,11 @@ namespace slskd.Transfers.Uploads /// /// Computes the estimated queue position of the specified for the specified . /// + /// + /// The returned position is relative to the user's group only. Higher priority groups are not factored in + /// because of the amount of data that would need to be processed to compute a number, and how variable it + /// would be due to the interplay of slot availability, number of higher priority users waiting, etc. + /// /// The username associated with the file. /// The filename of the file for which the position is to be estimated. /// The estimated queue position of the file. -- cgit v1.2.3 From efc33e19a7e33c38d59f7d3d26a0b93318af9a26 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 Oct 2026 19:34:01 -0500 Subject: synchronize EstimatePosition, reduce memory pressure --- src/slskd/Transfers/Uploads/UploadQueue.cs | 108 ++++++++++++++++------------- 1 file changed, 59 insertions(+), 49 deletions(-) diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index fa3bb68c..441bc368 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -91,6 +91,11 @@ namespace slskd.Transfers.Uploads /// /// Computes the estimated queue position of the specified for the specified . /// + /// + /// The returned position is relative to the user's group only. Higher priority groups are not factored in + /// because of the amount of data that would need to be processed to compute a number, and how variable it + /// would be due to the interplay of slot availability, number of higher priority users waiting, etc. + /// /// The username associated with the file. /// The filename of the file for which the position is to be estimated. /// The estimated queue position of the file. @@ -323,11 +328,9 @@ namespace slskd.Transfers.Uploads // the Uploads dictionary is keyed by username; gather all of the users that belong to the same group as the requested user var uploadsForGroup = UploadDictionary.Where(kvp => Users.GetGroup(kvp.Key) == groupName); - // the RoundRobin queue implementation is not strictly fair to all users; only uploads that are ready are candidates - // for selection. this means that if Bob downloads files twice as fast as Alice, Bob is going to advance through the - // queue twice as fast, too. assume everyone downloads at equal speed for this estimate. also assume that all files - // are of equal length. - if (groupRecord.Strategy == QueueStrategy.RoundRobin) + SyncRoot.Wait(); + + try { // find this user's uploads if (!UploadDictionary.TryGetValue(username, out var uploadsForUser)) @@ -335,59 +338,66 @@ namespace slskd.Transfers.Uploads throw new NotFoundException($"File {filename} is not enqueued for user {username}"); } - // find the position of the requested file in the user's queue - var localPosition = uploadsForUser - .OrderBy(upload => upload.Enqueued) - .ToList() - .FindIndex(upload => upload.Username == username && upload.Filename == filename); - - if (localPosition < 0) + // the RoundRobin queue implementation is not strictly fair to all users; only uploads that are ready are candidates + // for selection. this means that if Bob downloads files twice as fast as Alice, Bob is going to advance through the + // queue twice as fast, too. assume everyone downloads at equal speed for this estimate. also assume that all files + // are of equal length. + if (groupRecord.Strategy == QueueStrategy.RoundRobin) { - throw new NotFoundException($"File {filename} is not enqueued for user {username}"); - } + // find the position of the requested file in the user's queue + // note: backed by List, which is stable and already ordered by enqueue time ASC + var localPosition = uploadsForUser + .FindIndex(u => u.Username == username && u.Filename == filename); - // start the position to the local position within this user's queue; the user's own files must be completed - // before this one can start. - var position = localPosition; - - // for each other user, add either localPosition or the count of that user's uploads, whichever is less - // example: - // - // aaaaa - // bb - // cccccccccccc - // ddddddd - // ^ - // - // if we want the position of the file over the carat above, first find the position of it - // within its own queue (= 5). assume uploads will process top down, left to right until reaching - // this one. that's 5 files from a, 2 from b, 5 from c, and the other 4 from d, putting the file over - // the carat at position 16. the actual number will vary due to many factors, including where in the - // round-robin ordering d is actually positioned (so +/- number of users downloading). - foreach (var group in uploadsForGroup.Where(group => group.Key != username)) - { - position += Math.Min(localPosition, group.Value.Count); + if (localPosition < 0) + { + throw new NotFoundException($"File {filename} is not enqueued for user {username}"); + } + + // start the position to the local position within this user's queue; the user's own files must be completed + // before this one can start. + var position = localPosition; + + // for each other user, add either localPosition or the count of that user's uploads, whichever is less + // example: + // + // aaaaa + // bb + // cccccccccccc + // ddddddd + // ^ + // + // if we want the position of the file over the carat above, first find the position of it + // within its own queue (= 5). assume uploads will process top down, left to right until reaching + // this one. that's 5 files from a, 2 from b, 5 from c, and the other 4 from d, putting the file over + // the carat at position 16. the actual number will vary due to many factors, including where in the + // round-robin ordering d is actually positioned (so +/- number of users downloading). + foreach (var group in uploadsForGroup.Where(group => group.Key != username)) + { + position += Math.Min(localPosition, group.Value.Count); + } + + return position; } - return position; - } + // find the upload + var upload = uploadsForUser.SingleOrDefault(u => u.Username == username && u.Filename == filename); - // for FIFO queues, files are uploaded in the order they are enqueued, so the position should be pretty good estimate. - // List ordering is guaranteed, so we are getting an accurate portrayal of where this file is in the queue by order of - // time enqueued. this includes uploads that are in progress. - var flattenedSortedUploadsForGroup = uploadsForGroup - .SelectMany(group => group.Value) - .OrderBy(upload => upload.Enqueued) - .ToList(); + if (upload is null) + { + throw new NotFoundException($"File {filename} is not enqueued for user {username}"); + } - var globalPosition = flattenedSortedUploadsForGroup.FindIndex(upload => upload.Username == username && upload.Filename == filename); + // the place in queue is simply the sum of all uploads across all other users in the group that were + // enqueued before this upload. + var globalPosition = uploadsForGroup.Sum(kvp => kvp.Value.Count(c => c.Enqueued < upload.Enqueued)); - if (globalPosition < 0) + return globalPosition; + } + finally { - throw new NotFoundException($"File {filename} is not enqueued for user {username}"); + SyncRoot.Release(); } - - return globalPosition; } /// -- cgit v1.2.3 From 02ece515553cf2c669ff8e8e7f9a5b70d954d078 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 Oct 2026 19:34:42 -0500 Subject: add tests for EstimatePosition --- .../Transfers/Uploads/UploadQueueTests.cs | 210 +++++++++++++++++++++ 1 file changed, 210 insertions(+) diff --git a/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs b/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs index b1da3a77..f878f95d 100644 --- a/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs @@ -562,6 +562,216 @@ namespace slskd.Tests.Unit.Transfers.Uploads Assert.Equal(task, uploads[username][0].TaskCompletionSource.Task); } + public class EstimatePosition + { + private static readonly DateTime Now = DateTime.UtcNow; + + [Theory] + [InlineAutoData(QueueStrategy.RoundRobin)] + [InlineAutoData(QueueStrategy.FirstInFirstOut)] + public void Throws_NotFoundException_If_User_Has_No_Uploads(QueueStrategy strategy, string username, string filename) + { + var (queue, _) = GetFixture(); + + SetStrategy(queue, strategy); + + var ex = Record.Exception(() => queue.EstimatePosition(username, filename)); + + Assert.IsType(ex); + } + + [Theory] + [InlineAutoData(QueueStrategy.RoundRobin)] + [InlineAutoData(QueueStrategy.FirstInFirstOut)] + public void Throws_NotFoundException_If_File_Is_Not_Enqueued(QueueStrategy strategy, string username, string filename, string otherFilename) + { + var (queue, _) = GetFixture(); + + SetStrategy(queue, strategy); + + var uploads = new ConcurrentDictionary>(); + + uploads.TryAdd(username, new List() + { + new Upload() { Username = username, Filename = otherFilename, Enqueued = Now }, + }); + + queue.SetProperty("UploadDictionary", uploads); + + var ex = Record.Exception(() => queue.EstimatePosition(username, filename)); + + Assert.IsType(ex); + } + + [Theory, AutoData] + public void RoundRobin_Returns_Local_Position_If_User_Is_Alone_In_Group(string username) + { + var (queue, _) = GetFixture(); + + SetStrategy(queue, QueueStrategy.RoundRobin); + + var uploads = new ConcurrentDictionary>(); + uploads.TryAdd(username, CreateUploads(username, count: 3)); + + queue.SetProperty("UploadDictionary", uploads); + + Assert.Equal(0, queue.EstimatePosition(username, "file0")); + Assert.Equal(1, queue.EstimatePosition(username, "file1")); + Assert.Equal(2, queue.EstimatePosition(username, "file2")); + } + + [Theory, AutoData] + public void RoundRobin_Returns_Zero_For_First_File_Regardless_Of_Other_Users(string username, string other) + { + var (queue, _) = GetFixture(); + + SetStrategy(queue, QueueStrategy.RoundRobin); + + var uploads = new ConcurrentDictionary>(); + uploads.TryAdd(other, CreateUploads(other, count: 10, offset: -100)); + uploads.TryAdd(username, CreateUploads(username, count: 3)); + + queue.SetProperty("UploadDictionary", uploads); + + Assert.Equal(0, queue.EstimatePosition(username, "file0")); + } + + [Theory, AutoData] + public void RoundRobin_Adds_Lesser_Of_Local_Position_And_Upload_Count_For_Each_Other_User(string a, string b, string c, string d) + { + var (queue, _) = GetFixture(); + + SetStrategy(queue, QueueStrategy.RoundRobin); + + // aaaaa + // bb + // cccccccccccc + // ddddddd + // ^ (local position 4) + var uploads = new ConcurrentDictionary>(); + uploads.TryAdd(a, CreateUploads(a, count: 5)); + uploads.TryAdd(b, CreateUploads(b, count: 2)); + uploads.TryAdd(c, CreateUploads(c, count: 12)); + uploads.TryAdd(d, CreateUploads(d, count: 7)); + + queue.SetProperty("UploadDictionary", uploads); + + // 4 (local) + min(4, 5) + min(4, 2) + min(4, 12) + Assert.Equal(4 + 4 + 2 + 4, queue.EstimatePosition(d, "file4")); + } + + [Theory, AutoData] + public void RoundRobin_Ignores_Users_In_Other_Groups(string username, string other) + { + var (queue, mocks) = GetFixture(); + + SetStrategy(queue, QueueStrategy.RoundRobin); + + mocks.UserService.Setup(m => m.GetGroup(other)).Returns(Application.PrivilegedGroup); + + var uploads = new ConcurrentDictionary>(); + uploads.TryAdd(other, CreateUploads(other, count: 10)); + uploads.TryAdd(username, CreateUploads(username, count: 3)); + + queue.SetProperty("UploadDictionary", uploads); + + Assert.Equal(2, queue.EstimatePosition(username, "file2")); + } + + [Theory, AutoData] + public void FirstInFirstOut_Returns_Zero_If_Upload_Is_Earliest_In_Group(string username, string other) + { + var (queue, _) = GetFixture(); + + SetStrategy(queue, QueueStrategy.FirstInFirstOut); + + var uploads = new ConcurrentDictionary>(); + uploads.TryAdd(username, CreateUploads(username, count: 1)); + uploads.TryAdd(other, CreateUploads(other, count: 5, offset: 10)); + + queue.SetProperty("UploadDictionary", uploads); + + Assert.Equal(0, queue.EstimatePosition(username, "file0")); + } + + [Theory, AutoData] + public void FirstInFirstOut_Counts_All_Uploads_In_Group_Enqueued_Earlier(string a, string b, string c) + { + var (queue, _) = GetFixture(); + + SetStrategy(queue, QueueStrategy.FirstInFirstOut); + + // enqueued at: + // a: 0, 3, 6 + // b: 1, 4, 7 + // c: 2, 5, 8 + var uploads = new ConcurrentDictionary>(); + uploads.TryAdd(a, CreateUploads(a, count: 3, offset: 0, step: 3)); + uploads.TryAdd(b, CreateUploads(b, count: 3, offset: 1, step: 3)); + uploads.TryAdd(c, CreateUploads(c, count: 3, offset: 2, step: 3)); + + queue.SetProperty("UploadDictionary", uploads); + + Assert.Equal(0, queue.EstimatePosition(a, "file0")); + Assert.Equal(4, queue.EstimatePosition(b, "file1")); + Assert.Equal(8, queue.EstimatePosition(c, "file2")); + } + + [Theory, AutoData] + public void FirstInFirstOut_Counts_Uploads_In_Progress(string username, string other) + { + var (queue, _) = GetFixture(); + + SetStrategy(queue, QueueStrategy.FirstInFirstOut); + + var started = CreateUploads(other, count: 2); + started.ForEach(u => u.Started = Now); + + var uploads = new ConcurrentDictionary>(); + uploads.TryAdd(other, started); + uploads.TryAdd(username, CreateUploads(username, count: 1, offset: 10)); + + queue.SetProperty("UploadDictionary", uploads); + + Assert.Equal(2, queue.EstimatePosition(username, "file0")); + } + + [Theory, AutoData] + public void FirstInFirstOut_Ignores_Users_In_Other_Groups(string username, string other) + { + var (queue, mocks) = GetFixture(); + + SetStrategy(queue, QueueStrategy.FirstInFirstOut); + + mocks.UserService.Setup(m => m.GetGroup(other)).Returns(Application.PrivilegedGroup); + + var uploads = new ConcurrentDictionary>(); + uploads.TryAdd(other, CreateUploads(other, count: 10, offset: -100)); + uploads.TryAdd(username, CreateUploads(username, count: 3)); + + queue.SetProperty("UploadDictionary", uploads); + + Assert.Equal(2, queue.EstimatePosition(username, "file2")); + } + + private static void SetStrategy(UploadQueue queue, QueueStrategy strategy) + { + var groups = queue.GetProperty>("Groups"); + groups[Application.DefaultGroup].Strategy = strategy; + } + + // creates uploads named file0..fileN, enqueued at Now + offset + (i * step) seconds, in ascending order + private static List CreateUploads(string username, int count, int offset = 0, int step = 1) + { + return Enumerable.Range(0, count) + .Select(i => new Upload() + { + Username = username, + Filename = $"file{i}", + Enqueued = Now.AddSeconds(offset + (i * step)), + }) + .ToList(); + } } public class Process -- cgit v1.2.3 From 3b76fbbf168d2ec9798f36ac8be6beda8675e022 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 Oct 2026 19:35:27 -0500 Subject: make it more clear that uploads are initialized with Enqueued set --- src/slskd/Transfers/Uploads/UploadQueue.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index 441bc368..2494f5c1 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -272,11 +272,11 @@ namespace slskd.Transfers.Uploads try { - var upload = new Upload() { Username = username, Filename = filename }; + var upload = new Upload() { Username = username, Filename = filename, Enqueued = DateTime.UtcNow }; UploadDictionary.AddOrUpdate( key: username, - addValue: new List(new[] { upload }), + addValue: [upload], updateValueFactory: (key, list) => { list.Add(upload); -- cgit v1.2.3 From 54b0de8d76d383dcd32cb0a485e6222fb50b783f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 Oct 2026 21:48:59 -0500 Subject: throw if we can't find a users group --- src/slskd/Transfers/Uploads/UploadQueue.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index 2494f5c1..1cefe74f 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -419,8 +419,14 @@ namespace slskd.Transfers.Uploads } // the Uploads dictionary is keyed by username; gather all of the users that belong to the same group as the requested user + // a user's group can change either by user changing the config or updating counts (for leech detection); resist the urge to cache this var uploadsForGroup = UploadDictionary.Where(kvp => Users.GetGroup(kvp.Key) == groupName); + if (groupRecord is null) + { + throw new SlskdException($"Upload group {groupName} doesn't have an entry in upload dictionary. Please report this on GitHub: {Program.IssuesUrl}"); + } + // assuming that the queue will be processed in a true round-robin fashion and that the user will be the last in the // rotation (worst case), the user's start position will be equal to the number of users downloading or waiting, + 1. if (groupRecord.Strategy == QueueStrategy.RoundRobin) -- cgit v1.2.3 From cafcd731584a69dcdddf184e1258043f34bf967c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 Oct 2026 21:49:38 -0500 Subject: be pessimistic when estimating (assume round robin selects user last) --- src/slskd/Transfers/Uploads/UploadQueue.cs | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/src/slskd/Transfers/Uploads/UploadQueue.cs b/src/slskd/Transfers/Uploads/UploadQueue.cs index 1cefe74f..8f083c5d 100644 --- a/src/slskd/Transfers/Uploads/UploadQueue.cs +++ b/src/slskd/Transfers/Uploads/UploadQueue.cs @@ -326,6 +326,7 @@ namespace slskd.Transfers.Uploads var groupRecord = Groups.GetValueOrDefault(groupName); // the Uploads dictionary is keyed by username; gather all of the users that belong to the same group as the requested user + // a user's group can change either by user changing the config or updating counts (for leech detection); resist the urge to cache this var uploadsForGroup = UploadDictionary.Where(kvp => Users.GetGroup(kvp.Key) == groupName); SyncRoot.Wait(); @@ -368,16 +369,20 @@ namespace slskd.Transfers.Uploads // ^ // // if we want the position of the file over the carat above, first find the position of it - // within its own queue (= 5). assume uploads will process top down, left to right until reaching - // this one. that's 5 files from a, 2 from b, 5 from c, and the other 4 from d, putting the file over - // the carat at position 16. the actual number will vary due to many factors, including where in the - // round-robin ordering d is actually positioned (so +/- number of users downloading). + // within its own queue (= 4). assume uploads will process top down, left to right until reaching + // this one. that's the 4 ahead of it from d, plus 4 from a, 2 from b, and 4 from c in earlier rounds (= 14). foreach (var group in uploadsForGroup.Where(group => group.Key != username)) { position += Math.Min(localPosition, group.Value.Count); } - return position; + // be pessimistic and assume d is last in the rotation; every other user with a file in the same round + // goes first. in the example, a and c have a 5th file and b doesn't, putting the file over the carat + // at position 16. + var usersWithAtLeastAsManyFiles = uploadsForGroup + .Count(g => g.Key != username && g.Value.Count() >= localPosition + 1); // localPosition is zero-based + + return position + usersWithAtLeastAsManyFiles; } // find the upload -- cgit v1.2.3 From 2463b2e8601ddb4b6ee70811d381f921fde414ad Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 Oct 2026 21:51:00 -0500 Subject: tests for forecast/estimation --- .../Transfers/Uploads/UploadQueueTests.cs | 214 +++++++++++++++++++-- 1 file changed, 196 insertions(+), 18 deletions(-) diff --git a/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs b/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs index f878f95d..77a65dd5 100644 --- a/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs @@ -621,19 +621,21 @@ namespace slskd.Tests.Unit.Transfers.Uploads } [Theory, AutoData] - public void RoundRobin_Returns_Zero_For_First_File_Regardless_Of_Other_Users(string username, string other) + public void RoundRobin_First_File_Is_Behind_Every_Other_User_With_Queued_Files(string username, string other1, string other2) { var (queue, _) = GetFixture(); SetStrategy(queue, QueueStrategy.RoundRobin); var uploads = new ConcurrentDictionary>(); - uploads.TryAdd(other, CreateUploads(other, count: 10, offset: -100)); + uploads.TryAdd(other1, CreateUploads(other1, count: 10, offset: -100)); + uploads.TryAdd(other2, CreateUploads(other2, count: 1, offset: -100)); uploads.TryAdd(username, CreateUploads(username, count: 3)); queue.SetProperty("UploadDictionary", uploads); - Assert.Equal(0, queue.EstimatePosition(username, "file0")); + // pessimistic; both other users have a file in round 0, and are assumed to go first + Assert.Equal(2, queue.EstimatePosition(username, "file0")); } [Theory, AutoData] @@ -656,8 +658,30 @@ namespace slskd.Tests.Unit.Transfers.Uploads queue.SetProperty("UploadDictionary", uploads); - // 4 (local) + min(4, 5) + min(4, 2) + min(4, 12) - Assert.Equal(4 + 4 + 2 + 4, queue.EstimatePosition(d, "file4")); + // 4 (local) + min(4, 5) + min(4, 2) + min(4, 12), + 1 each for a and c, which have a file in round 4 + Assert.Equal(4 + 4 + 2 + 4 + 2, queue.EstimatePosition(d, "file4")); + } + + [Theory] + [InlineAutoData(1, 3)] + [InlineAutoData(2, 4)] + [InlineAutoData(3, 5)] + [InlineAutoData(10, 5)] + public void RoundRobin_Counts_Other_User_As_Ahead_Only_If_They_Have_A_File_In_The_Same_Round(int otherCount, int expected, string username, string other) + { + var (queue, _) = GetFixture(); + + SetStrategy(queue, QueueStrategy.RoundRobin); + + // the requested file is at local position 2 (round 2). the other user contends for round 2 only if they + // have more than 2 files: 2 (local) + min(2, otherCount) + (otherCount > 2 ? 1 : 0) + var uploads = new ConcurrentDictionary>(); + uploads.TryAdd(username, CreateUploads(username, count: 3)); + uploads.TryAdd(other, CreateUploads(other, count: otherCount)); + + queue.SetProperty("UploadDictionary", uploads); + + Assert.Equal(expected, queue.EstimatePosition(username, "file2")); } [Theory, AutoData] @@ -753,24 +777,150 @@ namespace slskd.Tests.Unit.Transfers.Uploads Assert.Equal(2, queue.EstimatePosition(username, "file2")); } + } - private static void SetStrategy(UploadQueue queue, QueueStrategy strategy) + public class ForecastPosition + { + [Theory] + [InlineAutoData(QueueStrategy.RoundRobin)] + [InlineAutoData(QueueStrategy.FirstInFirstOut)] + public void Returns_Zero_If_Slot_Is_Available_Regardless_Of_Queue(QueueStrategy strategy, string username, string other) { - var groups = queue.GetProperty>("Groups"); - groups[Application.DefaultGroup].Strategy = strategy; + var (queue, _) = GetFixture(); + + SetStrategy(queue, strategy); + SetSlotAvailable(queue, true); + + var uploads = new ConcurrentDictionary>(); + uploads.TryAdd(other, CreateUploads(other, count: 10)); + + queue.SetProperty("UploadDictionary", uploads); + + Assert.Equal(0, queue.ForecastPosition(username)); + } + + [Theory] + [InlineAutoData(QueueStrategy.RoundRobin)] + [InlineAutoData(QueueStrategy.FirstInFirstOut)] + public void Returns_One_If_No_Slot_Is_Available_And_Queue_Is_Empty(QueueStrategy strategy, string username) + { + var (queue, _) = GetFixture(); + + SetStrategy(queue, strategy); + SetSlotAvailable(queue, false); + + Assert.Equal(1, queue.ForecastPosition(username)); } - // creates uploads named file0..fileN, enqueued at Now + offset + (i * step) seconds, in ascending order - private static List CreateUploads(string username, int count, int offset = 0, int step = 1) + [Theory, AutoData] + public void RoundRobin_Returns_Number_Of_Users_In_Group_Plus_One(string username, string other1, string other2) { - return Enumerable.Range(0, count) - .Select(i => new Upload() - { - Username = username, - Filename = $"file{i}", - Enqueued = Now.AddSeconds(offset + (i * step)), - }) - .ToList(); + var (queue, _) = GetFixture(); + + SetStrategy(queue, QueueStrategy.RoundRobin); + SetSlotAvailable(queue, false); + + var uploads = new ConcurrentDictionary>(); + uploads.TryAdd(other1, CreateUploads(other1, count: 10)); + uploads.TryAdd(other2, CreateUploads(other2, count: 1)); + + queue.SetProperty("UploadDictionary", uploads); + + // worst case; the new file is last in the rotation. file counts don't matter + Assert.Equal(3, queue.ForecastPosition(username)); + } + + [Theory, AutoData] + public void RoundRobin_Counts_Requesting_User_Once_Regardless_Of_Their_Queued_Files(string username, string other) + { + var (queue, _) = GetFixture(); + + SetStrategy(queue, QueueStrategy.RoundRobin); + SetSlotAvailable(queue, false); + + var uploads = new ConcurrentDictionary>(); + uploads.TryAdd(username, CreateUploads(username, count: 10)); + uploads.TryAdd(other, CreateUploads(other, count: 1)); + + queue.SetProperty("UploadDictionary", uploads); + + Assert.Equal(3, queue.ForecastPosition(username)); + } + + [Theory, AutoData] + public void RoundRobin_Ignores_Users_In_Other_Groups(string username, string other1, string other2) + { + var (queue, mocks) = GetFixture(); + + SetStrategy(queue, QueueStrategy.RoundRobin); + SetSlotAvailable(queue, false); + + mocks.UserService.Setup(m => m.GetGroup(other2)).Returns(Application.PrivilegedGroup); + + var uploads = new ConcurrentDictionary>(); + uploads.TryAdd(other1, CreateUploads(other1, count: 1)); + uploads.TryAdd(other2, CreateUploads(other2, count: 1)); + + queue.SetProperty("UploadDictionary", uploads); + + Assert.Equal(2, queue.ForecastPosition(username)); + } + + [Theory, AutoData] + public void FirstInFirstOut_Returns_Number_Of_Uploads_In_Group_Plus_One(string username, string other1, string other2) + { + var (queue, _) = GetFixture(); + + SetStrategy(queue, QueueStrategy.FirstInFirstOut); + SetSlotAvailable(queue, false); + + var uploads = new ConcurrentDictionary>(); + uploads.TryAdd(username, CreateUploads(username, count: 2)); + uploads.TryAdd(other1, CreateUploads(other1, count: 3)); + uploads.TryAdd(other2, CreateUploads(other2, count: 4)); + + queue.SetProperty("UploadDictionary", uploads); + + // the new file goes to the back of the queue, behind every upload in the group, including the user's own + Assert.Equal(2 + 3 + 4 + 1, queue.ForecastPosition(username)); + } + + [Theory, AutoData] + public void FirstInFirstOut_Counts_Uploads_In_Progress(string username, string other) + { + var (queue, _) = GetFixture(); + + SetStrategy(queue, QueueStrategy.FirstInFirstOut); + SetSlotAvailable(queue, false); + + var started = CreateUploads(other, count: 2); + started.ForEach(u => u.Started = Now); + + var uploads = new ConcurrentDictionary>(); + uploads.TryAdd(other, started); + + queue.SetProperty("UploadDictionary", uploads); + + Assert.Equal(3, queue.ForecastPosition(username)); + } + + [Theory, AutoData] + public void FirstInFirstOut_Ignores_Users_In_Other_Groups(string username, string other1, string other2) + { + var (queue, mocks) = GetFixture(); + + SetStrategy(queue, QueueStrategy.FirstInFirstOut); + SetSlotAvailable(queue, false); + + mocks.UserService.Setup(m => m.GetGroup(other2)).Returns(Application.PrivilegedGroup); + + var uploads = new ConcurrentDictionary>(); + uploads.TryAdd(other1, CreateUploads(other1, count: 3)); + uploads.TryAdd(other2, CreateUploads(other2, count: 10)); + + queue.SetProperty("UploadDictionary", uploads); + + Assert.Equal(4, queue.ForecastPosition(username)); } } @@ -975,6 +1125,34 @@ namespace slskd.Tests.Unit.Transfers.Uploads } } + private static readonly DateTime Now = DateTime.UtcNow; + + private static void SetStrategy(UploadQueue queue, QueueStrategy strategy) + { + var groups = queue.GetProperty>("Groups"); + groups[Application.DefaultGroup].Strategy = strategy; + } + + private static void SetSlotAvailable(UploadQueue queue, bool available) + { + var groups = queue.GetProperty>("Groups"); + groups[Application.DefaultGroup].Slots = 1; + groups[Application.DefaultGroup].UsedSlots = available ? 0 : 1; + } + + // creates uploads named file0..fileN, enqueued at Now + offset + (i * step) seconds, in ascending order + private static List CreateUploads(string username, int count, int offset = 0, int step = 1) + { + return Enumerable.Range(0, count) + .Select(i => new Upload() + { + Username = username, + Filename = $"file{i}", + Enqueued = Now.AddSeconds(offset + (i * step)), + }) + .ToList(); + } + private static (UploadQueue queue, Mocks mocks) GetFixture(Options options = null) { var mocks = new Mocks(options); -- cgit v1.2.3 From 1915a370c1bd11aee8849574e116b353a0b7153f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 3 Oct 2026 23:14:04 -0500 Subject: fix errant brace --- tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs b/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs index 77a65dd5..7b35232c 100644 --- a/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/Uploads/UploadQueueTests.cs @@ -562,6 +562,8 @@ namespace slskd.Tests.Unit.Transfers.Uploads Assert.Equal(task, uploads[username][0].TaskCompletionSource.Task); } + } + public class EstimatePosition { private static readonly DateTime Now = DateTime.UtcNow; -- cgit v1.2.3