Usenet streaming with a WebDAV server and a SABnzbd-compatible API
C#
Address 'Client not connected' errors.
nzbdav-dev572e1b165d67
diff --git a/backend/Clients/Connections/ConnectionLock.cs b/backend/Clients/Connections/ConnectionLock.csindex fcb2d43b..a828b3b3 100644--- a/backend/Clients/Connections/ConnectionLock.cs+++ b/backend/Clients/Connections/ConnectionLock.cs@@ -1,4 +1,4 @@-namespace NzbWebDAV.Clients.Connections;+namespace NzbWebDAV.Clients.Connections;/// <summary>/// Disposable wrapper that automatically returns a borrowed connection to the@@ -10,27 +10,50 @@ public sealed class ConnectionLock<T> : IDisposable, IAsyncDisposable{private readonly Action<T> _syncReturn;private readonly Func<T, ValueTask>? _asyncReturn;+ private readonly Action<T> _syncDestroy;+ private readonly Func<T, ValueTask>? _asyncDestroy;private T? _connection;private int _disposed; // 0 == false, 1 == true+ private int _replace; // 0 == false, 1 == trueinternal ConnectionLock(T connection,Action<T> syncReturn,- Func<T,ValueTask>? asyncReturn = null)+ Func<T,ValueTask>? asyncReturn = null,+ Action<T>? syncDestroy = null,+ Func<T,ValueTask>? asyncDestroy = null){_connection = connection;_syncReturn = syncReturn;_asyncReturn = asyncReturn;+ _syncDestroy = syncDestroy ?? (_ => { /* no-op fallback */ });+ _asyncDestroy = asyncDestroy; // may be null; will fall back to _syncDestroy}public T Connection=> _connection ?? throw new ObjectDisposedException(nameof(ConnectionLock<T>));+ /// <summary>+ /// Marks the underlying connection to be replaced. When this lock is disposed,+ /// the underlying connection will be destroyed instead of returned to the pool.+ /// </summary>+ public void Replace()+ {+ Volatile.Write(ref _replace, 1);+ }+public void Dispose(){if (Interlocked.Exchange(ref _disposed, 1) == 1) return; // already donevar conn = Interlocked.Exchange(ref _connection, default);- if (conn is not null) _syncReturn(conn);+ if (conn is not null)+ {+ var replace = Volatile.Read(ref _replace) == 1;+ if (replace)+ _syncDestroy(conn);+ else+ _syncReturn(conn);+ }GC.SuppressFinalize(this);}@@ -40,10 +63,21 @@ public sealed class ConnectionLock<T> : IDisposable, IAsyncDisposablevar conn = Interlocked.Exchange(ref _connection, default);if (conn is not null){- if (_asyncReturn is not null)- await _asyncReturn(conn).ConfigureAwait(false);+ var replace = Volatile.Read(ref _replace) == 1;+ if (replace)+ {+ if (_asyncDestroy is not null)+ await _asyncDestroy(conn).ConfigureAwait(false);+ else+ _syncDestroy(conn);+ }else- _syncReturn(conn);+ {+ if (_asyncReturn is not null)+ await _asyncReturn(conn).ConfigureAwait(false);+ else+ _syncReturn(conn);+ }}GC.SuppressFinalize(this);}diff --git a/backend/Clients/Connections/ConnectionPool.cs b/backend/Clients/Connections/ConnectionPool.csindex d23a0800..2e927ec8 100644--- a/backend/Clients/Connections/ConnectionPool.cs+++ b/backend/Clients/Connections/ConnectionPool.cs@@ -1,4 +1,4 @@-using System.Collections.Concurrent;+using System.Collections.Concurrent;using System.Runtime.CompilerServices;namespace NzbWebDAV.Clients.Connections;@@ -48,7 +48,7 @@ public sealed class ConnectionPool<T> : IDisposable, IAsyncDisposable_factory = connectionFactory?? throw new ArgumentNullException(nameof(connectionFactory));- IdleTimeout = idleTimeout ?? TimeSpan.FromMinutes(1);+ IdleTimeout = idleTimeout ?? TimeSpan.FromSeconds(30);_maxConnections = maxConnections;_gate = new SemaphoreSlim(maxConnections, maxConnections);@@ -106,7 +106,7 @@ public sealed class ConnectionPool<T> : IDisposable, IAsyncDisposablereturn BuildLock(conn);ConnectionLock<T> BuildLock(T c)- => new ConnectionLock<T>(c, Return, ReturnAsync);+ => new ConnectionLock<T>(c, Return, ReturnAsync, Destroy, DestroyAsync);static void ThrowDisposed()=> throw new ObjectDisposedException(nameof(ConnectionPool<T>));@@ -145,6 +145,30 @@ public sealed class ConnectionPool<T> : IDisposable, IAsyncDisposablereturn ValueTask.CompletedTask;}+ private void Destroy(T connection)+ {+ // When a lock requests replacement, we dispose the connection instead of reusing.+ _ = DisposeConnectionAsync(connection); // fire & forget+ Interlocked.Decrement(ref _live);+ if (Volatile.Read(ref _disposed) == 0)+ {+ _gate.Release();+ }+ TriggerConnectionPoolChangedEvent();+ }++ private ValueTask DestroyAsync(T connection)+ {+ _ = DisposeConnectionAsync(connection); // fire & forget+ Interlocked.Decrement(ref _live);+ if (Volatile.Read(ref _disposed) == 0)+ {+ _gate.Release();+ }+ TriggerConnectionPoolChangedEvent();+ return ValueTask.CompletedTask;+ }+private void TriggerConnectionPoolChangedEvent(){OnConnectionPoolChanged?.Invoke(this, new ConnectionPoolChangedEventArgs(diff --git a/backend/Clients/MultiConnectionNntpClient.cs b/backend/Clients/MultiConnectionNntpClient.csindex 0d127306..5785e943 100644--- a/backend/Clients/MultiConnectionNntpClient.cs+++ b/backend/Clients/MultiConnectionNntpClient.cs@@ -1,5 +1,6 @@using NzbWebDAV.Clients.Connections;using NzbWebDAV.Streams;+using Usenet.Exceptions;using Usenet.Nntp.Responses;using Usenet.Nzb;using Usenet.Yenc;@@ -47,10 +48,15 @@ public class MultiConnectionNntpClient(ConnectionPool<INntpClient> connectionPoopublic async Task WaitForReady(CancellationToken cancellationToken){- using var connectionLock = await _connectionPool.GetConnectionLockAsync(cancellationToken);+ await using var connectionLock = await _connectionPool.GetConnectionLockAsync(cancellationToken);}- private async Task<T> RunWithConnection<T>(Func<INntpClient, Task<T>> task, CancellationToken cancellationToken)+ private async Task<T> RunWithConnection<T>+ (+ Func<INntpClient, Task<T>> task,+ CancellationToken cancellationToken,+ int retries = 1+ ){var connectionLock = await _connectionPool.GetConnectionLockAsync(cancellationToken);try@@ -61,10 +67,23 @@ 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).ContinueWith(_ => connectionLock.Dispose());+ _ = connectionLock.Connection.WaitForReady(CancellationToken.None)+ .ContinueWith(_ => connectionLock.Dispose());return result;}- catch (Exception)+ catch (NntpException e)+ {+ // we want to replace the underlying connection in cases of NntpExceptions.+ connectionLock.Replace();+ connectionLock.Dispose();++ // and try again with a new connection (max 1 retry)+ if (retries > 0)+ return await RunWithConnection<T>(task, cancellationToken, retries - 1);++ throw;+ }+ catch (Exception e){// we also want to release the connection-lock if there was any error getting the result.connectionLock.Dispose();