Repository navigation
HTTP2: Rework shutdown handling - #39638
Conversation
| waiter.TrySetException(abortException != null ? (Exception) | ||
| new IOException(SR.net_http_request_aborted, abortException) : | ||
| CreateObjectDisposedException(forActiveWaiter: true)); | ||
| waiter.TrySetException(CreateObjectDisposedException(forActiveWaiter: true)); |
There was a problem hiding this comment.
I've not yet read most of the PR yet, but... is this revert a mistake, or is it no longer needed because we now expect there never to be a waiter present when a CreditManager is disposed? If the latter, seems there should be a Debug.Fail inside the waiters != null block.
There was a problem hiding this comment.
We now expect there never to be a waiter present.
Re Debug.Fail, where do you want this?
There was a problem hiding this comment.
Re Debug.Fail, where do you want this?
As the first line inside if (_waiters != null) block.
There was a problem hiding this comment.
Ah, yeah. Sure, I can make that change.
| if (NetEventSource.IsEnabled) Trace($"{nameof(ProcessIncomingFramesAsync)}: {e.Message}"); | ||
|
|
||
| if (!_disposed) | ||
| if (_abortException == null) |
There was a problem hiding this comment.
Why not just always call Abort and let its logic figure out what to do?
There was a problem hiding this comment.
Seems reasonable. I will make the change and see what happens.
The main point of the change here is to not skip this just because _disposed is set; this could mean we don't abort streams properly -- see my comment on _disposed at the top of the file.
FWIW, there's some weirdness here in that if the connection fails, we could end up throwing in both the read path and the write path, and racing to determine which exception is actually stored. That seems bad; better to have consistent behavior here. We should always fail in the read path, because we are constantly reading from the connection. We could also fail a write, and if that happens, that's when the race occurs. I thought about changing this so that we only actually abort when the read fails, but then what do we do if a write fails? Just keep trying to write and assume that the read will fail too, causing an abort? Seems a bit odd. Thoughts?
There was a problem hiding this comment.
Not really related, but anyway: We're also going to throw here when the server shuts down the connection and we receive EOF. We throw some exception about "expected 9 bytes to read" (frame header size). This is slightly annoying for two reasons: One is, we should avoid throwing in non-error situations, which this could be, if it the server has previously sent a GOAWAY and we've finished processing all streams. Two is, the actual exception text is not super helpful. Possibly we should make some changes here. We do need to still go through the abort path in this case because we need to abort any requests that the server didn't complete. Thoughts?
There was a problem hiding this comment.
we could end up throwing in both the read path and the write path, and racing to determine which exception is actually stored.
I think it's ok, or at least that the alternatives are worse. But this is why we have _abortException, user an interlocked to set it, and when it's set propagate it, in order to try to always surface the same exception, even when there's a race.
There was a problem hiding this comment.
One is, we should avoid throwing in non-error situations, which this could be, if it the server has previously sent a GOAWAY and we've finished processing all streams.
Doesn't seem particularly hard. We could just TryReadFrame or whatever, and then if it was false and there were active streams, we could abort them with a better exception.
| { | ||
| http2Stream.OnAbort(new Http2StreamException(protocolError)); | ||
| http2Stream.OnReset(new Http2StreamException(protocolError)); | ||
| } |
There was a problem hiding this comment.
How about just:
http2Stream.OnReset(
new Http2StreamException(protocolError),
canRetry: protocolError == Http2ProtocolErrorCode.RefusedStream);?
|
|
||
| // On cancel, we get TaskCanceledException here instead of OperationCanceledException. | ||
| // For consistency, try to ensure we get OperationCanceledException when the cancellationToken has fired. | ||
| cancellationToken.ThrowIfCancellationRequested(); |
There was a problem hiding this comment.
For consistency, try to ensure we get OperationCanceledException when the cancellationToken has fired.
We have a bunch of places that actually try to do the opposite.
I would remove this ThrowIfCancellationRequested. TCE derives from OCE; it's fine to let the former propagate.
There was a problem hiding this comment.
Ok, will do. I changed it because some test was explicitly checking for OCE; I'll fix the test.
| WriteHeaders(request); | ||
|
|
||
| Http2Stream http2Stream = AddStream(request); | ||
| int streamId = http2Stream.StreamId; |
There was a problem hiding this comment.
If something fails between here and the return, such as StartWriteAsync getting canceled, what removes the newly added stream?
There was a problem hiding this comment.
Yeah, there's a problem here. I changed this as I was changing all the RemoveStream stuff. But I think it ended up wrong.
I'm a little worried there are some error paths in this method that aren't handled properly. I'll go through it and try to ensure all cases are handled.
|
|
||
| lock (SyncObject) | ||
| { | ||
| if (NetEventSource.IsEnabled) Trace($"{nameof(abortException)}={abortException}"); |
There was a problem hiding this comment.
Should this be moved to the beginning of the method, prior to the InvalidateHttp2Connection call? I don't remember why we felt it was important to call it under the lock, but it seems misleading here for someone reading the trace.
| { | ||
| replacementException = new OperationCanceledException(oce.Message, oce, cancellationToken); | ||
| } | ||
| throw new HttpRequestException(SR.net_http_client_execution_error, e); |
There was a problem hiding this comment.
Why is it ok to remove the _abortException ?? here?
There was a problem hiding this comment.
Because the exception that propagates from failure above should be the correct exception to give to the user.
It's possible that there's some weird timing issues where (a) an exception happens above, and starts to propagate; (b) OnReset is called, and sets _resetException; (c) this causes the original exception to get overwritten. If the code above is failing for the same reason OnReset is being called -- i.e. connection failure or whatever -- then the same exception should get propagated both ways.
| } | ||
|
|
||
| // We run out of IDs or we have race condition between receiving GOAWAY and processing requests. | ||
| // We ran out of stream IDs or we raced condition between acquiring the connection from the pool and shutting down. |
There was a problem hiding this comment.
Nit: "or we raced condition"... strange phrasing
| // Stream can be removed from background ProcessIncomingFramesAsync() when endOfStream is set | ||
| // or when we hit various error conditions in SendAsync() call. | ||
| // Skip logic below if stream was already removed. | ||
| Debug.Assert(false, "Stream not found in dictionary during RemoveStream???"); |
There was a problem hiding this comment.
Nit: Debug.Assert(false, => Debug.Fail(
| _responseProtocolState = ResponseProtocolState.ExpectingStatus; | ||
|
|
||
| _disposed = false; | ||
| _request = request; |
There was a problem hiding this comment.
Nit: move this to be the very first line, so that the first three lines map to assigning the first three arguments to fields?
| { | ||
| using (Http2WriteStream writeStream = new Http2WriteStream(this)) | ||
| if (NetEventSource.IsEnabled) | ||
| Trace($"{_request.Content}"); |
| catch (Exception e) | ||
| { | ||
| if (NetEventSource.IsEnabled) Trace($"Failed to send request body: {e}"); | ||
| await _connection.SendEndStreamAsync(_streamId); |
| if (_requestBodyCancellationSource != null) | ||
| { | ||
| _requestBodyCancellationSource.Dispose(); | ||
| } |
There was a problem hiding this comment.
Nit: _requestBodyCancellationSource?.Dispose();
| { | ||
| var thisRef = (Http2Stream)s; | ||
| if (NetEventSource.IsEnabled) | ||
| thisRef.Trace($"100-Continue timer expired."); |
| } | ||
| else | ||
|
|
||
| if (NetEventSource.IsEnabled) Trace($"Stream complete."); |
There was a problem hiding this comment.
Nit:
if (NetEventSource.IsEnabled) Trace($"Stream complete. Request={_requestCompletionState}, Response={_responseCompletionState}.");?
| { | ||
| return; | ||
| } | ||
|
|
There was a problem hiding this comment.
Debug.Assert(_requestBodyCancellationSource != null);?
|
|
||
| if (endStream) | ||
| { | ||
| Debug.Assert(_responseCompletionState == StreamCompletionState.InProgress, $"Response already completed with state={_responseCompletionState}"); |
There was a problem hiding this comment.
Can we assert this safely? i.e. what if the server sent erroneous data... could it trigger this assert?
There was a problem hiding this comment.
When we process the first endStream, we should set _responseProtocolState (NOT _responseCompletionState) to Completed. Then any subsequent frames received should throw a protocol error when they check the state. So we shouldn't get here.
That said, some of the state logic around _responseProtocolState above and elsewhere is a little messy, so I can't say 100% we catch all of these. We have tests for this, but we could be missing something. I've tried not to mess with _responseProtocolState too much here because I didn't want to break anything here, but perhaps I should review all this and clean it up a bit.
| _waitSource.SetResult(true); | ||
| } | ||
| CancelRequestBody(); | ||
| CancelResponseBody(); |
There was a problem hiding this comment.
CancelResponseBody calls CancelRequestBody. Do we need both here?
There was a problem hiding this comment.
I've been thinking I may combine these into one routine anyway, just Cancel(). As you point out, CancelResponseBody calls CancelRequestBody anyway. And we only call CancelRequestBody without calling CancelResponseBody in cases where the response body is already completed (I think -- will verify), so in that case cancelling the response body is a no-op anyway. Will look at this further.
b2899ee to
29328b7
Compare
|
/azp run |
|
Azure Pipelines successfully started running 4 pipeline(s). |
| // We can't validate that we hold the semaphore, but we can at least validate that someone is holding it. | ||
| Debug.Assert(_writerLock.CurrentCount == 0); | ||
|
|
||
| EndWrite(false); |
There was a problem hiding this comment.
Nit: EndWrite(forceFlush: false);
| FrameFlags flags = | ||
| (remaining.Length == 0 ? FrameFlags.EndHeaders : FrameFlags.None) | | ||
| (request.Content == null ? FrameFlags.EndStream : FrameFlags.None); | ||
| // Client-initiated streams are always odd-numbered, so increase by 2. |
There was a problem hiding this comment.
Worth adding an assert that _nextStream is odd?
|
/azp run |
|
Azure Pipelines successfully started running 4 pipeline(s). |
|
Failures are unrelated |
Are you sure about this one? HTTP/1.1 has to do this in order to maintain the connection protocol (e.g. content-length many bytes MUST be sent or you have to close the connection). HTTP/2 is more flexible, it can reset the stream without disrupting the connection. Once you have a final non-success status code the request body is no longer needed. The server is likely to reset the stream anyways if the client keeps sending unwanted request data. |
|
@Tratcher I agree, it would be good to stop sending the request body in this case. We were trying to do this previously, but the logic wasn't correct in some cases. Given the 3.0 timeframe, and given how HTTP/1.1 works, it seems best to just match 1.1 behavior here. We can revisit in the future. |
|
Is this being included with 3.0? I downloaded the latest nightly SDK and gRPC functional tests are still broken. Is that because the nightly SDK doesn't include this PR yet or because it hasn't been applied to the 3.0 branch? |
|
It's not in the 3.0 branch yet. Should be in today. |
|
This is now in the 3.0 branch -- see PR #39775 |
|
@geoffkizer please link the PRs (ideally also all issues) in future, it is not clear which PR ported it to 3.0 :( |
|
@geoffkizer it seems one of the issues linked in top post is incorrect (I crossed it). Do you know which was the right number? |
|
It should be #39458, not #39548. |
|
Great, top post updated, thanks! |
|
This PR went into master - fixing milestone to 5.0. |
…fixes4 HTTP2: Rework shutdown handling Commit migrated from dotnet/corefx@ca3fe67
Fixes #39630
Fixes #39624
Incomplete attempt to fix #39586
Fixes #39461
Fixes #39460
Fixes #39458
Fixes #39459
Fixes #39404
Rework shutdown handling to be reliable and consistent, for both streams and connections.
Each Http2Stream has to complete both request and response before shutting down, at which time it will remove itself from the stream dictionary and clean up associated state.
The request body and response body can each be cancelled, and these are now cancelled at appropriate times (e.g. Dispose on response stream before reading to end).
The behavior of early non-success status codes is changed to not cancel the request body. This matches HTTP/1.1 behavior.
The connection is now shut down only when all streams are removed from the dictionary. Receiving EndStream or RST_STREAM does not automatically remove the stream; instead we let the stream manage its own shutdown and then remove it from the dictionary.
Add relevant tests, fix up some existing tests, and remove one bogus test.
I haven't run stress tests on this yet -- I wanted to get the review out first. Will report when I have stress results.
cc @stephentoub @dotnet/ncl