* Rearrange Http2Connection.SendHeadersAsync to increase scale
Many concurrent streams are currently bottlenecking in SendHeadersAsync. They:
- take the headers serialization lock
- request a stream credit
- serialize all their headers to a buffer stored on the connection
- take the write lock
- write out the headers
- release the write lock
- release the headers serialization lock
Instead of using a header buffer pooled on the connection, we can instead temporarily grab ArrayPool buffers into which we serialize the headers, which allows us to eliminate the headers serialization lock. With that, we get:
- request a stream credit
- serialize the headers to a pooled buffer
- take the write lock
- write out the headers
- release the write lock
This has a significant impact on the ability for many concurrent streams to scale, as all of the header serialization work happens outside of the lock.
* Use ContinueWith instead of async/await in Ignore/LogExceptions
The current implementation will always invoke the continuation, even in the majority case where there's no failure (and if there is a failure, it's cheaper not to throw it again). We can avoid that and decrease both overhead and allocation in the common case.
* Remove CopyToAsync wrapping task from SendRequestBodyAsync
* Reduce contention on semaphore locks
We're seeing a lot of contention trying to acquire the monitors inside of semaphore slims, even when the contention is to release the semaphore, which should entail minimal contention (and delay of a release will just cause more contention). We can use a small interlocked gate to add a fast path.
* Stop clearing ArrayBuffer's pooled byte arrays
We already weren't clearing as the array grew, nor are we clearing in most other places in the library. It's not clear why we were clearing in this one spot, but the zero'ing is showing up meaningfully in profiles.
* Add several gRPC known headers
* Avoid dictionary lookup in HttpMethod.Normalize
* Avoid allocating strings for known Content-Types
* Combine AcquireWriteLockAsync into StartWriteAsync
There's not a good reason to keep them separate, and StartWriteAsync is AcquireWriteLockAsync's only caller.
* Remove GetCancelableWaiterTask async method
We can achieve the same thing without the extra async method by putting the cleanup logic into the awaiter's GetResult.
* Address PR feedback
There are a bunch of tests that don't make sense on HTTP/2, but end up executing because of how our tests are structured. As a result, the test itself checks whether HTTP/2 is applicable and bails if it isn't. Currently some of these are bailing by throwing a SkipTestException, which results in a message being output on the console. Such messages are meant for tests that can be run in some circumstances, e.g. a stress test that needs an environment variable set. They aren't needed when a test is never going to run.
I also marked the stress tests as outerloop so they don't spam the console when just running innerloop.
Http2_PendingSend_SendsReset test fails because client sends the second request with EndOfStream flag sooner than the server reads the last RstStream frame of the first request. This is caused by too short delay before the second request is made on the client. This PR replaces Task.Delay with a synchronization via TaskCompletionSource.
Fixes#2131
PR adds an optional stream termination handling to `Http2LoopbackConnection.ReadBodyAsync` and fixes `HttpClient` construction missing the `SocketHttpHandler` created in the test.
Fixes#31220
`_waitForCompletion` gets reset to null in `DuplexContent.Complete` and `Fail` which leads to race condition with `SerializeToStreamAsync`. This reset seems redundant since `_waitForCompletion` is always unconditionally initialized on each call to `SerializeToStreamAsync`. This PR removes that reset logic.
Fixes#33141
Constructing a ByteArrayContent (or anything that derives from it, like StringContent) or a ReadOnlyMemoryContent proactively allocates a MemoryStream that it stores as the _bufferedContent on the base HttpContent. But the 99.99% use case for ByteArrayContent is as a request payload, and this _bufferedContent isn't used for that. The only time this would be used is if a developer created a ByteArrayContent and then explicitly got the stream from it, e.g. via GetStreamAsync, in which case we're no worse off by doing the creation lazily. This PR just deletes the unnecessary code / allocation.
* Update HttpClientMiniStressTest.cs
Currently, it's possible for 4 different instances of SingleClient_ManyGets_Sync to run in parallel, each using up to 2 x 5000 sockets, totaling in 40,000 sockets. way beyond the original intent of testing 5000 client instances. since this additional stress is random in nature, I believe it is not intentional.
This change make sure that those tests will not run in parallel, this avoids some issues I've encountered in some systems.
* HttpClientMiniStressTest: Disable Parallelism: Used CollectionAttribute on the base class
The current implementation of `ObjectCollection<T>` wraps a `List<T>` and derives from `Collection<T>`. This means that every `ObjectCollection<T>` allocated also involves an extra `List<T>` object (and its array if items are added to it) as well as multiple levels of indirection on each operation.
We can instead just implement `ObjectCollection<T>` directly. Since most uses end up with just a single object contained (e.g. for a `MedaTypeHeaderValue`'s `CharSet`), and since it only ever stores `T`s that are non-null classes, we can use the items field to be either a `T` or a `T[]`, optimizing for the case where a single element is stored. In implementing it directly, we then also avoid the extra `List<T>` object allocation, as well as the interface dispatch that results from going through the `IList<T>` interface.
* Optimize HttpDateParser.TryStringToDate
When HttpResponseMessage headers are enumerated, even though SocketsHttpHandler adds headers with TryAddWithoutValidation, the enumeration ends up validating them (that's something to be discussed and follow-up on separately). As part of that, it validates the Date header that's required of most responses. It does so using DateTimeOffset.TryParseExact, but using a long list of allowed formats as well as options that knock TryParseExact's processing off the fast path. Since most responses are going to contain a date using RFC1123 format (aka "r"), we just try that first, in a way that will generally result in hitting the optimized "r" code path which is much faster.
* Address PR feedback
* Remove state machine allocation for SendWithNtConnectionAuthAsync
Just manually inline the tiny helper that's only used from one call site.
* Remove unnecessary HeaderStoreItemInfo allocations
For the common case of a raw string, let the dictionary store the raw string directly rather than always wrapping it in a HeaderStoreItemInfo.
* Cache Date and Server response header values
For Server, we expect it to be the same for every request on the same connection.
For Date, if we're making lots of requests in a high-throughput fashion, we expect many responses on the same connection to have the same value.
In both cases, we compare the received value against the last one received, and if it's the same, reuse the same string.
* Feed cleanup
Move away from blob feeds.
* Add dotnet5 feed
* Update version of System.CommandLine.Experimental
* Revert to released versions in SuperILC and R2RDump
* Don't remove public feeds for tests
- Use RestoreUseStaticGraphEvaluation which improves no-op restore by 10-15x down to 10-20 seconds.
- .builds msbuild files renamed to .proj as RestoreUseStaticGraphEvaluation throws for non .proj files without an env var set.
- Introducing subsets for libraries and mono and replacing -buildtests switch which was only working for libraries in favor of the subset switch -subset tests which works consistently.
- Fixing the Microsoft.DotNet.CodeAnalysis analyzer which wasn't running and adding missing exclusions.
- Separating restore and build phases in different parts in the repo (ie for installer.tasks) as generated props and targets need to be imported which requires a reevaluation in the build phase.
- Fix eng/docker/build-docker-sdk.ps1 by using the official build entrypoints (cc @alnikola)
- Remove a few depprojs in favor of project restore (faster restore :))
- Fix root code coverage measurement not working correctly
- Traversal support instead of dir.traversal.targets or manual build target defines.
- Introduce a root Build.proj entrypoint which is responsible for building and restoring the repository. This is necessary to enable the new NuGet fast restore which works best and fastest with a single entrypoint.
- Avoid binclashes in libraries and between libraries and installer (netstandard.depproj vs netstandard.csproj)
- Upgrading the SDK to 5.0 latest
- Code cleanup
Currently, it's possible to run stress tests on privately built CoreCLR and libraries by executing load-corefx-testhost.ps1 -b followed by run-docker-compose.ps1 -b. However, it was not possible to run the stress server on a private Asp.Net Core package which is used for private libraries build.
This PR adds a new -pa parameter to run-docker-compose.ps1 which builds a server container with a private Asp.Net Core package version.
* Enable restore for projects in libraries
Enabling project restore for ref and src projects
* Remove winrt.depproj
* Remove tools.depproj
* Enable upfront restore
* Fix casing of PInvokeAnalyzerException file
* Remove harvestPackages.depproj and refactoring
Removing havestPackages.depproj in favor of a target that is hooked
into Arcade's repo restore phase in Tools.props.
Additionally moving common properties that are used both in Arcade and
the repo inside Configurations.props. Before they were scattered around
multiple places (Versions.props, Subsets.props).
* Set ilasm/ildasm RID for restore
* Sequence restore into steps out of upfront restore
* Fix docker entrypoints by using build.cmd/sh
The response Stream returned from SocketsHttpHandler.SendAsync supports all of the various forms of read operations, including synchronous reads.
For HTTP/1.x, we're able to implement these as sync all the way down to synchronous calls on the underlying Socket, as every request/response owns its own connection (at least for the duration of the operation; the connection may be returned to the pool for subsequent reuse after).
For HTTP/2, however, a single connection is shared across all requests multiplexed onto it, and as such, reads on those individual responses need to coordinate, which can mean waiting one's turn. Such waiting for asynchronous operations is implemented via async/await and a ManualResetValueTaskSource-based implementation. For the sync operations, though, they're implemented as simply blocking waiting on the async equivalent, aka sync-over-async. This not only blocks the calling thread, but because the MRVTS-based implementation specifies RunContinuationsAsynchronously==true (which is important for reliability with how the async code paths are structured) it means that, in order to unblock this waiter, another thread pool thread needs to be available to run the small continuation that will in turn unblock the sync primitive being blocked on.
This PR tweaks the use of MRVTS so that when we perform a synchronous read, we set MRVTS.RunContinuationsAsynchronously to false. Since the only action that will be taken as part of the continuation is to set a sync primitive, we don't need to worry about arbitrary code running as part of the completing call stack. This in turn means that in the common case, sync reads will still end up blocking the calling thread _but_ won't require an additional thread pool thread to unblock it, other than for the task running the main connection loop.
Stress test build fails because we have a plural tag <TargetFrameworks>, but only one nested element. PR converts it to a singular <TargetFramework>.
Fixes#32813
Adds HttpRequestException.StatusCode property, to be set by EnsureSuccessStatusCode and convenience methods when an exception is generated by a status code.
The CreditManager implementation supports multiple awaiters, but Http2Stream's CreditManager never has more than one waiter at a time. We can instead just encode similar logic into Http2Stream, and make its waiter a reusable singleton, such that if we have to allocate it, we can just keep reusing it for all subsequent waits. This means we avoid the CreditManager allocation per Http2Stream as well as the Waiter allocation per wait (other than the first).
Fix: leaking NetworkAddressChangedEventHandler and related WeakReference if user does not Dispose HttpClient. Resolves#32526.
Fix: using HttpClient from within a suppressed execution context. Add test for this. Resolves#32524.
Fix: capturing excessive execution context in Alt-Svc expiration timer.
Optimization: do not monitor for network changes until a non-persistent Alt-Svc is used.
* Remove cancellation-related allocations in Http2Stream
We don't need to allocate a linked token source in SendRequestBodyAsync if the caller's token is the default
* Reduce size of SendDataAsync state machine
We're carrying around an extra 24-bytes for a `ReadOnlyMemory<byte>`, when we could instead just use the argument.
* Tweak HeaderField's ctor to use ROS.ToArray
If `value` happens to be empty, this will avoid an allocation. But what actually led me to do this was just tightening up the code.
* Make HPackDecoder.State enum 1 instead of 4 bytes
* Remove spilled CancellationTokenSource field from SendDataAsync
* Add known-header values for access-control-* headers
* Reduce allocation in SslStream.ReadAsync
The current structure is that ReadAsync makes two calls to FillBufferAsync, one to ensure the frame header is read and another to ensure any additional payload is read. This has two issues:
1. It ensures that in addition to allocating a state machine for FillBufferAsync (or, rather, a helper it uses) when it needs to yield, it'll also end up allocating for ReadAsync.
2. It complicates error handling, which needs to differentiate whether the first read can't get any bytes or whether a subsequent read can't, which necessitates storing state like how many bytes we initially had buffered so we can compare to that to see if we need to throw.
We can instead:
- Make FillBufferAsync into a simple "read until we get the requested number of bytes" loop and throw if it fails to do so.
- Do the initial read in ReadAsync, thereby allowing us to special-case the first read for both error handling and to minimize the chances that the helper call needs to yield.
This eliminates a bunch of FillBufferAsync state machines and also decreases the size of the state machines when they are needed.
* Replace CreditManager's waiter queue with a circular singly-linked list
This has a variety of benefits:
- We no longer need to allocate a `Queue<Waiter>` and its underlying `Waiter[]`.
- We no longer need to allocate a `TaskCompletionSource<int>` and its `Task<int>`, instead creating a single `IValueTaskSource<T>` implementation.
- For non-cancelable waiters, we can specialize to not need to carry around a meaningless CancellationToken field.
- For cancelable waiters (the common case), we can avoid an entire async method and its state machine by just storing the relevant state onto the waiter itself.
* Fix comment from previous change
* Manually inline and specialize EnsureIncomingBytesAsync
It's not that much more code to just manually inline EnsureIncomingBytesAsync into the three places it's used, and doing so has multiple benefits, both for size and for error messages.
* Update src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http2Connection.cs
Co-Authored-By: Cory Nelson <[email protected]>
* Fix typo in online feedback
Co-authored-by: Cory Nelson <[email protected]>