Skip to content

HTTP2: Support bidirectional content #1511

Open

Description

@Tratcher

Update & re-scoping of the issue

#1511 (comment)
Remaining work: We added an internal AllowDuplex property on HttpContent. We should consider making this public.

Old Update

As part of 3.0 we essentially disabled bidirectional HttpContent, implementing only what was needed for gRPC support. We now need to, as part of 5.0/Future, consider how to enable general-purpose bidirectional support.

Original issue

dotnet/corefx#36884 (HTTP/2 100 Continue) also snuck in bidirectional support (https://github.com/dotnet/corefx/issues/36855) for HTTP/2. This works pretty well but does introduce an ambiguous scenario when the server completes the response before the client completes the request.

Server code: (Kestrel 3.0.0-preview7)

                var response = "hello, world";
                context.Response.ContentLength = response.Length;
                await context.Response.WriteAsync(response);

                await context.Features.Get<IHttpResponseCompletionFeature>().CompleteAsync();
                await Task.Delay(TimeSpan.FromSeconds(5));
                // Drain the request body
                await context.Request.Body.CopyToAsync(Stream.Null);

Yes this server code is a bit unusual, it was written this way to make the error visible from CopyToAsync. You'll get similar behavior if you just write Hello World and let the request unwind.

Client code:

            var client = new HttpClient();
            client.DefaultRequestVersion = new Version(2, 0);
            using var file = File.OpenRead(@"A200MbFile.txt");
            var content = new StreamContent(file);
            var response = await client.PostAsync("https://localhost:5001", content);
  • In HTTP/1.x this works fine, PostAsync won't complete until the request stream has been completely uploaded.
  • In HTTP/2 it's ambiguous because when PostAsync completes you have a fully buffered response body but you have no idea what the state of the request is nor a way to be notified of its completion. Trying to perform any operations on that file can cause errors in the client code because it's still in use. If you close the file now the request will fail, but the error will only be visible on the server.
  • HttpCompletionOptions do not have any affect on the request, they only affect the response.
  • None of the built in HttpContent implementations provide any visibility on their progress. PushStreamContent from WebApi is the only HttpContent example I've seen that would surface this state to users.

Mitigations:

  • Servers usually wait for the request body to end before ending the response body. However the client can't always rely on the server behaving a specific way, ending the response early is within spec.
  • For >= 300 responses the HTTP/2 stream will be reset and the request stream abandon. These are the most common scenarios where the server would end the response without draining the request. This doesn't surface any errors directly to the caller unless they have a custom HttpContent, they have to infer the request body is done/abandon from the status code.

These mitigations make the issue occur infrequently enough that it will cause some very non-obvious issues when it it does happen (e.g. locked files, InvalidOperationExceptions, multi-threaded stream re-use, etc.).

Proposals:
A) At a minimum there needs to be guidance given that this might happen and how the user might handle it. I don't know what guidance could be given beyond implementing a custom HttpContent.
B) Add something to HttpContent to make progress more visible. E.g. something they could await or DisposeAsync that could wait for things to finish first. This wouldn't be very discoverable and would need to be accompanied by guidance.
C) Only enable bidirectional support when using HttpCompletionOptions.ResponseHeadersRead (or a new flag?). Most people don't use this flag so they wouldn't be impacted by the behavior change (e.g. PostAsync doesn't support that mode). I'm not sure how you implement this without B.

@wfurt @davidsh

Activity

  1. wfurt commented on Jun 14, 2019

    @wfurt
    Member

    The original implementation did C) but consensus through review was to do it al the time.

    cc: @stephentoub

  2. stephentoub commented on Jun 14, 2019

    @stephentoub
    Member

    How about:

    D) Don't let the response stream yield EOF until all request content has finished sending.

    Would that break anything? It'd also give us a place to propagate exceptions we're currently just logging.

  3. Tratcher commented on Jun 14, 2019

    @Tratcher
    MemberAuthor

    D is certainly simpler, and doesn't depend on any of the other proposals. It might break the gRPC scenario where they send an error status in the trailers. However they usually follow that with a Reset so that might unblock it anyways. @JamesNK ?

  4. JamesNK commented on Jun 14, 2019

    @JamesNK
    Member

    Don't let the response stream yield EOF

    What do you mean by this?

    I'll put together some gRPC streaming scenarios so we can judge if changes will break anything.

  5. JamesNK commented on Jun 14, 2019

    @JamesNK
    Member

    This is what gRPC's HttpContent looks like:

    internal class PushStreamContent : HttpContent
    {
        private readonly Func<Stream, Task> _onStreamAvailable;
    
        public PushStreamContent(Func<Stream, Task> onStreamAvailable, MediaTypeHeaderValue mediaType)
        {
            _onStreamAvailable = onStreamAvailable;
            Headers.ContentType = mediaType;
        }
    
        protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
        {
            return _onStreamAvailable(stream);
        }
    
        protected override bool TryComputeLength(out long length)
        {
            // We can't know the length of the content being pushed to the output stream.
            length = -1;
            return false;
        }
    
        // For unit tests. Hacky. ReadAsStreamAsync does not complete until SerializeToStreamAsync finishes
        internal Task PushComplete => ReadAsStreamAsync();
    }

    In a client or duplex streaming call gRPC will write to the stream until the client closes it (either explicitly, or by the response ending).

    _writeStreamTcs = new TaskCompletionSource<Stream>(TaskCreationOptions.RunContinuationsAsynchronously);
    _completeTcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
    
    message.Content = new PushStreamContent(
        (stream) =>
        {
            _writeStreamTcs.TrySetResult(stream);
            return _completeTcs.Task;
        },
        GrpcProtocolConstants.GrpcContentTypeHeaderValue);
  6. Tratcher commented on Jun 14, 2019

    @Tratcher
    MemberAuthor

    or by the response ending

    This part that might break you. Proposal D is for the response stream not to end until the request stream ends. Looks like a classic deadlock for you.

  7. JamesNK commented on Jun 14, 2019

    @JamesNK
    Member

    That seems problematic. We need to read to the end of the response stream. Its completion is the only indication we have that HttpResponseMessage.TrailingHeaders has been populated with values.

    I'm going to experiment with Grpc.Core (native client and server) to see what they do when the response has been completed while the client stream is still open.

  8. JamesNK commented on Jun 15, 2019

    @JamesNK
    Member

    Ok, here is what Grpc.Core does.

    Scenario 1: Client explicitly sends the request stream, completes it, and awaits a response. The server reads the entire request stream before sending a response.

    image

    Client sends an DATA END_STREAM=true frame.

    Server responds with HEADER, DATA, HEADER. The final HEADER (trailers) has END_STREAM=true.

    Scenario 2: Client explicitly sends the request stream, completes it, and awaits a response. The server does not read the entire request stream before sending a response.

    image

    Client never sends a DATA END_STREAM=true frame.

    Server responds with HEADER, DATA, HEADER, RST_STREAM. The final HEADER (trailers) has END_STREAM=true. RST_STREAM has NO_ERROR.

  9. JamesNK commented on Jun 15, 2019

    @JamesNK
    Member

    tldr: the server sends a RST_STREAM (NO_ERROR) frame to the client if it never reads an END_STREAM=true frame in the request stream.

    @wfurt @stephentoub In option D, will the RST_STREAM force the client's request stream to close, which allow's the response stream to end?

    @Tratcher Does Kestrel automatically send a RST_STREAM if the response finishes without reading the entire request? Is this behavior part of the standard? I worry about option D breaking HttpClient if a server implementation never resets the request stream when it finishes.

  10. JamesNK commented on Jun 15, 2019

    @JamesNK
    Member

    https://tools.ietf.org/html/rfc7540#section-8.1

    @Tratcher Looks optional:

    An HTTP response is complete after the server sends -- or the client
    receives -- a frame with the END_STREAM flag set (including any
    CONTINUATION frames needed to complete a header block). A server can
    send a complete response prior to the client sending an entire
    request if the response does not depend on any portion of the request
    that has not been sent and received. When this is true, a server MAY
    request that the client abort transmission of a request without error
    by sending a RST_STREAM with an error code of NO_ERROR after sending
    a complete response (i.e., a frame with the END_STREAM flag).

    Clients MUST NOT discard responses as a result of receiving such a
    RST_STREAM, though clients can always discard responses at their
    discretion for other reasons.

  11. wfurt commented on Jun 15, 2019

    @wfurt
    Member

    If HttpClient gets RST_STREAM before EOF, it will rest response stream and throw exception. We put protocol error to inner exception.

  12. JamesNK commented on Jun 15, 2019

    @JamesNK
    Member

    In situation 2 above the response stream has been ended with END_STREAM=true. The RST_STREAM comes afterwards to tell the client to end the request stream (if it is still open).

  13. davidsh commented on Jun 21, 2019

    @davidsh
    Contributor

    @Tratcher @JamesNK Can you summarize where we are on this issue? What do we need to do for .NET Core 3.0 release? Is this now a documentation issue? Or do we need to change product code/behavior?

  14. JamesNK commented on Jun 25, 2019

    @JamesNK
    Member

    @Tratcher is the person to talk to about this.

    (also, I'm on holiday beginning of this week 🌴🌞)

  15. 32 remaining items

  16. ryan-motive commented on Feb 22, 2022

    @ryan-motive

    Has there been any movement on this issue? More generally, is there any way to wrestle HttpClient to work as a truly bi-directional HTTP/2 connection? We're talking to an HTTP/2 service and at a bit of a loss for how best to tackle this in C#. Are there any options besides building out a custom implementation using TcpClient?

  17. alexandrehtrb commented on Sep 5, 2022

    @alexandrehtrb

    +1

    Are there any options besides building out a custom implementation using TcpClient?

    I think WebSockets is an alternative...

  18. ryan-motive commented on Sep 6, 2022

    @ryan-motive

    Yep, using Websockets currently and it's working well, but it feels like a placeholder until .NET gets proper support for HTTP/2 streaming.

  19. karelz commented on Sep 7, 2022

    @karelz
    Member

    @ryan-motive can you share some details about your scenario? Why do you need it? Is it server requirement you need to match?

  20. ryan-motive commented on Sep 7, 2022

    @ryan-motive

    It's not really relevant why I need it--the spec was written in 2015 and yet this part of the spec is still not supported by the .NET networking library. This seems like a pretty significant missing piece.

  21. karelz commented on Sep 7, 2022

    @karelz
    Member

    @ryan-motive I respectfully disagree. There are things RFCs specify which are rarely used and not all stacks implement them. We believe this might be one of them in HTTP/2 RFC.
    In general, we prioritize work based on customer demand -- when we know about user scenarios requiring the features and/or when there are lots of +1s. If you want to help us prioritize the work in upcoming releases, then sharing details about your scenario will help us with that.

    I also suggest everyone who wishes to have this feature to upvote top post. Thanks!

  22. ryan-motive commented on Sep 7, 2022

    @ryan-motive

    Then at a minimum make this the official policy and include it in the documentation so that we don't spend days digging through Github forums trying to figure out why the feature is not there.

  23. stephentoub commented on Sep 7, 2022

    @stephentoub
    Member

    More generally, is there any way to wrestle HttpClient to work as a truly bi-directional HTTP/2 connection?

    I'm a little confused. This is already possible with HTTP/2, has been since .NET Core 3.0; that's how gRPC works. What specifically isn't working? The core of this issue was addressed as described in #1511 (comment).

  24. ryan-motive commented on Sep 7, 2022

    @ryan-motive

    I don't see how this solves the problem but maybe I'm not understanding that comment? Basically I just need a stream for writing and a stream for reading a duplex connection. I wasn't able to find a solution and this thread suggested there wasn't one. I do recall reading your comment when I was trying to solve this, but frankly I didn't really understand it 😆

    You're correct though--the use cases here are gRPC and there are a number of AWS services that use HTTP/2 streaming. Right now it's not possible to use C# to access those so we're having to go through a C++ wrapper which adds complexity.

  25. davidfowl commented on Sep 7, 2022

    @davidfowl
    Member

    I wanted to reply with what @stephentoub said but I was waiting for a code sample to show what the problem was. I wrote this a long time ago, what am I missing https://github.com/davidfowl/StreamingSample?

  26. stephentoub commented on Sep 7, 2022

    @stephentoub
    Member

    Right, what David just said. A custom HttpContent-derived type set on the request supports copying concurrently with the HttpContent on the response stream. So you can author an HttpContent that's the send side that you write to for the duration of the operation, and consume from the response HttpContent for the duration of the operation. The comments in this thread about it not working were from before we allowed it to work with HTTP/2.

  27. ryan-motive commented on Sep 7, 2022

    @ryan-motive

    Wow, I wish I'd seen this! It's long in the past now, but this is helpful to know for the future.

  28. karelz commented on Sep 7, 2022

    @karelz
    Member

    @stephentoub what is left to track on this issue then?

  29. stephentoub commented on Sep 7, 2022

    @stephentoub
    Member

    @stephentoub what is left to track on this issue then?

    #1511 (comment)
    "Notes re remaining work: We added an internal "AllowDuplex" property on HttpContent. We should consider making this public."

  30. karelz commented on Sep 8, 2022

    @karelz
    Member

    Thanks @stephentoub! Top post updated to clarify for future.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-suggestionarea-System.Net.Httptenet-performance

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions