Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement dynamic HTTP/2 window scaling #54755

Merged
merged 40 commits into from
Jul 8, 2021
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
Show all changes
40 commits
Select commit Hold shift + click to select a range
1d41853
Implement dynamic HTTP2 window scaling
antonfirsov Jun 25, 2021
4067443
Merge branch 'main' into http/dynamic-window-02
antonfirsov Jun 25, 2021
a3800d3
actually fix the conflict with #54437
antonfirsov Jun 25, 2021
9f50764
add comment on PING payloads
antonfirsov Jun 25, 2021
3c7c474
delete StringBuilderOutput
antonfirsov Jun 25, 2021
6eb66e9
DisableDynamicWindowSizing: fix name
antonfirsov Jun 25, 2021
4c7f3ac
make RttEstimator.MinRtt thread-safe
antonfirsov Jun 26, 2021
473139d
simplify RuntimeSettingParserTest code
antonfirsov Jun 28, 2021
f2ff4ee
respond to PING while reading CONTINUATION frames in ProcessHeadersFrame
antonfirsov Jun 28, 2021
2bf13e0
fix test
antonfirsov Jun 28, 2021
526d723
add PingBeforeContinuationFrame_Success
antonfirsov Jun 28, 2021
7362e87
WIP: SetupAutomaticPingResponse by default
antonfirsov Jun 30, 2021
4dfcfeb
WIP: SetupAutomaticPingResponse by default
antonfirsov Jun 30, 2021
6e9142b
fix Http2_PingKeepAlive formatting
antonfirsov Jun 30, 2021
e30ab75
delete manual ping response setup code
antonfirsov Jun 30, 2021
20416ac
disallow PING frames before CONTINUATION again
antonfirsov Jun 30, 2021
9f53e0a
move process-wide settings to GlobalHttpSettings & remove MaximumWind…
antonfirsov Jun 30, 2021
13d2066
cleanup defaults
antonfirsov Jun 30, 2021
e6cc7c3
nits
antonfirsov Jun 30, 2021
b89e4bc
reduce footprint of Http2StreamWindowManager & RttEstimator
antonfirsov Jun 30, 2021
1df65a2
comments
antonfirsov Jun 30, 2021
3e18b0b
allow receiving PING ACK after GOAWAY
antonfirsov Jun 30, 2021
fb3b90e
Merge branch 'main' into http/dynamic-window-02
antonfirsov Jun 30, 2021
a54dfdc
nit
antonfirsov Jun 30, 2021
dd8d2cc
defer _lastWindowUpdate = Stopwatch.GetTimestamp()
antonfirsov Jun 30, 2021
4f302c7
delete extra newlines
antonfirsov Jun 30, 2021
e4d8639
remove _respondToPing
antonfirsov Jun 30, 2021
c7761e2
Http2LoopbackConnection: allow PING ACK after GOAWAY
antonfirsov Jun 30, 2021
e23cac8
EnableTransparentPingResponse = false in Http2_PingKeepAlive
antonfirsov Jun 30, 2021
70a04c3
commit suggestion
antonfirsov Jun 30, 2021
ddd6ea1
Merge branch 'main' into http/dynamic-window-02
antonfirsov Jul 1, 2021
7b006a5
sync DiagnosticsHandler with #54437
antonfirsov Jul 1, 2021
bc2b9b5
fix build
antonfirsov Jul 1, 2021
95f9e0d
Apply suggestions
antonfirsov Jul 2, 2021
aba1735
separate _expectPingFrame and _transparentPingResponse functionality
antonfirsov Jul 2, 2021
5cbf0e1
check for _streamWindowSize < MaxStreamWindowSize before trying to ex…
antonfirsov Jul 2, 2021
cd94dcf
nit
antonfirsov Jul 5, 2021
6954f61
move DefaultInitialHttp2StreamWindowSize
antonfirsov Jul 5, 2021
6dbfa47
harden LowBandwidthDelayProduct_ClientStreamReceiveWindowStopsScaling
antonfirsov Jul 5, 2021
3009773
delete unreliable LowBandwidthDelayProduct_ClientStreamReceiveWindowS…
antonfirsov Jul 5, 2021
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,7 @@ internal static partial class HttpHandlerDefaults
public static readonly TimeSpan DefaultPooledConnectionIdleTimeout = TimeSpan.FromMinutes(1);
public static readonly TimeSpan DefaultExpect100ContinueTimeout = TimeSpan.FromSeconds(1);
public static readonly TimeSpan DefaultConnectTimeout = Timeout.InfiniteTimeSpan;
public const int DefaultHttp2MaxStreamWindowSize = 16 * 1024 * 1024;
public const double DefaultHttp2StreamWindowScaleThresholdMultiplier = 1.0;
antonfirsov marked this conversation as resolved.
Show resolved Hide resolved
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ public class Http2LoopbackConnection : GenericLoopbackConnection
private TaskCompletionSource<bool> _ignoredSettingsAckPromise;
private bool _ignoreWindowUpdates;
private TaskCompletionSource<PingFrame> _expectPingFrame;
private bool _autoProcessPingFrames;
private bool _respondToPing;
private readonly TimeSpan _timeout;
private int _lastStreamId;

Expand Down Expand Up @@ -121,11 +123,11 @@ public async Task SendConnectionPrefaceAsync()
clientSettings = await ReadFrameAsync(_timeout).ConfigureAwait(false);
}

public async Task WriteFrameAsync(Frame frame)
public async Task WriteFrameAsync(Frame frame, CancellationToken cancellationToken = default)
{
byte[] writeBuffer = new byte[Frame.FrameHeaderLength + frame.Length];
frame.WriteTo(writeBuffer);
await _connectionStream.WriteAsync(writeBuffer, 0, writeBuffer.Length).ConfigureAwait(false);
await _connectionStream.WriteAsync(writeBuffer, 0, writeBuffer.Length, cancellationToken).ConfigureAwait(false);
}

// Read until the buffer is full
Expand Down Expand Up @@ -159,7 +161,7 @@ public async Task<Frame> ReadFrameAsync(TimeSpan timeout)
return await ReadFrameAsync(timeoutCts.Token).ConfigureAwait(false);
}

private async Task<Frame> ReadFrameAsync(CancellationToken cancellationToken)
public async Task<Frame> ReadFrameAsync(CancellationToken cancellationToken)
{
// First read the frame headers, which should tell us how long the rest of the frame is.
byte[] headerBytes = new byte[Frame.FrameHeaderLength];
Expand Down Expand Up @@ -200,9 +202,18 @@ private async Task<Frame> ReadFrameAsync(CancellationToken cancellationToken)

if (_expectPingFrame != null && header.Type == FrameType.Ping)
{
_expectPingFrame.SetResult(PingFrame.ReadFrom(header, data));
_expectPingFrame = null;
return await ReadFrameAsync(cancellationToken).ConfigureAwait(false);
PingFrame pingFrame = PingFrame.ReadFrom(header, data);

// _expectPingFrame is not intended to work with PING ACK:
if (!pingFrame.AckFlag)
{
await ProcessExpectedPingFrameAsync(pingFrame);
return await ReadFrameAsync(cancellationToken).ConfigureAwait(false);
}
else
{
return pingFrame;
}
}

// Construct the correct frame type and return it.
Expand All @@ -224,11 +235,30 @@ private async Task<Frame> ReadFrameAsync(CancellationToken cancellationToken)
return GoAwayFrame.ReadFrom(header, data);
case FrameType.Continuation:
return ContinuationFrame.ReadFrom(header, data);
case FrameType.WindowUpdate:
return WindowUpdateFrame.ReadFrom(header, data);
default:
return header;
}
}

private async Task ProcessExpectedPingFrameAsync(PingFrame pingFrame)
{
_expectPingFrame.SetResult(pingFrame);
if (_respondToPing && !pingFrame.AckFlag)
antonfirsov marked this conversation as resolved.
Show resolved Hide resolved
{
await SendPingAckAsync(pingFrame.Data);
}

_expectPingFrame = null;
_respondToPing = false;

if (_autoProcessPingFrames)
{
_ = ExpectPingFrameAsync(true);
}
}

// Reset and return underlying networking objects.
public (SocketWrapper, Stream) ResetNetwork()
{
Expand Down Expand Up @@ -263,15 +293,32 @@ public void IgnoreWindowUpdates()
_ignoreWindowUpdates = true;
}

// Set up loopback server to expect PING frames among other frames.
// Set up loopback server to expect a (non-ACK) PING frame among other frames.
// Once PING frame is read in ReadFrameAsync, the returned task is completed.
// The returned task is canceled in ReadPingAsync if no PING frame has been read so far.
public Task<PingFrame> ExpectPingFrameAsync()
public Task<PingFrame> ExpectPingFrameAsync(bool respond = false)
{
_expectPingFrame ??= new TaskCompletionSource<PingFrame>();
_respondToPing = respond;

return _expectPingFrame.Task;
}

// Recurring variant of ExpectPingFrame().
// Starting from the time of the call, respond to all (non-ACK) PING frames which are received among other frames.
public void SetupAutomaticPingResponse()
{
_autoProcessPingFrames = true;
_ = ExpectPingFrameAsync(true);
antonfirsov marked this conversation as resolved.
Show resolved Hide resolved
}

// Tear down automatic PING responses, but still expect (at most one) PING in flight
public void TearDownAutomaticPingResponse()
{
_respondToPing = false;
_autoProcessPingFrames = false;
}

public async Task ReadRstStreamAsync(int streamId)
{
Frame frame = await ReadFrameAsync(_timeout);
Expand All @@ -292,6 +339,14 @@ public async Task ReadRstStreamAsync(int streamId)
}
}

// Receive a single PING frame and respond with an ACK
public async Task RespondToPingFrameAsync()
{
PingFrame pingFrame = (PingFrame)await ReadFrameAsync(_timeout);
Assert.False(pingFrame.AckFlag, "Unexpected PING ACK");
await SendPingAckAsync(pingFrame.Data);
}

// Wait for the client to close the connection, e.g. after the HttpClient is disposed.
public async Task WaitForClientDisconnectAsync(bool ignoreUnexpectedFrames = false)
{
Expand Down Expand Up @@ -720,18 +775,23 @@ public async Task PingPong()
PingFrame ping = new PingFrame(pingData, FrameFlags.None, 0);
await WriteFrameAsync(ping).ConfigureAwait(false);
PingFrame pingAck = (PingFrame)await ReadFrameAsync(_timeout).ConfigureAwait(false);

if (pingAck == null || pingAck.Type != FrameType.Ping || !pingAck.AckFlag)
{
throw new Exception("Expected PING ACK");
string faultDetails = pingAck == null ? "" : $" frame.Type:{pingAck.Type} frame.AckFlag: {pingAck.AckFlag}";
throw new Exception("Expected PING ACK" + faultDetails);
}

Assert.Equal(pingData, pingAck.Data);
}

public Task<PingFrame> ReadPingAsync() => ReadPingAsync(_timeout);

public async Task<PingFrame> ReadPingAsync(TimeSpan timeout)
{
_expectPingFrame?.TrySetCanceled();
_expectPingFrame = null;
_respondToPing = false;

Frame frame = await ReadFrameAsync(timeout).ConfigureAwait(false);
Assert.NotNull(frame);
Expand All @@ -743,7 +803,7 @@ public async Task<PingFrame> ReadPingAsync(TimeSpan timeout)
return Assert.IsAssignableFrom<PingFrame>(frame);
}

public async Task SendPingAckAsync(long payload)
public async Task SendPingAckAsync(long payload, CancellationToken cancellationToken = default)
{
PingFrame pingAck = new PingFrame(payload, FrameFlags.Ack, 0);
await WriteFrameAsync(pingAck).ConfigureAwait(false);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1475,6 +1475,11 @@ await LoopbackServerFactory.CreateClientAndServerAsync(async uri =>
{
await server.AcceptConnectionAsync(async connection =>
{
if (connection is Http2LoopbackConnection http2Connection)
antonfirsov marked this conversation as resolved.
Show resolved Hide resolved
{
http2Connection.SetupAutomaticPingResponse(); // Handle RTT PING
}

// Send unexpected 1xx responses.
HttpRequestData requestData = await connection.ReadRequestDataAsync(readBody: false);
await connection.SendResponseAsync(responseStatusCode, isFinal: false);
Expand Down Expand Up @@ -1524,6 +1529,10 @@ await LoopbackServerFactory.CreateClientAndServerAsync(async uri =>
await server.AcceptConnectionAsync(async connection =>
{
await connection.ReadRequestDataAsync(readBody: false);
if (connection is Http2LoopbackConnection http2Connection)
{
http2Connection.SetupAutomaticPingResponse(); // Respond to RTT PING
}
// Send multiple 100-Continue responses.
for (int count = 0 ; count < 4; count++)
{
Expand Down Expand Up @@ -1627,6 +1636,11 @@ await server.AcceptConnectionAsync(async connection =>

await connection.SendResponseAsync(HttpStatusCode.OK, headers: new HttpHeaderData[] {new HttpHeaderData("Content-Length", $"{ResponseString.Length}")}, isFinal : false);

if (connection is Http2LoopbackConnection http2Connection)
{
http2Connection.SetupAutomaticPingResponse(); // Respond to RTT PING
}

byte[] body = await connection.ReadRequestBodyAsync();
Assert.Equal(RequestString, Encoding.ASCII.GetString(body));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ protected static HttpClient CreateHttpClient(HttpMessageHandler handler, string
#endif
};

public const int DefaultInitialWindowSize = 65535;

public static readonly bool[] BoolValues = new[] { true, false };

// For use by remote server tests
Expand Down
1 change: 1 addition & 0 deletions src/libraries/System.Net.Http/ref/System.Net.Http.cs
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,7 @@ protected override void SerializeToStream(System.IO.Stream stream, System.Net.Tr
public sealed partial class SocketsHttpHandler : System.Net.Http.HttpMessageHandler
{
public SocketsHttpHandler() { }
public int InitialHttp2StreamWindowSize { get { throw null; } set { } }
[System.Runtime.Versioning.UnsupportedOSPlatformGuardAttribute("browser")]
public static bool IsSupported { get { throw null; } }
public bool AllowAutoRedirect { get { throw null; } set { } }
Expand Down
3 changes: 3 additions & 0 deletions src/libraries/System.Net.Http/src/Resources/Strings.resx
Original file line number Diff line number Diff line change
Expand Up @@ -429,6 +429,9 @@
<data name="net_http_http2_connection_not_established" xml:space="preserve">
<value>An HTTP/2 connection could not be established because the server did not complete the HTTP/2 handshake.</value>
</data>
<data name="net_http_http2_invalidinitialstreamwindowsize" xml:space="preserve">
<value>The initial HTTP/2 stream window size must be between {0} and {1}.</value>
</data>
<data name="net_MethodNotImplementedException" xml:space="preserve">
<value>This method is not implemented by this class.</value>
</data>
Expand Down
2 changes: 2 additions & 0 deletions src/libraries/System.Net.Http/src/System.Net.Http.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@
<Compile Include="System\Net\Http\ReadOnlyMemoryContent.cs" />
<Compile Include="System\Net\Http\RequestRetryType.cs" />
<Compile Include="System\Net\Http\SocketsHttpHandler\HttpMessageHandlerStage.cs" />
<Compile Include="System\Net\Http\SocketsHttpHandler\RuntimeSettingParser.cs" />
<Compile Include="System\Net\Http\StreamContent.cs" />
<Compile Include="System\Net\Http\StreamToStreamCopy.cs" />
<Compile Include="System\Net\Http\StringContent.cs" />
Expand Down Expand Up @@ -160,6 +161,7 @@
<Compile Include="System\Net\Http\SocketsHttpHandler\Http2ProtocolException.cs" />
<Compile Include="System\Net\Http\SocketsHttpHandler\Http2Stream.cs" />
<Compile Include="System\Net\Http\SocketsHttpHandler\Http2StreamException.cs" />
<Compile Include="System\Net\Http\SocketsHttpHandler\Http2StreamWindowManager.cs" />
<Compile Include="System\Net\Http\SocketsHttpHandler\Http3Connection.cs" />
<Compile Include="System\Net\Http\SocketsHttpHandler\Http3ConnectionException.cs" />
<Compile Include="System\Net\Http\SocketsHttpHandler\Http3ProtocolException.cs" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,12 @@ public bool UseCookies
set => throw new PlatformNotSupportedException();
}

public int InitialHttp2StreamWindowSize
antonfirsov marked this conversation as resolved.
Show resolved Hide resolved
{
get => throw new PlatformNotSupportedException();
set => throw new PlatformNotSupportedException();
}

[AllowNull]
public CookieContainer CookieContainer
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,25 +28,8 @@ internal sealed class DiagnosticsHandler : DelegatingHandler

public static bool IsGloballyEnabled { get; } = GetEnableActivityPropagationValue();

private static bool GetEnableActivityPropagationValue()
{
// First check for the AppContext switch, giving it priority over the environment variable.
if (AppContext.TryGetSwitch(Namespace + ".EnableActivityPropagation", out bool enableActivityPropagation))
{
return enableActivityPropagation;
}

// AppContext switch wasn't used. Check the environment variable to determine which handler should be used.
string? envVar = Environment.GetEnvironmentVariable("DOTNET_SYSTEM_NET_HTTP_ENABLEACTIVITYPROPAGATION");
if (envVar != null && (envVar.Equals("false", StringComparison.OrdinalIgnoreCase) || envVar.Equals("0")))
{
// Suppress Activity propagation.
return false;
}

// Defaults to enabling Activity propagation.
return true;
}
private static bool GetEnableActivityPropagationValue() =>
RuntimeSettingParser.QueryRuntimeSettingSwitch(Namespace + ".EnableActivityPropagation", "DOTNET_SYSTEM_NET_HTTP_ENABLEACTIVITYPROPAGATION", true);

public DiagnosticsHandler(HttpMessageHandler innerHandler) : base(innerHandler)
{
Expand Down
Loading