Skip to content
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

Add HttpClient.Shared #84327

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/libraries/System.Net.Http/ref/System.Net.Http.cs
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ protected override void Dispose(bool disposing) { }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Net.Http.HttpCompletionOption completionOption) { throw null; }
public System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Net.Http.HttpCompletionOption completionOption, System.Threading.CancellationToken cancellationToken) { throw null; }
public override System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> SendAsync(System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { throw null; }
public static System.Net.Http.HttpClient Shared { get { throw null; } }
}
public partial class HttpClientHandler : System.Net.Http.HttpMessageHandler
{
Expand Down
2 changes: 1 addition & 1 deletion src/libraries/System.Net.Http/src/Resources/SR.resx
Original file line number Diff line number Diff line change
Expand Up @@ -156,4 +156,4 @@
<data name="net_http_request_invalid_char_encoding" xml:space="preserve">
<value>Request headers must contain only ASCII characters.</value>
</data>
</root>
</root>
3 changes: 3 additions & 0 deletions src/libraries/System.Net.Http/src/Resources/Strings.resx
Original file line number Diff line number Diff line change
Expand Up @@ -579,4 +579,7 @@
<data name="net_unsupported_extended_connect" xml:space="preserve">
<value>Failed to establish web socket connection over HTTP/2 because extended CONNECT is not supported. Try to downgrade the request version to HTTP/1.1.</value>
</data>
<data name="net_http_shared_httpclient_notsupported" xml:space="preserve">
<value>This operation is not supported on the instance available from HttpClient.Shared.</value>
</data>
</root>
61 changes: 52 additions & 9 deletions src/libraries/System.Net.Http/src/System/Net/Http/HttpClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,15 @@ public partial class HttpClient : HttpMessageInvoker
#region Fields

private static IWebProxy? s_defaultProxy;
private static HttpClient? s_shared;
private static readonly TimeSpan s_defaultTimeout = TimeSpan.FromSeconds(100);
private static readonly TimeSpan s_maxTimeout = TimeSpan.FromMilliseconds(int.MaxValue);
private static readonly TimeSpan s_infiniteTimeout = Threading.Timeout.InfiniteTimeSpan;
private const HttpCompletionOption DefaultCompletionOption = HttpCompletionOption.ResponseContentRead;

private volatile bool _operationStarted;
private volatile bool _disposed;
private bool _isSharedInstance;

private CancellationTokenSource _pendingRequestsCts;
private HttpRequestHeaders? _defaultRequestHeaders;
Expand All @@ -46,8 +48,41 @@ public static IWebProxy DefaultProxy
}
}

public HttpRequestHeaders DefaultRequestHeaders =>
_defaultRequestHeaders ??= new HttpRequestHeaders();
/// <summary>Gets an <see cref="HttpClient"/> instance configured with all of the default options.</summary>
public static HttpClient Shared
{
get
{
return s_shared ?? Initialize();

static HttpClient Initialize()
{
var shared = new HttpClient() { _isSharedInstance = true, _operationStarted = true };
if (Interlocked.CompareExchange(ref s_shared, shared, null) is not null)
{
shared._isSharedInstance = false;
shared.Dispose();
shared = s_shared;
}
return shared;
}
}
}

public HttpRequestHeaders DefaultRequestHeaders
{
get
{
if (_isSharedInstance)
{
// HttpRequestHeaders is not thread safe. Developers trying to mutate HttpClient.Shared.DefaultRequestHeaders
// could thus corrupt the instance if used from multiple threads.
throw new NotSupportedException(SR.net_http_shared_httpclient_notsupported);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This makes me feel better about this feature.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not a fan of getter's throwing, I'd rather return a read-only object that threw if you tried to modify it.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd rather return a read-only object that threw if you tried to modify it.

That would a) make HttpRequestHeaders slower for everyone and b) not really affect anything because it has getters that mutate (e.g. lazily instantiate) and they would then need to throw instead.

Copy link
Member

@antonfirsov antonfirsov Apr 5, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't we want to do the same in CancelPendingRequests(), and any other member that has a chance to mess with independent callers?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't we want to do the same in CancelPendingRequests(), and any other member that has a chance to mess with independent callers?

We could. CancelPendingRequests is "safe" to use concurrently, whereas DefaultRequestHeaders is not, hence why I gave the latter this treatment.

}

return _defaultRequestHeaders ??= new HttpRequestHeaders();
}
}

public Version DefaultRequestVersion
{
Expand Down Expand Up @@ -699,15 +734,23 @@ public void CancelPendingRequests()

protected override void Dispose(bool disposing)
{
if (disposing && !_disposed)
if (disposing)
{
_disposed = true;
if (_isSharedInstance)
{
return;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As we're not disposing the client, we might see more issues with H/3 similar to this: #71927
The problem is that without Dispose, msquic might not send the last frames before exiting the app, causing problems on the other side, e.g. missing ACKs causing hangs.

}

// Cancel all pending requests (if any). Note that we don't call CancelPendingRequests() but cancel
// the CTS directly. The reason is that CancelPendingRequests() would cancel the current CTS and create
// a new CTS. We don't want a new CTS in this case.
_pendingRequestsCts.Cancel();
_pendingRequestsCts.Dispose();
if (!_disposed)
{
_disposed = true;

// Cancel all pending requests (if any). Note that we don't call CancelPendingRequests() but cancel
// the CTS directly. The reason is that CancelPendingRequests() would cancel the current CTS and create
// a new CTS. We don't want a new CTS in this case.
_pendingRequestsCts.Cancel();
_pendingRequestsCts.Dispose();
}
}

base.Dispose(disposing);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1377,6 +1377,53 @@ public async Task DefaultRequestVersion_UsedInCreatedMessages()
}
}

[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
public void Shared_NonNull_Idempotent()
{
RemoteExecutor.Invoke(() =>
{
HttpClient client = HttpClient.Shared;
Assert.NotNull(client);
Assert.Same(client, HttpClient.Shared);
}).Dispose();
}

[Fact]
public void Shared_PropertiesConfiguredWithDefaults()
{
Assert.Null(HttpClient.Shared.BaseAddress);
Assert.Equal(HttpVersion.Version11, HttpClient.Shared.DefaultRequestVersion);
Assert.Equal(HttpVersionPolicy.RequestVersionOrLower, HttpClient.Shared.DefaultVersionPolicy);
Assert.Equal(int.MaxValue, HttpClient.Shared.MaxResponseContentBufferSize);
Assert.Equal(TimeSpan.FromSeconds(100), HttpClient.Shared.Timeout);

Assert.Throws<NotSupportedException>(() => HttpClient.Shared.DefaultRequestHeaders);

Assert.Throws<InvalidOperationException>(() => HttpClient.Shared.BaseAddress = null);
Assert.Throws<InvalidOperationException>(() => HttpClient.Shared.DefaultRequestVersion = HttpVersion.Version11);
Assert.Throws<InvalidOperationException>(() => HttpClient.Shared.DefaultVersionPolicy = HttpVersionPolicy.RequestVersionOrLower);
Assert.Throws<InvalidOperationException>(() => HttpClient.Shared.MaxResponseContentBufferSize = int.MaxValue);
Assert.Throws<InvalidOperationException>(() => HttpClient.Shared.Timeout = TimeSpan.FromSeconds(100));
}

[Fact]
public async Task Shared_SimpleRequestsSucceed()
{
for (int i = 0; i < 3; i++)
{
const string Content = "hello shared";
await LoopbackServerFactory.CreateClientAndServerAsync(
async uri =>
{
using (HttpClient client = HttpClient.Shared)
{
Assert.Equal(Content, await client.GetStringAsync(uri));
}
},
async server => await server.AcceptConnectionSendResponseAndCloseAsync(content: Content));
}
}

private sealed class StoreMessageHttpMessageInvoker : HttpMessageHandler
{
public HttpRequestMessage Message;
Expand Down