Skip to content

Commit c8cee13

Browse files
committed
Simplify!
1 parent 3e32341 commit c8cee13

File tree

3 files changed

+57
-246
lines changed

3 files changed

+57
-246
lines changed

src/ReverseProxy/Service/Proxy/HttpProxy.cs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,6 @@ internal class HttpProxy : IHttpProxy
3434
private readonly ILogger _logger;
3535
private readonly IClock _clock;
3636

37-
private static readonly TimeoutCtsPool _ctsPool = new(DefaultTimeout, resolution: TimeSpan.FromSeconds(2));
38-
3937
public HttpProxy(ILogger<HttpProxy> logger, IClock clock)
4038
{
4139
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
@@ -125,7 +123,7 @@ public async Task ProxyAsync(
125123
// :: Step 4: Send the outgoing request using HttpClient
126124
HttpResponseMessage destinationResponse;
127125

128-
var requestTimeoutSource = _ctsPool.Rent(requestOptions?.Timeout ?? DefaultTimeout, requestAborted);
126+
var requestTimeoutSource = PooledCTS.Rent(requestOptions?.Timeout ?? DefaultTimeout, requestAborted);
129127
var requestTimeoutToken = requestTimeoutSource.Token;
130128
try
131129
{
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
// Copyright (c) Microsoft Corporation.
2+
// Licensed under the MIT License.
3+
4+
#nullable enable
5+
6+
using System;
7+
using System.Collections.Concurrent;
8+
using System.Threading;
9+
10+
namespace Yarp.ReverseProxy.Utilities
11+
{
12+
internal sealed class PooledCTS : CancellationTokenSource
13+
{
14+
private static readonly ConcurrentQueue<PooledCTS> _sharedSources = new();
15+
16+
private static readonly Action<object?> _linkedTokenCancelDelegate = static s =>
17+
{
18+
((CancellationTokenSource)s!).Cancel(throwOnFirstException: false);
19+
};
20+
21+
private CancellationTokenRegistration _registration;
22+
23+
public static PooledCTS Rent(TimeSpan timeout, CancellationToken linkedToken)
24+
{
25+
if (!_sharedSources.TryDequeue(out var cts))
26+
{
27+
cts = new PooledCTS();
28+
}
29+
30+
cts._registration = linkedToken.UnsafeRegister(_linkedTokenCancelDelegate, cts);
31+
32+
cts.CancelAfter(timeout);
33+
34+
return cts;
35+
}
36+
37+
public void Return()
38+
{
39+
_registration.Dispose();
40+
_registration = default;
41+
42+
// TODO: Replace CancelAfter(Timeout.Infinite) & IsCancellationRequested with TryReset in 6.0+
43+
44+
CancelAfter(Timeout.Infinite);
45+
46+
if (IsCancellationRequested)
47+
{
48+
Dispose();
49+
}
50+
else
51+
{
52+
_sharedSources.Enqueue(this);
53+
}
54+
}
55+
}
56+
}

src/ReverseProxy/Utilities/TimeoutCtsPool.cs

Lines changed: 0 additions & 243 deletions
This file was deleted.

0 commit comments

Comments
 (0)