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]>
Currently, HttpClient throws the same TaskCancellationException regardless of the request cancellation reason that can be caller's cancellation, all pending request cancellation or timeout. This makes it impossible to handle a request timeout in a way different from all other cases (e.g. special retry logic).
This PR adds a timeout detection logic into HttpClient. It watches for all TaskCancelledExceptions and catches the one caused by timeout. Then, it creates two new exceptions and build a hierarchy. The first is a TimeoutException having its InnerException set to the original TaskCancelledException. The second is a new TaskCancelledException having its InnerException set to that new TimeoutException, but preserving the original stack trace, message and cancellation token. Finally, this top-level TaskCancelledException gets thrown.
Fixes#21965
Fix: QuicStream now throws OperationCanceledException with a set CancellationToken.
Fix: QPackDecoder detects 0-length header name and throws.
Fix: Http3RequestStream.ReadResponseContent incorrectly slicing user buffer.
Fix: Http3RequestStream.ReadResponseContent not detecting early EOF.
Fix: Http3LoopbackServer adding :status header to end of headers rather than beginning.
Optimization: don't parse Alt-Svc header if HTTP/3 is disabled.
* Avoid forcing ExpectContinue / TransferEncodingChunked headers into existence
* Reduce cookie-related allocations
- Make CookieParser/CookieTokenizer into structs. CookieParser is just created as a helper with some state to help a loop do parsing; it's not passed around in any way. And CookieTokenizer is just the implementation of CookieParser separated out for some reason. They can both be structs.
- Remove enumerator allocations related to cookies. Also reduces interface method invocations.
* Remove often-unnecessary allocation in Uri.IdnHost
This is happening for every request. But if the host is already all ASCII, we don't need to create a new string, and if it's already all lowercase, we don't need to create yet another new string. (This logic could stand to be cleaned up further; I just removed the allocations and some unnecessarily complex unsafe code along the way.)
* Combine ReadAtLeastAsync into EnsureIncomingBytesAsync
There's no need for them to be separate, and separating them leads to an extra async stack frame / state machine.
* Reduce calls to ReadFrameAsync that need to yield
Many frames either won't have a payload, or the act of waiting for the header will also end up waiting for the payload (in the same packet). By pulling out the wait in the hot path, we significantly reduce the number of times ReadFrameAsync will need to yield.
* Override Http2ReadStream.CopyToAsync
Reduces allocation / improves throughput when using responseStream.CopyToAsync.
* Shrink EnsureIncomingBytesAsync state machine by 8 bytes
Remove two lifted Int32s.
* Shrink size of Http2Connection.SendAsync state machine
The order of a comparison operation is, based on C# required order of operations, forcing a temporary to be spilled and lifted to the state machine.
* Add additional values to known headers
Avoids string allocations when these common response values are used.
* Remove dead Uri code
Update generic tests to use a Version rather than boolean IsHttp11/IsHttp20, and update some HTTP/2 to work for HTTP/3.
Enable tests for HTTP/3, behind a conditional feature test.
Fix QPackDecoder lzcnt assuming an 8-bit test.
Rename test QPACK classes from QPackEncoder/QPackDecoder -> QPackTestEncoder/QPackTestDecoder to avoid naming confusion with product code classes.
Fix QPackTestDecoder bit flag checks.
Fix a double call to QuicConnection.CloseAsync(). Update to shutdown QuicConnection in a background task.
Fix test cert usage.
- Optimize ToUpperInvariant/ToLowerInvariant
- Also optimize static field TextInfo.Invariant
- Rewrite ToUpper/Lower(Invariant) call sites to use optimized method
- Fix some uses of culture-aware ToUpper / ToLower to use invariant culture
- Replace Trim().Length with IsNullOrWhiteSpace where appropriate
- Use ordinal StartsWith / EndsWith where appropriate
- Avoid calling CultureInfo.InvariantCulture where possible
* Add Process.WaitForExitAsync() and associated unit tests
Add a task-based `WaitForExitAsync()` for the `Process` class, and
duplicate existing `WaitForExit()` tests to add async versions.
In order to ensure that the `Exited` event is never lost, it is the
callers responsibility to ensure that `EnableRaisingEvents` is `true`
_prior_ to calling `WaitForExitAsync()`. A new
`InvalidOperationException` is introduced to enforce those semantics.
* Review feedback: Change WaitForExitAsync to return Task
Per review feedback, change `WaitForExitAsync` to return a `Task`
instead of `Task<bool>`. Now, to determine if the process has exited,
callers should check `HasExited` after the await, and cancellation
follows the async pattern of setting canceled on the task.
* Remove asserts on Task properties
Per code review feedback, remove the asserts that verify that the Task
returned by WaitForExitAsync is completed successfully / canceled, as
they're essentially Task tests and not relevant to WaitForExitAsync.
* Fix unit test to not create async void
Per code review feedback, fix the
MultipleProcesses_ParallelStartKillWaitAsync test to make work a
`Func<Task>` instead of an `Action` since we're await-ing it.
* Remove implicit delegate creation for ExitHandler
Per code review feedback, converting ExitHandler from a local function
to an `EventHandler` to avoid the extra delegate allocation to convert
between the types.
* Flow CancellationToken to OperationCanceledExceptions
Per code review, register the `TaskCompletionSource` with the
`CancellationToken` so that if an `OperationCanceledException` is thrown
the relevant token is available on
`OperationCanceledException.CancellationToken`.
To accomplish that the `TaskCompletionSourceWithCancellation` class
that's internal to `System.Net.Http` is moved to Common and consumed in
both places.
Unit tests are also updated to verify that the cancellation token passed
in is the same one returned from
`OperationCanceledException.CancellationToken`.
* Do not require EnableRaisingEvents to already be true
Per code review feedback, update `WaitForExitAsync` to not require the
user to call `EnableRaisingEvents` first.
Setting `EnableRaisingEvents` ourselves introduces the chance for an
exception in the case where the process has already exited, so I've
added a comment to the top of the method to detail the possible paths
through the code and added comment annotations for each case.
Lastly, I updated the unit tests to remove `EnableRaisingEvents` calls.
* Follow style guidelines in ProcessWaitingTests
Per code review feedback, update the new unit tests in
ProcessWaitingTests to follow style guidelines.
* Update tests to follow coding guidelines
Per code review feedback, update tests to follow coding guidelines,
simplify creating cancellation tokens, and verify synchronous completion
of tasks in the exited / canceled case.
* Update WaitForExitAsync to early out in canceled case
Per code review feedback, add an early out for a non-exited process when
canceled.
* Add a test for completion without a cancellation token
Per code review feedback, add a test for a process that completes
normally and doesn't use a canellation token.
* Address PR feedback in xmldocs
Per code review feedback, update the xmldocs for `WaitForExitAsync` to
specify the language keyword for "true", and add a `<returns>` element.
* Update xmldocs per code review feedback
Per code review feedback, update xmldocs to list other conditions that
can cause the function to return.
* Update function guards per code review feedback
Per code review feedback, update the method guards to span multiple
lines to adhere to style guidelines.
* Refactor test to verify async as well as sync cancellation
Per code review feedback, update
SingleProcess_TryWaitAsyncMultipleTimesBeforeCompleting to test both the
case where the token is canceled before creating the Task as well as
after the task is already created.