Skip to content

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

C#

Replace all default cancellation tokens with sigterm-aware cancellation tokens.

nzbdav-devc4bfd05e94b4
diff --git a/backend/Clients/Usenet/Connections/ExtendedSemaphoreSlim.cs b/backend/Clients/Usenet/Connections/ExtendedSemaphoreSlim.cs
index b1a1da63..0ea403ed 100644
--- a/backend/Clients/Usenet/Connections/ExtendedSemaphoreSlim.cs
+++ b/backend/Clients/Usenet/Connections/ExtendedSemaphoreSlim.cs
@@ -1,4 +1,6 @@
-namespace NzbWebDAV.Clients.Usenet.Connections
+using NzbWebDAV.Utils;
+
+namespace NzbWebDAV.Clients.Usenet.Connections
{
/// <summary>
/// A semaphore-like primitive where each waiter specifies the number of
@@ -90,7 +92,7 @@
// Dispose registration when the wait completes in any way.
_ = tcs.Task.ContinueWith(static (_, s) => { ((CancellationTokenRegistration)s!).Dispose(); }, ctr,
- CancellationToken.None,
+ SigtermUtil.GetCancellationToken(),
TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
diff --git a/backend/Clients/Usenet/MultiConnectionNntpClient.cs b/backend/Clients/Usenet/MultiConnectionNntpClient.cs
index 6e814ac8..f0c49f32 100644
--- a/backend/Clients/Usenet/MultiConnectionNntpClient.cs
+++ b/backend/Clients/Usenet/MultiConnectionNntpClient.cs
@@ -1,5 +1,6 @@
using NzbWebDAV.Clients.Usenet.Connections;
using NzbWebDAV.Streams;
+using NzbWebDAV.Utils;
using Usenet.Exceptions;
using Usenet.Nntp.Responses;
using Usenet.Nzb;
@@ -67,7 +68,7 @@ public class MultiConnectionNntpClient(ConnectionPool<INntpClient> connectionPoo
// ReSharper disable once MethodSupportsCancellation
// we intentionally do not pass the cancellation token to ContinueWith,
// since we want the continuation to always run.
- _ = connectionLock.Connection.WaitForReady(CancellationToken.None)
+ _ = connectionLock.Connection.WaitForReady(SigtermUtil.GetCancellationToken())
.ContinueWith(_ => connectionLock.Dispose());
return result;
}
diff --git a/backend/Program.cs b/backend/Program.cs
index cbf9bcb9..7c706053 100644
--- a/backend/Program.cs
+++ b/backend/Program.cs
@@ -110,6 +110,7 @@ class Program
app.MapControllers();
app.UseAuthentication();
app.UseNWebDav();
+ app.Lifetime.ApplicationStopping.Register(SigtermUtil.Cancel);
await app.RunAsync();
}
diff --git a/backend/Streams/BufferToEndStream.cs b/backend/Streams/BufferToEndStream.cs
index 5b74de98..9cd993fd 100644
--- a/backend/Streams/BufferToEndStream.cs
+++ b/backend/Streams/BufferToEndStream.cs
@@ -1,6 +1,7 @@
using System.Buffers;
using System.IO.Pipelines;
using System.Runtime.ExceptionServices;
+using NzbWebDAV.Utils;
namespace NzbWebDAV.Streams;
@@ -54,7 +55,7 @@ public sealed class BufferToEndStream : Stream
minimumSegmentSize: _segmentSize,
useSynchronizationContext: false));
- _pumpTask = Task.Run(() => PumpAsync(sourceStream), CancellationToken.None);
+ _pumpTask = Task.Run(() => PumpAsync(sourceStream), SigtermUtil.GetCancellationToken());
}
// ─────────────────────────────────── background producer
@@ -73,7 +74,7 @@ public sealed class BufferToEndStream : Stream
{
await _pipe.Writer.WriteAsync(
scratch.AsMemory(0, read),
- CancellationToken.None).ConfigureAwait(false);
+ SigtermUtil.GetCancellationToken()).ConfigureAwait(false);
}
// else: wrapper already disposed → just discard into 'scratch'
}
@@ -147,7 +148,7 @@ public sealed class BufferToEndStream : Stream
byte[] tmp = ArrayPool<byte>.Shared.Rent(buffer.Length);
try
{
- int read = ReadCoreAsync(tmp.AsMemory(0, buffer.Length), CancellationToken.None)
+ int read = ReadCoreAsync(tmp.AsMemory(0, buffer.Length), SigtermUtil.GetCancellationToken())
.AsTask().GetAwaiter().GetResult();
tmp.AsSpan(0, read).CopyTo(buffer);
return read;
diff --git a/backend/Streams/LimitedLengthStream.cs b/backend/Streams/LimitedLengthStream.cs
index cd74ffd4..d6711b94 100644
--- a/backend/Streams/LimitedLengthStream.cs
+++ b/backend/Streams/LimitedLengthStream.cs
@@ -1,4 +1,6 @@
-namespace NzbWebDAV.Streams;
+using NzbWebDAV.Utils;
+
+namespace NzbWebDAV.Streams;
public class LimitedLengthStream(Stream stream, long length) : Stream
{
@@ -8,7 +10,7 @@ public class LimitedLengthStream(Stream stream, long length) : Stream
public override void Flush() => stream.Flush();
public override int Read(byte[] buffer, int offset, int count) =>
- ReadAsync(buffer, offset, count, CancellationToken.None).GetAwaiter().GetResult();
+ ReadAsync(buffer, offset, count, SigtermUtil.GetCancellationToken()).GetAwaiter().GetResult();
public override async Task<int>
ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
diff --git a/backend/Utils/InterpolationSearch.cs b/backend/Utils/InterpolationSearch.cs
index c7dacd80..736100c9 100644
--- a/backend/Utils/InterpolationSearch.cs
+++ b/backend/Utils/InterpolationSearch.cs
@@ -18,7 +18,7 @@ public static class InterpolationSearch
indexRangeToSearch,
byteRangeToSearch,
guess => new ValueTask<LongRange>(getByteRangeOfGuessedIndex(guess)),
- CancellationToken.None
+ SigtermUtil.GetCancellationToken()
).GetAwaiter().GetResult();
}
diff --git a/backend/Utils/SigtermUtil.cs b/backend/Utils/SigtermUtil.cs
index 5b6c8576..4c6ee94b 100644
--- a/backend/Utils/SigtermUtil.cs
+++ b/backend/Utils/SigtermUtil.cs
@@ -39,4 +39,9 @@ public static class SigtermUtil
return CancellationTokenSource.Token;
}
+
+ public static void Cancel()
+ {
+ CancellationTokenSource.Cancel();
+ }
}
\ No newline at end of file
diff --git a/backend/Websocket/WebsocketManager.cs b/backend/Websocket/WebsocketManager.cs
index 62712bfd..11cb26f5 100644
--- a/backend/Websocket/WebsocketManager.cs
+++ b/backend/Websocket/WebsocketManager.cs
@@ -84,8 +84,8 @@ public class WebsocketManager
var buffer = new byte[1024];
WebSocketReceiveResult? result = null;
while (result is not { CloseStatus: not null })
- result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), default);
- await socket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, default);
+ result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), SigtermUtil.GetCancellationToken());
+ await socket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
}
catch (Exception e)
{
@@ -115,7 +115,7 @@ public class WebsocketManager
{
try
{
- await socket.SendAsync(message, WebSocketMessageType.Text, true, default);
+ await socket.SendAsync(message, WebSocketMessageType.Text, true, SigtermUtil.GetCancellationToken());
}
catch (Exception e)
{
@@ -134,7 +134,7 @@ public class WebsocketManager
try
{
var buffer = new byte[1024];
- using var cts = new CancellationTokenSource();
+ using var cts = CancellationTokenSource.CreateLinkedTokenSource(SigtermUtil.GetCancellationToken());
cts.CancelAfter(TimeSpan.FromSeconds(5));
var result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), cts.Token);
return result.MessageType == WebSocketMessageType.Text