Usenet streaming with a WebDAV server and a SABnzbd-compatible API
C#
Added DownloadingNntpClient.
nzbdav-devfa8b49799ad8
diff --git a/backend/Clients/Usenet/Concurrency/PrioritizedSemaphore.cs b/backend/Clients/Usenet/Concurrency/PrioritizedSemaphore.csindex 71f8f7de..a5651f95 100644--- a/backend/Clients/Usenet/Concurrency/PrioritizedSemaphore.cs+++ b/backend/Clients/Usenet/Concurrency/PrioritizedSemaphore.cs@@ -18,7 +18,7 @@ public class PrioritizedSemaphore : IDisposable{private readonly LinkedList<TaskCompletionSource<bool>> _highPriorityWaiters = [];private readonly LinkedList<TaskCompletionSource<bool>> _lowPriorityWaiters = [];- private readonly SemaphorePriorityOdds _priorityOdds;+ private SemaphorePriorityOdds _priorityOdds;private int _maxAllowed;private int _enteredCount;private bool _disposed = false;@@ -165,6 +165,14 @@ public class PrioritizedSemaphore : IDisposable}}+ public void UpdatePriorityOdds(SemaphorePriorityOdds newPriorityOdds)+ {+ lock (_lock)+ {+ _priorityOdds = newPriorityOdds;+ }+ }+public void Dispose(){List<TaskCompletionSource<bool>> waitersToCancel;diff --git a/backend/Clients/Usenet/Concurrency/SemaphorePriority.cs b/backend/Clients/Usenet/Concurrency/SemaphorePriority.csindex 33cc4c05..41fe6dfb 100644--- a/backend/Clients/Usenet/Concurrency/SemaphorePriority.cs+++ b/backend/Clients/Usenet/Concurrency/SemaphorePriority.cs@@ -2,6 +2,6 @@public enum SemaphorePriority{- High,Low,+ High,}\ No newline at end of filediff --git a/backend/Clients/Usenet/Concurrency/SemaphorePriorityOdds.cs b/backend/Clients/Usenet/Concurrency/SemaphorePriorityOdds.csindex 47d8b1f3..6cadbbbb 100644--- a/backend/Clients/Usenet/Concurrency/SemaphorePriorityOdds.cs+++ b/backend/Clients/Usenet/Concurrency/SemaphorePriorityOdds.cs@@ -1,6 +1,6 @@namespace NzbWebDAV.Clients.Usenet.Concurrency;-public class SemaphorePriorityOdds+public record SemaphorePriorityOdds{public required double HighPriorityOdds { get; set; }public double LowPriorityOdds => 1.0 - HighPriorityOdds;diff --git a/backend/Clients/Usenet/Contexts/DownloadPriorityContext.cs b/backend/Clients/Usenet/Contexts/DownloadPriorityContext.csnew file mode 100644index 00000000..d775f0bb--- /dev/null+++ b/backend/Clients/Usenet/Contexts/DownloadPriorityContext.cs@@ -0,0 +1,7 @@+namespace NzbWebDAV.Clients.Usenet.Contexts;++public enum DownloadPriorityContext+{+ Low,+ High,+}\ No newline at end of filediff --git a/backend/Clients/Usenet/DownloadingNntpClient.cs b/backend/Clients/Usenet/DownloadingNntpClient.csnew file mode 100644index 00000000..846ecb86--- /dev/null+++ b/backend/Clients/Usenet/DownloadingNntpClient.cs@@ -0,0 +1,107 @@+using NzbWebDAV.Clients.Usenet.Concurrency;+using NzbWebDAV.Clients.Usenet.Contexts;+using NzbWebDAV.Clients.Usenet.Models;+using NzbWebDAV.Config;+using NzbWebDAV.Extensions;+using UsenetSharp.Models;++namespace NzbWebDAV.Clients.Usenet;++/// <summary>+/// This client is only responsible for limiting download operations (HEAD/ARTICLE)+/// to the configured number of maximum download connections.+/// </summary>+/// <param name="usenetClient"></param>+public class DownloadingNntpClient : WrappingNntpClient+{+ private readonly ConfigManager _configManager;+ private readonly PrioritizedSemaphore _semaphore;++ public DownloadingNntpClient(INntpClient usenetClient, ConfigManager configManager) : base(usenetClient)+ {+ var maxDownloadConnections = configManager.GetMaxDownloadConnections();+ var streamingPriority = configManager.GetStreamingPriority();+ _configManager = configManager;+ _semaphore = new PrioritizedSemaphore(maxDownloadConnections, maxDownloadConnections, streamingPriority);+ configManager.OnConfigChanged += OnConfigChanged;+ }++ private void OnConfigChanged(object? sender, ConfigManager.ConfigEventArgs e)+ {+ if (e.ChangedConfig.ContainsKey("usenet.max-download-connections"))+ {+ var maxDownloadConnections = _configManager.GetMaxDownloadConnections();+ _semaphore.UpdateMaxAllowed(maxDownloadConnections);+ }++ if (e.ChangedConfig.ContainsKey("usenet.streaming-priority"))+ {+ var streamingPriority = _configManager.GetStreamingPriority();+ _semaphore.UpdatePriorityOdds(streamingPriority);+ }+ }++ public override Task<UsenetDecodedBodyResponse> DecodedBodyAsync(SegmentId segmentId,+ CancellationToken cancellationToken)+ {+ return DecodedBodyAsync(segmentId, null, cancellationToken);+ }++ public override Task<UsenetDecodedArticleResponse> DecodedArticleAsync(SegmentId segmentId,+ CancellationToken cancellationToken)+ {+ return DecodedArticleAsync(segmentId, null, cancellationToken);+ }++ public override async Task<UsenetDecodedBodyResponse> DecodedBodyAsync(SegmentId segmentId,+ Action<ArticleBodyResult>? onConnectionReadyAgain, CancellationToken cancellationToken)+ {+ await WaitForDownloadConnection(onConnectionReadyAgain, cancellationToken).ConfigureAwait(false);+ return await base.DecodedBodyAsync(segmentId, OnConnectionReadyAgain, cancellationToken).ConfigureAwait(false);++ void OnConnectionReadyAgain(ArticleBodyResult articleBodyResult)+ {+ _semaphore.Release();+ onConnectionReadyAgain?.Invoke(articleBodyResult);+ }+ }++ public override async Task<UsenetDecodedArticleResponse> DecodedArticleAsync(SegmentId segmentId,+ Action<ArticleBodyResult>? onConnectionReadyAgain, CancellationToken cancellationToken)+ {+ await WaitForDownloadConnection(onConnectionReadyAgain, cancellationToken).ConfigureAwait(false);+ return await base.DecodedArticleAsync(segmentId, OnConnectionReadyAgain, cancellationToken)+ .ConfigureAwait(false);++ void OnConnectionReadyAgain(ArticleBodyResult articleBodyResult)+ {+ _semaphore.Release();+ onConnectionReadyAgain?.Invoke(articleBodyResult);+ }+ }++ private async Task WaitForDownloadConnection(Action<ArticleBodyResult>? onConnectionReadyAgain,+ CancellationToken cancellationToken)+ {+ try+ {+ var downloadPriorityContext = cancellationToken.GetContext<DownloadPriorityContext>();+ var semaphorePriority = downloadPriorityContext == DownloadPriorityContext.Low+ ? SemaphorePriority.Low+ : SemaphorePriority.High;+ await _semaphore.WaitAsync(semaphorePriority, cancellationToken);+ }+ catch+ {+ onConnectionReadyAgain?.Invoke(ArticleBodyResult.NotRetrieved);+ throw;+ }+ }++ public override void Dispose()+ {+ _configManager.OnConfigChanged -= OnConfigChanged;+ base.Dispose();+ GC.SuppressFinalize(this);+ }+}\ No newline at end of filediff --git a/backend/Clients/Usenet/UsenetStreamingClient.cs b/backend/Clients/Usenet/UsenetStreamingClient.csindex 3625d3fa..80f05db0 100644--- a/backend/Clients/Usenet/UsenetStreamingClient.cs+++ b/backend/Clients/Usenet/UsenetStreamingClient.cs@@ -1,5 +1,4 @@-using System.Text.Json;-using NzbWebDAV.Clients.Usenet.Connections;+using NzbWebDAV.Clients.Usenet.Connections;using NzbWebDAV.Config;using NzbWebDAV.Websocket;@@ -8,27 +7,37 @@ namespace NzbWebDAV.Clients.Usenet;public class UsenetStreamingClient : WrappingNntpClient{public UsenetStreamingClient(ConfigManager configManager, WebsocketManager websocketManager)- : base(CreateMultiProviderClient(configManager.GetUsenetProviderConfig(), websocketManager))+ : base(CreateDownloadingNntpClient(configManager, websocketManager)){// when config changes, create a new MultiProviderClient to use instead.configManager.OnConfigChanged += (_, configEventArgs) =>{// if unrelated config changed, do nothing- if (!configEventArgs.ChangedConfig.TryGetValue("usenet.providers", out var rawConfig)) return;+ if (!configEventArgs.ChangedConfig.ContainsKey("usenet.providers")) return;// update the connection-pool according to the new config- var newProviderConfig = JsonSerializer.Deserialize<UsenetProviderConfig>(rawConfig);- var newMultiProviderClient = CreateMultiProviderClient(newProviderConfig!, websocketManager);- ReplaceUnderlyingClient(newMultiProviderClient);+ var newUsenetClient = CreateDownloadingNntpClient(configManager, websocketManager);+ ReplaceUnderlyingClient(newUsenetClient);};}+ private static DownloadingNntpClient CreateDownloadingNntpClient+ (+ ConfigManager configManager,+ WebsocketManager websocketManager+ )+ {+ var multiProviderClient = CreateMultiProviderClient(configManager, websocketManager);+ return new DownloadingNntpClient(multiProviderClient, configManager);+ }+private static MultiProviderNntpClient CreateMultiProviderClient(- UsenetProviderConfig providerConfig,+ ConfigManager configManager,WebsocketManager websocketManager){+ var providerConfig = configManager.GetUsenetProviderConfig();var connectionPoolStats = new ConnectionPoolStats(providerConfig, websocketManager);var providerClients = providerConfig.Providers.Select((provider, index) => CreateProviderClient(diff --git a/backend/Clients/Usenet/WrappingNntpClient.cs b/backend/Clients/Usenet/WrappingNntpClient.csindex a51610b6..72c6ad5d 100644--- a/backend/Clients/Usenet/WrappingNntpClient.cs+++ b/backend/Clients/Usenet/WrappingNntpClient.cs@@ -7,49 +7,49 @@ public class WrappingNntpClient(INntpClient usenetClient) : INntpClient{private INntpClient _usenetClient = usenetClient;- public Task ConnectAsync(string host, int port, bool useSsl, CancellationToken cancellationToken)+ public virtual Task ConnectAsync(string host, int port, bool useSsl, CancellationToken cancellationToken){return _usenetClient.ConnectAsync(host, port, useSsl, cancellationToken);}- public Task<UsenetResponse> AuthenticateAsync(string user, string pass, CancellationToken cancellationToken)+ public virtual Task<UsenetResponse> AuthenticateAsync(string user, string pass, CancellationToken cancellationToken){return _usenetClient.AuthenticateAsync(user, pass, cancellationToken);}- public Task<UsenetStatResponse> StatAsync(SegmentId segmentId, CancellationToken cancellationToken)+ public virtual Task<UsenetStatResponse> StatAsync(SegmentId segmentId, CancellationToken cancellationToken){return _usenetClient.StatAsync(segmentId, cancellationToken);}- public Task<UsenetHeadResponse> HeadAsync(SegmentId segmentId, CancellationToken cancellationToken)+ public virtual Task<UsenetHeadResponse> HeadAsync(SegmentId segmentId, CancellationToken cancellationToken){return _usenetClient.HeadAsync(segmentId, cancellationToken);}- public Task<UsenetDecodedBodyResponse> DecodedBodyAsync(SegmentId segmentId, CancellationToken cancellationToken)+ public virtual Task<UsenetDecodedBodyResponse> DecodedBodyAsync(SegmentId segmentId, CancellationToken cancellationToken){return _usenetClient.DecodedBodyAsync(segmentId, cancellationToken);}- public Task<UsenetDecodedArticleResponse> DecodedArticleAsync(SegmentId segmentId,+ public virtual Task<UsenetDecodedArticleResponse> DecodedArticleAsync(SegmentId segmentId,CancellationToken cancellationToken){return _usenetClient.DecodedArticleAsync(segmentId, cancellationToken);}- public Task<UsenetDateResponse> DateAsync(CancellationToken cancellationToken)+ public virtual Task<UsenetDateResponse> DateAsync(CancellationToken cancellationToken){return _usenetClient.DateAsync(cancellationToken);}- public Task<UsenetDecodedBodyResponse> DecodedBodyAsync(SegmentId segmentId,+ public virtual Task<UsenetDecodedBodyResponse> DecodedBodyAsync(SegmentId segmentId,Action<ArticleBodyResult>? onConnectionReadyAgain, CancellationToken cancellationToken){return _usenetClient.DecodedBodyAsync(segmentId, onConnectionReadyAgain, cancellationToken);}- public Task<UsenetDecodedArticleResponse> DecodedArticleAsync(SegmentId segmentId,+ public virtual Task<UsenetDecodedArticleResponse> DecodedArticleAsync(SegmentId segmentId,Action<ArticleBodyResult>? onConnectionReadyAgain, CancellationToken cancellationToken){return _usenetClient.DecodedArticleAsync(segmentId, onConnectionReadyAgain, cancellationToken);@@ -63,7 +63,7 @@ public class WrappingNntpClient(INntpClient usenetClient) : INntpClientdisposable.Dispose();}- public void Dispose()+ public virtual void Dispose(){_usenetClient.Dispose();GC.SuppressFinalize(this);diff --git a/backend/Config/ConfigManager.cs b/backend/Config/ConfigManager.csindex c2d6f8e7..502dc5f8 100644--- a/backend/Config/ConfigManager.cs+++ b/backend/Config/ConfigManager.cs@@ -1,5 +1,6 @@using System.Text.Json;using Microsoft.EntityFrameworkCore;+using NzbWebDAV.Clients.Usenet.Concurrency;using NzbWebDAV.Database;using NzbWebDAV.Database.Models;using NzbWebDAV.Utils;@@ -147,6 +148,13 @@ public class ConfigManager);}+ public SemaphorePriorityOdds GetStreamingPriority()+ {+ var stringValue = StringUtil.EmptyToNull(GetConfigValue("usenet.streaming-priority"));+ var numericalValue = int.Parse(stringValue ?? "80");+ return new SemaphorePriorityOdds() { HighPriorityOdds = numericalValue / 100.0 };+ }+public bool IsEnforceReadonlyWebdavEnabled(){var defaultValue = true;diff --git a/backend/WebDav/Base/BaseStoreStreamFile.cs b/backend/WebDav/Base/BaseStoreStreamFile.csindex 0d761f9b..2fec2402 100644--- a/backend/WebDav/Base/BaseStoreStreamFile.cs+++ b/backend/WebDav/Base/BaseStoreStreamFile.cs@@ -1,11 +1,22 @@-namespace NzbWebDAV.WebDav.Base;+using Microsoft.AspNetCore.Http;+using NzbWebDAV.Clients.Usenet.Contexts;+using NzbWebDAV.Extensions;-public abstract class BaseStoreStreamFile() : BaseStoreReadonlyItem+namespace NzbWebDAV.WebDav.Base;++public abstract class BaseStoreStreamFile(HttpContext context) : BaseStoreReadonlyItem{protected abstract Task<Stream> GetStreamAsync(CancellationToken cancellationToken);public override Task<Stream> GetReadableStreamAsync(CancellationToken cancellationToken){+ var downloadPriorityContext = cancellationToken.SetScopedContext(DownloadPriorityContext.High);+ context.Response.OnCompleted(() =>+ {+ downloadPriorityContext.Dispose();+ return Task.CompletedTask;+ });+return GetStreamAsync(cancellationToken);}}\ No newline at end of filediff --git a/backend/WebDav/DatabaseStoreMultipartFile.cs b/backend/WebDav/DatabaseStoreMultipartFile.csindex 75930dbe..89e4c6d4 100644--- a/backend/WebDav/DatabaseStoreMultipartFile.cs+++ b/backend/WebDav/DatabaseStoreMultipartFile.cs@@ -15,7 +15,7 @@ public class DatabaseStoreMultipartFile(DavDatabaseClient dbClient,UsenetStreamingClient usenetClient,ConfigManager configManager-) : BaseStoreStreamFile+) : BaseStoreStreamFile(httpContext){public DavItem DavItem => davMultipartFile;public override string Name => davMultipartFile.Name;diff --git a/backend/WebDav/DatabaseStoreNzbFile.cs b/backend/WebDav/DatabaseStoreNzbFile.csindex 7e11efb6..9a0ac1a3 100644--- a/backend/WebDav/DatabaseStoreNzbFile.cs+++ b/backend/WebDav/DatabaseStoreNzbFile.cs@@ -13,7 +13,7 @@ public class DatabaseStoreNzbFile(DavDatabaseClient dbClient,INntpClient usenetClient,ConfigManager configManager-) : BaseStoreStreamFile+) : BaseStoreStreamFile(httpContext){public DavItem DavItem => davNzbFile;public override string Name => davNzbFile.Name;diff --git a/backend/WebDav/DatabaseStoreRarFile.cs b/backend/WebDav/DatabaseStoreRarFile.csindex 1af2b5fe..0310a8d6 100644--- a/backend/WebDav/DatabaseStoreRarFile.cs+++ b/backend/WebDav/DatabaseStoreRarFile.cs@@ -15,7 +15,7 @@ public class DatabaseStoreRarFile(DavDatabaseClient dbClient,UsenetStreamingClient usenetClient,ConfigManager configManager-) : BaseStoreStreamFile+) : BaseStoreStreamFile(httpContext){public DavItem DavItem => davRarFile;public override string Name => davRarFile.Name;