-
-
Notifications
You must be signed in to change notification settings - Fork 0
feat: Built-in request timeout interceptor without Polly dependency (ITimeoutRequest)
#154
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,53 @@ | ||
| namespace NetEvolve.Pulse.Extensibility; | ||
|
|
||
| /// <summary> | ||
| /// Marker interface for requests that enforce a per-request deadline using a <see cref="System.Threading.CancellationTokenSource"/>. | ||
| /// Implement this interface alongside <see cref="ICommand{TResponse}"/> or <see cref="IQuery{TResponse}"/> to opt in to | ||
| /// built-in timeout enforcement without any external dependencies. | ||
| /// </summary> | ||
| /// <remarks> | ||
| /// <para><strong>Usage:</strong></para> | ||
| /// When a request implements <see cref="ITimeoutRequest"/>, the <c>TimeoutRequestInterceptor</c> | ||
| /// will create a linked <see cref="System.Threading.CancellationTokenSource"/> using the effective timeout. | ||
| /// If the handler does not complete within that deadline, a <see cref="System.TimeoutException"/> is thrown. | ||
| /// <para><strong>Timeout Resolution:</strong></para> | ||
| /// <list type="number"> | ||
| /// <item><description>If <see cref="Timeout"/> is non-<see langword="null"/>, that value is used as the deadline.</description></item> | ||
| /// <item><description>If <see cref="Timeout"/> is <see langword="null"/>, the globally configured fallback timeout is used (if set).</description></item> | ||
| /// <item><description>If neither is set, the interceptor is a transparent pass-through.</description></item> | ||
| /// </list> | ||
| /// Requests that do not implement <see cref="ITimeoutRequest"/> are always passed through without any timeout. | ||
| /// <para><strong>Distinguishing Timeout from User Cancellation:</strong></para> | ||
| /// The interceptor correctly distinguishes between a timeout-triggered cancellation and a caller-initiated | ||
| /// cancellation, re-throwing a <see cref="System.TimeoutException"/> only in the former case. | ||
| /// </remarks> | ||
| /// <example> | ||
| /// <code> | ||
| /// // Explicit per-request timeout | ||
| /// public record ProcessOrderCommand(string OrderId) : ICommand<OrderResult>, ITimeoutRequest | ||
| /// { | ||
| /// public string? CorrelationId { get; set; } | ||
| /// public TimeSpan? Timeout => TimeSpan.FromSeconds(10); | ||
| /// } | ||
| /// | ||
| /// // Defer to the global fallback configured via AddRequestTimeout(globalTimeout: ...) | ||
| /// public record GetStatusQuery(string Id) : IQuery<Status>, ITimeoutRequest | ||
| /// { | ||
| /// public string? CorrelationId { get; set; } | ||
| /// public TimeSpan? Timeout => null; | ||
| /// } | ||
| /// </code> | ||
| /// </example> | ||
| /// <seealso cref="IRequest{TResponse}"/> | ||
| /// <seealso cref="ICommand{TResponse}"/> | ||
| /// <seealso cref="IQuery{TResponse}"/> | ||
| public interface ITimeoutRequest | ||
| { | ||
| /// <summary> | ||
| /// Gets the maximum allowed duration for the handler to complete before a | ||
| /// <see cref="System.TimeoutException"/> is raised. | ||
| /// When <see langword="null"/>, the globally configured fallback timeout is applied if set; | ||
| /// otherwise the interceptor is a transparent pass-through for this request. | ||
| /// </summary> | ||
| TimeSpan? Timeout { get; } | ||
| } |
93 changes: 93 additions & 0 deletions
93
src/NetEvolve.Pulse/Interceptors/TimeoutRequestInterceptor.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,93 @@ | ||
| namespace NetEvolve.Pulse.Interceptors; | ||
|
|
||
| using System; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| using Microsoft.Extensions.Options; | ||
| using NetEvolve.Pulse.Extensibility; | ||
|
|
||
| /// <summary> | ||
| /// Built-in request interceptor that enforces a per-request deadline using a linked | ||
| /// <see cref="CancellationTokenSource"/>, without any external dependencies. | ||
| /// </summary> | ||
| /// <typeparam name="TRequest">The type of request being intercepted.</typeparam> | ||
| /// <typeparam name="TResponse">The type of response produced by the request.</typeparam> | ||
| /// <remarks> | ||
| /// <para><strong>Activation:</strong></para> | ||
| /// The interceptor only activates when the request implements <see cref="ITimeoutRequest"/>. | ||
| /// Requests that do not implement <see cref="ITimeoutRequest"/> are always passed through without any timeout. | ||
| /// For <see cref="ITimeoutRequest"/> implementations the effective deadline is resolved as follows: | ||
| /// <list type="number"> | ||
| /// <item><description><see cref="ITimeoutRequest.Timeout"/> — used when non-<see langword="null"/>.</description></item> | ||
| /// <item><description><see cref="TimeoutRequestInterceptorOptions.GlobalTimeout"/> — used as fallback when <see cref="ITimeoutRequest.Timeout"/> is <see langword="null"/>.</description></item> | ||
| /// <item><description>If neither is set, the interceptor is a transparent pass-through for that request.</description></item> | ||
| /// </list> | ||
| /// <para><strong>Cancellation Semantics:</strong></para> | ||
| /// The interceptor correctly distinguishes between a timeout-triggered cancellation and a | ||
| /// caller-initiated cancellation: only when the deadline is exceeded is a | ||
| /// <see cref="TimeoutException"/> thrown. Caller cancellations are propagated as | ||
| /// <see cref="OperationCanceledException"/> as usual. | ||
| /// <para><strong>Resource Management:</strong></para> | ||
| /// The internally created <see cref="CancellationTokenSource"/> is always disposed, even when | ||
| /// the handler throws. | ||
| /// </remarks> | ||
| internal sealed class TimeoutRequestInterceptor<TRequest, TResponse> : IRequestInterceptor<TRequest, TResponse> | ||
| where TRequest : IRequest<TResponse> | ||
| { | ||
| private readonly IOptions<TimeoutRequestInterceptorOptions> _options; | ||
|
|
||
| /// <summary> | ||
| /// Initializes a new instance of the <see cref="TimeoutRequestInterceptor{TRequest, TResponse}"/> class. | ||
| /// </summary> | ||
| /// <param name="options">The timeout interceptor options.</param> | ||
| /// <exception cref="ArgumentNullException">Thrown when <paramref name="options"/> is <see langword="null"/>.</exception> | ||
| public TimeoutRequestInterceptor(IOptions<TimeoutRequestInterceptorOptions> options) | ||
| { | ||
| ArgumentNullException.ThrowIfNull(options); | ||
| _options = options; | ||
| } | ||
|
|
||
| /// <inheritdoc /> | ||
| /// <exception cref="TimeoutException"> | ||
| /// Thrown when the handler does not complete within the configured deadline and the original | ||
| /// <see cref="CancellationToken"/> has not been independently cancelled. | ||
| /// </exception> | ||
| public async Task<TResponse> HandleAsync( | ||
| TRequest request, | ||
| Func<TRequest, CancellationToken, Task<TResponse>> handler, | ||
| CancellationToken cancellationToken = default | ||
| ) | ||
| { | ||
| ArgumentNullException.ThrowIfNull(handler); | ||
|
|
||
| // Requests not implementing ITimeoutRequest are always passed through. | ||
| if (request is not ITimeoutRequest timeoutRequest) | ||
| { | ||
| return await handler(request, cancellationToken).ConfigureAwait(false); | ||
| } | ||
|
|
||
| // Resolve effective timeout: per-request value first, global fallback second. | ||
| var timeout = timeoutRequest.Timeout ?? _options.Value.GlobalTimeout; | ||
|
|
||
| // No timeout configured — transparent pass-through. | ||
| if (timeout is null) | ||
| { | ||
| return await handler(request, cancellationToken).ConfigureAwait(false); | ||
| } | ||
|
|
||
| using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); | ||
| cts.CancelAfter(timeout.Value); | ||
|
|
||
| try | ||
| { | ||
| return await handler(request, cts.Token).ConfigureAwait(false); | ||
| } | ||
| catch (OperationCanceledException) | ||
| when (!cancellationToken.IsCancellationRequested && cts.Token.IsCancellationRequested) | ||
| { | ||
| throw new TimeoutException( | ||
| $"The request '{typeof(TRequest).Name}' timed out after {timeout.Value.TotalMilliseconds}ms." | ||
| ); | ||
| } | ||
| } | ||
| } |
73 changes: 73 additions & 0 deletions
73
src/NetEvolve.Pulse/TimeoutMediatorConfiguratorExtensions.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,73 @@ | ||
| namespace NetEvolve.Pulse; | ||
|
|
||
| using System; | ||
| using Microsoft.Extensions.DependencyInjection; | ||
| using Microsoft.Extensions.DependencyInjection.Extensions; | ||
| using NetEvolve.Pulse.Extensibility; | ||
| using NetEvolve.Pulse.Interceptors; | ||
|
|
||
| /// <summary> | ||
| /// Provides fluent extension methods for registering the built-in request timeout interceptor | ||
| /// with the Pulse mediator. | ||
| /// </summary> | ||
| /// <seealso cref="TimeoutRequestInterceptorOptions"/> | ||
| /// <seealso cref="ITimeoutRequest"/> | ||
| public static class TimeoutMediatorConfiguratorExtensions | ||
| { | ||
| /// <summary> | ||
| /// Registers the built-in <c>TimeoutRequestInterceptor</c> that enforces per-request deadlines | ||
| /// using a linked <see cref="System.Threading.CancellationTokenSource"/>. | ||
| /// </summary> | ||
| /// <param name="configurator">The mediator configurator.</param> | ||
| /// <param name="globalTimeout"> | ||
| /// An optional global fallback timeout applied to <see cref="ITimeoutRequest"/> implementations | ||
| /// that return <see langword="null"/> from <see cref="ITimeoutRequest.Timeout"/>. | ||
| /// Requests that do not implement <see cref="ITimeoutRequest"/> are always passed through | ||
| /// regardless of this value. | ||
| /// When <see langword="null"/> (default), only requests implementing <see cref="ITimeoutRequest"/> | ||
| /// with a non-<see langword="null"/> <see cref="ITimeoutRequest.Timeout"/> are subject to a deadline. | ||
| /// </param> | ||
| /// <returns>The configurator for method chaining.</returns> | ||
| /// <exception cref="ArgumentNullException">Thrown when <paramref name="configurator"/> is <see langword="null"/>.</exception> | ||
| /// <remarks> | ||
| /// <para><strong>Timeout Resolution (for <see cref="ITimeoutRequest"/> requests only):</strong></para> | ||
| /// <list type="number"> | ||
| /// <item><description><see cref="ITimeoutRequest.Timeout"/> — used when non-<see langword="null"/>.</description></item> | ||
| /// <item><description><paramref name="globalTimeout"/> — used as fallback when <see cref="ITimeoutRequest.Timeout"/> is <see langword="null"/>.</description></item> | ||
| /// <item><description>If neither is set, the interceptor is a transparent pass-through.</description></item> | ||
| /// </list> | ||
| /// Requests that do not implement <see cref="ITimeoutRequest"/> are always passed through. | ||
| /// <para><strong>Cancellation Semantics:</strong></para> | ||
| /// A <see cref="System.TimeoutException"/> is thrown only when the deadline is exceeded. | ||
| /// Caller-initiated cancellations propagate as <see cref="System.OperationCanceledException"/> as usual. | ||
| /// </remarks> | ||
| /// <example> | ||
| /// <para><strong>Without global timeout (only ITimeoutRequest requests with a non-null Timeout are affected):</strong></para> | ||
| /// <code> | ||
| /// services.AddPulse(c => c.AddRequestTimeout()); | ||
| /// </code> | ||
| /// <para><strong>With global fallback timeout (ITimeoutRequest requests with a null Timeout use this as deadline):</strong></para> | ||
| /// <code> | ||
| /// services.AddPulse(c => c.AddRequestTimeout(TimeSpan.FromSeconds(30))); | ||
| /// </code> | ||
| /// </example> | ||
| /// <seealso cref="ITimeoutRequest"/> | ||
| /// <seealso cref="TimeoutRequestInterceptorOptions"/> | ||
| public static IMediatorConfigurator AddRequestTimeout( | ||
| this IMediatorConfigurator configurator, | ||
| TimeSpan? globalTimeout = null | ||
| ) | ||
| { | ||
| ArgumentNullException.ThrowIfNull(configurator); | ||
|
|
||
| _ = configurator.Services.Configure<TimeoutRequestInterceptorOptions>(opts => | ||
| opts.GlobalTimeout = globalTimeout | ||
| ); | ||
|
|
||
| configurator.Services.TryAddEnumerable( | ||
| ServiceDescriptor.Singleton(typeof(IRequestInterceptor<,>), typeof(TimeoutRequestInterceptor<,>)) | ||
| ); | ||
|
|
||
| return configurator; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| namespace NetEvolve.Pulse; | ||
|
|
||
| /// <summary> | ||
| /// Options for the built-in request timeout interceptor registered via <c>AddRequestTimeout()</c>. | ||
| /// </summary> | ||
| /// <remarks> | ||
| /// <para><strong>Global Timeout:</strong></para> | ||
| /// When <see cref="GlobalTimeout"/> is set, all requests that do not implement | ||
| /// <see cref="Extensibility.ITimeoutRequest"/> are also subject to the global deadline. | ||
| /// Requests that implement <see cref="Extensibility.ITimeoutRequest"/> always use their own | ||
| /// <see cref="Extensibility.ITimeoutRequest.Timeout"/> value, which takes precedence over | ||
| /// <see cref="GlobalTimeout"/>. | ||
| /// </remarks> | ||
| /// <example> | ||
| /// <code> | ||
| /// services.AddPulse(c => c.AddRequestTimeout(TimeSpan.FromSeconds(30))); | ||
| /// </code> | ||
| /// </example> | ||
| /// <seealso cref="Extensibility.ITimeoutRequest"/> | ||
| public sealed class TimeoutRequestInterceptorOptions | ||
| { | ||
| /// <summary> | ||
| /// Gets or sets the global fallback timeout applied to <see cref="Extensibility.ITimeoutRequest"/> | ||
| /// implementations that return <see langword="null"/> from <see cref="Extensibility.ITimeoutRequest.Timeout"/>. | ||
| /// Requests that do not implement <see cref="Extensibility.ITimeoutRequest"/> are always passed through | ||
| /// regardless of this value. | ||
| /// When <see langword="null"/> (default), requests with a <see langword="null"/> | ||
| /// <see cref="Extensibility.ITimeoutRequest.Timeout"/> are not subject to any deadline. | ||
| /// </summary> | ||
| public TimeSpan? GlobalTimeout { get; set; } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The remarks claim GlobalTimeout affects requests not implementing ITimeoutRequest, but interceptor control flow always bypasses those requests, so this documented behavior is impossible.
Show fix
Details
✨ AI Reasoning
The codebase defines that only opted-in requests participate in timeout enforcement, but this documentation states that requests without opt-in are also affected by the global timeout. That creates an impossible expectation for consumers because the documented path cannot occur under the current control flow.
Reply
@AikidoSec feedback: [FEEDBACK]to get better review comments in the future.Reply
@AikidoSec ignore: [REASON]to ignore this issue.More info
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@copilot resolve this issue