Skip to content

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

C#

Refactored Streams to use fast memory apis.

nzbdav-dev31ae2feaec36
diff --git a/backend/Extensions/StreamExtensions.cs b/backend/Extensions/StreamExtensions.cs
index 53aac57e..55a4a9a6 100644
--- a/backend/Extensions/StreamExtensions.cs
+++ b/backend/Extensions/StreamExtensions.cs
@@ -1,4 +1,5 @@
-using NzbWebDAV.Streams;
+using System.Buffers;
+using NzbWebDAV.Streams;
namespace NzbWebDAV.Extensions;
@@ -9,10 +10,25 @@ public static class StreamExtensions
return new LimitedLengthStream(stream, length);
}
- public static void Drain(this Stream stream)
+ public static async Task DiscardBytesAsync(this Stream stream, long count, CancellationToken ct = default)
{
- var buffer = new byte[1024];
- while (stream.Read(buffer, 0, buffer.Length) > 0) ;
+ if (count == 0) return;
+ var remaining = count;
+ var throwaway = ArrayPool<byte>.Shared.Rent(1024);
+ try
+ {
+ while (remaining > 0)
+ {
+ var toRead = (int)Math.Min(remaining, throwaway.Length);
+ var read = await stream.ReadAsync(throwaway.AsMemory(0, toRead), ct).ConfigureAwait(false);
+ if (read == 0) break;
+ remaining -= read;
+ }
+ }
+ finally
+ {
+ ArrayPool<byte>.Shared.Return(throwaway);
+ }
}
public static Stream OnDispose(this Stream stream, Action onDispose)
diff --git a/backend/Streams/BufferToEndStream.cs b/backend/Streams/BufferToEndStream.cs
deleted file mode 100644
index 9cd993fd..00000000
--- a/backend/Streams/BufferToEndStream.cs
+++ /dev/null
@@ -1,241 +0,0 @@
-using System.Buffers;
-using System.IO.Pipelines;
-using System.Runtime.ExceptionServices;
-using NzbWebDAV.Utils;
-
-namespace NzbWebDAV.Streams;
-
-/// <summary>
-/// Wraps a readable <see cref="Stream"/>.
-/// • As soon as it is constructed it begins copying every byte
-/// from <paramref name="sourceStream"/> into memory.
-/// • Callers can read while the copy is in progress, but even if
-/// they never read (or dispose early) the copy continues in the
-/// background
-/// • Drains the source to EOF, then disposes it.
-/// • Dispose / DisposeAsync are non-blocking; they simply mark the public
-/// wrapper dead and release any waiting readers.
-/// • Note: This class was entirely authored by ChatGPT o3
-/// </summary>
-public sealed class BufferToEndStream : Stream
-{
- // ─────────────────────────────────── configuration
- private readonly int _segmentSize;
-
- // ─────────────────────────────────── pipeline & pump
- private readonly Pipe _pipe;
- private readonly Task _pumpTask;
-
- // ─────────────────────────────────── coordination primitives
- private readonly CancellationTokenSource _localCts = new();
- private readonly SemaphoreSlim _readLock = new(1, 1);
-
- private volatile Exception? _backgroundError;
- private volatile bool _publiclyDisposed;
- private int _coreDisposed; // 0 ⇒ alive, 1 ⇒ core cleaned up
-
- // ─────────────────────────────────── constructor
- public BufferToEndStream(
- Stream sourceStream,
- int minimumSegmentSize = 1024,
- long pauseWriterThreshold = long.MaxValue,
- long resumeWriterThreshold = long.MaxValue - 1)
- {
- if (sourceStream is null) throw new ArgumentNullException(nameof(sourceStream));
- if (!sourceStream.CanRead) throw new ArgumentException("Stream must be readable.", nameof(sourceStream));
-
- _segmentSize = Math.Max(256, minimumSegmentSize);
-
- _pipe = new Pipe(new PipeOptions(
- pool: null, // default pool
- readerScheduler: PipeScheduler.ThreadPool,
- writerScheduler: PipeScheduler.ThreadPool,
- pauseWriterThreshold: pauseWriterThreshold,
- resumeWriterThreshold: resumeWriterThreshold,
- minimumSegmentSize: _segmentSize,
- useSynchronizationContext: false));
-
- _pumpTask = Task.Run(() => PumpAsync(sourceStream), SigtermUtil.GetCancellationToken());
- }
-
- // ─────────────────────────────────── background producer
- private async Task PumpAsync(Stream source)
- {
- byte[] scratch = ArrayPool<byte>.Shared.Rent(_segmentSize);
-
- try
- {
- while (true)
- {
- int read = await source.ReadAsync(scratch, 0, scratch.Length).ConfigureAwait(false);
- if (read == 0) break; // EOF
-
- if (!_publiclyDisposed) // normal mode: write to Pipe
- {
- await _pipe.Writer.WriteAsync(
- scratch.AsMemory(0, read),
- SigtermUtil.GetCancellationToken()).ConfigureAwait(false);
- }
- // else: wrapper already disposed → just discard into 'scratch'
- }
-
- _pipe.Writer.Complete(); // clean completion
- }
- catch (Exception ex) when (ex is not OperationCanceledException)
- {
- _backgroundError = ex;
- _pipe.Writer.Complete(ex); // propagate to readers
- }
- finally
- {
- source.Dispose(); // ALWAYS reached
- ArrayPool<byte>.Shared.Return(scratch);
- }
- }
-
- // ─────────────────────────────────── core read helper
- private async ValueTask<int> ReadCoreAsync(
- Memory<byte> destination,
- CancellationToken cancellationToken)
- {
- ThrowIfCoreDisposed();
- if (destination.Length == 0) return 0;
-
- using var linked = CancellationTokenSource
- .CreateLinkedTokenSource(_localCts.Token, cancellationToken);
-
- await _readLock.WaitAsync(linked.Token).ConfigureAwait(false);
- try
- {
- while (true)
- {
- ReadResult result = await _pipe.Reader
- .ReadAsync(linked.Token)
- .ConfigureAwait(false);
- var buffer = result.Buffer;
-
- if (!buffer.IsEmpty)
- {
- int n = (int)Math.Min(buffer.Length, destination.Length);
- buffer.Slice(0, n).CopyTo(destination.Span);
- _pipe.Reader.AdvanceTo(buffer.GetPosition(n));
- return n;
- }
-
- if (result.IsCompleted)
- {
- _pipe.Reader.AdvanceTo(buffer.End);
-
- if (_backgroundError is not null)
- ExceptionDispatchInfo.Capture(_backgroundError).Throw();
-
- return 0; // true EOF
- }
-
- _pipe.Reader.AdvanceTo(buffer.Start, buffer.End); // nothing yet → loop
- }
- }
- finally
- {
- _readLock.Release();
- }
- }
-
- // ─────────────────────────────────── Stream overrides
- public override int Read(Span<byte> buffer)
- {
- // simple sync path – allocate once then copy
- byte[] tmp = ArrayPool<byte>.Shared.Rent(buffer.Length);
- try
- {
- int read = ReadCoreAsync(tmp.AsMemory(0, buffer.Length), SigtermUtil.GetCancellationToken())
- .AsTask().GetAwaiter().GetResult();
- tmp.AsSpan(0, read).CopyTo(buffer);
- return read;
- }
- finally
- {
- ArrayPool<byte>.Shared.Return(tmp);
- }
- }
-
- public override int Read(byte[] array, int offset, int count) =>
- Read(array.AsSpan(offset, count));
-
- public override ValueTask<int> ReadAsync(
- Memory<byte> buffer,
- CancellationToken cancellationToken = default) =>
- ReadCoreAsync(buffer, cancellationToken);
-
- public override Task<int> ReadAsync(
- byte[] array, int offset, int count, CancellationToken cancellationToken) =>
- ReadCoreAsync(array.AsMemory(offset, count), cancellationToken).AsTask();
-
- // ─────────────────────────────────── Dispose pattern
- protected override void Dispose(bool disposing)
- {
- if (Interlocked.Exchange(ref _coreDisposed, 1) == 1) return;
-
- if (disposing)
- {
- _publiclyDisposed = true; // pump switches to discard mode
- _localCts.Cancel(); // cancel any waiting readers
- _readLock.Dispose(); // forbid further reads
-
- try { _pipe.Reader.Complete(); } // maybe already done – ignore
- catch (InvalidOperationException) { }
- }
-
- base.Dispose(disposing); // returns immediately
- }
-
- public override async ValueTask DisposeAsync()
- {
- if (Interlocked.Exchange(ref _coreDisposed, 1) == 1) return;
-
- _publiclyDisposed = true;
- _localCts.Cancel();
- _readLock.Dispose();
-
- try { _pipe.Reader.Complete(); }
- catch (InvalidOperationException) { }
-
- await base.DisposeAsync().ConfigureAwait(false); // still non-blocking
- }
-
- // ─────────────────────────────────── plumbing
- public override bool CanRead => _coreDisposed == 0;
- public override bool CanSeek => false;
- public override bool CanWrite => false;
-
- public override long Length => throw new NotSupportedException();
- public override long Position
- {
- get => throw new NotSupportedException();
- set => throw new NotSupportedException();
- }
-
- public override void Flush() =>
- throw new NotSupportedException();
- public override Task FlushAsync(CancellationToken _) =>
- throw new NotSupportedException();
-
- public override long Seek(long _, SeekOrigin __) =>
- throw new NotSupportedException();
- public override void SetLength(long _) =>
- throw new NotSupportedException();
-
- public override void Write(byte[] _, int __, int ___) =>
- throw new NotSupportedException();
- public override void Write(ReadOnlySpan<byte> _) =>
- throw new NotSupportedException();
- public override ValueTask WriteAsync(ReadOnlyMemory<byte> _, CancellationToken __ = default) =>
- throw new NotSupportedException();
-
- // ─────────────────────────────────── helpers
- private void ThrowIfCoreDisposed()
- {
- if (_coreDisposed != 0)
- throw new ObjectDisposedException(nameof(BufferToEndStream));
- }
-}
diff --git a/backend/Streams/CombinedStream.cs b/backend/Streams/CombinedStream.cs
index b6a75cb9..6951c63a 100644
--- a/backend/Streams/CombinedStream.cs
+++ b/backend/Streams/CombinedStream.cs
@@ -1,31 +1,23 @@
-namespace NzbWebDAV.Streams;
+using UsenetSharp.Streams;
-public class CombinedStream(IEnumerable<Task<Stream>> streams) : Stream
+namespace NzbWebDAV.Streams;
+
+public class CombinedStream(IEnumerable<Task<Stream>> streams) : FastReadOnlyNonSeekableStream
{
private readonly IEnumerator<Task<Stream>> _streams = streams.GetEnumerator();
private Stream? _currentStream;
private long _position;
private bool _isDisposed;
- public override bool CanRead => true;
- public override bool CanSeek => false;
- public override bool CanWrite => false;
- public override long Length => throw new NotSupportedException();
-
public override long Position
{
get => _position;
set => throw new NotSupportedException();
}
- public override int Read(byte[] buffer, int offset, int count)
- {
- return ReadAsync(buffer, offset, count).GetAwaiter().GetResult();
- }
-
- public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
+ public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
{
- if (count == 0) return 0;
+ if (buffer.Length == 0) return 0;
while (!cancellationToken.IsCancellationRequested)
{
// If we haven't read the first stream, read it.
@@ -36,11 +28,7 @@ public class CombinedStream(IEnumerable<Task<Stream>> streams) : Stream
}
// read from our current stream
- var readCount = await _currentStream.ReadAsync
- (
- buffer.AsMemory(offset, count),
- cancellationToken
- ).ConfigureAwait(false);
+ var readCount = await _currentStream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false);
_position += readCount;
if (readCount > 0) return readCount;
@@ -54,40 +42,14 @@ public class CombinedStream(IEnumerable<Task<Stream>> streams) : Stream
return 0;
}
- public async Task DiscardBytesAsync(long count)
- {
- if (count == 0) return;
- var remaining = count;
- var throwaway = new byte[1024];
- while (remaining > 0)
- {
- var toRead = (int)Math.Min(remaining, throwaway.Length);
- var read = await ReadAsync(throwaway, 0, toRead).ConfigureAwait(false);
- remaining -= read;
- if (read == 0) break;
- }
-
- _position += count;
- }
-
public override void Flush()
{
- throw new NotSupportedException();
- }
-
- public override long Seek(long offset, SeekOrigin origin)
- {
- throw new NotSupportedException();
- }
-
- public override void SetLength(long value)
- {
- throw new NotSupportedException();
+ _currentStream?.Flush();
}
- public override void Write(byte[] buffer, int offset, int count)
+ public override Task FlushAsync(CancellationToken cancellationToken)
{
- throw new NotSupportedException();
+ return _currentStream?.FlushAsync(cancellationToken) ?? Task.CompletedTask;
}
protected override void Dispose(bool disposing)
diff --git a/backend/Streams/LimitedLengthStream.cs b/backend/Streams/LimitedLengthStream.cs
index ce371c77..3b299ed0 100644
--- a/backend/Streams/LimitedLengthStream.cs
+++ b/backend/Streams/LimitedLengthStream.cs
@@ -1,20 +1,20 @@
-using NzbWebDAV.Utils;
+using UsenetSharp.Streams;
namespace NzbWebDAV.Streams;
-public class LimitedLengthStream(Stream stream, long length) : Stream
+public class LimitedLengthStream(Stream stream, long length) : FastReadOnlyNonSeekableStream
{
+ private long _position;
private bool _disposed;
- private long _position = 0;
+ public override long Length => length;
public override void Flush() => stream.Flush();
- public override int Read(byte[] buffer, int offset, int count) =>
- ReadAsync(buffer, offset, count, SigtermUtil.GetCancellationToken()).GetAwaiter().GetResult();
-
- public override async Task<int>
- ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
- await ReadAsync(buffer.AsMemory(offset, count), cancellationToken).ConfigureAwait(false);
+ public override long Position
+ {
+ get => stream.Position;
+ set => throw new NotSupportedException();
+ }
public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
{
@@ -36,21 +36,6 @@ public class LimitedLengthStream(Stream stream, long length) : Stream
return bytesRead;
}
- public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
- public override void SetLength(long value) => throw new NotSupportedException();
- public override void Write(byte[] buffer, int offset, int count) => stream.Write(buffer, offset, count);
-
- public override bool CanRead => stream.CanRead;
- public override bool CanSeek => false;
- public override bool CanWrite => false;
- public override long Length => length;
-
- public override long Position
- {
- get => stream.Position;
- set => throw new NotSupportedException();
- }
-
protected override void Dispose(bool disposing)
{
if (_disposed) return;
diff --git a/backend/Streams/MultipartFileStream.cs b/backend/Streams/MultipartFileStream.cs
index 76dbaf26..3947ed44 100644
--- a/backend/Streams/MultipartFileStream.cs
+++ b/backend/Streams/MultipartFileStream.cs
@@ -1,21 +1,18 @@
using NzbWebDAV.Clients.Usenet;
using NzbWebDAV.Models;
using NzbWebDAV.Utils;
+using UsenetSharp.Streams;
namespace NzbWebDAV.Streams;
-public class MultipartFileStream : Stream
+public class MultipartFileStream(MultipartFile multipartFile, INntpClient usenetClient) : FastReadOnlyStream
{
+ private long _position;
private bool _isDisposed;
- private readonly INntpClient _usenetClient;
- private readonly MultipartFile _multipartFile;
private Stream? _currentStream;
- private long _position = 0;
- public override bool CanRead => true;
public override bool CanSeek => true;
- public override bool CanWrite => false;
- public override long Length => _multipartFile.FileSize;
+ public override long Length => multipartFile.FileSize;
public override long Position
{
@@ -23,31 +20,21 @@ public class MultipartFileStream : Stream
set => throw new NotSupportedException();
}
- public MultipartFileStream(MultipartFile multipartFile, INntpClient usenetClient)
- {
- _multipartFile = multipartFile;
- _usenetClient = usenetClient;
- }
-
public override int Read(byte[] buffer, int offset, int count)
{
return ReadAsync(buffer, offset, count).GetAwaiter().GetResult();
}
- public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
+ public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
{
- if (count == 0) return 0;
+ if (buffer.Length == 0) return 0;
while (_position < Length && !cancellationToken.IsCancellationRequested)
{
// If we haven't read the first stream, read it.
_currentStream ??= GetCurrentStream();
// read from our current stream
- var readCount = await _currentStream.ReadAsync
- (
- buffer.AsMemory(offset, count),
- cancellationToken
- ).ConfigureAwait(false);
+ var readCount = await _currentStream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false);
_position += readCount;
if (readCount > 0) return readCount;
@@ -60,17 +47,17 @@ public class MultipartFileStream : Stream
return 0;
}
- private Stream GetCurrentStream()
+ private NzbFileStream GetCurrentStream()
{
var searchResult = InterpolationSearch.Find(
_position,
- new LongRange(0, _multipartFile.FileParts.Count),
+ new LongRange(0, multipartFile.FileParts.Count),
new LongRange(0, Length),
- guess => _multipartFile.FileParts[guess].ByteRange
+ guess => multipartFile.FileParts[guess].ByteRange
);
- var filePart = _multipartFile.FileParts[searchResult.FoundIndex];
- var stream = _usenetClient.GetFileStream(filePart.NzbFile, filePart.PartSize, concurrentConnections: 1);
+ var filePart = multipartFile.FileParts[searchResult.FoundIndex];
+ var stream = usenetClient.GetFileStream(filePart.NzbFile, filePart.PartSize, concurrentConnections: 1);
stream.Seek(_position - searchResult.FoundByteRange.StartInclusive, SeekOrigin.Begin);
return stream;
}
@@ -92,16 +79,6 @@ public class MultipartFileStream : Stream
_currentStream?.Flush();
}
- public override void SetLength(long value)
- {
- throw new NotSupportedException();
- }
-
- public override void Write(byte[] buffer, int offset, int count)
- {
- throw new NotSupportedException();
- }
-
protected override void Dispose(bool disposing)
{
if (_isDisposed) return;
diff --git a/backend/Streams/NzbFileStream.cs b/backend/Streams/NzbFileStream.cs
index 525d3cc3..48e2b259 100644
--- a/backend/Streams/NzbFileStream.cs
+++ b/backend/Streams/NzbFileStream.cs
@@ -2,6 +2,7 @@
using NzbWebDAV.Extensions;
using NzbWebDAV.Models;
using NzbWebDAV.Utils;
+using UsenetSharp.Streams;
namespace NzbWebDAV.Streams;
@@ -10,27 +11,31 @@ public class NzbFileStream(
long fileSize,
INntpClient client,
int concurrency
-) : Stream
+) : FastReadOnlyStream
{
- private long _position = 0;
- private CombinedStream? _innerStream;
+ private long _position;
private bool _disposed;
+ private CombinedStream? _innerStream;
- public override void Flush()
+ public override bool CanSeek => true;
+ public override long Length => fileSize;
+
+ public override long Position
{
- _innerStream?.Flush();
+ get => _position;
+ set => Seek(value, SeekOrigin.Begin);
}
- public override int Read(byte[] buffer, int offset, int count)
+ public override void Flush()
{
- return ReadAsync(buffer, offset, count).GetAwaiter().GetResult();
+ _innerStream?.Flush();
}
- public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
+ public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
{
if (_innerStream == null)
_innerStream = await GetFileStream(_position, cancellationToken).ConfigureAwait(false);
- var read = await _innerStream.ReadAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false);
+ var read = await _innerStream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false);
_position += read;
return read;
}
@@ -47,28 +52,6 @@ public class NzbFileStream(
return _position;
}
- public override void SetLength(long value)
- {
- throw new InvalidOperationException();
- }
-
- public override void Write(byte[] buffer, int offset, int count)
- {
- throw new InvalidOperationException();
- }
-
- public override bool CanRead => true;
- public override bool CanSeek => true;
- public override bool CanWrite => false;
- public override long Length => fileSize;
-
- public override long Position
- {
- get => _position;
- set => Seek(value, SeekOrigin.Begin);
- }
-
-
private async Task<InterpolationSearch.Result> SeekSegment(long byteOffset, CancellationToken ct)
{
return await InterpolationSearch.Find(