Skip to content

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

C#

Added MultiSegmentStream with optimized buffering.

nzbdav-dev5970ad3372c8
diff --git a/backend/Config/ConfigManager.cs b/backend/Config/ConfigManager.cs
index 7c6fde5b..2c14ce2e 100644
--- a/backend/Config/ConfigManager.cs
+++ b/backend/Config/ConfigManager.cs
@@ -131,6 +131,14 @@ public class ConfigManager
);
}
+ public int GetArticleBufferSize()
+ {
+ return int.Parse(
+ StringUtil.EmptyToNull(GetConfigValue("usenet.article-buffer-size"))
+ ?? "40"
+ );
+ }
+
public SemaphorePriorityOdds GetStreamingPriority()
{
var stringValue = StringUtil.EmptyToNull(GetConfigValue("usenet.streaming-priority"));
diff --git a/backend/Streams/MultiSegmentStream.cs b/backend/Streams/MultiSegmentStream.cs
new file mode 100644
index 00000000..25226565
--- /dev/null
+++ b/backend/Streams/MultiSegmentStream.cs
@@ -0,0 +1,114 @@
+using System.Threading.Channels;
+using NzbWebDAV.Clients.Usenet;
+using NzbWebDAV.Clients.Usenet.Models;
+using UsenetSharp.Streams;
+
+namespace NzbWebDAV.Streams;
+
+public class MultiSegmentStream : FastReadOnlyNonSeekableStream
+{
+ private readonly Memory<string> _segmentIds;
+ private readonly INntpClient _usenetClient;
+ private readonly Channel<Task<Stream>> _streamTasks;
+ private readonly CancellationTokenSource _cts;
+ private Stream? _stream;
+ private bool _disposed;
+
+
+ public MultiSegmentStream(Memory<string> segmentIds, INntpClient usenetClient, int articleBufferSize)
+ {
+ _segmentIds = segmentIds;
+ _usenetClient = usenetClient;
+ _streamTasks = Channel.CreateBounded<Task<Stream>>(articleBufferSize);
+ _cts = new CancellationTokenSource();
+ _ = DownloadSegments(_cts.Token);
+ }
+
+ private async Task DownloadSegments(CancellationToken cancellationToken)
+ {
+ try
+ {
+ for (var i = 0; i < _segmentIds.Length; i++)
+ {
+ var segmentId = _segmentIds.Span[i];
+
+ await _streamTasks.Writer.WaitToWriteAsync(cancellationToken);
+ var connection = await _usenetClient.AcquireExclusiveConnectionAsync(segmentId, cancellationToken);
+ var streamTask = DownloadSegment(segmentId, connection, cancellationToken);
+ if (_streamTasks.Writer.TryWrite(streamTask)) continue;
+
+ // if we never get a chance to write the stream to the writer
+ // then make sure the stream gets disposed.
+ _ = Task.Run(async () => await (await streamTask).DisposeAsync(), CancellationToken.None);
+ break;
+ }
+ }
+ finally
+ {
+ _streamTasks.Writer.TryComplete();
+ }
+
+ return;
+ }
+
+ private async Task<Stream> DownloadSegment
+ (
+ string segmentId,
+ UsenetExclusiveConnection exclusiveConnection,
+ CancellationToken cancellationToken
+ )
+ {
+ var bodyResponse = await _usenetClient
+ .DecodedBodyAsync(segmentId, exclusiveConnection, cancellationToken)
+ .ConfigureAwait(false);
+ return bodyResponse.Stream;
+ }
+
+ public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
+ {
+ ThrowIfDisposed();
+
+ while (!cancellationToken.IsCancellationRequested)
+ {
+ // if the stream is null, get the next stream.
+ if (_stream == null)
+ {
+ if (!await _streamTasks.Reader.WaitToReadAsync(cancellationToken)) return 0;
+ if (!_streamTasks.Reader.TryRead(out var streamTask)) return 0;
+ _stream = await streamTask;
+ }
+
+ // read from the stream
+ var read = await _stream.ReadAsync(buffer, cancellationToken);
+ if (read > 0) return read;
+
+ // if the stream ended, continue to the next stream.
+ await _stream.DisposeAsync();
+ _stream = null;
+ }
+
+ return 0;
+ }
+
+ private void ThrowIfDisposed()
+ {
+ ObjectDisposedException.ThrowIf(_disposed, this);
+ }
+
+ protected override void Dispose(bool disposing)
+ {
+ if (_disposed) return;
+ if (!disposing) return;
+ _disposed = true;
+ _cts.Cancel();
+ _cts.Dispose();
+ _stream?.Dispose();
+ _streamTasks.Writer.TryComplete();
+
+ // ensure that streams that were never read from the channel get disposed
+ while (_streamTasks.Reader.TryRead(out var streamTask))
+ _ = Task.Run(async () => await (await streamTask).DisposeAsync(), CancellationToken.None);
+
+ base.Dispose();
+ }
+}
\ No newline at end of file
diff --git a/backend/Streams/NzbFileStream.cs b/backend/Streams/NzbFileStream.cs
index 57ad2007..2ddbb345 100644
--- a/backend/Streams/NzbFileStream.cs
+++ b/backend/Streams/NzbFileStream.cs
@@ -15,7 +15,7 @@ public class NzbFileStream(
{
private long _position;
private bool _disposed;
- private CombinedStream? _innerStream;
+ private MultiSegmentStream? _innerStream;
public override bool CanSeek => true;
public override long Length => fileSize;
@@ -67,22 +67,20 @@ public class NzbFileStream(
).ConfigureAwait(false);
}
- private async Task<CombinedStream> GetFileStream(long rangeStart, CancellationToken cancellationToken)
+ private async Task<MultiSegmentStream> GetFileStream(long rangeStart, CancellationToken cancellationToken)
{
- if (rangeStart == 0) return GetCombinedStream(0, cancellationToken);
+ if (rangeStart == 0) return GetMultiSegmentStream(0);
var foundSegment = await SeekSegment(rangeStart, cancellationToken).ConfigureAwait(false);
- var stream = GetCombinedStream(foundSegment.FoundIndex, cancellationToken);
- await stream.DiscardBytesAsync(rangeStart - foundSegment.FoundByteRange.StartInclusive).ConfigureAwait(false);
+ var stream = GetMultiSegmentStream(foundSegment.FoundIndex);
+ await stream.DiscardBytesAsync(rangeStart - foundSegment.FoundByteRange.StartInclusive, cancellationToken)
+ .ConfigureAwait(false);
return stream;
}
- private CombinedStream GetCombinedStream(int firstSegmentIndex, CancellationToken ct)
+ private MultiSegmentStream GetMultiSegmentStream(int firstSegmentIndex)
{
- return new CombinedStream(
- fileSegmentIds[firstSegmentIndex..]
- .Select(async x => (Stream)(await usenetClient.DecodedBodyAsync(x, ct).ConfigureAwait(false)).Stream)
- .WithConcurrency(articleBufferSize)
- );
+ var segmentIds = fileSegmentIds.AsMemory()[firstSegmentIndex..];
+ return new MultiSegmentStream(segmentIds, usenetClient, articleBufferSize);
}
protected override void Dispose(bool disposing)
diff --git a/backend/WebDav/DatabaseStoreMultipartFile.cs b/backend/WebDav/DatabaseStoreMultipartFile.cs
index 2f736ecf..565d2a92 100644
--- a/backend/WebDav/DatabaseStoreMultipartFile.cs
+++ b/backend/WebDav/DatabaseStoreMultipartFile.cs
@@ -35,7 +35,7 @@ public class DatabaseStoreMultipartFile(
var packedStream = new DavMultipartFileStream(
multipartFile.Metadata.FileParts,
usenetClient,
- configManager.GetMaxDownloadConnections()
+ configManager.GetArticleBufferSize()
);
return multipartFile.Metadata.AesParams != null
? new AesDecoderStream(packedStream, multipartFile.Metadata.AesParams)
diff --git a/backend/WebDav/DatabaseStoreNzbFile.cs b/backend/WebDav/DatabaseStoreNzbFile.cs
index 09a6a104..a6b5680a 100644
--- a/backend/WebDav/DatabaseStoreNzbFile.cs
+++ b/backend/WebDav/DatabaseStoreNzbFile.cs
@@ -30,6 +30,6 @@ public class DatabaseStoreNzbFile(
var id = davNzbFile.Id;
var file = await dbClient.GetNzbFileAsync(id, cancellationToken).ConfigureAwait(false);
if (file is null) throw new FileNotFoundException($"Could not find nzb file with id: {id}");
- return usenetClient.GetFileStream(file.SegmentIds, FileSize, configManager.GetMaxDownloadConnections());
+ return usenetClient.GetFileStream(file.SegmentIds, FileSize, configManager.GetArticleBufferSize());
}
}
\ No newline at end of file
diff --git a/backend/WebDav/DatabaseStoreRarFile.cs b/backend/WebDav/DatabaseStoreRarFile.cs
index d045724a..98b06a71 100644
--- a/backend/WebDav/DatabaseStoreRarFile.cs
+++ b/backend/WebDav/DatabaseStoreRarFile.cs
@@ -36,7 +36,7 @@ public class DatabaseStoreRarFile(
(
rarFile.ToDavMultipartFileMeta().FileParts,
usenetClient,
- configManager.GetMaxDownloadConnections()
+ configManager.GetArticleBufferSize()
);
}
}
\ No newline at end of file