Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ permissions:

jobs:
publish:
# Dispatch from any other branch would build, test and push to NuGet.
if: github.ref == 'refs/heads/master'
runs-on: ubuntu-latest

steps:
Expand Down
21 changes: 21 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,27 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

### Changed

- The default `Cushion` failure predicate now counts `TimeoutRejectedException` as a failure.
It derives from `OperationCanceledException`, which the default ignored, so a hanging
dependency behind `Bounce.WithTimeout` never opened the breaker. Breakers with the default
predicate that never opened on Bounce timeouts now will. Other cancellation is still ignored.

### Fixed

- `CaromHttpHandler` sent POST and PATCH, and requests with a declared body over
`MaxRetryBufferBytes`, straight to the inner handler, so `Bounce.WithTimeout` was silently
dropped for them. They still skip retries, but the timeout now applies.
- The `Carom.DependencyInjection` retry strategy retried `CircuitOpenException` with backoff
when it wrapped a circuit breaker. It now fails fast, like the Extensions path.
- `JitterStrategy.CalculateDelay` returned NaN for a zero base delay with more than 1023
retries and jitter off, which threw `ArgumentException` from inside the catch block. The
exponent is now capped.
- The publish workflow only runs from `master`.

## [2.0.1] - 2026-09-29

Five defects found in a second audit, each reproduced against 2.0.0 before it was
Expand Down
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,9 @@ The circuit opens as soon as 5 failures are recorded. `trackingLast` bounds how
failures are counted, and `WithinLast` expires them by age, so an old incident cannot
combine with a fresh failure to trip the breaker. `When` decides which exceptions count
as the dependency's fault: without it, a bug in your own calling code would open the
circuit on a healthy service. Retries run inside the breaker, so one logical call
circuit on a healthy service. The default counts everything except cancellation, but a
`Bounce.WithTimeout` timeout (`TimeoutRejectedException`) counts as a failure, so a hanging
dependency opens the breaker. Retries run inside the breaker, so one logical call
records one outcome no matter how many attempts it took.

### Fallback
Expand Down
9 changes: 7 additions & 2 deletions src/Carom.DependencyInjection/ResiliencePipeline.cs
Original file line number Diff line number Diff line change
Expand Up @@ -158,10 +158,15 @@ public RetryStrategy(Bounce config)
_config = config;
}

public T Execute<T>(Func<T> action) => Carom.Shot(action, _config);
// An open breaker is not worth retrying with backoff. Same default as the Extensions path.
private Bounce Effective => _config.ShouldBounce == null
? _config.When(CaromCushionExtensions.DefaultShouldBounce)
: _config;

public T Execute<T>(Func<T> action) => Carom.Shot(action, Effective);

public Task<T> ExecuteAsync<T>(Func<CancellationToken, Task<T>> action, CancellationToken ct) =>
Carom.ShotAsync(action, _config, ct);
Carom.ShotAsync(action, Effective, ct);
}

/// <summary>
Expand Down
15 changes: 10 additions & 5 deletions src/Carom.Extensions/Cushion.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,13 +40,17 @@ public readonly struct Cushion

/// <summary>
/// Predicate deciding whether an exception counts as a dependency failure.
/// Null means the default: everything except OperationCanceledException.
/// Null means the default: everything except OperationCanceledException,
/// with one exception to that: TimeoutRejectedException (the Bounce timeout) counts as a failure.
/// </summary>
public Func<Exception, bool>? ShouldTrip { get; }

// Caller-side exceptions must not open the circuit; cancellation is the
// caller giving up, not the dependency failing.
internal static bool DefaultShouldTrip(Exception ex) => ex is not OperationCanceledException;
// Caller-side exceptions must not open the circuit; plain cancellation is the
// caller giving up, not the dependency failing. TimeoutRejectedException derives
// from OperationCanceledException but is the library's own deadline firing on a
// slow dependency, so it counts.
internal static bool DefaultShouldTrip(Exception ex) =>
ex is TimeoutRejectedException || ex is not OperationCanceledException;

// Test seam for the injectable monotonic clock (issue #8 pattern); null
// means Stopwatch.GetTimestamp. Not part of the public API.
Expand Down Expand Up @@ -319,7 +323,8 @@ public CushionBuilder WithinLast(TimeSpan duration)
/// Sets which exceptions count as dependency failures. Exceptions the
/// predicate rejects are rethrown without touching the circuit, so a bug in
/// calling code cannot open the circuit for a healthy dependency.
/// Default: everything except OperationCanceledException.
/// Default: everything except OperationCanceledException, but a Bounce
/// timeout (TimeoutRejectedException) counts as a failure.
/// </summary>
public CushionBuilder When(Func<Exception, bool> predicate)
{
Expand Down
13 changes: 11 additions & 2 deletions src/Carom.Http/CaromHttpHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,8 @@ protected override async Task<HttpResponseMessage> SendAsync(
{
if (!RetryNonIdempotentRequests && !IsIdempotent(request.Method))
{
return await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
// Sent once, no retries, but the Bounce timeout still applies.
return await SendOnceAsync(request, cancellationToken).ConfigureAwait(false);
}

// Buffered before the first attempt, because every attempt re-sends this same request and
Expand All @@ -118,7 +119,7 @@ protected override async Task<HttpResponseMessage> SendAsync(
// Known to be too big, and nothing has touched the body yet, so it can still be
// sent exactly once. Retry is an optimisation; a large upload is a reason to skip
// it rather than to fail the call.
return await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
return await SendOnceAsync(request, cancellationToken).ConfigureAwait(false);
}

// Unknown length, or known and within the bound. LoadIntoBufferAsync partially
Expand Down Expand Up @@ -159,6 +160,14 @@ protected override async Task<HttpResponseMessage> SendAsync(
cancellationToken).ConfigureAwait(false);
}

// One attempt, no retries, but the Bounce timeout still applies.
private Task<HttpResponseMessage> SendOnceAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var once = Bounce.Times(0);
if (_config.Timeout is TimeSpan timeout) once = once.WithTimeout(timeout);
return Carom.ShotAsync(token => base.SendAsync(request, token), once, cancellationToken);
}

/// <summary>
/// Determines if an HTTP method is idempotent per RFC 9110 and therefore safe to retry.
/// </summary>
Expand Down
3 changes: 2 additions & 1 deletion src/Carom/JitterStrategy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,8 @@ public static TimeSpan CalculateDelay(
if (disableJitter)
{
// Fixed exponential backoff: base * 2^attempt, capped
var multiplier = Math.Pow(2, attempt);
// Exponent capped so 2^attempt never reaches Infinity (0 * Infinity is NaN).
var multiplier = Math.Pow(2, Math.Min(attempt, 62));
var delayMs = baseDelay.TotalMilliseconds * multiplier;
return TimeSpan.FromMilliseconds(Math.Min(delayMs, capMs));
}
Expand Down
32 changes: 32 additions & 0 deletions tests/Carom.DependencyInjection.Tests/PipelineCancellationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -79,5 +79,37 @@ public async Task Timeout_strategy_still_reports_its_own_deadline()
Assert.Same(call, await Task.WhenAny(call, Task.Delay(TimeSpan.FromSeconds(30))));
await call;
}

[Fact]
public async Task Retry_outside_an_open_breaker_surfaces_CircuitOpenException_without_backoff()
{
var key = "pipeline-open-" + Guid.NewGuid();
var cushion = global::Carom.Extensions.Cushion.ForService(key)
.OpenAfter(failures: 1, trackingLast: 2)
.HalfOpenAfter(TimeSpan.FromMinutes(10));
var pipeline = new ResiliencePipelineBuilder("retry-over-breaker")
.AddRetry(Bounce.Times(3).WithDelay(TimeSpan.FromMilliseconds(50)).WithoutJitter())
.AddCircuitBreaker(key, cushion)
.Build();

var calls = 0;
Task<int> Fail(CancellationToken _)
{
Interlocked.Increment(ref calls);
throw new InvalidOperationException("down");
}

// Opens the breaker. The InvalidOperationException is retried, which is fine here: the
// breaker opens on the first failure and the retries then hit the open circuit.
await Assert.ThrowsAnyAsync<Exception>(() => pipeline.ExecuteAsync(Fail));
var before = Volatile.Read(ref calls);
var sw = System.Diagnostics.Stopwatch.StartNew();

await Assert.ThrowsAsync<global::Carom.Extensions.CircuitOpenException>(() => pipeline.ExecuteAsync(Fail));

Assert.Equal(before, Volatile.Read(ref calls));
// Three retries at 50 ms base would take 350 ms if the open circuit were retried.
Assert.True(sw.Elapsed < TimeSpan.FromMilliseconds(250), $"backoff ran: {sw.Elapsed}");
}
}
}
43 changes: 43 additions & 0 deletions tests/Carom.Extensions.Tests/TripPredicateTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -110,5 +110,48 @@ public void When_rejects_a_null_predicate()
Assert.Throws<ArgumentNullException>(() =>
Cushion.ForService("car01-null-" + Guid.NewGuid()).When(null!));
}

[Fact]
public async Task Default_predicate_counts_Bounce_timeouts_as_failures()
{
var key = "timeout-trips-" + Guid.NewGuid();
var cushion = Cushion.ForService(key)
.OpenAfter(failures: 2, trackingLast: 4)
.HalfOpenAfter(TimeSpan.FromMinutes(10));
var bounce = Bounce.Times(0).WithTimeout(TimeSpan.FromMilliseconds(50));

for (int i = 0; i < 2; i++)
{
await Assert.ThrowsAsync<TimeoutRejectedException>(() =>
CaromCushionExtensions.ShotAsync<int>(async () =>
{
await Task.Delay(TimeSpan.FromSeconds(30));
return 1;
}, cushion, bounce));
}

Assert.Equal(CircuitState.Open, Cushion.GetState(key));
}

[Fact]
public async Task Default_predicate_ignores_caller_cancellation()
{
var key = "cancel-ignored-" + Guid.NewGuid();
var cushion = Cushion.ForService(key)
.OpenAfter(failures: 2, trackingLast: 4)
.HalfOpenAfter(TimeSpan.FromMinutes(10));
var bounce = Bounce.Times(0).WithTimeout(TimeSpan.FromSeconds(30));
using var cts = new System.Threading.CancellationTokenSource();
cts.Cancel();

for (int i = 0; i < 4; i++)
{
await Assert.ThrowsAnyAsync<OperationCanceledException>(() =>
CaromCushionExtensions.ShotAsync<int>(
() => throw new OperationCanceledException(cts.Token), cushion, bounce, cts.Token));
}

Assert.Equal(CircuitState.Closed, Cushion.GetState(key));
}
}
}
33 changes: 33 additions & 0 deletions tests/Carom.Http.Tests/BouncePassthroughTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -109,4 +109,37 @@ public async Task Max_delay_from_the_bounce_caps_the_backoff()
// Uncapped, the backoff is the 30 second default ceiling.
Assert.True(sw.Elapsed < TimeSpan.FromSeconds(15), $"took {sw.Elapsed}");
}

[Fact]
public async Task Post_still_gets_the_bounce_timeout_but_is_not_retried()
{
var inner = new SlowHandler();
var bounce = Bounce.Times(3).WithDelay(TimeSpan.Zero).WithTimeout(TimeSpan.FromMilliseconds(200));
using var client = new HttpClient(new CaromHttpHandler(inner, bounce)) { Timeout = Timeout.InfiniteTimeSpan };
using var cleanup = new CancellationTokenSource(TimeSpan.FromSeconds(60));

var call = client.PostAsync("http://carom.test/", new StringContent("x"), cleanup.Token);
Assert.Same(call, await Task.WhenAny(call, Task.Delay(TimeSpan.FromSeconds(30))));
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => call);

var winner = await Task.WhenAny(inner.SawCancellation.Task, Task.Delay(TimeSpan.FromSeconds(30)));
Assert.Same(inner.SawCancellation.Task, winner);
}

[Fact]
public async Task Oversized_body_still_gets_the_bounce_timeout()
{
var inner = new SlowHandler();
var bounce = Bounce.Times(3).WithDelay(TimeSpan.Zero).WithTimeout(TimeSpan.FromMilliseconds(200));
var handler = new CaromHttpHandler(inner, bounce) { MaxRetryBufferBytes = 4 };
using var client = new HttpClient(handler) { Timeout = Timeout.InfiniteTimeSpan };
using var cleanup = new CancellationTokenSource(TimeSpan.FromSeconds(60));

var call = client.PutAsync("http://carom.test/", new ByteArrayContent(new byte[64]), cleanup.Token);
Assert.Same(call, await Task.WhenAny(call, Task.Delay(TimeSpan.FromSeconds(30))));
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => call);

var winner = await Task.WhenAny(inner.SawCancellation.Task, Task.Delay(TimeSpan.FromSeconds(30)));
Assert.Same(inner.SawCancellation.Task, winner);
}
}
8 changes: 8 additions & 0 deletions tests/Carom.Tests/JitterStrategyTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -129,5 +129,13 @@ List<double> Sample()

Assert.False(a.SequenceEqual(b), "two threads produced identical jitter sequences");
}

[Fact]
public void Zero_base_delay_with_a_huge_attempt_count_returns_zero_not_NaN()
{
var d = JitterStrategy.CalculateDelay(TimeSpan.Zero, TimeSpan.Zero, disableJitter: true, attempt: 2000);

Assert.Equal(TimeSpan.Zero, d);
}
}
}
Loading