From 4d6ebffe0905515443e7d57c4dc5519fd1db31b4 Mon Sep 17 00:00:00 2001 From: Arnel Robles Date: Sat, 14 Nov 2026 09:38:05 +0800 Subject: [PATCH 1/4] Add Bounce attempt timeout, delay hint and CaromHooks.Retrying event --- CHANGELOG.md | 26 ++ Carom.sln | 15 ++ README.md | 63 ++++- .../CaromTelemetry.cs | 4 +- src/Carom/Bounce.cs | 161 +++++++++++- src/Carom/Carom.cs | 219 ++++++++++------ src/Carom/CaromHooks.cs | 49 +++- .../ApprovedApi/Carom.approved.txt | 11 + .../Carom.ReadmeSamples.Tests.csproj | 24 ++ .../ReadmeSamples.cs | 81 ++++++ .../ReadmeSamplesTests.cs | 74 ++++++ tests/Carom.Tests/AttemptTimeoutTests.cs | 172 +++++++++++++ tests/Carom.Tests/CaromHooksTests.cs | 138 ++++++++++ tests/Carom.Tests/DelayHintTests.cs | 235 ++++++++++++++++++ tests/Carom.Tests/PublishedClaimsTests.cs | 6 +- 15 files changed, 1180 insertions(+), 98 deletions(-) create mode 100644 tests/Carom.ReadmeSamples.Tests/Carom.ReadmeSamples.Tests.csproj create mode 100644 tests/Carom.ReadmeSamples.Tests/ReadmeSamples.cs create mode 100644 tests/Carom.ReadmeSamples.Tests/ReadmeSamplesTests.cs create mode 100644 tests/Carom.Tests/AttemptTimeoutTests.cs create mode 100644 tests/Carom.Tests/DelayHintTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 8ff69e8..7feab5e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,29 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- `Bounce.WithAttemptTimeout(TimeSpan)` (also on `Bounce`): 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. The synchronous `Shot` overloads throw + `InvalidOperationException` if one is set, like `WithTimeout`. +- `Bounce.WithDelayHint(Func)` (also on `Bounce`): 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. +- `CaromHooks.Retrying` event. Add and remove are atomic and it cannot be assigned from + outside, so one subscriber cannot remove another. +- The core assembly grew from 25.5 KB to 31 KB with these additions. The published size bound + moves from 28 KB to 34 KB, in the README and in `PublishedClaimsTests`. +- `tests/Carom.ReadmeSamples.Tests` compiles the README samples and fails when the README text + drifts from the compiled copy. + +### Deprecated + +- `CaromHooks.OnRetry` is obsolete. It is still raised, next to `Retrying`. Assigning it no + longer removes `Retrying` subscribers. It will be removed in the next major version. + `CaromTelemetry.Subscribe` now uses `Retrying`. + ### Changed - The default `Cushion` failure predicate now counts `TimeoutRejectedException` as a failure. @@ -16,6 +39,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. diff --git a/Carom.sln b/Carom.sln index 8e7e55b..941c692 100644 --- a/Carom.sln +++ b/Carom.sln @@ -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 @@ -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 @@ -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 diff --git a/README.md b/README.md index 28f7576..418b2c8 100644 --- a/README.md +++ b/README.md @@ -15,16 +15,16 @@ 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** (31KB core, 54KB extensions) - **Fully Composable** (all patterns work together) ## 📦 Packages -Sizes are the Release-built assemblies. Tests fail if the core grows past 28KB or the extensions past 60KB. +Sizes are the Release-built assemblies. Tests fail if the core grows past 34KB or the extensions past 60KB. | Package | Size | Purpose | |---------|------|---------| -| **Carom** | 25.5KB | Core retry + timeout | +| **Carom** | 31KB | Core retry + timeout | | **Carom.Extensions** | 54KB | Circuit Breaker, Fallback, Bulkhead, Rate Limiting | | **Carom.Http** | 12.5KB | HTTP integration | | **Carom.DependencyInjection** | 21.5KB | Named resilience pipelines for `IServiceCollection` | @@ -43,17 +43,68 @@ dotnet add package Carom.Extensions ### 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. `WithAttemptTimeout` bounds each try: 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. Attempt timeouts +need `ShotAsync`; the synchronous `Shot` overloads throw if one is set. + + +```csharp +// Each try gets 2 seconds, the whole call gets 10 +var bounce = Bounce.Times(3) + .WithAttemptTimeout(TimeSpan.FromSeconds(2)) + .WithTimeout(TimeSpan.FromSeconds(10)); + +var data = await Retry.ShotAsync(ct => apiClient.FetchAsync(ct), bounce); +``` + +`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. + + +```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); +``` + +To watch retries, subscribe to the `CaromHooks.Retrying` event. Add and remove are atomic and +one subscriber cannot remove another. The old settable `CaromHooks.OnRetry` property is +obsolete and will go in the next major version. + + +```csharp +CaromHooks.Retrying += signal => + Console.WriteLine($"retry {signal.Attempt} in {signal.Delay}"); +``` + +These samples are compiled by `tests/Carom.ReadmeSamples.Tests`, which also fails when the +README text drifts from the compiled copy. + ### Circuit Breaker ```csharp @@ -150,7 +201,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 31 KB and Carom.Extensions.dll 54 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). diff --git a/src/Carom.Telemetry.OpenTelemetry/CaromTelemetry.cs b/src/Carom.Telemetry.OpenTelemetry/CaromTelemetry.cs index 324e5fc..778513b 100644 --- a/src/Carom.Telemetry.OpenTelemetry/CaromTelemetry.cs +++ b/src/Carom.Telemetry.OpenTelemetry/CaromTelemetry.cs @@ -74,7 +74,7 @@ public static void Subscribe() lock (SubscriptionGate) { if (_subscribed) return; - CaromHooks.OnRetry += RetryHandler; + CaromHooks.Retrying += RetryHandler; CaromHooks.OnCircuitOpened += CircuitOpenedHandler; CaromHooks.OnBulkheadRejected += BulkheadRejectedHandler; CaromHooks.OnRateLimitRejected += RateLimitRejectedHandler; @@ -91,7 +91,7 @@ public static void Unsubscribe() lock (SubscriptionGate) { if (!_subscribed) return; - CaromHooks.OnRetry -= RetryHandler; + CaromHooks.Retrying -= RetryHandler; CaromHooks.OnCircuitOpened -= CircuitOpenedHandler; CaromHooks.OnBulkheadRejected -= BulkheadRejectedHandler; CaromHooks.OnRateLimitRejected -= RateLimitRejectedHandler; diff --git a/src/Carom/Bounce.cs b/src/Carom/Bounce.cs index 31faabe..9c64a2e 100644 --- a/src/Carom/Bounce.cs +++ b/src/Carom/Bounce.cs @@ -2,6 +2,8 @@ // 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 { @@ -53,7 +55,22 @@ public readonly struct Bounce // Nullable backing so default(Bounce) still reports the 30 second default. private readonly TimeSpan? _maxDelay; - private Bounce(int retries, TimeSpan baseDelay, TimeSpan? timeout, bool disableJitter, Func? shouldBounce, TimeSpan? maxDelay = null) + /// + /// Optional timeout for each single try, set by WithAttemptTimeout. + /// + public TimeSpan? AttemptTimeout => _extras?.AttemptTimeout; + + /// + /// Optional hint for the delay before the next retry, set by WithDelayHint. + /// + public Func? DelayHint => _extras?.DelayHint; + + // Rarely used options live in one reference so a Bounce without them stays small. + private readonly BounceExtras? _extras; + + internal BounceExtras? Extras => _extras; + + private Bounce(int retries, TimeSpan baseDelay, TimeSpan? timeout, bool disableJitter, Func? shouldBounce, TimeSpan? maxDelay = null, BounceExtras? extras = null) { Retries = retries; BaseDelay = baseDelay; @@ -61,6 +78,7 @@ private Bounce(int retries, TimeSpan baseDelay, TimeSpan? timeout, bool disableJ DisableJitter = disableJitter; ShouldBounce = shouldBounce; _maxDelay = maxDelay; + _extras = extras; } /// @@ -90,7 +108,7 @@ public Bounce WithDelay(TimeSpan delay) { if (delay < TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(delay), "Delay cannot be negative"); - return new Bounce(Retries, delay, Timeout, DisableJitter, ShouldBounce, _maxDelay); + return new Bounce(Retries, delay, Timeout, DisableJitter, ShouldBounce, _maxDelay, _extras); } /// @@ -99,7 +117,7 @@ public Bounce WithDelay(TimeSpan delay) /// /// A new Bounce configuration with jitter disabled. public Bounce WithoutJitter() => - new Bounce(Retries, BaseDelay, Timeout, disableJitter: true, ShouldBounce, _maxDelay); + new Bounce(Retries, BaseDelay, Timeout, disableJitter: true, ShouldBounce, _maxDelay, _extras); /// /// Sets a predicate to determine which exceptions should trigger a retry. @@ -107,7 +125,7 @@ public Bounce WithoutJitter() => /// The exception predicate. /// A new Bounce configuration with the specified predicate. public Bounce When(Func predicate) => - new Bounce(Retries, BaseDelay, Timeout, DisableJitter, predicate, _maxDelay); + new Bounce(Retries, BaseDelay, Timeout, DisableJitter, predicate, _maxDelay, _extras); /// /// Sets the maximum delay between retries. @@ -121,7 +139,7 @@ public Bounce WithMaxDelay(TimeSpan maxDelay) { if (maxDelay <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(maxDelay), "Max delay must be positive"); - return new Bounce(Retries, BaseDelay, Timeout, DisableJitter, ShouldBounce, maxDelay); + return new Bounce(Retries, BaseDelay, Timeout, DisableJitter, ShouldBounce, maxDelay, _extras); } /// @@ -136,8 +154,45 @@ public Bounce WithTimeout(TimeSpan timeout) { if (timeout <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(timeout), "Timeout must be positive"); - return new Bounce(Retries, BaseDelay, timeout, DisableJitter, ShouldBounce, _maxDelay); + return new Bounce(Retries, BaseDelay, timeout, DisableJitter, ShouldBounce, _maxDelay, _extras); } + + /// + /// Sets a timeout for each single try. When one try runs longer, it is cancelled + /// (the token passed to a cancellable action is cancelled) and fails with a + /// , which is retried like any other failure + /// that passes the exception predicate. The overall still + /// bounds the whole operation including retries. Enforced only by the asynchronous + /// ShotAsync overloads; the synchronous Shot overloads throw InvalidOperationException. + /// + /// The per-try timeout. Must be positive. + /// A new Bounce configuration with the specified per-try timeout. + public Bounce WithAttemptTimeout(TimeSpan timeout) + { + if (timeout <= TimeSpan.Zero) + throw new ArgumentOutOfRangeException(nameof(timeout), "Attempt timeout must be positive"); + return new Bounce(Retries, BaseDelay, Timeout, DisableJitter, ShouldBounce, _maxDelay, BounceExtras.With(_extras, attemptTimeout: timeout)); + } + + /// + /// Sets a function that can name the delay before the next retry, for example the + /// Retry-After a server sent. It receives the exception that failed the try. Return null + /// to use the computed backoff. A returned delay replaces the computed delay (no jitter is + /// added), is clamped to zero at the bottom and to at the top, and + /// is still cut short by the overall timeout and by cancellation. A hint does not feed the + /// jitter sequence, and a hint that throws is ignored. + /// + /// Returns the delay to wait, or null for the computed backoff. + /// A new Bounce configuration with the specified delay hint. + public Bounce WithDelayHint(Func hint) + { + if (hint == null) throw new ArgumentNullException(nameof(hint)); + return new Bounce(Retries, BaseDelay, Timeout, DisableJitter, ShouldBounce, _maxDelay, BounceExtras.With(_extras, delayHint: hint)); + } + + // Test seam: replaces Task.Delay so a fake clock can observe and release the waits. + internal Bounce WithSleep(Func sleep) => + new Bounce(Retries, BaseDelay, Timeout, DisableJitter, ShouldBounce, _maxDelay, BounceExtras.With(_extras, sleep: sleep)); } /// @@ -187,8 +242,23 @@ public readonly struct Bounce // Nullable backing so default(Bounce) still reports the 30 second default. private readonly TimeSpan? _maxDelay; + /// + /// Optional timeout for each single try, set by WithAttemptTimeout. + /// + public TimeSpan? AttemptTimeout => _extras?.AttemptTimeout; + + /// + /// Optional hint for the delay before the next retry, set by WithDelayHint. + /// + public Func? DelayHint => _extras?.DelayHint; + + // Rarely used options live in one reference so a Bounce without them stays small. + private readonly BounceExtras? _extras; + + internal BounceExtras? Extras => _extras; + private Bounce(int retries, TimeSpan baseDelay, TimeSpan? timeout, bool disableJitter, - Func? shouldBounce, Func? shouldRetryResult, TimeSpan? maxDelay = null) + Func? shouldBounce, Func? shouldRetryResult, TimeSpan? maxDelay = null, BounceExtras? extras = null) { Retries = retries; BaseDelay = baseDelay; @@ -197,6 +267,7 @@ private Bounce(int retries, TimeSpan baseDelay, TimeSpan? timeout, bool disableJ ShouldBounce = shouldBounce; ShouldRetryResult = shouldRetryResult; _maxDelay = maxDelay; + _extras = extras; } /// @@ -227,7 +298,7 @@ public Bounce WithDelay(TimeSpan delay) { if (delay < TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(delay), "Delay cannot be negative"); - return new Bounce(Retries, delay, Timeout, DisableJitter, ShouldBounce, ShouldRetryResult, _maxDelay); + return new Bounce(Retries, delay, Timeout, DisableJitter, ShouldBounce, ShouldRetryResult, _maxDelay, _extras); } /// @@ -236,7 +307,7 @@ public Bounce WithDelay(TimeSpan delay) /// /// A new Bounce configuration with jitter disabled. public Bounce WithoutJitter() => - new Bounce(Retries, BaseDelay, Timeout, disableJitter: true, ShouldBounce, ShouldRetryResult, _maxDelay); + new Bounce(Retries, BaseDelay, Timeout, disableJitter: true, ShouldBounce, ShouldRetryResult, _maxDelay, _extras); /// /// Sets a predicate to determine which exceptions should trigger a retry. @@ -244,7 +315,7 @@ public Bounce WithoutJitter() => /// The exception predicate. /// A new Bounce configuration with the specified predicate. public Bounce When(Func predicate) => - new Bounce(Retries, BaseDelay, Timeout, DisableJitter, predicate, ShouldRetryResult, _maxDelay); + new Bounce(Retries, BaseDelay, Timeout, DisableJitter, predicate, ShouldRetryResult, _maxDelay, _extras); /// /// Sets a predicate to determine which results should trigger a retry. @@ -252,7 +323,7 @@ public Bounce When(Func predicate) => /// The result predicate (returns true to retry). /// A new Bounce configuration with the specified result predicate. public Bounce WhenResult(Func predicate) => - new Bounce(Retries, BaseDelay, Timeout, DisableJitter, ShouldBounce, predicate, _maxDelay); + new Bounce(Retries, BaseDelay, Timeout, DisableJitter, ShouldBounce, predicate, _maxDelay, _extras); /// /// Sets the maximum delay between retries. @@ -266,7 +337,7 @@ public Bounce WithMaxDelay(TimeSpan maxDelay) { if (maxDelay <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(maxDelay), "Max delay must be positive"); - return new Bounce(Retries, BaseDelay, Timeout, DisableJitter, ShouldBounce, ShouldRetryResult, maxDelay); + return new Bounce(Retries, BaseDelay, Timeout, DisableJitter, ShouldBounce, ShouldRetryResult, maxDelay, _extras); } /// @@ -281,7 +352,71 @@ public Bounce WithTimeout(TimeSpan timeout) { if (timeout <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(timeout), "Timeout must be positive"); - return new Bounce(Retries, BaseDelay, timeout, DisableJitter, ShouldBounce, ShouldRetryResult, _maxDelay); + return new Bounce(Retries, BaseDelay, timeout, DisableJitter, ShouldBounce, ShouldRetryResult, _maxDelay, _extras); + } + + /// + /// Sets a timeout for each single try. When one try runs longer, it is cancelled + /// (the token passed to a cancellable action is cancelled) and fails with a + /// , which is retried like any other failure + /// that passes the exception predicate. The overall still + /// bounds the whole operation including retries. Enforced only by the asynchronous + /// ShotAsync overloads; the synchronous Shot overloads throw InvalidOperationException. + /// + /// The per-try timeout. Must be positive. + /// A new Bounce configuration with the specified per-try timeout. + public Bounce WithAttemptTimeout(TimeSpan timeout) + { + if (timeout <= TimeSpan.Zero) + throw new ArgumentOutOfRangeException(nameof(timeout), "Attempt timeout must be positive"); + return new Bounce(Retries, BaseDelay, Timeout, DisableJitter, ShouldBounce, ShouldRetryResult, _maxDelay, BounceExtras.With(_extras, attemptTimeout: timeout)); + } + + /// + /// Sets a function that can name the delay before the next retry, for example the + /// Retry-After a server sent. It receives the exception that failed the try. Return null + /// to use the computed backoff. A returned delay replaces the computed delay (no jitter is + /// added), is clamped to zero at the bottom and to at the top, and + /// is still cut short by the overall timeout and by cancellation. A hint does not feed the + /// jitter sequence, and a hint that throws is ignored. + /// + /// Returns the delay to wait, or null for the computed backoff. + /// A new Bounce configuration with the specified delay hint. + public Bounce WithDelayHint(Func hint) + { + if (hint == null) throw new ArgumentNullException(nameof(hint)); + return new Bounce(Retries, BaseDelay, Timeout, DisableJitter, ShouldBounce, ShouldRetryResult, _maxDelay, BounceExtras.With(_extras, delayHint: hint)); + } + + // Test seam: replaces Task.Delay so a fake clock can observe and release the waits. + internal Bounce WithSleep(Func sleep) => + new Bounce(Retries, BaseDelay, Timeout, DisableJitter, ShouldBounce, ShouldRetryResult, _maxDelay, BounceExtras.With(_extras, sleep: sleep)); + } +} + +namespace Carom +{ + /// + /// Optional Bounce settings, kept behind one reference so the common Bounce is unchanged. + /// + internal sealed class BounceExtras + { + public TimeSpan? AttemptTimeout { get; private set; } + public Func? DelayHint { get; private set; } + public Func? Sleep { get; private set; } + + public static BounceExtras With( + BounceExtras? current, + TimeSpan? attemptTimeout = null, + Func? delayHint = null, + Func? sleep = null) + { + return new BounceExtras + { + AttemptTimeout = attemptTimeout ?? current?.AttemptTimeout, + DelayHint = delayHint ?? current?.DelayHint, + Sleep = sleep ?? current?.Sleep, + }; } } } diff --git a/src/Carom/Carom.cs b/src/Carom/Carom.cs index c11882a..bd6ff5a 100644 --- a/src/Carom/Carom.cs +++ b/src/Carom/Carom.cs @@ -64,7 +64,8 @@ private static T ShotCore( Func? shouldBounce, Func? shouldRetryResult, bool disableJitter, - TimeSpan? maxDelay) + TimeSpan? maxDelay, + BounceExtras? extras = null) { if (action == null) throw new ArgumentNullException(nameof(action)); retries = Math.Max(0, retries); @@ -92,8 +93,7 @@ private static T ShotCore( // Calculate and wait for the next delay var nextDelay = JitterStrategy.CalculateDelay(delay, previousDelay, disableJitter, attempt + 1, maxDelay); - var onResultRetry = CaromHooks.OnRetry; - if (onResultRetry != null) CaromHooks.Invoke(onResultRetry, new RetrySignal(attempt + 1, nextDelay, null)); + if (CaromHooks.HasRetryHandlers) CaromHooks.RaiseRetry(new RetrySignal(attempt + 1, nextDelay, null)); Thread.Sleep(nextDelay); previousDelay = nextDelay; continue; @@ -119,11 +119,11 @@ private static T ShotCore( } // Calculate and wait for the next delay - var nextDelay = JitterStrategy.CalculateDelay(delay, previousDelay, disableJitter, attempt + 1, maxDelay); - var onRetry = CaromHooks.OnRetry; - if (onRetry != null) CaromHooks.Invoke(onRetry, new RetrySignal(attempt + 1, nextDelay, ex.GetType().Name)); + var hinted = TryGetDelayHint(extras, ex, maxDelay, out var nextDelay); + if (!hinted) nextDelay = JitterStrategy.CalculateDelay(delay, previousDelay, disableJitter, attempt + 1, maxDelay); + if (CaromHooks.HasRetryHandlers) CaromHooks.RaiseRetry(new RetrySignal(attempt + 1, nextDelay, ex.GetType().Name)); Thread.Sleep(nextDelay); - previousDelay = nextDelay; + if (!hinted) previousDelay = nextDelay; } } @@ -147,7 +147,8 @@ private static void ShotCore( TimeSpan? baseDelay, Func? shouldBounce, bool disableJitter, - TimeSpan? maxDelay) + TimeSpan? maxDelay, + BounceExtras? extras = null) { if (action == null) throw new ArgumentNullException(nameof(action)); retries = Math.Max(0, retries); @@ -169,11 +170,11 @@ private static void ShotCore( if (!ShouldRetryException(ex, shouldBounce)) throw; if (attempt >= retries) throw; - var nextDelay = JitterStrategy.CalculateDelay(delay, previousDelay, disableJitter, attempt + 1, maxDelay); - var onRetry = CaromHooks.OnRetry; - if (onRetry != null) CaromHooks.Invoke(onRetry, new RetrySignal(attempt + 1, nextDelay, ex.GetType().Name)); + var hinted = TryGetDelayHint(extras, ex, maxDelay, out var nextDelay); + if (!hinted) nextDelay = JitterStrategy.CalculateDelay(delay, previousDelay, disableJitter, attempt + 1, maxDelay); + if (CaromHooks.HasRetryHandlers) CaromHooks.RaiseRetry(new RetrySignal(attempt + 1, nextDelay, ex.GetType().Name)); Thread.Sleep(nextDelay); - previousDelay = nextDelay; + if (!hinted) previousDelay = nextDelay; } } @@ -192,8 +193,8 @@ private static void ShotCore( /// The bounce carries a timeout. public static T Shot(Func action, Bounce bounce) { - ThrowIfTimeoutOnSyncPath(bounce.Timeout); - return ShotCore(action, bounce.Retries, bounce.BaseDelay, bounce.ShouldBounce, shouldRetryResult: null, bounce.DisableJitter, bounce.MaxDelay); + ThrowIfTimeoutOnSyncPath(bounce.Timeout, bounce.Extras); + return ShotCore(action, bounce.Retries, bounce.BaseDelay, bounce.ShouldBounce, shouldRetryResult: null, bounce.DisableJitter, bounce.MaxDelay, bounce.Extras); } /// @@ -208,8 +209,8 @@ public static T Shot(Func action, Bounce bounce) /// The bounce carries a timeout. public static T Shot(Func action, Bounce bounce) { - ThrowIfTimeoutOnSyncPath(bounce.Timeout); - return ShotCore(action, bounce.Retries, bounce.BaseDelay, bounce.ShouldBounce, bounce.ShouldRetryResult, bounce.DisableJitter, bounce.MaxDelay); + ThrowIfTimeoutOnSyncPath(bounce.Timeout, bounce.Extras); + return ShotCore(action, bounce.Retries, bounce.BaseDelay, bounce.ShouldBounce, bounce.ShouldRetryResult, bounce.DisableJitter, bounce.MaxDelay, bounce.Extras); } /// @@ -222,15 +223,19 @@ public static T Shot(Func action, Bounce bounce) /// The bounce carries a timeout. public static void Shot(Action action, Bounce bounce) { - ThrowIfTimeoutOnSyncPath(bounce.Timeout); - ShotCore(action, bounce.Retries, bounce.BaseDelay, bounce.ShouldBounce, bounce.DisableJitter, bounce.MaxDelay); + ThrowIfTimeoutOnSyncPath(bounce.Timeout, bounce.Extras); + ShotCore(action, bounce.Retries, bounce.BaseDelay, bounce.ShouldBounce, bounce.DisableJitter, bounce.MaxDelay, bounce.Extras); } /// /// Rejects a Bounce timeout on the synchronous path, which cannot enforce one. /// - private static void ThrowIfTimeoutOnSyncPath(TimeSpan? timeout) + private static void ThrowIfTimeoutOnSyncPath(TimeSpan? timeout, BounceExtras? extras) { + if (extras?.AttemptTimeout != null) + throw new InvalidOperationException( + "This Bounce carries an attempt timeout, but the synchronous Shot overloads cannot enforce one. " + + "Use ShotAsync if the attempt timeout must be enforced, or remove WithAttemptTimeout from the Bounce."); if (timeout.HasValue) throw new InvalidOperationException( "This Bounce carries a timeout, but the synchronous Shot overloads cannot enforce one. " + @@ -362,7 +367,8 @@ private static async Task ShotAsyncCore( Func? shouldRetryResult, bool disableJitter, CancellationToken ct, - TimeSpan? maxDelay = null) + TimeSpan? maxDelay = null, + BounceExtras? extras = null) { if (timeout.HasValue && timeout.Value <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(timeout), "Timeout must be positive"); @@ -390,32 +396,48 @@ private static async Task ShotAsyncCore( { effectiveCt.ThrowIfCancellationRequested(); + // Each try runs on its own token only when an attempt timeout is set. + var attemptTimeout = extras?.AttemptTimeout; + using var attemptCts = attemptTimeout.HasValue + ? CancellationTokenSource.CreateLinkedTokenSource(effectiveCt) + : null; + if (attemptCts != null) attemptCts.CancelAfter(attemptTimeout!.Value); + var tryCt = attemptCts?.Token ?? effectiveCt; + try { - Task task = ctAction != null ? ctAction(effectiveCt) : action!(); T result; - - // Only use WhenAny pattern if we have a cancellation mechanism - // This prevents Task.Delay(-1, ct) from leaking when ct is never cancelled - if (effectiveCt.CanBeCanceled) + try { - var completedTask = await Task.WhenAny(task, Task.Delay(-1, effectiveCt)).ConfigureAwait(false); + Task task = ctAction != null ? ctAction(tryCt) : action!(); - if (completedTask == task) + // Only use WhenAny pattern if we have a cancellation mechanism + // This prevents Task.Delay(-1, ct) from leaking when ct is never cancelled + if (tryCt.CanBeCanceled) { - result = await task.ConfigureAwait(false); + var completedTask = await Task.WhenAny(task, Task.Delay(-1, tryCt)).ConfigureAwait(false); + + if (completedTask == task) + { + result = await task.ConfigureAwait(false); + } + else + { + // Task.Delay completed, which means the try token was cancelled (timeout or manual) + ObserveAbandonedTask(task); + throw new OperationCanceledException(tryCt); + } } else { - // Task.Delay completed, which means effectiveCt was cancelled (timeout or manual) - ObserveAbandonedTask(task); - throw new OperationCanceledException(effectiveCt); + // No cancellation possible - just await directly (prevents leak) + result = await task.ConfigureAwait(false); } } - else + catch (OperationCanceledException) when (attemptCts != null && attemptCts.IsCancellationRequested && !effectiveCt.IsCancellationRequested) { - // No cancellation possible - just await directly (prevents leak) - result = await task.ConfigureAwait(false); + // The per-try timer fired, not the overall timeout or the caller. + throw new TimeoutRejectedException(attemptTimeout!.Value); } // Check if we should retry based on result @@ -431,9 +453,8 @@ private static async Task ShotAsyncCore( // Calculate and wait for the next delay var nextDelay = JitterStrategy.CalculateDelay(delay, previousDelay, disableJitter, attempt + 1, maxDelay); - var onResultRetry = CaromHooks.OnRetry; - if (onResultRetry != null) CaromHooks.Invoke(onResultRetry, new RetrySignal(attempt + 1, nextDelay, null)); - await Task.Delay(nextDelay, effectiveCt).ConfigureAwait(false); + if (CaromHooks.HasRetryHandlers) CaromHooks.RaiseRetry(new RetrySignal(attempt + 1, nextDelay, null)); + await SleepAsync(extras, nextDelay, effectiveCt).ConfigureAwait(false); previousDelay = nextDelay; continue; } @@ -465,11 +486,11 @@ private static async Task ShotAsyncCore( } // Calculate and wait for the next delay - var nextDelay = JitterStrategy.CalculateDelay(delay, previousDelay, disableJitter, attempt + 1, maxDelay); - var onRetry = CaromHooks.OnRetry; - if (onRetry != null) CaromHooks.Invoke(onRetry, new RetrySignal(attempt + 1, nextDelay, ex.GetType().Name)); - await BackoffDelayAsync(nextDelay, effectiveCt, timeout, ct).ConfigureAwait(false); - previousDelay = nextDelay; + var hinted = TryGetDelayHint(extras, ex, maxDelay, out var nextDelay); + if (!hinted) nextDelay = JitterStrategy.CalculateDelay(delay, previousDelay, disableJitter, attempt + 1, maxDelay); + if (CaromHooks.HasRetryHandlers) CaromHooks.RaiseRetry(new RetrySignal(attempt + 1, nextDelay, ex.GetType().Name)); + await BackoffDelayAsync(nextDelay, effectiveCt, timeout, ct, extras).ConfigureAwait(false); + if (!hinted) previousDelay = nextDelay; } } @@ -537,7 +558,8 @@ private static async Task ShotAsyncCore( Func? shouldBounce, bool disableJitter, CancellationToken ct, - TimeSpan? maxDelay = null) + TimeSpan? maxDelay = null, + BounceExtras? extras = null) { if (timeout.HasValue && timeout.Value <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(timeout), "Timeout must be positive"); @@ -564,30 +586,46 @@ private static async Task ShotAsyncCore( { effectiveCt.ThrowIfCancellationRequested(); + // Each try runs on its own token only when an attempt timeout is set. + var attemptTimeout = extras?.AttemptTimeout; + using var attemptCts = attemptTimeout.HasValue + ? CancellationTokenSource.CreateLinkedTokenSource(effectiveCt) + : null; + if (attemptCts != null) attemptCts.CancelAfter(attemptTimeout!.Value); + var tryCt = attemptCts?.Token ?? effectiveCt; + try { - var task = ctAction != null ? ctAction(effectiveCt) : action!(); - - // Only use WhenAny pattern if we have a cancellation mechanism - // This prevents Task.Delay(-1, ct) from leaking when ct is never cancelled - if (effectiveCt.CanBeCanceled) + try { - var completedTask = await Task.WhenAny(task, Task.Delay(-1, effectiveCt)).ConfigureAwait(false); + var task = ctAction != null ? ctAction(tryCt) : action!(); - if (completedTask == task) + // Only use WhenAny pattern if we have a cancellation mechanism + // This prevents Task.Delay(-1, ct) from leaking when ct is never cancelled + if (tryCt.CanBeCanceled) { + var completedTask = await Task.WhenAny(task, Task.Delay(-1, tryCt)).ConfigureAwait(false); + + if (completedTask == task) + { + await task.ConfigureAwait(false); + return; + } + + ObserveAbandonedTask(task); + throw new OperationCanceledException(tryCt); + } + else + { + // No cancellation possible - just await directly (prevents leak) await task.ConfigureAwait(false); return; } - - ObserveAbandonedTask(task); - throw new OperationCanceledException(effectiveCt); } - else + catch (OperationCanceledException) when (attemptCts != null && attemptCts.IsCancellationRequested && !effectiveCt.IsCancellationRequested) { - // No cancellation possible - just await directly (prevents leak) - await task.ConfigureAwait(false); - return; + // The per-try timer fired, not the overall timeout or the caller. + throw new TimeoutRejectedException(attemptTimeout!.Value); } } catch (OperationCanceledException) when (effectiveCt.IsCancellationRequested) @@ -604,11 +642,11 @@ private static async Task ShotAsyncCore( if (!ShouldRetryException(ex, shouldBounce)) throw; if (attempt >= retries) throw; - var nextDelay = JitterStrategy.CalculateDelay(delay, previousDelay, disableJitter, attempt + 1, maxDelay); - var onRetry = CaromHooks.OnRetry; - if (onRetry != null) CaromHooks.Invoke(onRetry, new RetrySignal(attempt + 1, nextDelay, ex.GetType().Name)); - await BackoffDelayAsync(nextDelay, effectiveCt, timeout, ct).ConfigureAwait(false); - previousDelay = nextDelay; + var hinted = TryGetDelayHint(extras, ex, maxDelay, out var nextDelay); + if (!hinted) nextDelay = JitterStrategy.CalculateDelay(delay, previousDelay, disableJitter, attempt + 1, maxDelay); + if (CaromHooks.HasRetryHandlers) CaromHooks.RaiseRetry(new RetrySignal(attempt + 1, nextDelay, ex.GetType().Name)); + await BackoffDelayAsync(nextDelay, effectiveCt, timeout, ct, extras).ConfigureAwait(false); + if (!hinted) previousDelay = nextDelay; } } @@ -636,11 +674,12 @@ private static async Task BackoffDelayAsync( TimeSpan nextDelay, CancellationToken effectiveCt, TimeSpan? timeout, - CancellationToken ct) + CancellationToken ct, + BounceExtras? extras = null) { try { - await Task.Delay(nextDelay, effectiveCt).ConfigureAwait(false); + await SleepAsync(extras, nextDelay, effectiveCt).ConfigureAwait(false); } catch (OperationCanceledException) when (effectiveCt.IsCancellationRequested) { @@ -650,6 +689,46 @@ private static async Task BackoffDelayAsync( } } + /// + /// Waits out a delay. Task.Delay unless a test replaced the clock. + /// + private static Task SleepAsync(BounceExtras? extras, TimeSpan delay, CancellationToken ct) + { + var sleep = extras?.Sleep; + return sleep != null ? sleep(delay, ct) : Task.Delay(delay, ct); + } + + /// + /// Asks the delay hint for the wait before the next retry. A hint is clamped to + /// [0, MaxDelay]. Returns false (use the computed backoff) when there is no hint, + /// it returns null, or it throws. + /// + private static bool TryGetDelayHint(BounceExtras? extras, Exception ex, TimeSpan? maxDelay, out TimeSpan delay) + { + delay = TimeSpan.Zero; + var hint = extras?.DelayHint; + if (hint == null) return false; + + TimeSpan? hinted; + try + { + hinted = hint(ex); + } + catch + { + return false; + } + + if (!hinted.HasValue) return false; + + var cap = maxDelay ?? JitterStrategy.DefaultMaxDelay; + var value = hinted.Value; + if (value < TimeSpan.Zero) value = TimeSpan.Zero; + if (value > cap) value = cap; + delay = value; + return true; + } + /// /// Attaches a fault observer to a task abandoned after losing the timeout race, /// so its eventual exception never surfaces as an UnobservedTaskException. @@ -675,7 +754,7 @@ private static void ObserveAbandonedTask(Task task) public static Task ShotAsync(Func> action, Bounce bounce, CancellationToken ct = default) { if (action == null) throw new ArgumentNullException(nameof(action)); - return ShotAsyncCore(action, ctAction: null, bounce.Retries, bounce.BaseDelay, bounce.Timeout, bounce.ShouldBounce, shouldRetryResult: null, bounce.DisableJitter, ct, bounce.MaxDelay); + return ShotAsyncCore(action, ctAction: null, bounce.Retries, bounce.BaseDelay, bounce.Timeout, bounce.ShouldBounce, shouldRetryResult: null, bounce.DisableJitter, ct, bounce.MaxDelay, bounce.Extras); } /// @@ -689,7 +768,7 @@ public static Task ShotAsync(Func> action, Bounce bounce, Cancella public static Task ShotAsync(Func> action, Bounce bounce, CancellationToken ct = default) { if (action == null) throw new ArgumentNullException(nameof(action)); - return ShotAsyncCore(action, ctAction: null, bounce.Retries, bounce.BaseDelay, bounce.Timeout, bounce.ShouldBounce, bounce.ShouldRetryResult, bounce.DisableJitter, ct, bounce.MaxDelay); + return ShotAsyncCore(action, ctAction: null, bounce.Retries, bounce.BaseDelay, bounce.Timeout, bounce.ShouldBounce, bounce.ShouldRetryResult, bounce.DisableJitter, ct, bounce.MaxDelay, bounce.Extras); } /// @@ -701,7 +780,7 @@ public static Task ShotAsync(Func> action, Bounce bounce, Cance public static Task ShotAsync(Func action, Bounce bounce, CancellationToken ct = default) { if (action == null) throw new ArgumentNullException(nameof(action)); - return ShotAsyncCore(action, ctAction: null, bounce.Retries, bounce.BaseDelay, bounce.Timeout, bounce.ShouldBounce, bounce.DisableJitter, ct, bounce.MaxDelay); + return ShotAsyncCore(action, ctAction: null, bounce.Retries, bounce.BaseDelay, bounce.Timeout, bounce.ShouldBounce, bounce.DisableJitter, ct, bounce.MaxDelay, bounce.Extras); } /// @@ -716,7 +795,7 @@ public static Task ShotAsync(Func action, Bounce bounce, CancellationToken public static Task ShotAsync(Func> action, Bounce bounce, CancellationToken ct = default) { if (action == null) throw new ArgumentNullException(nameof(action)); - return ShotAsyncCore(action: null, ctAction: action, bounce.Retries, bounce.BaseDelay, bounce.Timeout, bounce.ShouldBounce, shouldRetryResult: null, bounce.DisableJitter, ct, bounce.MaxDelay); + return ShotAsyncCore(action: null, ctAction: action, bounce.Retries, bounce.BaseDelay, bounce.Timeout, bounce.ShouldBounce, shouldRetryResult: null, bounce.DisableJitter, ct, bounce.MaxDelay, bounce.Extras); } /// @@ -731,7 +810,7 @@ public static Task ShotAsync(Func> action, Boun public static Task ShotAsync(Func> action, Bounce bounce, CancellationToken ct = default) { if (action == null) throw new ArgumentNullException(nameof(action)); - return ShotAsyncCore(action: null, ctAction: action, bounce.Retries, bounce.BaseDelay, bounce.Timeout, bounce.ShouldBounce, bounce.ShouldRetryResult, bounce.DisableJitter, ct, bounce.MaxDelay); + return ShotAsyncCore(action: null, ctAction: action, bounce.Retries, bounce.BaseDelay, bounce.Timeout, bounce.ShouldBounce, bounce.ShouldRetryResult, bounce.DisableJitter, ct, bounce.MaxDelay, bounce.Extras); } /// @@ -744,7 +823,7 @@ public static Task ShotAsync(Func> action, Boun public static Task ShotAsync(Func action, Bounce bounce, CancellationToken ct = default) { if (action == null) throw new ArgumentNullException(nameof(action)); - return ShotAsyncCore(action: null, ctAction: action, bounce.Retries, bounce.BaseDelay, bounce.Timeout, bounce.ShouldBounce, bounce.DisableJitter, ct, bounce.MaxDelay); + return ShotAsyncCore(action: null, ctAction: action, bounce.Retries, bounce.BaseDelay, bounce.Timeout, bounce.ShouldBounce, bounce.DisableJitter, ct, bounce.MaxDelay, bounce.Extras); } #endregion diff --git a/src/Carom/CaromHooks.cs b/src/Carom/CaromHooks.cs index 20508bb..514d524 100644 --- a/src/Carom/CaromHooks.cs +++ b/src/Carom/CaromHooks.cs @@ -73,16 +73,57 @@ public RateLimitRejectedSignal(string serviceKey) /// /// Process-wide hooks raised by Carom and Carom.Extensions. Subscribe with += and - /// unsubscribe with -=. Plain settable delegates, not events, so a consumer or a - /// test can read, replace or clear a hook; an event could never be reset. + /// unsubscribe with -=. The retry hook is the event, whose add and + /// remove are atomic and which no consumer can overwrite. The other hooks are still plain + /// settable delegates, so a consumer or a test can read, replace or clear them. /// Nothing is computed or allocated when a hook is null, so an unsubscribed /// process pays nothing. Handlers run synchronously on the calling thread and /// must be fast and must not throw. /// public static class CaromHooks { - /// Raised after the backoff delay is computed, just before a retry runs. - public static Action? OnRetry { get; set; } + private static Action? _legacyOnRetry; + + /// + /// Raised after the backoff delay is computed, just before a retry runs. Add and remove + /// are atomic, and the event cannot be assigned from outside, so one subscriber cannot + /// remove another. Each subscriber is called on its own: one that throws does not stop + /// the ones after it. + /// + public static event Action? Retrying; + + /// + /// The old settable retry hook, still raised. Assigning it replaces only what was + /// assigned to this property, never a subscriber, but += on it is + /// still a non-atomic read, combine and write, so two threads can lose a subscriber. + /// + [Obsolete("Subscribe to CaromHooks.Retrying instead. This property is not atomic and will be removed in the next major version.")] + public static Action? OnRetry + { + get => _legacyOnRetry; + set => _legacyOnRetry = value; + } + + internal static bool HasRetryHandlers => _legacyOnRetry != null || Retrying != null; + + /// + /// Raises the retry hooks. Each handler runs on its own so a throwing or + /// misbehaving one cannot skip the rest. Allocates only while a subscriber exists. + /// + internal static void RaiseRetry(RetrySignal signal) + { + var legacy = _legacyOnRetry; + if (legacy != null) Invoke(legacy, signal); + + var handlers = Retrying; + if (handlers == null) return; + + var list = handlers.GetInvocationList(); + for (int i = 0; i < list.Length; i++) + { + Invoke((Action)list[i], signal); + } + } /// Raised when a circuit breaker transitions from closed to open. public static Action? OnCircuitOpened { get; set; } diff --git a/tests/Carom.ApiApproval.Tests/ApprovedApi/Carom.approved.txt b/tests/Carom.ApiApproval.Tests/ApprovedApi/Carom.approved.txt index 7ca1bdb..31760a7 100644 --- a/tests/Carom.ApiApproval.Tests/ApprovedApi/Carom.approved.txt +++ b/tests/Carom.ApiApproval.Tests/ApprovedApi/Carom.approved.txt @@ -4,14 +4,18 @@ namespace Carom { public readonly struct Bounce { + public System.TimeSpan? AttemptTimeout { get; } public System.TimeSpan BaseDelay { get; } + public System.Func? DelayHint { get; } public bool DisableJitter { get; } public System.TimeSpan MaxDelay { get; } public int Retries { get; } public System.Func? ShouldBounce { get; } public System.TimeSpan? Timeout { get; } public Carom.Bounce When(System.Func predicate) { } + public Carom.Bounce WithAttemptTimeout(System.TimeSpan timeout) { } public Carom.Bounce WithDelay(System.TimeSpan delay) { } + public Carom.Bounce WithDelayHint(System.Func hint) { } public Carom.Bounce WithMaxDelay(System.TimeSpan maxDelay) { } public Carom.Bounce WithTimeout(System.TimeSpan timeout) { } public Carom.Bounce WithoutJitter() { } @@ -22,7 +26,9 @@ namespace Carom } public readonly struct Bounce { + public System.TimeSpan? AttemptTimeout { get; } public System.TimeSpan BaseDelay { get; } + public System.Func? DelayHint { get; } public bool DisableJitter { get; } public System.TimeSpan MaxDelay { get; } public int Retries { get; } @@ -31,7 +37,9 @@ namespace Carom public System.TimeSpan? Timeout { get; } public Carom.Bounce When(System.Func predicate) { } public Carom.Bounce WhenResult(System.Func predicate) { } + public Carom.Bounce WithAttemptTimeout(System.TimeSpan timeout) { } public Carom.Bounce WithDelay(System.TimeSpan delay) { } + public Carom.Bounce WithDelayHint(System.Func hint) { } public Carom.Bounce WithMaxDelay(System.TimeSpan maxDelay) { } public Carom.Bounce WithTimeout(System.TimeSpan timeout) { } public Carom.Bounce WithoutJitter() { } @@ -70,7 +78,10 @@ namespace Carom public static System.Action? OnBulkheadRejected { get; set; } public static System.Action? OnCircuitOpened { get; set; } public static System.Action? OnRateLimitRejected { get; set; } + [System.Obsolete("Subscribe to CaromHooks.Retrying instead. This property is not atomic and will be" + + " removed in the next major version.")] public static System.Action? OnRetry { get; set; } + public static event System.Action? Retrying; } public readonly struct CircuitOpenedSignal { diff --git a/tests/Carom.ReadmeSamples.Tests/Carom.ReadmeSamples.Tests.csproj b/tests/Carom.ReadmeSamples.Tests/Carom.ReadmeSamples.Tests.csproj new file mode 100644 index 0000000..aab577c --- /dev/null +++ b/tests/Carom.ReadmeSamples.Tests/Carom.ReadmeSamples.Tests.csproj @@ -0,0 +1,24 @@ + + + + net8.0;net10.0 + latest + enable + disable + false + true + $(NoWarn);CS1591 + + + + + + + + + + + + + + diff --git a/tests/Carom.ReadmeSamples.Tests/ReadmeSamples.cs b/tests/Carom.ReadmeSamples.Tests/ReadmeSamples.cs new file mode 100644 index 0000000..9455065 --- /dev/null +++ b/tests/Carom.ReadmeSamples.Tests/ReadmeSamples.cs @@ -0,0 +1,81 @@ +// Every sample here is copied from README.md and compiled as a consumer would write it: +// the using directives sit at the top of the file, outside any namespace, which is where +// `Carom.ShotAsync` stops resolving because the namespace Carom hides the class Carom. +// ReadmeSamplesTests checks that each fragment below still matches the README text. +// +// readme:begin basic-usage +using Carom; +using Retry = Carom.Carom; +// readme:end basic-usage +using System; +using System.Threading; +using System.Threading.Tasks; + +public sealed class RateLimitedException : Exception +{ + public TimeSpan RetryAfter { get; set; } +} + +public sealed class ApiClient +{ + public Task CallAsync() => Task.FromResult(1); + public Task FetchAsync() => Task.FromResult("data"); + public Task FetchAsync(CancellationToken ct) => Task.FromResult("data"); +} + +public static class ReadmeSamples +{ + private static readonly ApiClient api = new ApiClient(); + private static readonly ApiClient apiClient = new ApiClient(); + + public static async Task BasicUsage() + { + // readme:begin basic-usage + // Simple retry with exponential backoff + var result = await Retry.ShotAsync(() => api.CallAsync(), retries: 3); + + // With timeout + var bounce = Bounce.Times(5).WithTimeout(TimeSpan.FromSeconds(30)); + var data = await Retry.ShotAsync(() => apiClient.FetchAsync(), bounce); + // readme:end basic-usage + + GC.KeepAlive(result); + GC.KeepAlive(data); + } + + public static async Task AttemptTimeout() + { + // readme:begin attempt-timeout + // Each try gets 2 seconds, the whole call gets 10 + var bounce = Bounce.Times(3) + .WithAttemptTimeout(TimeSpan.FromSeconds(2)) + .WithTimeout(TimeSpan.FromSeconds(10)); + + var data = await Retry.ShotAsync(ct => apiClient.FetchAsync(ct), bounce); + // readme:end attempt-timeout + + GC.KeepAlive(data); + } + + public static async Task DelayHint() + { + // readme:begin delay-hint + // 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); + // readme:end delay-hint + + GC.KeepAlive(data); + } + + public static void RetryEvent() + { + // readme:begin retry-event + CaromHooks.Retrying += signal => + Console.WriteLine($"retry {signal.Attempt} in {signal.Delay}"); + // readme:end retry-event + } +} diff --git a/tests/Carom.ReadmeSamples.Tests/ReadmeSamplesTests.cs b/tests/Carom.ReadmeSamples.Tests/ReadmeSamplesTests.cs new file mode 100644 index 0000000..c89fecc --- /dev/null +++ b/tests/Carom.ReadmeSamples.Tests/ReadmeSamplesTests.cs @@ -0,0 +1,74 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.RegularExpressions; +using Xunit; + +namespace Carom.ReadmeSamples.Tests +{ + /// + /// The samples compile because this project builds ReadmeSamples.cs. These tests keep + /// that file and README.md saying the same thing, so a README edit that is not compiled + /// fails here. + /// + public class ReadmeSamplesTests + { + public static IEnumerable Samples => new[] + { + new object[] { "basic-usage" }, + new object[] { "attempt-timeout" }, + new object[] { "delay-hint" }, + new object[] { "retry-event" }, + }; + + [Theory] + [MemberData(nameof(Samples))] + public void ReadmeSample_MatchesTheCompiledSample(string name) + { + var root = FindRepoRoot(); + var readme = File.ReadAllText(Path.Combine(root, "README.md")); + var compiled = File.ReadAllText(Path.Combine(root, "tests", "Carom.ReadmeSamples.Tests", "ReadmeSamples.cs")); + + var fromReadme = ReadmeBlock(readme, name); + var fromSource = CompiledFragments(compiled, name); + + Assert.True(fromReadme != null, $"README.md has no `` block."); + Assert.True(Normalize(fromReadme!) == Normalize(fromSource), + $"README sample '{name}' differs from tests/Carom.ReadmeSamples.Tests/ReadmeSamples.cs. " + + "Change both together so the README text is the code that compiles."); + } + + private static string? ReadmeBlock(string readme, string name) + { + var m = Regex.Match(readme, + "\\s*```csharp\\r?\\n(.*?)```", + RegexOptions.Singleline); + return m.Success ? m.Groups[1].Value : null; + } + + private static string CompiledFragments(string source, string name) + { + var parts = new List(); + foreach (Match m in Regex.Matches(source, + "// readme:begin " + Regex.Escape(name) + "\\r?\\n(.*?)// readme:end " + Regex.Escape(name), + RegexOptions.Singleline)) + { + parts.Add(m.Groups[1].Value); + } + Assert.True(parts.Count > 0, $"ReadmeSamples.cs has no fragment named '{name}'."); + return string.Join("\n", parts); + } + + private static string Normalize(string text) => + string.Join("\n", text.Split('\n').Select(l => l.Trim()).Where(l => l.Length > 0)); + + private static string FindRepoRoot() + { + var dir = new DirectoryInfo(AppContext.BaseDirectory); + while (dir != null && !File.Exists(Path.Combine(dir.FullName, "Carom.sln"))) dir = dir.Parent; + Assert.True(dir != null, "Could not find Carom.sln above the test output directory."); + return dir!.FullName; + } + } +} diff --git a/tests/Carom.Tests/AttemptTimeoutTests.cs b/tests/Carom.Tests/AttemptTimeoutTests.cs new file mode 100644 index 0000000..d35e990 --- /dev/null +++ b/tests/Carom.Tests/AttemptTimeoutTests.cs @@ -0,0 +1,172 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using Xunit; + +namespace Carom.Tests +{ + /// + /// Bounce.WithAttemptTimeout: each try gets its own timeout, a try that runs out fails + /// with a retryable TimeoutRejectedException, and the overall timeout still wins. + /// Waits between tries go through a fake clock so no test sleeps for real. + /// + public class AttemptTimeoutTests + { + private static readonly Func NoWait = (_, _) => Task.CompletedTask; + + [Fact] + public void WithAttemptTimeout_SetsProperty_AndRejectsNonPositive() + { + var bounce = Bounce.Times(1).WithAttemptTimeout(TimeSpan.FromSeconds(2)); + + Assert.Equal(TimeSpan.FromSeconds(2), bounce.AttemptTimeout); + Assert.Null(Bounce.Times(1).AttemptTimeout); + Assert.Throws(() => Bounce.Times(1).WithAttemptTimeout(TimeSpan.Zero)); + } + + [Fact] + public void WithAttemptTimeout_SurvivesTheOtherWithMethods() + { + var bounce = Bounce.Times(1) + .WithAttemptTimeout(TimeSpan.FromSeconds(2)) + .WithDelay(TimeSpan.FromMilliseconds(5)) + .WithTimeout(TimeSpan.FromSeconds(9)) + .WithMaxDelay(TimeSpan.FromSeconds(1)) + .WithoutJitter(); + + Assert.Equal(TimeSpan.FromSeconds(2), bounce.AttemptTimeout); + } + + [Fact] + public async Task PerTryTimeout_FirstTryHangs_RetriesAndTheNextTrySucceeds() + { + var bounce = Bounce.Times(2).WithAttemptTimeout(TimeSpan.FromMilliseconds(50)).WithSleep(NoWait); + int calls = 0; + + var result = await Carom.ShotAsync(async ct => + { + calls++; + if (calls == 1) await Task.Delay(Timeout.Infinite, ct); + return 7; + }, bounce); + + Assert.Equal(7, result); + Assert.Equal(2, calls); + } + + [Fact] + public async Task PerTryTimeout_WithAnActionThatTakesNoToken_AbandonsTheTryAndRetries() + { + var bounce = Bounce.Times(2).WithAttemptTimeout(TimeSpan.FromMilliseconds(50)).WithSleep(NoWait); + int calls = 0; + + var result = await Carom.ShotAsync(() => + { + calls++; + return calls == 1 ? new TaskCompletionSource().Task : Task.FromResult(7); + }, bounce); + + Assert.Equal(7, result); + Assert.Equal(2, calls); + } + + [Fact] + public async Task PerTryTimeout_VoidAction_RetriesAndSucceeds() + { + var bounce = Bounce.Times(2).WithAttemptTimeout(TimeSpan.FromMilliseconds(50)).WithSleep(NoWait); + int calls = 0; + + await Carom.ShotAsync(async ct => + { + calls++; + if (calls == 1) await Task.Delay(Timeout.Infinite, ct); + }, bounce); + + Assert.Equal(2, calls); + } + + [Fact] + public async Task PerTryTimeout_EveryTryHangs_ThrowsTimeoutRejectedWithTheAttemptTimeout() + { + var attempt = TimeSpan.FromMilliseconds(40); + var bounce = Bounce.Times(1).WithAttemptTimeout(attempt).WithSleep(NoWait); + int calls = 0; + + var ex = await Assert.ThrowsAsync(() => + Carom.ShotAsync(async ct => + { + calls++; + await Task.Delay(Timeout.Infinite, ct); + return 0; + }, bounce)); + + Assert.Equal(attempt, ex.Timeout); + Assert.Equal(2, calls); + } + + [Fact] + public async Task PerTryTimeout_TypedBounce_RetriesAndSucceeds() + { + var bounce = Bounce.For(2).WithAttemptTimeout(TimeSpan.FromMilliseconds(50)).WithSleep(NoWait); + int calls = 0; + + var result = await Carom.ShotAsync(async ct => + { + calls++; + if (calls == 1) await Task.Delay(Timeout.Infinite, ct); + return "ok"; + }, bounce); + + Assert.Equal("ok", result); + } + + [Fact] + public async Task OverallTimeout_StillWins_OverALongerAttemptTimeout() + { + var overall = TimeSpan.FromMilliseconds(150); + var bounce = Bounce.Times(5) + .WithAttemptTimeout(TimeSpan.FromSeconds(30)) + .WithTimeout(overall) + .WithSleep(NoWait); + + var ex = await Assert.ThrowsAsync(() => + Carom.ShotAsync(async ct => + { + await Task.Delay(Timeout.Infinite, ct); + return 0; + }, bounce)); + + Assert.Equal(overall, ex.Timeout); + } + + [Fact] + public async Task CallerCancellation_IsNotTurnedIntoAnAttemptTimeout() + { + var bounce = Bounce.Times(3).WithAttemptTimeout(TimeSpan.FromSeconds(30)).WithSleep(NoWait); + using var cts = new CancellationTokenSource(); + int calls = 0; + + var task = Carom.ShotAsync(async ct => + { + calls++; + await Task.Delay(Timeout.Infinite, ct); + return 0; + }, bounce, cts.Token); + cts.CancelAfter(50); + + var ex = await Assert.ThrowsAnyAsync(() => task); + + Assert.IsNotType(ex); + Assert.Equal(1, calls); + } + + [Fact] + public void SyncShot_WithAnAttemptTimeout_Throws() + { + var bounce = Bounce.Times(1).WithAttemptTimeout(TimeSpan.FromSeconds(1)); + + Assert.Throws(() => Carom.Shot(() => 1, bounce)); + } + } +} diff --git a/tests/Carom.Tests/CaromHooksTests.cs b/tests/Carom.Tests/CaromHooksTests.cs index e2db6e8..9b53a94 100644 --- a/tests/Carom.Tests/CaromHooksTests.cs +++ b/tests/Carom.Tests/CaromHooksTests.cs @@ -1,3 +1,5 @@ +#pragma warning disable CS0618 // These tests cover the obsolete OnRetry property next to the Retrying event. + using System; using System.Collections.Generic; using System.Threading.Tasks; @@ -267,5 +269,141 @@ public async Task AThrowingHook_DoesNotBreakTheAsyncRetryItObserves() } } + [Fact] + public void Retrying_TwoSubscribers_BothReceiveTheRetry() + { + var threadId = Environment.CurrentManagedThreadId; + var first = new List(); + var second = new List(); + Action a = s => { if (Environment.CurrentManagedThreadId == threadId) first.Add(s); }; + Action b = s => { if (Environment.CurrentManagedThreadId == threadId) second.Add(s); }; + CaromHooks.Retrying += a; + CaromHooks.Retrying += b; + try + { + RunOneRetry(); + + Assert.Single(first); + Assert.Single(second); + Assert.Equal(1, first[0].Attempt); + } + finally + { + CaromHooks.Retrying -= a; + CaromHooks.Retrying -= b; + } + } + + [Fact] + public void Retrying_OneSubscriberUnsubscribing_LeavesTheOther() + { + var threadId = Environment.CurrentManagedThreadId; + var first = new List(); + var second = new List(); + Action a = s => { if (Environment.CurrentManagedThreadId == threadId) first.Add(s); }; + Action b = s => { if (Environment.CurrentManagedThreadId == threadId) second.Add(s); }; + CaromHooks.Retrying += a; + CaromHooks.Retrying += b; + try + { + CaromHooks.Retrying -= a; + + RunOneRetry(); + + Assert.Empty(first); + Assert.Single(second); + } + finally + { + CaromHooks.Retrying -= a; + CaromHooks.Retrying -= b; + } + } + + [Fact] + public void AssigningTheObsoleteProperty_DoesNotRemoveRetryingSubscribers() + { + var threadId = Environment.CurrentManagedThreadId; + var received = new List(); + Action sub = s => { if (Environment.CurrentManagedThreadId == threadId) received.Add(s); }; + var prior = CaromHooks.OnRetry; + CaromHooks.Retrying += sub; + try + { + // This is the assignment that used to wipe every other subscriber. + CaromHooks.OnRetry = _ => { }; + CaromHooks.OnRetry = null; + + RunOneRetry(); + + Assert.Single(received); + } + finally + { + CaromHooks.Retrying -= sub; + CaromHooks.OnRetry = prior; + } + } + + [Fact] + public void Retrying_AThrowingSubscriber_DoesNotStopTheNextOne() + { + var threadId = Environment.CurrentManagedThreadId; + var received = new List(); + Action bad = s => { if (Environment.CurrentManagedThreadId == threadId) throw new InvalidOperationException("broken"); }; + Action good = s => { if (Environment.CurrentManagedThreadId == threadId) received.Add(s); }; + CaromHooks.Retrying += bad; + CaromHooks.Retrying += good; + try + { + RunOneRetry(); + + Assert.Single(received); + } + finally + { + CaromHooks.Retrying -= bad; + CaromHooks.Retrying -= good; + } + } + + [Fact] + public void Retrying_AndTheObsoleteProperty_BothReceiveTheRetry() + { + var threadId = Environment.CurrentManagedThreadId; + int viaEvent = 0, viaProperty = 0; + Action sub = s => { if (Environment.CurrentManagedThreadId == threadId) viaEvent++; }; + var prior = CaromHooks.OnRetry; + CaromHooks.Retrying += sub; + CaromHooks.OnRetry = s => { if (Environment.CurrentManagedThreadId == threadId) viaProperty++; }; + try + { + RunOneRetry(); + + Assert.Equal(1, viaEvent); + Assert.Equal(1, viaProperty); + } + finally + { + CaromHooks.Retrying -= sub; + CaromHooks.OnRetry = prior; + } + } + + private static void RunOneRetry() + { + int calls = 0; + Carom.Shot( + () => + { + calls++; + if (calls == 1) throw new CaromHooksProbeException(); + return 7; + }, + retries: 2, + baseDelay: TimeSpan.Zero, + shouldBounce: null, + disableJitter: true); + } } } diff --git a/tests/Carom.Tests/DelayHintTests.cs b/tests/Carom.Tests/DelayHintTests.cs new file mode 100644 index 0000000..ec12254 --- /dev/null +++ b/tests/Carom.Tests/DelayHintTests.cs @@ -0,0 +1,235 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Threading; +using System.Threading.Tasks; +using Xunit; + +namespace Carom.Tests +{ + /// + /// Bounce.WithDelayHint: a server's Retry-After replaces the computed jitter, is clamped to + /// MaxDelay, and is still bounded by the overall timeout and by cancellation. The waits go + /// through a fake clock that records each requested delay and returns at once. + /// + public class DelayHintTests + { + private sealed class RetryAfterException : Exception + { + public TimeSpan After { get; } + public RetryAfterException(TimeSpan after) { After = after; } + } + + private sealed class FakeClock + { + public List Waits { get; } = new List(); + + public Task Sleep(TimeSpan delay, CancellationToken ct) + { + Waits.Add(delay); + return Task.CompletedTask; + } + } + + private static Func> FailOnceThenSucceed(Func failure) + { + int calls = 0; + return () => ++calls == 1 ? throw failure() : Task.FromResult(7); + } + + [Fact] + public async Task AHintOfThreeSeconds_IsWaited_InsteadOfJitter() + { + var clock = new FakeClock(); + var bounce = Bounce.Times(2) + .WithDelayHint(ex => ex is RetryAfterException r ? r.After : (TimeSpan?)null) + .WithSleep(clock.Sleep); + + var result = await Carom.ShotAsync( + FailOnceThenSucceed(() => new RetryAfterException(TimeSpan.FromSeconds(3))), bounce); + + Assert.Equal(7, result); + Assert.Equal(new[] { TimeSpan.FromSeconds(3) }, clock.Waits); + } + + [Fact] + public async Task AHintPastMaxDelay_IsClampedToMaxDelay() + { + var clock = new FakeClock(); + var bounce = Bounce.Times(2) + .WithMaxDelay(TimeSpan.FromSeconds(2)) + .WithDelayHint(_ => TimeSpan.FromMinutes(10)) + .WithSleep(clock.Sleep); + + await Carom.ShotAsync(FailOnceThenSucceed(() => new RetryAfterException(TimeSpan.Zero)), bounce); + + Assert.Equal(new[] { TimeSpan.FromSeconds(2) }, clock.Waits); + } + + [Fact] + public async Task AHintPastTheDefaultMaxDelay_IsClampedToThirtySeconds() + { + var clock = new FakeClock(); + var bounce = Bounce.Times(2) + .WithDelayHint(_ => TimeSpan.FromHours(1)) + .WithSleep(clock.Sleep); + + await Carom.ShotAsync(FailOnceThenSucceed(() => new RetryAfterException(TimeSpan.Zero)), bounce); + + Assert.Equal(new[] { TimeSpan.FromSeconds(30) }, clock.Waits); + } + + [Fact] + public async Task ANegativeHint_WaitsZero() + { + var clock = new FakeClock(); + var bounce = Bounce.Times(2).WithDelayHint(_ => TimeSpan.FromSeconds(-5)).WithSleep(clock.Sleep); + + await Carom.ShotAsync(FailOnceThenSucceed(() => new RetryAfterException(TimeSpan.Zero)), bounce); + + Assert.Equal(new[] { TimeSpan.Zero }, clock.Waits); + } + + [Fact] + public async Task ANullHint_FallsBackToTheComputedBackoff() + { + var clock = new FakeClock(); + var bounce = Bounce.Times(2) + .WithDelay(TimeSpan.FromMilliseconds(10)) + .WithoutJitter() + .WithDelayHint(_ => null) + .WithSleep(clock.Sleep); + + await Carom.ShotAsync(FailOnceThenSucceed(() => new RetryAfterException(TimeSpan.Zero)), bounce); + + // Jitter off: base * 2^attempt for the first retry. + Assert.Equal(new[] { TimeSpan.FromMilliseconds(20) }, clock.Waits); + } + + [Fact] + public async Task AThrowingHint_FallsBackToTheComputedBackoff() + { + var clock = new FakeClock(); + var bounce = Bounce.Times(2) + .WithDelay(TimeSpan.FromMilliseconds(10)) + .WithoutJitter() + .WithDelayHint(_ => throw new InvalidOperationException("broken hint")) + .WithSleep(clock.Sleep); + + var result = await Carom.ShotAsync( + FailOnceThenSucceed(() => new RetryAfterException(TimeSpan.Zero)), bounce); + + Assert.Equal(7, result); + Assert.Equal(new[] { TimeSpan.FromMilliseconds(20) }, clock.Waits); + } + + [Fact] + public async Task AHint_DoesNotFeedTheNextJitterRange() + { + var clock = new FakeClock(); + int calls = 0; + var bounce = Bounce.Times(3) + .WithDelay(TimeSpan.FromMilliseconds(10)) + .WithoutJitter() + .WithDelayHint(ex => ex is RetryAfterException ? TimeSpan.FromSeconds(3) : (TimeSpan?)null) + .WithSleep(clock.Sleep); + + await Carom.ShotAsync(() => + { + calls++; + if (calls == 1) throw new RetryAfterException(TimeSpan.Zero); + if (calls == 2) throw new InvalidOperationException("no hint"); + return Task.FromResult(7); + }, bounce); + + Assert.Equal(2, clock.Waits.Count); + Assert.Equal(TimeSpan.FromSeconds(3), clock.Waits[0]); + Assert.Equal(TimeSpan.FromMilliseconds(40), clock.Waits[1]); + } + + [Fact] + public async Task TypedBounce_AlsoHonoursTheHint() + { + var clock = new FakeClock(); + var bounce = Bounce.For(2).WithDelayHint(_ => TimeSpan.FromSeconds(3)).WithSleep(clock.Sleep); + + await Carom.ShotAsync(FailOnceThenSucceed(() => new RetryAfterException(TimeSpan.Zero)), bounce); + + Assert.Equal(new[] { TimeSpan.FromSeconds(3) }, clock.Waits); + } + + [Fact] + public async Task VoidAction_HonoursTheHint() + { + var clock = new FakeClock(); + var bounce = Bounce.Times(2).WithDelayHint(_ => TimeSpan.FromSeconds(3)).WithSleep(clock.Sleep); + int calls = 0; + + await Carom.ShotAsync(() => + { + if (++calls == 1) throw new RetryAfterException(TimeSpan.Zero); + return Task.CompletedTask; + }, bounce); + + Assert.Equal(new[] { TimeSpan.FromSeconds(3) }, clock.Waits); + } + + [Fact] + public async Task TheOverallTimeout_CutsAHintShort() + { + // Real clock on purpose: the wait must be cancelled by the overall timeout. + var overall = TimeSpan.FromMilliseconds(150); + var bounce = Bounce.Times(2) + .WithTimeout(overall) + .WithDelayHint(_ => TimeSpan.FromSeconds(20)); + var watch = Stopwatch.StartNew(); + + var ex = await Assert.ThrowsAsync(() => + Carom.ShotAsync(FailOnceThenSucceed(() => new RetryAfterException(TimeSpan.Zero)), bounce)); + + Assert.Equal(overall, ex.Timeout); + Assert.True(watch.Elapsed < TimeSpan.FromSeconds(10), "the hint was waited in full"); + } + + [Fact] + public async Task Cancellation_CutsAHintShort() + { + var bounce = Bounce.Times(2).WithDelayHint(_ => TimeSpan.FromSeconds(20)); + using var cts = new CancellationTokenSource(); + var watch = Stopwatch.StartNew(); + + var task = Carom.ShotAsync(FailOnceThenSucceed(() => new RetryAfterException(TimeSpan.Zero)), bounce, cts.Token); + cts.CancelAfter(100); + + var ex = await Assert.ThrowsAnyAsync(() => task); + + Assert.IsNotType(ex); + Assert.True(watch.Elapsed < TimeSpan.FromSeconds(10), "the hint was waited in full"); + } + + [Fact] + public void WithDelayHint_RejectsNull_AndSurvivesTheOtherWithMethods() + { + Assert.Throws(() => Bounce.Times(1).WithDelayHint(null!)); + + Func hint = _ => null; + var bounce = Bounce.Times(1).WithDelayHint(hint).WithDelay(TimeSpan.Zero).WithTimeout(TimeSpan.FromSeconds(1)).WithoutJitter(); + + Assert.Same(hint, bounce.DelayHint); + } + + [Fact] + public void SyncShot_HonoursTheHint() + { + var bounce = Bounce.Times(2).WithDelay(TimeSpan.FromSeconds(30)).WithDelayHint(_ => TimeSpan.FromMilliseconds(5)); + int calls = 0; + var watch = Stopwatch.StartNew(); + + var result = Carom.Shot(() => ++calls == 1 ? throw new RetryAfterException(TimeSpan.Zero) : 7, bounce); + + // The computed delay would be at least the 30 s base; the hint is 5 ms. + Assert.Equal(7, result); + Assert.True(watch.Elapsed < TimeSpan.FromSeconds(10)); + } + } +} diff --git a/tests/Carom.Tests/PublishedClaimsTests.cs b/tests/Carom.Tests/PublishedClaimsTests.cs index f827cf2..6cb5795 100644 --- a/tests/Carom.Tests/PublishedClaimsTests.cs +++ b/tests/Carom.Tests/PublishedClaimsTests.cs @@ -12,9 +12,9 @@ namespace Carom.Tests /// public class PublishedClaimsTests { - // README states these bounds. They sit about 10% above the measured 25.5 KB and 54 KB; + // README states these bounds. They sit about 10% above the measured 31 KB and 54 KB; // the old 40 KB and 100 KB bounds let the README's 21.5 KB core go stale unnoticed. - private const long CoreSizeBoundBytes = 28 * 1024; + private const long CoreSizeBoundBytes = 34 * 1024; private const long ExtensionsSizeBoundBytes = 60 * 1024; private static readonly Func SucceedingAction = static () => 42; @@ -53,7 +53,7 @@ public void CaromAssembly_StaysWithinPublishedSizeBound() Assert.True(size <= CoreSizeBoundBytes, $"Carom.dll is {size} bytes, over the {CoreSizeBoundBytes} byte bound. " + - "The README states a 28 KB bound for the core (the 'Tiny Footprint' bullet and the package table). " + + "The README states a 34 KB bound for the core (the 'Tiny Footprint' bullet and the package table). " + "Update the README sizes and this bound together, deliberately."); } From 4ea6686f605e924f4664658533aa6f7528b2b589 Mon Sep 17 00:00:00 2001 From: Arnel Robles Date: Sat, 14 Nov 2026 09:49:46 +0800 Subject: [PATCH 2/4] Move attempt timeout to Carom.Extensions and trim core under 28 KB --- CHANGELOG.md | 12 +- README.md | 27 +-- .../CaromAttemptTimeoutExtensions.cs | 123 ++++++++++++ src/Carom/Bounce.cs | 123 +++--------- src/Carom/Carom.cs | 183 +++++++----------- src/Carom/CaromHooks.cs | 20 +- .../ApprovedApi/Carom.Extensions.approved.txt | 6 + .../ApprovedApi/Carom.approved.txt | 9 +- .../AttemptTimeoutTests.cs | 138 +++++++++++++ .../Carom.ReadmeSamples.Tests.csproj | 1 + .../ReadmeSamples.cs | 10 +- tests/Carom.Tests/AttemptTimeoutTests.cs | 172 ---------------- tests/Carom.Tests/DelayHintTests.cs | 2 +- tests/Carom.Tests/PublishedClaimsTests.cs | 6 +- 14 files changed, 402 insertions(+), 430 deletions(-) create mode 100644 src/Carom.Extensions/CaromAttemptTimeoutExtensions.cs create mode 100644 tests/Carom.Extensions.Tests/AttemptTimeoutTests.cs delete mode 100644 tests/Carom.Tests/AttemptTimeoutTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 7feab5e..fc1b408 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,18 +9,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- `Bounce.WithAttemptTimeout(TimeSpan)` (also on `Bounce`): 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. The synchronous `Shot` overloads throw - `InvalidOperationException` if one is set, like `WithTimeout`. -- `Bounce.WithDelayHint(Func)` (also on `Bounce`): names the delay +- `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. It lives in the add-on package so the core + stays under its published size bound. +- `Bounce.WithDelayHint(Func)` (also on `Bounce`; 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. - `CaromHooks.Retrying` event. Add and remove are atomic and it cannot be assigned from outside, so one subscriber cannot remove another. -- The core assembly grew from 25.5 KB to 31 KB with these additions. The published size bound - moves from 28 KB to 34 KB, in the README and in `PublishedClaimsTests`. - `tests/Carom.ReadmeSamples.Tests` compiles the README samples and fails when the README text drifts from the compiled copy. diff --git a/README.md b/README.md index 418b2c8..75a61c6 100644 --- a/README.md +++ b/README.md @@ -15,17 +15,17 @@ 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** (31KB core, 54KB extensions) +- **Tiny Footprint** (27.5KB core, 57.5KB extensions) - **Fully Composable** (all patterns work together) ## 📦 Packages -Sizes are the Release-built assemblies. Tests fail if the core grows past 34KB or the extensions past 60KB. +Sizes are the Release-built assemblies. Tests fail if the core grows past 28KB or the extensions past 60KB. | Package | Size | Purpose | |---------|------|---------| -| **Carom** | 31KB | Core retry + timeout | -| **Carom.Extensions** | 54KB | Circuit Breaker, Fallback, Bulkhead, Rate Limiting | +| **Carom** | 27.5KB | Core retry + timeout | +| **Carom.Extensions** | 57.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 | @@ -62,19 +62,20 @@ file a bare `Carom.ShotAsync` does not resolve. The alias above fixes that, and ### Per-try timeout and Retry-After -`WithTimeout` bounds the whole call. `WithAttemptTimeout` bounds each try: 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. Attempt timeouts -need `ShotAsync`; the synchronous `Shot` overloads throw if one is set. +`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` action. ```csharp +using Carom.Extensions; + // Each try gets 2 seconds, the whole call gets 10 -var bounce = Bounce.Times(3) - .WithAttemptTimeout(TimeSpan.FromSeconds(2)) - .WithTimeout(TimeSpan.FromSeconds(10)); +var bounce = Bounce.Times(3).WithTimeout(TimeSpan.FromSeconds(10)); -var data = await Retry.ShotAsync(ct => apiClient.FetchAsync(ct), bounce); +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 @@ -201,7 +202,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 31 KB and Carom.Extensions.dll 54 KB. Polly.Core.dll (net8.0) is 237 KB. +- **Small on disk**: Carom.dll is 27.5 KB and Carom.Extensions.dll 57.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). diff --git a/src/Carom.Extensions/CaromAttemptTimeoutExtensions.cs b/src/Carom.Extensions/CaromAttemptTimeoutExtensions.cs new file mode 100644 index 0000000..ada811d --- /dev/null +++ b/src/Carom.Extensions/CaromAttemptTimeoutExtensions.cs @@ -0,0 +1,123 @@ +// 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 +{ + /// + /// A timeout for each single try. Bounce.WithTimeout 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 + /// , which Carom retries like any other failure that + /// passes the Bounce predicate. The overall timeout and caller cancellation still end the call. + /// + public static class CaromAttemptTimeoutExtensions + { + /// + /// Executes a cancellable async action with retry logic and a timeout for each try. + /// + /// The return type of the action. + /// The action. Receives a token cancelled on a try timeout, the overall timeout or caller cancellation. + /// The retry configuration. + /// The timeout for each try. Must be positive. + /// Cancellation token. + public static Task ShotAsync( + Func> action, + Bounce bounce, + TimeSpan attemptTimeout, + CancellationToken ct = default) + { + Validate(action, attemptTimeout); + return Carom.ShotAsync(Limit(action, attemptTimeout), bounce, ct); + } + + /// + /// Executes a cancellable async action with result-based retry and a timeout for each try. + /// + /// The return type of the action. + /// The action. Receives a token cancelled on a try timeout, the overall timeout or caller cancellation. + /// The retry configuration with result predicate. + /// The timeout for each try. Must be positive. + /// Cancellation token. + public static Task ShotAsync( + Func> action, + Bounce bounce, + TimeSpan attemptTimeout, + CancellationToken ct = default) + { + Validate(action, attemptTimeout); + return Carom.ShotAsync(Limit(action, attemptTimeout), bounce, ct); + } + + /// + /// Executes a cancellable async void action with retry logic and a timeout for each try. + /// + /// The action. Receives a token cancelled on a try timeout, the overall timeout or caller cancellation. + /// The retry configuration. + /// The timeout for each try. Must be positive. + /// Cancellation token. + public static Task ShotAsync( + Func 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"); + } + + private static Func> Limit(Func> 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 Limit(Func action, TimeSpan attemptTimeout) + { + var limited = Limit(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); + } + } +} diff --git a/src/Carom/Bounce.cs b/src/Carom/Bounce.cs index 9c64a2e..5bd6d64 100644 --- a/src/Carom/Bounce.cs +++ b/src/Carom/Bounce.cs @@ -55,22 +55,10 @@ public readonly struct Bounce // Nullable backing so default(Bounce) still reports the 30 second default. private readonly TimeSpan? _maxDelay; - /// - /// Optional timeout for each single try, set by WithAttemptTimeout. - /// - public TimeSpan? AttemptTimeout => _extras?.AttemptTimeout; - - /// - /// Optional hint for the delay before the next retry, set by WithDelayHint. - /// - public Func? DelayHint => _extras?.DelayHint; - // Rarely used options live in one reference so a Bounce without them stays small. - private readonly BounceExtras? _extras; - - internal BounceExtras? Extras => _extras; + internal readonly Opts? _o; - private Bounce(int retries, TimeSpan baseDelay, TimeSpan? timeout, bool disableJitter, Func? shouldBounce, TimeSpan? maxDelay = null, BounceExtras? extras = null) + private Bounce(int retries, TimeSpan baseDelay, TimeSpan? timeout, bool disableJitter, Func? shouldBounce, TimeSpan? maxDelay = null, Opts? extras = null) { Retries = retries; BaseDelay = baseDelay; @@ -78,7 +66,7 @@ private Bounce(int retries, TimeSpan baseDelay, TimeSpan? timeout, bool disableJ DisableJitter = disableJitter; ShouldBounce = shouldBounce; _maxDelay = maxDelay; - _extras = extras; + _o = extras; } /// @@ -108,7 +96,7 @@ public Bounce WithDelay(TimeSpan delay) { if (delay < TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(delay), "Delay cannot be negative"); - return new Bounce(Retries, delay, Timeout, DisableJitter, ShouldBounce, _maxDelay, _extras); + return new Bounce(Retries, delay, Timeout, DisableJitter, ShouldBounce, _maxDelay, _o); } /// @@ -117,7 +105,7 @@ public Bounce WithDelay(TimeSpan delay) /// /// A new Bounce configuration with jitter disabled. public Bounce WithoutJitter() => - new Bounce(Retries, BaseDelay, Timeout, disableJitter: true, ShouldBounce, _maxDelay, _extras); + new Bounce(Retries, BaseDelay, Timeout, disableJitter: true, ShouldBounce, _maxDelay, _o); /// /// Sets a predicate to determine which exceptions should trigger a retry. @@ -125,7 +113,7 @@ public Bounce WithoutJitter() => /// The exception predicate. /// A new Bounce configuration with the specified predicate. public Bounce When(Func predicate) => - new Bounce(Retries, BaseDelay, Timeout, DisableJitter, predicate, _maxDelay, _extras); + new Bounce(Retries, BaseDelay, Timeout, DisableJitter, predicate, _maxDelay, _o); /// /// Sets the maximum delay between retries. @@ -139,7 +127,7 @@ public Bounce WithMaxDelay(TimeSpan maxDelay) { if (maxDelay <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(maxDelay), "Max delay must be positive"); - return new Bounce(Retries, BaseDelay, Timeout, DisableJitter, ShouldBounce, maxDelay, _extras); + return new Bounce(Retries, BaseDelay, Timeout, DisableJitter, ShouldBounce, maxDelay, _o); } /// @@ -154,24 +142,7 @@ public Bounce WithTimeout(TimeSpan timeout) { if (timeout <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(timeout), "Timeout must be positive"); - return new Bounce(Retries, BaseDelay, timeout, DisableJitter, ShouldBounce, _maxDelay, _extras); - } - - /// - /// Sets a timeout for each single try. When one try runs longer, it is cancelled - /// (the token passed to a cancellable action is cancelled) and fails with a - /// , which is retried like any other failure - /// that passes the exception predicate. The overall still - /// bounds the whole operation including retries. Enforced only by the asynchronous - /// ShotAsync overloads; the synchronous Shot overloads throw InvalidOperationException. - /// - /// The per-try timeout. Must be positive. - /// A new Bounce configuration with the specified per-try timeout. - public Bounce WithAttemptTimeout(TimeSpan timeout) - { - if (timeout <= TimeSpan.Zero) - throw new ArgumentOutOfRangeException(nameof(timeout), "Attempt timeout must be positive"); - return new Bounce(Retries, BaseDelay, Timeout, DisableJitter, ShouldBounce, _maxDelay, BounceExtras.With(_extras, attemptTimeout: timeout)); + return new Bounce(Retries, BaseDelay, timeout, DisableJitter, ShouldBounce, _maxDelay, _o); } /// @@ -187,12 +158,12 @@ public Bounce WithAttemptTimeout(TimeSpan timeout) public Bounce WithDelayHint(Func hint) { if (hint == null) throw new ArgumentNullException(nameof(hint)); - return new Bounce(Retries, BaseDelay, Timeout, DisableJitter, ShouldBounce, _maxDelay, BounceExtras.With(_extras, delayHint: hint)); + return new Bounce(Retries, BaseDelay, Timeout, DisableJitter, ShouldBounce, _maxDelay, new Opts(hint, _o?.Sleep)); } // Test seam: replaces Task.Delay so a fake clock can observe and release the waits. internal Bounce WithSleep(Func sleep) => - new Bounce(Retries, BaseDelay, Timeout, DisableJitter, ShouldBounce, _maxDelay, BounceExtras.With(_extras, sleep: sleep)); + new Bounce(Retries, BaseDelay, Timeout, DisableJitter, ShouldBounce, _maxDelay, new Opts(_o?.Hint, sleep)); } /// @@ -242,23 +213,11 @@ public readonly struct Bounce // Nullable backing so default(Bounce) still reports the 30 second default. private readonly TimeSpan? _maxDelay; - /// - /// Optional timeout for each single try, set by WithAttemptTimeout. - /// - public TimeSpan? AttemptTimeout => _extras?.AttemptTimeout; - - /// - /// Optional hint for the delay before the next retry, set by WithDelayHint. - /// - public Func? DelayHint => _extras?.DelayHint; - // Rarely used options live in one reference so a Bounce without them stays small. - private readonly BounceExtras? _extras; - - internal BounceExtras? Extras => _extras; + internal readonly Opts? _o; private Bounce(int retries, TimeSpan baseDelay, TimeSpan? timeout, bool disableJitter, - Func? shouldBounce, Func? shouldRetryResult, TimeSpan? maxDelay = null, BounceExtras? extras = null) + Func? shouldBounce, Func? shouldRetryResult, TimeSpan? maxDelay = null, Opts? extras = null) { Retries = retries; BaseDelay = baseDelay; @@ -267,7 +226,7 @@ private Bounce(int retries, TimeSpan baseDelay, TimeSpan? timeout, bool disableJ ShouldBounce = shouldBounce; ShouldRetryResult = shouldRetryResult; _maxDelay = maxDelay; - _extras = extras; + _o = extras; } /// @@ -298,7 +257,7 @@ public Bounce WithDelay(TimeSpan delay) { if (delay < TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(delay), "Delay cannot be negative"); - return new Bounce(Retries, delay, Timeout, DisableJitter, ShouldBounce, ShouldRetryResult, _maxDelay, _extras); + return new Bounce(Retries, delay, Timeout, DisableJitter, ShouldBounce, ShouldRetryResult, _maxDelay, _o); } /// @@ -307,7 +266,7 @@ public Bounce WithDelay(TimeSpan delay) /// /// A new Bounce configuration with jitter disabled. public Bounce WithoutJitter() => - new Bounce(Retries, BaseDelay, Timeout, disableJitter: true, ShouldBounce, ShouldRetryResult, _maxDelay, _extras); + new Bounce(Retries, BaseDelay, Timeout, disableJitter: true, ShouldBounce, ShouldRetryResult, _maxDelay, _o); /// /// Sets a predicate to determine which exceptions should trigger a retry. @@ -315,7 +274,7 @@ public Bounce WithoutJitter() => /// The exception predicate. /// A new Bounce configuration with the specified predicate. public Bounce When(Func predicate) => - new Bounce(Retries, BaseDelay, Timeout, DisableJitter, predicate, ShouldRetryResult, _maxDelay, _extras); + new Bounce(Retries, BaseDelay, Timeout, DisableJitter, predicate, ShouldRetryResult, _maxDelay, _o); /// /// Sets a predicate to determine which results should trigger a retry. @@ -323,7 +282,7 @@ public Bounce When(Func predicate) => /// The result predicate (returns true to retry). /// A new Bounce configuration with the specified result predicate. public Bounce WhenResult(Func predicate) => - new Bounce(Retries, BaseDelay, Timeout, DisableJitter, ShouldBounce, predicate, _maxDelay, _extras); + new Bounce(Retries, BaseDelay, Timeout, DisableJitter, ShouldBounce, predicate, _maxDelay, _o); /// /// Sets the maximum delay between retries. @@ -337,7 +296,7 @@ public Bounce WithMaxDelay(TimeSpan maxDelay) { if (maxDelay <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(maxDelay), "Max delay must be positive"); - return new Bounce(Retries, BaseDelay, Timeout, DisableJitter, ShouldBounce, ShouldRetryResult, maxDelay, _extras); + return new Bounce(Retries, BaseDelay, Timeout, DisableJitter, ShouldBounce, ShouldRetryResult, maxDelay, _o); } /// @@ -352,24 +311,7 @@ public Bounce WithTimeout(TimeSpan timeout) { if (timeout <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(timeout), "Timeout must be positive"); - return new Bounce(Retries, BaseDelay, timeout, DisableJitter, ShouldBounce, ShouldRetryResult, _maxDelay, _extras); - } - - /// - /// Sets a timeout for each single try. When one try runs longer, it is cancelled - /// (the token passed to a cancellable action is cancelled) and fails with a - /// , which is retried like any other failure - /// that passes the exception predicate. The overall still - /// bounds the whole operation including retries. Enforced only by the asynchronous - /// ShotAsync overloads; the synchronous Shot overloads throw InvalidOperationException. - /// - /// The per-try timeout. Must be positive. - /// A new Bounce configuration with the specified per-try timeout. - public Bounce WithAttemptTimeout(TimeSpan timeout) - { - if (timeout <= TimeSpan.Zero) - throw new ArgumentOutOfRangeException(nameof(timeout), "Attempt timeout must be positive"); - return new Bounce(Retries, BaseDelay, Timeout, DisableJitter, ShouldBounce, ShouldRetryResult, _maxDelay, BounceExtras.With(_extras, attemptTimeout: timeout)); + return new Bounce(Retries, BaseDelay, timeout, DisableJitter, ShouldBounce, ShouldRetryResult, _maxDelay, _o); } /// @@ -385,12 +327,12 @@ public Bounce WithAttemptTimeout(TimeSpan timeout) public Bounce WithDelayHint(Func hint) { if (hint == null) throw new ArgumentNullException(nameof(hint)); - return new Bounce(Retries, BaseDelay, Timeout, DisableJitter, ShouldBounce, ShouldRetryResult, _maxDelay, BounceExtras.With(_extras, delayHint: hint)); + return new Bounce(Retries, BaseDelay, Timeout, DisableJitter, ShouldBounce, ShouldRetryResult, _maxDelay, new Opts(hint, _o?.Sleep)); } // Test seam: replaces Task.Delay so a fake clock can observe and release the waits. internal Bounce WithSleep(Func sleep) => - new Bounce(Retries, BaseDelay, Timeout, DisableJitter, ShouldBounce, ShouldRetryResult, _maxDelay, BounceExtras.With(_extras, sleep: sleep)); + new Bounce(Retries, BaseDelay, Timeout, DisableJitter, ShouldBounce, ShouldRetryResult, _maxDelay, new Opts(_o?.Hint, sleep)); } } @@ -399,24 +341,15 @@ namespace Carom /// /// Optional Bounce settings, kept behind one reference so the common Bounce is unchanged. /// - internal sealed class BounceExtras + internal sealed class Opts { - public TimeSpan? AttemptTimeout { get; private set; } - public Func? DelayHint { get; private set; } - public Func? Sleep { get; private set; } - - public static BounceExtras With( - BounceExtras? current, - TimeSpan? attemptTimeout = null, - Func? delayHint = null, - Func? sleep = null) + internal readonly Func? Hint; + internal readonly Func? Sleep; + + internal Opts(Func? delayHint, Func? sleep) { - return new BounceExtras - { - AttemptTimeout = attemptTimeout ?? current?.AttemptTimeout, - DelayHint = delayHint ?? current?.DelayHint, - Sleep = sleep ?? current?.Sleep, - }; + Hint = delayHint; + Sleep = sleep; } } } diff --git a/src/Carom/Carom.cs b/src/Carom/Carom.cs index bd6ff5a..938b0e9 100644 --- a/src/Carom/Carom.cs +++ b/src/Carom/Carom.cs @@ -65,14 +65,13 @@ private static T ShotCore( Func? shouldRetryResult, bool disableJitter, TimeSpan? maxDelay, - BounceExtras? extras = null) + Opts? extras = null) { if (action == null) throw new ArgumentNullException(nameof(action)); retries = Math.Max(0, retries); var delay = baseDelay ?? JitterStrategy.DefaultBaseDelay; var previousDelay = delay; Exception? lastException = null; - T lastResult = default!; for (int attempt = 0; attempt <= retries; attempt++) { @@ -83,7 +82,6 @@ private static T ShotCore( // Check if we should retry based on result if (shouldRetryResult != null && shouldRetryResult(result)) { - lastResult = result; // Check if we have retries left if (attempt >= retries) @@ -93,7 +91,7 @@ private static T ShotCore( // Calculate and wait for the next delay var nextDelay = JitterStrategy.CalculateDelay(delay, previousDelay, disableJitter, attempt + 1, maxDelay); - if (CaromHooks.HasRetryHandlers) CaromHooks.RaiseRetry(new RetrySignal(attempt + 1, nextDelay, null)); + CaromHooks.Raise(attempt + 1, nextDelay, null); Thread.Sleep(nextDelay); previousDelay = nextDelay; continue; @@ -119,9 +117,9 @@ private static T ShotCore( } // Calculate and wait for the next delay - var hinted = TryGetDelayHint(extras, ex, maxDelay, out var nextDelay); + var hinted = Hinted(extras, ex, maxDelay, out var nextDelay); if (!hinted) nextDelay = JitterStrategy.CalculateDelay(delay, previousDelay, disableJitter, attempt + 1, maxDelay); - if (CaromHooks.HasRetryHandlers) CaromHooks.RaiseRetry(new RetrySignal(attempt + 1, nextDelay, ex.GetType().Name)); + CaromHooks.Raise(attempt + 1, nextDelay, ex); Thread.Sleep(nextDelay); if (!hinted) previousDelay = nextDelay; } @@ -148,7 +146,7 @@ private static void ShotCore( Func? shouldBounce, bool disableJitter, TimeSpan? maxDelay, - BounceExtras? extras = null) + Opts? extras = null) { if (action == null) throw new ArgumentNullException(nameof(action)); retries = Math.Max(0, retries); @@ -170,9 +168,9 @@ private static void ShotCore( if (!ShouldRetryException(ex, shouldBounce)) throw; if (attempt >= retries) throw; - var hinted = TryGetDelayHint(extras, ex, maxDelay, out var nextDelay); + var hinted = Hinted(extras, ex, maxDelay, out var nextDelay); if (!hinted) nextDelay = JitterStrategy.CalculateDelay(delay, previousDelay, disableJitter, attempt + 1, maxDelay); - if (CaromHooks.HasRetryHandlers) CaromHooks.RaiseRetry(new RetrySignal(attempt + 1, nextDelay, ex.GetType().Name)); + CaromHooks.Raise(attempt + 1, nextDelay, ex); Thread.Sleep(nextDelay); if (!hinted) previousDelay = nextDelay; } @@ -193,8 +191,8 @@ private static void ShotCore( /// The bounce carries a timeout. public static T Shot(Func action, Bounce bounce) { - ThrowIfTimeoutOnSyncPath(bounce.Timeout, bounce.Extras); - return ShotCore(action, bounce.Retries, bounce.BaseDelay, bounce.ShouldBounce, shouldRetryResult: null, bounce.DisableJitter, bounce.MaxDelay, bounce.Extras); + ThrowIfTimeoutOnSyncPath(bounce.Timeout); + return ShotCore(action, bounce.Retries, bounce.BaseDelay, bounce.ShouldBounce, shouldRetryResult: null, bounce.DisableJitter, bounce.MaxDelay, bounce._o); } /// @@ -209,8 +207,8 @@ public static T Shot(Func action, Bounce bounce) /// The bounce carries a timeout. public static T Shot(Func action, Bounce bounce) { - ThrowIfTimeoutOnSyncPath(bounce.Timeout, bounce.Extras); - return ShotCore(action, bounce.Retries, bounce.BaseDelay, bounce.ShouldBounce, bounce.ShouldRetryResult, bounce.DisableJitter, bounce.MaxDelay, bounce.Extras); + ThrowIfTimeoutOnSyncPath(bounce.Timeout); + return ShotCore(action, bounce.Retries, bounce.BaseDelay, bounce.ShouldBounce, bounce.ShouldRetryResult, bounce.DisableJitter, bounce.MaxDelay, bounce._o); } /// @@ -223,19 +221,15 @@ public static T Shot(Func action, Bounce bounce) /// The bounce carries a timeout. public static void Shot(Action action, Bounce bounce) { - ThrowIfTimeoutOnSyncPath(bounce.Timeout, bounce.Extras); - ShotCore(action, bounce.Retries, bounce.BaseDelay, bounce.ShouldBounce, bounce.DisableJitter, bounce.MaxDelay, bounce.Extras); + ThrowIfTimeoutOnSyncPath(bounce.Timeout); + ShotCore(action, bounce.Retries, bounce.BaseDelay, bounce.ShouldBounce, bounce.DisableJitter, bounce.MaxDelay, bounce._o); } /// /// Rejects a Bounce timeout on the synchronous path, which cannot enforce one. /// - private static void ThrowIfTimeoutOnSyncPath(TimeSpan? timeout, BounceExtras? extras) + private static void ThrowIfTimeoutOnSyncPath(TimeSpan? timeout) { - if (extras?.AttemptTimeout != null) - throw new InvalidOperationException( - "This Bounce carries an attempt timeout, but the synchronous Shot overloads cannot enforce one. " + - "Use ShotAsync if the attempt timeout must be enforced, or remove WithAttemptTimeout from the Bounce."); if (timeout.HasValue) throw new InvalidOperationException( "This Bounce carries a timeout, but the synchronous Shot overloads cannot enforce one. " + @@ -368,7 +362,7 @@ private static async Task ShotAsyncCore( bool disableJitter, CancellationToken ct, TimeSpan? maxDelay = null, - BounceExtras? extras = null) + Opts? extras = null) { if (timeout.HasValue && timeout.Value <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(timeout), "Timeout must be positive"); @@ -390,60 +384,42 @@ private static async Task ShotAsyncCore( var delay = baseDelay ?? JitterStrategy.DefaultBaseDelay; var previousDelay = delay; Exception? lastException = null; - T lastResult = default!; for (int attempt = 0; attempt <= retries; attempt++) { effectiveCt.ThrowIfCancellationRequested(); - // Each try runs on its own token only when an attempt timeout is set. - var attemptTimeout = extras?.AttemptTimeout; - using var attemptCts = attemptTimeout.HasValue - ? CancellationTokenSource.CreateLinkedTokenSource(effectiveCt) - : null; - if (attemptCts != null) attemptCts.CancelAfter(attemptTimeout!.Value); - var tryCt = attemptCts?.Token ?? effectiveCt; - try { T result; - try + Task task = ctAction != null ? ctAction(effectiveCt) : action!(); + + // Only use WhenAny pattern if we have a cancellation mechanism + // This prevents Task.Delay(-1, ct) from leaking when ct is never cancelled + if (effectiveCt.CanBeCanceled) { - Task task = ctAction != null ? ctAction(tryCt) : action!(); + var completedTask = await Task.WhenAny(task, Task.Delay(-1, effectiveCt)).ConfigureAwait(false); - // Only use WhenAny pattern if we have a cancellation mechanism - // This prevents Task.Delay(-1, ct) from leaking when ct is never cancelled - if (tryCt.CanBeCanceled) + if (completedTask == task) { - var completedTask = await Task.WhenAny(task, Task.Delay(-1, tryCt)).ConfigureAwait(false); - - if (completedTask == task) - { - result = await task.ConfigureAwait(false); - } - else - { - // Task.Delay completed, which means the try token was cancelled (timeout or manual) - ObserveAbandonedTask(task); - throw new OperationCanceledException(tryCt); - } + result = await task.ConfigureAwait(false); } else { - // No cancellation possible - just await directly (prevents leak) - result = await task.ConfigureAwait(false); + // Task.Delay completed, which means effectiveCt was cancelled (timeout or manual) + ObserveAbandonedTask(task); + throw new OperationCanceledException(effectiveCt); } } - catch (OperationCanceledException) when (attemptCts != null && attemptCts.IsCancellationRequested && !effectiveCt.IsCancellationRequested) + else { - // The per-try timer fired, not the overall timeout or the caller. - throw new TimeoutRejectedException(attemptTimeout!.Value); + // No cancellation possible - just await directly (prevents leak) + result = await task.ConfigureAwait(false); } // Check if we should retry based on result if (shouldRetryResult != null && shouldRetryResult(result)) { - lastResult = result; // Check if we have retries left if (attempt >= retries) @@ -453,8 +429,8 @@ private static async Task ShotAsyncCore( // Calculate and wait for the next delay var nextDelay = JitterStrategy.CalculateDelay(delay, previousDelay, disableJitter, attempt + 1, maxDelay); - if (CaromHooks.HasRetryHandlers) CaromHooks.RaiseRetry(new RetrySignal(attempt + 1, nextDelay, null)); - await SleepAsync(extras, nextDelay, effectiveCt).ConfigureAwait(false); + CaromHooks.Raise(attempt + 1, nextDelay, null); + await Task.Delay(nextDelay, effectiveCt).ConfigureAwait(false); previousDelay = nextDelay; continue; } @@ -486,9 +462,9 @@ private static async Task ShotAsyncCore( } // Calculate and wait for the next delay - var hinted = TryGetDelayHint(extras, ex, maxDelay, out var nextDelay); + var hinted = Hinted(extras, ex, maxDelay, out var nextDelay); if (!hinted) nextDelay = JitterStrategy.CalculateDelay(delay, previousDelay, disableJitter, attempt + 1, maxDelay); - if (CaromHooks.HasRetryHandlers) CaromHooks.RaiseRetry(new RetrySignal(attempt + 1, nextDelay, ex.GetType().Name)); + CaromHooks.Raise(attempt + 1, nextDelay, ex); await BackoffDelayAsync(nextDelay, effectiveCt, timeout, ct, extras).ConfigureAwait(false); if (!hinted) previousDelay = nextDelay; } @@ -559,7 +535,7 @@ private static async Task ShotAsyncCore( bool disableJitter, CancellationToken ct, TimeSpan? maxDelay = null, - BounceExtras? extras = null) + Opts? extras = null) { if (timeout.HasValue && timeout.Value <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(timeout), "Timeout must be positive"); @@ -586,46 +562,30 @@ private static async Task ShotAsyncCore( { effectiveCt.ThrowIfCancellationRequested(); - // Each try runs on its own token only when an attempt timeout is set. - var attemptTimeout = extras?.AttemptTimeout; - using var attemptCts = attemptTimeout.HasValue - ? CancellationTokenSource.CreateLinkedTokenSource(effectiveCt) - : null; - if (attemptCts != null) attemptCts.CancelAfter(attemptTimeout!.Value); - var tryCt = attemptCts?.Token ?? effectiveCt; - try { - try + var task = ctAction != null ? ctAction(effectiveCt) : action!(); + + // Only use WhenAny pattern if we have a cancellation mechanism + // This prevents Task.Delay(-1, ct) from leaking when ct is never cancelled + if (effectiveCt.CanBeCanceled) { - var task = ctAction != null ? ctAction(tryCt) : action!(); + var completedTask = await Task.WhenAny(task, Task.Delay(-1, effectiveCt)).ConfigureAwait(false); - // Only use WhenAny pattern if we have a cancellation mechanism - // This prevents Task.Delay(-1, ct) from leaking when ct is never cancelled - if (tryCt.CanBeCanceled) + if (completedTask == task) { - var completedTask = await Task.WhenAny(task, Task.Delay(-1, tryCt)).ConfigureAwait(false); - - if (completedTask == task) - { - await task.ConfigureAwait(false); - return; - } - - ObserveAbandonedTask(task); - throw new OperationCanceledException(tryCt); - } - else - { - // No cancellation possible - just await directly (prevents leak) await task.ConfigureAwait(false); return; } + + ObserveAbandonedTask(task); + throw new OperationCanceledException(effectiveCt); } - catch (OperationCanceledException) when (attemptCts != null && attemptCts.IsCancellationRequested && !effectiveCt.IsCancellationRequested) + else { - // The per-try timer fired, not the overall timeout or the caller. - throw new TimeoutRejectedException(attemptTimeout!.Value); + // No cancellation possible - just await directly (prevents leak) + await task.ConfigureAwait(false); + return; } } catch (OperationCanceledException) when (effectiveCt.IsCancellationRequested) @@ -642,9 +602,9 @@ private static async Task ShotAsyncCore( if (!ShouldRetryException(ex, shouldBounce)) throw; if (attempt >= retries) throw; - var hinted = TryGetDelayHint(extras, ex, maxDelay, out var nextDelay); + var hinted = Hinted(extras, ex, maxDelay, out var nextDelay); if (!hinted) nextDelay = JitterStrategy.CalculateDelay(delay, previousDelay, disableJitter, attempt + 1, maxDelay); - if (CaromHooks.HasRetryHandlers) CaromHooks.RaiseRetry(new RetrySignal(attempt + 1, nextDelay, ex.GetType().Name)); + CaromHooks.Raise(attempt + 1, nextDelay, ex); await BackoffDelayAsync(nextDelay, effectiveCt, timeout, ct, extras).ConfigureAwait(false); if (!hinted) previousDelay = nextDelay; } @@ -675,11 +635,12 @@ private static async Task BackoffDelayAsync( CancellationToken effectiveCt, TimeSpan? timeout, CancellationToken ct, - BounceExtras? extras = null) + Opts? extras = null) { try { - await SleepAsync(extras, nextDelay, effectiveCt).ConfigureAwait(false); + var sleep = extras?.Sleep; + await (sleep != null ? sleep(nextDelay, effectiveCt) : Task.Delay(nextDelay, effectiveCt)).ConfigureAwait(false); } catch (OperationCanceledException) when (effectiveCt.IsCancellationRequested) { @@ -689,43 +650,31 @@ private static async Task BackoffDelayAsync( } } - /// - /// Waits out a delay. Task.Delay unless a test replaced the clock. - /// - private static Task SleepAsync(BounceExtras? extras, TimeSpan delay, CancellationToken ct) - { - var sleep = extras?.Sleep; - return sleep != null ? sleep(delay, ct) : Task.Delay(delay, ct); - } - /// /// Asks the delay hint for the wait before the next retry. A hint is clamped to /// [0, MaxDelay]. Returns false (use the computed backoff) when there is no hint, /// it returns null, or it throws. /// - private static bool TryGetDelayHint(BounceExtras? extras, Exception ex, TimeSpan? maxDelay, out TimeSpan delay) + private static bool Hinted(Opts? extras, Exception ex, TimeSpan? maxDelay, out TimeSpan delay) { delay = TimeSpan.Zero; - var hint = extras?.DelayHint; + var hint = extras?.Hint; if (hint == null) return false; - TimeSpan? hinted; try { - hinted = hint(ex); + var hinted = hint(ex); + if (hinted == null) return false; + delay = hinted.Value; } catch { return false; } - if (!hinted.HasValue) return false; - var cap = maxDelay ?? JitterStrategy.DefaultMaxDelay; - var value = hinted.Value; - if (value < TimeSpan.Zero) value = TimeSpan.Zero; - if (value > cap) value = cap; - delay = value; + if (delay > cap) delay = cap; + if (delay < TimeSpan.Zero) delay = TimeSpan.Zero; return true; } @@ -754,7 +703,7 @@ private static void ObserveAbandonedTask(Task task) public static Task ShotAsync(Func> action, Bounce bounce, CancellationToken ct = default) { if (action == null) throw new ArgumentNullException(nameof(action)); - return ShotAsyncCore(action, ctAction: null, bounce.Retries, bounce.BaseDelay, bounce.Timeout, bounce.ShouldBounce, shouldRetryResult: null, bounce.DisableJitter, ct, bounce.MaxDelay, bounce.Extras); + return ShotAsyncCore(action, ctAction: null, bounce.Retries, bounce.BaseDelay, bounce.Timeout, bounce.ShouldBounce, shouldRetryResult: null, bounce.DisableJitter, ct, bounce.MaxDelay, bounce._o); } /// @@ -768,7 +717,7 @@ public static Task ShotAsync(Func> action, Bounce bounce, Cancella public static Task ShotAsync(Func> action, Bounce bounce, CancellationToken ct = default) { if (action == null) throw new ArgumentNullException(nameof(action)); - return ShotAsyncCore(action, ctAction: null, bounce.Retries, bounce.BaseDelay, bounce.Timeout, bounce.ShouldBounce, bounce.ShouldRetryResult, bounce.DisableJitter, ct, bounce.MaxDelay, bounce.Extras); + return ShotAsyncCore(action, ctAction: null, bounce.Retries, bounce.BaseDelay, bounce.Timeout, bounce.ShouldBounce, bounce.ShouldRetryResult, bounce.DisableJitter, ct, bounce.MaxDelay, bounce._o); } /// @@ -780,7 +729,7 @@ public static Task ShotAsync(Func> action, Bounce bounce, Cance public static Task ShotAsync(Func action, Bounce bounce, CancellationToken ct = default) { if (action == null) throw new ArgumentNullException(nameof(action)); - return ShotAsyncCore(action, ctAction: null, bounce.Retries, bounce.BaseDelay, bounce.Timeout, bounce.ShouldBounce, bounce.DisableJitter, ct, bounce.MaxDelay, bounce.Extras); + return ShotAsyncCore(action, ctAction: null, bounce.Retries, bounce.BaseDelay, bounce.Timeout, bounce.ShouldBounce, bounce.DisableJitter, ct, bounce.MaxDelay, bounce._o); } /// @@ -795,7 +744,7 @@ public static Task ShotAsync(Func action, Bounce bounce, CancellationToken public static Task ShotAsync(Func> action, Bounce bounce, CancellationToken ct = default) { if (action == null) throw new ArgumentNullException(nameof(action)); - return ShotAsyncCore(action: null, ctAction: action, bounce.Retries, bounce.BaseDelay, bounce.Timeout, bounce.ShouldBounce, shouldRetryResult: null, bounce.DisableJitter, ct, bounce.MaxDelay, bounce.Extras); + return ShotAsyncCore(action: null, ctAction: action, bounce.Retries, bounce.BaseDelay, bounce.Timeout, bounce.ShouldBounce, shouldRetryResult: null, bounce.DisableJitter, ct, bounce.MaxDelay, bounce._o); } /// @@ -810,7 +759,7 @@ public static Task ShotAsync(Func> action, Boun public static Task ShotAsync(Func> action, Bounce bounce, CancellationToken ct = default) { if (action == null) throw new ArgumentNullException(nameof(action)); - return ShotAsyncCore(action: null, ctAction: action, bounce.Retries, bounce.BaseDelay, bounce.Timeout, bounce.ShouldBounce, bounce.ShouldRetryResult, bounce.DisableJitter, ct, bounce.MaxDelay, bounce.Extras); + return ShotAsyncCore(action: null, ctAction: action, bounce.Retries, bounce.BaseDelay, bounce.Timeout, bounce.ShouldBounce, bounce.ShouldRetryResult, bounce.DisableJitter, ct, bounce.MaxDelay, bounce._o); } /// @@ -823,7 +772,7 @@ public static Task ShotAsync(Func> action, Boun public static Task ShotAsync(Func action, Bounce bounce, CancellationToken ct = default) { if (action == null) throw new ArgumentNullException(nameof(action)); - return ShotAsyncCore(action: null, ctAction: action, bounce.Retries, bounce.BaseDelay, bounce.Timeout, bounce.ShouldBounce, bounce.DisableJitter, ct, bounce.MaxDelay, bounce.Extras); + return ShotAsyncCore(action: null, ctAction: action, bounce.Retries, bounce.BaseDelay, bounce.Timeout, bounce.ShouldBounce, bounce.DisableJitter, ct, bounce.MaxDelay, bounce._o); } #endregion diff --git a/src/Carom/CaromHooks.cs b/src/Carom/CaromHooks.cs index 514d524..4c40a08 100644 --- a/src/Carom/CaromHooks.cs +++ b/src/Carom/CaromHooks.cs @@ -82,7 +82,7 @@ public RateLimitRejectedSignal(string serviceKey) /// public static class CaromHooks { - private static Action? _legacyOnRetry; + private static Action? _onRetry; /// /// Raised after the backoff delay is computed, just before a retry runs. Add and remove @@ -97,25 +97,25 @@ public static class CaromHooks /// assigned to this property, never a subscriber, but += on it is /// still a non-atomic read, combine and write, so two threads can lose a subscriber. /// - [Obsolete("Subscribe to CaromHooks.Retrying instead. This property is not atomic and will be removed in the next major version.")] + [Obsolete("Use Retrying.")] public static Action? OnRetry { - get => _legacyOnRetry; - set => _legacyOnRetry = value; + get => _onRetry; + set => _onRetry = value; } - internal static bool HasRetryHandlers => _legacyOnRetry != null || Retrying != null; - /// /// Raises the retry hooks. Each handler runs on its own so a throwing or /// misbehaving one cannot skip the rest. Allocates only while a subscriber exists. /// - internal static void RaiseRetry(RetrySignal signal) + internal static void Raise(int attempt, TimeSpan delay, Exception? cause) { - var legacy = _legacyOnRetry; - if (legacy != null) Invoke(legacy, signal); - + var legacy = _onRetry; var handlers = Retrying; + if (legacy == null && handlers == null) return; + + var signal = new RetrySignal(attempt, delay, cause?.GetType().Name); + if (legacy != null) Invoke(legacy, signal); if (handlers == null) return; var list = handlers.GetInvocationList(); diff --git a/tests/Carom.ApiApproval.Tests/ApprovedApi/Carom.Extensions.approved.txt b/tests/Carom.ApiApproval.Tests/ApprovedApi/Carom.Extensions.approved.txt index 2f1fc06..5c85fe2 100644 --- a/tests/Carom.ApiApproval.Tests/ApprovedApi/Carom.Extensions.approved.txt +++ b/tests/Carom.ApiApproval.Tests/ApprovedApi/Carom.Extensions.approved.txt @@ -2,6 +2,12 @@ [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("Carom.Extensions.Tests")] namespace Carom.Extensions { + public static class CaromAttemptTimeoutExtensions + { + public static System.Threading.Tasks.Task ShotAsync(System.Func action, Carom.Bounce bounce, System.TimeSpan attemptTimeout, System.Threading.CancellationToken ct = default) { } + public static System.Threading.Tasks.Task ShotAsync(System.Func> action, Carom.Bounce bounce, System.TimeSpan attemptTimeout, System.Threading.CancellationToken ct = default) { } + public static System.Threading.Tasks.Task ShotAsync(System.Func> action, Carom.Bounce bounce, System.TimeSpan attemptTimeout, System.Threading.CancellationToken ct = default) { } + } public static class CaromCompartmentExtensions { public static T Shot(System.Func action, Carom.Extensions.Compartment compartment, Carom.Bounce bounce) { } diff --git a/tests/Carom.ApiApproval.Tests/ApprovedApi/Carom.approved.txt b/tests/Carom.ApiApproval.Tests/ApprovedApi/Carom.approved.txt index 31760a7..c24f29d 100644 --- a/tests/Carom.ApiApproval.Tests/ApprovedApi/Carom.approved.txt +++ b/tests/Carom.ApiApproval.Tests/ApprovedApi/Carom.approved.txt @@ -4,16 +4,13 @@ namespace Carom { public readonly struct Bounce { - public System.TimeSpan? AttemptTimeout { get; } public System.TimeSpan BaseDelay { get; } - public System.Func? DelayHint { get; } public bool DisableJitter { get; } public System.TimeSpan MaxDelay { get; } public int Retries { get; } public System.Func? ShouldBounce { get; } public System.TimeSpan? Timeout { get; } public Carom.Bounce When(System.Func predicate) { } - public Carom.Bounce WithAttemptTimeout(System.TimeSpan timeout) { } public Carom.Bounce WithDelay(System.TimeSpan delay) { } public Carom.Bounce WithDelayHint(System.Func hint) { } public Carom.Bounce WithMaxDelay(System.TimeSpan maxDelay) { } @@ -26,9 +23,7 @@ namespace Carom } public readonly struct Bounce { - public System.TimeSpan? AttemptTimeout { get; } public System.TimeSpan BaseDelay { get; } - public System.Func? DelayHint { get; } public bool DisableJitter { get; } public System.TimeSpan MaxDelay { get; } public int Retries { get; } @@ -37,7 +32,6 @@ namespace Carom public System.TimeSpan? Timeout { get; } public Carom.Bounce When(System.Func predicate) { } public Carom.Bounce WhenResult(System.Func predicate) { } - public Carom.Bounce WithAttemptTimeout(System.TimeSpan timeout) { } public Carom.Bounce WithDelay(System.TimeSpan delay) { } public Carom.Bounce WithDelayHint(System.Func hint) { } public Carom.Bounce WithMaxDelay(System.TimeSpan maxDelay) { } @@ -78,8 +72,7 @@ namespace Carom public static System.Action? OnBulkheadRejected { get; set; } public static System.Action? OnCircuitOpened { get; set; } public static System.Action? OnRateLimitRejected { get; set; } - [System.Obsolete("Subscribe to CaromHooks.Retrying instead. This property is not atomic and will be" + - " removed in the next major version.")] + [System.Obsolete("Use Retrying.")] public static System.Action? OnRetry { get; set; } public static event System.Action? Retrying; } diff --git a/tests/Carom.Extensions.Tests/AttemptTimeoutTests.cs b/tests/Carom.Extensions.Tests/AttemptTimeoutTests.cs new file mode 100644 index 0000000..93febd5 --- /dev/null +++ b/tests/Carom.Extensions.Tests/AttemptTimeoutTests.cs @@ -0,0 +1,138 @@ +using Carom.Extensions; + +namespace Carom.Extensions.Tests +{ + /// + /// CaromAttemptTimeoutExtensions: each try gets its own timeout, a try that runs out fails + /// with a retryable TimeoutRejectedException, and the overall timeout still wins. + /// A zero base delay keeps the waits between tries at zero. + /// + public class AttemptTimeoutTests + { + private static Bounce Quick(int retries) => Bounce.Times(retries).WithDelay(TimeSpan.Zero); + + [Fact] + public async Task PerTryTimeout_FirstTryHangs_RetriesAndTheNextTrySucceeds() + { + int calls = 0; + + var result = await CaromAttemptTimeoutExtensions.ShotAsync(async ct => + { + calls++; + if (calls == 1) await Task.Delay(Timeout.Infinite, ct); + return 7; + }, Quick(2), TimeSpan.FromMilliseconds(50)); + + Assert.Equal(7, result); + Assert.Equal(2, calls); + } + + [Fact] + public async Task PerTryTimeout_ActionThatIgnoresItsToken_IsAbandonedAndRetried() + { + int calls = 0; + + var result = await CaromAttemptTimeoutExtensions.ShotAsync(ct => + { + calls++; + return calls == 1 ? new TaskCompletionSource().Task : Task.FromResult(7); + }, Quick(2), TimeSpan.FromMilliseconds(50)); + + Assert.Equal(7, result); + Assert.Equal(2, calls); + } + + [Fact] + public async Task PerTryTimeout_VoidAction_RetriesAndSucceeds() + { + int calls = 0; + + await CaromAttemptTimeoutExtensions.ShotAsync(async ct => + { + calls++; + if (calls == 1) await Task.Delay(Timeout.Infinite, ct); + }, Quick(2), TimeSpan.FromMilliseconds(50)); + + Assert.Equal(2, calls); + } + + [Fact] + public async Task PerTryTimeout_TypedBounce_RetriesAndSucceeds() + { + int calls = 0; + var bounce = Bounce.For(2).WithDelay(TimeSpan.Zero); + + var result = await CaromAttemptTimeoutExtensions.ShotAsync(async ct => + { + calls++; + if (calls == 1) await Task.Delay(Timeout.Infinite, ct); + return "ok"; + }, bounce, TimeSpan.FromMilliseconds(50)); + + Assert.Equal("ok", result); + } + + [Fact] + public async Task PerTryTimeout_EveryTryHangs_ThrowsTimeoutRejectedWithTheAttemptTimeout() + { + var attempt = TimeSpan.FromMilliseconds(40); + int calls = 0; + + var ex = await Assert.ThrowsAsync(() => + CaromAttemptTimeoutExtensions.ShotAsync(async ct => + { + calls++; + await Task.Delay(Timeout.Infinite, ct); + return 0; + }, Quick(1), attempt)); + + Assert.Equal(attempt, ex.Timeout); + Assert.Equal(2, calls); + } + + [Fact] + public async Task OverallTimeout_StillWins_OverALongerAttemptTimeout() + { + var overall = TimeSpan.FromMilliseconds(150); + var bounce = Quick(5).WithTimeout(overall); + + var ex = await Assert.ThrowsAsync(() => + CaromAttemptTimeoutExtensions.ShotAsync(async ct => + { + await Task.Delay(Timeout.Infinite, ct); + return 0; + }, bounce, TimeSpan.FromSeconds(30))); + + Assert.Equal(overall, ex.Timeout); + } + + [Fact] + public async Task CallerCancellation_IsNotTurnedIntoAnAttemptTimeout() + { + using var cts = new CancellationTokenSource(); + int calls = 0; + + var task = CaromAttemptTimeoutExtensions.ShotAsync(async ct => + { + calls++; + await Task.Delay(Timeout.Infinite, ct); + return 0; + }, Quick(3), TimeSpan.FromSeconds(30), cts.Token); + cts.CancelAfter(50); + + var ex = await Assert.ThrowsAnyAsync(() => task); + + Assert.IsNotType(ex); + Assert.Equal(1, calls); + } + + [Fact] + public async Task NonPositiveAttemptTimeout_AndNullAction_Throw() + { + await Assert.ThrowsAsync(() => + CaromAttemptTimeoutExtensions.ShotAsync(ct => Task.FromResult(1), Quick(1), TimeSpan.Zero)); + await Assert.ThrowsAsync(() => + CaromAttemptTimeoutExtensions.ShotAsync(null!, Quick(1), TimeSpan.FromSeconds(1))); + } + } +} diff --git a/tests/Carom.ReadmeSamples.Tests/Carom.ReadmeSamples.Tests.csproj b/tests/Carom.ReadmeSamples.Tests/Carom.ReadmeSamples.Tests.csproj index aab577c..65bc003 100644 --- a/tests/Carom.ReadmeSamples.Tests/Carom.ReadmeSamples.Tests.csproj +++ b/tests/Carom.ReadmeSamples.Tests/Carom.ReadmeSamples.Tests.csproj @@ -19,6 +19,7 @@ + diff --git a/tests/Carom.ReadmeSamples.Tests/ReadmeSamples.cs b/tests/Carom.ReadmeSamples.Tests/ReadmeSamples.cs index 9455065..f482108 100644 --- a/tests/Carom.ReadmeSamples.Tests/ReadmeSamples.cs +++ b/tests/Carom.ReadmeSamples.Tests/ReadmeSamples.cs @@ -7,6 +7,9 @@ using Carom; using Retry = Carom.Carom; // readme:end basic-usage +// readme:begin attempt-timeout +using Carom.Extensions; +// readme:end attempt-timeout using System; using System.Threading; using System.Threading.Tasks; @@ -47,11 +50,10 @@ public static async Task AttemptTimeout() { // readme:begin attempt-timeout // Each try gets 2 seconds, the whole call gets 10 - var bounce = Bounce.Times(3) - .WithAttemptTimeout(TimeSpan.FromSeconds(2)) - .WithTimeout(TimeSpan.FromSeconds(10)); + var bounce = Bounce.Times(3).WithTimeout(TimeSpan.FromSeconds(10)); - var data = await Retry.ShotAsync(ct => apiClient.FetchAsync(ct), bounce); + var data = await CaromAttemptTimeoutExtensions.ShotAsync( + ct => apiClient.FetchAsync(ct), bounce, attemptTimeout: TimeSpan.FromSeconds(2)); // readme:end attempt-timeout GC.KeepAlive(data); diff --git a/tests/Carom.Tests/AttemptTimeoutTests.cs b/tests/Carom.Tests/AttemptTimeoutTests.cs deleted file mode 100644 index d35e990..0000000 --- a/tests/Carom.Tests/AttemptTimeoutTests.cs +++ /dev/null @@ -1,172 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using Xunit; - -namespace Carom.Tests -{ - /// - /// Bounce.WithAttemptTimeout: each try gets its own timeout, a try that runs out fails - /// with a retryable TimeoutRejectedException, and the overall timeout still wins. - /// Waits between tries go through a fake clock so no test sleeps for real. - /// - public class AttemptTimeoutTests - { - private static readonly Func NoWait = (_, _) => Task.CompletedTask; - - [Fact] - public void WithAttemptTimeout_SetsProperty_AndRejectsNonPositive() - { - var bounce = Bounce.Times(1).WithAttemptTimeout(TimeSpan.FromSeconds(2)); - - Assert.Equal(TimeSpan.FromSeconds(2), bounce.AttemptTimeout); - Assert.Null(Bounce.Times(1).AttemptTimeout); - Assert.Throws(() => Bounce.Times(1).WithAttemptTimeout(TimeSpan.Zero)); - } - - [Fact] - public void WithAttemptTimeout_SurvivesTheOtherWithMethods() - { - var bounce = Bounce.Times(1) - .WithAttemptTimeout(TimeSpan.FromSeconds(2)) - .WithDelay(TimeSpan.FromMilliseconds(5)) - .WithTimeout(TimeSpan.FromSeconds(9)) - .WithMaxDelay(TimeSpan.FromSeconds(1)) - .WithoutJitter(); - - Assert.Equal(TimeSpan.FromSeconds(2), bounce.AttemptTimeout); - } - - [Fact] - public async Task PerTryTimeout_FirstTryHangs_RetriesAndTheNextTrySucceeds() - { - var bounce = Bounce.Times(2).WithAttemptTimeout(TimeSpan.FromMilliseconds(50)).WithSleep(NoWait); - int calls = 0; - - var result = await Carom.ShotAsync(async ct => - { - calls++; - if (calls == 1) await Task.Delay(Timeout.Infinite, ct); - return 7; - }, bounce); - - Assert.Equal(7, result); - Assert.Equal(2, calls); - } - - [Fact] - public async Task PerTryTimeout_WithAnActionThatTakesNoToken_AbandonsTheTryAndRetries() - { - var bounce = Bounce.Times(2).WithAttemptTimeout(TimeSpan.FromMilliseconds(50)).WithSleep(NoWait); - int calls = 0; - - var result = await Carom.ShotAsync(() => - { - calls++; - return calls == 1 ? new TaskCompletionSource().Task : Task.FromResult(7); - }, bounce); - - Assert.Equal(7, result); - Assert.Equal(2, calls); - } - - [Fact] - public async Task PerTryTimeout_VoidAction_RetriesAndSucceeds() - { - var bounce = Bounce.Times(2).WithAttemptTimeout(TimeSpan.FromMilliseconds(50)).WithSleep(NoWait); - int calls = 0; - - await Carom.ShotAsync(async ct => - { - calls++; - if (calls == 1) await Task.Delay(Timeout.Infinite, ct); - }, bounce); - - Assert.Equal(2, calls); - } - - [Fact] - public async Task PerTryTimeout_EveryTryHangs_ThrowsTimeoutRejectedWithTheAttemptTimeout() - { - var attempt = TimeSpan.FromMilliseconds(40); - var bounce = Bounce.Times(1).WithAttemptTimeout(attempt).WithSleep(NoWait); - int calls = 0; - - var ex = await Assert.ThrowsAsync(() => - Carom.ShotAsync(async ct => - { - calls++; - await Task.Delay(Timeout.Infinite, ct); - return 0; - }, bounce)); - - Assert.Equal(attempt, ex.Timeout); - Assert.Equal(2, calls); - } - - [Fact] - public async Task PerTryTimeout_TypedBounce_RetriesAndSucceeds() - { - var bounce = Bounce.For(2).WithAttemptTimeout(TimeSpan.FromMilliseconds(50)).WithSleep(NoWait); - int calls = 0; - - var result = await Carom.ShotAsync(async ct => - { - calls++; - if (calls == 1) await Task.Delay(Timeout.Infinite, ct); - return "ok"; - }, bounce); - - Assert.Equal("ok", result); - } - - [Fact] - public async Task OverallTimeout_StillWins_OverALongerAttemptTimeout() - { - var overall = TimeSpan.FromMilliseconds(150); - var bounce = Bounce.Times(5) - .WithAttemptTimeout(TimeSpan.FromSeconds(30)) - .WithTimeout(overall) - .WithSleep(NoWait); - - var ex = await Assert.ThrowsAsync(() => - Carom.ShotAsync(async ct => - { - await Task.Delay(Timeout.Infinite, ct); - return 0; - }, bounce)); - - Assert.Equal(overall, ex.Timeout); - } - - [Fact] - public async Task CallerCancellation_IsNotTurnedIntoAnAttemptTimeout() - { - var bounce = Bounce.Times(3).WithAttemptTimeout(TimeSpan.FromSeconds(30)).WithSleep(NoWait); - using var cts = new CancellationTokenSource(); - int calls = 0; - - var task = Carom.ShotAsync(async ct => - { - calls++; - await Task.Delay(Timeout.Infinite, ct); - return 0; - }, bounce, cts.Token); - cts.CancelAfter(50); - - var ex = await Assert.ThrowsAnyAsync(() => task); - - Assert.IsNotType(ex); - Assert.Equal(1, calls); - } - - [Fact] - public void SyncShot_WithAnAttemptTimeout_Throws() - { - var bounce = Bounce.Times(1).WithAttemptTimeout(TimeSpan.FromSeconds(1)); - - Assert.Throws(() => Carom.Shot(() => 1, bounce)); - } - } -} diff --git a/tests/Carom.Tests/DelayHintTests.cs b/tests/Carom.Tests/DelayHintTests.cs index ec12254..64a1994 100644 --- a/tests/Carom.Tests/DelayHintTests.cs +++ b/tests/Carom.Tests/DelayHintTests.cs @@ -215,7 +215,7 @@ public void WithDelayHint_RejectsNull_AndSurvivesTheOtherWithMethods() Func hint = _ => null; var bounce = Bounce.Times(1).WithDelayHint(hint).WithDelay(TimeSpan.Zero).WithTimeout(TimeSpan.FromSeconds(1)).WithoutJitter(); - Assert.Same(hint, bounce.DelayHint); + Assert.Same(hint, bounce._o!.Hint); } [Fact] diff --git a/tests/Carom.Tests/PublishedClaimsTests.cs b/tests/Carom.Tests/PublishedClaimsTests.cs index 6cb5795..f827cf2 100644 --- a/tests/Carom.Tests/PublishedClaimsTests.cs +++ b/tests/Carom.Tests/PublishedClaimsTests.cs @@ -12,9 +12,9 @@ namespace Carom.Tests /// public class PublishedClaimsTests { - // README states these bounds. They sit about 10% above the measured 31 KB and 54 KB; + // README states these bounds. They sit about 10% above the measured 25.5 KB and 54 KB; // the old 40 KB and 100 KB bounds let the README's 21.5 KB core go stale unnoticed. - private const long CoreSizeBoundBytes = 34 * 1024; + private const long CoreSizeBoundBytes = 28 * 1024; private const long ExtensionsSizeBoundBytes = 60 * 1024; private static readonly Func SucceedingAction = static () => 42; @@ -53,7 +53,7 @@ public void CaromAssembly_StaysWithinPublishedSizeBound() Assert.True(size <= CoreSizeBoundBytes, $"Carom.dll is {size} bytes, over the {CoreSizeBoundBytes} byte bound. " + - "The README states a 34 KB bound for the core (the 'Tiny Footprint' bullet and the package table). " + + "The README states a 28 KB bound for the core (the 'Tiny Footprint' bullet and the package table). " + "Update the README sizes and this bound together, deliberately."); } From e0ffc83f4af4841726fbac4469943d106725ed80 Mon Sep 17 00:00:00 2001 From: Arnel Robles Date: Sat, 14 Nov 2026 09:55:15 +0800 Subject: [PATCH 3/4] Keep OnRetry as it was, drop the Retrying event --- CHANGELOG.md | 8 - README.md | 16 +- .../CaromTelemetry.cs | 4 +- src/Carom/CaromHooks.cs | 55 ++----- .../ApprovedApi/Carom.approved.txt | 2 - .../ReadmeSamples.cs | 8 - .../ReadmeSamplesTests.cs | 1 - tests/Carom.Tests/CaromHooksTests.cs | 138 ------------------ 8 files changed, 15 insertions(+), 217 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fc1b408..95743bf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,17 +17,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 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. -- `CaromHooks.Retrying` event. Add and remove are atomic and it cannot be assigned from - outside, so one subscriber cannot remove another. - `tests/Carom.ReadmeSamples.Tests` compiles the README samples and fails when the README text drifts from the compiled copy. -### Deprecated - -- `CaromHooks.OnRetry` is obsolete. It is still raised, next to `Retrying`. Assigning it no - longer removes `Retrying` subscribers. It will be removed in the next major version. - `CaromTelemetry.Subscribe` now uses `Retrying`. - ### Changed - The default `Cushion` failure predicate now counts `TimeoutRejectedException` as a failure. diff --git a/README.md b/README.md index 75a61c6..1769dc4 100644 --- a/README.md +++ b/README.md @@ -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** (27.5KB core, 57.5KB extensions) +- **Tiny Footprint** (27KB core, 57.5KB extensions) - **Fully Composable** (all patterns work together) ## 📦 Packages @@ -24,7 +24,7 @@ Sizes are the Release-built assemblies. Tests fail if the core grows past 28KB o | Package | Size | Purpose | |---------|------|---------| -| **Carom** | 27.5KB | Core retry + timeout | +| **Carom** | 27KB | Core retry + timeout | | **Carom.Extensions** | 57.5KB | Circuit Breaker, Fallback, Bulkhead, Rate Limiting | | **Carom.Http** | 12.5KB | HTTP integration | | **Carom.DependencyInjection** | 21.5KB | Named resilience pipelines for `IServiceCollection` | @@ -93,16 +93,6 @@ var bounce = Bounce.Times(3) var data = await Retry.ShotAsync(() => apiClient.FetchAsync(), bounce); ``` -To watch retries, subscribe to the `CaromHooks.Retrying` event. Add and remove are atomic and -one subscriber cannot remove another. The old settable `CaromHooks.OnRetry` property is -obsolete and will go in the next major version. - - -```csharp -CaromHooks.Retrying += signal => - Console.WriteLine($"retry {signal.Attempt} in {signal.Delay}"); -``` - These samples are compiled by `tests/Carom.ReadmeSamples.Tests`, which also fails when the README text drifts from the compiled copy. @@ -202,7 +192,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 27.5 KB and Carom.Extensions.dll 57.5 KB. Polly.Core.dll (net8.0) is 237 KB. +- **Small on disk**: Carom.dll is 27 KB and Carom.Extensions.dll 57.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). diff --git a/src/Carom.Telemetry.OpenTelemetry/CaromTelemetry.cs b/src/Carom.Telemetry.OpenTelemetry/CaromTelemetry.cs index 778513b..324e5fc 100644 --- a/src/Carom.Telemetry.OpenTelemetry/CaromTelemetry.cs +++ b/src/Carom.Telemetry.OpenTelemetry/CaromTelemetry.cs @@ -74,7 +74,7 @@ public static void Subscribe() lock (SubscriptionGate) { if (_subscribed) return; - CaromHooks.Retrying += RetryHandler; + CaromHooks.OnRetry += RetryHandler; CaromHooks.OnCircuitOpened += CircuitOpenedHandler; CaromHooks.OnBulkheadRejected += BulkheadRejectedHandler; CaromHooks.OnRateLimitRejected += RateLimitRejectedHandler; @@ -91,7 +91,7 @@ public static void Unsubscribe() lock (SubscriptionGate) { if (!_subscribed) return; - CaromHooks.Retrying -= RetryHandler; + CaromHooks.OnRetry -= RetryHandler; CaromHooks.OnCircuitOpened -= CircuitOpenedHandler; CaromHooks.OnBulkheadRejected -= BulkheadRejectedHandler; CaromHooks.OnRateLimitRejected -= RateLimitRejectedHandler; diff --git a/src/Carom/CaromHooks.cs b/src/Carom/CaromHooks.cs index 4c40a08..d68cd28 100644 --- a/src/Carom/CaromHooks.cs +++ b/src/Carom/CaromHooks.cs @@ -73,57 +73,16 @@ public RateLimitRejectedSignal(string serviceKey) /// /// Process-wide hooks raised by Carom and Carom.Extensions. Subscribe with += and - /// unsubscribe with -=. The retry hook is the event, whose add and - /// remove are atomic and which no consumer can overwrite. The other hooks are still plain - /// settable delegates, so a consumer or a test can read, replace or clear them. + /// unsubscribe with -=. Plain settable delegates, not events, so a consumer or a + /// test can read, replace or clear a hook; an event could never be reset. /// Nothing is computed or allocated when a hook is null, so an unsubscribed /// process pays nothing. Handlers run synchronously on the calling thread and /// must be fast and must not throw. /// public static class CaromHooks { - private static Action? _onRetry; - - /// - /// Raised after the backoff delay is computed, just before a retry runs. Add and remove - /// are atomic, and the event cannot be assigned from outside, so one subscriber cannot - /// remove another. Each subscriber is called on its own: one that throws does not stop - /// the ones after it. - /// - public static event Action? Retrying; - - /// - /// The old settable retry hook, still raised. Assigning it replaces only what was - /// assigned to this property, never a subscriber, but += on it is - /// still a non-atomic read, combine and write, so two threads can lose a subscriber. - /// - [Obsolete("Use Retrying.")] - public static Action? OnRetry - { - get => _onRetry; - set => _onRetry = value; - } - - /// - /// Raises the retry hooks. Each handler runs on its own so a throwing or - /// misbehaving one cannot skip the rest. Allocates only while a subscriber exists. - /// - internal static void Raise(int attempt, TimeSpan delay, Exception? cause) - { - var legacy = _onRetry; - var handlers = Retrying; - if (legacy == null && handlers == null) return; - - var signal = new RetrySignal(attempt, delay, cause?.GetType().Name); - if (legacy != null) Invoke(legacy, signal); - if (handlers == null) return; - - var list = handlers.GetInvocationList(); - for (int i = 0; i < list.Length; i++) - { - Invoke((Action)list[i], signal); - } - } + /// Raised after the backoff delay is computed, just before a retry runs. + public static Action? OnRetry { get; set; } /// Raised when a circuit breaker transitions from closed to open. public static Action? OnCircuitOpened { get; set; } @@ -134,6 +93,12 @@ internal static void Raise(int attempt, TimeSpan delay, Exception? cause) /// Raised when a rate limiter rejects a call. public static Action? OnRateLimitRejected { get; set; } + internal static void Raise(int attempt, TimeSpan delay, Exception? cause) + { + var onRetry = OnRetry; + if (onRetry != null) Invoke(onRetry, new RetrySignal(attempt, delay, cause?.GetType().Name)); + } + /// /// Invokes a hook without letting it break the path it observes. Raises happen inside /// catch blocks, so a subscriber that throws would replace the caller's exception and diff --git a/tests/Carom.ApiApproval.Tests/ApprovedApi/Carom.approved.txt b/tests/Carom.ApiApproval.Tests/ApprovedApi/Carom.approved.txt index c24f29d..080cb89 100644 --- a/tests/Carom.ApiApproval.Tests/ApprovedApi/Carom.approved.txt +++ b/tests/Carom.ApiApproval.Tests/ApprovedApi/Carom.approved.txt @@ -72,9 +72,7 @@ namespace Carom public static System.Action? OnBulkheadRejected { get; set; } public static System.Action? OnCircuitOpened { get; set; } public static System.Action? OnRateLimitRejected { get; set; } - [System.Obsolete("Use Retrying.")] public static System.Action? OnRetry { get; set; } - public static event System.Action? Retrying; } public readonly struct CircuitOpenedSignal { diff --git a/tests/Carom.ReadmeSamples.Tests/ReadmeSamples.cs b/tests/Carom.ReadmeSamples.Tests/ReadmeSamples.cs index f482108..3c01033 100644 --- a/tests/Carom.ReadmeSamples.Tests/ReadmeSamples.cs +++ b/tests/Carom.ReadmeSamples.Tests/ReadmeSamples.cs @@ -72,12 +72,4 @@ public static async Task DelayHint() GC.KeepAlive(data); } - - public static void RetryEvent() - { - // readme:begin retry-event - CaromHooks.Retrying += signal => - Console.WriteLine($"retry {signal.Attempt} in {signal.Delay}"); - // readme:end retry-event - } } diff --git a/tests/Carom.ReadmeSamples.Tests/ReadmeSamplesTests.cs b/tests/Carom.ReadmeSamples.Tests/ReadmeSamplesTests.cs index c89fecc..e3e4afb 100644 --- a/tests/Carom.ReadmeSamples.Tests/ReadmeSamplesTests.cs +++ b/tests/Carom.ReadmeSamples.Tests/ReadmeSamplesTests.cs @@ -19,7 +19,6 @@ public class ReadmeSamplesTests new object[] { "basic-usage" }, new object[] { "attempt-timeout" }, new object[] { "delay-hint" }, - new object[] { "retry-event" }, }; [Theory] diff --git a/tests/Carom.Tests/CaromHooksTests.cs b/tests/Carom.Tests/CaromHooksTests.cs index 9b53a94..e2db6e8 100644 --- a/tests/Carom.Tests/CaromHooksTests.cs +++ b/tests/Carom.Tests/CaromHooksTests.cs @@ -1,5 +1,3 @@ -#pragma warning disable CS0618 // These tests cover the obsolete OnRetry property next to the Retrying event. - using System; using System.Collections.Generic; using System.Threading.Tasks; @@ -269,141 +267,5 @@ public async Task AThrowingHook_DoesNotBreakTheAsyncRetryItObserves() } } - [Fact] - public void Retrying_TwoSubscribers_BothReceiveTheRetry() - { - var threadId = Environment.CurrentManagedThreadId; - var first = new List(); - var second = new List(); - Action a = s => { if (Environment.CurrentManagedThreadId == threadId) first.Add(s); }; - Action b = s => { if (Environment.CurrentManagedThreadId == threadId) second.Add(s); }; - CaromHooks.Retrying += a; - CaromHooks.Retrying += b; - try - { - RunOneRetry(); - - Assert.Single(first); - Assert.Single(second); - Assert.Equal(1, first[0].Attempt); - } - finally - { - CaromHooks.Retrying -= a; - CaromHooks.Retrying -= b; - } - } - - [Fact] - public void Retrying_OneSubscriberUnsubscribing_LeavesTheOther() - { - var threadId = Environment.CurrentManagedThreadId; - var first = new List(); - var second = new List(); - Action a = s => { if (Environment.CurrentManagedThreadId == threadId) first.Add(s); }; - Action b = s => { if (Environment.CurrentManagedThreadId == threadId) second.Add(s); }; - CaromHooks.Retrying += a; - CaromHooks.Retrying += b; - try - { - CaromHooks.Retrying -= a; - - RunOneRetry(); - - Assert.Empty(first); - Assert.Single(second); - } - finally - { - CaromHooks.Retrying -= a; - CaromHooks.Retrying -= b; - } - } - - [Fact] - public void AssigningTheObsoleteProperty_DoesNotRemoveRetryingSubscribers() - { - var threadId = Environment.CurrentManagedThreadId; - var received = new List(); - Action sub = s => { if (Environment.CurrentManagedThreadId == threadId) received.Add(s); }; - var prior = CaromHooks.OnRetry; - CaromHooks.Retrying += sub; - try - { - // This is the assignment that used to wipe every other subscriber. - CaromHooks.OnRetry = _ => { }; - CaromHooks.OnRetry = null; - - RunOneRetry(); - - Assert.Single(received); - } - finally - { - CaromHooks.Retrying -= sub; - CaromHooks.OnRetry = prior; - } - } - - [Fact] - public void Retrying_AThrowingSubscriber_DoesNotStopTheNextOne() - { - var threadId = Environment.CurrentManagedThreadId; - var received = new List(); - Action bad = s => { if (Environment.CurrentManagedThreadId == threadId) throw new InvalidOperationException("broken"); }; - Action good = s => { if (Environment.CurrentManagedThreadId == threadId) received.Add(s); }; - CaromHooks.Retrying += bad; - CaromHooks.Retrying += good; - try - { - RunOneRetry(); - - Assert.Single(received); - } - finally - { - CaromHooks.Retrying -= bad; - CaromHooks.Retrying -= good; - } - } - - [Fact] - public void Retrying_AndTheObsoleteProperty_BothReceiveTheRetry() - { - var threadId = Environment.CurrentManagedThreadId; - int viaEvent = 0, viaProperty = 0; - Action sub = s => { if (Environment.CurrentManagedThreadId == threadId) viaEvent++; }; - var prior = CaromHooks.OnRetry; - CaromHooks.Retrying += sub; - CaromHooks.OnRetry = s => { if (Environment.CurrentManagedThreadId == threadId) viaProperty++; }; - try - { - RunOneRetry(); - - Assert.Equal(1, viaEvent); - Assert.Equal(1, viaProperty); - } - finally - { - CaromHooks.Retrying -= sub; - CaromHooks.OnRetry = prior; - } - } - - private static void RunOneRetry() - { - int calls = 0; - Carom.Shot( - () => - { - calls++; - if (calls == 1) throw new CaromHooksProbeException(); - return 7; - }, - retries: 2, - baseDelay: TimeSpan.Zero, - shouldBounce: null, - disableJitter: true); - } } } From b1687cacbe497aaf10c7148d62c193d01f124c76 Mon Sep 17 00:00:00 2001 From: Arnel Robles Date: Sat, 14 Nov 2026 10:09:37 +0800 Subject: [PATCH 4/4] Pin attempt timeout and delay hint lines with tests, validate attempt timeout bound, document limits --- README.md | 6 +++--- .../AttemptTimeoutTests.cs | 21 +++++++++++++++++++ tests/Carom.Tests/DelayHintTests.cs | 6 +++--- 3 files changed, 27 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 1631e1d..773ae58 100644 --- a/README.md +++ b/README.md @@ -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** (27KB core, 57.5KB extensions) +- **Tiny Footprint** (27KB core, 59.5KB extensions) - **Fully Composable** (all patterns work together) ## 📦 Packages @@ -25,7 +25,7 @@ Sizes are the Release-built assemblies. Tests fail if the core grows past 28KB o | Package | Size | Purpose | |---------|------|---------| | **Carom** | 27KB | Core retry + timeout | -| **Carom.Extensions** | 57.5KB | Circuit Breaker, Fallback, Bulkhead, Rate Limiting | +| **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 | @@ -203,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 27 KB and Carom.Extensions.dll 57.5 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). diff --git a/tests/Carom.Extensions.Tests/AttemptTimeoutTests.cs b/tests/Carom.Extensions.Tests/AttemptTimeoutTests.cs index afe7b20..5c8bc76 100644 --- a/tests/Carom.Extensions.Tests/AttemptTimeoutTests.cs +++ b/tests/Carom.Extensions.Tests/AttemptTimeoutTests.cs @@ -174,6 +174,27 @@ public async Task CallerCancellation_SurfacesAsCancellation_NotAsAnAttemptTimeou Assert.False(ex is TimeoutRejectedException, "caller cancellation was reported as a try timeout"); } + [Fact] + public async Task ACancelledTry_WhenTheCallerCancelled_IsNotReportedAsAnAttemptTimeout() + { + // The caller cancels and the action returns an already-cancelled task, so the try + // ends with the caller's cancellation before any timer fires. Core's own race + // cannot pre-empt this: the task is complete when it is awaited. + using var cts = new CancellationTokenSource(); + int calls = 0; + + var ex = await Assert.ThrowsAnyAsync(() => + CaromAttemptTimeoutExtensions.ShotAsync(ct => + { + calls++; + cts.Cancel(); + return Task.FromCanceled(ct); + }, Quick(3), TimeSpan.FromSeconds(30), cts.Token)); + + Assert.False(ex is TimeoutRejectedException, "caller cancellation was reported as a try timeout"); + Assert.Equal(1, calls); + } + [Fact] public async Task TheTryTokenSource_IsDisposedWhenTheTryEnds() { diff --git a/tests/Carom.Tests/DelayHintTests.cs b/tests/Carom.Tests/DelayHintTests.cs index a831693..aff8c7b 100644 --- a/tests/Carom.Tests/DelayHintTests.cs +++ b/tests/Carom.Tests/DelayHintTests.cs @@ -221,15 +221,15 @@ public void WithDelayHint_RejectsNull_AndSurvivesTheOtherWithMethods() [Fact] public void SyncShot_HonoursTheHint() { - var bounce = Bounce.Times(2).WithDelay(TimeSpan.FromSeconds(30)).WithDelayHint(_ => TimeSpan.FromMilliseconds(5)); + var bounce = Bounce.Times(2).WithDelay(TimeSpan.FromSeconds(2)).WithDelayHint(_ => TimeSpan.FromMilliseconds(5)); int calls = 0; var watch = Stopwatch.StartNew(); var result = Carom.Shot(() => ++calls == 1 ? throw new RetryAfterException(TimeSpan.Zero) : 7, bounce); - // The computed delay would be at least the 30 s base; the hint is 5 ms. + // The computed delay would be at least the 2 s base; the hint is 5 ms. Assert.Equal(7, result); - Assert.True(watch.Elapsed < TimeSpan.FromSeconds(10)); + Assert.True(watch.Elapsed < TimeSpan.FromMilliseconds(1000), $"waited {watch.Elapsed}"); } [Fact]