Usenet streaming with a WebDAV server and a SABnzbd-compatible API
C#
Limit connections used during queue processing (#37)
nzbdav-dev6bd91eead9a2
diff --git a/backend/Clients/Connections/ConnectionPool.cs b/backend/Clients/Connections/ConnectionPool.csindex 2e927ec8..bb99ce9b 100644--- a/backend/Clients/Connections/ConnectionPool.cs+++ b/backend/Clients/Connections/ConnectionPool.cs@@ -1,5 +1,6 @@using System.Collections.Concurrent;using System.Runtime.CompilerServices;+using NzbWebDAV.Extensions;namespace NzbWebDAV.Clients.Connections;@@ -29,7 +30,7 @@ public sealed class ConnectionPool<T> : IDisposable, IAsyncDisposable/* --------------------------------- state --------------------------------------- */private readonly ConcurrentStack<Pooled> _idleConnections = new();- private readonly SemaphoreSlim _gate;+ private readonly ExtendedSemaphoreSlim _gate;private readonly CancellationTokenSource _sweepCts = new();private readonly Task _sweeperTask; // keeps timer alive@@ -51,21 +52,29 @@ public sealed class ConnectionPool<T> : IDisposable, IAsyncDisposableIdleTimeout = idleTimeout ?? TimeSpan.FromSeconds(30);_maxConnections = maxConnections;- _gate = new SemaphoreSlim(maxConnections, maxConnections);+ _gate = new ExtendedSemaphoreSlim(maxConnections, maxConnections);_sweeperTask = Task.Run(SweepLoop); // background idle-reaper}/* ============================== public API ==================================== */- /// <summary>Borrow a connection; releases automatically with the lock.</summary>+ /// <summary>+ /// Borrow a connection while reserving capacity for higher-priority callers.+ /// Waits until at least (`reservedCount` + 1) slots are free before acquiring one,+ /// ensuring that after acquisition at least `reservedCount` remain available.+ /// </summary>public async Task<ConnectionLock<T>> GetConnectionLockAsync(CancellationToken cancellationToken = default){+ var reservedCount = cancellationToken.GetContext<ReservedConnectionsContext>().Count;+ if (reservedCount < 0 || reservedCount > _maxConnections)+ reservedCount = 0;+// Make caller cancellation also cancel the wait on the gate.using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _sweepCts.Token);- await _gate.WaitAsync(linked.Token).ConfigureAwait(false);+ await _gate.WaitAsync(reservedCount, linked.Token).ConfigureAwait(false);// Pool might have been disposed after wait returned:if (Volatile.Read(ref _disposed) == 1)diff --git a/backend/Clients/Connections/ExtendedSemaphoreSlim.cs b/backend/Clients/Connections/ExtendedSemaphoreSlim.csnew file mode 100644index 00000000..04bf7a25--- /dev/null+++ b/backend/Clients/Connections/ExtendedSemaphoreSlim.cs@@ -0,0 +1,241 @@+namespace NzbWebDAV.Clients.Connections+{+ /// <summary>+ /// A semaphore-like primitive where each waiter specifies the number of+ /// free slots that must remain available after acquisition.+ ///+ /// WaitAsync(requiredAvailable): acquires only if (CurrentCount >= requiredAvailable + 1).+ /// Release(): releases one slot.+ ///+ /// Higher requiredAvailable implies higher priority when multiple waiters exist.+ /// </summary>+ public sealed class ExtendedSemaphoreSlim+ {+ private readonly object _lock = new object();++ // Available slots (like SemaphoreSlim's CurrentCount)+ private int _currentCount;+ private readonly int _maxCount;++ // Waiters bucketed by requiredAvailable; keys sorted ascending, we serve descending.+ private readonly SortedDictionary<int, LinkedList<Waiter>> _queues = new();+ private int _waiterCount; // volatile read for fast-path guard++ public ExtendedSemaphoreSlim(int initialCount, int maxCount)+ {+ if (maxCount <= 0) throw new ArgumentOutOfRangeException(nameof(maxCount));+ if (initialCount < 0 || initialCount > maxCount)+ throw new ArgumentOutOfRangeException(nameof(initialCount));++ _currentCount = initialCount;+ _maxCount = maxCount;+ }++ public ExtendedSemaphoreSlim(int initialCount) : this(initialCount, int.MaxValue)+ {+ }++ /// <summary>+ /// Current number of available slots.+ /// </summary>+ public int CurrentCount => Volatile.Read(ref _currentCount);++ /// <summary>+ /// Wait until there are at least (requiredAvailable + 1) slots free, then acquire 1 slot.+ /// After this completes successfully, at least requiredAvailable slots remain free.+ /// </summary>+ public Task WaitAsync(int requiredAvailable, CancellationToken cancellationToken = default)+ {+ if (requiredAvailable < 0) throw new ArgumentOutOfRangeException(nameof(requiredAvailable));+ if (requiredAvailable >= _maxCount)+ throw new ArgumentOutOfRangeException(nameof(requiredAvailable),+ "requiredAvailable must be less than the semaphore's maximum count.");++ // Fast path: no waiters and enough capacity -> try to take one with a single CAS.+ if (Volatile.Read(ref _waiterCount) == 0 && TryAcquireFast(requiredAvailable))+ return Task.CompletedTask;++ // Slow path: enqueue and let the scheduler (by priority) grant slots.+ var tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);+ var waiter = new Waiter(requiredAvailable, tcs);++ List<Waiter>? toGrant = null;+ CancellationTokenRegistration ctr = default;+ bool registered = false;++ lock (_lock)+ {+ EnqueueWaiter_NoLock(waiter);++ // Try to grant immediately in case capacity is there (or arrived just before we enqueued).+ toGrant = TryGrantWaiters_NoLock();+ }++ // Fire completions outside the lock.+ CompleteGranted(toGrant);++ if (tcs.Task.IsCompleted)+ return tcs.Task;++ if (cancellationToken.CanBeCanceled)+ {+ // Register cancellation; remove in O(1) if still queued.+ ctr = cancellationToken.Register(static state =>+ {+ var (sem, w, tok) = ((ExtendedSemaphoreSlim, Waiter, CancellationToken))state!;+ bool removed = sem.TryRemoveWaiter(w);+ if (removed)+ w.Tcs.TrySetCanceled(tok);+ }, (this, waiter, cancellationToken));+ registered = true;++ // Dispose registration when the wait completes in any way.+ _ = tcs.Task.ContinueWith(static (_, s) => ((CancellationTokenRegistration)s!).Dispose(),+ ctr, CancellationToken.None,+ TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);+ }++ return tcs.Task;++ // ---------------- local helpers ----------------++ bool TryAcquireFast(int reqAvail)+ {+ while (true)+ {+ int observed = Volatile.Read(ref _currentCount);+ if (observed <= reqAvail) return false; // need at least reqAvail+1 to take one+ int newVal = observed - 1;+ if (Interlocked.CompareExchange(ref _currentCount, newVal, observed) == observed)+ return true;+ }+ }+ }++ /// <summary>+ /// Release one slot back to the semaphore.+ /// </summary>+ public void Release()+ {+ int newCount = Interlocked.Increment(ref _currentCount);+ if (newCount > _maxCount)+ {+ Interlocked.Decrement(ref _currentCount);+ throw new SemaphoreFullException();+ }++ // If there are no waiters, we're done.+ if (Volatile.Read(ref _waiterCount) == 0)+ return;++ List<Waiter>? toGrant;+ lock (_lock)+ {+ toGrant = TryGrantWaiters_NoLock();+ }++ // Complete outside the lock to avoid running continuations under the lock.+ CompleteGranted(toGrant);+ }++ // ---------------- core scheduling ----------------++ private void EnqueueWaiter_NoLock(Waiter w)+ {+ if (!_queues.TryGetValue(w.Required, out var list))+ {+ list = new LinkedList<Waiter>();+ _queues.Add(w.Required, list);+ }++ w.Node = list.AddLast(w);+ _waiterCount++;+ }++ private bool TryRemoveWaiter(Waiter w)+ {+ lock (_lock)+ {+ if (w.Signaled) return false; // already granted+ if (w.Node == null) return false; // not in a queue (already removed)+ if (!_queues.TryGetValue(w.Required, out var list)) return false;++ list.Remove(w.Node);+ w.Node = null;+ _waiterCount--;+ if (list.Count == 0) _queues.Remove(w.Required);+ return true;+ }+ }++ /// <summary>+ /// Grants as many queued waiters as possible by descending requiredAvailable.+ /// Must be called under _lock. Returns the waiters to complete outside the lock.+ /// </summary>+ private List<Waiter> TryGrantWaiters_NoLock()+ {+ if (_waiterCount == 0)+ return s_empty;++ var granted = new List<Waiter>();+ List<int>? emptyKeys = null;++ // Iterate priorities descending; serve FIFO within each priority.+ foreach (var kvp in _queues.Reverse())+ {+ int req = kvp.Key;+ var list = kvp.Value;++ while (_currentCount > req && list.First is not null)+ {+ var node = list.First!;+ list.RemoveFirst();++ var w = node.Value;+ w.Node = null;+ w.Signaled = true;++ _currentCount--; // consume one slot for this grant+ _waiterCount--;+ granted.Add(w);+ }++ if (list.Count == 0)+ (emptyKeys ??= new List<int>()).Add(req);+ }++ if (emptyKeys is not null)+ {+ foreach (var k in emptyKeys)+ _queues.Remove(k);+ }++ return granted;+ }++ private static void CompleteGranted(List<Waiter>? granted)+ {+ if (granted is null || granted.Count == 0) return;+ foreach (var w in granted)+ w.Tcs.TrySetResult(true);+ }++ // ---------------- inner types ----------------++ private sealed class Waiter+ {+ public readonly int Required;+ public readonly TaskCompletionSource<bool> Tcs;+ public LinkedListNode<Waiter>? Node;+ public bool Signaled;++ public Waiter(int required, TaskCompletionSource<bool> tcs)+ {+ Required = required;+ Tcs = tcs;+ }+ }++ private static readonly List<Waiter> s_empty = new List<Waiter>(0);+ }+}\ No newline at end of filediff --git a/backend/Clients/Connections/ReservedConnectionsContext.cs b/backend/Clients/Connections/ReservedConnectionsContext.csnew file mode 100644index 00000000..090ae8d6--- /dev/null+++ b/backend/Clients/Connections/ReservedConnectionsContext.cs@@ -0,0 +1,6 @@+namespace NzbWebDAV.Clients.Connections;++public readonly struct ReservedConnectionsContext(int reservedCount)+{+ public int Count => reservedCount;+}\ No newline at end of filediff --git a/backend/Clients/UsenetStreamingClient.cs b/backend/Clients/UsenetStreamingClient.csindex ecc1dc64..fcbedab2 100644--- a/backend/Clients/UsenetStreamingClient.cs+++ b/backend/Clients/UsenetStreamingClient.cs@@ -27,7 +27,7 @@ public class UsenetStreamingClientvar useSsl = bool.Parse(configManager.GetConfigValue("usenet.use-ssl") ?? "false");var user = configManager.GetConfigValue("usenet.user") ?? string.Empty;var pass = configManager.GetConfigValue("usenet.pass") ?? string.Empty;- var connections = int.Parse(configManager.GetConfigValue("usenet.connections") ?? "10");+ var connections = configManager.GetMaxConnections();// initialize the nntp-clientvar createNewConnection = (CancellationToken ct) => CreateNewConnection(host, port, useSsl, user, pass, ct);diff --git a/backend/Config/ConfigManager.cs b/backend/Config/ConfigManager.csindex 75314c3a..9396d9cc 100644--- a/backend/Config/ConfigManager.cs+++ b/backend/Config/ConfigManager.cs@@ -69,6 +69,14 @@ public class ConfigManager?? "audio,software,tv,movies";}+ public int GetMaxConnections()+ {+ return int.Parse(+ StringUtil.EmptyToNull(GetConfigValue("usenet.connections"))+ ?? "10"+ );+ }+public int GetConnectionsPerStream(){return int.Parse(@@ -112,6 +120,14 @@ public class ConfigManagerreturn StringUtil.EmptyToNull(GetConfigValue("media.library-dir"));}+ public int GetMaxQueueConnections()+ {+ return int.Parse(+ StringUtil.EmptyToNull(GetConfigValue("api.max-queue-connections"))+ ?? GetMaxConnections().ToString()+ );+ }+public class ConfigEventArgs : EventArgs{public Dictionary<string, string> ChangedConfig { get; set; } = new();diff --git a/backend/Database/DavDatabaseClient.cs b/backend/Database/DavDatabaseClient.csindex 6910403c..5a1d31f0 100644--- a/backend/Database/DavDatabaseClient.cs+++ b/backend/Database/DavDatabaseClient.cs@@ -80,7 +80,7 @@ public sealed class DavDatabaseClient(DavDatabaseContext ctx)return Ctx.QueueItems.OrderByDescending(q => q.Priority).ThenBy(q => q.CreatedAt)- .Where(q => q.PauseUntil == null || DateTime.Now >= q.PauseUntil)+ .Where(q => q.PauseUntil == null || nowTime >= q.PauseUntil).Skip(0).Take(1).FirstOrDefaultAsync(ct);diff --git a/backend/Extensions/CancellationTokenExtensions.cs b/backend/Extensions/CancellationTokenExtensions.csnew file mode 100644index 00000000..6aa1efec--- /dev/null+++ b/backend/Extensions/CancellationTokenExtensions.cs@@ -0,0 +1,27 @@+using System.Collections.Concurrent;++namespace NzbWebDAV.Extensions;++public static class CancellationTokenExtensions+{+ private static readonly ConcurrentDictionary<CancellationToken, object?> Context = new();++ public static CancellationTokenScopedContext SetScopedContext<T>(this CancellationToken ct, T? value)+ {+ Context[ct] = value;+ return new CancellationTokenScopedContext(ct);+ }++ public static T? GetContext<T>(this CancellationToken ct)+ {+ return Context.TryGetValue(ct, out var result) && result is T context ? context : default;+ }++ public class CancellationTokenScopedContext(CancellationToken ct) : IDisposable+ {+ public void Dispose()+ {+ Context.Remove(ct, out _);+ }+ }+}\ No newline at end of filediff --git a/backend/Queue/QueueItemProcessor.cs b/backend/Queue/QueueItemProcessor.csindex 15ada3a3..ee4982d2 100644--- a/backend/Queue/QueueItemProcessor.cs+++ b/backend/Queue/QueueItemProcessor.cs@@ -2,6 +2,7 @@ using System.Text;using Microsoft.EntityFrameworkCore;using NzbWebDAV.Api.SabControllers.GetHistory;using NzbWebDAV.Clients;+using NzbWebDAV.Clients.Connections;using NzbWebDAV.Config;using NzbWebDAV.Database;using NzbWebDAV.Database.Models;@@ -90,6 +91,10 @@ public class QueueItemProcessor(return;}+ // ensure we don't use more than max-queue-connections+ var reservedConnections = configManager.GetMaxConnections() - configManager.GetMaxQueueConnections();+ using var _ = ct.SetScopedContext(new ReservedConnectionsContext(reservedConnections));+// read the nzb documentvar documentBytes = Encoding.UTF8.GetBytes(queueItem.NzbContents);using var stream = new MemoryStream(documentBytes);diff --git a/backend/Utils/SigtermUtil.cs b/backend/Utils/SigtermUtil.csindex f97ec7d7..5b6c8576 100644--- a/backend/Utils/SigtermUtil.cs+++ b/backend/Utils/SigtermUtil.cs@@ -1,5 +1,4 @@using System.Runtime.Loader;-using Serilog;namespace NzbWebDAV.Utils;