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
15 changes: 15 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Added

- `CaromAttemptTimeoutExtensions.ShotAsync` in `Carom.Extensions`: a timeout for each try. A try
that runs out is cancelled and fails with a `TimeoutRejectedException`, which is retried. The
overall `WithTimeout` and cancellation still win. An action that ignores its token keeps
running after its try times out, so the next try can overlap it. It lives in the add-on package
so the core stays under its published size bound.
- `Bounce.WithDelayHint(Func<Exception, TimeSpan?>)` (also on `Bounce<T>`; honoured by `Shot` and
`ShotAsync`): names the delay before the next retry, such as a server's `Retry-After`. It
replaces the computed jitter for that retry, is clamped to `MaxDelay`, and is still cut short
by the overall timeout and cancellation. A null result keeps the computed backoff. It applies
to retries after an exception only, not to `WhenResult` retries.
- `tests/Carom.ReadmeSamples.Tests` compiles the README samples and fails when the README text
drifts from the compiled copy.
- `Cushion` breaker overloads that take `Func<CancellationToken, Task<T>>`, so a `Bounce.WithTimeout` cancels the guarded call.
- Public `Cushion.Execute` and `Cushion.ExecuteAsync`, `Cushion.MaxBreakers`, `Cushion.Reset(key)` and `CushionBuilder.WithClock`.
- Note: a method group that has both `M()` and `M(CancellationToken)` overloads is now ambiguous when passed to `CaromCushionExtensions.ShotAsync`, as it already is for `Carom.ShotAsync`. Use a lambda or a cast.
Expand All @@ -23,6 +35,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Fixed

- The README Basic Usage sample (`using Carom;` then `Carom.ShotAsync`) did not compile from a
file with the using at the top, because the namespace `Carom` hides the class. The sample
now uses a `using Retry = Carom.Carom;` alias. The class is not renamed.
- `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.
Expand Down
15 changes: 15 additions & 0 deletions Carom.sln
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Carom.Telemetry.OpenTelemet
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Carom.AspNetCore.Tests", "tests\Carom.AspNetCore.Tests\Carom.AspNetCore.Tests.csproj", "{06AD07A1-7416-41BC-B47E-6E33791937B1}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Carom.ReadmeSamples.Tests", "tests\Carom.ReadmeSamples.Tests\Carom.ReadmeSamples.Tests.csproj", "{042469EE-BEC5-4512-B63A-AAAFFDF032A8}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -257,6 +259,18 @@ Global
{06AD07A1-7416-41BC-B47E-6E33791937B1}.Release|x64.Build.0 = Release|Any CPU
{06AD07A1-7416-41BC-B47E-6E33791937B1}.Release|x86.ActiveCfg = Release|Any CPU
{06AD07A1-7416-41BC-B47E-6E33791937B1}.Release|x86.Build.0 = Release|Any CPU
{042469EE-BEC5-4512-B63A-AAAFFDF032A8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{042469EE-BEC5-4512-B63A-AAAFFDF032A8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{042469EE-BEC5-4512-B63A-AAAFFDF032A8}.Debug|x64.ActiveCfg = Debug|Any CPU
{042469EE-BEC5-4512-B63A-AAAFFDF032A8}.Debug|x64.Build.0 = Debug|Any CPU
{042469EE-BEC5-4512-B63A-AAAFFDF032A8}.Debug|x86.ActiveCfg = Debug|Any CPU
{042469EE-BEC5-4512-B63A-AAAFFDF032A8}.Debug|x86.Build.0 = Debug|Any CPU
{042469EE-BEC5-4512-B63A-AAAFFDF032A8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{042469EE-BEC5-4512-B63A-AAAFFDF032A8}.Release|Any CPU.Build.0 = Release|Any CPU
{042469EE-BEC5-4512-B63A-AAAFFDF032A8}.Release|x64.ActiveCfg = Release|Any CPU
{042469EE-BEC5-4512-B63A-AAAFFDF032A8}.Release|x64.Build.0 = Release|Any CPU
{042469EE-BEC5-4512-B63A-AAAFFDF032A8}.Release|x86.ActiveCfg = Release|Any CPU
{042469EE-BEC5-4512-B63A-AAAFFDF032A8}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand All @@ -276,5 +290,6 @@ Global
{BA696805-B73E-40D5-A54D-7D5D031A3472} = {92C92E59-A76E-4AB2-842A-AF22E07901C0}
{D821AE31-0B33-41C5-A652-3C8FFBA9443D} = {92C92E59-A76E-4AB2-842A-AF22E07901C0}
{06AD07A1-7416-41BC-B47E-6E33791937B1} = {92C92E59-A76E-4AB2-842A-AF22E07901C0}
{042469EE-BEC5-4512-B63A-AAAFFDF032A8} = {92C92E59-A76E-4AB2-842A-AF22E07901C0}
EndGlobalSection
EndGlobal
57 changes: 51 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ Runs on .NET 10 and .NET 8. The core packages target `netstandard2.0`, so .NET F
- **Zero Dependencies** (core packages)
- **Zero Allocations** (0 bytes on the successful hot path, test-enforced)
- **Safe by Default** (mandatory decorrelated jitter)
- **Tiny Footprint** (25.5KB core, 54KB extensions)
- **Tiny Footprint** (27KB core, 59.5KB extensions)
- **Fully Composable** (all patterns work together)

## 📦 Packages
Expand All @@ -24,8 +24,8 @@ Sizes are the Release-built assemblies. Tests fail if the core grows past 28KB o

| Package | Size | Purpose |
|---------|------|---------|
| **Carom** | 25.5KB | Core retry + timeout |
| **Carom.Extensions** | 54KB | Circuit Breaker, Fallback, Bulkhead, Rate Limiting |
| **Carom** | 27KB | Core retry + timeout |
| **Carom.Extensions** | 59.5KB | Circuit Breaker, Fallback, Bulkhead, Rate Limiting |
| **Carom.Http** | 12.5KB | HTTP integration |
| **Carom.DependencyInjection** | 21.5KB | Named resilience pipelines for `IServiceCollection` |
| **Carom.AspNetCore** | 8.5KB | ASP.NET Core health checks |
Expand All @@ -43,17 +43,62 @@ dotnet add package Carom.Extensions

### Basic Usage

<!-- sample: basic-usage -->
```csharp
using Carom;
using Retry = Carom.Carom;

// Simple retry with exponential backoff
var result = await Carom.ShotAsync(() => api.CallAsync(), retries: 3);
var result = await Retry.ShotAsync(() => api.CallAsync(), retries: 3);

// With timeout
var bounce = Bounce.Times(5).WithTimeout(TimeSpan.FromSeconds(30));
var data = await Carom.ShotAsync(() => apiClient.FetchAsync(), bounce);
var data = await Retry.ShotAsync(() => apiClient.FetchAsync(), bounce);
```

The class `Carom` shares its name with the namespace, so with `using Carom;` at the top of a
file a bare `Carom.ShotAsync` does not resolve. The alias above fixes that, and
`global::Carom.Carom.ShotAsync` works too. The class keeps its name.

### Per-try timeout and Retry-After

`WithTimeout` bounds the whole call. To bound each try as well, use `CaromAttemptTimeoutExtensions`
from `Carom.Extensions`: a try that runs out is cancelled and fails with a
`TimeoutRejectedException`, which is retried like any other failure. The overall timeout and
cancellation still end the call. It needs a `Func<CancellationToken, Task>` action. An action
that ignores its token keeps running after its try times out, so the next try can overlap it;
pass the token on to whatever the action calls.

<!-- sample: attempt-timeout -->
```csharp
using Carom.Extensions;

// Each try gets 2 seconds, the whole call gets 10
var bounce = Bounce.Times(3).WithTimeout(TimeSpan.FromSeconds(10));

var data = await CaromAttemptTimeoutExtensions.ShotAsync(
ct => apiClient.FetchAsync(ct), bounce, attemptTimeout: TimeSpan.FromSeconds(2));
```

`WithDelayHint` lets the failure name the wait before the next retry, such as a server's
`Retry-After`. The hint replaces the computed jitter for that retry, is clamped to
`MaxDelay`, and is still cut short by the overall timeout and by cancellation. Return null
to keep the computed backoff. The hint applies to retries after an exception only, not to
`WhenResult` retries.

<!-- sample: delay-hint -->
```csharp
// Wait the Retry-After the server sent, up to MaxDelay
var bounce = Bounce.Times(3)
.WithMaxDelay(TimeSpan.FromSeconds(60))
.WithDelayHint(ex => ex is RateLimitedException limited ? limited.RetryAfter : null);

var data = await Retry.ShotAsync(() => apiClient.FetchAsync(), bounce);
```

These samples are compiled by `tests/Carom.ReadmeSamples.Tests`, which also fails when the
README text drifts from the compiled copy.

### Circuit Breaker

```csharp
Expand Down Expand Up @@ -158,7 +203,7 @@ Speed is not the pitch. Per successful call, both Carom and Polly cost nanosecon
The claims we do make are measured (Apple M1, .NET 8, against Polly 8.4.2) and enforced by `tests/Carom.Tests/PublishedClaimsTests.cs`:

- **Zero allocations on the successful hot path**: Carom 0 B per call. Polly v8 allocates 24 B per call, the Polly v7 API 248 B.
- **Small on disk**: Carom.dll is 25.5 KB and Carom.Extensions.dll 54 KB. Polly.Core.dll (net8.0) is 237 KB.
- **Small on disk**: Carom.dll is 27 KB and Carom.Extensions.dll 59.5 KB. Polly.Core.dll (net8.0) is 237 KB.
- **Zero package dependencies on every target**: Polly.Core has none on net8.0 but needs four packages on netstandard2.0 and five on .NET Framework.

Details and methodology in [docs/BENCHMARKS.md](docs/BENCHMARKS.md).
128 changes: 128 additions & 0 deletions src/Carom.Extensions/CaromAttemptTimeoutExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
// Copyright (c) BaryoDev. All rights reserved.
// Licensed under the MPL-2.0 license. See LICENSE file in the project root for full license information.

using System;
using System.Threading;
using System.Threading.Tasks;

namespace Carom.Extensions
{
/// <summary>
/// A timeout for each single try. <c>Bounce.WithTimeout</c> bounds the whole call including
/// retries; these overloads also give every try its own timeout. A try that runs out is
/// cancelled (the token passed to the action is cancelled) and fails with a
/// <see cref="TimeoutRejectedException"/>, which Carom retries like any other failure that
/// passes the Bounce predicate. The overall timeout and caller cancellation still end the call.
/// An action that ignores its token keeps running after its try times out, so the next try can
/// overlap it.
/// </summary>
public static class CaromAttemptTimeoutExtensions
{
/// <summary>
/// Executes a cancellable async action with retry logic and a timeout for each try.
/// </summary>
/// <typeparam name="T">The return type of the action.</typeparam>
/// <param name="action">The action. Receives a token cancelled on a try timeout, the overall timeout or caller cancellation.</param>
/// <param name="bounce">The retry configuration.</param>
/// <param name="attemptTimeout">The timeout for each try. Must be positive and at most int.MaxValue milliseconds.</param>
/// <param name="ct">Cancellation token.</param>
public static Task<T> ShotAsync<T>(
Func<CancellationToken, Task<T>> action,
Bounce bounce,
TimeSpan attemptTimeout,
CancellationToken ct = default)
{
Validate(action, attemptTimeout);
return Carom.ShotAsync(Limit(action, attemptTimeout), bounce, ct);
}

/// <summary>
/// Executes a cancellable async action with result-based retry and a timeout for each try.
/// </summary>
/// <typeparam name="T">The return type of the action.</typeparam>
/// <param name="action">The action. Receives a token cancelled on a try timeout, the overall timeout or caller cancellation.</param>
/// <param name="bounce">The retry configuration with result predicate.</param>
/// <param name="attemptTimeout">The timeout for each try. Must be positive and at most int.MaxValue milliseconds.</param>
/// <param name="ct">Cancellation token.</param>
public static Task<T> ShotAsync<T>(
Func<CancellationToken, Task<T>> action,
Bounce<T> bounce,
TimeSpan attemptTimeout,
CancellationToken ct = default)
{
Validate(action, attemptTimeout);
return Carom.ShotAsync(Limit(action, attemptTimeout), bounce, ct);
}

/// <summary>
/// Executes a cancellable async void action with retry logic and a timeout for each try.
/// </summary>
/// <param name="action">The action. Receives a token cancelled on a try timeout, the overall timeout or caller cancellation.</param>
/// <param name="bounce">The retry configuration.</param>
/// <param name="attemptTimeout">The timeout for each try. Must be positive and at most int.MaxValue milliseconds.</param>
/// <param name="ct">Cancellation token.</param>
public static Task ShotAsync(
Func<CancellationToken, Task> action,
Bounce bounce,
TimeSpan attemptTimeout,
CancellationToken ct = default)
{
Validate(action, attemptTimeout);
return Carom.ShotAsync(Limit(action, attemptTimeout), bounce, ct);
}

private static void Validate(Delegate action, TimeSpan attemptTimeout)
{
if (action == null) throw new ArgumentNullException(nameof(action));
if (attemptTimeout <= TimeSpan.Zero)
throw new ArgumentOutOfRangeException(nameof(attemptTimeout), "Attempt timeout must be positive");
// CancelAfter rejects larger values, and inside the retried lambda that would be retried.
if (attemptTimeout.TotalMilliseconds > int.MaxValue)
throw new ArgumentOutOfRangeException(nameof(attemptTimeout), "Attempt timeout must be at most int.MaxValue milliseconds");
}

private static Func<CancellationToken, Task<T>> Limit<T>(Func<CancellationToken, Task<T>> action, TimeSpan attemptTimeout)
{
return async ct =>
{
using var attemptCts = CancellationTokenSource.CreateLinkedTokenSource(ct);
attemptCts.CancelAfter(attemptTimeout);
var token = attemptCts.Token;
try
{
var task = action(token);
var completed = await Task.WhenAny(task, Task.Delay(-1, token)).ConfigureAwait(false);
if (completed == task) return await task.ConfigureAwait(false);

Observe(task);
throw new OperationCanceledException(token);
}
catch (OperationCanceledException) when (token.IsCancellationRequested && !ct.IsCancellationRequested)
{
// The per-try timer fired, not the overall timeout or the caller.
throw new TimeoutRejectedException(attemptTimeout);
}
};
}

private static Func<CancellationToken, Task> Limit(Func<CancellationToken, Task> action, TimeSpan attemptTimeout)
{
var limited = Limit<bool>(async token =>
{
await action(token).ConfigureAwait(false);
return true;
}, attemptTimeout);
return ct => limited(ct);
}

// An abandoned try keeps running; observe its fault so it never surfaces as unobserved.
private static void Observe(Task task)
{
_ = task.ContinueWith(
static t => _ = t.Exception,
CancellationToken.None,
TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously,
TaskScheduler.Default);
}
}
}
Loading
Loading