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.
* libraries -restore for vertical build without test restore
* Automatic test change and regex to remove the addition of an extra line at eof
* manual test restore fixed (restore completely done for vertical build)
* build native done
* Automatic ref change and regex to remove the last line
* manual reference assebly change and generated shims build
* automatic src change and regex
* native bin place and src build manual change
* apicompat and pretest.csproj done
* fixing the package build
* fixing all config
* packaging and feedback
* adding back placeholder configuration
* fixing the shims
* delete configuration.props
* making the build work in master
* Test Change
* fixing the packageing, test restore replacing TargetFramework -> OriginalTargetFramework
* delete test configuraiton.props, trailing semicolon and use targetFramework
* reverting the package change
* enable apicompat and fixing configurationGroup for individual projects
* fixing the api compat
* making ilproj work
* adding the outerBuildTest
* adding the arcade package version
* fixing the merge conflicts
* minor changes
* adding additional configs and setting the runtimeOS
* making the vs stuff work
* removing the target Group to fix the apicompat
* fixing the linux build and some minor changes
* making additionalBuildTargetFramework LOcalProperty
* fixing the allConfigurations build
* fixing the netfx build
* fixing package Testing and restore
* Missing TargetFrameworks tag
* making the VSdesgin stuff work
* Remove OriginalFramework Entirely
* some minor pr feedback
* RemoveExtraSemicolon
* use boolean exclude flag
* fixing yml scripts to pass tests
* adding comments and some minor feedback
* moving packaging property to correct plave
* fixing the build for web assembly
* Fixing the live ci build
* Fixing the live build for shims
* fixing the tests
* fixing the packaging and enterprise linux
* fixing package sizes
* Fix the targetFramework
* updating the targetFramework sdl
* removing the buildOS and be able to use OSGroup as done in the old system
* Fixing the osgroup stuff for send to helix task
* Fix OSX failures
* Fixing the osx build
* uploading tmp folder to artifacts
* running restore for runtime.deproj correctly
System.Net.Http stress test infra can build test containers from a local runtime build, however it currently fails on startup due to missing SDKs. This PR adds script which can be run before running the main run-docker-compose.ps1 to copy SDKs to testhost folder, so container building logic can find them.
- In some cases, I deleted ActiveIssues associated with issues where the problem was supposedly fixed. We'll see.
- In some cases, I deleted test cases entirely, e.g. where the corresponding issue said effectively "we'll live with the behavior" or "another repo is responsible for this now" (paraphrasing), or where the tests were initially added to the repo years ago already disabled and against bug numbers from some old bug database.
- In some cases, I replaced the link with the correct one.
- In some cases, I re-opened closed issues.
The tests used by PlatformHandlerTest moved to Common/tests in order to share them between System.Net.Http and System.Net.Http.WinHttpHandler.
The added conditions correspond to the state before WinHttpHandler removal. They're just based on IsWinHttpHandler instead of UseSocketHandler.
Some of the code must be conditionally compiled since there is no usable common base class for HttpClientHandler and WinHttpHandler. Other issues solved by introducing WinHttpClientHandler for testing purposes. It corresponds to HttpClientHandler.Windows.cs code from before its removal.
* Address more issue numbers in the code
Replaced a bunch of unadorned issue numbers with links, so we know which repo the issue is for. In some cases the repo was named, but for consistency I still replaced it with a link.
In some cases, in particular where the issue had been closed saying effectively "we're not going to do anything here", I removed TODOs and the associated issue numbers.
In a few cases, the TODO and issue number was to say "we should do X when Y is fixed", so I did X since Y was fixed.
* Apply suggestions from code review
Co-Authored-By: Jan Kotas <[email protected]>
* Address PR feedback
* Fix OrderedEnumerable by using MemoryExtensions.Sort
Co-authored-by: Jan Kotas <[email protected]>
* Implement HttpContent and HttpClient cancellation APIs
Implements APIs approved in dotnet/corefx#32615 and dotnet/runtime#576
* Use new CreateContentReadStreamAsync overload in MultipartContent
* Expose HttpContent.SerializeToStreamAsync overload with cancellation
* Remove HTTP_DLL preprocessor directives
* Rename WIN_HTTP_HANDLER to WINHTTPHANDLER_DLL
* Use more 'var' where type is obvious
Currently, some of the known headers disallowed in the message trailer are marked with HttpHeaderType.NonTrailing flag. However, there are others identified as disallowed by the related RFC missing this flag.
Fixesdotnet/corefx#42474
* netcoreapp -> netcoreapp5.0 in .sln files
* netcoreapp; -> netcoreapp5.0; , netcoreapp- to netcoreapp5.0-
* netcoreapp- -> netcoreapp5.0 in .csproj
* 'netcoreapp -> 'netcoreapp5.0 in .csproj
* done with libraries sub folder
* missed semicolon
* minor changes
* netcoreapp -> netcoreapp5.0 in some extra files
* vNext target variable in configurations.props
* netcoreapp => netcoreapp5/0 in some other .props file
* netcoreapp -> vnext in .csproj
* making the netcorepap framework switch work
* fixing sendToHelix and linux build
* TargetFrameworkVNext -> netcoreappCurrent
* case correct netcoreappcurrent
* fixing send to helix zip path
* netfx -> net472 in .sln
* netfx; -> net472; in .props
* netfx- -> net472- in .props
* netfx - -> net472- in .csproj
* 'netfx-> 'net472 in .csproj
* netfx -> net472 manual change
* fixing ci build for netfx
* Not trying to change the global property
* Fixing build failure due to master changes in net https tests
* adding documentaiton and fixing filtering
* netcoreapp -> netcore5.0 in py file
* changing the path to use netcoreapp5.0 version
* feedback and override corefx path corrected in installers
* remaing netcoreapp5.0 changes done
* netcoreapp-> netcoreapp5.0 after live builds
* net472 -> netframeworkcurrent
On retrieving a connection from a pool, HttpConnectionPoolManager adds the current user identity to the HttpConnectionKey for direct and proxy connections when the default credentials is used on Windows platform. Since on Unix there is not the concept of a user identity on the thread, the identity component in the key is always set to string.Empty.
Fixesdotnet/corefx#39621
This is just prelminary, as all of the docs need to be rationalized with each other now that they're all in the same repo. But it at least keeps most of the links working for now.