From 55daa4cd4e995e55df6737d898af031ea4037f2b Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Fri, 15 Mar 2019 17:37:00 +0000 Subject: [PATCH] Correctly notify StreamMultiplexer of SETTINGS changes. (#67) Motivation: The StreamMultiplexer and StreamChannels are responsible for sending WINDOW_UPDATE frames, but they were never told if the user changed the value of SETTINGS_INITIAL_WINDOW_SIZE. They should be. Modifications: - Send user events when SETTINGS_INITIAL_WINDOW_SIZE changes. - Use those window events to change the target window size in HTTP2StreamChannel. - Keep track of the last stream window size we knew. Result: Less chance of flow control mess. --- .../HasLocalSettings.swift | 8 +- Sources/NIOHTTP2/HTTP2ChannelHandler.swift | 4 + .../NIOHTTP2/HTTP2ConnectionStateChange.swift | 11 +++ Sources/NIOHTTP2/HTTP2StreamChannel.swift | 11 ++- Sources/NIOHTTP2/HTTP2StreamMultiplexer.swift | 11 ++- Sources/NIOHTTP2/HTTP2UserEvents.swift | 21 ++++- Sources/NIOHTTP2/InboundWindowManager.swift | 18 ++++- .../SimpleClientServerTests+XCTest.swift | 2 + .../SimpleClientServerTests.swift | 77 +++++++++++++++++++ 9 files changed, 155 insertions(+), 8 deletions(-) diff --git a/Sources/NIOHTTP2/ConnectionStateMachine/HasLocalSettings.swift b/Sources/NIOHTTP2/ConnectionStateMachine/HasLocalSettings.swift index 5546885..ae11d97 100644 --- a/Sources/NIOHTTP2/ConnectionStateMachine/HasLocalSettings.swift +++ b/Sources/NIOHTTP2/ConnectionStateMachine/HasLocalSettings.swift @@ -37,6 +37,8 @@ extension HasLocalSettings { swap(&temporarySettings, &self.localSettings) } + var effect = NIOHTTP2ConnectionStateChange.LocalSettingsChanged() + do { try temporarySettings.receiveSettingsAck { (setting, originalValue, newValue) in switch setting { @@ -56,6 +58,10 @@ extension HasLocalSettings { try self.streamState.forAllStreams { try $0.localInitialWindowSizeChanged(by: delta) } + + // We do a += here because the value may change multiple times in one settings block. This way, we correctly + // respect that possibility. + effect.streamWindowSizeChange += Int(delta) case .maxFrameSize: // TODO(cory): Implement! break @@ -64,7 +70,7 @@ extension HasLocalSettings { return } } - return .init(result: .succeed, effect: nil) + return .init(result: .succeed, effect: .localSettingsChanged(effect)) } catch { return .init(result: .connectionError(underlyingError: error, type: .protocolError), effect: nil) } diff --git a/Sources/NIOHTTP2/HTTP2ChannelHandler.swift b/Sources/NIOHTTP2/HTTP2ChannelHandler.swift index 97895d6..509d48b 100644 --- a/Sources/NIOHTTP2/HTTP2ChannelHandler.swift +++ b/Sources/NIOHTTP2/HTTP2ChannelHandler.swift @@ -464,6 +464,10 @@ extension NIOHTTP2Handler { if settingsChange.streamWindowSizeChange != 0 { self.outboundBuffer.initialWindowSizeChanged(settingsChange.streamWindowSizeChange) } + case .localSettingsChanged(let settingsChange): + if settingsChange.streamWindowSizeChange != 0 { + self.inboundEventBuffer.pendingUserEvent(NIOHTTP2BulkStreamWindowChangeEvent(delta: settingsChange.streamWindowSizeChange)) + } } } diff --git a/Sources/NIOHTTP2/HTTP2ConnectionStateChange.swift b/Sources/NIOHTTP2/HTTP2ConnectionStateChange.swift index 905ebd8..0920130 100644 --- a/Sources/NIOHTTP2/HTTP2ConnectionStateChange.swift +++ b/Sources/NIOHTTP2/HTTP2ConnectionStateChange.swift @@ -39,6 +39,9 @@ internal enum NIOHTTP2ConnectionStateChange: Hashable { /// The remote peer's settings have been changed. case remoteSettingsChanged(RemoteSettingsChanged) + /// The local peer's settings have been changed. + case localSettingsChanged(LocalSettingsChanged) + /// A stream has been created. internal struct StreamCreated: Hashable { internal var streamID: HTTP2StreamID @@ -144,6 +147,14 @@ internal enum NIOHTTP2ConnectionStateChange: Hashable { internal struct RemoteSettingsChanged: Hashable { internal var streamWindowSizeChange: Int = 0 } + + /// The local peer's settings have changed in a way that is not trivial to decode. + /// + /// This object keeps track of the change on all stream window sizes via + /// SETTINGS frame. + internal struct LocalSettingsChanged: Hashable { + internal var streamWindowSizeChange: Int = 0 + } } diff --git a/Sources/NIOHTTP2/HTTP2StreamChannel.swift b/Sources/NIOHTTP2/HTTP2StreamChannel.swift index 85e6fdc..165b87a 100644 --- a/Sources/NIOHTTP2/HTTP2StreamChannel.swift +++ b/Sources/NIOHTTP2/HTTP2StreamChannel.swift @@ -231,7 +231,7 @@ final class HTTP2StreamChannel: Channel, ChannelCore { private var state: StreamChannelState - private let windowManager: InboundWindowManager + private var windowManager: InboundWindowManager /// If close0 was called but the stream could not synchronously close (because it's currently /// active), the promise is stored here until it can be fulfilled. @@ -512,5 +512,14 @@ internal extension HTTP2StreamChannel { self.parent?.flush() } } + + func initialWindowSizeChanged(delta: Int) { + if let increment = self.windowManager.initialWindowSizeChanged(delta: delta) { + let frame = HTTP2Frame(streamID: self.streamID, payload: .windowUpdate(windowSizeIncrement: increment)) + self.receiveOutboundFrame(frame, promise: nil) + // This flush should really go away, but we need it for now until we sort out window management. + self.parent?.flush() + } + } } diff --git a/Sources/NIOHTTP2/HTTP2StreamMultiplexer.swift b/Sources/NIOHTTP2/HTTP2StreamMultiplexer.swift index f4300a1..e5069ef 100644 --- a/Sources/NIOHTTP2/HTTP2StreamMultiplexer.swift +++ b/Sources/NIOHTTP2/HTTP2StreamMultiplexer.swift @@ -31,7 +31,7 @@ public final class HTTP2StreamMultiplexer: ChannelInboundHandler, ChannelOutboun private let inboundStreamStateInitializer: ((Channel, HTTP2StreamID) -> EventLoopFuture)? private let channel: Channel private var nextOutboundStreamID: HTTP2StreamID - private let connectionFlowControlManager: InboundWindowManager + private var connectionFlowControlManager: InboundWindowManager public func handlerAdded(context: ChannelHandlerContext) { // We now need to check that we're on the same event loop as the one we were originally given. @@ -61,7 +61,7 @@ public final class HTTP2StreamMultiplexer: ChannelInboundHandler, ChannelOutboun let channel = HTTP2StreamChannel(allocator: self.channel.allocator, parent: self.channel, streamID: streamID, - targetWindowSize: 65535, // TODO: make configurable + targetWindowSize: 65535, initiatedRemotely: true) self.streams[streamID] = channel channel.configure(initializer: self.inboundStreamStateInitializer) @@ -106,6 +106,13 @@ public final class HTTP2StreamMultiplexer: ChannelInboundHandler, ChannelOutboun if let channel = self.streams[evt.streamID], let windowSize = evt.inboundWindowSize { channel.receiveWindowUpdatedEvent(windowSize) } + case let evt as NIOHTTP2BulkStreamWindowChangeEvent: + // Here we need to pull the channels out so we aren't holding the streams dict mutably. This is because it + // will trigger an overlapping access violation if we do. + let channels = self.streams.values + for channel in channels { + channel.initialWindowSizeChanged(delta: evt.delta) + } default: break } diff --git a/Sources/NIOHTTP2/HTTP2UserEvents.swift b/Sources/NIOHTTP2/HTTP2UserEvents.swift index 8ca09bf..1fae050 100644 --- a/Sources/NIOHTTP2/HTTP2UserEvents.swift +++ b/Sources/NIOHTTP2/HTTP2UserEvents.swift @@ -33,7 +33,7 @@ public struct StreamClosedEvent { } } -extension StreamClosedEvent: Equatable { } +extension StreamClosedEvent: Hashable { } /// A `NIOHTTP2WindowUpdatedEvent` is fired whenever a flow control window is changed. @@ -63,7 +63,7 @@ public struct NIOHTTP2WindowUpdatedEvent { } } -extension NIOHTTP2WindowUpdatedEvent: Equatable { } +extension NIOHTTP2WindowUpdatedEvent: Hashable { } /// A `NIOHTTP2StreamCreatedEvent` is fired whenever a HTTP/2 stream is created. @@ -83,4 +83,19 @@ public struct NIOHTTP2StreamCreatedEvent { } } -extension NIOHTTP2StreamCreatedEvent: Equatable { } +extension NIOHTTP2StreamCreatedEvent: Hashable { } + +/// A `NIOHTTP2BulkStreamWindowChangeEvent` is fired whenever all of the remote flow control windows for a given stream have been changed. +/// +/// This occurs when an ACK to a SETTINGS frame is received that changes the value of SETTINGS_INITIAL_WINDOW_SIZE. This is only fired +/// when the local peer has changed its settings. +public struct NIOHTTP2BulkStreamWindowChangeEvent { + /// The change in the remote stream window sizes. + public let delta: Int + + public init(delta: Int) { + self.delta = delta + } +} + +extension NIOHTTP2BulkStreamWindowChangeEvent: Hashable { } diff --git a/Sources/NIOHTTP2/InboundWindowManager.swift b/Sources/NIOHTTP2/InboundWindowManager.swift index 8e11d70..429cd1f 100644 --- a/Sources/NIOHTTP2/InboundWindowManager.swift +++ b/Sources/NIOHTTP2/InboundWindowManager.swift @@ -19,6 +19,9 @@ struct InboundWindowManager { private var targetWindowSize: Int32 + // The last window size we were told about. Used when we get changes to SETTINGS_INITIAL_WINDOW_SIZE. + private var lastWindowSize: Int? + init(targetSize: Int32) { assert(targetSize <= HTTP2FlowControlWindow.maxSize) assert(targetSize >= 0) @@ -26,7 +29,9 @@ struct InboundWindowManager { self.targetWindowSize = targetSize } - func newWindowSize(_ newSize: Int) -> Int? { + mutating func newWindowSize(_ newSize: Int) -> Int? { + self.lastWindowSize = newSize + // All math here happens on 64-bit ints, as it avoids overflow problems. // The simplest case is where newSize >= targetWindowSize. In that case, we do nothing. @@ -51,4 +56,15 @@ struct InboundWindowManager { return Int(increment) } } + + mutating func initialWindowSizeChanged(delta: Int) -> Int? { + self.targetWindowSize += Int32(delta) + + if let lastWindowSize = self.lastWindowSize { + // The delta applies to the current window size as well. + return self.newWindowSize(lastWindowSize + delta) + } else { + return nil + } + } } diff --git a/Tests/NIOHTTP2Tests/SimpleClientServerTests+XCTest.swift b/Tests/NIOHTTP2Tests/SimpleClientServerTests+XCTest.swift index bed0d78..2101a14 100644 --- a/Tests/NIOHTTP2Tests/SimpleClientServerTests+XCTest.swift +++ b/Tests/NIOHTTP2Tests/SimpleClientServerTests+XCTest.swift @@ -50,6 +50,8 @@ extension SimpleClientServerTests { ("testManyConcurrentInactiveStreams", testManyConcurrentInactiveStreams), ("testBadClientMagic", testBadClientMagic), ("testOpeningWindowsViaSettingsInitialWindowSize", testOpeningWindowsViaSettingsInitialWindowSize), + ("testSettingsAckNotifiesAboutChangedFlowControl", testSettingsAckNotifiesAboutChangedFlowControl), + ("testStreamMultiplexerAcknowledgesSettingsBasedFlowControlChanges", testStreamMultiplexerAcknowledgesSettingsBasedFlowControlChanges), ] } } diff --git a/Tests/NIOHTTP2Tests/SimpleClientServerTests.swift b/Tests/NIOHTTP2Tests/SimpleClientServerTests.swift index 2f7e8d6..b5976a2 100644 --- a/Tests/NIOHTTP2Tests/SimpleClientServerTests.swift +++ b/Tests/NIOHTTP2Tests/SimpleClientServerTests.swift @@ -1093,4 +1093,81 @@ class SimpleClientServerTests: XCTestCase { XCTAssertNoThrow(try self.clientChannel.finish()) XCTAssertNoThrow(try self.serverChannel.finish()) } + + func testSettingsAckNotifiesAboutChangedFlowControl() throws { + // Begin by getting the connection up. + try self.basicHTTP2Connection() + let recorder = UserEventRecorder() + XCTAssertNoThrow(try self.clientChannel.pipeline.addHandler(recorder).wait()) + + // Let's open a few streams. + let headers = HPACKHeaders([(":path", "/"), (":method", "GET"), (":scheme", "https"), (":authority", "localhost")]) + let frames = [HTTP2StreamID(1), HTTP2StreamID(3), HTTP2StreamID(5)].map { HTTP2Frame(streamID: $0, payload: .headers(.init(headers: headers))) } + try self.assertFramesRoundTrip(frames: frames, sender: self.clientChannel, receiver: self.serverChannel) + + // We will have some user events here, none should be a SETTINGS_INITIAL_WINDOW_SIZE change. + XCTAssertFalse(recorder.events.contains(where: { $0 is NIOHTTP2BulkStreamWindowChangeEvent })) + + // Now the client will send, and get acknowledged, a new settings with a different stream window size. + // For fanciness, we change it twice. + try self.assertSettingsUpdateWithAck([HTTP2Setting(parameter: .initialWindowSize, value: 60000), HTTP2Setting(parameter: .initialWindowSize, value: 50000)], sender: self.clientChannel, receiver: self.serverChannel) + let events = recorder.events.compactMap { $0 as? NIOHTTP2BulkStreamWindowChangeEvent } + XCTAssertEqual(events, [NIOHTTP2BulkStreamWindowChangeEvent(delta: -15535)]) + + // Let's do it again, just to prove it isn't a fluke. + try self.assertSettingsUpdateWithAck([HTTP2Setting(parameter: .initialWindowSize, value: 65535)], sender: self.clientChannel, receiver: self.serverChannel) + let newEvents = recorder.events.compactMap { $0 as? NIOHTTP2BulkStreamWindowChangeEvent } + XCTAssertEqual(newEvents, [NIOHTTP2BulkStreamWindowChangeEvent(delta: -15535), NIOHTTP2BulkStreamWindowChangeEvent(delta: 15535)]) + + XCTAssertNoThrow(try self.clientChannel.finish()) + XCTAssertNoThrow(try self.serverChannel.finish()) + } + + func testStreamMultiplexerAcknowledgesSettingsBasedFlowControlChanges() throws { + // This test verifies that the stream multiplexer pays attention to notifications about settings changes to flow + // control windows. It can't do that by *raising* the flow control window, as that information is duplicated in the + // stream flow control change notifications sent by receiving data frames. So it must do it by *shrinking* the window. + + // Begin by getting the connection up and add a stream multiplexer. + try self.basicHTTP2Connection() + XCTAssertNoThrow(try self.serverChannel.pipeline.addHandler(HTTP2StreamMultiplexer(mode: .server, channel: self.serverChannel)).wait()) + + var largeBuffer = self.clientChannel.allocator.buffer(capacity: 32767) + largeBuffer.writeBytes(repeatElement(UInt8(0xFF), count: 32767)) + + // Let's open a stream, and write a DATA frame that consumes slightly less than half the window. + let headers = HPACKHeaders([(":path", "/"), (":method", "GET"), (":scheme", "https"), (":authority", "localhost")]) + let headersFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: headers))) + let bodyFrame = HTTP2Frame(streamID: 1, payload: .data(.init(data: .byteBuffer(largeBuffer)))) + + self.clientChannel.write(headersFrame, promise: nil) + self.clientChannel.writeAndFlush(bodyFrame, promise: nil) + self.interactInMemory(self.clientChannel, self.serverChannel) + + // No window update frame should be emitted. + self.clientChannel.assertNoFramesReceived() + self.serverChannel.assertNoFramesReceived() + + // Now have the server shrink the client's flow control window. + // When it does this, the stream multiplexer will be told, and the stream will set its new expected maintained window size accordingly. + // However, the new *actual* window size will now be small enough to emit a window update for. Note that the connection will not have a window + // update frame sent as well maintain its size. + try self.assertSettingsUpdateWithAck([(HTTP2Setting(parameter: .initialWindowSize, value: 32768))], sender: self.serverChannel, receiver: self.clientChannel) + try self.clientChannel.assertReceivedFrame().assertWindowUpdateFrame(streamID: 1, windowIncrement: 32767) + self.clientChannel.assertNoFramesReceived() + self.serverChannel.assertNoFramesReceived() + + // Shrink it further. We shouldn't emit another window update. + try self.assertSettingsUpdateWithAck([(HTTP2Setting(parameter: .initialWindowSize, value: 16384))], sender: self.serverChannel, receiver: self.clientChannel) + self.clientChannel.assertNoFramesReceived() + self.serverChannel.assertNoFramesReceived() + + // And resize up. No window update either. + try self.assertSettingsUpdateWithAck([(HTTP2Setting(parameter: .initialWindowSize, value: 65535))], sender: self.serverChannel, receiver: self.clientChannel) + self.clientChannel.assertNoFramesReceived() + self.serverChannel.assertNoFramesReceived() + + XCTAssertNoThrow(try self.clientChannel.finish()) + XCTAssertNoThrow(try self.serverChannel.finish()) + } }