-
Notifications
You must be signed in to change notification settings - Fork 10.2k
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
Implement request timeout middleware #46115
Merged
Merged
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
d784a5b
Resolve conflict
Kahbazi 17dffdd
Fix tests
Kahbazi 4250e31
Fix typos/casing.
adityamandaleeka 0e71e8e
Doc comments.
adityamandaleeka e7839c6
Rename test file.
adityamandaleeka 61eb2ee
Misc cleanup.
adityamandaleeka 4a29159
Add to HttpProtocolFeatureCollection.
adityamandaleeka 2515bf1
More edits.
adityamandaleeka 2e5a6a1
Re-run generator for feature collection.
adityamandaleeka 8f28de5
Fix namespaces
Tratcher fb7422b
Fix test
Tratcher 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 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
149 changes: 149 additions & 0 deletions
149
src/Http/Http/perf/Microbenchmarks/RequestTimeoutsMiddlewareBenchmark.cs
This file contains 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,149 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
using BenchmarkDotNet.Attributes; | ||
using Microsoft.AspNetCore.Http.Timeouts; | ||
using Microsoft.Extensions.Logging.Abstractions; | ||
using Microsoft.Extensions.Options; | ||
|
||
namespace Microsoft.AspNetCore.Http; | ||
|
||
public class RequestTimeoutsMiddlewareBenchmark | ||
{ | ||
RequestTimeoutsMiddleware _middlewareWithNoTimeout; | ||
RequestTimeoutsMiddleware _middleware; | ||
RequestTimeoutsMiddleware _middlewareWithThrow; | ||
|
||
[GlobalSetup] | ||
public void GlobalSetup() | ||
{ | ||
_middlewareWithNoTimeout = new RequestTimeoutsMiddleware( | ||
async context => { await Task.Yield(); }, | ||
new CancellationTokenLinker(), | ||
NullLogger<RequestTimeoutsMiddleware>.Instance, | ||
Options.Create(new RequestTimeoutOptions())); | ||
|
||
_middleware = new RequestTimeoutsMiddleware( | ||
async context => { await Task.Yield(); }, | ||
new CancellationTokenLinker(), | ||
NullLogger<RequestTimeoutsMiddleware>.Instance, | ||
Options.Create(new RequestTimeoutOptions | ||
{ | ||
DefaultPolicy = new RequestTimeoutPolicy | ||
{ | ||
Timeout = TimeSpan.FromMilliseconds(200) | ||
}, | ||
Policies = | ||
{ | ||
["policy1"] = new RequestTimeoutPolicy { Timeout = TimeSpan.FromMilliseconds(200)} | ||
} | ||
})); | ||
|
||
_middlewareWithThrow = new RequestTimeoutsMiddleware( | ||
async context => | ||
{ | ||
await Task.Delay(TimeSpan.FromMicroseconds(2)); | ||
context.RequestAborted.ThrowIfCancellationRequested(); | ||
}, | ||
new CancellationTokenLinker(), | ||
NullLogger<RequestTimeoutsMiddleware>.Instance, | ||
Options.Create(new RequestTimeoutOptions | ||
{ | ||
DefaultPolicy = new RequestTimeoutPolicy | ||
{ | ||
Timeout = TimeSpan.FromMicroseconds(1) | ||
} | ||
})); | ||
} | ||
|
||
[Benchmark] | ||
public async Task NoMetadataNoDefault() | ||
{ | ||
var context = CreateHttpContext(new Endpoint(null, null, null)); | ||
await _middlewareWithNoTimeout.Invoke(context); | ||
} | ||
|
||
[Benchmark] | ||
public async Task DefaultTimeout() | ||
{ | ||
var context = CreateHttpContext(new Endpoint(null, null, null)); | ||
|
||
await _middleware.Invoke(context); | ||
} | ||
|
||
[Benchmark] | ||
public async Task DefaultTimeoutOverriddenByDisable() | ||
{ | ||
var context = CreateHttpContext(new Endpoint( | ||
null, | ||
new EndpointMetadataCollection(new DisableRequestTimeoutAttribute()), | ||
null)); | ||
|
||
await _middleware.Invoke(context); | ||
} | ||
|
||
[Benchmark] | ||
public async Task TimeoutMetadata() | ||
{ | ||
var context = CreateHttpContext(new Endpoint( | ||
null, | ||
new EndpointMetadataCollection(new RequestTimeoutAttribute(200)), | ||
null)); | ||
|
||
await _middleware.Invoke(context); | ||
} | ||
|
||
[Benchmark] | ||
public async Task NamedPolicyMetadata() | ||
{ | ||
var context = CreateHttpContext(new Endpoint( | ||
null, | ||
new EndpointMetadataCollection(new RequestTimeoutAttribute("policy1")), | ||
null)); | ||
|
||
await _middleware.Invoke(context); | ||
} | ||
|
||
[Benchmark] | ||
public async Task TimeoutFires() | ||
{ | ||
var context = CreateHttpContext(new Endpoint(null, null, null)); | ||
|
||
await _middlewareWithThrow.Invoke(context); | ||
} | ||
|
||
private HttpContext CreateHttpContext(Endpoint endpoint) | ||
{ | ||
var context = new DefaultHttpContext(); | ||
context.SetEndpoint(endpoint); | ||
|
||
var cts = new CancellationTokenSource(); | ||
context.RequestAborted = cts.Token; | ||
|
||
return context; | ||
} | ||
|
||
private sealed class Options : IOptionsMonitor<RequestTimeoutOptions> | ||
{ | ||
private readonly RequestTimeoutOptions _options; | ||
|
||
private Options(RequestTimeoutOptions options) | ||
{ | ||
_options = options; | ||
} | ||
|
||
public static Options Create(RequestTimeoutOptions options) | ||
{ | ||
return new Options(options); | ||
} | ||
|
||
public RequestTimeoutOptions CurrentValue => _options; | ||
|
||
public RequestTimeoutOptions Get(string name) => _options; | ||
|
||
public IDisposable OnChange(Action<RequestTimeoutOptions, string> listener) | ||
{ | ||
return default; | ||
} | ||
} | ||
} |
This file contains 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
This file contains 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 |
---|---|---|
@@ -1,3 +1,38 @@ | ||
#nullable enable | ||
Microsoft.AspNetCore.Builder.RequestTimeoutsIApplicationBuilderExtensions | ||
Microsoft.AspNetCore.Builder.RequestTimeoutsIEndpointConventionBuilderExtensions | ||
Microsoft.AspNetCore.Http.BindingAddress.IsNamedPipe.get -> bool | ||
Microsoft.AspNetCore.Http.BindingAddress.NamedPipeName.get -> string! | ||
Microsoft.AspNetCore.Http.BindingAddress.NamedPipeName.get -> string! | ||
Microsoft.AspNetCore.Http.Timeouts.DisableRequestTimeoutAttribute | ||
Microsoft.AspNetCore.Http.Timeouts.DisableRequestTimeoutAttribute.DisableRequestTimeoutAttribute() -> void | ||
Microsoft.AspNetCore.Http.Timeouts.IHttpRequestTimeoutFeature | ||
Microsoft.AspNetCore.Http.Timeouts.IHttpRequestTimeoutFeature.DisableTimeout() -> void | ||
Microsoft.AspNetCore.Http.Timeouts.IHttpRequestTimeoutFeature.RequestTimeoutToken.get -> System.Threading.CancellationToken | ||
Microsoft.AspNetCore.Http.Timeouts.RequestTimeoutAttribute | ||
Microsoft.AspNetCore.Http.Timeouts.RequestTimeoutAttribute.PolicyName.get -> string? | ||
Microsoft.AspNetCore.Http.Timeouts.RequestTimeoutAttribute.RequestTimeoutAttribute(int milliseconds) -> void | ||
Microsoft.AspNetCore.Http.Timeouts.RequestTimeoutAttribute.RequestTimeoutAttribute(string! policyName) -> void | ||
Microsoft.AspNetCore.Http.Timeouts.RequestTimeoutAttribute.Timeout.get -> System.TimeSpan? | ||
Microsoft.AspNetCore.Http.Timeouts.RequestTimeoutOptions | ||
Microsoft.AspNetCore.Http.Timeouts.RequestTimeoutOptions.AddPolicy(string! policyName, Microsoft.AspNetCore.Http.Timeouts.RequestTimeoutPolicy! policy) -> Microsoft.AspNetCore.Http.Timeouts.RequestTimeoutOptions! | ||
Microsoft.AspNetCore.Http.Timeouts.RequestTimeoutOptions.AddPolicy(string! policyName, System.TimeSpan timeout) -> Microsoft.AspNetCore.Http.Timeouts.RequestTimeoutOptions! | ||
Microsoft.AspNetCore.Http.Timeouts.RequestTimeoutOptions.DefaultPolicy.get -> Microsoft.AspNetCore.Http.Timeouts.RequestTimeoutPolicy? | ||
Microsoft.AspNetCore.Http.Timeouts.RequestTimeoutOptions.DefaultPolicy.set -> void | ||
Microsoft.AspNetCore.Http.Timeouts.RequestTimeoutOptions.Policies.get -> System.Collections.Generic.IDictionary<string!, Microsoft.AspNetCore.Http.Timeouts.RequestTimeoutPolicy!>! | ||
Microsoft.AspNetCore.Http.Timeouts.RequestTimeoutOptions.RequestTimeoutOptions() -> void | ||
Microsoft.AspNetCore.Http.Timeouts.RequestTimeoutPolicy | ||
Microsoft.AspNetCore.Http.Timeouts.RequestTimeoutPolicy.RequestTimeoutPolicy() -> void | ||
Microsoft.AspNetCore.Http.Timeouts.RequestTimeoutPolicy.Timeout.get -> System.TimeSpan? | ||
Microsoft.AspNetCore.Http.Timeouts.RequestTimeoutPolicy.Timeout.init -> void | ||
Microsoft.AspNetCore.Http.Timeouts.RequestTimeoutPolicy.TimeoutStatusCode.get -> int? | ||
Microsoft.AspNetCore.Http.Timeouts.RequestTimeoutPolicy.TimeoutStatusCode.init -> void | ||
Microsoft.AspNetCore.Http.Timeouts.RequestTimeoutPolicy.WriteTimeoutResponse.get -> Microsoft.AspNetCore.Http.RequestDelegate? | ||
Microsoft.AspNetCore.Http.Timeouts.RequestTimeoutPolicy.WriteTimeoutResponse.init -> void | ||
Microsoft.Extensions.DependencyInjection.RequestTimeoutsIServiceCollectionExtensions | ||
static Microsoft.AspNetCore.Builder.RequestTimeoutsIApplicationBuilderExtensions.UseRequestTimeouts(this Microsoft.AspNetCore.Builder.IApplicationBuilder! builder) -> Microsoft.AspNetCore.Builder.IApplicationBuilder! | ||
static Microsoft.AspNetCore.Builder.RequestTimeoutsIEndpointConventionBuilderExtensions.DisableRequestTimeout(this Microsoft.AspNetCore.Builder.IEndpointConventionBuilder! builder) -> Microsoft.AspNetCore.Builder.IEndpointConventionBuilder! | ||
static Microsoft.AspNetCore.Builder.RequestTimeoutsIEndpointConventionBuilderExtensions.WithRequestTimeout(this Microsoft.AspNetCore.Builder.IEndpointConventionBuilder! builder, Microsoft.AspNetCore.Http.Timeouts.RequestTimeoutPolicy! policy) -> Microsoft.AspNetCore.Builder.IEndpointConventionBuilder! | ||
static Microsoft.AspNetCore.Builder.RequestTimeoutsIEndpointConventionBuilderExtensions.WithRequestTimeout(this Microsoft.AspNetCore.Builder.IEndpointConventionBuilder! builder, string! policyName) -> Microsoft.AspNetCore.Builder.IEndpointConventionBuilder! | ||
static Microsoft.AspNetCore.Builder.RequestTimeoutsIEndpointConventionBuilderExtensions.WithRequestTimeout(this Microsoft.AspNetCore.Builder.IEndpointConventionBuilder! builder, System.TimeSpan timeout) -> Microsoft.AspNetCore.Builder.IEndpointConventionBuilder! | ||
static Microsoft.Extensions.DependencyInjection.RequestTimeoutsIServiceCollectionExtensions.AddRequestTimeouts(this Microsoft.Extensions.DependencyInjection.IServiceCollection! services) -> Microsoft.Extensions.DependencyInjection.IServiceCollection! | ||
static Microsoft.Extensions.DependencyInjection.RequestTimeoutsIServiceCollectionExtensions.AddRequestTimeouts(this Microsoft.Extensions.DependencyInjection.IServiceCollection! services, System.Action<Microsoft.AspNetCore.Http.Timeouts.RequestTimeoutOptions!>! configure) -> Microsoft.Extensions.DependencyInjection.IServiceCollection! |
This file contains 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,20 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
using Microsoft.AspNetCore.Internal; | ||
|
||
namespace Microsoft.AspNetCore.Http.Timeouts; | ||
|
||
internal sealed class CancellationTokenLinker : ICancellationTokenLinker | ||
{ | ||
private readonly CancellationTokenSourcePool _ctsPool = new(); | ||
|
||
public (CancellationTokenSource linkedCts, CancellationTokenSource timeoutCts) GetLinkedCancellationTokenSource(HttpContext httpContext, CancellationToken originalToken, TimeSpan timeSpan) | ||
{ | ||
var timeoutCts = _ctsPool.Rent(); | ||
timeoutCts.CancelAfter(timeSpan); | ||
httpContext.Response.RegisterForDispose(timeoutCts); | ||
var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(originalToken, timeoutCts.Token); | ||
return (linkedCts, timeoutCts); | ||
} | ||
} |
15 changes: 15 additions & 0 deletions
15
src/Http/Http/src/Timeouts/DisableRequestTimeoutAttribute.cs
This file contains 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,15 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
namespace Microsoft.AspNetCore.Http.Timeouts; | ||
|
||
/// <summary> | ||
/// Metadata that disables request timeouts on an endpoint. | ||
/// </summary> | ||
/// <remarks> | ||
/// Completely disables the request timeouts middleware from applying to this endpoint. | ||
/// </remarks> | ||
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)] | ||
public sealed class DisableRequestTimeoutAttribute : Attribute | ||
{ | ||
} |
This file contains 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,21 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
namespace Microsoft.AspNetCore.Http.Timeouts; | ||
|
||
internal sealed class HttpRequestTimeoutFeature : IHttpRequestTimeoutFeature | ||
{ | ||
private readonly CancellationTokenSource _timeoutCancellationTokenSource; | ||
|
||
public HttpRequestTimeoutFeature(CancellationTokenSource timeoutCancellationTokenSource) | ||
{ | ||
_timeoutCancellationTokenSource = timeoutCancellationTokenSource; | ||
} | ||
|
||
public CancellationToken RequestTimeoutToken => _timeoutCancellationTokenSource.Token; | ||
|
||
public void DisableTimeout() | ||
{ | ||
_timeoutCancellationTokenSource.CancelAfter(Timeout.Infinite); | ||
} | ||
} |
This file contains 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,9 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
namespace Microsoft.AspNetCore.Http.Timeouts; | ||
|
||
internal interface ICancellationTokenLinker | ||
{ | ||
(CancellationTokenSource linkedCts, CancellationTokenSource timeoutCts) GetLinkedCancellationTokenSource(HttpContext httpContext, CancellationToken originalToken, TimeSpan timeSpan); | ||
} |
This file contains 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,21 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
namespace Microsoft.AspNetCore.Http.Timeouts; | ||
|
||
/// <summary> | ||
/// Used to control timeouts on the current request. | ||
/// </summary> | ||
public interface IHttpRequestTimeoutFeature | ||
{ | ||
/// <summary> | ||
/// A <see cref="CancellationToken" /> that will trigger when the request times out. | ||
/// </summary> | ||
CancellationToken RequestTimeoutToken { get; } | ||
Kahbazi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
/// <summary> | ||
/// Disables the request timeout if it hasn't already expired. This does not | ||
/// trigger the <see cref="RequestTimeoutToken"/>. | ||
/// </summary> | ||
void DisableTimeout(); | ||
} |
This file contains 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,12 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
using Microsoft.Extensions.Logging; | ||
|
||
namespace Microsoft.AspNetCore.Http.Timeouts; | ||
|
||
internal static partial class LoggerExtensions | ||
{ | ||
[LoggerMessage(1, LogLevel.Warning, "Timeout exception handled.")] | ||
adityamandaleeka marked this conversation as resolved.
Show resolved
Hide resolved
|
||
public static partial void TimeoutExceptionHandled(this ILogger logger, Exception exception); | ||
} |
This file contains 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,43 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
namespace Microsoft.AspNetCore.Http.Timeouts; | ||
|
||
/// <summary> | ||
/// Metadata that provides endpoint-specific request timeouts. | ||
/// </summary> | ||
/// <remarks> | ||
/// The default policy will be ignored with this attribute applied. | ||
/// </remarks> | ||
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)] | ||
public sealed class RequestTimeoutAttribute : Attribute | ||
{ | ||
/// <summary> | ||
/// The timeout to apply for this endpoint. | ||
/// </summary> | ||
public TimeSpan? Timeout { get; } | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Is there prior art for attributes converting constructor arguments to a property not supported on attributes? (by which I mean you can't have a settable |
||
|
||
/// <summary> | ||
/// The name of the policy which needs to be applied. | ||
/// This value is case-insensitive. | ||
/// </summary> | ||
public string? PolicyName { get; } | ||
|
||
/// <summary> | ||
/// Creates a new instance of <see cref="RequestTimeoutAttribute"/> using the specified timeout. | ||
/// </summary> | ||
/// <param name="milliseconds">The duration, in milliseconds, of the timeout for this endpoint.</param> | ||
public RequestTimeoutAttribute(int milliseconds) | ||
Tratcher marked this conversation as resolved.
Show resolved
Hide resolved
|
||
{ | ||
Timeout = TimeSpan.FromMilliseconds(milliseconds); | ||
} | ||
|
||
/// <summary> | ||
/// Creates a new instance of <see cref="RequestTimeoutAttribute"/> using the specified policy. | ||
/// </summary> | ||
/// <param name="policyName">The name of the policy which needs to be applied (case-insensitive).</param> | ||
public RequestTimeoutAttribute(string policyName) | ||
{ | ||
PolicyName = policyName; | ||
} | ||
} |
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.
It's good to change these tuple members to PascalCase.
dotnet/runtime#27939