Skip to content

Bidirectional HTTP/2 streaming truncates the request body if the response ends #30230

Closed
dotnet/corefx
#39638

Description

@Tratcher

RE: https://github.com/dotnet/corefx/issues/38559. There's also a functional issue where as soon as the client disposes the response stream no future request data frames are sent to the server. The server eventually times out and aborts the connection.

@stephentoub @geoffkizer

This is happening with Microsoft.NETCore.App 3.0.0-preview8-27904-06.

Flow:

  • Client sends headers, Expect 100-Continue
  • Server sends 100-Continue
  • Client sends first message "Hello World"
  • Server echos "Hello World" and completes the response (END_STREAM)
  • Client consumes the response and disposes the response stream.
  • Client sends final message "Hello World" and closes the request.
    Bug: this message is never sent. Nor does the client send a RST or otherwise indicate it is done with the request. The server times out and aborts the whole connection.
    Expected: the client would send the last message and END_STREAM. Alternatively it must at least send a RST.
    Workaround: Do not Dispose the response stream after the last write returns 0.

See the 6 second gap in the logs after sending the response END_STREAM.

[0.003s] [TestLifetime] [Information] Starting test BidirectionalStreamingMoreClientData-http at 2019-07-11T18:47:34
[0.006s] [Microsoft.Extensions.Hosting.Internal.Host] [Debug] Hosting starting
[0.009s] [Microsoft.Hosting.Lifetime] [Information] Now listening on: http://127.0.0.1:21567
[0.009s] [Microsoft.AspNetCore.Hosting.Diagnostics] [Debug] Loaded hosting startup assembly Interop.FunctionalTests
[0.009s] [Microsoft.Hosting.Lifetime] [Information] Application started. Press Ctrl+C to shut down.
[0.010s] [Microsoft.Hosting.Lifetime] [Information] Hosting environment: Production
[0.010s] [Microsoft.Hosting.Lifetime] [Information] Content root path: D:\github\AspNetCore\artifacts\bin\Interop.FunctionalTests\Debug\netcoreapp3.0\
[0.011s] [Microsoft.Extensions.Hosting.Internal.Host] [Debug] Hosting started
[0.015s] [Microsoft.AspNetCore.Server.Kestrel] [Debug] Connection id "0HLO660SITO23" started.
[0.017s] [Microsoft.AspNetCore.Server.Kestrel] [Verbose] Connection id "0HLO660SITO23" sending SETTINGS frame for stream ID 0 with length 18 and flags NONE
[0.017s] [Microsoft.AspNetCore.Server.Kestrel] [Verbose] Connection id "0HLO660SITO23" sending WINDOW_UPDATE frame for stream ID 0 with length 4 and flags 0x0
[0.017s] [Microsoft.AspNetCore.Server.Kestrel] [Verbose] Connection id "0HLO660SITO23" received SETTINGS frame for stream ID 0 with length 12 and flags NONE
[0.017s] [Microsoft.AspNetCore.Server.Kestrel] [Verbose] Connection id "0HLO660SITO23" sending SETTINGS frame for stream ID 0 with length 0 and flags ACK
[0.018s] [Microsoft.AspNetCore.Server.Kestrel] [Verbose] Connection id "0HLO660SITO23" received WINDOW_UPDATE frame for stream ID 0 with length 4 and flags 0x0
[0.018s] [Microsoft.AspNetCore.Server.Kestrel] [Verbose] Connection id "0HLO660SITO23" received HEADERS frame for stream ID 1 with length 35 and flags END_HEADERS
[0.018s] [Microsoft.AspNetCore.Server.Kestrel] [Verbose] Connection id "0HLO660SITO23" received SETTINGS frame for stream ID 0 with length 0 and flags ACK
[0.020s] [Microsoft.AspNetCore.Hosting.Diagnostics] [Information] Request starting HTTP/2 POST http://127.0.0.1:21567/  
[0.020s] [Microsoft.AspNetCore.Server.Kestrel] [Debug] Connection id "0HLO660SITO23", Request id "0HLO660SITO23:00000001": started reading request body.
[0.021s] [Microsoft.AspNetCore.Server.Kestrel] [Verbose] Connection id "0HLO660SITO23" sending HEADERS frame for stream ID 1 with length 5 and flags END_HEADERS
[0.023s] [Microsoft.AspNetCore.Server.Kestrel] [Verbose] Connection id "0HLO660SITO23" received DATA frame for stream ID 1 with length 11 and flags NONE
[0.023s] [Microsoft.AspNetCore.Server.Kestrel] [Verbose] Connection id "0HLO660SITO23" sending HEADERS frame for stream ID 1 with length 53 and flags END_HEADERS
[0.024s] [Microsoft.AspNetCore.Server.Kestrel] [Verbose] Connection id "0HLO660SITO23" sending DATA frame for stream ID 1 with length 11 and flags NONE
[0.024s] [Microsoft.AspNetCore.Server.Kestrel] [Verbose] Connection id "0HLO660SITO23" sending DATA frame for stream ID 1 with length 0 and flags END_STREAM
[6.017s] [Microsoft.AspNetCore.Server.Kestrel] [Information] Connection id "0HLO660SITO23", Request id "null": the request timed out because it was not sent by the client at a minimum of 240 bytes/second.
[6.019s] [Microsoft.AspNetCore.Server.Kestrel] [Debug] Connection id "0HLO660SITO23" is closed. The last processed stream ID was 1.
[6.020s] [Microsoft.AspNetCore.Server.Kestrel] [Verbose] Connection id "0HLO660SITO23" sending GOAWAY frame for stream ID 0 with length 8 and flags 0x0
[6.022s] [Microsoft.AspNetCore.Server.Kestrel.Transport.Sockets] [Debug] Connection id "0HLO660SITO23" sending FIN because: "Reading the request body timed out due to data arriving too slowly. See MinRequestBodyDataRate."
[6.025s] [Microsoft.AspNetCore.Hosting.Diagnostics] [Information] Request finished in 6005.1414ms 200 
[6.026s] [Microsoft.AspNetCore.Server.Kestrel] [Debug] Connection id "0HLO660SITO23", Request id "0HLO660SITO23:00000001": done reading request body.
[6.026s] [Microsoft.AspNetCore.Server.Kestrel] [Information] Connection id "0HLO660SITO23", Request id "0HLO660SITO23:00000001": the application completed without reading the entire request body.
[6.026s] [Microsoft.AspNetCore.Server.Kestrel] [Debug] Some connections failed to close gracefully during server shutdown.
[6.027s] [Microsoft.AspNetCore.Server.Kestrel] [Debug] Connection id "0HLO660SITO23" stopped.
[6.032s] [TestLifetime] [Information] Finished test BidirectionalStreamingMoreClientData-http in 6.028651399999999s
Test code:
        public async Task BidirectionalStreamingMoreClientData(string scheme)
        {
            var lastPacket = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);
            var hostBuilder = new HostBuilder()
                .ConfigureWebHost(webHostBuilder =>
                {
                    ConfigureKestrel(webHostBuilder, scheme);
                    webHostBuilder.ConfigureServices(AddTestLogging)
                    .Configure(app => app.Run(async context =>
                    {
                        var reader = context.Request.BodyReader;

                        var readResult = await reader.ReadAsync();
                        while (!readResult.IsCompleted && readResult.Buffer.Length < "Hello World".Length)
                        {
                            reader.AdvanceTo(readResult.Buffer.Start, readResult.Buffer.End);
                            readResult = await reader.ReadAsync();
                        }

                        var sequence = readResult.Buffer.Slice(0, "Hello World".Length);
                        Assert.True(sequence.IsSingleSegment);
                        await context.Response.BodyWriter.WriteAsync(sequence.First);
                        reader.AdvanceTo(sequence.End);
                        await context.Features.Get<IHttpResponseCompletionFeature>().CompleteAsync();

                        try
                        {
                            // The client sends one more packet after the server completes
                            readResult = await reader.ReadAsync();
                            while (!readResult.IsCompleted && readResult.Buffer.Length < "Hello World".Length)
                            {
                                reader.AdvanceTo(readResult.Buffer.Start, readResult.Buffer.End);
                                readResult = await reader.ReadAsync();
                            }

                            Assert.True(readResult.Buffer.IsSingleSegment);
                            var result = Encoding.UTF8.GetString(readResult.Buffer.FirstSpan);
                            reader.AdvanceTo(readResult.Buffer.End);

                            var finalResult = await reader.ReadAsync();
                            Assert.True(finalResult.IsCompleted && finalResult.Buffer.Length == 0);
                            lastPacket.SetResult(result);
                        }
                        catch (Exception ex)
                        {
                            lastPacket.SetException(ex);
                        }
                    }));
                });
            using var host = await hostBuilder.StartAsync();

            var url = $"{scheme}://127.0.0.1:{host.GetPort().ToString(CultureInfo.InvariantCulture)}/";

            using var client = CreateClient();
            client.DefaultRequestHeaders.ExpectContinue = true;

            var streamingContent = new StreamingContent();
            var request = new HttpRequestMessage(HttpMethod.Post, url)
            {
                Version = HttpVersion.Version20,
                Content = streamingContent,
            };
            var responseTask = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead).DefaultTimeout();
            // The server doesn't respond until we send the first set of data
            await streamingContent.SendAsync("Hello World").DefaultTimeout();
            var response = await responseTask;

            Assert.Equal(HttpVersion.Version20, response.Version);
            var stream = await response.Content.ReadAsStreamAsync();
            var responseBuffer = new byte["Hello World".Length];

            var read = await stream.ReadAsync(responseBuffer, 0, responseBuffer.Length).DefaultTimeout();
            Assert.Equal(responseBuffer.Length, read);
            Assert.Equal("Hello World", Encoding.UTF8.GetString(responseBuffer));

            read = await stream.ReadAsync(responseBuffer, 0, responseBuffer.Length).DefaultTimeout();
            Assert.Equal(0, read);
            stream.Dispose();

            // Send one more message after the server has finished.
            await streamingContent.SendAsync("Hello World").DefaultTimeout();
            streamingContent.Complete();

            var lastData = await lastPacket.Task.DefaultTimeout();
            Assert.Equal("Hello World", lastData);

            await host.StopAsync();
        }

        private class StreamingContent : HttpContent
        {
            private TaskCompletionSource<int> _sendStarted = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);
            private Func<string, Task> _sendContent;
            private TaskCompletionSource<int> _sendComplete;

            public StreamingContent()
            {
            }

            public async Task SendAsync(string text)
            {
                await _sendStarted.Task;
                await _sendContent(text);
            }

            public void Complete()
            {
                if (_sendComplete == null)
                {
                    throw new InvalidOperationException("Sending hasn't started yet.");
                }
                _sendComplete.TrySetResult(0);
            }

            protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
            {
                _sendComplete = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);
                _sendContent = async text =>
                {
                    try
                    {
                        var bytes = Encoding.UTF8.GetBytes(text);
                        await stream.WriteAsync(bytes);
                    }
                    catch (Exception ex)
                    {
                        _sendComplete.TrySetException(ex);
                    }
                };
                _sendStarted.SetResult(0);
                return _sendComplete.Task;
            }

            protected override bool TryComputeLength(out long length)
            {
                length = 0;
                return false;
            }
        }

        private static HttpClient CreateClient()
        {
            var handler = new HttpClientHandler();
            handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
            var client = new HttpClient(handler);
            client.DefaultRequestVersion = HttpVersion.Version20;
            return client;
        }

        private static void ConfigureKestrel(IWebHostBuilder webHostBuilder, string scheme)
        {
            webHostBuilder.UseKestrel(options =>
            {
                options.Listen(IPAddress.Loopback, 0, listenOptions =>
                {
                    listenOptions.Protocols = HttpProtocols.Http2;
                    if (scheme == "https")
                    {
                        listenOptions.UseHttps(TestResources.GetTestCertificate());
                    }
                });
            });
        }

Activity

  1. Tratcher commented on Jul 11, 2019

    @Tratcher
    MemberAuthor

    Ah, that last write gets an error:

    System.ObjectDisposedException
     	System.Net.Http.dll!System.Net.Http.CreditManager.RequestCreditAsync(int amount, System.Threading.CancellationToken cancellationToken)	Unknown
     	System.Net.Http.dll!System.Net.Http.Http2Connection.Http2Stream.SendDataAsync(System.ReadOnlyMemory<byte> buffer, System.Threading.CancellationToken cancellationToken)	Unknown
     	System.Private.CoreLib.dll!System.Runtime.CompilerServices.AsyncMethodBuilderCore.Start<System.Net.Http.Http2Connection.Http2Stream.<SendDataAsync>d__45>(ref System.Net.Http.Http2Connection.Http2Stream.<SendDataAsync>d__45 stateMachine)	Unknown
     	System.Private.CoreLib.dll!System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start<System.Net.Http.Http2Connection.Http2Stream.<SendDataAsync>d__45>(ref System.Net.Http.Http2Connection.Http2Stream.<SendDataAsync>d__45 stateMachine)	Unknown
     	System.Net.Http.dll!System.Net.Http.Http2Connection.Http2Stream.SendDataAsync(System.ReadOnlyMemory<byte> buffer, System.Threading.CancellationToken cancellationToken)	Unknown
     	System.Net.Http.dll!System.Net.Http.Http2Connection.Http2Stream.Http2WriteStream.WriteAsync(System.ReadOnlyMemory<byte> buffer, System.Threading.CancellationToken cancellationToken)	Unknown
    >	Interop.FunctionalTests.dll!Interop.FunctionalTests.HttpClientHttp2InteropTests.StreamingContent.SerializeToStreamAsync.AnonymousMethod__0(string text) Line 551	C#
     	Interop.FunctionalTests.dll!Interop.FunctionalTests.HttpClientHttp2InteropTests.StreamingContent.SendAsync(string text) Line 531	C#
     	Interop.FunctionalTests.dll!Interop.FunctionalTests.HttpClientHttp2InteropTests.BidirectionalStreamingMoreClientData(string scheme) Line 437	C#
    
  2. geoffkizer commented on Jul 11, 2019

    @geoffkizer
    Contributor

    We're disposing the entire Http2Stream when you dispose the response body stream. That's not correct.

  3. geoffkizer commented on Jul 12, 2019

    @geoffkizer
    Contributor

    We have deeper problems here, unfortunately. We're removing the Http2Stream from the stream dictionary when we receive EndStream on the response body (and similar). This code was written before we implemented duplex support, so it's assuming that the end of the response stream means the end of the entire stream.

    We need to change the logic here to keep the stream alive until both the request body and the response body are completed, and only dispose and remove from the dictionary then.

  4. self-assigned this
    on Jul 15, 2019
  5. karelz commented on Aug 3, 2019

    @karelz
    Member

    Fixed in master (5.0) in PR dotnet/corefx#39638 and also in release/3.0 branch (3.0) in PR dotnet/corefx#39775.

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

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions