Skip to content

Usenet streaming with a WebDAV server and a SABnzbd-compatible API

C#

Added ArticleCachingNntpClient.

nzbdav-deva21b3b01ad78
diff --git a/backend/Clients/Usenet/ArticleCachingNntpClient.cs b/backend/Clients/Usenet/ArticleCachingNntpClient.cs
new file mode 100644
index 00000000..81bc8561
--- /dev/null
+++ b/backend/Clients/Usenet/ArticleCachingNntpClient.cs
@@ -0,0 +1,221 @@
+using System.Collections.Concurrent;
+using System.Security.Cryptography;
+using System.Text;
+using NzbWebDAV.Clients.Usenet.Models;
+using NzbWebDAV.Streams;
+using UsenetSharp.Models;
+using UsenetSharp.Streams;
+
+namespace NzbWebDAV.Clients.Usenet;
+
+/// <summary>
+/// This client is responsible for caching Article/Body commands to disk.
+/// It is intended to be short-lived. It will delete all cached articles on disposal.
+/// </summary>
+/// <param name="usenetClient">The underlying client to cache.</param>
+/// <param name="leaveOpen">Indicates whether disposing this client also disposes the underlying client.</param>
+public class ArticleCachingNntpClient(INntpClient usenetClient, bool leaveOpen = true) : WrappingNntpClient(usenetClient)
+{
+ private readonly string _cacheDir = Directory.CreateTempSubdirectory().FullName;
+ private readonly ConcurrentDictionary<string, SemaphoreSlim> _pendingRequests = new();
+ private readonly ConcurrentDictionary<string, CacheEntry> _cachedSegments = new();
+
+ private record CacheEntry(
+ UsenetYencHeader YencHeaders,
+ bool HasArticleHeaders,
+ UsenetArticleHeader? ArticleHeaders);
+
+ public override Task<UsenetDecodedBodyResponse> DecodedBodyAsync(
+ SegmentId segmentId, Action<ArticleBodyResult>? onConnectionReadyAgain, CancellationToken cancellationToken)
+ {
+ throw new NotImplementedException();
+ }
+
+ public override Task<UsenetDecodedArticleResponse> DecodedArticleAsync(
+ SegmentId segmentId, Action<ArticleBodyResult>? onConnectionReadyAgain, CancellationToken cancellationToken)
+ {
+ throw new NotImplementedException();
+ }
+
+ public override async Task<UsenetDecodedBodyResponse> DecodedBodyAsync(
+ SegmentId segmentId, CancellationToken cancellationToken)
+ {
+ var semaphore = _pendingRequests.GetOrAdd(segmentId, _ => new SemaphoreSlim(1, 1));
+
+ await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
+ try
+ {
+ // Check if already cached
+ if (_cachedSegments.TryGetValue(segmentId, out var existingEntry))
+ {
+ return ReadCachedBodyAsync(segmentId, existingEntry.YencHeaders);
+ }
+
+ // Fetch and cache the body
+ var response = await base.DecodedBodyAsync(segmentId, cancellationToken)
+ .ConfigureAwait(false);
+
+ // Get the decoded stream
+ await using var stream = response.Stream;
+
+ // Get yenc headers before caching the decoded stream
+ var yencHeaders = await stream.GetYencHeadersAsync(cancellationToken).ConfigureAwait(false);
+ if (yencHeaders == null)
+ {
+ throw new InvalidOperationException($"Failed to read yenc headers for segment {segmentId}");
+ }
+
+ await CacheDecodedStreamAsync(segmentId, stream, cancellationToken).ConfigureAwait(false);
+
+ // Mark as cached (body only, no article headers yet)
+ _cachedSegments.TryAdd(segmentId, new CacheEntry(
+ YencHeaders: yencHeaders,
+ HasArticleHeaders: false,
+ ArticleHeaders: null));
+
+ // Return a new stream from the cached file
+ return ReadCachedBodyAsync(segmentId, yencHeaders);
+ }
+ finally
+ {
+ semaphore.Release();
+ }
+ }
+
+ public override async Task<UsenetDecodedArticleResponse> DecodedArticleAsync(
+ SegmentId segmentId, CancellationToken cancellationToken)
+ {
+ var semaphore = _pendingRequests.GetOrAdd(segmentId, _ => new SemaphoreSlim(1, 1));
+
+ await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
+ try
+ {
+ // Check if already cached with headers
+ if (_cachedSegments.TryGetValue(segmentId, out var cacheEntry))
+ {
+ if (cacheEntry.HasArticleHeaders)
+ {
+ // Full article is cached, read from cache
+ return ReadCachedArticleAsync(segmentId, cacheEntry.YencHeaders, cacheEntry.ArticleHeaders!);
+ }
+ else
+ {
+ // Only body is cached, fetch article headers separately
+ var headResponse = await base.HeadAsync(segmentId, cancellationToken).ConfigureAwait(false);
+
+ // Update cache entry to include article headers
+ var updatedEntry = new CacheEntry(
+ YencHeaders: cacheEntry.YencHeaders,
+ HasArticleHeaders: true,
+ ArticleHeaders: headResponse.ArticleHeaders);
+
+ _cachedSegments.TryUpdate(segmentId, updatedEntry, cacheEntry);
+
+ return ReadCachedArticleAsync(segmentId, cacheEntry.YencHeaders, headResponse.ArticleHeaders!);
+ }
+ }
+
+ // Fetch and cache the full article
+ var response = await base.DecodedArticleAsync(segmentId, cancellationToken)
+ .ConfigureAwait(false);
+
+ // Get the decoded stream
+ await using var stream = response.Stream;
+
+ // Get yenc headers before caching the decoded stream
+ var yencHeaders = await stream.GetYencHeadersAsync(cancellationToken).ConfigureAwait(false);
+ if (yencHeaders == null)
+ {
+ throw new InvalidOperationException($"Failed to read yenc headers for segment {segmentId}");
+ }
+
+ await CacheDecodedStreamAsync(segmentId, stream, cancellationToken).ConfigureAwait(false);
+
+ // Mark as cached with both yenc and article headers
+ _cachedSegments.TryAdd(segmentId, new CacheEntry(
+ YencHeaders: yencHeaders,
+ HasArticleHeaders: true,
+ ArticleHeaders: response.ArticleHeaders));
+
+ // Return a new stream from the cached file
+ return ReadCachedArticleAsync(segmentId, yencHeaders, response.ArticleHeaders);
+ }
+ finally
+ {
+ semaphore.Release();
+ }
+ }
+
+ public override Task<UsenetYencHeader> GetYencHeadersAsync(string segmentId, CancellationToken ct)
+ {
+ return _cachedSegments.TryGetValue(segmentId, out var existingEntry)
+ ? Task.FromResult(existingEntry.YencHeaders)
+ : base.GetYencHeadersAsync(segmentId, ct);
+ }
+
+ private async Task CacheDecodedStreamAsync(string segmentId, YencStream stream, CancellationToken cancellationToken)
+ {
+ var cachePath = GetCachePath(segmentId);
+ await using var fileStream = new FileStream(cachePath, FileMode.Create, FileAccess.Write, FileShare.None,
+ bufferSize: 81920, useAsync: true);
+ await stream.CopyToAsync(fileStream, cancellationToken).ConfigureAwait(false);
+ }
+
+ private UsenetDecodedBodyResponse ReadCachedBodyAsync(string segmentId, UsenetYencHeader yencHeaders)
+ {
+ var cachePath = GetCachePath(segmentId);
+ var fileStream = new FileStream(cachePath, FileMode.Open, FileAccess.Read, FileShare.Read,
+ bufferSize: 81920, useAsync: true);
+
+ return new UsenetDecodedBodyResponse
+ {
+ SegmentId = segmentId,
+ ResponseCode = (int)UsenetResponseType.ArticleRetrievedBodyFollows,
+ ResponseMessage = "222 - Article retrieved from file cache",
+ Stream = new CachedYencStream(yencHeaders, fileStream)
+ };
+ }
+
+ private UsenetDecodedArticleResponse ReadCachedArticleAsync(
+ string segmentId, UsenetYencHeader yencHeaders, UsenetArticleHeader articleHeaders)
+ {
+ var cachePath = GetCachePath(segmentId);
+ var fileStream = new FileStream(cachePath, FileMode.Open, FileAccess.Read, FileShare.Read,
+ bufferSize: 81920, useAsync: true);
+
+ return new UsenetDecodedArticleResponse
+ {
+ SegmentId = segmentId,
+ ResponseCode = (int)UsenetResponseType.ArticleRetrievedHeadAndBodyFollow,
+ ResponseMessage = "220 - Article retrieved from cache",
+ ArticleHeaders = articleHeaders,
+ Stream = new CachedYencStream(yencHeaders, fileStream)
+ };
+ }
+
+ private string GetCachePath(string segmentId)
+ {
+ // Use SHA256 hash of segment ID to create a valid filename
+ var hash = SHA256.HashData(Encoding.UTF8.GetBytes(segmentId));
+ var filename = Convert.ToHexString(hash);
+ return Path.Combine(_cacheDir, filename);
+ }
+
+ public override void Dispose()
+ {
+ // Dispose the underlying client
+ // only when leaveOpen is false.
+ if (!leaveOpen)
+ base.Dispose();
+
+ // Clean up semaphores
+ foreach (var semaphore in _pendingRequests.Values)
+ semaphore.Dispose();
+
+ _pendingRequests.Clear();
+ _cachedSegments.Clear();
+
+ Task.Run(() => Directory.Delete(_cacheDir, recursive: true));
+ GC.SuppressFinalize(this);
+ }
+}
\ No newline at end of file
diff --git a/backend/NzbWebDAV.csproj b/backend/NzbWebDAV.csproj
index 8bc94b7c..6cf80bd7 100644
--- a/backend/NzbWebDAV.csproj
+++ b/backend/NzbWebDAV.csproj
@@ -19,7 +19,7 @@
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.1-dev-00953" />
<PackageReference Include="SharpCompress" Version="0.39.0" />
<PackageReference Include="Usenet" Version="3.1.0" />
- <PackageReference Include="UsenetSharp" Version="1.0.2" />
+ <PackageReference Include="UsenetSharp" Version="1.0.3" />
</ItemGroup>
<ItemGroup>
diff --git a/backend/Streams/CachedYencStream.cs b/backend/Streams/CachedYencStream.cs
new file mode 100644
index 00000000..2b47213a
--- /dev/null
+++ b/backend/Streams/CachedYencStream.cs
@@ -0,0 +1,41 @@
+using UsenetSharp.Models;
+using UsenetSharp.Streams;
+
+namespace NzbWebDAV.Streams;
+
+/// <summary>
+/// A YencStream that reads from already-decoded cached data instead of decoding yenc-encoded data.
+/// This stream bypasses the yenc decoding process by directly serving cached decoded bytes
+/// and returning pre-parsed yenc headers.
+/// </summary>
+public class CachedYencStream : YencStream
+{
+ private readonly UsenetYencHeader _cachedHeaders;
+ private readonly Stream _cachedDecodedStream;
+
+ public CachedYencStream(UsenetYencHeader cachedHeaders, Stream cachedDecodedStream) : base(Null)
+ {
+ _cachedHeaders = cachedHeaders ?? throw new ArgumentNullException(nameof(cachedHeaders));
+ _cachedDecodedStream = cachedDecodedStream ?? throw new ArgumentNullException(nameof(cachedDecodedStream));
+ }
+
+ public override ValueTask<UsenetYencHeader?> GetYencHeadersAsync(CancellationToken cancellationToken = default)
+ {
+ return ValueTask.FromResult<UsenetYencHeader?>(_cachedHeaders);
+ }
+
+ public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
+ {
+ return _cachedDecodedStream.ReadAsync(buffer, cancellationToken);
+ }
+
+ protected override void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
+ _cachedDecodedStream?.Dispose();
+ }
+
+ base.Dispose(disposing);
+ }
+}
\ No newline at end of file