Skip to content

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

C#

fix(nntp): Skip failing usenet providers with circuit breaker (#400)

Anthony Hoivikc5fa860930a5
diff --git a/backend/Clients/Usenet/Connections/ProviderCircuitBreaker.cs b/backend/Clients/Usenet/Connections/ProviderCircuitBreaker.cs
new file mode 100644
index 00000000..bb748a0c
--- /dev/null
+++ b/backend/Clients/Usenet/Connections/ProviderCircuitBreaker.cs
@@ -0,0 +1,75 @@
+using Serilog;
+
+namespace NzbWebDAV.Clients.Usenet.Connections;
+
+/// <summary>
+/// Tracks consecutive connection failures for an NNTP provider and temporarily
+/// disables it when a failure threshold is reached, preventing a single
+/// misbehaving provider from blocking the entire download pipeline.
+/// <para>
+/// After tripping, the provider enters a cooldown period during which it is
+/// skipped. When the cooldown expires, a single probe attempt is allowed.
+/// If the probe succeeds, the breaker resets. If it fails, the cooldown
+/// doubles (up to a cap) and the breaker re-trips.
+/// </para>
+/// </summary>
+public class ProviderCircuitBreaker
+{
+ private const int FailureThreshold = 3;
+ private static readonly TimeSpan InitialCooldown = TimeSpan.FromSeconds(60);
+ private static readonly TimeSpan MaxCooldown = TimeSpan.FromMinutes(5);
+
+ private readonly string _providerName;
+ private readonly object _lock = new();
+
+ private int _consecutiveFailures;
+ private long _trippedUntilMs;
+ private TimeSpan _currentCooldown = InitialCooldown;
+
+ public ProviderCircuitBreaker(string providerName)
+ {
+ _providerName = providerName;
+ }
+
+ public bool IsTripped
+ {
+ get
+ {
+ var trippedUntil = Volatile.Read(ref _trippedUntilMs);
+ if (trippedUntil == 0) return false;
+ return Environment.TickCount64 < trippedUntil;
+ }
+ }
+
+ public void RecordSuccess()
+ {
+ lock (_lock)
+ {
+ if (_consecutiveFailures > 0 || _trippedUntilMs > 0)
+ Log.Information("Provider {Provider} recovered — circuit breaker reset.", _providerName);
+
+ _consecutiveFailures = 0;
+ _trippedUntilMs = 0;
+ _currentCooldown = InitialCooldown;
+ }
+ }
+
+ public void RecordFailure()
+ {
+ lock (_lock)
+ {
+ _consecutiveFailures++;
+
+ if (_consecutiveFailures < FailureThreshold) return;
+
+ _trippedUntilMs = Environment.TickCount64 + (long)_currentCooldown.TotalMilliseconds;
+ Log.Warning(
+ "Provider {Provider} tripped after {Failures} consecutive failures. " +
+ "Skipping for {Cooldown}s.",
+ _providerName, _consecutiveFailures, _currentCooldown.TotalSeconds);
+
+ _currentCooldown = TimeSpan.FromMilliseconds(
+ Math.Min(_currentCooldown.TotalMilliseconds * 2, MaxCooldown.TotalMilliseconds));
+ }
+ }
+}
diff --git a/backend/Clients/Usenet/MultiConnectionNntpClient.cs b/backend/Clients/Usenet/MultiConnectionNntpClient.cs
index ba05c4e6..9f634436 100644
--- a/backend/Clients/Usenet/MultiConnectionNntpClient.cs
+++ b/backend/Clients/Usenet/MultiConnectionNntpClient.cs
@@ -20,10 +20,16 @@ namespace NzbWebDAV.Clients.Usenet;
/// </summary>
/// <param name="connectionPool"></param>
/// <param name="type"></param>
+/// <param name="circuitBreaker"></param>
[SuppressMessage("ReSharper", "AccessToDisposedClosure")]
-public class MultiConnectionNntpClient(ConnectionPool<INntpClient> connectionPool, ProviderType type) : NntpClient
+public class MultiConnectionNntpClient(
+ ConnectionPool<INntpClient> connectionPool,
+ ProviderType type,
+ ProviderCircuitBreaker circuitBreaker
+) : NntpClient
{
public ProviderType ProviderType { get; } = type;
+ public bool IsTripped => circuitBreaker.IsTripped;
public int LiveConnections => connectionPool.LiveConnections;
public int IdleConnections => connectionPool.IdleConnections;
public int ActiveConnections => connectionPool.ActiveConnections;
@@ -156,6 +162,7 @@ public class MultiConnectionNntpClient(ConnectionPool<INntpClient> connectionPoo
}
catch (Exception e)
{
+ circuitBreaker.RecordFailure();
LogException(() => connectionLock?.Replace());
LogException(() => connectionLock?.Dispose());
if (retryCount > 0)
@@ -189,6 +196,7 @@ public class MultiConnectionNntpClient(ConnectionPool<INntpClient> connectionPoo
}
catch (Exception e)
{
+ circuitBreaker.RecordFailure();
LogException(() => connectionLock?.Replace());
LogException(() => connectionLock?.Dispose());
if (retryCount > 0)
@@ -203,6 +211,8 @@ public class MultiConnectionNntpClient(ConnectionPool<INntpClient> connectionPoo
throw;
}
+ circuitBreaker.RecordSuccess();
+
// stat, head, and date
if (name is "STAT" or "HEAD" or "DATE")
{
diff --git a/backend/Clients/Usenet/MultiProviderNntpClient.cs b/backend/Clients/Usenet/MultiProviderNntpClient.cs
index 7cd2a018..8d24e45a 100644
--- a/backend/Clients/Usenet/MultiProviderNntpClient.cs
+++ b/backend/Clients/Usenet/MultiProviderNntpClient.cs
@@ -160,11 +160,16 @@ public class MultiProviderNntpClient(List<MultiConnectionNntpClient> providers)
private List<MultiConnectionNntpClient> GetOrderedProviders()
{
- return providers
+ var enabled = providers
.Where(x => x.ProviderType != ProviderType.Disabled)
.OrderBy(x => x.ProviderType)
.ThenByDescending(x => x.AvailableConnections)
.ToList();
+
+ var healthy = enabled.Where(x => !x.IsTripped).ToList();
+
+ // Always return at least one provider so cooldown probes can fire.
+ return healthy.Count > 0 ? healthy : enabled;
}
public override void Dispose()
diff --git a/backend/Clients/Usenet/UsenetStreamingClient.cs b/backend/Clients/Usenet/UsenetStreamingClient.cs
index 80f05db0..dc9752f3 100644
--- a/backend/Clients/Usenet/UsenetStreamingClient.cs
+++ b/backend/Clients/Usenet/UsenetStreamingClient.cs
@@ -59,7 +59,8 @@ public class UsenetStreamingClient : WrappingNntpClient
connectionFactory: ct => CreateNewConnection(connectionDetails, ct),
onConnectionPoolChanged
);
- return new MultiConnectionNntpClient(connectionPool, connectionDetails.Type);
+ var circuitBreaker = new ProviderCircuitBreaker(connectionDetails.Host);
+ return new MultiConnectionNntpClient(connectionPool, connectionDetails.Type, circuitBreaker);
}
private static ConnectionPool<INntpClient> CreateNewConnectionPool