Skip to content

HTTP2: Missing duplex steaming - HttpClient.SendAsync with HttpCompletionOption.ResponseHeadersRead #29255

Closed
dotnet/corefx
#38226

Description

@JamesNK

Problem I encountered when writing a .NET gRPC client:
httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead) with HTTP/2 is not returning a HttpResponseMessage until the response body is complete. Update: https://github.com/dotnet/corefx/issues/36855#issuecomment-483063866

This blocks anyone from using HttpClient with server and duplex streaming in HTTP/2.

Activity

  1. davidsh commented on Apr 14, 2019

    @davidsh
    Contributor
  2. JamesNK commented on Apr 14, 2019

    @JamesNK
    MemberAuthor

    I've narrowed down when it happens.

    HttpResponseMessage only returns when HttpRequestMessage.Content has finished sending. Even if the server has finished and returned the entire request, SendAsync still waits on the request content's SerializeToStreamAsync method completing.

    public class PushStreamContent : HttpContent
    {
        private readonly Func<Stream, Task> _onStreamAvailable;
    
        public PushStreamContent(Func<Stream, Task> onStreamAvailable)
        {
            _onStreamAvailable = onStreamAvailable;
        }
    
        protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context)
        {
            await _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;
        }
    }
    var httpRequest = new HttpRequestMessage();
    httpRequest.Version = new Version(2, 0);
    httpRequest.RequestUri = new Uri("https://localhost:50051" + path);
    httpRequest.Method = HttpMethod.Post;
    httpRequest.Content = new PushStreamContent(async stream =>
    {
        Console.WriteLine("Sending message 1");
        await stream.WriteAsync(Encoding.UTF8.GetBytes("Hello world 1"));
    
        // removing this delay will allow headers and content to return as soon as they are available
        await Task.Delay(TimeSpan.FromSeconds(10));
    
        Console.WriteLine("Sending message 2");
        await stream.WriteAsync(Encoding.UTF8.GetBytes("Hello world 2"));
    });

    (btw let me know if this is the wrong way to stream content from the client to the server)

    Repo of this issue: WebApplication37.zip

    This issue blocks using HttpClient for HTTP/2 duplex streaming.

  3. davidsh commented on Apr 14, 2019

    @davidsh
    Contributor

    HttpResponseMessage only returns when HttpRequestMessage.Content has finished sending. Even if the server has finished and returned the entire request, SendAsync still waits on the request content's SerializeToStreamAsync method completing.

    That is how HttpClient works even with HTTP/1.1. While HttpCompletionOption.ResponseHeadersRead won't download the response body, the general architecture of HttpClient and it's handler architecture (HttpMessageHandler.SendAsync) requires that the request body be fully sent before a response can be received, even just response headers.

    @stephentoub @geoffkizer

  4. stephentoub commented on Apr 15, 2019

    @stephentoub
    Member

    That is how HttpClient works even with HTTP/1.1.

    Note that we'd had support for it in SocketsHttpHandler for HTTP/1.1, but removed it in dotnet/corefx#27341 prior to .NET Core 2.1 shipping due to a lack of strong need for it and complication it incurred / lack of robustness in the implementation.

  5. wfurt commented on Apr 16, 2019

    @wfurt
    Member

    Do you expect something like this @JamesNK

    furt@Ubuntu16:~/repro/ConsoleApp1$ /home/furt/repro/ConsoleApp1/bin/Debug/netcoreapp3.0/linux-x64/publish/ConsoleApp1
    Starting HTTP/2 call - https://localhost:50051/response-body-flushasync
    Sending message 1
    Headers received - 0.26169719999999996
    Sending message 2
    Content received - 10.2539346
    
    Starting HTTP/2 call - https://localhost:50051/response-startasync
    Sending message 1
    Headers received - 5.0222359999999995
    Sending message 2
    Content received - 10.021061699999999
    
    Starting HTTP/2 call - https://localhost:50051/response-bodywriter-flushasync
    Sending message 1
    Headers received - 0.0209085
    Sending message 2
    Content received - 10.023050099999999
    
    Press any key to exit
    
    

    One thing I'm not sure about is how to propagate errors from request body if we return response back before finished. We can probably raise exception on response content but that does not seems quite right. We can also simply ignore them if server was happy to give response before complete request.

  6. JamesNK commented on Apr 16, 2019

    @JamesNK
    MemberAuthor

    Yes that looks like what I would have expected. I'd like to ensure content is being sent and received on both sides. I will extend the test app to have the server to react to content from the client and stream it back to the client, and have more logging.

    We can probably raise exception on response content but that does not seems quite right.

    The client app is writing content to the stream in HttpContent.SerializeToStream, so I would expect errors in sending the request come from writing to that stream. I think that would work well for gRPC because the gRPC client's call.RequestStream.WriteAsync(message) call would write to that stream, so an error thrown from it would propagate the error immediately to the user.

    httpRequest.Content = new PushStreamContent(async stream =>
    {
        await stream.WriteAsync(Encoding.UTF8.GetBytes("Hello world 1"));
    
        await Task.Delay(TimeSpan.FromSeconds(10));
    
        // An error sending request content would be raised from WriteAsync
        await stream.WriteAsync(Encoding.UTF8.GetBytes("Hello world 2"));
    });

    Will reading the response stream error after HttpResponseMessage is returned? If so then writing to the request stream throwing an error would be a nice symmetry.

    var response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
    
    var ms = new MemoryStream();
    var stream = await response.ReadAsStreamAsync();
    await stream.CopyToAsync(ms); // Will this error today?
  7. davidfowl commented on Apr 17, 2019

    @davidfowl
    Member

    Note that we'd had support for it in SocketsHttpHandler for HTTP/1.1, but removed it in dotnet/corefx#27341 prior to .NET Core 2.1 shipping due to a lack of strong need for it and complication it incurred / lack of robustness in the implementation.

    This makes me sad, I thought we left that support in there. Streaming is one of the important for GRPC so I hope we can fix this.

  8. JamesNK commented on Apr 17, 2019

    @JamesNK
    MemberAuthor

    @wfurt I've updated the test app to have the client stream data to the server and the server to stream it back in response.

    WebApplication37.zip

    Could you try it out with your changes and post the console output? (the client and the server output would be useful to see)

    The results I hope to see is the client sending and receiving data with the server.

  9. wfurt commented on Apr 17, 2019

    @wfurt
    Member

    Ok, I'll give it try @JamesNK. I need to polish error handling on my experiment.

  10. self-assigned this
    on Apr 18, 2019
  11. changed the title [-]HttpClient.SendAsync with HTTP/2 and HttpCompletionOption.ResponseHeadersRead[/-] [+]HTTP2: Missing duplex steaming - HttpClient.SendAsync with HttpCompletionOption.ResponseHeadersRead[/+] on Apr 25, 2019
  12. JamesNK commented on May 15, 2019

    @JamesNK
    MemberAuthor

    Interop test repo:

    1. git clone https://github.com/grpc/grpc-dotnet.git
    2. git checkout master
    3. dotnet run -p testassets\InteropTestsNativeServer
    4. dotnet run -p testassets\InteropTestsClient --server_port 8070 --test_case ping_pong

    Currently the test will hang with this output:

    C:\Development\Source\grpc-dotnet [master ≡]> dotnet run -p testassets\InteropTestsClient --server_port 8070 --test_case ping_pong
    Use TLS: False
    Use Test CA: False
    Client type: httpclient
    Server host: localhost
    Server port: 8070
    running ping_pong
    dbug: Grpc.NetCore.HttpClient.Internal.GrpcCall[1]
          => GrpcMethodType:DuplexStreaming GrpcUri:/grpc.testing.TestService/FullDuplexCall
          Starting gRPC call. Method type: 'DuplexStreaming', URI: '/grpc.testing.TestService/FullDuplexCall'.
    dbug: Grpc.NetCore.HttpClient.Internal.GrpcCall[6]
          => GrpcMethodType:DuplexStreaming GrpcUri:/grpc.testing.TestService/FullDuplexCall
          Sending message.
    trce: Grpc.NetCore.HttpClient.Internal.GrpcCall[9]
          => GrpcMethodType:DuplexStreaming GrpcUri:/grpc.testing.TestService/FullDuplexCall
          Serialized 'Grpc.Testing.StreamingOutputCallRequest' to 27196 byte message.
    trce: Grpc.NetCore.HttpClient.Internal.GrpcCall[7]
          => GrpcMethodType:DuplexStreaming GrpcUri:/grpc.testing.TestService/FullDuplexCall
          Message sent.
    

    Expected behavior is the client sends and receives messages with the server in the context of a gRPC duplex streaming call.

    Replace step 4 of repo with this command to see the test succeed:

    dotnet run -p testassets\InteropTestsClient --server_port 8070 --client_type ccore --test_case ping_pong
    

    `

  13. transferred this issue fromdotnet/corefxon Feb 1, 2020
  14. added this to the 3.0 milestone on Feb 1, 2020
  15. ghost locked as resolved and limited conversation to collaborators on Dec 13, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

enhancement

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions