diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..08891d8 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,8 @@ +root = true + +[*] +indent_style = space +indent_size = 4 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true \ No newline at end of file diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml index 9c2e2a8..e1dcf6f 100644 --- a/.github/workflows/pull_request.yml +++ b/.github/workflows/pull_request.yml @@ -10,7 +10,7 @@ jobs: uses: swiftlang/github-workflows/.github/workflows/soundness.yml@main with: license_header_check_project_name: "SwiftNIO" - format_check_enabled: false + format_check_enabled: true shell_check_enabled: false unit-tests: diff --git a/.swift-format b/.swift-format new file mode 100644 index 0000000..7fa06fb --- /dev/null +++ b/.swift-format @@ -0,0 +1,62 @@ +{ + "version" : 1, + "indentation" : { + "spaces" : 4 + }, + "tabWidth" : 4, + "fileScopedDeclarationPrivacy" : { + "accessLevel" : "private" + }, + "spacesAroundRangeFormationOperators" : false, + "indentConditionalCompilationBlocks" : false, + "indentSwitchCaseLabels" : false, + "lineBreakAroundMultilineExpressionChainComponents" : false, + "lineBreakBeforeControlFlowKeywords" : false, + "lineBreakBeforeEachArgument" : true, + "lineBreakBeforeEachGenericRequirement" : true, + "lineLength" : 120, + "maximumBlankLines" : 1, + "respectsExistingLineBreaks" : true, + "prioritizeKeepingFunctionOutputTogether" : true, + "rules" : { + "AllPublicDeclarationsHaveDocumentation" : false, + "AlwaysUseLiteralForEmptyCollectionInit" : false, + "AlwaysUseLowerCamelCase" : false, + "AmbiguousTrailingClosureOverload" : true, + "BeginDocumentationCommentWithOneLineSummary" : false, + "DoNotUseSemicolons" : true, + "DontRepeatTypeInStaticProperties" : true, + "FileScopedDeclarationPrivacy" : true, + "FullyIndirectEnum" : true, + "GroupNumericLiterals" : true, + "IdentifiersMustBeASCII" : true, + "NeverForceUnwrap" : false, + "NeverUseForceTry" : false, + "NeverUseImplicitlyUnwrappedOptionals" : false, + "NoAccessLevelOnExtensionDeclaration" : true, + "NoAssignmentInExpressions" : true, + "NoBlockComments" : true, + "NoCasesWithOnlyFallthrough" : true, + "NoEmptyTrailingClosureParentheses" : true, + "NoLabelsInCasePatterns" : true, + "NoLeadingUnderscores" : false, + "NoParensAroundConditions" : true, + "NoVoidReturnOnFunctionSignature" : true, + "OmitExplicitReturns" : true, + "OneCasePerLine" : true, + "OneVariableDeclarationPerLine" : true, + "OnlyOneTrailingClosureArgument" : true, + "OrderedImports" : true, + "ReplaceForEachWithForLoop" : true, + "ReturnVoidInsteadOfEmptyTuple" : true, + "UseEarlyExits" : false, + "UseExplicitNilCheckInConditions" : false, + "UseLetInEveryBoundCaseVariable" : false, + "UseShorthandTypeNames" : true, + "UseSingleLinePropertyGetter" : false, + "UseSynthesizedInitializer" : false, + "UseTripleSlashForDocumentationComments" : true, + "UseWhereClausesInForLoops" : false, + "ValidateDocumentationComments" : false + } +} diff --git a/FuzzTesting/Package.swift b/FuzzTesting/Package.swift index c612408..5bc5cd5 100644 --- a/FuzzTesting/Package.swift +++ b/FuzzTesting/Package.swift @@ -30,6 +30,6 @@ let package = Package( .product(name: "NIOCore", package: "swift-nio"), .product(name: "NIOEmbedded", package: "swift-nio"), ] - ), + ) ] ) diff --git a/FuzzTesting/Sources/FuzzHTTP2/main.swift b/FuzzTesting/Sources/FuzzHTTP2/main.swift index 02d8ed2..734a74c 100644 --- a/FuzzTesting/Sources/FuzzHTTP2/main.swift +++ b/FuzzTesting/Sources/FuzzHTTP2/main.swift @@ -19,22 +19,20 @@ // See LICENSE.txt for license information: // https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt - import Foundation - import NIOCore import NIOEmbedded import NIOHTTP1 import NIOHTTP2 -fileprivate func fuzzInput(_ bytes: UnsafeRawBufferPointer) throws { +private func fuzzInput(_ bytes: UnsafeRawBufferPointer) throws { let channel = EmbeddedChannel() defer { _ = try? channel.finish() } _ = try channel.configureHTTP2Pipeline( mode: .server, - initialLocalSettings: [HTTP2Setting(parameter: .maxConcurrentStreams, value: 1<<23)], + initialLocalSettings: [HTTP2Setting(parameter: .maxConcurrentStreams, value: 1 << 23)], inboundStreamInitializer: nil ).wait() try channel.connect(to: SocketAddress(unixDomainSocketPath: "/foo")).wait() @@ -48,12 +46,12 @@ fileprivate func fuzzInput(_ bytes: UnsafeRawBufferPointer) throws { @_cdecl("LLVMFuzzerTestOneInput") public func FuzzServer(_ start: UnsafeRawPointer, _ count: Int) -> CInt { - let bytes = UnsafeRawBufferPointer(start: start, count: count) - do { - let _ = try fuzzInput(bytes) - } catch { - // Errors parsing are to be expected since not all inputs will be well formed. - } + let bytes = UnsafeRawBufferPointer(start: start, count: count) + do { + let _ = try fuzzInput(bytes) + } catch { + // Errors parsing are to be expected since not all inputs will be well formed. + } - return 0 + return 0 } diff --git a/IntegrationTests/tests_01_allocation_counters/test_01_resources/shared.swift b/IntegrationTests/tests_01_allocation_counters/test_01_resources/shared.swift index d483870..06ede5a 100644 --- a/IntegrationTests/tests_01_allocation_counters/test_01_resources/shared.swift +++ b/IntegrationTests/tests_01_allocation_counters/test_01_resources/shared.swift @@ -18,21 +18,27 @@ import NIOHTTP2 /// Test use only. Allows abstracting over the two multiplexer implementations to write common testing code internal protocol MultiplexerChannelCreator { - func createStreamChannel(promise: EventLoopPromise?, _ streamStateInitializer: @escaping NIOHTTP2Handler.StreamInitializer) + func createStreamChannel( + promise: EventLoopPromise?, + _ streamStateInitializer: @escaping NIOHTTP2Handler.StreamInitializer + ) func createStreamChannel(_ initializer: @escaping NIOChannelInitializer) -> EventLoopFuture } -extension HTTP2StreamMultiplexer: MultiplexerChannelCreator { } -extension NIOHTTP2Handler.StreamMultiplexer: MultiplexerChannelCreator { } +extension HTTP2StreamMultiplexer: MultiplexerChannelCreator {} +extension NIOHTTP2Handler.StreamMultiplexer: MultiplexerChannelCreator {} /// Have two `EmbeddedChannel` objects send and receive data from each other until /// they make no forward progress. func interactInMemory(_ first: EmbeddedChannel, _ second: EmbeddedChannel) throws { - precondition(first.eventLoop === second.eventLoop, "interactInMemory assumes both channels are on the same event loop.") + precondition( + first.eventLoop === second.eventLoop, + "interactInMemory assumes both channels are on the same event loop." + ) var operated: Bool func readBytesFromChannel(_ channel: EmbeddedChannel) throws -> ByteBuffer? { - return try channel.readOutbound(as: ByteBuffer.self) + try channel.readOutbound(as: ByteBuffer.self) } repeat { diff --git a/IntegrationTests/tests_01_allocation_counters/test_01_resources/test_1k_requests.swift b/IntegrationTests/tests_01_allocation_counters/test_01_resources/test_1k_requests.swift index 01ad4d1..bc39b84 100644 --- a/IntegrationTests/tests_01_allocation_counters/test_01_resources/test_1k_requests.swift +++ b/IntegrationTests/tests_01_allocation_counters/test_01_resources/test_1k_requests.swift @@ -52,9 +52,12 @@ struct ServerOnly1KRequestsBenchmark { headers.add(name: ":authority", value: "localhost", indexing: .nonIndexable) headers.add(name: ":path", value: "/", indexing: .indexable) headers.add(name: ":scheme", value: "https", indexing: .indexable) - headers.add(name: "user-agent", - value: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36", - indexing: .nonIndexable) + headers.add( + name: "user-agent", + value: + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36", + indexing: .nonIndexable + ) headers.add(name: "accept-encoding", value: "gzip, deflate", indexing: .indexable) var hpackEncoder = HPACKEncoder(allocator: .init()) @@ -108,7 +111,7 @@ struct ServerOnly1KRequestsBenchmark { return settingsCopy } - init(concurrentStreams: Int, pipelineConfigurator: (Channel) throws -> ()) throws { + init(concurrentStreams: Int, pipelineConfigurator: (Channel) throws -> Void) throws { self.concurrentStreams = concurrentStreams self.channel = EmbeddedChannel() @@ -122,7 +125,7 @@ struct ServerOnly1KRequestsBenchmark { initialBytes.writeImmutableBuffer(self.settingsACK) try self.channel.writeInbound(initialBytes) - while try self.channel.readOutbound(as: ByteBuffer.self) != nil { } + while try self.channel.readOutbound(as: ByteBuffer.self) != nil {} } func tearDown() { @@ -142,7 +145,7 @@ struct ServerOnly1KRequestsBenchmark { private mutating func sendInterleavedRequests(_ interleavedRequests: Int) throws -> Int { var streamID = self.streamID - for _ in 0 ..< interleavedRequests { + for _ in 0.. EventLoopFuture in - return streamChannel.pipeline.addHandler(TestServer()) + streamChannel.pipeline.addHandler(TestServer()) }.wait() } measure(identifier: identifier + "_interleaved") { - return try! interleaved.run() + try! interleaved.run() } interleaved.tearDown() var noninterleaved = try! ServerOnly1KRequestsBenchmark(concurrentStreams: 1) { channel in _ = try channel.configureHTTP2Pipeline(mode: .server) { streamChannel -> EventLoopFuture in - return streamChannel.pipeline.addHandler(TestServer()) + streamChannel.pipeline.addHandler(TestServer()) }.wait() } measure(identifier: identifier + "_noninterleaved") { - return try! noninterleaved.run() + try! noninterleaved.run() } noninterleaved.tearDown() @@ -223,25 +226,33 @@ func run(identifier: String) { // // MARK: - Inline HTTP2 multiplexer tests var inlineInterleaved = try! ServerOnly1KRequestsBenchmark(concurrentStreams: 100) { channel in - _ = try channel.configureHTTP2Pipeline(mode: .server, connectionConfiguration: .init(), streamConfiguration: .init()) { streamChannel -> EventLoopFuture in - return streamChannel.pipeline.addHandler(TestServer()) + _ = try channel.configureHTTP2Pipeline( + mode: .server, + connectionConfiguration: .init(), + streamConfiguration: .init() + ) { streamChannel -> EventLoopFuture in + streamChannel.pipeline.addHandler(TestServer()) }.wait() } measure(identifier: identifier + "_inline_interleaved") { - return try! inlineInterleaved.run() + try! inlineInterleaved.run() } inlineInterleaved.tearDown() var inlineNoninterleaved = try! ServerOnly1KRequestsBenchmark(concurrentStreams: 1) { channel in - _ = try channel.configureHTTP2Pipeline(mode: .server, connectionConfiguration: .init(), streamConfiguration: .init()) { streamChannel -> EventLoopFuture in - return streamChannel.pipeline.addHandler(TestServer()) + _ = try channel.configureHTTP2Pipeline( + mode: .server, + connectionConfiguration: .init(), + streamConfiguration: .init() + ) { streamChannel -> EventLoopFuture in + streamChannel.pipeline.addHandler(TestServer()) }.wait() } measure(identifier: identifier + "_inline_noninterleaved") { - return try! inlineNoninterleaved.run() + try! inlineNoninterleaved.run() } inlineNoninterleaved.tearDown() diff --git a/IntegrationTests/tests_01_allocation_counters/test_01_resources/test_client_server_h1_request_response.swift b/IntegrationTests/tests_01_allocation_counters/test_01_resources/test_client_server_h1_request_response.swift index 2737da2..b334e59 100644 --- a/IntegrationTests/tests_01_allocation_counters/test_01_resources/test_client_server_h1_request_response.swift +++ b/IntegrationTests/tests_01_allocation_counters/test_01_resources/test_client_server_h1_request_response.swift @@ -39,14 +39,18 @@ final class ServerHandler: ChannelInboundHandler { } } - final class ClientHandler: ChannelInboundHandler { typealias InboundIn = HTTPClientResponsePart typealias OutboundOut = HTTPClientRequestPart func channelActive(context: ChannelHandlerContext) { // Send a request. - let head = HTTPRequestHead(version: .init(major: 2, minor: 0), method: .GET, uri: "/", headers: HTTPHeaders([("host", "localhost")])) + let head = HTTPRequestHead( + version: .init(major: 2, minor: 0), + method: .GET, + uri: "/", + headers: HTTPHeaders([("host", "localhost")]) + ) context.write(self.wrapOutboundOut(.head(head)), promise: nil) context.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil) } @@ -54,27 +58,39 @@ final class ClientHandler: ChannelInboundHandler { func run(identifier: String) { testRun(identifier: identifier) { clientChannel in - return try! clientChannel.configureHTTP2Pipeline(mode: .client, inboundStreamInitializer: nil).wait() + try! clientChannel.configureHTTP2Pipeline(mode: .client, inboundStreamInitializer: nil).wait() } serverPipelineConfigurator: { serverChannel in _ = try! serverChannel.configureHTTP2Pipeline(mode: .server) { channel in - return channel.pipeline.addHandlers([HTTP2FramePayloadToHTTP1ServerCodec(), ServerHandler()]) + channel.pipeline.addHandlers([HTTP2FramePayloadToHTTP1ServerCodec(), ServerHandler()]) }.wait() } // // MARK: - Inline HTTP2 multiplexer tests testRun(identifier: identifier + "_inline") { clientChannel in - return try! clientChannel.configureHTTP2Pipeline(mode: .client, connectionConfiguration: .init(), streamConfiguration: .init()) { channel in - return channel.eventLoop.makeSucceededVoidFuture() + try! clientChannel.configureHTTP2Pipeline( + mode: .client, + connectionConfiguration: .init(), + streamConfiguration: .init() + ) { channel in + channel.eventLoop.makeSucceededVoidFuture() }.wait() } serverPipelineConfigurator: { serverChannel in - _ = try! serverChannel.configureHTTP2Pipeline(mode: .server, connectionConfiguration: .init(), streamConfiguration: .init()) { channel in - return channel.pipeline.addHandlers([HTTP2FramePayloadToHTTP1ServerCodec(), ServerHandler()]) + _ = try! serverChannel.configureHTTP2Pipeline( + mode: .server, + connectionConfiguration: .init(), + streamConfiguration: .init() + ) { channel in + channel.pipeline.addHandlers([HTTP2FramePayloadToHTTP1ServerCodec(), ServerHandler()]) }.wait() } } -private func testRun(identifier: String, clientPipelineConfigurator: (Channel) throws -> MultiplexerChannelCreator, serverPipelineConfigurator: (Channel) throws -> ()) { +private func testRun( + identifier: String, + clientPipelineConfigurator: (Channel) throws -> MultiplexerChannelCreator, + serverPipelineConfigurator: (Channel) throws -> Void +) { let loop = EmbeddedEventLoop() measure(identifier: identifier) { @@ -91,7 +107,9 @@ private func testRun(identifier: String, clientPipelineConfigurator: (Channel) t let promise = clientChannel.eventLoop.makePromise(of: Channel.self) clientMultiplexer.createStreamChannel(promise: promise) { channel in - return channel.pipeline.addHandlers([HTTP2FramePayloadToHTTP1ClientCodec(httpProtocol: .https), ClientHandler()]) + channel.pipeline.addHandlers([ + HTTP2FramePayloadToHTTP1ClientCodec(httpProtocol: .https), ClientHandler(), + ]) } clientChannel.embeddedEventLoop.run() let child = try! promise.futureResult.wait() @@ -108,4 +126,3 @@ private func testRun(identifier: String, clientPipelineConfigurator: (Channel) t return sumOfStreamIDs } } - diff --git a/IntegrationTests/tests_01_allocation_counters/test_01_resources/test_client_server_request_response.swift b/IntegrationTests/tests_01_allocation_counters/test_01_resources/test_client_server_request_response.swift index 25bdeb7..08e9e6a 100644 --- a/IntegrationTests/tests_01_allocation_counters/test_01_resources/test_client_server_request_response.swift +++ b/IntegrationTests/tests_01_allocation_counters/test_01_resources/test_client_server_request_response.swift @@ -41,7 +41,6 @@ final class ServerHandler: ChannelInboundHandler { } } - final class ClientHandler: ChannelInboundHandler { typealias InboundIn = HTTP2Frame.FramePayload typealias OutboundOut = HTTP2Frame.FramePayload @@ -56,10 +55,12 @@ final class ClientHandler: ChannelInboundHandler { func channelActive(context: ChannelHandlerContext) { // Send a request. - let headers = HPACKHeaders([(":path", "/"), - (":authority", "localhost"), - (":method", "GET"), - (":scheme", "https")]) + let headers = HPACKHeaders([ + (":path", "/"), + (":authority", "localhost"), + (":method", "GET"), + (":scheme", "https"), + ]) if self.dataBlockCount > 0 { let requestFramePayload = HTTP2Frame.FramePayload.headers(.init(headers: headers, endStream: false)) @@ -67,10 +68,18 @@ final class ClientHandler: ChannelInboundHandler { let buffer = ByteBuffer(repeating: 0, count: self.dataBlockLengthBytes) - for _ in 0 ..< self.dataBlockCount-1 { - context.write(self.wrapOutboundOut(HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(buffer), endStream: false))), promise: nil) + for _ in 0.. MultiplexerChannelCreator, serverPipelineConfigurator: (Channel) throws -> ()) { +private func testRun( + identifier: String, + dataBlockCount: Int = 0, + dataBlockLengthBytes: Int = 0, + clientPipelineConfigurator: (Channel) throws -> MultiplexerChannelCreator, + serverPipelineConfigurator: (Channel) throws -> Void +) { let loop = EmbeddedEventLoop() measure(identifier: identifier) { @@ -139,7 +170,9 @@ private func testRun(identifier: String, dataBlockCount: Int = 0, dataBlockLengt let promise = clientChannel.eventLoop.makePromise(of: Channel.self) clientMultiplexer.createStreamChannel(promise: promise) { channel in - return channel.pipeline.addHandler(ClientHandler(dataBlockCount: dataBlockCount, dataBlockLengthBytes: dataBlockLengthBytes)) + channel.pipeline.addHandler( + ClientHandler(dataBlockCount: dataBlockCount, dataBlockLengthBytes: dataBlockLengthBytes) + ) } clientChannel.embeddedEventLoop.run() let child = try! promise.futureResult.wait() @@ -156,4 +189,3 @@ private func testRun(identifier: String, dataBlockCount: Int = 0, dataBlockLengt return sumOfStreamIDs } } - diff --git a/IntegrationTests/tests_01_allocation_counters/test_01_resources/test_create_client_stream_channel.swift b/IntegrationTests/tests_01_allocation_counters/test_01_resources/test_create_client_stream_channel.swift index 8a304eb..0681d11 100644 --- a/IntegrationTests/tests_01_allocation_counters/test_01_resources/test_create_client_stream_channel.swift +++ b/IntegrationTests/tests_01_allocation_counters/test_01_resources/test_create_client_stream_channel.swift @@ -18,14 +18,13 @@ import NIOHPACK import NIOHTTP1 import NIOHTTP2 - func run(identifier: String) { testRun(identifier: identifier, usePromiseBasedAPI: true) { channel in let http2Handler = NIOHTTP2Handler(mode: .client) let multiplexer = HTTP2StreamMultiplexer(mode: .client, channel: channel, inboundStreamInitializer: nil) try! channel.pipeline.addHandlers([ http2Handler, - multiplexer + multiplexer, ]).wait() return multiplexer } @@ -35,7 +34,7 @@ func run(identifier: String) { let multiplexer = HTTP2StreamMultiplexer(mode: .client, channel: channel, inboundStreamInitializer: nil) try! channel.pipeline.addHandlers([ http2Handler, - multiplexer + multiplexer, ]).wait() return multiplexer } @@ -43,7 +42,7 @@ func run(identifier: String) { // MARK: - Inline HTTP2 multiplexer tests testRun(identifier: identifier + "_inline", usePromiseBasedAPI: true) { channel in let http2Handler = NIOHTTP2Handler(mode: .client, eventLoop: channel.eventLoop) { channel in - return channel.eventLoop.makeSucceededVoidFuture() + channel.eventLoop.makeSucceededVoidFuture() } try! channel.pipeline.addHandler(http2Handler).wait() return try! http2Handler.multiplexer.wait() @@ -51,7 +50,7 @@ func run(identifier: String) { testRun(identifier: identifier + "_inline_no_promise_based_API", usePromiseBasedAPI: false) { channel in let http2Handler = NIOHTTP2Handler(mode: .client, eventLoop: channel.eventLoop) { channel in - return channel.eventLoop.makeSucceededVoidFuture() + channel.eventLoop.makeSucceededVoidFuture() } try! channel.pipeline.addHandler(http2Handler).wait() return try! http2Handler.multiplexer.wait() @@ -75,12 +74,12 @@ private func testRun( if usePromiseBasedAPI { let promise = channel.eventLoop.makePromise(of: Channel.self) multiplexer.createStreamChannel(promise: promise) { channel in - return channel.eventLoop.makeSucceededFuture(()) + channel.eventLoop.makeSucceededFuture(()) } channelFuture = promise.futureResult } else { channelFuture = multiplexer.createStreamChannel { channel in - return channel.eventLoop.makeSucceededFuture(()) + channel.eventLoop.makeSucceededFuture(()) } } channel.embeddedEventLoop.run() diff --git a/IntegrationTests/tests_01_allocation_counters/test_01_resources/test_hpack_decoding.swift b/IntegrationTests/tests_01_allocation_counters/test_01_resources/test_hpack_decoding.swift index 6bfe98b..26ba662 100644 --- a/IntegrationTests/tests_01_allocation_counters/test_01_resources/test_hpack_decoding.swift +++ b/IntegrationTests/tests_01_allocation_counters/test_01_resources/test_hpack_decoding.swift @@ -13,18 +13,24 @@ //===----------------------------------------------------------------------===// import NIOCore -import NIOHTTP2 import NIOHPACK +import NIOHTTP2 func run(identifier: String) { var buffer = ByteBufferAllocator().buffer(capacity: 128) - buffer.writeBytes([0x82, 0x86, 0x84, 0x41, 0x0f, 0x77, 0x77, 0x77, 0x2e, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x2e, 0x63, 0x6f, 0x6d]) + buffer.writeBytes([ + 0x82, 0x86, 0x84, 0x41, 0x0f, 0x77, 0x77, 0x77, 0x2e, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x2e, 0x63, + 0x6f, 0x6d, + ]) let request1 = buffer buffer.clear() buffer.writeBytes([0x82, 0x86, 0x84, 0xbe, 0x58, 0x08, 0x6e, 0x6f, 0x2d, 0x63, 0x61, 0x63, 0x68, 0x65]) let request2 = buffer buffer.clear() - buffer.writeBytes([0x82, 0x87, 0x85, 0xbf, 0x40, 0x0a, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x2d, 0x6b, 0x65, 0x79, 0x0c, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x2d, 0x76, 0x61, 0x6c, 0x75, 0x65]) + buffer.writeBytes([ + 0x82, 0x87, 0x85, 0xbf, 0x40, 0x0a, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x2d, 0x6b, 0x65, 0x79, 0x0c, 0x63, + 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x2d, 0x76, 0x61, 0x6c, 0x75, 0x65, + ]) let request3 = buffer measure(identifier: identifier) { diff --git a/IntegrationTests/tests_01_allocation_counters/test_01_resources/test_stream_teardown_100_concurrent.swift b/IntegrationTests/tests_01_allocation_counters/test_01_resources/test_stream_teardown_100_concurrent.swift index fe96d84..53cf887 100644 --- a/IntegrationTests/tests_01_allocation_counters/test_01_resources/test_stream_teardown_100_concurrent.swift +++ b/IntegrationTests/tests_01_allocation_counters/test_01_resources/test_stream_teardown_100_concurrent.swift @@ -12,11 +12,11 @@ // //===----------------------------------------------------------------------===// +import Atomics import NIOCore import NIOEmbedded import NIOHPACK import NIOHTTP2 -import Atomics struct StreamTeardownBenchmark { private let concurrentStreams: Int @@ -28,9 +28,12 @@ struct StreamTeardownBenchmark { headers.add(name: ":authority", value: "localhost", indexing: .nonIndexable) headers.add(name: ":path", value: "/", indexing: .indexable) headers.add(name: ":scheme", value: "https", indexing: .indexable) - headers.add(name: "user-agent", - value: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36", - indexing: .nonIndexable) + headers.add( + name: "user-agent", + value: + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36", + indexing: .nonIndexable + ) headers.add(name: "accept-encoding", value: "gzip, deflate", indexing: .indexable) var hpackEncoder = HPACKEncoder(allocator: .init()) @@ -88,7 +91,7 @@ struct StreamTeardownBenchmark { self.concurrentStreams = concurrentStreams } - private func createChannel(pipelineConfigurator: (Channel, Int) throws -> ()) throws -> EmbeddedChannel { + private func createChannel(pipelineConfigurator: (Channel, Int) throws -> Void) throws -> EmbeddedChannel { let channel = EmbeddedChannel() try! pipelineConfigurator(channel, self.concurrentStreams) @@ -100,7 +103,7 @@ struct StreamTeardownBenchmark { initialBytes.writeImmutableBuffer(self.settingsACK) try channel.writeInbound(initialBytes) - while try channel.readOutbound(as: ByteBuffer.self) != nil { } + while try channel.readOutbound(as: ByteBuffer.self) != nil {} return channel } @@ -109,7 +112,7 @@ struct StreamTeardownBenchmark { _ = try channel.finish() } - fileprivate mutating func run(pipelineConfigurator: (Channel, Int) throws -> ()) throws -> Int { + fileprivate mutating func run(pipelineConfigurator: (Channel, Int) throws -> Void) throws -> Int { var bodyByteCount = 0 var completedIterations = 0 while completedIterations < 10_000 { @@ -121,10 +124,13 @@ struct StreamTeardownBenchmark { return bodyByteCount } - private mutating func sendInterleavedRequestsAndTerminate(_ interleavedRequests: Int, _ channel: EmbeddedChannel) throws -> Int { + private mutating func sendInterleavedRequestsAndTerminate( + _ interleavedRequests: Int, + _ channel: EmbeddedChannel + ) throws -> Int { var streamID = HTTP2StreamID(1) - for _ in 0 ..< interleavedRequests { + for _ in 0.. EventLoopFuture in - return streamChannel.pipeline.addHandler(DoNothingServer()) + streamChannel.pipeline.addHandler(DoNothingServer()) }.wait() try channel.pipeline.addHandler(SendGoawayHandler(expectedStreams: concurrentStreams)).wait() } } measure(identifier: identifier + "_inline") { - return try! benchmark.run() { channel, concurrentStreams in + try! benchmark.run { channel, concurrentStreams in _ = try channel.configureHTTP2Pipeline( mode: .server, connectionConfiguration: .init(), streamConfiguration: .init(), streamDelegate: SendGoawayDelegate(expectedStreams: concurrentStreams) ) { streamChannel -> EventLoopFuture in - return streamChannel.pipeline.addHandler(DoNothingServer()) + streamChannel.pipeline.addHandler(DoNothingServer()) }.wait() } } } - diff --git a/Package.swift b/Package.swift index 85d4cbf..36c6dec 100644 --- a/Package.swift +++ b/Package.swift @@ -18,7 +18,7 @@ import PackageDescription let package = Package( name: "swift-nio-http2", products: [ - .library(name: "NIOHTTP2", targets: ["NIOHTTP2"]), + .library(name: "NIOHTTP2", targets: ["NIOHTTP2"]) ], dependencies: [ .package(url: "https://github.com/apple/swift-nio.git", from: "2.60.0"), @@ -32,7 +32,8 @@ let package = Package( .product(name: "NIOCore", package: "swift-nio"), .product(name: "NIOPosix", package: "swift-nio"), .product(name: "NIOHTTP1", package: "swift-nio"), - ]), + ] + ), .executableTarget( name: "NIOHTTP2PerformanceTester", dependencies: [ @@ -40,7 +41,8 @@ let package = Package( .product(name: "NIOCore", package: "swift-nio"), .product(name: "NIOPosix", package: "swift-nio"), .product(name: "NIOEmbedded", package: "swift-nio"), - ]), + ] + ), .target( name: "NIOHTTP2", dependencies: [ @@ -51,7 +53,8 @@ let package = Package( .product(name: "NIOTLS", package: "swift-nio"), .product(name: "NIOConcurrencyHelpers", package: "swift-nio"), .product(name: "Atomics", package: "swift-atomics"), - ]), + ] + ), .target( name: "NIOHPACK", dependencies: [ @@ -59,7 +62,8 @@ let package = Package( .product(name: "NIOCore", package: "swift-nio"), .product(name: "NIOConcurrencyHelpers", package: "swift-nio"), .product(name: "NIOHTTP1", package: "swift-nio"), - ]), + ] + ), .testTarget( name: "NIOHTTP2Tests", dependencies: [ @@ -70,7 +74,8 @@ let package = Package( .product(name: "NIOHTTP1", package: "swift-nio"), .product(name: "NIOFoundationCompat", package: "swift-nio"), .product(name: "Atomics", package: "swift-atomics"), - ]), + ] + ), .testTarget( name: "NIOHPACKTests", dependencies: [ @@ -82,6 +87,6 @@ let package = Package( .copy("Fixtures/large_complex_huffman_b64.txt"), .copy("Fixtures/large_huffman_b64.txt"), ] - ) + ), ] ) diff --git a/Sources/NIOHPACK/DynamicHeaderTable.swift b/Sources/NIOHPACK/DynamicHeaderTable.swift index 6b22dd9..076cd63 100644 --- a/Sources/NIOHPACK/DynamicHeaderTable.swift +++ b/Sources/NIOHPACK/DynamicHeaderTable.swift @@ -19,15 +19,15 @@ import NIOCore @usableFromInline struct DynamicHeaderTable: Sendable { public static let defaultSize = 4096 - + /// The actual table, with items looked up by index. private var storage: HeaderTableStorage - + /// The length of the contents of the table. var length: Int { - return self.storage.length + self.storage.length } - + /// The size to which the dynamic table may currently grow. Represents /// the current maximum length signaled by the peer via a table-resize /// value at the start of an encoded header block. @@ -35,13 +35,13 @@ struct DynamicHeaderTable: Sendable { /// - note: This value cannot exceed `self.maximumTableLength`. var allowedLength: Int { get { - return self.storage.maxSize + self.storage.maxSize } set { self.storage.setTableSize(to: newValue) } } - + /// The maximum permitted size of the dynamic header table as set /// through a SETTINGS_HEADER_TABLE_SIZE value in a SETTINGS frame. var maximumTableLength: Int { @@ -51,33 +51,34 @@ struct DynamicHeaderTable: Sendable { } } } - + /// The number of items in the table. var count: Int { - return self.storage.count + self.storage.count } - + init(maximumLength: Int = DynamicHeaderTable.defaultSize) { self.storage = HeaderTableStorage(maxSize: maximumLength) self.maximumTableLength = maximumLength - self.allowedLength = maximumLength // until we're told otherwise, this is what we assume the other side expects. + // until we're told otherwise, this is what we assume the other side expects. + self.allowedLength = maximumLength } - + /// Subscripts into the dynamic table alone, using a zero-based index. subscript(i: Int) -> HeaderTableEntry { - return self.storage[i] + self.storage[i] } - + // internal for testing func dumpHeaders() -> String { - return self.storage.dumpHeaders(offsetBy: StaticHeaderTable.count) + self.storage.dumpHeaders(offsetBy: StaticHeaderTable.count) } - + // internal for testing -- clears the dynamic table mutating func clear() { self.storage.purge(toRelease: self.storage.length) } - + /// Searches the table for a matching header, optionally with a particular value. If /// a match is found, returns the index of the item and an indication whether it contained /// the matching value as well. @@ -97,7 +98,7 @@ struct DynamicHeaderTable: Sendable { // no `first` on AnySequence, just `first(where:)` return self.storage.firstIndex(matching: name).map { ($0, false) } } - + // If we have a value, locate the index of the lowest header which contains that // value, but if no value matches, return the index of the lowest header with a // matching name alone. @@ -110,7 +111,7 @@ struct DynamicHeaderTable: Sendable { return nil } } - + /// Appends a header to the table. Note that if this succeeds, the new item's index /// is always zero. /// diff --git a/Sources/NIOHPACK/HPACKDecoder.swift b/Sources/NIOHPACK/HPACKDecoder.swift index f7e0ab0..f341bcf 100644 --- a/Sources/NIOHPACK/HPACKDecoder.swift +++ b/Sources/NIOHPACK/HPACKDecoder.swift @@ -27,7 +27,7 @@ import NIOCore /// by a single HTTP/2 stream, operating on a single NIO `EventLoop`. public struct HPACKDecoder: Sendable { public static var maxDynamicTableSize: Int { - return DynamicHeaderTable.defaultSize + DynamicHeaderTable.defaultSize } /// The default value of the maximum header list size for the decoder. @@ -35,20 +35,20 @@ public struct HPACKDecoder: Sendable { /// This value is somewhat arbitrary, but 16kB should be sufficiently large to decode all reasonably /// sized header lists. public static var defaultMaxHeaderListSize: Int { - return 1<<14 + 1 << 14 } - + // private but tests var headerTable: IndexedHeaderTable - + var dynamicTableLength: Int { - return headerTable.dynamicTableLength + headerTable.dynamicTableLength } /// The current allowed length of the dynamic portion of the header table. May be /// less than the current protocol-assigned maximum supplied by a SETTINGS frame. public private(set) var allowedDynamicTableLength: Int { - get { return self.headerTable.dynamicTableAllowedLength } + get { self.headerTable.dynamicTableAllowedLength } set { self.headerTable.dynamicTableAllowedLength = newValue } } @@ -60,7 +60,7 @@ public struct HPACKDecoder: Sendable { enum HPACKString { case indexed(index: Int) case literal - + init(fromEncodedInteger value: Int) { switch value { case 0: @@ -70,23 +70,27 @@ public struct HPACKDecoder: Sendable { } } } - + /// The maximum size of the dynamic table as set by the enclosing protocol. This is defined in RFC 7541 /// to be the sum of [name-octet-count] + [value-octet-count] + 32 for /// each header it contains. public var maxDynamicTableLength: Int { - get { return headerTable.maxDynamicTableLength } - /* private but tests */ + get { headerTable.maxDynamicTableLength } + // private but tests set { headerTable.maxDynamicTableLength = newValue } } - + /// Creates a new decoder /// /// - Parameters: /// - allocator: Allocator for headers view byte buffer (which is deprecated) /// - maxDynamicTableSize: Maximum allowed size of the dynamic header table. public init(allocator: ByteBufferAllocator, maxDynamicTableSize: Int = HPACKDecoder.maxDynamicTableSize) { - self.init(allocator: allocator, maxDynamicTableSize: maxDynamicTableSize, maxHeaderListSize: HPACKDecoder.defaultMaxHeaderListSize) + self.init( + allocator: allocator, + maxDynamicTableSize: maxDynamicTableSize, + maxHeaderListSize: HPACKDecoder.defaultMaxHeaderListSize + ) } /// Creates a new decoder @@ -100,7 +104,7 @@ public struct HPACKDecoder: Sendable { self.headerTable = IndexedHeaderTable(allocator: allocator, maxDynamicTableSize: maxDynamicTableSize) self.maxHeaderListSize = maxHeaderListSize } - + /// Reads HPACK encoded header data from a `ByteBuffer`. /// /// It is expected that the buffer cover only the bytes of the header list, i.e. @@ -169,59 +173,79 @@ public struct HPACKDecoder: Sendable { throw NIOHPACKErrors.ZeroHeaderIndex() } return try .header(self.decodeIndexedHeader(from: Int(hidx))) - + case let x where x & 0b1100_0000 == 0b0100_0000: // 0b01xxxxxx -- two-bit prefix, six bits of value // literal header with possibly-indexed name let hidx = try buffer.readEncodedInteger(withPrefix: 6) - return try .header(self.decodeLiteralHeader(from: &buffer, headerName: HPACKString(fromEncodedInteger: hidx), addToIndex: true)) - + return try .header( + self.decodeLiteralHeader( + from: &buffer, + headerName: HPACKString(fromEncodedInteger: hidx), + addToIndex: true + ) + ) + case let x where x & 0b1111_0000 == 0b0000_0000: // 0b0000xxxx -- four-bit prefix, four bits of value // literal header with possibly-indexed name, not added to dynamic table let hidx = try buffer.readEncodedInteger(withPrefix: 4) - var header = try self.decodeLiteralHeader(from: &buffer, headerName: HPACKString(fromEncodedInteger: hidx), addToIndex: false) + var header = try self.decodeLiteralHeader( + from: &buffer, + headerName: HPACKString(fromEncodedInteger: hidx), + addToIndex: false + ) header.indexing = .nonIndexable return .header(header) - + case let x where x & 0b1111_0000 == 0b0001_0000: // 0b0001xxxx -- four-bit prefix, four bits of value // literal header with possibly-indexed name, never added to dynamic table nor // rewritten by proxies let hidx = try buffer.readEncodedInteger(withPrefix: 4) - var header = try self.decodeLiteralHeader(from: &buffer, headerName: HPACKString(fromEncodedInteger: hidx), addToIndex: false) + var header = try self.decodeLiteralHeader( + from: &buffer, + headerName: HPACKString(fromEncodedInteger: hidx), + addToIndex: false + ) header.indexing = .neverIndexed return .header(header) - + case let x where x & 0b1110_0000 == 0b0010_0000: // 0b001xxxxx -- three-bit prefix, five bits of value // dynamic header table size update let newMaxLength = try Int(buffer.readEncodedInteger(withPrefix: 5)) - + // RFC 7541 ยง 4.2 : // // 1. "the chosen size MUST stay lower than or equal to the maximum set by the protocol." guard newMaxLength <= self.headerTable.maxDynamicTableLength else { - throw NIOHPACKErrors.InvalidDynamicTableSize(requestedSize: newMaxLength, allowedSize: self.headerTable.maxDynamicTableLength) + throw NIOHPACKErrors.InvalidDynamicTableSize( + requestedSize: newMaxLength, + allowedSize: self.headerTable.maxDynamicTableLength + ) } - + self.allowedDynamicTableLength = newMaxLength return .tableSizeChange - + default: throw NIOHPACKErrors.InvalidHeaderStartByte(byte: initial) } } - + private mutating func decodeIndexedHeader(from hidx: Int) throws -> HPACKHeader { let (name, value) = try self.headerTable.header(at: hidx) return HPACKHeader(name: name, value: value) } - - private mutating func decodeLiteralHeader(from buffer: inout ByteBuffer, headerName: HPACKString, - addToIndex: Bool) throws -> HPACKHeader { + + private mutating func decodeLiteralHeader( + from buffer: inout ByteBuffer, + headerName: HPACKString, + addToIndex: Bool + ) throws -> HPACKHeader { let name: String - + switch headerName { case .indexed(let idx): (name, _) = try self.headerTable.header(at: idx) @@ -232,23 +256,23 @@ public struct HPACKDecoder: Sendable { throw NIOHPACKErrors.EmptyLiteralHeaderFieldName() } } - + let value = try self.readEncodedString(from: &buffer) - + if addToIndex { try headerTable.add(headerNamed: name, value: value) } - + return HPACKHeader(name: name, value: value) } - + private mutating func readEncodedString(from buffer: inout ByteBuffer) throws -> String { // peek to read the encoding bit guard let initialByte: UInt8 = buffer.getInteger(at: buffer.readerIndex) else { throw NIOHPACKErrors.InsufficientInput() } let huffmanEncoded = initialByte & 0x80 == 0x80 - + // read the length; there's a seven-bit prefix here (one-bit encoding flag) let len = try Int(buffer.readEncodedInteger(withPrefix: 7)) guard len <= buffer.readableBytes else { @@ -259,7 +283,7 @@ public struct HPACKDecoder: Sendable { return try buffer.readHuffmanEncodedString(length: len) } else { // This force-unwrap is safe as we have checked above that len is less than or equal to the buffer readable bytes. - return buffer.readString(length: len)! + return buffer.readString(length: len)! } } } diff --git a/Sources/NIOHPACK/HPACKEncoder.swift b/Sources/NIOHPACK/HPACKEncoder.swift index e0c5d41..ed8d724 100644 --- a/Sources/NIOHPACK/HPACKEncoder.swift +++ b/Sources/NIOHPACK/HPACKEncoder.swift @@ -24,53 +24,58 @@ import NIOCore /// RFC 7541, appending and evicting items as described there. public struct HPACKEncoder { /// The default size of the encoder's dynamic header table. - public static var defaultDynamicTableSize: Int { return DynamicHeaderTable.defaultSize } + public static var defaultDynamicTableSize: Int { DynamicHeaderTable.defaultSize } private static let defaultDataBufferSize = 128 - + public struct HeaderDefinition: Sendable { var name: String var value: String var indexing: HPACKIndexing } - + private enum EncoderState { case idle case resized(smallestMaxTableSize: Int?) case encoding } - + // private but tests var headerIndexTable: IndexedHeaderTable - + private var state: EncoderState private var buffer: ByteBuffer - + /// Whether to use Huffman encoding. public let useHuffmanEncoding: Bool - + /// The current size of the dynamic table. /// /// This is defined as the sum of [name] + [value] + 32 for each header. public var dynamicTableSize: Int { - return self.headerIndexTable.dynamicTableLength + self.headerIndexTable.dynamicTableLength } - + /// The current maximum size to which the dynamic header table may grow. public private(set) var allowedDynamicTableSize: Int { - get { return self.headerIndexTable.dynamicTableAllowedLength } + get { self.headerIndexTable.dynamicTableAllowedLength } set { self.headerIndexTable.dynamicTableAllowedLength = newValue } } - + /// The hard maximum size of the dynamic header table, set via an HTTP/2 /// SETTINGS frame. public var maximumDynamicTableSize: Int { - get { return self.headerIndexTable.maxDynamicTableLength } + get { self.headerIndexTable.maxDynamicTableLength } // This should have been private, but we messed up. Nevermind. - @available(*, deprecated, message: "Setting the dynamic table length on the HPACK encoder doesn't have the intended effect.", renamed: "setDynamicTableSize(_:)") + @available( + *, + deprecated, + message: "Setting the dynamic table length on the HPACK encoder doesn't have the intended effect.", + renamed: "setDynamicTableSize(_:)" + ) set { self.headerIndexTable.maxDynamicTableLength = newValue } } - + /// Sets the maximum size for the dynamic table and encodes the new value /// at the start of the current packed header block to send to the peer. /// @@ -82,7 +87,7 @@ public struct HPACKEncoder { // no need to change anything return } - + switch self.state { case .idle: self.state = .resized(smallestMaxTableSize: nil) @@ -96,19 +101,23 @@ public struct HPACKEncoder { // we don't need to change smallest recorded resize value break } - + // set the new size on our dynamic table self.headerIndexTable.maxDynamicTableLength = size self.allowedDynamicTableSize = size } - + /// Initializer and returns a new HPACK encoder. /// /// - Parameters: /// - allocator: An allocator for `ByteBuffer`s. /// - useHuffmanEncoding: Should huffman enccoding be used. /// - maxDynamicTableSize: An initial maximum size for the encoder's dynamic header table. - public init(allocator: ByteBufferAllocator, useHuffmanEncoding: Bool = true, maxDynamicTableSize: Int = HPACKEncoder.defaultDynamicTableSize) { + public init( + allocator: ByteBufferAllocator, + useHuffmanEncoding: Bool = true, + maxDynamicTableSize: Int = HPACKEncoder.defaultDynamicTableSize + ) { self.headerIndexTable = IndexedHeaderTable(allocator: allocator, maxDynamicTableSize: maxDynamicTableSize) self.useHuffmanEncoding = useHuffmanEncoding self.state = .idle @@ -117,7 +126,7 @@ public struct HPACKEncoder { // mode. I want to remove it: see https://github.com/apple/swift-nio-http2/issues/85. self.buffer = allocator.buffer(capacity: 128) } - + /// Sets up the encoder to begin encoding a new header block. /// /// - Parameter allocator: Used to allocate the `ByteBuffer` that will contain the encoded @@ -145,17 +154,17 @@ public struct HPACKEncoder { break } } - + /// Finishes encoding the current header block and returns the resulting buffer. public mutating func endEncoding() throws -> ByteBuffer { guard case .encoding = self.state else { throw NIOHPACKErrors.EncoderNotStarted() } - + self.state = .idle return self.buffer } - + /// A one-shot encoder that writes to a provided buffer. /// /// In general this encoding mechanism is more efficient than the incremental one. @@ -188,22 +197,22 @@ public struct HPACKEncoder { try self.append(headers: headers) } - + /// Appends() headers in the default fashion: indexed if possible, literal+indexable if not. /// /// - Parameter headers: A sequence of key/value pairs representing HTTP headers. public mutating func append(headers: S) throws where S.Element == (name: String, value: String) { try self.append(headers: headers.lazy.map { HeaderDefinition(name: $0.0, value: $0.1, indexing: .indexable) }) } - + /// Appends headers with their specified indexability. /// /// - Parameter headers: A sequence of key/value/indexability tuples representing HTTP headers. - public mutating func append(headers: S) throws where S.Element == HeaderDefinition { + public mutating func append(headers: S) throws where S.Element == HeaderDefinition { guard case .encoding = self.state else { throw NIOHPACKErrors.EncoderNotStarted() } - + for header in headers { switch header.indexing { case .indexable: @@ -215,7 +224,7 @@ public struct HPACKEncoder { } } } - + /// Appends a set of headers with their associated indexability. /// /// - Parameter headers: A `HPACKHeaders` structure containing a set of HTTP/2 header values. @@ -223,7 +232,7 @@ public struct HPACKEncoder { guard case .encoding = self.state else { throw NIOHPACKErrors.EncoderNotStarted() } - + for header in headers { switch header.indexable { case .indexable: @@ -235,7 +244,7 @@ public struct HPACKEncoder { } } } - + /// Appends a header/value pair, using indexed names/values if possible. If no indexed pair is available, /// it will use an indexed header and literal value, or a literal header and value. The name/value pair /// will be indexed for future use. @@ -245,7 +254,7 @@ public struct HPACKEncoder { } try self._appendIndexed(header: name, value: value) } - + /// Returns `true` if the item needs to be added to the header table private mutating func _appendIndexed(header name: String, value: String) throws { if let (index, hasValue) = self.headerIndexTable.firstHeaderMatch(for: name, value: value) { @@ -267,11 +276,11 @@ public struct HPACKEncoder { self.appendEncodedString(name) self.appendEncodedString(value) } - + // add to the header table try self.headerIndexTable.add(headerNamed: name, value: value) } - + private mutating func appendEncodedString(_ string: String) { let utf8 = string.utf8 @@ -279,14 +288,18 @@ public struct HPACKEncoder { if self.useHuffmanEncoding { // problem: we need to encode the length before the encoded bytes, so we can't just receive the length // after encoding to the target buffer itself. So we have to determine the length first. - self.buffer.write(encodedInteger: UInt64(ByteBuffer.huffmanEncodedLength(of: utf8)), prefix: 7, prefixBits: 0x80) + self.buffer.write( + encodedInteger: UInt64(ByteBuffer.huffmanEncodedLength(of: utf8)), + prefix: 7, + prefixBits: 0x80 + ) self.buffer.writeHuffmanEncoded(bytes: utf8) } else { self.buffer.write(encodedInteger: UInt64(utf8.count), prefix: 7, prefixBits: 0) self.buffer.writeBytes(utf8) } } - + /// Appends a header that is *not* to be entered into the dynamic header table, but allows that /// stipulation to be overriden by a proxy server/rewriter. public mutating func appendNonIndexed(header: String, value: String) throws { @@ -295,7 +308,7 @@ public struct HPACKEncoder { } self._appendNonIndexed(header: header, value: value) } - + private mutating func _appendNonIndexed(header: String, value: String) { if let (index, _) = self.headerIndexTable.firstHeaderMatch(for: header, value: nil) { // we actually don't care if it has a value in this instance; we're only indexing the @@ -304,12 +317,12 @@ public struct HPACKEncoder { // now append the value self.appendEncodedString(value) } else { - self.buffer.writeInteger(UInt8(0)) // top 4 bits are zero, and index is zero (no index) + self.buffer.writeInteger(UInt8(0)) // top 4 bits are zero, and index is zero (no index) self.appendEncodedString(header) self.appendEncodedString(value) } } - + /// Appends a header that is *never* indexed, preventing even rewriting proxies from doing so. public mutating func appendNeverIndexed(header: String, value: String) throws { guard case .encoding = self.state else { @@ -317,7 +330,7 @@ public struct HPACKEncoder { } self._appendNeverIndexed(header: header, value: value) } - + private mutating func _appendNeverIndexed(header: String, value: String) { if let (index, _) = self.headerIndexTable.firstHeaderMatch(for: header, value: nil) { // we only use the index in this instance @@ -325,7 +338,7 @@ public struct HPACKEncoder { // now append the value self.appendEncodedString(value) } else { - self.buffer.writeInteger(UInt8(0x10)) // prefix bits + zero index + self.buffer.writeInteger(UInt8(0x10)) // prefix bits + zero index self.appendEncodedString(header) self.appendEncodedString(value) } diff --git a/Sources/NIOHPACK/HPACKErrors.swift b/Sources/NIOHPACK/HPACKErrors.swift index fd3f020..dae3e0c 100644 --- a/Sources/NIOHPACK/HPACKErrors.swift +++ b/Sources/NIOHPACK/HPACKErrors.swift @@ -14,13 +14,13 @@ import NIOCore -public protocol NIOHPACKError : Error, Equatable { } +public protocol NIOHPACKError: Error, Equatable {} /// Errors raised by NIOHPACK while encoding/decoding data. public enum NIOHPACKErrors { /// An indexed header referenced an index that doesn't exist in our /// header tables. - public struct InvalidHeaderIndex : NIOHPACKError { + public struct InvalidHeaderIndex: NIOHPACKError { /// The offending index. public let suppliedIndex: Int @@ -31,14 +31,14 @@ public enum NIOHPACKErrors { /// A header block indicated an indexed header with no accompanying /// value, but the index referenced an entry with no value of its own /// e.g. one of the many valueless items in the static header table. - public struct IndexedHeaderWithNoValue : NIOHPACKError { + public struct IndexedHeaderWithNoValue: NIOHPACKError { /// The offending index. public let index: Int } /// An encoded string contained an invalid length that extended /// beyond its frame's payload size. - public struct StringLengthBeyondPayloadSize : NIOHPACKError { + public struct StringLengthBeyondPayloadSize: NIOHPACKError { /// The length supplied. public let length: Int @@ -47,20 +47,20 @@ public enum NIOHPACKErrors { } /// Decoded string data could not be parsed as valid UTF-8. - public struct InvalidUTF8Data : NIOHPACKError { + public struct InvalidUTF8Data: NIOHPACKError { /// The offending bytes. public let bytes: ByteBuffer } /// The start byte of a header did not match any format allowed by /// the HPACK specification. - public struct InvalidHeaderStartByte : NIOHPACKError { + public struct InvalidHeaderStartByte: NIOHPACKError { /// The offending byte. public let byte: UInt8 } /// A dynamic table size update specified an invalid size. - public struct InvalidDynamicTableSize : NIOHPACKError { + public struct InvalidDynamicTableSize: NIOHPACKError { /// The offending size. public let requestedSize: Int @@ -70,11 +70,12 @@ public enum NIOHPACKErrors { /// A dynamic table size update was found outside its allowed place. /// They may only be included at the start of a header block. - public struct IllegalDynamicTableSizeChange : NIOHPACKError {} + public struct IllegalDynamicTableSizeChange: NIOHPACKError {} /// A new header could not be added to the dynamic table. Usually /// this means the header itself is larger than the current /// dynamic table size. - public struct FailedToAddIndexedHeader : NIOHPACKError where Name.Element == UInt8, Value.Element == UInt8 { + public struct FailedToAddIndexedHeader: NIOHPACKError + where Name.Element == UInt8, Value.Element == UInt8 { /// The table size required to be able to add this header to the table. public let bytesNeeded: Int @@ -84,7 +85,10 @@ public enum NIOHPACKErrors { /// The value of the header that could not be written. public let value: Value - public static func == (lhs: NIOHPACKErrors.FailedToAddIndexedHeader, rhs: NIOHPACKErrors.FailedToAddIndexedHeader) -> Bool { + public static func == ( + lhs: NIOHPACKErrors.FailedToAddIndexedHeader, + rhs: NIOHPACKErrors.FailedToAddIndexedHeader + ) -> Bool { guard lhs.bytesNeeded == rhs.bytesNeeded else { return false } @@ -93,29 +97,29 @@ public enum NIOHPACKErrors { } /// Ran out of input bytes while decoding. - public struct InsufficientInput : NIOHPACKError {} + public struct InsufficientInput: NIOHPACKError {} /// HPACK encoder asked to begin a new header block while partway through encoding /// another block. - public struct EncoderAlreadyActive : NIOHPACKError {} + public struct EncoderAlreadyActive: NIOHPACKError {} /// HPACK encoder asked to append a header without first calling `beginEncoding(allocator:)`. - public struct EncoderNotStarted : NIOHPACKError {} + public struct EncoderNotStarted: NIOHPACKError {} /// HPACK decoder asked to decode an indexed header with index zero. public struct ZeroHeaderIndex: NIOHPACKError { - public init() { } + public init() {} } /// HPACK decoder asked to decode a header list that would violate the configured /// max header list size. public struct MaxHeaderListSizeViolation: NIOHPACKError { - public init() { } + public init() {} } /// HPACK decoder asked to decode a header field name that was empty. public struct EmptyLiteralHeaderFieldName: NIOHPACKError { - public init() { } + public init() {} } /// The integer being decoded is not representable by this implementation. diff --git a/Sources/NIOHPACK/HPACKHeader.swift b/Sources/NIOHPACK/HPACKHeader.swift index e4a7cd4..cfe84ba 100644 --- a/Sources/NIOHPACK/HPACKHeader.swift +++ b/Sources/NIOHPACK/HPACKHeader.swift @@ -39,8 +39,10 @@ public struct HPACKHeaders: ExpressibleByDictionaryLiteral, Sendable { // see 8.1.2.2. Connection-Specific Header Fields in RFC 7540 @usableFromInline - static let illegalHeaders: [String] = ["connection", "keep-alive", "proxy-connection", - "transfer-encoding", "upgrade"] + static let illegalNames: [String] = [ + "connection", "keep-alive", "proxy-connection", + "transfer-encoding", "upgrade", + ] /// Constructor that can be used to map between `HTTPHeaders` and `HPACKHeaders` types. @inlinable @@ -55,14 +57,14 @@ public struct HPACKHeaders: ExpressibleByDictionaryLiteral, Sendable { if connectionHeaderValue.count > Self.connectionHeaderValueArraySizeLimit { var headersToRemove = Set(connectionHeaderValue) // Since we have a set we can just merge in the illegal headers. - headersToRemove.formUnion(Self.illegalHeaders.lazy.map { $0[...] }) + headersToRemove.formUnion(Self.illegalNames.lazy.map { $0[...] }) self.headers.removeAll { header in headersToRemove.contains(header.name[...]) } } else { self.headers.removeAll { header in - connectionHeaderValue.contains(header.name[...]) || - HPACKHeaders.illegalHeaders.contains(header.name) + connectionHeaderValue.contains(header.name[...]) + || HPACKHeaders.illegalNames.contains(header.name) } } } else { @@ -153,7 +155,8 @@ public struct HPACKHeaders: ExpressibleByDictionaryLiteral, Sendable { /// - indexing: The types of indexing and rewriting operations a decoder may take with /// regard to this header. @inlinable - public mutating func add(contentsOf other: S, indexing: HPACKIndexing = .indexable) where S.Element == (String, String) { + public mutating func add(contentsOf other: S, indexing: HPACKIndexing = .indexable) + where S.Element == (String, String) { self.reserveCapacity(self.headers.count + other.underestimatedCount) for (name, value) in other { self.add(name: name, value: value, indexing: indexing) @@ -205,7 +208,7 @@ public struct HPACKHeaders: ExpressibleByDictionaryLiteral, Sendable { @inlinable public mutating func remove(name nameToRemove: String) { self.headers.removeAll { header in - return nameToRemove.isEqualCaseInsensitiveASCIIBytes(to: header.name) + nameToRemove.isEqualCaseInsensitiveASCIIBytes(to: header.name) } } @@ -222,7 +225,7 @@ public struct HPACKHeaders: ExpressibleByDictionaryLiteral, Sendable { /// - Returns: A list of the values for that header field name. @inlinable public subscript(name: String) -> [String] { - return self._values(forHeader: name, canonicalForm: false) + self._values(forHeader: name, canonicalForm: false) } /// Retrieves the first value for a given header field name from the block. @@ -273,7 +276,7 @@ public struct HPACKHeaders: ExpressibleByDictionaryLiteral, Sendable { /// - Returns: A list of the values for that header field name. @inlinable public subscript(canonicalForm name: String) -> [String] { - return self._values(forHeader: name, canonicalForm: true) + self._values(forHeader: name, canonicalForm: true) } /// Return a sequence of header values for the header field named `name`. @@ -298,7 +301,10 @@ public struct HPACKHeaders: ExpressibleByDictionaryLiteral, Sendable { /// Special internal function for use by tests. internal subscript(position: Int) -> (String, String) { - precondition(position < self.headers.endIndex, "Position \(position) is beyond bounds of \(self.headers.endIndex)") + precondition( + position < self.headers.endIndex, + "Position \(position) is beyond bounds of \(self.headers.endIndex)" + ) let header = self.headers[position] return (header.name, header.value) } @@ -341,7 +347,7 @@ extension HPACKHeaders { } public func makeIterator() -> Iterator { - return Iterator(headers: self.headers, name: self.name, canonicalize: self.canonicalize) + Iterator(headers: self.headers, name: self.name, canonicalize: self.canonicalize) } } } @@ -423,7 +429,7 @@ extension HPACKHeaders { /// The total number of headers that can be contained without allocating new storage. @inlinable public var capacity: Int { - return self.headers.capacity + self.headers.capacity } /// Reserves enough space to store the specified number of headers. @@ -458,28 +464,28 @@ extension HPACKHeaders: RandomAccessCollection { @inlinable public static func < (lhs: Index, rhs: Index) -> Bool { - return lhs._base < rhs._base + lhs._base < rhs._base } } @inlinable public var startIndex: HPACKHeaders.Index { - return .init(_base: self.headers.startIndex) + .init(_base: self.headers.startIndex) } @inlinable public var endIndex: HPACKHeaders.Index { - return .init(_base: self.headers.endIndex) + .init(_base: self.headers.endIndex) } @inlinable public func index(before i: HPACKHeaders.Index) -> HPACKHeaders.Index { - return .init(_base: self.headers.index(before: i._base)) + .init(_base: self.headers.index(before: i._base)) } @inlinable public func index(after i: HPACKHeaders.Index) -> HPACKHeaders.Index { - return .init(_base: self.headers.index(after: i._base)) + .init(_base: self.headers.index(after: i._base)) } @inlinable @@ -517,11 +523,10 @@ extension HPACKHeaders: RandomAccessCollection { @inlinable public func makeIterator() -> HPACKHeaders.Iterator { - return Iterator(self) + Iterator(self) } } - extension HPACKHeaders: CustomStringConvertible { public var description: String { var headersArray: [(HPACKIndexing, String, String)] = [] @@ -539,7 +544,7 @@ extension HPACKHeaders: CustomStringConvertible { // More discussion at https://github.com/apple/swift-nio-http2/issues/342. extension HPACKHeaders: Equatable { @inlinable - public static func ==(lhs: HPACKHeaders, rhs: HPACKHeaders) -> Bool { + public static func == (lhs: HPACKHeaders, rhs: HPACKHeaders) -> Bool { guard lhs.headers.count == rhs.headers.count else { return false } @@ -619,7 +624,6 @@ internal struct HPACKHeader: Sendable { } } - extension HPACKHeader { @inlinable internal var size: Int { @@ -630,25 +634,24 @@ extension HPACKHeader { // // The size of an entry is calculated using the length of its name and value // without any Huffman encoding applied. - return name.utf8.count + value.utf8.count + 32 + name.utf8.count + value.utf8.count + 32 } } - -internal extension UInt8 { +extension UInt8 { @inlinable var isASCII: Bool { - return self <= 127 + self <= 127 } } -/* private but inlinable */ -internal extension UTF8.CodeUnit { +// private but inlinable +extension UTF8.CodeUnit { @inlinable var isASCIIWhitespace: Bool { switch self { case UInt8(ascii: " "), - UInt8(ascii: "\t"): + UInt8(ascii: "\t"): return true default: return false @@ -660,7 +663,7 @@ extension Substring.UTF8View { @inlinable func _trimWhitespace() -> Substring.UTF8View { guard let firstNonWhitespace = self.firstIndex(where: { !$0.isASCIIWhitespace }) else { - // The whole substring is ASCII whitespace. + // The whole substring is ASCII whitespace. return Substring().utf8 } @@ -673,7 +676,7 @@ extension Substring.UTF8View { extension String.UTF8View { @inlinable func _lazySplit(separator: UTF8.CodeUnit) -> LazyUTF8ViewSplitSequence { - return LazyUTF8ViewSplitSequence(self, separator: separator) + LazyUTF8ViewSplitSequence(self, separator: separator) } @usableFromInline @@ -691,7 +694,7 @@ extension String.UTF8View { @inlinable func makeIterator() -> Iterator { - return Iterator(self) + Iterator(self) } @usableFromInline @@ -729,7 +732,6 @@ extension String.UTF8View { } } - extension String.UTF8View { /// Compares two UTF8 strings as case insensitive ASCII bytes. /// @@ -737,41 +739,40 @@ extension String.UTF8View { /// - Returns: Whether the collection contains **EXACTLY** this array or no, but by ignoring case. @inlinable func compareCaseInsensitiveASCIIBytes(to other: String.UTF8View) -> Bool { - // fast path: we can get the underlying bytes of both - let maybeMaybeResult = self.withContiguousStorageIfAvailable { lhsBuffer -> Bool? in - other.withContiguousStorageIfAvailable { rhsBuffer in - if lhsBuffer.count != rhsBuffer.count { + // fast path: we can get the underlying bytes of both + let maybeMaybeResult = self.withContiguousStorageIfAvailable { lhsBuffer -> Bool? in + other.withContiguousStorageIfAvailable { rhsBuffer in + if lhsBuffer.count != rhsBuffer.count { + return false + } + + for idx in 0.. Bool { - return self.elementsEqual(other, by: { return (($0 & 0xdf) == ($1 & 0xdf) && $0.isASCII) }) + self.elementsEqual(other, by: { (($0 & 0xdf) == ($1 & 0xdf) && $0.isASCII) }) } } - extension String { @inlinable internal func isEqualCaseInsensitiveASCIIBytes(to: String) -> Bool { - return self.utf8.compareCaseInsensitiveASCIIBytes(to: to.utf8) + self.utf8.compareCaseInsensitiveASCIIBytes(to: to.utf8) } } diff --git a/Sources/NIOHPACK/HeaderTables.swift b/Sources/NIOHPACK/HeaderTables.swift index 55c8aa1..8acb79e 100644 --- a/Sources/NIOHPACK/HeaderTables.swift +++ b/Sources/NIOHPACK/HeaderTables.swift @@ -27,7 +27,7 @@ internal struct HeaderTableEntry: Sendable { // The size of an entry is calculated using the length of its name and value // without any Huffman encoding applied. var length: Int { - return self.name.utf8.count + self.value.utf8.count + 32 + self.name.utf8.count + self.value.utf8.count + 32 } } @@ -39,19 +39,19 @@ struct HeaderTableStorage { static let defaultMaxSize = 4096 private var headers: CircularBuffer - + internal private(set) var maxSize: Int internal private(set) var length: Int = 0 - + var count: Int { - return self.headers.count + self.headers.count } - + init(maxSize: Int = HeaderTableStorage.defaultMaxSize) { self.maxSize = maxSize - self.headers = CircularBuffer(initialCapacity: self.maxSize / 64) // rough guess: 64 bytes per header + self.headers = CircularBuffer(initialCapacity: self.maxSize / 64) // rough guess: 64 bytes per header } - + init(staticHeaderList: [(String, String)]) { self.headers = CircularBuffer(initialCapacity: staticHeaderList.count) @@ -64,7 +64,7 @@ struct HeaderTableStorage { self.maxSize = len } - + subscript(index: Int) -> HeaderTableEntry { let baseIndex = self.headers.index(self.headers.startIndex, offsetBy: index) return self.headers[baseIndex] @@ -114,7 +114,7 @@ struct HeaderTableStorage { return .none } } - + func firstIndex(matching name: String) -> Int? { for (idx, header) in self.headers.enumerated() { if header.name.isEqualCaseInsensitiveASCIIBytes(to: name) { @@ -123,7 +123,7 @@ struct HeaderTableStorage { } return nil } - + mutating func setTableSize(to newSize: Int) { precondition(newSize >= 0) if newSize < self.length { @@ -135,7 +135,7 @@ struct HeaderTableStorage { self.maxSize = newSize } - + mutating func add(name: String, value: String) { let entry = HeaderTableEntry(name: name, value: value) @@ -145,7 +145,6 @@ struct HeaderTableStorage { newLength = self.length + entry.length } - if newLength > self.maxSize { // We can't free up enough space. This is not an error: RFC 7541 ยง 4.4 explicitly allows it. // In this case, the append fails but the above purge is preserved. @@ -155,7 +154,7 @@ struct HeaderTableStorage { self.headers.prepend(entry) self.length = newLength } - + /// Purges `toRelease` bytes from the table, where 'bytes' refers to the byte-count /// of a table entry specified in RFC 7541: [name octets] + [value octets] + 32. /// @@ -167,14 +166,14 @@ struct HeaderTableStorage { self.length = 0 return } - + var available = self.maxSize - self.length let needed = available + count while available < needed && !self.headers.isEmpty { available += self.purgeOne() } } - + @discardableResult private mutating func purgeOne() -> Int { precondition(self.headers.isEmpty == false, "should not call purgeOne() unless we have something to purge") @@ -184,16 +183,16 @@ struct HeaderTableStorage { self.length -= entry.length return entry.length } - + // internal for testing func dumpHeaders(offsetBy amount: Int = 0) -> String { - return self.headers.enumerated().reduce("") { + self.headers.enumerated().reduce("") { $0 + "\($1.0 + amount) - \($1.1.name) : \($1.1.value)\n" } } } -extension HeaderTableStorage : CustomStringConvertible { +extension HeaderTableStorage: CustomStringConvertible { @usableFromInline var description: String { var array: [(String, String)] = [] @@ -207,4 +206,3 @@ extension HeaderTableStorage : CustomStringConvertible { // The `@unchecked` is needed because at the time of writing `NIOCore` didn't have `Sendable` support. extension HeaderTableStorage: Sendable {} - diff --git a/Sources/NIOHPACK/HuffmanCoding.swift b/Sources/NIOHPACK/HuffmanCoding.swift index 5bfc089..862758b 100644 --- a/Sources/NIOHPACK/HuffmanCoding.swift +++ b/Sources/NIOHPACK/HuffmanCoding.swift @@ -22,19 +22,19 @@ extension ByteBuffer { var offset = 0 var remainingBits = 8 } - + /// Returns the number of *bits* required to encode a given string. - fileprivate static func encodedBitLength(of bytes: C) -> Int where C.Element == UInt8 { + fileprivate static func encodedBitLength(of bytes: C) -> Int where C.Element == UInt8 { let clen = bytes.reduce(0) { $0 + StaticHuffmanTable[Int($1)].nbits } // round up to nearest multiple of 8 for EOS prefix return (clen + 7) & ~7 } - + /// Returns the number of bytes required to encode a given string. - static func huffmanEncodedLength(of bytes: C) -> Int where C.Element == UInt8 { - return self.encodedBitLength(of: bytes) / 8 + static func huffmanEncodedLength(of bytes: C) -> Int where C.Element == UInt8 { + self.encodedBitLength(of: bytes) / 8 } - + /// Encodes the given string to the buffer, using HPACK Huffman encoding. /// /// - Parameter string: The string data to encode. @@ -43,33 +43,37 @@ extension ByteBuffer { mutating func setHuffmanEncoded(bytes stringBytes: C) -> Int where C.Element == UInt8 { let clen = ByteBuffer.encodedBitLength(of: stringBytes) self.ensureBitsAvailable(clen) - + return self.withUnsafeMutableWritableBytes { bytes in var state = _EncoderState() - + for ch in stringBytes { ByteBuffer.appendSym_fast(StaticHuffmanTable[Int(ch)], &state, bytes: bytes) } - + if state.remainingBits > 0 && state.remainingBits < 8 { // set all remaining bits of the last byte to 1 bytes[state.offset] |= UInt8(1 << state.remainingBits) - 1 state.offset += 1 state.remainingBits = (state.offset == bytes.count ? 0 : 8) } - + return state.offset } } - + @discardableResult mutating func writeHuffmanEncoded(bytes stringBytes: C) -> Int where C.Element == UInt8 { let written = self.setHuffmanEncoded(bytes: stringBytes) self.moveWriterIndex(forwardBy: written) return written } - - fileprivate static func appendSym_fast(_ sym: HuffmanTableEntry, _ state: inout _EncoderState, bytes: UnsafeMutableRawBufferPointer) { + + fileprivate static func appendSym_fast( + _ sym: HuffmanTableEntry, + _ state: inout _EncoderState, + bytes: UnsafeMutableRawBufferPointer + ) { // will it fit as-is? if sym.nbits == state.remainingBits { bytes[state.offset] |= UInt8(sym.bits) @@ -81,23 +85,23 @@ extension ByteBuffer { state.remainingBits -= sym.nbits } else { var (code, nbits) = sym - + nbits -= state.remainingBits bytes[state.offset] |= UInt8(code >> nbits) state.offset += 1 - + if nbits & 0x7 != 0 { // align code to MSB code <<= 8 - (nbits & 0x7) } - + // we can short-circuit if less than 8 bits are remaining if nbits < 8 { bytes[state.offset] = UInt8(truncatingIfNeeded: code) state.remainingBits = 8 - nbits return } - + // longer path for larger amounts switch nbits { case _ where nbits > 24: @@ -117,7 +121,7 @@ extension ByteBuffer { default: break } - + if nbits == 8 { bytes[state.offset] = UInt8(truncatingIfNeeded: code) state.offset += 1 @@ -128,7 +132,7 @@ extension ByteBuffer { } } } - + fileprivate mutating func ensureBitsAvailable(_ bits: Int) { let bytesNeeded = bits / 8 if bytesNeeded <= self.writableBytes { @@ -138,13 +142,13 @@ extension ByteBuffer { } return } - + let neededToAdd = bytesNeeded - self.writableBytes let newLength = self.capacity + neededToAdd - + // reallocate to ensure we have the room we need self.reserveCapacity(newLength) - + // now zero all writable bytes that we expect to use self.withUnsafeMutableWritableBytes { ptr in ptr.copyBytes(from: repeatElement(0, count: bytesNeeded)) @@ -153,24 +157,23 @@ extension ByteBuffer { } /// Errors that may be encountered by the Huffman decoder. -public enum HuffmanDecodeError -{ +public enum HuffmanDecodeError { /// The decoder entered an invalid state. Usually this means invalid input. - public struct InvalidState : NIOHPACKError { + public struct InvalidState: NIOHPACKError { fileprivate init() {} } - + /// The output data could not be validated as UTF-8. - public struct InvalidUTF8 : NIOHPACKError { + public struct InvalidUTF8: NIOHPACKError { fileprivate init() {} } } /// The decoder table. This structure doesn't actually take up any space, I think? -fileprivate let decoderTable = HuffmanDecoderTable() +private let decoderTable = HuffmanDecoderTable() extension ByteBuffer { - + /// Decodes a huffman-encoded string from the `ByteBuffer`. /// /// - Parameter at: The location of the encoded bytes to read. @@ -179,7 +182,10 @@ extension ByteBuffer { /// - Throws: HuffmanDecodeError if the data could not be decoded. @discardableResult func getHuffmanEncodedString(at index: Int, length: Int) throws -> String { - precondition(index + length <= self.capacity, "Requested range out of bounds: \(index ..< index+length) vs. \(self.capacity)") + precondition( + index + length <= self.capacity, + "Requested range out of bounds: \(index ..< index+length) vs. \(self.capacity)" + ) if length == 0 { return "" } @@ -226,10 +232,9 @@ extension ByteBuffer { return offset } - return decoded } - + /// Decodes a huffman-encoded string from the provided `ByteBuffer`, starting at the buffer's /// current `readerIndex`. Updates the `readerIndex` when it completes. /// @@ -249,24 +254,30 @@ extension String { /// This feature will be useful when decoding Huffman-encoded HPACK strings. /// /// As this API does not exist prior to 5.3 on Linux, or on older Apple platforms, we fake it out with a pointer and accept the extra copy. - init(backportUnsafeUninitializedCapacity capacity: Int, - initializingUTF8With initializer: (_ buffer: UnsafeMutableBufferPointer) throws -> Int) rethrows { + init( + backportUnsafeUninitializedCapacity capacity: Int, + initializingUTF8With initializer: (_ buffer: UnsafeMutableBufferPointer) throws -> Int + ) rethrows { let buffer = UnsafeMutableBufferPointer.allocate(capacity: capacity) defer { buffer.deallocate() } - let initializedCount = try initializer(buffer) precondition(initializedCount <= capacity, "Overran buffer in initializer!") - self = String(decoding: UnsafeMutableBufferPointer(start: buffer.baseAddress!, count: initializedCount), as: UTF8.self) + self = String( + decoding: UnsafeMutableBufferPointer(start: buffer.baseAddress!, count: initializedCount), + as: UTF8.self + ) } } extension String { - init(customUnsafeUninitializedCapacity capacity: Int, - initializingUTF8With initializer: (_ buffer: UnsafeMutableBufferPointer) throws -> Int) rethrows { + init( + customUnsafeUninitializedCapacity capacity: Int, + initializingUTF8With initializer: (_ buffer: UnsafeMutableBufferPointer) throws -> Int + ) rethrows { if #available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, *) { try self.init(unsafeUninitializedCapacity: capacity, initializingUTF8With: initializer) } else { diff --git a/Sources/NIOHPACK/HuffmanTables.swift b/Sources/NIOHPACK/HuffmanTables.swift index 182ba91..f955817 100644 --- a/Sources/NIOHPACK/HuffmanTables.swift +++ b/Sources/NIOHPACK/HuffmanTables.swift @@ -17,24 +17,20 @@ typealias HuffmanTableEntry = (bits: UInt32, nbits: Int) /// Base-64 decoding has been jovially purloined from swift-corelibs-foundation/.../NSData.swift. /// The ranges of ASCII characters that are used to encode data in Base64. private let base64ByteMappings: [Range] = [ - 65 ..< 91, // A-Z - 97 ..< 123, // a-z - 48 ..< 58, // 0-9 - 43 ..< 44, // + - 47 ..< 48, // / + 65..<91, // A-Z + 97..<123, // a-z + 48..<58, // 0-9 + 43..<44, // + + 47..<48, // / ] -/** - Padding character used when the number of bytes to encode is not divisible by 3 - */ -private let base64Padding : UInt8 = 61 // = +/// Padding character used when the number of bytes to encode is not divisible by 3 +private let base64Padding: UInt8 = 61 // = -/** - This method takes a byte with a character from Base64-encoded string - and gets the binary value that the character corresponds to. - - - parameter byte: The byte with the Base64 character. - - returns: Base64DecodedByte value containing the result (Valid , Invalid, Padding) - */ +/// This method takes a byte with a character from Base64-encoded string +/// and gets the binary value that the character corresponds to. +/// +/// - parameter byte: The byte with the Base64 character. +/// - returns: Base64DecodedByte value containing the result (Valid , Invalid, Padding) private enum Base64DecodedByte { case valid(UInt8) case invalid @@ -42,7 +38,7 @@ private enum Base64DecodedByte { } private func base64DecodeByte(_ byte: UInt8) -> Base64DecodedByte { - guard byte != base64Padding else {return .padding} + guard byte != base64Padding else { return .padding } var decodedStart: UInt8 = 0 for range in base64ByteMappings { if range.contains(byte) { @@ -54,30 +50,28 @@ private func base64DecodeByte(_ byte: UInt8) -> Base64DecodedByte { return .invalid } -/** - This method decodes Base64-encoded data. - - If the input contains any bytes that are not valid Base64 characters, - this will return nil. - - - parameter bytes: The Base64 bytes - - parameter options: Options for handling invalid input - - returns: The decoded bytes. - */ -private func base64DecodeBytes(_ bytes: C, ignoreUnknownCharacters: Bool = false) -> [UInt8]? where C.Element == UInt8 { +/// This method decodes Base64-encoded data. +/// +/// If the input contains any bytes that are not valid Base64 characters, +/// this will return nil. +/// +/// - parameter bytes: The Base64 bytes +/// - parameter options: Options for handling invalid input +/// - returns: The decoded bytes. +private func base64DecodeBytes(_ bytes: C, ignoreUnknownCharacters: Bool = false) -> [UInt8]? +where C.Element == UInt8 { var decodedBytes = [UInt8]() - decodedBytes.reserveCapacity((bytes.count/3)*2) - - var currentByte : UInt8 = 0 + decodedBytes.reserveCapacity((bytes.count / 3) * 2) + + var currentByte: UInt8 = 0 var validCharacterCount = 0 var paddingCount = 0 var index = 0 - - + for base64Char in bytes { - - let value : UInt8 - + + let value: UInt8 + switch base64DecodeByte(base64Char) { case .valid(let v): value = v @@ -92,13 +86,13 @@ private func base64DecodeBytes(_ bytes: C, ignoreUnknownCharacter paddingCount += 1 continue } - + //padding found in the middle of the sequence is invalid if paddingCount > 0 { return nil } - - switch index%4 { + + switch index % 4 { case 0: currentByte = (value << 2) case 1: @@ -115,11 +109,11 @@ private func base64DecodeBytes(_ bytes: C, ignoreUnknownCharacter default: fatalError() } - + index += 1 } - - guard (validCharacterCount + paddingCount)%4 == 0 else { + + guard (validCharacterCount + paddingCount) % 4 == 0 else { //invalid character count return nil } @@ -128,9 +122,9 @@ private func base64DecodeBytes(_ bytes: C, ignoreUnknownCharacter internal let StaticHuffmanTable: [HuffmanTableEntry] = [ (0x1ff8, 13), (0x7fffd8, 23), (0xfffffe2, 28), (0xfffffe3, 28), (0xfffffe4, 28), (0xfffffe5, 28), - (0xfffffe6, 28), (0xfffffe7, 28), (0xfffffe8, 28), (0xffffea, 24), (0x3ffffffc, 30), (0xfffffe9, 28), - (0xfffffea, 28), (0x3ffffffd, 30), (0xfffffeb, 28), (0xfffffec, 28), (0xfffffed, 28), (0xfffffee, 28), - (0xfffffef, 28), (0xffffff0, 28), (0xffffff1, 28), (0xffffff2, 28), (0x3ffffffe, 30), (0xffffff3, 28), + (0xfffffe6, 28), (0xfffffe7, 28), (0xfffffe8, 28), (0xffffea, 24), (0x3fff_fffc, 30), (0xfffffe9, 28), + (0xfffffea, 28), (0x3fff_fffd, 30), (0xfffffeb, 28), (0xfffffec, 28), (0xfffffed, 28), (0xfffffee, 28), + (0xfffffef, 28), (0xffffff0, 28), (0xffffff1, 28), (0xffffff2, 28), (0x3fff_fffe, 30), (0xffffff3, 28), (0xffffff4, 28), (0xffffff5, 28), (0xffffff6, 28), (0xffffff7, 28), (0xffffff8, 28), (0xffffff9, 28), (0xffffffa, 28), (0xffffffb, 28), (0x14, 6), (0x3f8, 10), (0x3f9, 10), (0xffa, 12), (0x1ff9, 13), (0x15, 6), (0xf8, 8), (0x7fa, 11), (0x3fa, 10), (0x3fb, 10), @@ -169,361 +163,356 @@ internal let StaticHuffmanTable: [HuffmanTableEntry] = [ (0x1ffffee, 25), (0x1ffffef, 25), (0xfffff4, 24), (0xfffff5, 24), (0x3ffffea, 26), (0x7ffff4, 23), (0x3ffffeb, 26), (0x7ffffe6, 27), (0x3ffffec, 26), (0x3ffffed, 26), (0x7ffffe7, 27), (0x7ffffe8, 27), (0x7ffffe9, 27), (0x7ffffea, 27), (0x7ffffeb, 27), (0xffffffe, 28), (0x7ffffec, 27), (0x7ffffed, 27), - (0x7ffffee, 27), (0x7ffffef, 27), (0x7fffff0, 27), (0x3ffffee, 26), (0x3fffffff, 30) + (0x7ffffee, 27), (0x7ffffef, 27), (0x7fffff0, 27), (0x3ffffee, 26), (0x3fff_ffff, 30), ] // Great googly-moogly that's a large array! This comes from the nice folks at nghttp. -/* - This implementation of a Huffman decoding table for HTTP/2 is essentially a - Swift port of the C tables from nghttp2's Huffman decoding implementation, - and is thus clearly a derivative work of the nghttp2 file - ``nghttp2_hd_huffman_data.c``, obtained from https://github.com/tatsuhiro-t/nghttp2/. - That work is also available under the Apache 2.0 license under the following terms: - - Copyright (c) 2013 Tatsuhiro Tsujikawa - - Permission is hereby granted, free of charge, to any person obtaining - a copy of this software and associated documentation files (the - "Software"), to deal in the Software without restriction, including - without limitation the rights to use, copy, modify, merge, publish, - distribute, sublicense, and/or sell copies of the Software, and to - permit persons to whom the Software is furnished to do so, subject to - the following conditions: - - The above copyright notice and this permission notice shall be - included in all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE - LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION - OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ +// This implementation of a Huffman decoding table for HTTP/2 is essentially a +// Swift port of the C tables from nghttp2's Huffman decoding implementation, +// and is thus clearly a derivative work of the nghttp2 file +// ``nghttp2_hd_huffman_data.c``, obtained from https://github.com/tatsuhiro-t/nghttp2/. +// That work is also available under the Apache 2.0 license under the following terms: +// +// Copyright (c) 2013 Tatsuhiro Tsujikawa +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. typealias HuffmanDecodeEntry = (state: UInt8, flags: HuffmanDecoderFlags, sym: UInt8) -internal struct HuffmanDecoderFlags : OptionSet -{ +internal struct HuffmanDecoderFlags: OptionSet { var rawValue: UInt8 - - static let none = HuffmanDecoderFlags([]) + + static let none = HuffmanDecoderFlags([]) static let accepted = HuffmanDecoderFlags(rawValue: 0b001) - static let symbol = HuffmanDecoderFlags(rawValue: 0b010) - static let failure = HuffmanDecoderFlags(rawValue: 0b100) + static let symbol = HuffmanDecoderFlags(rawValue: 0b010) + static let failure = HuffmanDecoderFlags(rawValue: 0b100) } -/** - This was described nicely by `@Lukasa` in his Python implementation: - - The essence of this approach is that it builds a finite state machine out of - 4-bit nybbles of Huffman coded data. The input function passes 4 bits worth of - data to the state machine each time, which uses those 4 bits of data along with - the current accumulated state data to process the data given. - - For the sake of efficiency, the in-memory representation of the states, - transitions, and result values of the state machine are represented as a long - list containing three-tuples. This list is enormously long, and viewing it as - an in-memory representation is not very clear, but it is laid out here in a way - that is intended to be *somewhat* more clear. - - Essentially, the list is structured as 256 collections of 16 entries (one for - each nybble) of three-tuples. Each collection is called a "node", and the - zeroth collection is called the "root node". The state machine tracks one - value: the "state" byte. - - For each nybble passed to the state machine, it first multiplies the "state" - byte by 16 and adds the numerical value of the nybble. This number is the index - into the large flat list. - - The three-tuple that is found by looking up that index consists of three - values: - - - a new state value, used for subsequent decoding - - a collection of flags, used to determine whether data is emitted or whether - the state machine is complete. - - the byte value to emit, assuming that emitting a byte is required. - - The flags are consulted, if necessary a byte is emitted, and then the next - nybble is used. This continues until the state machine believes it has - completely Huffman-decoded the data. - - This approach has relatively little indirection, and therefore performs - relatively well. The total number of loop - iterations is 4x the number of bytes passed to the decoder. - */ +/// This was described nicely by `@Lukasa` in his Python implementation: +/// +/// The essence of this approach is that it builds a finite state machine out of +/// 4-bit nybbles of Huffman coded data. The input function passes 4 bits worth of +/// data to the state machine each time, which uses those 4 bits of data along with +/// the current accumulated state data to process the data given. +/// +/// For the sake of efficiency, the in-memory representation of the states, +/// transitions, and result values of the state machine are represented as a long +/// list containing three-tuples. This list is enormously long, and viewing it as +/// an in-memory representation is not very clear, but it is laid out here in a way +/// that is intended to be *somewhat* more clear. +/// +/// Essentially, the list is structured as 256 collections of 16 entries (one for +/// each nybble) of three-tuples. Each collection is called a "node", and the +/// zeroth collection is called the "root node". The state machine tracks one +/// value: the "state" byte. +/// +/// For each nybble passed to the state machine, it first multiplies the "state" +/// byte by 16 and adds the numerical value of the nybble. This number is the index +/// into the large flat list. +/// +/// The three-tuple that is found by looking up that index consists of three +/// values: +/// +/// - a new state value, used for subsequent decoding +/// - a collection of flags, used to determine whether data is emitted or whether +/// the state machine is complete. +/// - the byte value to emit, assuming that emitting a byte is required. +/// +/// The flags are consulted, if necessary a byte is emitted, and then the next +/// nybble is used. This continues until the state machine believes it has +/// completely Huffman-decoded the data. +/// +/// This approach has relatively little indirection, and therefore performs +/// relatively well. The total number of loop +/// iterations is 4x the number of bytes passed to the decoder. internal struct HuffmanDecoderTable { subscript(state state: UInt8, nybble nybble: UInt8) -> HuffmanDecodeEntry { assert(nybble < 16) let index = (Int(state) * 16) + Int(nybble) return HuffmanDecoderTable.rawTable[index] } - + // You would not *believe* how much faster this compiles now. // TODO(jim): decide if it's worth dropping the un-encoded raw bytes into // a segment of the binary, i.e. __DATA,__huffman_decode_table. I don't know // how to do that (automatically) via SwiftPM though, only via Xcode. private static let rawTable: [HuffmanDecodeEntry] = { let base64_table_bytes: StaticString = """ - BAAABQAABwAACAAACwAADAAAEAAAEwAAGQAAHAAAIAAAIwAAKgAAMQAAOQAAQAEA - AAMwAAMxAAMyAANhAANjAANlAANpAANvAANzAAN0DQAADgAAEQAAEgAAFAAAFQAA - AQIwFgMwAQIxFgMxAQIyFgMyAQJhFgNhAQJjFgNjAQJlFgNlAQJpFgNpAQJvFgNv - AgIwCQIwFwIwKAMwAgIxCQIxFwIxKAMxAgIyCQIyFwIyKAMyAgJhCQJhFwJhKANh - AwIwBgIwCgIwDwIwGAIwHwIwKQIwOAMwAwIxBgIxCgIxDwIxGAIxHwIxKQIxOAMx - AwIyBgIyCgIyDwIyGAIyHwIyKQIyOAMyAwJhBgJhCgJhDwJhGAJhHwJhKQJhOANh - AgJjCQJjFwJjKANjAgJlCQJlFwJlKANlAgJpCQJpFwJpKANpAgJvCQJvFwJvKANv - AwJjBgJjCgJjDwJjGAJjHwJjKQJjOANjAwJlBgJlCgJlDwJlGAJlHwJlKQJlOANl - AwJpBgJpCgJpDwJpGAJpHwJpKQJpOANpAwJvBgJvCgJvDwJvGAJvHwJvKQJvOANv - AQJzFgNzAQJ0FgN0AAMgAAMlAAMtAAMuAAMvAAMzAAM0AAM1AAM2AAM3AAM4AAM5 - AgJzCQJzFwJzKANzAgJ0CQJ0FwJ0KAN0AQIgFgMgAQIlFgMlAQItFgMtAQIuFgMu - AwJzBgJzCgJzDwJzGAJzHwJzKQJzOANzAwJ0BgJ0CgJ0DwJ0GAJ0HwJ0KQJ0OAN0 - AgIgCQIgFwIgKAMgAgIlCQIlFwIlKAMlAgItCQItFwItKAMtAgIuCQIuFwIuKAMu - AwIgBgIgCgIgDwIgGAIgHwIgKQIgOAMgAwIlBgIlCgIlDwIlGAIlHwIlKQIlOAMl - AwItBgItCgItDwItGAItHwItKQItOAMtAwIuBgIuCgIuDwIuGAIuHwIuKQIuOAMu - AQIvFgMvAQIzFgMzAQI0FgM0AQI1FgM1AQI2FgM2AQI3FgM3AQI4FgM4AQI5FgM5 - AgIvCQIvFwIvKAMvAgIzCQIzFwIzKAMzAgI0CQI0FwI0KAM0AgI1CQI1FwI1KAM1 - AwIvBgIvCgIvDwIvGAIvHwIvKQIvOAMvAwIzBgIzCgIzDwIzGAIzHwIzKQIzOAMz - AwI0BgI0CgI0DwI0GAI0HwI0KQI0OAM0AwI1BgI1CgI1DwI1GAI1HwI1KQI1OAM1 - AgI2CQI2FwI2KAM2AgI3CQI3FwI3KAM3AgI4CQI4FwI4KAM4AgI5CQI5FwI5KAM5 - AwI2BgI2CgI2DwI2GAI2HwI2KQI2OAM2AwI3BgI3CgI3DwI3GAI3HwI3KQI3OAM3 - AwI4BgI4CgI4DwI4GAI4HwI4KQI4OAM4AwI5BgI5CgI5DwI5GAI5HwI5KQI5OAM5 - GgAAGwAAHQAAHgAAIQAAIgAAJAAAJQAAKwAALgAAMgAANQAAOgAAPQAAQQAARAEA - AAM9AANBAANfAANiAANkAANmAANnAANoAANsAANtAANuAANwAANyAAN1JgAAJwAA - AQI9FgM9AQJBFgNBAQJfFgNfAQJiFgNiAQJkFgNkAQJmFgNmAQJnFgNnAQJoFgNo - AgI9CQI9FwI9KAM9AgJBCQJBFwJBKANBAgJfCQJfFwJfKANfAgJiCQJiFwJiKANi - AwI9BgI9CgI9DwI9GAI9HwI9KQI9OAM9AwJBBgJBCgJBDwJBGAJBHwJBKQJBOANB - AwJfBgJfCgJfDwJfGAJfHwJfKQJfOANfAwJiBgJiCgJiDwJiGAJiHwJiKQJiOANi - AgJkCQJkFwJkKANkAgJmCQJmFwJmKANmAgJnCQJnFwJnKANnAgJoCQJoFwJoKANo - AwJkBgJkCgJkDwJkGAJkHwJkKQJkOANkAwJmBgJmCgJmDwJmGAJmHwJmKQJmOANm - AwJnBgJnCgJnDwJnGAJnHwJnKQJnOANnAwJoBgJoCgJoDwJoGAJoHwJoKQJoOANo - AQJsFgNsAQJtFgNtAQJuFgNuAQJwFgNwAQJyFgNyAQJ1FgN1AAM6AANCAANDAANE - AgJsCQJsFwJsKANsAgJtCQJtFwJtKANtAgJuCQJuFwJuKANuAgJwCQJwFwJwKANw - AwJsBgJsCgJsDwJsGAJsHwJsKQJsOANsAwJtBgJtCgJtDwJtGAJtHwJtKQJtOANt - AwJuBgJuCgJuDwJuGAJuHwJuKQJuOANuAwJwBgJwCgJwDwJwGAJwHwJwKQJwOANw - AgJyCQJyFwJyKANyAgJ1CQJ1FwJ1KAN1AQI6FgM6AQJCFgNCAQJDFgNDAQJEFgNE - AwJyBgJyCgJyDwJyGAJyHwJyKQJyOANyAwJ1BgJ1CgJ1DwJ1GAJ1HwJ1KQJ1OAN1 - AgI6CQI6FwI6KAM6AgJCCQJCFwJCKANCAgJDCQJDFwJDKANDAgJECQJEFwJEKANE - AwI6BgI6CgI6DwI6GAI6HwI6KQI6OAM6AwJCBgJCCgJCDwJCGAJCHwJCKQJCOANC - AwJDBgJDCgJDDwJDGAJDHwJDKQJDOANDAwJEBgJECgJEDwJEGAJEHwJEKQJEOANE - LAAALQAALwAAMAAAMwAANAAANgAANwAAOwAAPAAAPgAAPwAAQgAAQwAARQAASAEA - AANFAANGAANHAANIAANJAANKAANLAANMAANNAANOAANPAANQAANRAANSAANTAANU - AQJFFgNFAQJGFgNGAQJHFgNHAQJIFgNIAQJJFgNJAQJKFgNKAQJLFgNLAQJMFgNM - AgJFCQJFFwJFKANFAgJGCQJGFwJGKANGAgJHCQJHFwJHKANHAgJICQJIFwJIKANI - AwJFBgJFCgJFDwJFGAJFHwJFKQJFOANFAwJGBgJGCgJGDwJGGAJGHwJGKQJGOANG - AwJHBgJHCgJHDwJHGAJHHwJHKQJHOANHAwJIBgJICgJIDwJIGAJIHwJIKQJIOANI - AgJJCQJJFwJJKANJAgJKCQJKFwJKKANKAgJLCQJLFwJLKANLAgJMCQJMFwJMKANM - AwJJBgJJCgJJDwJJGAJJHwJJKQJJOANJAwJKBgJKCgJKDwJKGAJKHwJKKQJKOANK - AwJLBgJLCgJLDwJLGAJLHwJLKQJLOANLAwJMBgJMCgJMDwJMGAJMHwJMKQJMOANM - AQJNFgNNAQJOFgNOAQJPFgNPAQJQFgNQAQJRFgNRAQJSFgNSAQJTFgNTAQJUFgNU - AgJNCQJNFwJNKANNAgJOCQJOFwJOKANOAgJPCQJPFwJPKANPAgJQCQJQFwJQKANQ - AwJNBgJNCgJNDwJNGAJNHwJNKQJNOANNAwJOBgJOCgJODwJOGAJOHwJOKQJOOANO - AwJPBgJPCgJPDwJPGAJPHwJPKQJPOANPAwJQBgJQCgJQDwJQGAJQHwJQKQJQOANQ - AgJRCQJRFwJRKANRAgJSCQJSFwJSKANSAgJTCQJTFwJTKANTAgJUCQJUFwJUKANU - AwJRBgJRCgJRDwJRGAJRHwJRKQJROANRAwJSBgJSCgJSDwJSGAJSHwJSKQJSOANS - AwJTBgJTCgJTDwJTGAJTHwJTKQJTOANTAwJUBgJUCgJUDwJUGAJUHwJUKQJUOANU - AANVAANWAANXAANZAANqAANrAANxAAN2AAN3AAN4AAN5AAN6RgAARwAASQAASgEA - AQJVFgNVAQJWFgNWAQJXFgNXAQJZFgNZAQJqFgNqAQJrFgNrAQJxFgNxAQJ2FgN2 - AgJVCQJVFwJVKANVAgJWCQJWFwJWKANWAgJXCQJXFwJXKANXAgJZCQJZFwJZKANZ - AwJVBgJVCgJVDwJVGAJVHwJVKQJVOANVAwJWBgJWCgJWDwJWGAJWHwJWKQJWOANW - AwJXBgJXCgJXDwJXGAJXHwJXKQJXOANXAwJZBgJZCgJZDwJZGAJZHwJZKQJZOANZ - AgJqCQJqFwJqKANqAgJrCQJrFwJrKANrAgJxCQJxFwJxKANxAgJ2CQJ2FwJ2KAN2 - AwJqBgJqCgJqDwJqGAJqHwJqKQJqOANqAwJrBgJrCgJrDwJrGAJrHwJrKQJrOANr - AwJxBgJxCgJxDwJxGAJxHwJxKQJxOANxAwJ2BgJ2CgJ2DwJ2GAJ2HwJ2KQJ2OAN2 - AQJ3FgN3AQJ4FgN4AQJ5FgN5AQJ6FgN6AAMmAAMqAAMsAAM7AANYAANaSwAATgAA - AgJ3CQJ3FwJ3KAN3AgJ4CQJ4FwJ4KAN4AgJ5CQJ5FwJ5KAN5AgJ6CQJ6FwJ6KAN6 - AwJ3BgJ3CgJ3DwJ3GAJ3HwJ3KQJ3OAN3AwJ4BgJ4CgJ4DwJ4GAJ4HwJ4KQJ4OAN4 - AwJ5BgJ5CgJ5DwJ5GAJ5HwJ5KQJ5OAN5AwJ6BgJ6CgJ6DwJ6GAJ6HwJ6KQJ6OAN6 - AQImFgMmAQIqFgMqAQIsFgMsAQI7FgM7AQJYFgNYAQJaFgNaTAAATQAATwAAUQAA - AgImCQImFwImKAMmAgIqCQIqFwIqKAMqAgIsCQIsFwIsKAMsAgI7CQI7FwI7KAM7 - AwImBgImCgImDwImGAImHwImKQImOAMmAwIqBgIqCgIqDwIqGAIqHwIqKQIqOAMq - AwIsBgIsCgIsDwIsGAIsHwIsKQIsOAMsAwI7BgI7CgI7DwI7GAI7HwI7KQI7OAM7 - AgJYCQJYFwJYKANYAgJaCQJaFwJaKANaAAMhAAMiAAMoAAMpAAM/UAAAUgAAVAAA - AwJYBgJYCgJYDwJYGAJYHwJYKQJYOANYAwJaBgJaCgJaDwJaGAJaHwJaKQJaOANa - AQIhFgMhAQIiFgMiAQIoFgMoAQIpFgMpAQI/FgM/AAMnAAMrAAN8UwAAVQAAWAAA - AgIhCQIhFwIhKAMhAgIiCQIiFwIiKAMiAgIoCQIoFwIoKAMoAgIpCQIpFwIpKAMp - AwIhBgIhCgIhDwIhGAIhHwIhKQIhOAMhAwIiBgIiCgIiDwIiGAIiHwIiKQIiOAMi - AwIoBgIoCgIoDwIoGAIoHwIoKQIoOAMoAwIpBgIpCgIpDwIpGAIpHwIpKQIpOAMp - AgI/CQI/FwI/KAM/AQInFgMnAQIrFgMrAQJ8FgN8AAMjAAM+VgAAVwAAWQAAWgAA - AwI/BgI/CgI/DwI/GAI/HwI/KQI/OAM/AgInCQInFwInKAMnAgIrCQIrFwIrKAMr - AwInBgInCgInDwInGAInHwInKQInOAMnAwIrBgIrCgIrDwIrGAIrHwIrKQIrOAMr - AgJ8CQJ8FwJ8KAN8AQIjFgMjAQI+FgM+AAMAAAMkAANAAANbAANdAAN+WwAAXAAA - AwJ8BgJ8CgJ8DwJ8GAJ8HwJ8KQJ8OAN8AgIjCQIjFwIjKAMjAgI+CQI+FwI+KAM+ - AwIjBgIjCgIjDwIjGAIjHwIjKQIjOAMjAwI+BgI+CgI+DwI+GAI+HwI+KQI+OAM+ - AQIAFgMAAQIkFgMkAQJAFgNAAQJbFgNbAQJdFgNdAQJ+FgN+AANeAAN9XQAAXgAA - AgIACQIAFwIAKAMAAgIkCQIkFwIkKAMkAgJACQJAFwJAKANAAgJbCQJbFwJbKANb - AwIABgIACgIADwIAGAIAHwIAKQIAOAMAAwIkBgIkCgIkDwIkGAIkHwIkKQIkOAMk - AwJABgJACgJADwJAGAJAHwJAKQJAOANAAwJbBgJbCgJbDwJbGAJbHwJbKQJbOANb - AgJdCQJdFwJdKANdAgJ+CQJ+FwJ+KAN+AQJeFgNeAQJ9FgN9AAM8AANgAAN7XwAA - AwJdBgJdCgJdDwJdGAJdHwJdKQJdOANdAwJ+BgJ+CgJ+DwJ+GAJ+HwJ+KQJ+OAN+ - AgJeCQJeFwJeKANeAgJ9CQJ9FwJ9KAN9AQI8FgM8AQJgFgNgAQJ7FgN7YAAAbgAA - AwJeBgJeCgJeDwJeGAJeHwJeKQJeOANeAwJ9BgJ9CgJ9DwJ9GAJ9HwJ9KQJ9OAN9 - AgI8CQI8FwI8KAM8AgJgCQJgFwJgKANgAgJ7CQJ7FwJ7KAN7YQAAZQAAbwAAhQAA - AwI8BgI8CgI8DwI8GAI8HwI8KQI8OAM8AwJgBgJgCgJgDwJgGAJgHwJgKQJgOANg - AwJ7BgJ7CgJ7DwJ7GAJ7HwJ7KQJ7OAN7YgAAYwAAZgAAaQAAcAAAdwAAhgAAmQAA - AANcAAPDAAPQZAAAZwAAaAAAagAAawAAcQAAdAAAeAAAfgAAhwAAjgAAmgAAqQAA - AQJcFgNcAQLDFgPDAQLQFgPQAAOAAAOCAAODAAOiAAO4AAPCAAPgAAPibAAAbQAA - AgJcCQJcFwJcKANcAgLDCQLDFwLDKAPDAgLQCQLQFwLQKAPQAQKAFgOAAQKCFgOC - AwJcBgJcCgJcDwJcGAJcHwJcKQJcOANcAwLDBgLDCgLDDwLDGALDHwLDKQLDOAPD - AwLQBgLQCgLQDwLQGALQHwLQKQLQOAPQAgKACQKAFwKAKAOAAgKCCQKCFwKCKAOC - AwKABgKACgKADwKAGAKAHwKAKQKAOAOAAwKCBgKCCgKCDwKCGAKCHwKCKQKCOAOC - AQKDFgODAQKiFgOiAQK4FgO4AQLCFgPCAQLgFgPgAQLiFgPiAAOZAAOhAAOnAAOs - AgKDCQKDFwKDKAODAgKiCQKiFwKiKAOiAgK4CQK4FwK4KAO4AgLCCQLCFwLCKAPC - AwKDBgKDCgKDDwKDGAKDHwKDKQKDOAODAwKiBgKiCgKiDwKiGAKiHwKiKQKiOAOi - AwK4BgK4CgK4DwK4GAK4HwK4KQK4OAO4AwLCBgLCCgLCDwLCGALCHwLCKQLCOAPC - AgLgCQLgFwLgKAPgAgLiCQLiFwLiKAPiAQKZFgOZAQKhFgOhAQKnFgOnAQKsFgOs - AwLgBgLgCgLgDwLgGALgHwLgKQLgOAPgAwLiBgLiCgLiDwLiGALiHwLiKQLiOAPi - AgKZCQKZFwKZKAOZAgKhCQKhFwKhKAOhAgKnCQKnFwKnKAOnAgKsCQKsFwKsKAOs - AwKZBgKZCgKZDwKZGAKZHwKZKQKZOAOZAwKhBgKhCgKhDwKhGAKhHwKhKQKhOAOh - AwKnBgKnCgKnDwKnGAKnHwKnKQKnOAOnAwKsBgKsCgKsDwKsGAKsHwKsKQKsOAOs - cgAAcwAAdQAAdgAAeQAAewAAfwAAggAAiAAAiwAAjwAAkgAAmwAAogAAqgAAtAAA - AAOwAAOxAAOzAAPRAAPYAAPZAAPjAAPlAAPmegAAfAAAfQAAgAAAgQAAgwAAhAAA - AQKwFgOwAQKxFgOxAQKzFgOzAQLRFgPRAQLYFgPYAQLZFgPZAQLjFgPjAQLlFgPl - AgKwCQKwFwKwKAOwAgKxCQKxFwKxKAOxAgKzCQKzFwKzKAOzAgLRCQLRFwLRKAPR - AwKwBgKwCgKwDwKwGAKwHwKwKQKwOAOwAwKxBgKxCgKxDwKxGAKxHwKxKQKxOAOx - AwKzBgKzCgKzDwKzGAKzHwKzKQKzOAOzAwLRBgLRCgLRDwLRGALRHwLRKQLROAPR - AgLYCQLYFwLYKAPYAgLZCQLZFwLZKAPZAgLjCQLjFwLjKAPjAgLlCQLlFwLlKAPl - AwLYBgLYCgLYDwLYGALYHwLYKQLYOAPYAwLZBgLZCgLZDwLZGALZHwLZKQLZOAPZ - AwLjBgLjCgLjDwLjGALjHwLjKQLjOAPjAwLlBgLlCgLlDwLlGALlHwLlKQLlOAPl - AQLmFgPmAAOBAAOEAAOFAAOGAAOIAAOSAAOaAAOcAAOgAAOjAAOkAAOpAAOqAAOt - AgLmCQLmFwLmKAPmAQKBFgOBAQKEFgOEAQKFFgOFAQKGFgOGAQKIFgOIAQKSFgOS - AwLmBgLmCgLmDwLmGALmHwLmKQLmOAPmAgKBCQKBFwKBKAOBAgKECQKEFwKEKAOE - AwKBBgKBCgKBDwKBGAKBHwKBKQKBOAOBAwKEBgKECgKEDwKEGAKEHwKEKQKEOAOE - AgKFCQKFFwKFKAOFAgKGCQKGFwKGKAOGAgKICQKIFwKIKAOIAgKSCQKSFwKSKAOS - AwKFBgKFCgKFDwKFGAKFHwKFKQKFOAOFAwKGBgKGCgKGDwKGGAKGHwKGKQKGOAOG - AwKIBgKICgKIDwKIGAKIHwKIKQKIOAOIAwKSBgKSCgKSDwKSGAKSHwKSKQKSOAOS - AQKaFgOaAQKcFgOcAQKgFgOgAQKjFgOjAQKkFgOkAQKpFgOpAQKqFgOqAQKtFgOt - AgKaCQKaFwKaKAOaAgKcCQKcFwKcKAOcAgKgCQKgFwKgKAOgAgKjCQKjFwKjKAOj - AwKaBgKaCgKaDwKaGAKaHwKaKQKaOAOaAwKcBgKcCgKcDwKcGAKcHwKcKQKcOAOc - AwKgBgKgCgKgDwKgGAKgHwKgKQKgOAOgAwKjBgKjCgKjDwKjGAKjHwKjKQKjOAOj - AgKkCQKkFwKkKAOkAgKpCQKpFwKpKAOpAgKqCQKqFwKqKAOqAgKtCQKtFwKtKAOt - AwKkBgKkCgKkDwKkGAKkHwKkKQKkOAOkAwKpBgKpCgKpDwKpGAKpHwKpKQKpOAOp - AwKqBgKqCgKqDwKqGAKqHwKqKQKqOAOqAwKtBgKtCgKtDwKtGAKtHwKtKQKtOAOt - iQAAigAAjAAAjQAAkAAAkQAAkwAAlgAAnAAAnwAAowAApgAAqwAArgAAtQAAvgAA - AAOyAAO1AAO5AAO6AAO7AAO9AAO+AAPEAAPGAAPkAAPoAAPplAAAlQAAlwAAmAAA - AQKyFgOyAQK1FgO1AQK5FgO5AQK6FgO6AQK7FgO7AQK9FgO9AQK+FgO+AQLEFgPE - AgKyCQKyFwKyKAOyAgK1CQK1FwK1KAO1AgK5CQK5FwK5KAO5AgK6CQK6FwK6KAO6 - AwKyBgKyCgKyDwKyGAKyHwKyKQKyOAOyAwK1BgK1CgK1DwK1GAK1HwK1KQK1OAO1 - AwK5BgK5CgK5DwK5GAK5HwK5KQK5OAO5AwK6BgK6CgK6DwK6GAK6HwK6KQK6OAO6 - AgK7CQK7FwK7KAO7AgK9CQK9FwK9KAO9AgK+CQK+FwK+KAO+AgLECQLEFwLEKAPE - AwK7BgK7CgK7DwK7GAK7HwK7KQK7OAO7AwK9BgK9CgK9DwK9GAK9HwK9KQK9OAO9 - AwK+BgK+CgK+DwK+GAK+HwK+KQK+OAO+AwLEBgLECgLEDwLEGALEHwLEKQLEOAPE - AQLGFgPGAQLkFgPkAQLoFgPoAQLpFgPpAAMBAAOHAAOJAAOKAAOLAAOMAAONAAOP - AgLGCQLGFwLGKAPGAgLkCQLkFwLkKAPkAgLoCQLoFwLoKAPoAgLpCQLpFwLpKAPp - AwLGBgLGCgLGDwLGGALGHwLGKQLGOAPGAwLkBgLkCgLkDwLkGALkHwLkKQLkOAPk - AwLoBgLoCgLoDwLoGALoHwLoKQLoOAPoAwLpBgLpCgLpDwLpGALpHwLpKQLpOAPp - AQIBFgMBAQKHFgOHAQKJFgOJAQKKFgOKAQKLFgOLAQKMFgOMAQKNFgONAQKPFgOP - AgIBCQIBFwIBKAMBAgKHCQKHFwKHKAOHAgKJCQKJFwKJKAOJAgKKCQKKFwKKKAOK - AwIBBgIBCgIBDwIBGAIBHwIBKQIBOAMBAwKHBgKHCgKHDwKHGAKHHwKHKQKHOAOH - AwKJBgKJCgKJDwKJGAKJHwKJKQKJOAOJAwKKBgKKCgKKDwKKGAKKHwKKKQKKOAOK - AgKLCQKLFwKLKAOLAgKMCQKMFwKMKAOMAgKNCQKNFwKNKAONAgKPCQKPFwKPKAOP - AwKLBgKLCgKLDwKLGAKLHwKLKQKLOAOLAwKMBgKMCgKMDwKMGAKMHwKMKQKMOAOM - AwKNBgKNCgKNDwKNGAKNHwKNKQKNOAONAwKPBgKPCgKPDwKPGAKPHwKPKQKPOAOP - nQAAngAAoAAAoQAApAAApQAApwAAqAAArAAArQAArwAAsQAAtgAAuQAAvwAAzwAA - AAOTAAOVAAOWAAOXAAOYAAObAAOdAAOeAAOlAAOmAAOoAAOuAAOvAAO0AAO2AAO3 - AQKTFgOTAQKVFgOVAQKWFgOWAQKXFgOXAQKYFgOYAQKbFgObAQKdFgOdAQKeFgOe - AgKTCQKTFwKTKAOTAgKVCQKVFwKVKAOVAgKWCQKWFwKWKAOWAgKXCQKXFwKXKAOX - AwKTBgKTCgKTDwKTGAKTHwKTKQKTOAOTAwKVBgKVCgKVDwKVGAKVHwKVKQKVOAOV - AwKWBgKWCgKWDwKWGAKWHwKWKQKWOAOWAwKXBgKXCgKXDwKXGAKXHwKXKQKXOAOX - AgKYCQKYFwKYKAOYAgKbCQKbFwKbKAObAgKdCQKdFwKdKAOdAgKeCQKeFwKeKAOe - AwKYBgKYCgKYDwKYGAKYHwKYKQKYOAOYAwKbBgKbCgKbDwKbGAKbHwKbKQKbOAOb - AwKdBgKdCgKdDwKdGAKdHwKdKQKdOAOdAwKeBgKeCgKeDwKeGAKeHwKeKQKeOAOe - AQKlFgOlAQKmFgOmAQKoFgOoAQKuFgOuAQKvFgOvAQK0FgO0AQK2FgO2AQK3FgO3 - AgKlCQKlFwKlKAOlAgKmCQKmFwKmKAOmAgKoCQKoFwKoKAOoAgKuCQKuFwKuKAOu - AwKlBgKlCgKlDwKlGAKlHwKlKQKlOAOlAwKmBgKmCgKmDwKmGAKmHwKmKQKmOAOm - AwKoBgKoCgKoDwKoGAKoHwKoKQKoOAOoAwKuBgKuCgKuDwKuGAKuHwKuKQKuOAOu - AgKvCQKvFwKvKAOvAgK0CQK0FwK0KAO0AgK2CQK2FwK2KAO2AgK3CQK3FwK3KAO3 - AwKvBgKvCgKvDwKvGAKvHwKvKQKvOAOvAwK0BgK0CgK0DwK0GAK0HwK0KQK0OAO0 - AwK2BgK2CgK2DwK2GAK2HwK2KQK2OAO2AwK3BgK3CgK3DwK3GAK3HwK3KQK3OAO3 - AAO8AAO/AAPFAAPnAAPvsAAAsgAAswAAtwAAuAAAugAAuwAAwAAAxwAA0AAA3wAA - AQK8FgO8AQK/FgO/AQLFFgPFAQLnFgPnAQLvFgPvAAMJAAOOAAOQAAORAAOUAAOf - AgK8CQK8FwK8KAO8AgK/CQK/FwK/KAO/AgLFCQLFFwLFKAPFAgLnCQLnFwLnKAPn - AwK8BgK8CgK8DwK8GAK8HwK8KQK8OAO8AwK/BgK/CgK/DwK/GAK/HwK/KQK/OAO/ - AwLFBgLFCgLFDwLFGALFHwLFKQLFOAPFAwLnBgLnCgLnDwLnGALnHwLnKQLnOAPn - AgLvCQLvFwLvKAPvAQIJFgMJAQKOFgOOAQKQFgOQAQKRFgORAQKUFgOUAQKfFgOf - AwLvBgLvCgLvDwLvGALvHwLvKQLvOAPvAgIJCQIJFwIJKAMJAgKOCQKOFwKOKAOO - AwIJBgIJCgIJDwIJGAIJHwIJKQIJOAMJAwKOBgKOCgKODwKOGAKOHwKOKQKOOAOO - AgKQCQKQFwKQKAOQAgKRCQKRFwKRKAORAgKUCQKUFwKUKAOUAgKfCQKfFwKfKAOf - AwKQBgKQCgKQDwKQGAKQHwKQKQKQOAOQAwKRBgKRCgKRDwKRGAKRHwKRKQKROAOR - AwKUBgKUCgKUDwKUGAKUHwKUKQKUOAOUAwKfBgKfCgKfDwKfGAKfHwKfKQKfOAOf - AAOrAAPOAAPXAAPhAAPsAAPtvAAAvQAAwQAAxAAAyAAAywAA0QAA2AAA4AAA7gAA - AQKrFgOrAQLOFgPOAQLXFgPXAQLhFgPhAQLsFgPsAQLtFgPtAAPHAAPPAAPqAAPr - AgKrCQKrFwKrKAOrAgLOCQLOFwLOKAPOAgLXCQLXFwLXKAPXAgLhCQLhFwLhKAPh - AwKrBgKrCgKrDwKrGAKrHwKrKQKrOAOrAwLOBgLOCgLODwLOGALOHwLOKQLOOAPO - AwLXBgLXCgLXDwLXGALXHwLXKQLXOAPXAwLhBgLhCgLhDwLhGALhHwLhKQLhOAPh - AgLsCQLsFwLsKAPsAgLtCQLtFwLtKAPtAQLHFgPHAQLPFgPPAQLqFgPqAQLrFgPr - AwLsBgLsCgLsDwLsGALsHwLsKQLsOAPsAwLtBgLtCgLtDwLtGALtHwLtKQLtOAPt - AgLHCQLHFwLHKAPHAgLPCQLPFwLPKAPPAgLqCQLqFwLqKAPqAgLrCQLrFwLrKAPr - AwLHBgLHCgLHDwLHGALHHwLHKQLHOAPHAwLPBgLPCgLPDwLPGALPHwLPKQLPOAPP - AwLqBgLqCgLqDwLqGALqHwLqKQLqOAPqAwLrBgLrCgLrDwLrGALrHwLrKQLrOAPr - wgAAwwAAxQAAxgAAyQAAygAAzAAAzQAA0gAA1QAA2QAA3AAA4QAA5wAA7wAA9gAA - AAPAAAPBAAPIAAPJAAPKAAPNAAPSAAPVAAPaAAPbAAPuAAPwAAPyAAPzAAP/zgAA - AQLAFgPAAQLBFgPBAQLIFgPIAQLJFgPJAQLKFgPKAQLNFgPNAQLSFgPSAQLVFgPV - AgLACQLAFwLAKAPAAgLBCQLBFwLBKAPBAgLICQLIFwLIKAPIAgLJCQLJFwLJKAPJ - AwLABgLACgLADwLAGALAHwLAKQLAOAPAAwLBBgLBCgLBDwLBGALBHwLBKQLBOAPB - AwLIBgLICgLIDwLIGALIHwLIKQLIOAPIAwLJBgLJCgLJDwLJGALJHwLJKQLJOAPJ - AgLKCQLKFwLKKAPKAgLNCQLNFwLNKAPNAgLSCQLSFwLSKAPSAgLVCQLVFwLVKAPV - AwLKBgLKCgLKDwLKGALKHwLKKQLKOAPKAwLNBgLNCgLNDwLNGALNHwLNKQLNOAPN - AwLSBgLSCgLSDwLSGALSHwLSKQLSOAPSAwLVBgLVCgLVDwLVGALVHwLVKQLVOAPV - AQLaFgPaAQLbFgPbAQLuFgPuAQLwFgPwAQLyFgPyAQLzFgPzAQL/FgP/AAPLAAPM - AgLaCQLaFwLaKAPaAgLbCQLbFwLbKAPbAgLuCQLuFwLuKAPuAgLwCQLwFwLwKAPw - AwLaBgLaCgLaDwLaGALaHwLaKQLaOAPaAwLbBgLbCgLbDwLbGALbHwLbKQLbOAPb - AwLuBgLuCgLuDwLuGALuHwLuKQLuOAPuAwLwBgLwCgLwDwLwGALwHwLwKQLwOAPw - AgLyCQLyFwLyKAPyAgLzCQLzFwLzKAPzAgL/CQL/FwL/KAP/AQLLFgPLAQLMFgPM - AwLyBgLyCgLyDwLyGALyHwLyKQLyOAPyAwLzBgLzCgLzDwLzGALzHwLzKQLzOAPz - AwL/BgL/CgL/DwL/GAL/HwL/KQL/OAP/AgLLCQLLFwLLKAPLAgLMCQLMFwLMKAPM - AwLLBgLLCgLLDwLLGALLHwLLKQLLOAPLAwLMBgLMCgLMDwLMGALMHwLMKQLMOAPM - 0wAA1AAA1gAA1wAA2gAA2wAA3QAA3gAA4gAA5AAA6AAA6wAA8AAA8wAA9wAA+gAA - AAPTAAPUAAPWAAPdAAPeAAPfAAPxAAP0AAP1AAP2AAP3AAP4AAP6AAP7AAP8AAP9 - AQLTFgPTAQLUFgPUAQLWFgPWAQLdFgPdAQLeFgPeAQLfFgPfAQLxFgPxAQL0FgP0 - AgLTCQLTFwLTKAPTAgLUCQLUFwLUKAPUAgLWCQLWFwLWKAPWAgLdCQLdFwLdKAPd - AwLTBgLTCgLTDwLTGALTHwLTKQLTOAPTAwLUBgLUCgLUDwLUGALUHwLUKQLUOAPU - AwLWBgLWCgLWDwLWGALWHwLWKQLWOAPWAwLdBgLdCgLdDwLdGALdHwLdKQLdOAPd - AgLeCQLeFwLeKAPeAgLfCQLfFwLfKAPfAgLxCQLxFwLxKAPxAgL0CQL0FwL0KAP0 - AwLeBgLeCgLeDwLeGALeHwLeKQLeOAPeAwLfBgLfCgLfDwLfGALfHwLfKQLfOAPf - AwLxBgLxCgLxDwLxGALxHwLxKQLxOAPxAwL0BgL0CgL0DwL0GAL0HwL0KQL0OAP0 - AQL1FgP1AQL2FgP2AQL3FgP3AQL4FgP4AQL6FgP6AQL7FgP7AQL8FgP8AQL9FgP9 - AgL1CQL1FwL1KAP1AgL2CQL2FwL2KAP2AgL3CQL3FwL3KAP3AgL4CQL4FwL4KAP4 - AwL1BgL1CgL1DwL1GAL1HwL1KQL1OAP1AwL2BgL2CgL2DwL2GAL2HwL2KQL2OAP2 - AwL3BgL3CgL3DwL3GAL3HwL3KQL3OAP3AwL4BgL4CgL4DwL4GAL4HwL4KQL4OAP4 - AgL6CQL6FwL6KAP6AgL7CQL7FwL7KAP7AgL8CQL8FwL8KAP8AgL9CQL9FwL9KAP9 - AwL6BgL6CgL6DwL6GAL6HwL6KQL6OAP6AwL7BgL7CgL7DwL7GAL7HwL7KQL7OAP7 - AwL8BgL8CgL8DwL8GAL8HwL8KQL8OAP8AwL9BgL9CgL9DwL9GAL9HwL9KQL9OAP9 - AAP+4wAA5QAA5gAA6QAA6gAA7AAA7QAA8QAA8gAA9AAA9QAA+AAA+QAA+wAA/AAA - AQL+FgP+AAMCAAMDAAMEAAMFAAMGAAMHAAMIAAMLAAMMAAMOAAMPAAMQAAMRAAMS - AgL+CQL+FwL+KAP+AQICFgMCAQIDFgMDAQIEFgMEAQIFFgMFAQIGFgMGAQIHFgMH - AwL+BgL+CgL+DwL+GAL+HwL+KQL+OAP+AgICCQICFwICKAMCAgIDCQIDFwIDKAMD - AwICBgICCgICDwICGAICHwICKQICOAMCAwIDBgIDCgIDDwIDGAIDHwIDKQIDOAMD - AgIECQIEFwIEKAMEAgIFCQIFFwIFKAMFAgIGCQIGFwIGKAMGAgIHCQIHFwIHKAMH - AwIEBgIECgIEDwIEGAIEHwIEKQIEOAMEAwIFBgIFCgIFDwIFGAIFHwIFKQIFOAMF - AwIGBgIGCgIGDwIGGAIGHwIGKQIGOAMGAwIHBgIHCgIHDwIHGAIHHwIHKQIHOAMH - AQIIFgMIAQILFgMLAQIMFgMMAQIOFgMOAQIPFgMPAQIQFgMQAQIRFgMRAQISFgMS - AgIICQIIFwIIKAMIAgILCQILFwILKAMLAgIMCQIMFwIMKAMMAgIOCQIOFwIOKAMO - AwIIBgIICgIIDwIIGAIIHwIIKQIIOAMIAwILBgILCgILDwILGAILHwILKQILOAML - AwIMBgIMCgIMDwIMGAIMHwIMKQIMOAMMAwIOBgIOCgIODwIOGAIOHwIOKQIOOAMO - AgIPCQIPFwIPKAMPAgIQCQIQFwIQKAMQAgIRCQIRFwIRKAMRAgISCQISFwISKAMS - AwIPBgIPCgIPDwIPGAIPHwIPKQIPOAMPAwIQBgIQCgIQDwIQGAIQHwIQKQIQOAMQ - AwIRBgIRCgIRDwIRGAIRHwIRKQIROAMRAwISBgISCgISDwISGAISHwISKQISOAMS - AAMTAAMUAAMVAAMXAAMYAAMZAAMaAAMbAAMcAAMdAAMeAAMfAAN/AAPcAAP5/QAA - AQITFgMTAQIUFgMUAQIVFgMVAQIXFgMXAQIYFgMYAQIZFgMZAQIaFgMaAQIbFgMb - AgITCQITFwITKAMTAgIUCQIUFwIUKAMUAgIVCQIVFwIVKAMVAgIXCQIXFwIXKAMX - AwITBgITCgITDwITGAITHwITKQITOAMTAwIUBgIUCgIUDwIUGAIUHwIUKQIUOAMU - AwIVBgIVCgIVDwIVGAIVHwIVKQIVOAMVAwIXBgIXCgIXDwIXGAIXHwIXKQIXOAMX - AgIYCQIYFwIYKAMYAgIZCQIZFwIZKAMZAgIaCQIaFwIaKAMaAgIbCQIbFwIbKAMb - AwIYBgIYCgIYDwIYGAIYHwIYKQIYOAMYAwIZBgIZCgIZDwIZGAIZHwIZKQIZOAMZ - AwIaBgIaCgIaDwIaGAIaHwIaKQIaOAMaAwIbBgIbCgIbDwIbGAIbHwIbKQIbOAMb - AQIcFgMcAQIdFgMdAQIeFgMeAQIfFgMfAQJ/FgN/AQLcFgPcAQL5FgP5/gAA/wAA - AgIcCQIcFwIcKAMcAgIdCQIdFwIdKAMdAgIeCQIeFwIeKAMeAgIfCQIfFwIfKAMf - AwIcBgIcCgIcDwIcGAIcHwIcKQIcOAMcAwIdBgIdCgIdDwIdGAIdHwIdKQIdOAMd - AwIeBgIeCgIeDwIeGAIeHwIeKQIeOAMeAwIfBgIfCgIfDwIfGAIfHwIfKQIfOAMf - AgJ/CQJ/FwJ/KAN/AgLcCQLcFwLcKAPcAgL5CQL5FwL5KAP5AAMKAAMNAAMWAAQA - AwJ/BgJ/CgJ/DwJ/GAJ/HwJ/KQJ/OAN/AwLcBgLcCgLcDwLcGALcHwLcKQLcOAPc - AwL5BgL5CgL5DwL5GAL5HwL5KQL5OAP5AQIKFgMKAQINFgMNAQIWFgMWAAQAAAQA - AgIKCQIKFwIKKAMKAgINCQINFwINKAMNAgIWCQIWFwIWKAMWAAQAAAQAAAQAAAQA - AwIKBgIKCgIKDwIKGAIKHwIKKQIKOAMKAwINBgINCgINDwINGAINHwINKQINOAMN - AwIWBgIWCgIWDwIWGAIWHwIWKQIWOAMWAAQAAAQAAAQAAAQAAAQAAAQAAAQAAAQA - """ + BAAABQAABwAACAAACwAADAAAEAAAEwAAGQAAHAAAIAAAIwAAKgAAMQAAOQAAQAEA + AAMwAAMxAAMyAANhAANjAANlAANpAANvAANzAAN0DQAADgAAEQAAEgAAFAAAFQAA + AQIwFgMwAQIxFgMxAQIyFgMyAQJhFgNhAQJjFgNjAQJlFgNlAQJpFgNpAQJvFgNv + AgIwCQIwFwIwKAMwAgIxCQIxFwIxKAMxAgIyCQIyFwIyKAMyAgJhCQJhFwJhKANh + AwIwBgIwCgIwDwIwGAIwHwIwKQIwOAMwAwIxBgIxCgIxDwIxGAIxHwIxKQIxOAMx + AwIyBgIyCgIyDwIyGAIyHwIyKQIyOAMyAwJhBgJhCgJhDwJhGAJhHwJhKQJhOANh + AgJjCQJjFwJjKANjAgJlCQJlFwJlKANlAgJpCQJpFwJpKANpAgJvCQJvFwJvKANv + AwJjBgJjCgJjDwJjGAJjHwJjKQJjOANjAwJlBgJlCgJlDwJlGAJlHwJlKQJlOANl + AwJpBgJpCgJpDwJpGAJpHwJpKQJpOANpAwJvBgJvCgJvDwJvGAJvHwJvKQJvOANv + AQJzFgNzAQJ0FgN0AAMgAAMlAAMtAAMuAAMvAAMzAAM0AAM1AAM2AAM3AAM4AAM5 + AgJzCQJzFwJzKANzAgJ0CQJ0FwJ0KAN0AQIgFgMgAQIlFgMlAQItFgMtAQIuFgMu + AwJzBgJzCgJzDwJzGAJzHwJzKQJzOANzAwJ0BgJ0CgJ0DwJ0GAJ0HwJ0KQJ0OAN0 + AgIgCQIgFwIgKAMgAgIlCQIlFwIlKAMlAgItCQItFwItKAMtAgIuCQIuFwIuKAMu + AwIgBgIgCgIgDwIgGAIgHwIgKQIgOAMgAwIlBgIlCgIlDwIlGAIlHwIlKQIlOAMl + AwItBgItCgItDwItGAItHwItKQItOAMtAwIuBgIuCgIuDwIuGAIuHwIuKQIuOAMu + AQIvFgMvAQIzFgMzAQI0FgM0AQI1FgM1AQI2FgM2AQI3FgM3AQI4FgM4AQI5FgM5 + AgIvCQIvFwIvKAMvAgIzCQIzFwIzKAMzAgI0CQI0FwI0KAM0AgI1CQI1FwI1KAM1 + AwIvBgIvCgIvDwIvGAIvHwIvKQIvOAMvAwIzBgIzCgIzDwIzGAIzHwIzKQIzOAMz + AwI0BgI0CgI0DwI0GAI0HwI0KQI0OAM0AwI1BgI1CgI1DwI1GAI1HwI1KQI1OAM1 + AgI2CQI2FwI2KAM2AgI3CQI3FwI3KAM3AgI4CQI4FwI4KAM4AgI5CQI5FwI5KAM5 + AwI2BgI2CgI2DwI2GAI2HwI2KQI2OAM2AwI3BgI3CgI3DwI3GAI3HwI3KQI3OAM3 + AwI4BgI4CgI4DwI4GAI4HwI4KQI4OAM4AwI5BgI5CgI5DwI5GAI5HwI5KQI5OAM5 + GgAAGwAAHQAAHgAAIQAAIgAAJAAAJQAAKwAALgAAMgAANQAAOgAAPQAAQQAARAEA + AAM9AANBAANfAANiAANkAANmAANnAANoAANsAANtAANuAANwAANyAAN1JgAAJwAA + AQI9FgM9AQJBFgNBAQJfFgNfAQJiFgNiAQJkFgNkAQJmFgNmAQJnFgNnAQJoFgNo + AgI9CQI9FwI9KAM9AgJBCQJBFwJBKANBAgJfCQJfFwJfKANfAgJiCQJiFwJiKANi + AwI9BgI9CgI9DwI9GAI9HwI9KQI9OAM9AwJBBgJBCgJBDwJBGAJBHwJBKQJBOANB + AwJfBgJfCgJfDwJfGAJfHwJfKQJfOANfAwJiBgJiCgJiDwJiGAJiHwJiKQJiOANi + AgJkCQJkFwJkKANkAgJmCQJmFwJmKANmAgJnCQJnFwJnKANnAgJoCQJoFwJoKANo + AwJkBgJkCgJkDwJkGAJkHwJkKQJkOANkAwJmBgJmCgJmDwJmGAJmHwJmKQJmOANm + AwJnBgJnCgJnDwJnGAJnHwJnKQJnOANnAwJoBgJoCgJoDwJoGAJoHwJoKQJoOANo + AQJsFgNsAQJtFgNtAQJuFgNuAQJwFgNwAQJyFgNyAQJ1FgN1AAM6AANCAANDAANE + AgJsCQJsFwJsKANsAgJtCQJtFwJtKANtAgJuCQJuFwJuKANuAgJwCQJwFwJwKANw + AwJsBgJsCgJsDwJsGAJsHwJsKQJsOANsAwJtBgJtCgJtDwJtGAJtHwJtKQJtOANt + AwJuBgJuCgJuDwJuGAJuHwJuKQJuOANuAwJwBgJwCgJwDwJwGAJwHwJwKQJwOANw + AgJyCQJyFwJyKANyAgJ1CQJ1FwJ1KAN1AQI6FgM6AQJCFgNCAQJDFgNDAQJEFgNE + AwJyBgJyCgJyDwJyGAJyHwJyKQJyOANyAwJ1BgJ1CgJ1DwJ1GAJ1HwJ1KQJ1OAN1 + AgI6CQI6FwI6KAM6AgJCCQJCFwJCKANCAgJDCQJDFwJDKANDAgJECQJEFwJEKANE + AwI6BgI6CgI6DwI6GAI6HwI6KQI6OAM6AwJCBgJCCgJCDwJCGAJCHwJCKQJCOANC + AwJDBgJDCgJDDwJDGAJDHwJDKQJDOANDAwJEBgJECgJEDwJEGAJEHwJEKQJEOANE + LAAALQAALwAAMAAAMwAANAAANgAANwAAOwAAPAAAPgAAPwAAQgAAQwAARQAASAEA + AANFAANGAANHAANIAANJAANKAANLAANMAANNAANOAANPAANQAANRAANSAANTAANU + AQJFFgNFAQJGFgNGAQJHFgNHAQJIFgNIAQJJFgNJAQJKFgNKAQJLFgNLAQJMFgNM + AgJFCQJFFwJFKANFAgJGCQJGFwJGKANGAgJHCQJHFwJHKANHAgJICQJIFwJIKANI + AwJFBgJFCgJFDwJFGAJFHwJFKQJFOANFAwJGBgJGCgJGDwJGGAJGHwJGKQJGOANG + AwJHBgJHCgJHDwJHGAJHHwJHKQJHOANHAwJIBgJICgJIDwJIGAJIHwJIKQJIOANI + AgJJCQJJFwJJKANJAgJKCQJKFwJKKANKAgJLCQJLFwJLKANLAgJMCQJMFwJMKANM + AwJJBgJJCgJJDwJJGAJJHwJJKQJJOANJAwJKBgJKCgJKDwJKGAJKHwJKKQJKOANK + AwJLBgJLCgJLDwJLGAJLHwJLKQJLOANLAwJMBgJMCgJMDwJMGAJMHwJMKQJMOANM + AQJNFgNNAQJOFgNOAQJPFgNPAQJQFgNQAQJRFgNRAQJSFgNSAQJTFgNTAQJUFgNU + AgJNCQJNFwJNKANNAgJOCQJOFwJOKANOAgJPCQJPFwJPKANPAgJQCQJQFwJQKANQ + AwJNBgJNCgJNDwJNGAJNHwJNKQJNOANNAwJOBgJOCgJODwJOGAJOHwJOKQJOOANO + AwJPBgJPCgJPDwJPGAJPHwJPKQJPOANPAwJQBgJQCgJQDwJQGAJQHwJQKQJQOANQ + AgJRCQJRFwJRKANRAgJSCQJSFwJSKANSAgJTCQJTFwJTKANTAgJUCQJUFwJUKANU + AwJRBgJRCgJRDwJRGAJRHwJRKQJROANRAwJSBgJSCgJSDwJSGAJSHwJSKQJSOANS + AwJTBgJTCgJTDwJTGAJTHwJTKQJTOANTAwJUBgJUCgJUDwJUGAJUHwJUKQJUOANU + AANVAANWAANXAANZAANqAANrAANxAAN2AAN3AAN4AAN5AAN6RgAARwAASQAASgEA + AQJVFgNVAQJWFgNWAQJXFgNXAQJZFgNZAQJqFgNqAQJrFgNrAQJxFgNxAQJ2FgN2 + AgJVCQJVFwJVKANVAgJWCQJWFwJWKANWAgJXCQJXFwJXKANXAgJZCQJZFwJZKANZ + AwJVBgJVCgJVDwJVGAJVHwJVKQJVOANVAwJWBgJWCgJWDwJWGAJWHwJWKQJWOANW + AwJXBgJXCgJXDwJXGAJXHwJXKQJXOANXAwJZBgJZCgJZDwJZGAJZHwJZKQJZOANZ + AgJqCQJqFwJqKANqAgJrCQJrFwJrKANrAgJxCQJxFwJxKANxAgJ2CQJ2FwJ2KAN2 + AwJqBgJqCgJqDwJqGAJqHwJqKQJqOANqAwJrBgJrCgJrDwJrGAJrHwJrKQJrOANr + AwJxBgJxCgJxDwJxGAJxHwJxKQJxOANxAwJ2BgJ2CgJ2DwJ2GAJ2HwJ2KQJ2OAN2 + AQJ3FgN3AQJ4FgN4AQJ5FgN5AQJ6FgN6AAMmAAMqAAMsAAM7AANYAANaSwAATgAA + AgJ3CQJ3FwJ3KAN3AgJ4CQJ4FwJ4KAN4AgJ5CQJ5FwJ5KAN5AgJ6CQJ6FwJ6KAN6 + AwJ3BgJ3CgJ3DwJ3GAJ3HwJ3KQJ3OAN3AwJ4BgJ4CgJ4DwJ4GAJ4HwJ4KQJ4OAN4 + AwJ5BgJ5CgJ5DwJ5GAJ5HwJ5KQJ5OAN5AwJ6BgJ6CgJ6DwJ6GAJ6HwJ6KQJ6OAN6 + AQImFgMmAQIqFgMqAQIsFgMsAQI7FgM7AQJYFgNYAQJaFgNaTAAATQAATwAAUQAA + AgImCQImFwImKAMmAgIqCQIqFwIqKAMqAgIsCQIsFwIsKAMsAgI7CQI7FwI7KAM7 + AwImBgImCgImDwImGAImHwImKQImOAMmAwIqBgIqCgIqDwIqGAIqHwIqKQIqOAMq + AwIsBgIsCgIsDwIsGAIsHwIsKQIsOAMsAwI7BgI7CgI7DwI7GAI7HwI7KQI7OAM7 + AgJYCQJYFwJYKANYAgJaCQJaFwJaKANaAAMhAAMiAAMoAAMpAAM/UAAAUgAAVAAA + AwJYBgJYCgJYDwJYGAJYHwJYKQJYOANYAwJaBgJaCgJaDwJaGAJaHwJaKQJaOANa + AQIhFgMhAQIiFgMiAQIoFgMoAQIpFgMpAQI/FgM/AAMnAAMrAAN8UwAAVQAAWAAA + AgIhCQIhFwIhKAMhAgIiCQIiFwIiKAMiAgIoCQIoFwIoKAMoAgIpCQIpFwIpKAMp + AwIhBgIhCgIhDwIhGAIhHwIhKQIhOAMhAwIiBgIiCgIiDwIiGAIiHwIiKQIiOAMi + AwIoBgIoCgIoDwIoGAIoHwIoKQIoOAMoAwIpBgIpCgIpDwIpGAIpHwIpKQIpOAMp + AgI/CQI/FwI/KAM/AQInFgMnAQIrFgMrAQJ8FgN8AAMjAAM+VgAAVwAAWQAAWgAA + AwI/BgI/CgI/DwI/GAI/HwI/KQI/OAM/AgInCQInFwInKAMnAgIrCQIrFwIrKAMr + AwInBgInCgInDwInGAInHwInKQInOAMnAwIrBgIrCgIrDwIrGAIrHwIrKQIrOAMr + AgJ8CQJ8FwJ8KAN8AQIjFgMjAQI+FgM+AAMAAAMkAANAAANbAANdAAN+WwAAXAAA + AwJ8BgJ8CgJ8DwJ8GAJ8HwJ8KQJ8OAN8AgIjCQIjFwIjKAMjAgI+CQI+FwI+KAM+ + AwIjBgIjCgIjDwIjGAIjHwIjKQIjOAMjAwI+BgI+CgI+DwI+GAI+HwI+KQI+OAM+ + AQIAFgMAAQIkFgMkAQJAFgNAAQJbFgNbAQJdFgNdAQJ+FgN+AANeAAN9XQAAXgAA + AgIACQIAFwIAKAMAAgIkCQIkFwIkKAMkAgJACQJAFwJAKANAAgJbCQJbFwJbKANb + AwIABgIACgIADwIAGAIAHwIAKQIAOAMAAwIkBgIkCgIkDwIkGAIkHwIkKQIkOAMk + AwJABgJACgJADwJAGAJAHwJAKQJAOANAAwJbBgJbCgJbDwJbGAJbHwJbKQJbOANb + AgJdCQJdFwJdKANdAgJ+CQJ+FwJ+KAN+AQJeFgNeAQJ9FgN9AAM8AANgAAN7XwAA + AwJdBgJdCgJdDwJdGAJdHwJdKQJdOANdAwJ+BgJ+CgJ+DwJ+GAJ+HwJ+KQJ+OAN+ + AgJeCQJeFwJeKANeAgJ9CQJ9FwJ9KAN9AQI8FgM8AQJgFgNgAQJ7FgN7YAAAbgAA + AwJeBgJeCgJeDwJeGAJeHwJeKQJeOANeAwJ9BgJ9CgJ9DwJ9GAJ9HwJ9KQJ9OAN9 + AgI8CQI8FwI8KAM8AgJgCQJgFwJgKANgAgJ7CQJ7FwJ7KAN7YQAAZQAAbwAAhQAA + AwI8BgI8CgI8DwI8GAI8HwI8KQI8OAM8AwJgBgJgCgJgDwJgGAJgHwJgKQJgOANg + AwJ7BgJ7CgJ7DwJ7GAJ7HwJ7KQJ7OAN7YgAAYwAAZgAAaQAAcAAAdwAAhgAAmQAA + AANcAAPDAAPQZAAAZwAAaAAAagAAawAAcQAAdAAAeAAAfgAAhwAAjgAAmgAAqQAA + AQJcFgNcAQLDFgPDAQLQFgPQAAOAAAOCAAODAAOiAAO4AAPCAAPgAAPibAAAbQAA + AgJcCQJcFwJcKANcAgLDCQLDFwLDKAPDAgLQCQLQFwLQKAPQAQKAFgOAAQKCFgOC + AwJcBgJcCgJcDwJcGAJcHwJcKQJcOANcAwLDBgLDCgLDDwLDGALDHwLDKQLDOAPD + AwLQBgLQCgLQDwLQGALQHwLQKQLQOAPQAgKACQKAFwKAKAOAAgKCCQKCFwKCKAOC + AwKABgKACgKADwKAGAKAHwKAKQKAOAOAAwKCBgKCCgKCDwKCGAKCHwKCKQKCOAOC + AQKDFgODAQKiFgOiAQK4FgO4AQLCFgPCAQLgFgPgAQLiFgPiAAOZAAOhAAOnAAOs + AgKDCQKDFwKDKAODAgKiCQKiFwKiKAOiAgK4CQK4FwK4KAO4AgLCCQLCFwLCKAPC + AwKDBgKDCgKDDwKDGAKDHwKDKQKDOAODAwKiBgKiCgKiDwKiGAKiHwKiKQKiOAOi + AwK4BgK4CgK4DwK4GAK4HwK4KQK4OAO4AwLCBgLCCgLCDwLCGALCHwLCKQLCOAPC + AgLgCQLgFwLgKAPgAgLiCQLiFwLiKAPiAQKZFgOZAQKhFgOhAQKnFgOnAQKsFgOs + AwLgBgLgCgLgDwLgGALgHwLgKQLgOAPgAwLiBgLiCgLiDwLiGALiHwLiKQLiOAPi + AgKZCQKZFwKZKAOZAgKhCQKhFwKhKAOhAgKnCQKnFwKnKAOnAgKsCQKsFwKsKAOs + AwKZBgKZCgKZDwKZGAKZHwKZKQKZOAOZAwKhBgKhCgKhDwKhGAKhHwKhKQKhOAOh + AwKnBgKnCgKnDwKnGAKnHwKnKQKnOAOnAwKsBgKsCgKsDwKsGAKsHwKsKQKsOAOs + cgAAcwAAdQAAdgAAeQAAewAAfwAAggAAiAAAiwAAjwAAkgAAmwAAogAAqgAAtAAA + AAOwAAOxAAOzAAPRAAPYAAPZAAPjAAPlAAPmegAAfAAAfQAAgAAAgQAAgwAAhAAA + AQKwFgOwAQKxFgOxAQKzFgOzAQLRFgPRAQLYFgPYAQLZFgPZAQLjFgPjAQLlFgPl + AgKwCQKwFwKwKAOwAgKxCQKxFwKxKAOxAgKzCQKzFwKzKAOzAgLRCQLRFwLRKAPR + AwKwBgKwCgKwDwKwGAKwHwKwKQKwOAOwAwKxBgKxCgKxDwKxGAKxHwKxKQKxOAOx + AwKzBgKzCgKzDwKzGAKzHwKzKQKzOAOzAwLRBgLRCgLRDwLRGALRHwLRKQLROAPR + AgLYCQLYFwLYKAPYAgLZCQLZFwLZKAPZAgLjCQLjFwLjKAPjAgLlCQLlFwLlKAPl + AwLYBgLYCgLYDwLYGALYHwLYKQLYOAPYAwLZBgLZCgLZDwLZGALZHwLZKQLZOAPZ + AwLjBgLjCgLjDwLjGALjHwLjKQLjOAPjAwLlBgLlCgLlDwLlGALlHwLlKQLlOAPl + AQLmFgPmAAOBAAOEAAOFAAOGAAOIAAOSAAOaAAOcAAOgAAOjAAOkAAOpAAOqAAOt + AgLmCQLmFwLmKAPmAQKBFgOBAQKEFgOEAQKFFgOFAQKGFgOGAQKIFgOIAQKSFgOS + AwLmBgLmCgLmDwLmGALmHwLmKQLmOAPmAgKBCQKBFwKBKAOBAgKECQKEFwKEKAOE + AwKBBgKBCgKBDwKBGAKBHwKBKQKBOAOBAwKEBgKECgKEDwKEGAKEHwKEKQKEOAOE + AgKFCQKFFwKFKAOFAgKGCQKGFwKGKAOGAgKICQKIFwKIKAOIAgKSCQKSFwKSKAOS + AwKFBgKFCgKFDwKFGAKFHwKFKQKFOAOFAwKGBgKGCgKGDwKGGAKGHwKGKQKGOAOG + AwKIBgKICgKIDwKIGAKIHwKIKQKIOAOIAwKSBgKSCgKSDwKSGAKSHwKSKQKSOAOS + AQKaFgOaAQKcFgOcAQKgFgOgAQKjFgOjAQKkFgOkAQKpFgOpAQKqFgOqAQKtFgOt + AgKaCQKaFwKaKAOaAgKcCQKcFwKcKAOcAgKgCQKgFwKgKAOgAgKjCQKjFwKjKAOj + AwKaBgKaCgKaDwKaGAKaHwKaKQKaOAOaAwKcBgKcCgKcDwKcGAKcHwKcKQKcOAOc + AwKgBgKgCgKgDwKgGAKgHwKgKQKgOAOgAwKjBgKjCgKjDwKjGAKjHwKjKQKjOAOj + AgKkCQKkFwKkKAOkAgKpCQKpFwKpKAOpAgKqCQKqFwKqKAOqAgKtCQKtFwKtKAOt + AwKkBgKkCgKkDwKkGAKkHwKkKQKkOAOkAwKpBgKpCgKpDwKpGAKpHwKpKQKpOAOp + AwKqBgKqCgKqDwKqGAKqHwKqKQKqOAOqAwKtBgKtCgKtDwKtGAKtHwKtKQKtOAOt + iQAAigAAjAAAjQAAkAAAkQAAkwAAlgAAnAAAnwAAowAApgAAqwAArgAAtQAAvgAA + AAOyAAO1AAO5AAO6AAO7AAO9AAO+AAPEAAPGAAPkAAPoAAPplAAAlQAAlwAAmAAA + AQKyFgOyAQK1FgO1AQK5FgO5AQK6FgO6AQK7FgO7AQK9FgO9AQK+FgO+AQLEFgPE + AgKyCQKyFwKyKAOyAgK1CQK1FwK1KAO1AgK5CQK5FwK5KAO5AgK6CQK6FwK6KAO6 + AwKyBgKyCgKyDwKyGAKyHwKyKQKyOAOyAwK1BgK1CgK1DwK1GAK1HwK1KQK1OAO1 + AwK5BgK5CgK5DwK5GAK5HwK5KQK5OAO5AwK6BgK6CgK6DwK6GAK6HwK6KQK6OAO6 + AgK7CQK7FwK7KAO7AgK9CQK9FwK9KAO9AgK+CQK+FwK+KAO+AgLECQLEFwLEKAPE + AwK7BgK7CgK7DwK7GAK7HwK7KQK7OAO7AwK9BgK9CgK9DwK9GAK9HwK9KQK9OAO9 + AwK+BgK+CgK+DwK+GAK+HwK+KQK+OAO+AwLEBgLECgLEDwLEGALEHwLEKQLEOAPE + AQLGFgPGAQLkFgPkAQLoFgPoAQLpFgPpAAMBAAOHAAOJAAOKAAOLAAOMAAONAAOP + AgLGCQLGFwLGKAPGAgLkCQLkFwLkKAPkAgLoCQLoFwLoKAPoAgLpCQLpFwLpKAPp + AwLGBgLGCgLGDwLGGALGHwLGKQLGOAPGAwLkBgLkCgLkDwLkGALkHwLkKQLkOAPk + AwLoBgLoCgLoDwLoGALoHwLoKQLoOAPoAwLpBgLpCgLpDwLpGALpHwLpKQLpOAPp + AQIBFgMBAQKHFgOHAQKJFgOJAQKKFgOKAQKLFgOLAQKMFgOMAQKNFgONAQKPFgOP + AgIBCQIBFwIBKAMBAgKHCQKHFwKHKAOHAgKJCQKJFwKJKAOJAgKKCQKKFwKKKAOK + AwIBBgIBCgIBDwIBGAIBHwIBKQIBOAMBAwKHBgKHCgKHDwKHGAKHHwKHKQKHOAOH + AwKJBgKJCgKJDwKJGAKJHwKJKQKJOAOJAwKKBgKKCgKKDwKKGAKKHwKKKQKKOAOK + AgKLCQKLFwKLKAOLAgKMCQKMFwKMKAOMAgKNCQKNFwKNKAONAgKPCQKPFwKPKAOP + AwKLBgKLCgKLDwKLGAKLHwKLKQKLOAOLAwKMBgKMCgKMDwKMGAKMHwKMKQKMOAOM + AwKNBgKNCgKNDwKNGAKNHwKNKQKNOAONAwKPBgKPCgKPDwKPGAKPHwKPKQKPOAOP + nQAAngAAoAAAoQAApAAApQAApwAAqAAArAAArQAArwAAsQAAtgAAuQAAvwAAzwAA + AAOTAAOVAAOWAAOXAAOYAAObAAOdAAOeAAOlAAOmAAOoAAOuAAOvAAO0AAO2AAO3 + AQKTFgOTAQKVFgOVAQKWFgOWAQKXFgOXAQKYFgOYAQKbFgObAQKdFgOdAQKeFgOe + AgKTCQKTFwKTKAOTAgKVCQKVFwKVKAOVAgKWCQKWFwKWKAOWAgKXCQKXFwKXKAOX + AwKTBgKTCgKTDwKTGAKTHwKTKQKTOAOTAwKVBgKVCgKVDwKVGAKVHwKVKQKVOAOV + AwKWBgKWCgKWDwKWGAKWHwKWKQKWOAOWAwKXBgKXCgKXDwKXGAKXHwKXKQKXOAOX + AgKYCQKYFwKYKAOYAgKbCQKbFwKbKAObAgKdCQKdFwKdKAOdAgKeCQKeFwKeKAOe + AwKYBgKYCgKYDwKYGAKYHwKYKQKYOAOYAwKbBgKbCgKbDwKbGAKbHwKbKQKbOAOb + AwKdBgKdCgKdDwKdGAKdHwKdKQKdOAOdAwKeBgKeCgKeDwKeGAKeHwKeKQKeOAOe + AQKlFgOlAQKmFgOmAQKoFgOoAQKuFgOuAQKvFgOvAQK0FgO0AQK2FgO2AQK3FgO3 + AgKlCQKlFwKlKAOlAgKmCQKmFwKmKAOmAgKoCQKoFwKoKAOoAgKuCQKuFwKuKAOu + AwKlBgKlCgKlDwKlGAKlHwKlKQKlOAOlAwKmBgKmCgKmDwKmGAKmHwKmKQKmOAOm + AwKoBgKoCgKoDwKoGAKoHwKoKQKoOAOoAwKuBgKuCgKuDwKuGAKuHwKuKQKuOAOu + AgKvCQKvFwKvKAOvAgK0CQK0FwK0KAO0AgK2CQK2FwK2KAO2AgK3CQK3FwK3KAO3 + AwKvBgKvCgKvDwKvGAKvHwKvKQKvOAOvAwK0BgK0CgK0DwK0GAK0HwK0KQK0OAO0 + AwK2BgK2CgK2DwK2GAK2HwK2KQK2OAO2AwK3BgK3CgK3DwK3GAK3HwK3KQK3OAO3 + AAO8AAO/AAPFAAPnAAPvsAAAsgAAswAAtwAAuAAAugAAuwAAwAAAxwAA0AAA3wAA + AQK8FgO8AQK/FgO/AQLFFgPFAQLnFgPnAQLvFgPvAAMJAAOOAAOQAAORAAOUAAOf + AgK8CQK8FwK8KAO8AgK/CQK/FwK/KAO/AgLFCQLFFwLFKAPFAgLnCQLnFwLnKAPn + AwK8BgK8CgK8DwK8GAK8HwK8KQK8OAO8AwK/BgK/CgK/DwK/GAK/HwK/KQK/OAO/ + AwLFBgLFCgLFDwLFGALFHwLFKQLFOAPFAwLnBgLnCgLnDwLnGALnHwLnKQLnOAPn + AgLvCQLvFwLvKAPvAQIJFgMJAQKOFgOOAQKQFgOQAQKRFgORAQKUFgOUAQKfFgOf + AwLvBgLvCgLvDwLvGALvHwLvKQLvOAPvAgIJCQIJFwIJKAMJAgKOCQKOFwKOKAOO + AwIJBgIJCgIJDwIJGAIJHwIJKQIJOAMJAwKOBgKOCgKODwKOGAKOHwKOKQKOOAOO + AgKQCQKQFwKQKAOQAgKRCQKRFwKRKAORAgKUCQKUFwKUKAOUAgKfCQKfFwKfKAOf + AwKQBgKQCgKQDwKQGAKQHwKQKQKQOAOQAwKRBgKRCgKRDwKRGAKRHwKRKQKROAOR + AwKUBgKUCgKUDwKUGAKUHwKUKQKUOAOUAwKfBgKfCgKfDwKfGAKfHwKfKQKfOAOf + AAOrAAPOAAPXAAPhAAPsAAPtvAAAvQAAwQAAxAAAyAAAywAA0QAA2AAA4AAA7gAA + AQKrFgOrAQLOFgPOAQLXFgPXAQLhFgPhAQLsFgPsAQLtFgPtAAPHAAPPAAPqAAPr + AgKrCQKrFwKrKAOrAgLOCQLOFwLOKAPOAgLXCQLXFwLXKAPXAgLhCQLhFwLhKAPh + AwKrBgKrCgKrDwKrGAKrHwKrKQKrOAOrAwLOBgLOCgLODwLOGALOHwLOKQLOOAPO + AwLXBgLXCgLXDwLXGALXHwLXKQLXOAPXAwLhBgLhCgLhDwLhGALhHwLhKQLhOAPh + AgLsCQLsFwLsKAPsAgLtCQLtFwLtKAPtAQLHFgPHAQLPFgPPAQLqFgPqAQLrFgPr + AwLsBgLsCgLsDwLsGALsHwLsKQLsOAPsAwLtBgLtCgLtDwLtGALtHwLtKQLtOAPt + AgLHCQLHFwLHKAPHAgLPCQLPFwLPKAPPAgLqCQLqFwLqKAPqAgLrCQLrFwLrKAPr + AwLHBgLHCgLHDwLHGALHHwLHKQLHOAPHAwLPBgLPCgLPDwLPGALPHwLPKQLPOAPP + AwLqBgLqCgLqDwLqGALqHwLqKQLqOAPqAwLrBgLrCgLrDwLrGALrHwLrKQLrOAPr + wgAAwwAAxQAAxgAAyQAAygAAzAAAzQAA0gAA1QAA2QAA3AAA4QAA5wAA7wAA9gAA + AAPAAAPBAAPIAAPJAAPKAAPNAAPSAAPVAAPaAAPbAAPuAAPwAAPyAAPzAAP/zgAA + AQLAFgPAAQLBFgPBAQLIFgPIAQLJFgPJAQLKFgPKAQLNFgPNAQLSFgPSAQLVFgPV + AgLACQLAFwLAKAPAAgLBCQLBFwLBKAPBAgLICQLIFwLIKAPIAgLJCQLJFwLJKAPJ + AwLABgLACgLADwLAGALAHwLAKQLAOAPAAwLBBgLBCgLBDwLBGALBHwLBKQLBOAPB + AwLIBgLICgLIDwLIGALIHwLIKQLIOAPIAwLJBgLJCgLJDwLJGALJHwLJKQLJOAPJ + AgLKCQLKFwLKKAPKAgLNCQLNFwLNKAPNAgLSCQLSFwLSKAPSAgLVCQLVFwLVKAPV + AwLKBgLKCgLKDwLKGALKHwLKKQLKOAPKAwLNBgLNCgLNDwLNGALNHwLNKQLNOAPN + AwLSBgLSCgLSDwLSGALSHwLSKQLSOAPSAwLVBgLVCgLVDwLVGALVHwLVKQLVOAPV + AQLaFgPaAQLbFgPbAQLuFgPuAQLwFgPwAQLyFgPyAQLzFgPzAQL/FgP/AAPLAAPM + AgLaCQLaFwLaKAPaAgLbCQLbFwLbKAPbAgLuCQLuFwLuKAPuAgLwCQLwFwLwKAPw + AwLaBgLaCgLaDwLaGALaHwLaKQLaOAPaAwLbBgLbCgLbDwLbGALbHwLbKQLbOAPb + AwLuBgLuCgLuDwLuGALuHwLuKQLuOAPuAwLwBgLwCgLwDwLwGALwHwLwKQLwOAPw + AgLyCQLyFwLyKAPyAgLzCQLzFwLzKAPzAgL/CQL/FwL/KAP/AQLLFgPLAQLMFgPM + AwLyBgLyCgLyDwLyGALyHwLyKQLyOAPyAwLzBgLzCgLzDwLzGALzHwLzKQLzOAPz + AwL/BgL/CgL/DwL/GAL/HwL/KQL/OAP/AgLLCQLLFwLLKAPLAgLMCQLMFwLMKAPM + AwLLBgLLCgLLDwLLGALLHwLLKQLLOAPLAwLMBgLMCgLMDwLMGALMHwLMKQLMOAPM + 0wAA1AAA1gAA1wAA2gAA2wAA3QAA3gAA4gAA5AAA6AAA6wAA8AAA8wAA9wAA+gAA + AAPTAAPUAAPWAAPdAAPeAAPfAAPxAAP0AAP1AAP2AAP3AAP4AAP6AAP7AAP8AAP9 + AQLTFgPTAQLUFgPUAQLWFgPWAQLdFgPdAQLeFgPeAQLfFgPfAQLxFgPxAQL0FgP0 + AgLTCQLTFwLTKAPTAgLUCQLUFwLUKAPUAgLWCQLWFwLWKAPWAgLdCQLdFwLdKAPd + AwLTBgLTCgLTDwLTGALTHwLTKQLTOAPTAwLUBgLUCgLUDwLUGALUHwLUKQLUOAPU + AwLWBgLWCgLWDwLWGALWHwLWKQLWOAPWAwLdBgLdCgLdDwLdGALdHwLdKQLdOAPd + AgLeCQLeFwLeKAPeAgLfCQLfFwLfKAPfAgLxCQLxFwLxKAPxAgL0CQL0FwL0KAP0 + AwLeBgLeCgLeDwLeGALeHwLeKQLeOAPeAwLfBgLfCgLfDwLfGALfHwLfKQLfOAPf + AwLxBgLxCgLxDwLxGALxHwLxKQLxOAPxAwL0BgL0CgL0DwL0GAL0HwL0KQL0OAP0 + AQL1FgP1AQL2FgP2AQL3FgP3AQL4FgP4AQL6FgP6AQL7FgP7AQL8FgP8AQL9FgP9 + AgL1CQL1FwL1KAP1AgL2CQL2FwL2KAP2AgL3CQL3FwL3KAP3AgL4CQL4FwL4KAP4 + AwL1BgL1CgL1DwL1GAL1HwL1KQL1OAP1AwL2BgL2CgL2DwL2GAL2HwL2KQL2OAP2 + AwL3BgL3CgL3DwL3GAL3HwL3KQL3OAP3AwL4BgL4CgL4DwL4GAL4HwL4KQL4OAP4 + AgL6CQL6FwL6KAP6AgL7CQL7FwL7KAP7AgL8CQL8FwL8KAP8AgL9CQL9FwL9KAP9 + AwL6BgL6CgL6DwL6GAL6HwL6KQL6OAP6AwL7BgL7CgL7DwL7GAL7HwL7KQL7OAP7 + AwL8BgL8CgL8DwL8GAL8HwL8KQL8OAP8AwL9BgL9CgL9DwL9GAL9HwL9KQL9OAP9 + AAP+4wAA5QAA5gAA6QAA6gAA7AAA7QAA8QAA8gAA9AAA9QAA+AAA+QAA+wAA/AAA + AQL+FgP+AAMCAAMDAAMEAAMFAAMGAAMHAAMIAAMLAAMMAAMOAAMPAAMQAAMRAAMS + AgL+CQL+FwL+KAP+AQICFgMCAQIDFgMDAQIEFgMEAQIFFgMFAQIGFgMGAQIHFgMH + AwL+BgL+CgL+DwL+GAL+HwL+KQL+OAP+AgICCQICFwICKAMCAgIDCQIDFwIDKAMD + AwICBgICCgICDwICGAICHwICKQICOAMCAwIDBgIDCgIDDwIDGAIDHwIDKQIDOAMD + AgIECQIEFwIEKAMEAgIFCQIFFwIFKAMFAgIGCQIGFwIGKAMGAgIHCQIHFwIHKAMH + AwIEBgIECgIEDwIEGAIEHwIEKQIEOAMEAwIFBgIFCgIFDwIFGAIFHwIFKQIFOAMF + AwIGBgIGCgIGDwIGGAIGHwIGKQIGOAMGAwIHBgIHCgIHDwIHGAIHHwIHKQIHOAMH + AQIIFgMIAQILFgMLAQIMFgMMAQIOFgMOAQIPFgMPAQIQFgMQAQIRFgMRAQISFgMS + AgIICQIIFwIIKAMIAgILCQILFwILKAMLAgIMCQIMFwIMKAMMAgIOCQIOFwIOKAMO + AwIIBgIICgIIDwIIGAIIHwIIKQIIOAMIAwILBgILCgILDwILGAILHwILKQILOAML + AwIMBgIMCgIMDwIMGAIMHwIMKQIMOAMMAwIOBgIOCgIODwIOGAIOHwIOKQIOOAMO + AgIPCQIPFwIPKAMPAgIQCQIQFwIQKAMQAgIRCQIRFwIRKAMRAgISCQISFwISKAMS + AwIPBgIPCgIPDwIPGAIPHwIPKQIPOAMPAwIQBgIQCgIQDwIQGAIQHwIQKQIQOAMQ + AwIRBgIRCgIRDwIRGAIRHwIRKQIROAMRAwISBgISCgISDwISGAISHwISKQISOAMS + AAMTAAMUAAMVAAMXAAMYAAMZAAMaAAMbAAMcAAMdAAMeAAMfAAN/AAPcAAP5/QAA + AQITFgMTAQIUFgMUAQIVFgMVAQIXFgMXAQIYFgMYAQIZFgMZAQIaFgMaAQIbFgMb + AgITCQITFwITKAMTAgIUCQIUFwIUKAMUAgIVCQIVFwIVKAMVAgIXCQIXFwIXKAMX + AwITBgITCgITDwITGAITHwITKQITOAMTAwIUBgIUCgIUDwIUGAIUHwIUKQIUOAMU + AwIVBgIVCgIVDwIVGAIVHwIVKQIVOAMVAwIXBgIXCgIXDwIXGAIXHwIXKQIXOAMX + AgIYCQIYFwIYKAMYAgIZCQIZFwIZKAMZAgIaCQIaFwIaKAMaAgIbCQIbFwIbKAMb + AwIYBgIYCgIYDwIYGAIYHwIYKQIYOAMYAwIZBgIZCgIZDwIZGAIZHwIZKQIZOAMZ + AwIaBgIaCgIaDwIaGAIaHwIaKQIaOAMaAwIbBgIbCgIbDwIbGAIbHwIbKQIbOAMb + AQIcFgMcAQIdFgMdAQIeFgMeAQIfFgMfAQJ/FgN/AQLcFgPcAQL5FgP5/gAA/wAA + AgIcCQIcFwIcKAMcAgIdCQIdFwIdKAMdAgIeCQIeFwIeKAMeAgIfCQIfFwIfKAMf + AwIcBgIcCgIcDwIcGAIcHwIcKQIcOAMcAwIdBgIdCgIdDwIdGAIdHwIdKQIdOAMd + AwIeBgIeCgIeDwIeGAIeHwIeKQIeOAMeAwIfBgIfCgIfDwIfGAIfHwIfKQIfOAMf + AgJ/CQJ/FwJ/KAN/AgLcCQLcFwLcKAPcAgL5CQL5FwL5KAP5AAMKAAMNAAMWAAQA + AwJ/BgJ/CgJ/DwJ/GAJ/HwJ/KQJ/OAN/AwLcBgLcCgLcDwLcGALcHwLcKQLcOAPc + AwL5BgL5CgL5DwL5GAL5HwL5KQL5OAP5AQIKFgMKAQINFgMNAQIWFgMWAAQAAAQA + AgIKCQIKFwIKKAMKAgINCQINFwINKAMNAgIWCQIWFwIWKAMWAAQAAAQAAAQAAAQA + AwIKBgIKCgIKDwIKGAIKHwIKKQIKOAMKAwINBgINCgINDwINGAINHwINKQINOAMN + AwIWBgIWCgIWDwIWGAIWHwIWKQIWOAMWAAQAAAQAAAQAAAQAAAQAAAQAAAQAAAQA + """ return base64_table_bytes.withUTF8Buffer { buf in // ignore newlines in the input guard let result = base64DecodeBytes(buf, ignoreUnknownCharacters: true) else { @@ -539,4872 +528,4871 @@ internal struct HuffmanDecoderTable { }() // for posterity, here's what the table effectively looks like: - /* - private static let rawTable: [HuffmanDecodeEntry] = [ - - /* 0 */ - - (4, .none, 0), - (5, .none, 0), - (7, .none, 0), - (8, .none, 0), - (11, .none, 0), - (12, .none, 0), - (16, .none, 0), - (19, .none, 0), - (25, .none, 0), - (28, .none, 0), - (32, .none, 0), - (35, .none, 0), - (42, .none, 0), - (49, .none, 0), - (57, .none, 0), - (64, .accepted, 0), - - /* 1 */ - - (0, [.accepted, .symbol], 48), - (0, [.accepted, .symbol], 49), - (0, [.accepted, .symbol], 50), - (0, [.accepted, .symbol], 97), - (0, [.accepted, .symbol], 99), - (0, [.accepted, .symbol], 101), - (0, [.accepted, .symbol], 105), - (0, [.accepted, .symbol], 111), - (0, [.accepted, .symbol], 115), - (0, [.accepted, .symbol], 116), - (13, .none, 0), - (14, .none, 0), - (17, .none, 0), - (18, .none, 0), - (20, .none, 0), - (21, .none, 0), - - /* 2 */ - - (1, .symbol, 48), - (22, [.accepted, .symbol], 48), - (1, .symbol, 49), - (22, [.accepted, .symbol], 49), - (1, .symbol, 50), - (22, [.accepted, .symbol], 50), - (1, .symbol, 97), - (22, [.accepted, .symbol], 97), - (1, .symbol, 99), - (22, [.accepted, .symbol], 99), - (1, .symbol, 101), - (22, [.accepted, .symbol], 101), - (1, .symbol, 105), - (22, [.accepted, .symbol], 105), - (1, .symbol, 111), - (22, [.accepted, .symbol], 111), - - /* 3 */ - - (2, .symbol, 48), - (9, .symbol, 48), - (23, .symbol, 48), - (40, [.accepted, .symbol], 48), - (2, .symbol, 49), - (9, .symbol, 49), - (23, .symbol, 49), - (40, [.accepted, .symbol], 49), - (2, .symbol, 50), - (9, .symbol, 50), - (23, .symbol, 50), - (40, [.accepted, .symbol], 50), - (2, .symbol, 97), - (9, .symbol, 97), - (23, .symbol, 97), - (40, [.accepted, .symbol], 97), - - /* 4 */ - - (3, .symbol, 48), - (6, .symbol, 48), - (10, .symbol, 48), - (15, .symbol, 48), - (24, .symbol, 48), - (31, .symbol, 48), - (41, .symbol, 48), - (56, [.accepted, .symbol], 48), - (3, .symbol, 49), - (6, .symbol, 49), - (10, .symbol, 49), - (15, .symbol, 49), - (24, .symbol, 49), - (31, .symbol, 49), - (41, .symbol, 49), - (56, [.accepted, .symbol], 49), - - /* 5 */ - - (3, .symbol, 50), - (6, .symbol, 50), - (10, .symbol, 50), - (15, .symbol, 50), - (24, .symbol, 50), - (31, .symbol, 50), - (41, .symbol, 50), - (56, [.accepted, .symbol], 50), - (3, .symbol, 97), - (6, .symbol, 97), - (10, .symbol, 97), - (15, .symbol, 97), - (24, .symbol, 97), - (31, .symbol, 97), - (41, .symbol, 97), - (56, [.accepted, .symbol], 97), - - /* 6 */ - - (2, .symbol, 99), - (9, .symbol, 99), - (23, .symbol, 99), - (40, [.accepted, .symbol], 99), - (2, .symbol, 101), - (9, .symbol, 101), - (23, .symbol, 101), - (40, [.accepted, .symbol], 101), - (2, .symbol, 105), - (9, .symbol, 105), - (23, .symbol, 105), - (40, [.accepted, .symbol], 105), - (2, .symbol, 111), - (9, .symbol, 111), - (23, .symbol, 111), - (40, [.accepted, .symbol], 111), - - /* 7 */ - - (3, .symbol, 99), - (6, .symbol, 99), - (10, .symbol, 99), - (15, .symbol, 99), - (24, .symbol, 99), - (31, .symbol, 99), - (41, .symbol, 99), - (56, [.accepted, .symbol], 99), - (3, .symbol, 101), - (6, .symbol, 101), - (10, .symbol, 101), - (15, .symbol, 101), - (24, .symbol, 101), - (31, .symbol, 101), - (41, .symbol, 101), - (56, [.accepted, .symbol], 101), - - /* 8 */ - - (3, .symbol, 105), - (6, .symbol, 105), - (10, .symbol, 105), - (15, .symbol, 105), - (24, .symbol, 105), - (31, .symbol, 105), - (41, .symbol, 105), - (56, [.accepted, .symbol], 105), - (3, .symbol, 111), - (6, .symbol, 111), - (10, .symbol, 111), - (15, .symbol, 111), - (24, .symbol, 111), - (31, .symbol, 111), - (41, .symbol, 111), - (56, [.accepted, .symbol], 111), - - /* 9 */ - - (1, .symbol, 115), - (22, [.accepted, .symbol], 115), - (1, .symbol, 116), - (22, [.accepted, .symbol], 116), - (0, [.accepted, .symbol], 32), - (0, [.accepted, .symbol], 37), - (0, [.accepted, .symbol], 45), - (0, [.accepted, .symbol], 46), - (0, [.accepted, .symbol], 47), - (0, [.accepted, .symbol], 51), - (0, [.accepted, .symbol], 52), - (0, [.accepted, .symbol], 53), - (0, [.accepted, .symbol], 54), - (0, [.accepted, .symbol], 55), - (0, [.accepted, .symbol], 56), - (0, [.accepted, .symbol], 57), - - /* 10 */ - - (2, .symbol, 115), - (9, .symbol, 115), - (23, .symbol, 115), - (40, [.accepted, .symbol], 115), - (2, .symbol, 116), - (9, .symbol, 116), - (23, .symbol, 116), - (40, [.accepted, .symbol], 116), - (1, .symbol, 32), - (22, [.accepted, .symbol], 32), - (1, .symbol, 37), - (22, [.accepted, .symbol], 37), - (1, .symbol, 45), - (22, [.accepted, .symbol], 45), - (1, .symbol, 46), - (22, [.accepted, .symbol], 46), - - /* 11 */ - - (3, .symbol, 115), - (6, .symbol, 115), - (10, .symbol, 115), - (15, .symbol, 115), - (24, .symbol, 115), - (31, .symbol, 115), - (41, .symbol, 115), - (56, [.accepted, .symbol], 115), - (3, .symbol, 116), - (6, .symbol, 116), - (10, .symbol, 116), - (15, .symbol, 116), - (24, .symbol, 116), - (31, .symbol, 116), - (41, .symbol, 116), - (56, [.accepted, .symbol], 116), - - /* 12 */ - - (2, .symbol, 32), - (9, .symbol, 32), - (23, .symbol, 32), - (40, [.accepted, .symbol], 32), - (2, .symbol, 37), - (9, .symbol, 37), - (23, .symbol, 37), - (40, [.accepted, .symbol], 37), - (2, .symbol, 45), - (9, .symbol, 45), - (23, .symbol, 45), - (40, [.accepted, .symbol], 45), - (2, .symbol, 46), - (9, .symbol, 46), - (23, .symbol, 46), - (40, [.accepted, .symbol], 46), - - /* 13 */ - - (3, .symbol, 32), - (6, .symbol, 32), - (10, .symbol, 32), - (15, .symbol, 32), - (24, .symbol, 32), - (31, .symbol, 32), - (41, .symbol, 32), - (56, [.accepted, .symbol], 32), - (3, .symbol, 37), - (6, .symbol, 37), - (10, .symbol, 37), - (15, .symbol, 37), - (24, .symbol, 37), - (31, .symbol, 37), - (41, .symbol, 37), - (56, [.accepted, .symbol], 37), - - /* 14 */ - - (3, .symbol, 45), - (6, .symbol, 45), - (10, .symbol, 45), - (15, .symbol, 45), - (24, .symbol, 45), - (31, .symbol, 45), - (41, .symbol, 45), - (56, [.accepted, .symbol], 45), - (3, .symbol, 46), - (6, .symbol, 46), - (10, .symbol, 46), - (15, .symbol, 46), - (24, .symbol, 46), - (31, .symbol, 46), - (41, .symbol, 46), - (56, [.accepted, .symbol], 46), - - /* 15 */ - - (1, .symbol, 47), - (22, [.accepted, .symbol], 47), - (1, .symbol, 51), - (22, [.accepted, .symbol], 51), - (1, .symbol, 52), - (22, [.accepted, .symbol], 52), - (1, .symbol, 53), - (22, [.accepted, .symbol], 53), - (1, .symbol, 54), - (22, [.accepted, .symbol], 54), - (1, .symbol, 55), - (22, [.accepted, .symbol], 55), - (1, .symbol, 56), - (22, [.accepted, .symbol], 56), - (1, .symbol, 57), - (22, [.accepted, .symbol], 57), - - /* 16 */ - - (2, .symbol, 47), - (9, .symbol, 47), - (23, .symbol, 47), - (40, [.accepted, .symbol], 47), - (2, .symbol, 51), - (9, .symbol, 51), - (23, .symbol, 51), - (40, [.accepted, .symbol], 51), - (2, .symbol, 52), - (9, .symbol, 52), - (23, .symbol, 52), - (40, [.accepted, .symbol], 52), - (2, .symbol, 53), - (9, .symbol, 53), - (23, .symbol, 53), - (40, [.accepted, .symbol], 53), - - /* 17 */ - - (3, .symbol, 47), - (6, .symbol, 47), - (10, .symbol, 47), - (15, .symbol, 47), - (24, .symbol, 47), - (31, .symbol, 47), - (41, .symbol, 47), - (56, [.accepted, .symbol], 47), - (3, .symbol, 51), - (6, .symbol, 51), - (10, .symbol, 51), - (15, .symbol, 51), - (24, .symbol, 51), - (31, .symbol, 51), - (41, .symbol, 51), - (56, [.accepted, .symbol], 51), - - /* 18 */ - - (3, .symbol, 52), - (6, .symbol, 52), - (10, .symbol, 52), - (15, .symbol, 52), - (24, .symbol, 52), - (31, .symbol, 52), - (41, .symbol, 52), - (56, [.accepted, .symbol], 52), - (3, .symbol, 53), - (6, .symbol, 53), - (10, .symbol, 53), - (15, .symbol, 53), - (24, .symbol, 53), - (31, .symbol, 53), - (41, .symbol, 53), - (56, [.accepted, .symbol], 53), - - /* 19 */ - - (2, .symbol, 54), - (9, .symbol, 54), - (23, .symbol, 54), - (40, [.accepted, .symbol], 54), - (2, .symbol, 55), - (9, .symbol, 55), - (23, .symbol, 55), - (40, [.accepted, .symbol], 55), - (2, .symbol, 56), - (9, .symbol, 56), - (23, .symbol, 56), - (40, [.accepted, .symbol], 56), - (2, .symbol, 57), - (9, .symbol, 57), - (23, .symbol, 57), - (40, [.accepted, .symbol], 57), - - /* 20 */ - - (3, .symbol, 54), - (6, .symbol, 54), - (10, .symbol, 54), - (15, .symbol, 54), - (24, .symbol, 54), - (31, .symbol, 54), - (41, .symbol, 54), - (56, [.accepted, .symbol], 54), - (3, .symbol, 55), - (6, .symbol, 55), - (10, .symbol, 55), - (15, .symbol, 55), - (24, .symbol, 55), - (31, .symbol, 55), - (41, .symbol, 55), - (56, [.accepted, .symbol], 55), - - /* 21 */ - - (3, .symbol, 56), - (6, .symbol, 56), - (10, .symbol, 56), - (15, .symbol, 56), - (24, .symbol, 56), - (31, .symbol, 56), - (41, .symbol, 56), - (56, [.accepted, .symbol], 56), - (3, .symbol, 57), - (6, .symbol, 57), - (10, .symbol, 57), - (15, .symbol, 57), - (24, .symbol, 57), - (31, .symbol, 57), - (41, .symbol, 57), - (56, [.accepted, .symbol], 57), - - /* 22 */ - - (26, .none, 0), - (27, .none, 0), - (29, .none, 0), - (30, .none, 0), - (33, .none, 0), - (34, .none, 0), - (36, .none, 0), - (37, .none, 0), - (43, .none, 0), - (46, .none, 0), - (50, .none, 0), - (53, .none, 0), - (58, .none, 0), - (61, .none, 0), - (65, .none, 0), - (68, .accepted, 0), - - /* 23 */ - - (0, [.accepted, .symbol], 61), - (0, [.accepted, .symbol], 65), - (0, [.accepted, .symbol], 95), - (0, [.accepted, .symbol], 98), - (0, [.accepted, .symbol], 100), - (0, [.accepted, .symbol], 102), - (0, [.accepted, .symbol], 103), - (0, [.accepted, .symbol], 104), - (0, [.accepted, .symbol], 108), - (0, [.accepted, .symbol], 109), - (0, [.accepted, .symbol], 110), - (0, [.accepted, .symbol], 112), - (0, [.accepted, .symbol], 114), - (0, [.accepted, .symbol], 117), - (38, .none, 0), - (39, .none, 0), - - /* 24 */ - - (1, .symbol, 61), - (22, [.accepted, .symbol], 61), - (1, .symbol, 65), - (22, [.accepted, .symbol], 65), - (1, .symbol, 95), - (22, [.accepted, .symbol], 95), - (1, .symbol, 98), - (22, [.accepted, .symbol], 98), - (1, .symbol, 100), - (22, [.accepted, .symbol], 100), - (1, .symbol, 102), - (22, [.accepted, .symbol], 102), - (1, .symbol, 103), - (22, [.accepted, .symbol], 103), - (1, .symbol, 104), - (22, [.accepted, .symbol], 104), - - /* 25 */ - - (2, .symbol, 61), - (9, .symbol, 61), - (23, .symbol, 61), - (40, [.accepted, .symbol], 61), - (2, .symbol, 65), - (9, .symbol, 65), - (23, .symbol, 65), - (40, [.accepted, .symbol], 65), - (2, .symbol, 95), - (9, .symbol, 95), - (23, .symbol, 95), - (40, [.accepted, .symbol], 95), - (2, .symbol, 98), - (9, .symbol, 98), - (23, .symbol, 98), - (40, [.accepted, .symbol], 98), - - /* 26 */ - - (3, .symbol, 61), - (6, .symbol, 61), - (10, .symbol, 61), - (15, .symbol, 61), - (24, .symbol, 61), - (31, .symbol, 61), - (41, .symbol, 61), - (56, [.accepted, .symbol], 61), - (3, .symbol, 65), - (6, .symbol, 65), - (10, .symbol, 65), - (15, .symbol, 65), - (24, .symbol, 65), - (31, .symbol, 65), - (41, .symbol, 65), - (56, [.accepted, .symbol], 65), - - /* 27 */ - - (3, .symbol, 95), - (6, .symbol, 95), - (10, .symbol, 95), - (15, .symbol, 95), - (24, .symbol, 95), - (31, .symbol, 95), - (41, .symbol, 95), - (56, [.accepted, .symbol], 95), - (3, .symbol, 98), - (6, .symbol, 98), - (10, .symbol, 98), - (15, .symbol, 98), - (24, .symbol, 98), - (31, .symbol, 98), - (41, .symbol, 98), - (56, [.accepted, .symbol], 98), - - /* 28 */ - - (2, .symbol, 100), - (9, .symbol, 100), - (23, .symbol, 100), - (40, [.accepted, .symbol], 100), - (2, .symbol, 102), - (9, .symbol, 102), - (23, .symbol, 102), - (40, [.accepted, .symbol], 102), - (2, .symbol, 103), - (9, .symbol, 103), - (23, .symbol, 103), - (40, [.accepted, .symbol], 103), - (2, .symbol, 104), - (9, .symbol, 104), - (23, .symbol, 104), - (40, [.accepted, .symbol], 104), - - /* 29 */ - - (3, .symbol, 100), - (6, .symbol, 100), - (10, .symbol, 100), - (15, .symbol, 100), - (24, .symbol, 100), - (31, .symbol, 100), - (41, .symbol, 100), - (56, [.accepted, .symbol], 100), - (3, .symbol, 102), - (6, .symbol, 102), - (10, .symbol, 102), - (15, .symbol, 102), - (24, .symbol, 102), - (31, .symbol, 102), - (41, .symbol, 102), - (56, [.accepted, .symbol], 102), - - /* 30 */ - - (3, .symbol, 103), - (6, .symbol, 103), - (10, .symbol, 103), - (15, .symbol, 103), - (24, .symbol, 103), - (31, .symbol, 103), - (41, .symbol, 103), - (56, [.accepted, .symbol], 103), - (3, .symbol, 104), - (6, .symbol, 104), - (10, .symbol, 104), - (15, .symbol, 104), - (24, .symbol, 104), - (31, .symbol, 104), - (41, .symbol, 104), - (56, [.accepted, .symbol], 104), - - /* 31 */ - - (1, .symbol, 108), - (22, [.accepted, .symbol], 108), - (1, .symbol, 109), - (22, [.accepted, .symbol], 109), - (1, .symbol, 110), - (22, [.accepted, .symbol], 110), - (1, .symbol, 112), - (22, [.accepted, .symbol], 112), - (1, .symbol, 114), - (22, [.accepted, .symbol], 114), - (1, .symbol, 117), - (22, [.accepted, .symbol], 117), - (0, [.accepted, .symbol], 58), - (0, [.accepted, .symbol], 66), - (0, [.accepted, .symbol], 67), - (0, [.accepted, .symbol], 68), - - /* 32 */ - - (2, .symbol, 108), - (9, .symbol, 108), - (23, .symbol, 108), - (40, [.accepted, .symbol], 108), - (2, .symbol, 109), - (9, .symbol, 109), - (23, .symbol, 109), - (40, [.accepted, .symbol], 109), - (2, .symbol, 110), - (9, .symbol, 110), - (23, .symbol, 110), - (40, [.accepted, .symbol], 110), - (2, .symbol, 112), - (9, .symbol, 112), - (23, .symbol, 112), - (40, [.accepted, .symbol], 112), - - /* 33 */ - - (3, .symbol, 108), - (6, .symbol, 108), - (10, .symbol, 108), - (15, .symbol, 108), - (24, .symbol, 108), - (31, .symbol, 108), - (41, .symbol, 108), - (56, [.accepted, .symbol], 108), - (3, .symbol, 109), - (6, .symbol, 109), - (10, .symbol, 109), - (15, .symbol, 109), - (24, .symbol, 109), - (31, .symbol, 109), - (41, .symbol, 109), - (56, [.accepted, .symbol], 109), - - /* 34 */ - - (3, .symbol, 110), - (6, .symbol, 110), - (10, .symbol, 110), - (15, .symbol, 110), - (24, .symbol, 110), - (31, .symbol, 110), - (41, .symbol, 110), - (56, [.accepted, .symbol], 110), - (3, .symbol, 112), - (6, .symbol, 112), - (10, .symbol, 112), - (15, .symbol, 112), - (24, .symbol, 112), - (31, .symbol, 112), - (41, .symbol, 112), - (56, [.accepted, .symbol], 112), - - /* 35 */ - - (2, .symbol, 114), - (9, .symbol, 114), - (23, .symbol, 114), - (40, [.accepted, .symbol], 114), - (2, .symbol, 117), - (9, .symbol, 117), - (23, .symbol, 117), - (40, [.accepted, .symbol], 117), - (1, .symbol, 58), - (22, [.accepted, .symbol], 58), - (1, .symbol, 66), - (22, [.accepted, .symbol], 66), - (1, .symbol, 67), - (22, [.accepted, .symbol], 67), - (1, .symbol, 68), - (22, [.accepted, .symbol], 68), - - /* 36 */ - - (3, .symbol, 114), - (6, .symbol, 114), - (10, .symbol, 114), - (15, .symbol, 114), - (24, .symbol, 114), - (31, .symbol, 114), - (41, .symbol, 114), - (56, [.accepted, .symbol], 114), - (3, .symbol, 117), - (6, .symbol, 117), - (10, .symbol, 117), - (15, .symbol, 117), - (24, .symbol, 117), - (31, .symbol, 117), - (41, .symbol, 117), - (56, [.accepted, .symbol], 117), - - /* 37 */ - - (2, .symbol, 58), - (9, .symbol, 58), - (23, .symbol, 58), - (40, [.accepted, .symbol], 58), - (2, .symbol, 66), - (9, .symbol, 66), - (23, .symbol, 66), - (40, [.accepted, .symbol], 66), - (2, .symbol, 67), - (9, .symbol, 67), - (23, .symbol, 67), - (40, [.accepted, .symbol], 67), - (2, .symbol, 68), - (9, .symbol, 68), - (23, .symbol, 68), - (40, [.accepted, .symbol], 68), - - /* 38 */ - - (3, .symbol, 58), - (6, .symbol, 58), - (10, .symbol, 58), - (15, .symbol, 58), - (24, .symbol, 58), - (31, .symbol, 58), - (41, .symbol, 58), - (56, [.accepted, .symbol], 58), - (3, .symbol, 66), - (6, .symbol, 66), - (10, .symbol, 66), - (15, .symbol, 66), - (24, .symbol, 66), - (31, .symbol, 66), - (41, .symbol, 66), - (56, [.accepted, .symbol], 66), - - /* 39 */ - - (3, .symbol, 67), - (6, .symbol, 67), - (10, .symbol, 67), - (15, .symbol, 67), - (24, .symbol, 67), - (31, .symbol, 67), - (41, .symbol, 67), - (56, [.accepted, .symbol], 67), - (3, .symbol, 68), - (6, .symbol, 68), - (10, .symbol, 68), - (15, .symbol, 68), - (24, .symbol, 68), - (31, .symbol, 68), - (41, .symbol, 68), - (56, [.accepted, .symbol], 68), - - /* 40 */ - - (44, .none, 0), - (45, .none, 0), - (47, .none, 0), - (48, .none, 0), - (51, .none, 0), - (52, .none, 0), - (54, .none, 0), - (55, .none, 0), - (59, .none, 0), - (60, .none, 0), - (62, .none, 0), - (63, .none, 0), - (66, .none, 0), - (67, .none, 0), - (69, .none, 0), - (72, .accepted, 0), - - /* 41 */ - - (0, [.accepted, .symbol], 69), - (0, [.accepted, .symbol], 70), - (0, [.accepted, .symbol], 71), - (0, [.accepted, .symbol], 72), - (0, [.accepted, .symbol], 73), - (0, [.accepted, .symbol], 74), - (0, [.accepted, .symbol], 75), - (0, [.accepted, .symbol], 76), - (0, [.accepted, .symbol], 77), - (0, [.accepted, .symbol], 78), - (0, [.accepted, .symbol], 79), - (0, [.accepted, .symbol], 80), - (0, [.accepted, .symbol], 81), - (0, [.accepted, .symbol], 82), - (0, [.accepted, .symbol], 83), - (0, [.accepted, .symbol], 84), - - /* 42 */ - - (1, .symbol, 69), - (22, [.accepted, .symbol], 69), - (1, .symbol, 70), - (22, [.accepted, .symbol], 70), - (1, .symbol, 71), - (22, [.accepted, .symbol], 71), - (1, .symbol, 72), - (22, [.accepted, .symbol], 72), - (1, .symbol, 73), - (22, [.accepted, .symbol], 73), - (1, .symbol, 74), - (22, [.accepted, .symbol], 74), - (1, .symbol, 75), - (22, [.accepted, .symbol], 75), - (1, .symbol, 76), - (22, [.accepted, .symbol], 76), - - /* 43 */ - - (2, .symbol, 69), - (9, .symbol, 69), - (23, .symbol, 69), - (40, [.accepted, .symbol], 69), - (2, .symbol, 70), - (9, .symbol, 70), - (23, .symbol, 70), - (40, [.accepted, .symbol], 70), - (2, .symbol, 71), - (9, .symbol, 71), - (23, .symbol, 71), - (40, [.accepted, .symbol], 71), - (2, .symbol, 72), - (9, .symbol, 72), - (23, .symbol, 72), - (40, [.accepted, .symbol], 72), - - /* 44 */ - - (3, .symbol, 69), - (6, .symbol, 69), - (10, .symbol, 69), - (15, .symbol, 69), - (24, .symbol, 69), - (31, .symbol, 69), - (41, .symbol, 69), - (56, [.accepted, .symbol], 69), - (3, .symbol, 70), - (6, .symbol, 70), - (10, .symbol, 70), - (15, .symbol, 70), - (24, .symbol, 70), - (31, .symbol, 70), - (41, .symbol, 70), - (56, [.accepted, .symbol], 70), - - /* 45 */ - - (3, .symbol, 71), - (6, .symbol, 71), - (10, .symbol, 71), - (15, .symbol, 71), - (24, .symbol, 71), - (31, .symbol, 71), - (41, .symbol, 71), - (56, [.accepted, .symbol], 71), - (3, .symbol, 72), - (6, .symbol, 72), - (10, .symbol, 72), - (15, .symbol, 72), - (24, .symbol, 72), - (31, .symbol, 72), - (41, .symbol, 72), - (56, [.accepted, .symbol], 72), - - /* 46 */ - - (2, .symbol, 73), - (9, .symbol, 73), - (23, .symbol, 73), - (40, [.accepted, .symbol], 73), - (2, .symbol, 74), - (9, .symbol, 74), - (23, .symbol, 74), - (40, [.accepted, .symbol], 74), - (2, .symbol, 75), - (9, .symbol, 75), - (23, .symbol, 75), - (40, [.accepted, .symbol], 75), - (2, .symbol, 76), - (9, .symbol, 76), - (23, .symbol, 76), - (40, [.accepted, .symbol], 76), - - /* 47 */ - - (3, .symbol, 73), - (6, .symbol, 73), - (10, .symbol, 73), - (15, .symbol, 73), - (24, .symbol, 73), - (31, .symbol, 73), - (41, .symbol, 73), - (56, [.accepted, .symbol], 73), - (3, .symbol, 74), - (6, .symbol, 74), - (10, .symbol, 74), - (15, .symbol, 74), - (24, .symbol, 74), - (31, .symbol, 74), - (41, .symbol, 74), - (56, [.accepted, .symbol], 74), - - /* 48 */ - - (3, .symbol, 75), - (6, .symbol, 75), - (10, .symbol, 75), - (15, .symbol, 75), - (24, .symbol, 75), - (31, .symbol, 75), - (41, .symbol, 75), - (56, [.accepted, .symbol], 75), - (3, .symbol, 76), - (6, .symbol, 76), - (10, .symbol, 76), - (15, .symbol, 76), - (24, .symbol, 76), - (31, .symbol, 76), - (41, .symbol, 76), - (56, [.accepted, .symbol], 76), - - /* 49 */ - - (1, .symbol, 77), - (22, [.accepted, .symbol], 77), - (1, .symbol, 78), - (22, [.accepted, .symbol], 78), - (1, .symbol, 79), - (22, [.accepted, .symbol], 79), - (1, .symbol, 80), - (22, [.accepted, .symbol], 80), - (1, .symbol, 81), - (22, [.accepted, .symbol], 81), - (1, .symbol, 82), - (22, [.accepted, .symbol], 82), - (1, .symbol, 83), - (22, [.accepted, .symbol], 83), - (1, .symbol, 84), - (22, [.accepted, .symbol], 84), - - /* 50 */ - - (2, .symbol, 77), - (9, .symbol, 77), - (23, .symbol, 77), - (40, [.accepted, .symbol], 77), - (2, .symbol, 78), - (9, .symbol, 78), - (23, .symbol, 78), - (40, [.accepted, .symbol], 78), - (2, .symbol, 79), - (9, .symbol, 79), - (23, .symbol, 79), - (40, [.accepted, .symbol], 79), - (2, .symbol, 80), - (9, .symbol, 80), - (23, .symbol, 80), - (40, [.accepted, .symbol], 80), - - /* 51 */ - - (3, .symbol, 77), - (6, .symbol, 77), - (10, .symbol, 77), - (15, .symbol, 77), - (24, .symbol, 77), - (31, .symbol, 77), - (41, .symbol, 77), - (56, [.accepted, .symbol], 77), - (3, .symbol, 78), - (6, .symbol, 78), - (10, .symbol, 78), - (15, .symbol, 78), - (24, .symbol, 78), - (31, .symbol, 78), - (41, .symbol, 78), - (56, [.accepted, .symbol], 78), - - /* 52 */ - - (3, .symbol, 79), - (6, .symbol, 79), - (10, .symbol, 79), - (15, .symbol, 79), - (24, .symbol, 79), - (31, .symbol, 79), - (41, .symbol, 79), - (56, [.accepted, .symbol], 79), - (3, .symbol, 80), - (6, .symbol, 80), - (10, .symbol, 80), - (15, .symbol, 80), - (24, .symbol, 80), - (31, .symbol, 80), - (41, .symbol, 80), - (56, [.accepted, .symbol], 80), - - /* 53 */ - - (2, .symbol, 81), - (9, .symbol, 81), - (23, .symbol, 81), - (40, [.accepted, .symbol], 81), - (2, .symbol, 82), - (9, .symbol, 82), - (23, .symbol, 82), - (40, [.accepted, .symbol], 82), - (2, .symbol, 83), - (9, .symbol, 83), - (23, .symbol, 83), - (40, [.accepted, .symbol], 83), - (2, .symbol, 84), - (9, .symbol, 84), - (23, .symbol, 84), - (40, [.accepted, .symbol], 84), - - /* 54 */ - - (3, .symbol, 81), - (6, .symbol, 81), - (10, .symbol, 81), - (15, .symbol, 81), - (24, .symbol, 81), - (31, .symbol, 81), - (41, .symbol, 81), - (56, [.accepted, .symbol], 81), - (3, .symbol, 82), - (6, .symbol, 82), - (10, .symbol, 82), - (15, .symbol, 82), - (24, .symbol, 82), - (31, .symbol, 82), - (41, .symbol, 82), - (56, [.accepted, .symbol], 82), - - /* 55 */ - - (3, .symbol, 83), - (6, .symbol, 83), - (10, .symbol, 83), - (15, .symbol, 83), - (24, .symbol, 83), - (31, .symbol, 83), - (41, .symbol, 83), - (56, [.accepted, .symbol], 83), - (3, .symbol, 84), - (6, .symbol, 84), - (10, .symbol, 84), - (15, .symbol, 84), - (24, .symbol, 84), - (31, .symbol, 84), - (41, .symbol, 84), - (56, [.accepted, .symbol], 84), - - /* 56 */ - - (0, [.accepted, .symbol], 85), - (0, [.accepted, .symbol], 86), - (0, [.accepted, .symbol], 87), - (0, [.accepted, .symbol], 89), - (0, [.accepted, .symbol], 106), - (0, [.accepted, .symbol], 107), - (0, [.accepted, .symbol], 113), - (0, [.accepted, .symbol], 118), - (0, [.accepted, .symbol], 119), - (0, [.accepted, .symbol], 120), - (0, [.accepted, .symbol], 121), - (0, [.accepted, .symbol], 122), - (70, .none, 0), - (71, .none, 0), - (73, .none, 0), - (74, .accepted, 0), - - /* 57 */ - - (1, .symbol, 85), - (22, [.accepted, .symbol], 85), - (1, .symbol, 86), - (22, [.accepted, .symbol], 86), - (1, .symbol, 87), - (22, [.accepted, .symbol], 87), - (1, .symbol, 89), - (22, [.accepted, .symbol], 89), - (1, .symbol, 106), - (22, [.accepted, .symbol], 106), - (1, .symbol, 107), - (22, [.accepted, .symbol], 107), - (1, .symbol, 113), - (22, [.accepted, .symbol], 113), - (1, .symbol, 118), - (22, [.accepted, .symbol], 118), - - /* 58 */ - - (2, .symbol, 85), - (9, .symbol, 85), - (23, .symbol, 85), - (40, [.accepted, .symbol], 85), - (2, .symbol, 86), - (9, .symbol, 86), - (23, .symbol, 86), - (40, [.accepted, .symbol], 86), - (2, .symbol, 87), - (9, .symbol, 87), - (23, .symbol, 87), - (40, [.accepted, .symbol], 87), - (2, .symbol, 89), - (9, .symbol, 89), - (23, .symbol, 89), - (40, [.accepted, .symbol], 89), - - /* 59 */ - - (3, .symbol, 85), - (6, .symbol, 85), - (10, .symbol, 85), - (15, .symbol, 85), - (24, .symbol, 85), - (31, .symbol, 85), - (41, .symbol, 85), - (56, [.accepted, .symbol], 85), - (3, .symbol, 86), - (6, .symbol, 86), - (10, .symbol, 86), - (15, .symbol, 86), - (24, .symbol, 86), - (31, .symbol, 86), - (41, .symbol, 86), - (56, [.accepted, .symbol], 86), - - /* 60 */ - - (3, .symbol, 87), - (6, .symbol, 87), - (10, .symbol, 87), - (15, .symbol, 87), - (24, .symbol, 87), - (31, .symbol, 87), - (41, .symbol, 87), - (56, [.accepted, .symbol], 87), - (3, .symbol, 89), - (6, .symbol, 89), - (10, .symbol, 89), - (15, .symbol, 89), - (24, .symbol, 89), - (31, .symbol, 89), - (41, .symbol, 89), - (56, [.accepted, .symbol], 89), - - /* 61 */ - - (2, .symbol, 106), - (9, .symbol, 106), - (23, .symbol, 106), - (40, [.accepted, .symbol], 106), - (2, .symbol, 107), - (9, .symbol, 107), - (23, .symbol, 107), - (40, [.accepted, .symbol], 107), - (2, .symbol, 113), - (9, .symbol, 113), - (23, .symbol, 113), - (40, [.accepted, .symbol], 113), - (2, .symbol, 118), - (9, .symbol, 118), - (23, .symbol, 118), - (40, [.accepted, .symbol], 118), - - /* 62 */ - - (3, .symbol, 106), - (6, .symbol, 106), - (10, .symbol, 106), - (15, .symbol, 106), - (24, .symbol, 106), - (31, .symbol, 106), - (41, .symbol, 106), - (56, [.accepted, .symbol], 106), - (3, .symbol, 107), - (6, .symbol, 107), - (10, .symbol, 107), - (15, .symbol, 107), - (24, .symbol, 107), - (31, .symbol, 107), - (41, .symbol, 107), - (56, [.accepted, .symbol], 107), - - /* 63 */ - - (3, .symbol, 113), - (6, .symbol, 113), - (10, .symbol, 113), - (15, .symbol, 113), - (24, .symbol, 113), - (31, .symbol, 113), - (41, .symbol, 113), - (56, [.accepted, .symbol], 113), - (3, .symbol, 118), - (6, .symbol, 118), - (10, .symbol, 118), - (15, .symbol, 118), - (24, .symbol, 118), - (31, .symbol, 118), - (41, .symbol, 118), - (56, [.accepted, .symbol], 118), - - /* 64 */ - - (1, .symbol, 119), - (22, [.accepted, .symbol], 119), - (1, .symbol, 120), - (22, [.accepted, .symbol], 120), - (1, .symbol, 121), - (22, [.accepted, .symbol], 121), - (1, .symbol, 122), - (22, [.accepted, .symbol], 122), - (0, [.accepted, .symbol], 38), - (0, [.accepted, .symbol], 42), - (0, [.accepted, .symbol], 44), - (0, [.accepted, .symbol], 59), - (0, [.accepted, .symbol], 88), - (0, [.accepted, .symbol], 90), - (75, .none, 0), - (78, .none, 0), - - /* 65 */ - - (2, .symbol, 119), - (9, .symbol, 119), - (23, .symbol, 119), - (40, [.accepted, .symbol], 119), - (2, .symbol, 120), - (9, .symbol, 120), - (23, .symbol, 120), - (40, [.accepted, .symbol], 120), - (2, .symbol, 121), - (9, .symbol, 121), - (23, .symbol, 121), - (40, [.accepted, .symbol], 121), - (2, .symbol, 122), - (9, .symbol, 122), - (23, .symbol, 122), - (40, [.accepted, .symbol], 122), - - /* 66 */ - - (3, .symbol, 119), - (6, .symbol, 119), - (10, .symbol, 119), - (15, .symbol, 119), - (24, .symbol, 119), - (31, .symbol, 119), - (41, .symbol, 119), - (56, [.accepted, .symbol], 119), - (3, .symbol, 120), - (6, .symbol, 120), - (10, .symbol, 120), - (15, .symbol, 120), - (24, .symbol, 120), - (31, .symbol, 120), - (41, .symbol, 120), - (56, [.accepted, .symbol], 120), - - /* 67 */ - - (3, .symbol, 121), - (6, .symbol, 121), - (10, .symbol, 121), - (15, .symbol, 121), - (24, .symbol, 121), - (31, .symbol, 121), - (41, .symbol, 121), - (56, [.accepted, .symbol], 121), - (3, .symbol, 122), - (6, .symbol, 122), - (10, .symbol, 122), - (15, .symbol, 122), - (24, .symbol, 122), - (31, .symbol, 122), - (41, .symbol, 122), - (56, [.accepted, .symbol], 122), - - /* 68 */ - - (1, .symbol, 38), - (22, [.accepted, .symbol], 38), - (1, .symbol, 42), - (22, [.accepted, .symbol], 42), - (1, .symbol, 44), - (22, [.accepted, .symbol], 44), - (1, .symbol, 59), - (22, [.accepted, .symbol], 59), - (1, .symbol, 88), - (22, [.accepted, .symbol], 88), - (1, .symbol, 90), - (22, [.accepted, .symbol], 90), - (76, .none, 0), - (77, .none, 0), - (79, .none, 0), - (81, .none, 0), - - /* 69 */ - - (2, .symbol, 38), - (9, .symbol, 38), - (23, .symbol, 38), - (40, [.accepted, .symbol], 38), - (2, .symbol, 42), - (9, .symbol, 42), - (23, .symbol, 42), - (40, [.accepted, .symbol], 42), - (2, .symbol, 44), - (9, .symbol, 44), - (23, .symbol, 44), - (40, [.accepted, .symbol], 44), - (2, .symbol, 59), - (9, .symbol, 59), - (23, .symbol, 59), - (40, [.accepted, .symbol], 59), - - /* 70 */ - - (3, .symbol, 38), - (6, .symbol, 38), - (10, .symbol, 38), - (15, .symbol, 38), - (24, .symbol, 38), - (31, .symbol, 38), - (41, .symbol, 38), - (56, [.accepted, .symbol], 38), - (3, .symbol, 42), - (6, .symbol, 42), - (10, .symbol, 42), - (15, .symbol, 42), - (24, .symbol, 42), - (31, .symbol, 42), - (41, .symbol, 42), - (56, [.accepted, .symbol], 42), - - /* 71 */ - - (3, .symbol, 44), - (6, .symbol, 44), - (10, .symbol, 44), - (15, .symbol, 44), - (24, .symbol, 44), - (31, .symbol, 44), - (41, .symbol, 44), - (56, [.accepted, .symbol], 44), - (3, .symbol, 59), - (6, .symbol, 59), - (10, .symbol, 59), - (15, .symbol, 59), - (24, .symbol, 59), - (31, .symbol, 59), - (41, .symbol, 59), - (56, [.accepted, .symbol], 59), - - /* 72 */ - - (2, .symbol, 88), - (9, .symbol, 88), - (23, .symbol, 88), - (40, [.accepted, .symbol], 88), - (2, .symbol, 90), - (9, .symbol, 90), - (23, .symbol, 90), - (40, [.accepted, .symbol], 90), - (0, [.accepted, .symbol], 33), - (0, [.accepted, .symbol], 34), - (0, [.accepted, .symbol], 40), - (0, [.accepted, .symbol], 41), - (0, [.accepted, .symbol], 63), - (80, .none, 0), - (82, .none, 0), - (84, .none, 0), - - /* 73 */ - - (3, .symbol, 88), - (6, .symbol, 88), - (10, .symbol, 88), - (15, .symbol, 88), - (24, .symbol, 88), - (31, .symbol, 88), - (41, .symbol, 88), - (56, [.accepted, .symbol], 88), - (3, .symbol, 90), - (6, .symbol, 90), - (10, .symbol, 90), - (15, .symbol, 90), - (24, .symbol, 90), - (31, .symbol, 90), - (41, .symbol, 90), - (56, [.accepted, .symbol], 90), - - /* 74 */ - - (1, .symbol, 33), - (22, [.accepted, .symbol], 33), - (1, .symbol, 34), - (22, [.accepted, .symbol], 34), - (1, .symbol, 40), - (22, [.accepted, .symbol], 40), - (1, .symbol, 41), - (22, [.accepted, .symbol], 41), - (1, .symbol, 63), - (22, [.accepted, .symbol], 63), - (0, [.accepted, .symbol], 39), - (0, [.accepted, .symbol], 43), - (0, [.accepted, .symbol], 124), - (83, .none, 0), - (85, .none, 0), - (88, .none, 0), - - /* 75 */ - - (2, .symbol, 33), - (9, .symbol, 33), - (23, .symbol, 33), - (40, [.accepted, .symbol], 33), - (2, .symbol, 34), - (9, .symbol, 34), - (23, .symbol, 34), - (40, [.accepted, .symbol], 34), - (2, .symbol, 40), - (9, .symbol, 40), - (23, .symbol, 40), - (40, [.accepted, .symbol], 40), - (2, .symbol, 41), - (9, .symbol, 41), - (23, .symbol, 41), - (40, [.accepted, .symbol], 41), - - /* 76 */ - - (3, .symbol, 33), - (6, .symbol, 33), - (10, .symbol, 33), - (15, .symbol, 33), - (24, .symbol, 33), - (31, .symbol, 33), - (41, .symbol, 33), - (56, [.accepted, .symbol], 33), - (3, .symbol, 34), - (6, .symbol, 34), - (10, .symbol, 34), - (15, .symbol, 34), - (24, .symbol, 34), - (31, .symbol, 34), - (41, .symbol, 34), - (56, [.accepted, .symbol], 34), - - /* 77 */ - - (3, .symbol, 40), - (6, .symbol, 40), - (10, .symbol, 40), - (15, .symbol, 40), - (24, .symbol, 40), - (31, .symbol, 40), - (41, .symbol, 40), - (56, [.accepted, .symbol], 40), - (3, .symbol, 41), - (6, .symbol, 41), - (10, .symbol, 41), - (15, .symbol, 41), - (24, .symbol, 41), - (31, .symbol, 41), - (41, .symbol, 41), - (56, [.accepted, .symbol], 41), - - /* 78 */ - - (2, .symbol, 63), - (9, .symbol, 63), - (23, .symbol, 63), - (40, [.accepted, .symbol], 63), - (1, .symbol, 39), - (22, [.accepted, .symbol], 39), - (1, .symbol, 43), - (22, [.accepted, .symbol], 43), - (1, .symbol, 124), - (22, [.accepted, .symbol], 124), - (0, [.accepted, .symbol], 35), - (0, [.accepted, .symbol], 62), - (86, .none, 0), - (87, .none, 0), - (89, .none, 0), - (90, .none, 0), - - /* 79 */ - - (3, .symbol, 63), - (6, .symbol, 63), - (10, .symbol, 63), - (15, .symbol, 63), - (24, .symbol, 63), - (31, .symbol, 63), - (41, .symbol, 63), - (56, [.accepted, .symbol], 63), - (2, .symbol, 39), - (9, .symbol, 39), - (23, .symbol, 39), - (40, [.accepted, .symbol], 39), - (2, .symbol, 43), - (9, .symbol, 43), - (23, .symbol, 43), - (40, [.accepted, .symbol], 43), - - /* 80 */ - - (3, .symbol, 39), - (6, .symbol, 39), - (10, .symbol, 39), - (15, .symbol, 39), - (24, .symbol, 39), - (31, .symbol, 39), - (41, .symbol, 39), - (56, [.accepted, .symbol], 39), - (3, .symbol, 43), - (6, .symbol, 43), - (10, .symbol, 43), - (15, .symbol, 43), - (24, .symbol, 43), - (31, .symbol, 43), - (41, .symbol, 43), - (56, [.accepted, .symbol], 43), - - /* 81 */ - - (2, .symbol, 124), - (9, .symbol, 124), - (23, .symbol, 124), - (40, [.accepted, .symbol], 124), - (1, .symbol, 35), - (22, [.accepted, .symbol], 35), - (1, .symbol, 62), - (22, [.accepted, .symbol], 62), - (0, [.accepted, .symbol], 0), - (0, [.accepted, .symbol], 36), - (0, [.accepted, .symbol], 64), - (0, [.accepted, .symbol], 91), - (0, [.accepted, .symbol], 93), - (0, [.accepted, .symbol], 126), - (91, .none, 0), - (92, .none, 0), - - /* 82 */ - - (3, .symbol, 124), - (6, .symbol, 124), - (10, .symbol, 124), - (15, .symbol, 124), - (24, .symbol, 124), - (31, .symbol, 124), - (41, .symbol, 124), - (56, [.accepted, .symbol], 124), - (2, .symbol, 35), - (9, .symbol, 35), - (23, .symbol, 35), - (40, [.accepted, .symbol], 35), - (2, .symbol, 62), - (9, .symbol, 62), - (23, .symbol, 62), - (40, [.accepted, .symbol], 62), - - /* 83 */ - - (3, .symbol, 35), - (6, .symbol, 35), - (10, .symbol, 35), - (15, .symbol, 35), - (24, .symbol, 35), - (31, .symbol, 35), - (41, .symbol, 35), - (56, [.accepted, .symbol], 35), - (3, .symbol, 62), - (6, .symbol, 62), - (10, .symbol, 62), - (15, .symbol, 62), - (24, .symbol, 62), - (31, .symbol, 62), - (41, .symbol, 62), - (56, [.accepted, .symbol], 62), - - /* 84 */ - - (1, .symbol, 0), - (22, [.accepted, .symbol], 0), - (1, .symbol, 36), - (22, [.accepted, .symbol], 36), - (1, .symbol, 64), - (22, [.accepted, .symbol], 64), - (1, .symbol, 91), - (22, [.accepted, .symbol], 91), - (1, .symbol, 93), - (22, [.accepted, .symbol], 93), - (1, .symbol, 126), - (22, [.accepted, .symbol], 126), - (0, [.accepted, .symbol], 94), - (0, [.accepted, .symbol], 125), - (93, .none, 0), - (94, .none, 0), - - /* 85 */ - - (2, .symbol, 0), - (9, .symbol, 0), - (23, .symbol, 0), - (40, [.accepted, .symbol], 0), - (2, .symbol, 36), - (9, .symbol, 36), - (23, .symbol, 36), - (40, [.accepted, .symbol], 36), - (2, .symbol, 64), - (9, .symbol, 64), - (23, .symbol, 64), - (40, [.accepted, .symbol], 64), - (2, .symbol, 91), - (9, .symbol, 91), - (23, .symbol, 91), - (40, [.accepted, .symbol], 91), - - /* 86 */ - - (3, .symbol, 0), - (6, .symbol, 0), - (10, .symbol, 0), - (15, .symbol, 0), - (24, .symbol, 0), - (31, .symbol, 0), - (41, .symbol, 0), - (56, [.accepted, .symbol], 0), - (3, .symbol, 36), - (6, .symbol, 36), - (10, .symbol, 36), - (15, .symbol, 36), - (24, .symbol, 36), - (31, .symbol, 36), - (41, .symbol, 36), - (56, [.accepted, .symbol], 36), - - /* 87 */ - - (3, .symbol, 64), - (6, .symbol, 64), - (10, .symbol, 64), - (15, .symbol, 64), - (24, .symbol, 64), - (31, .symbol, 64), - (41, .symbol, 64), - (56, [.accepted, .symbol], 64), - (3, .symbol, 91), - (6, .symbol, 91), - (10, .symbol, 91), - (15, .symbol, 91), - (24, .symbol, 91), - (31, .symbol, 91), - (41, .symbol, 91), - (56, [.accepted, .symbol], 91), - - /* 88 */ - - (2, .symbol, 93), - (9, .symbol, 93), - (23, .symbol, 93), - (40, [.accepted, .symbol], 93), - (2, .symbol, 126), - (9, .symbol, 126), - (23, .symbol, 126), - (40, [.accepted, .symbol], 126), - (1, .symbol, 94), - (22, [.accepted, .symbol], 94), - (1, .symbol, 125), - (22, [.accepted, .symbol], 125), - (0, [.accepted, .symbol], 60), - (0, [.accepted, .symbol], 96), - (0, [.accepted, .symbol], 123), - (95, .none, 0), - - /* 89 */ - - (3, .symbol, 93), - (6, .symbol, 93), - (10, .symbol, 93), - (15, .symbol, 93), - (24, .symbol, 93), - (31, .symbol, 93), - (41, .symbol, 93), - (56, [.accepted, .symbol], 93), - (3, .symbol, 126), - (6, .symbol, 126), - (10, .symbol, 126), - (15, .symbol, 126), - (24, .symbol, 126), - (31, .symbol, 126), - (41, .symbol, 126), - (56, [.accepted, .symbol], 126), - - /* 90 */ - - (2, .symbol, 94), - (9, .symbol, 94), - (23, .symbol, 94), - (40, [.accepted, .symbol], 94), - (2, .symbol, 125), - (9, .symbol, 125), - (23, .symbol, 125), - (40, [.accepted, .symbol], 125), - (1, .symbol, 60), - (22, [.accepted, .symbol], 60), - (1, .symbol, 96), - (22, [.accepted, .symbol], 96), - (1, .symbol, 123), - (22, [.accepted, .symbol], 123), - (96, .none, 0), - (110, .none, 0), - - /* 91 */ - - (3, .symbol, 94), - (6, .symbol, 94), - (10, .symbol, 94), - (15, .symbol, 94), - (24, .symbol, 94), - (31, .symbol, 94), - (41, .symbol, 94), - (56, [.accepted, .symbol], 94), - (3, .symbol, 125), - (6, .symbol, 125), - (10, .symbol, 125), - (15, .symbol, 125), - (24, .symbol, 125), - (31, .symbol, 125), - (41, .symbol, 125), - (56, [.accepted, .symbol], 125), - - /* 92 */ - - (2, .symbol, 60), - (9, .symbol, 60), - (23, .symbol, 60), - (40, [.accepted, .symbol], 60), - (2, .symbol, 96), - (9, .symbol, 96), - (23, .symbol, 96), - (40, [.accepted, .symbol], 96), - (2, .symbol, 123), - (9, .symbol, 123), - (23, .symbol, 123), - (40, [.accepted, .symbol], 123), - (97, .none, 0), - (101, .none, 0), - (111, .none, 0), - (133, .none, 0), - - /* 93 */ - - (3, .symbol, 60), - (6, .symbol, 60), - (10, .symbol, 60), - (15, .symbol, 60), - (24, .symbol, 60), - (31, .symbol, 60), - (41, .symbol, 60), - (56, [.accepted, .symbol], 60), - (3, .symbol, 96), - (6, .symbol, 96), - (10, .symbol, 96), - (15, .symbol, 96), - (24, .symbol, 96), - (31, .symbol, 96), - (41, .symbol, 96), - (56, [.accepted, .symbol], 96), - - /* 94 */ - - (3, .symbol, 123), - (6, .symbol, 123), - (10, .symbol, 123), - (15, .symbol, 123), - (24, .symbol, 123), - (31, .symbol, 123), - (41, .symbol, 123), - (56, [.accepted, .symbol], 123), - (98, .none, 0), - (99, .none, 0), - (102, .none, 0), - (105, .none, 0), - (112, .none, 0), - (119, .none, 0), - (134, .none, 0), - (153, .none, 0), - - /* 95 */ - - (0, [.accepted, .symbol], 92), - (0, [.accepted, .symbol], 195), - (0, [.accepted, .symbol], 208), - (100, .none, 0), - (103, .none, 0), - (104, .none, 0), - (106, .none, 0), - (107, .none, 0), - (113, .none, 0), - (116, .none, 0), - (120, .none, 0), - (126, .none, 0), - (135, .none, 0), - (142, .none, 0), - (154, .none, 0), - (169, .none, 0), - - /* 96 */ - - (1, .symbol, 92), - (22, [.accepted, .symbol], 92), - (1, .symbol, 195), - (22, [.accepted, .symbol], 195), - (1, .symbol, 208), - (22, [.accepted, .symbol], 208), - (0, [.accepted, .symbol], 128), - (0, [.accepted, .symbol], 130), - (0, [.accepted, .symbol], 131), - (0, [.accepted, .symbol], 162), - (0, [.accepted, .symbol], 184), - (0, [.accepted, .symbol], 194), - (0, [.accepted, .symbol], 224), - (0, [.accepted, .symbol], 226), - (108, .none, 0), - (109, .none, 0), - - /* 97 */ - - (2, .symbol, 92), - (9, .symbol, 92), - (23, .symbol, 92), - (40, [.accepted, .symbol], 92), - (2, .symbol, 195), - (9, .symbol, 195), - (23, .symbol, 195), - (40, [.accepted, .symbol], 195), - (2, .symbol, 208), - (9, .symbol, 208), - (23, .symbol, 208), - (40, [.accepted, .symbol], 208), - (1, .symbol, 128), - (22, [.accepted, .symbol], 128), - (1, .symbol, 130), - (22, [.accepted, .symbol], 130), - - /* 98 */ - - (3, .symbol, 92), - (6, .symbol, 92), - (10, .symbol, 92), - (15, .symbol, 92), - (24, .symbol, 92), - (31, .symbol, 92), - (41, .symbol, 92), - (56, [.accepted, .symbol], 92), - (3, .symbol, 195), - (6, .symbol, 195), - (10, .symbol, 195), - (15, .symbol, 195), - (24, .symbol, 195), - (31, .symbol, 195), - (41, .symbol, 195), - (56, [.accepted, .symbol], 195), - - /* 99 */ - - (3, .symbol, 208), - (6, .symbol, 208), - (10, .symbol, 208), - (15, .symbol, 208), - (24, .symbol, 208), - (31, .symbol, 208), - (41, .symbol, 208), - (56, [.accepted, .symbol], 208), - (2, .symbol, 128), - (9, .symbol, 128), - (23, .symbol, 128), - (40, [.accepted, .symbol], 128), - (2, .symbol, 130), - (9, .symbol, 130), - (23, .symbol, 130), - (40, [.accepted, .symbol], 130), - - /* 100 */ - - (3, .symbol, 128), - (6, .symbol, 128), - (10, .symbol, 128), - (15, .symbol, 128), - (24, .symbol, 128), - (31, .symbol, 128), - (41, .symbol, 128), - (56, [.accepted, .symbol], 128), - (3, .symbol, 130), - (6, .symbol, 130), - (10, .symbol, 130), - (15, .symbol, 130), - (24, .symbol, 130), - (31, .symbol, 130), - (41, .symbol, 130), - (56, [.accepted, .symbol], 130), - - /* 101 */ - - (1, .symbol, 131), - (22, [.accepted, .symbol], 131), - (1, .symbol, 162), - (22, [.accepted, .symbol], 162), - (1, .symbol, 184), - (22, [.accepted, .symbol], 184), - (1, .symbol, 194), - (22, [.accepted, .symbol], 194), - (1, .symbol, 224), - (22, [.accepted, .symbol], 224), - (1, .symbol, 226), - (22, [.accepted, .symbol], 226), - (0, [.accepted, .symbol], 153), - (0, [.accepted, .symbol], 161), - (0, [.accepted, .symbol], 167), - (0, [.accepted, .symbol], 172), - - /* 102 */ - - (2, .symbol, 131), - (9, .symbol, 131), - (23, .symbol, 131), - (40, [.accepted, .symbol], 131), - (2, .symbol, 162), - (9, .symbol, 162), - (23, .symbol, 162), - (40, [.accepted, .symbol], 162), - (2, .symbol, 184), - (9, .symbol, 184), - (23, .symbol, 184), - (40, [.accepted, .symbol], 184), - (2, .symbol, 194), - (9, .symbol, 194), - (23, .symbol, 194), - (40, [.accepted, .symbol], 194), - - /* 103 */ - - (3, .symbol, 131), - (6, .symbol, 131), - (10, .symbol, 131), - (15, .symbol, 131), - (24, .symbol, 131), - (31, .symbol, 131), - (41, .symbol, 131), - (56, [.accepted, .symbol], 131), - (3, .symbol, 162), - (6, .symbol, 162), - (10, .symbol, 162), - (15, .symbol, 162), - (24, .symbol, 162), - (31, .symbol, 162), - (41, .symbol, 162), - (56, [.accepted, .symbol], 162), - - /* 104 */ - - (3, .symbol, 184), - (6, .symbol, 184), - (10, .symbol, 184), - (15, .symbol, 184), - (24, .symbol, 184), - (31, .symbol, 184), - (41, .symbol, 184), - (56, [.accepted, .symbol], 184), - (3, .symbol, 194), - (6, .symbol, 194), - (10, .symbol, 194), - (15, .symbol, 194), - (24, .symbol, 194), - (31, .symbol, 194), - (41, .symbol, 194), - (56, [.accepted, .symbol], 194), - - /* 105 */ - - (2, .symbol, 224), - (9, .symbol, 224), - (23, .symbol, 224), - (40, [.accepted, .symbol], 224), - (2, .symbol, 226), - (9, .symbol, 226), - (23, .symbol, 226), - (40, [.accepted, .symbol], 226), - (1, .symbol, 153), - (22, [.accepted, .symbol], 153), - (1, .symbol, 161), - (22, [.accepted, .symbol], 161), - (1, .symbol, 167), - (22, [.accepted, .symbol], 167), - (1, .symbol, 172), - (22, [.accepted, .symbol], 172), - - /* 106 */ - - (3, .symbol, 224), - (6, .symbol, 224), - (10, .symbol, 224), - (15, .symbol, 224), - (24, .symbol, 224), - (31, .symbol, 224), - (41, .symbol, 224), - (56, [.accepted, .symbol], 224), - (3, .symbol, 226), - (6, .symbol, 226), - (10, .symbol, 226), - (15, .symbol, 226), - (24, .symbol, 226), - (31, .symbol, 226), - (41, .symbol, 226), - (56, [.accepted, .symbol], 226), - - /* 107 */ - - (2, .symbol, 153), - (9, .symbol, 153), - (23, .symbol, 153), - (40, [.accepted, .symbol], 153), - (2, .symbol, 161), - (9, .symbol, 161), - (23, .symbol, 161), - (40, [.accepted, .symbol], 161), - (2, .symbol, 167), - (9, .symbol, 167), - (23, .symbol, 167), - (40, [.accepted, .symbol], 167), - (2, .symbol, 172), - (9, .symbol, 172), - (23, .symbol, 172), - (40, [.accepted, .symbol], 172), - - /* 108 */ - - (3, .symbol, 153), - (6, .symbol, 153), - (10, .symbol, 153), - (15, .symbol, 153), - (24, .symbol, 153), - (31, .symbol, 153), - (41, .symbol, 153), - (56, [.accepted, .symbol], 153), - (3, .symbol, 161), - (6, .symbol, 161), - (10, .symbol, 161), - (15, .symbol, 161), - (24, .symbol, 161), - (31, .symbol, 161), - (41, .symbol, 161), - (56, [.accepted, .symbol], 161), - - /* 109 */ - - (3, .symbol, 167), - (6, .symbol, 167), - (10, .symbol, 167), - (15, .symbol, 167), - (24, .symbol, 167), - (31, .symbol, 167), - (41, .symbol, 167), - (56, [.accepted, .symbol], 167), - (3, .symbol, 172), - (6, .symbol, 172), - (10, .symbol, 172), - (15, .symbol, 172), - (24, .symbol, 172), - (31, .symbol, 172), - (41, .symbol, 172), - (56, [.accepted, .symbol], 172), - - /* 110 */ - - (114, .none, 0), - (115, .none, 0), - (117, .none, 0), - (118, .none, 0), - (121, .none, 0), - (123, .none, 0), - (127, .none, 0), - (130, .none, 0), - (136, .none, 0), - (139, .none, 0), - (143, .none, 0), - (146, .none, 0), - (155, .none, 0), - (162, .none, 0), - (170, .none, 0), - (180, .none, 0), - - /* 111 */ - - (0, [.accepted, .symbol], 176), - (0, [.accepted, .symbol], 177), - (0, [.accepted, .symbol], 179), - (0, [.accepted, .symbol], 209), - (0, [.accepted, .symbol], 216), - (0, [.accepted, .symbol], 217), - (0, [.accepted, .symbol], 227), - (0, [.accepted, .symbol], 229), - (0, [.accepted, .symbol], 230), - (122, .none, 0), - (124, .none, 0), - (125, .none, 0), - (128, .none, 0), - (129, .none, 0), - (131, .none, 0), - (132, .none, 0), - - /* 112 */ - - (1, .symbol, 176), - (22, [.accepted, .symbol], 176), - (1, .symbol, 177), - (22, [.accepted, .symbol], 177), - (1, .symbol, 179), - (22, [.accepted, .symbol], 179), - (1, .symbol, 209), - (22, [.accepted, .symbol], 209), - (1, .symbol, 216), - (22, [.accepted, .symbol], 216), - (1, .symbol, 217), - (22, [.accepted, .symbol], 217), - (1, .symbol, 227), - (22, [.accepted, .symbol], 227), - (1, .symbol, 229), - (22, [.accepted, .symbol], 229), - - /* 113 */ - - (2, .symbol, 176), - (9, .symbol, 176), - (23, .symbol, 176), - (40, [.accepted, .symbol], 176), - (2, .symbol, 177), - (9, .symbol, 177), - (23, .symbol, 177), - (40, [.accepted, .symbol], 177), - (2, .symbol, 179), - (9, .symbol, 179), - (23, .symbol, 179), - (40, [.accepted, .symbol], 179), - (2, .symbol, 209), - (9, .symbol, 209), - (23, .symbol, 209), - (40, [.accepted, .symbol], 209), - - /* 114 */ - - (3, .symbol, 176), - (6, .symbol, 176), - (10, .symbol, 176), - (15, .symbol, 176), - (24, .symbol, 176), - (31, .symbol, 176), - (41, .symbol, 176), - (56, [.accepted, .symbol], 176), - (3, .symbol, 177), - (6, .symbol, 177), - (10, .symbol, 177), - (15, .symbol, 177), - (24, .symbol, 177), - (31, .symbol, 177), - (41, .symbol, 177), - (56, [.accepted, .symbol], 177), - - /* 115 */ - - (3, .symbol, 179), - (6, .symbol, 179), - (10, .symbol, 179), - (15, .symbol, 179), - (24, .symbol, 179), - (31, .symbol, 179), - (41, .symbol, 179), - (56, [.accepted, .symbol], 179), - (3, .symbol, 209), - (6, .symbol, 209), - (10, .symbol, 209), - (15, .symbol, 209), - (24, .symbol, 209), - (31, .symbol, 209), - (41, .symbol, 209), - (56, [.accepted, .symbol], 209), - - /* 116 */ - - (2, .symbol, 216), - (9, .symbol, 216), - (23, .symbol, 216), - (40, [.accepted, .symbol], 216), - (2, .symbol, 217), - (9, .symbol, 217), - (23, .symbol, 217), - (40, [.accepted, .symbol], 217), - (2, .symbol, 227), - (9, .symbol, 227), - (23, .symbol, 227), - (40, [.accepted, .symbol], 227), - (2, .symbol, 229), - (9, .symbol, 229), - (23, .symbol, 229), - (40, [.accepted, .symbol], 229), - - /* 117 */ - - (3, .symbol, 216), - (6, .symbol, 216), - (10, .symbol, 216), - (15, .symbol, 216), - (24, .symbol, 216), - (31, .symbol, 216), - (41, .symbol, 216), - (56, [.accepted, .symbol], 216), - (3, .symbol, 217), - (6, .symbol, 217), - (10, .symbol, 217), - (15, .symbol, 217), - (24, .symbol, 217), - (31, .symbol, 217), - (41, .symbol, 217), - (56, [.accepted, .symbol], 217), - - /* 118 */ - - (3, .symbol, 227), - (6, .symbol, 227), - (10, .symbol, 227), - (15, .symbol, 227), - (24, .symbol, 227), - (31, .symbol, 227), - (41, .symbol, 227), - (56, [.accepted, .symbol], 227), - (3, .symbol, 229), - (6, .symbol, 229), - (10, .symbol, 229), - (15, .symbol, 229), - (24, .symbol, 229), - (31, .symbol, 229), - (41, .symbol, 229), - (56, [.accepted, .symbol], 229), - - /* 119 */ - - (1, .symbol, 230), - (22, [.accepted, .symbol], 230), - (0, [.accepted, .symbol], 129), - (0, [.accepted, .symbol], 132), - (0, [.accepted, .symbol], 133), - (0, [.accepted, .symbol], 134), - (0, [.accepted, .symbol], 136), - (0, [.accepted, .symbol], 146), - (0, [.accepted, .symbol], 154), - (0, [.accepted, .symbol], 156), - (0, [.accepted, .symbol], 160), - (0, [.accepted, .symbol], 163), - (0, [.accepted, .symbol], 164), - (0, [.accepted, .symbol], 169), - (0, [.accepted, .symbol], 170), - (0, [.accepted, .symbol], 173), - - /* 120 */ - - (2, .symbol, 230), - (9, .symbol, 230), - (23, .symbol, 230), - (40, [.accepted, .symbol], 230), - (1, .symbol, 129), - (22, [.accepted, .symbol], 129), - (1, .symbol, 132), - (22, [.accepted, .symbol], 132), - (1, .symbol, 133), - (22, [.accepted, .symbol], 133), - (1, .symbol, 134), - (22, [.accepted, .symbol], 134), - (1, .symbol, 136), - (22, [.accepted, .symbol], 136), - (1, .symbol, 146), - (22, [.accepted, .symbol], 146), - - /* 121 */ - - (3, .symbol, 230), - (6, .symbol, 230), - (10, .symbol, 230), - (15, .symbol, 230), - (24, .symbol, 230), - (31, .symbol, 230), - (41, .symbol, 230), - (56, [.accepted, .symbol], 230), - (2, .symbol, 129), - (9, .symbol, 129), - (23, .symbol, 129), - (40, [.accepted, .symbol], 129), - (2, .symbol, 132), - (9, .symbol, 132), - (23, .symbol, 132), - (40, [.accepted, .symbol], 132), - - /* 122 */ - - (3, .symbol, 129), - (6, .symbol, 129), - (10, .symbol, 129), - (15, .symbol, 129), - (24, .symbol, 129), - (31, .symbol, 129), - (41, .symbol, 129), - (56, [.accepted, .symbol], 129), - (3, .symbol, 132), - (6, .symbol, 132), - (10, .symbol, 132), - (15, .symbol, 132), - (24, .symbol, 132), - (31, .symbol, 132), - (41, .symbol, 132), - (56, [.accepted, .symbol], 132), - - /* 123 */ - - (2, .symbol, 133), - (9, .symbol, 133), - (23, .symbol, 133), - (40, [.accepted, .symbol], 133), - (2, .symbol, 134), - (9, .symbol, 134), - (23, .symbol, 134), - (40, [.accepted, .symbol], 134), - (2, .symbol, 136), - (9, .symbol, 136), - (23, .symbol, 136), - (40, [.accepted, .symbol], 136), - (2, .symbol, 146), - (9, .symbol, 146), - (23, .symbol, 146), - (40, [.accepted, .symbol], 146), - - /* 124 */ - - (3, .symbol, 133), - (6, .symbol, 133), - (10, .symbol, 133), - (15, .symbol, 133), - (24, .symbol, 133), - (31, .symbol, 133), - (41, .symbol, 133), - (56, [.accepted, .symbol], 133), - (3, .symbol, 134), - (6, .symbol, 134), - (10, .symbol, 134), - (15, .symbol, 134), - (24, .symbol, 134), - (31, .symbol, 134), - (41, .symbol, 134), - (56, [.accepted, .symbol], 134), - - /* 125 */ - - (3, .symbol, 136), - (6, .symbol, 136), - (10, .symbol, 136), - (15, .symbol, 136), - (24, .symbol, 136), - (31, .symbol, 136), - (41, .symbol, 136), - (56, [.accepted, .symbol], 136), - (3, .symbol, 146), - (6, .symbol, 146), - (10, .symbol, 146), - (15, .symbol, 146), - (24, .symbol, 146), - (31, .symbol, 146), - (41, .symbol, 146), - (56, [.accepted, .symbol], 146), - - /* 126 */ - - (1, .symbol, 154), - (22, [.accepted, .symbol], 154), - (1, .symbol, 156), - (22, [.accepted, .symbol], 156), - (1, .symbol, 160), - (22, [.accepted, .symbol], 160), - (1, .symbol, 163), - (22, [.accepted, .symbol], 163), - (1, .symbol, 164), - (22, [.accepted, .symbol], 164), - (1, .symbol, 169), - (22, [.accepted, .symbol], 169), - (1, .symbol, 170), - (22, [.accepted, .symbol], 170), - (1, .symbol, 173), - (22, [.accepted, .symbol], 173), - - /* 127 */ - - (2, .symbol, 154), - (9, .symbol, 154), - (23, .symbol, 154), - (40, [.accepted, .symbol], 154), - (2, .symbol, 156), - (9, .symbol, 156), - (23, .symbol, 156), - (40, [.accepted, .symbol], 156), - (2, .symbol, 160), - (9, .symbol, 160), - (23, .symbol, 160), - (40, [.accepted, .symbol], 160), - (2, .symbol, 163), - (9, .symbol, 163), - (23, .symbol, 163), - (40, [.accepted, .symbol], 163), - - /* 128 */ - - (3, .symbol, 154), - (6, .symbol, 154), - (10, .symbol, 154), - (15, .symbol, 154), - (24, .symbol, 154), - (31, .symbol, 154), - (41, .symbol, 154), - (56, [.accepted, .symbol], 154), - (3, .symbol, 156), - (6, .symbol, 156), - (10, .symbol, 156), - (15, .symbol, 156), - (24, .symbol, 156), - (31, .symbol, 156), - (41, .symbol, 156), - (56, [.accepted, .symbol], 156), - - /* 129 */ - - (3, .symbol, 160), - (6, .symbol, 160), - (10, .symbol, 160), - (15, .symbol, 160), - (24, .symbol, 160), - (31, .symbol, 160), - (41, .symbol, 160), - (56, [.accepted, .symbol], 160), - (3, .symbol, 163), - (6, .symbol, 163), - (10, .symbol, 163), - (15, .symbol, 163), - (24, .symbol, 163), - (31, .symbol, 163), - (41, .symbol, 163), - (56, [.accepted, .symbol], 163), - - /* 130 */ - - (2, .symbol, 164), - (9, .symbol, 164), - (23, .symbol, 164), - (40, [.accepted, .symbol], 164), - (2, .symbol, 169), - (9, .symbol, 169), - (23, .symbol, 169), - (40, [.accepted, .symbol], 169), - (2, .symbol, 170), - (9, .symbol, 170), - (23, .symbol, 170), - (40, [.accepted, .symbol], 170), - (2, .symbol, 173), - (9, .symbol, 173), - (23, .symbol, 173), - (40, [.accepted, .symbol], 173), - - /* 131 */ - - (3, .symbol, 164), - (6, .symbol, 164), - (10, .symbol, 164), - (15, .symbol, 164), - (24, .symbol, 164), - (31, .symbol, 164), - (41, .symbol, 164), - (56, [.accepted, .symbol], 164), - (3, .symbol, 169), - (6, .symbol, 169), - (10, .symbol, 169), - (15, .symbol, 169), - (24, .symbol, 169), - (31, .symbol, 169), - (41, .symbol, 169), - (56, [.accepted, .symbol], 169), - - /* 132 */ - - (3, .symbol, 170), - (6, .symbol, 170), - (10, .symbol, 170), - (15, .symbol, 170), - (24, .symbol, 170), - (31, .symbol, 170), - (41, .symbol, 170), - (56, [.accepted, .symbol], 170), - (3, .symbol, 173), - (6, .symbol, 173), - (10, .symbol, 173), - (15, .symbol, 173), - (24, .symbol, 173), - (31, .symbol, 173), - (41, .symbol, 173), - (56, [.accepted, .symbol], 173), - - /* 133 */ - - (137, .none, 0), - (138, .none, 0), - (140, .none, 0), - (141, .none, 0), - (144, .none, 0), - (145, .none, 0), - (147, .none, 0), - (150, .none, 0), - (156, .none, 0), - (159, .none, 0), - (163, .none, 0), - (166, .none, 0), - (171, .none, 0), - (174, .none, 0), - (181, .none, 0), - (190, .none, 0), - - /* 134 */ - - (0, [.accepted, .symbol], 178), - (0, [.accepted, .symbol], 181), - (0, [.accepted, .symbol], 185), - (0, [.accepted, .symbol], 186), - (0, [.accepted, .symbol], 187), - (0, [.accepted, .symbol], 189), - (0, [.accepted, .symbol], 190), - (0, [.accepted, .symbol], 196), - (0, [.accepted, .symbol], 198), - (0, [.accepted, .symbol], 228), - (0, [.accepted, .symbol], 232), - (0, [.accepted, .symbol], 233), - (148, .none, 0), - (149, .none, 0), - (151, .none, 0), - (152, .none, 0), - - /* 135 */ - - (1, .symbol, 178), - (22, [.accepted, .symbol], 178), - (1, .symbol, 181), - (22, [.accepted, .symbol], 181), - (1, .symbol, 185), - (22, [.accepted, .symbol], 185), - (1, .symbol, 186), - (22, [.accepted, .symbol], 186), - (1, .symbol, 187), - (22, [.accepted, .symbol], 187), - (1, .symbol, 189), - (22, [.accepted, .symbol], 189), - (1, .symbol, 190), - (22, [.accepted, .symbol], 190), - (1, .symbol, 196), - (22, [.accepted, .symbol], 196), - - /* 136 */ - - (2, .symbol, 178), - (9, .symbol, 178), - (23, .symbol, 178), - (40, [.accepted, .symbol], 178), - (2, .symbol, 181), - (9, .symbol, 181), - (23, .symbol, 181), - (40, [.accepted, .symbol], 181), - (2, .symbol, 185), - (9, .symbol, 185), - (23, .symbol, 185), - (40, [.accepted, .symbol], 185), - (2, .symbol, 186), - (9, .symbol, 186), - (23, .symbol, 186), - (40, [.accepted, .symbol], 186), - - /* 137 */ - - (3, .symbol, 178), - (6, .symbol, 178), - (10, .symbol, 178), - (15, .symbol, 178), - (24, .symbol, 178), - (31, .symbol, 178), - (41, .symbol, 178), - (56, [.accepted, .symbol], 178), - (3, .symbol, 181), - (6, .symbol, 181), - (10, .symbol, 181), - (15, .symbol, 181), - (24, .symbol, 181), - (31, .symbol, 181), - (41, .symbol, 181), - (56, [.accepted, .symbol], 181), - - /* 138 */ - - (3, .symbol, 185), - (6, .symbol, 185), - (10, .symbol, 185), - (15, .symbol, 185), - (24, .symbol, 185), - (31, .symbol, 185), - (41, .symbol, 185), - (56, [.accepted, .symbol], 185), - (3, .symbol, 186), - (6, .symbol, 186), - (10, .symbol, 186), - (15, .symbol, 186), - (24, .symbol, 186), - (31, .symbol, 186), - (41, .symbol, 186), - (56, [.accepted, .symbol], 186), - - /* 139 */ - - (2, .symbol, 187), - (9, .symbol, 187), - (23, .symbol, 187), - (40, [.accepted, .symbol], 187), - (2, .symbol, 189), - (9, .symbol, 189), - (23, .symbol, 189), - (40, [.accepted, .symbol], 189), - (2, .symbol, 190), - (9, .symbol, 190), - (23, .symbol, 190), - (40, [.accepted, .symbol], 190), - (2, .symbol, 196), - (9, .symbol, 196), - (23, .symbol, 196), - (40, [.accepted, .symbol], 196), - - /* 140 */ - - (3, .symbol, 187), - (6, .symbol, 187), - (10, .symbol, 187), - (15, .symbol, 187), - (24, .symbol, 187), - (31, .symbol, 187), - (41, .symbol, 187), - (56, [.accepted, .symbol], 187), - (3, .symbol, 189), - (6, .symbol, 189), - (10, .symbol, 189), - (15, .symbol, 189), - (24, .symbol, 189), - (31, .symbol, 189), - (41, .symbol, 189), - (56, [.accepted, .symbol], 189), - - /* 141 */ - - (3, .symbol, 190), - (6, .symbol, 190), - (10, .symbol, 190), - (15, .symbol, 190), - (24, .symbol, 190), - (31, .symbol, 190), - (41, .symbol, 190), - (56, [.accepted, .symbol], 190), - (3, .symbol, 196), - (6, .symbol, 196), - (10, .symbol, 196), - (15, .symbol, 196), - (24, .symbol, 196), - (31, .symbol, 196), - (41, .symbol, 196), - (56, [.accepted, .symbol], 196), - - /* 142 */ - - (1, .symbol, 198), - (22, [.accepted, .symbol], 198), - (1, .symbol, 228), - (22, [.accepted, .symbol], 228), - (1, .symbol, 232), - (22, [.accepted, .symbol], 232), - (1, .symbol, 233), - (22, [.accepted, .symbol], 233), - (0, [.accepted, .symbol], 1), - (0, [.accepted, .symbol], 135), - (0, [.accepted, .symbol], 137), - (0, [.accepted, .symbol], 138), - (0, [.accepted, .symbol], 139), - (0, [.accepted, .symbol], 140), - (0, [.accepted, .symbol], 141), - (0, [.accepted, .symbol], 143), - - /* 143 */ - - (2, .symbol, 198), - (9, .symbol, 198), - (23, .symbol, 198), - (40, [.accepted, .symbol], 198), - (2, .symbol, 228), - (9, .symbol, 228), - (23, .symbol, 228), - (40, [.accepted, .symbol], 228), - (2, .symbol, 232), - (9, .symbol, 232), - (23, .symbol, 232), - (40, [.accepted, .symbol], 232), - (2, .symbol, 233), - (9, .symbol, 233), - (23, .symbol, 233), - (40, [.accepted, .symbol], 233), - - /* 144 */ - - (3, .symbol, 198), - (6, .symbol, 198), - (10, .symbol, 198), - (15, .symbol, 198), - (24, .symbol, 198), - (31, .symbol, 198), - (41, .symbol, 198), - (56, [.accepted, .symbol], 198), - (3, .symbol, 228), - (6, .symbol, 228), - (10, .symbol, 228), - (15, .symbol, 228), - (24, .symbol, 228), - (31, .symbol, 228), - (41, .symbol, 228), - (56, [.accepted, .symbol], 228), - - /* 145 */ - - (3, .symbol, 232), - (6, .symbol, 232), - (10, .symbol, 232), - (15, .symbol, 232), - (24, .symbol, 232), - (31, .symbol, 232), - (41, .symbol, 232), - (56, [.accepted, .symbol], 232), - (3, .symbol, 233), - (6, .symbol, 233), - (10, .symbol, 233), - (15, .symbol, 233), - (24, .symbol, 233), - (31, .symbol, 233), - (41, .symbol, 233), - (56, [.accepted, .symbol], 233), - - /* 146 */ - - (1, .symbol, 1), - (22, [.accepted, .symbol], 1), - (1, .symbol, 135), - (22, [.accepted, .symbol], 135), - (1, .symbol, 137), - (22, [.accepted, .symbol], 137), - (1, .symbol, 138), - (22, [.accepted, .symbol], 138), - (1, .symbol, 139), - (22, [.accepted, .symbol], 139), - (1, .symbol, 140), - (22, [.accepted, .symbol], 140), - (1, .symbol, 141), - (22, [.accepted, .symbol], 141), - (1, .symbol, 143), - (22, [.accepted, .symbol], 143), - - /* 147 */ - - (2, .symbol, 1), - (9, .symbol, 1), - (23, .symbol, 1), - (40, [.accepted, .symbol], 1), - (2, .symbol, 135), - (9, .symbol, 135), - (23, .symbol, 135), - (40, [.accepted, .symbol], 135), - (2, .symbol, 137), - (9, .symbol, 137), - (23, .symbol, 137), - (40, [.accepted, .symbol], 137), - (2, .symbol, 138), - (9, .symbol, 138), - (23, .symbol, 138), - (40, [.accepted, .symbol], 138), - - /* 148 */ - - (3, .symbol, 1), - (6, .symbol, 1), - (10, .symbol, 1), - (15, .symbol, 1), - (24, .symbol, 1), - (31, .symbol, 1), - (41, .symbol, 1), - (56, [.accepted, .symbol], 1), - (3, .symbol, 135), - (6, .symbol, 135), - (10, .symbol, 135), - (15, .symbol, 135), - (24, .symbol, 135), - (31, .symbol, 135), - (41, .symbol, 135), - (56, [.accepted, .symbol], 135), - - /* 149 */ - - (3, .symbol, 137), - (6, .symbol, 137), - (10, .symbol, 137), - (15, .symbol, 137), - (24, .symbol, 137), - (31, .symbol, 137), - (41, .symbol, 137), - (56, [.accepted, .symbol], 137), - (3, .symbol, 138), - (6, .symbol, 138), - (10, .symbol, 138), - (15, .symbol, 138), - (24, .symbol, 138), - (31, .symbol, 138), - (41, .symbol, 138), - (56, [.accepted, .symbol], 138), - - /* 150 */ - - (2, .symbol, 139), - (9, .symbol, 139), - (23, .symbol, 139), - (40, [.accepted, .symbol], 139), - (2, .symbol, 140), - (9, .symbol, 140), - (23, .symbol, 140), - (40, [.accepted, .symbol], 140), - (2, .symbol, 141), - (9, .symbol, 141), - (23, .symbol, 141), - (40, [.accepted, .symbol], 141), - (2, .symbol, 143), - (9, .symbol, 143), - (23, .symbol, 143), - (40, [.accepted, .symbol], 143), - - /* 151 */ - - (3, .symbol, 139), - (6, .symbol, 139), - (10, .symbol, 139), - (15, .symbol, 139), - (24, .symbol, 139), - (31, .symbol, 139), - (41, .symbol, 139), - (56, [.accepted, .symbol], 139), - (3, .symbol, 140), - (6, .symbol, 140), - (10, .symbol, 140), - (15, .symbol, 140), - (24, .symbol, 140), - (31, .symbol, 140), - (41, .symbol, 140), - (56, [.accepted, .symbol], 140), - - /* 152 */ - - (3, .symbol, 141), - (6, .symbol, 141), - (10, .symbol, 141), - (15, .symbol, 141), - (24, .symbol, 141), - (31, .symbol, 141), - (41, .symbol, 141), - (56, [.accepted, .symbol], 141), - (3, .symbol, 143), - (6, .symbol, 143), - (10, .symbol, 143), - (15, .symbol, 143), - (24, .symbol, 143), - (31, .symbol, 143), - (41, .symbol, 143), - (56, [.accepted, .symbol], 143), - - /* 153 */ - - (157, .none, 0), - (158, .none, 0), - (160, .none, 0), - (161, .none, 0), - (164, .none, 0), - (165, .none, 0), - (167, .none, 0), - (168, .none, 0), - (172, .none, 0), - (173, .none, 0), - (175, .none, 0), - (177, .none, 0), - (182, .none, 0), - (185, .none, 0), - (191, .none, 0), - (207, .none, 0), - - /* 154 */ - - (0, [.accepted, .symbol], 147), - (0, [.accepted, .symbol], 149), - (0, [.accepted, .symbol], 150), - (0, [.accepted, .symbol], 151), - (0, [.accepted, .symbol], 152), - (0, [.accepted, .symbol], 155), - (0, [.accepted, .symbol], 157), - (0, [.accepted, .symbol], 158), - (0, [.accepted, .symbol], 165), - (0, [.accepted, .symbol], 166), - (0, [.accepted, .symbol], 168), - (0, [.accepted, .symbol], 174), - (0, [.accepted, .symbol], 175), - (0, [.accepted, .symbol], 180), - (0, [.accepted, .symbol], 182), - (0, [.accepted, .symbol], 183), - - /* 155 */ - - (1, .symbol, 147), - (22, [.accepted, .symbol], 147), - (1, .symbol, 149), - (22, [.accepted, .symbol], 149), - (1, .symbol, 150), - (22, [.accepted, .symbol], 150), - (1, .symbol, 151), - (22, [.accepted, .symbol], 151), - (1, .symbol, 152), - (22, [.accepted, .symbol], 152), - (1, .symbol, 155), - (22, [.accepted, .symbol], 155), - (1, .symbol, 157), - (22, [.accepted, .symbol], 157), - (1, .symbol, 158), - (22, [.accepted, .symbol], 158), - - /* 156 */ - - (2, .symbol, 147), - (9, .symbol, 147), - (23, .symbol, 147), - (40, [.accepted, .symbol], 147), - (2, .symbol, 149), - (9, .symbol, 149), - (23, .symbol, 149), - (40, [.accepted, .symbol], 149), - (2, .symbol, 150), - (9, .symbol, 150), - (23, .symbol, 150), - (40, [.accepted, .symbol], 150), - (2, .symbol, 151), - (9, .symbol, 151), - (23, .symbol, 151), - (40, [.accepted, .symbol], 151), - - /* 157 */ - - (3, .symbol, 147), - (6, .symbol, 147), - (10, .symbol, 147), - (15, .symbol, 147), - (24, .symbol, 147), - (31, .symbol, 147), - (41, .symbol, 147), - (56, [.accepted, .symbol], 147), - (3, .symbol, 149), - (6, .symbol, 149), - (10, .symbol, 149), - (15, .symbol, 149), - (24, .symbol, 149), - (31, .symbol, 149), - (41, .symbol, 149), - (56, [.accepted, .symbol], 149), - - /* 158 */ - - (3, .symbol, 150), - (6, .symbol, 150), - (10, .symbol, 150), - (15, .symbol, 150), - (24, .symbol, 150), - (31, .symbol, 150), - (41, .symbol, 150), - (56, [.accepted, .symbol], 150), - (3, .symbol, 151), - (6, .symbol, 151), - (10, .symbol, 151), - (15, .symbol, 151), - (24, .symbol, 151), - (31, .symbol, 151), - (41, .symbol, 151), - (56, [.accepted, .symbol], 151), - - /* 159 */ - - (2, .symbol, 152), - (9, .symbol, 152), - (23, .symbol, 152), - (40, [.accepted, .symbol], 152), - (2, .symbol, 155), - (9, .symbol, 155), - (23, .symbol, 155), - (40, [.accepted, .symbol], 155), - (2, .symbol, 157), - (9, .symbol, 157), - (23, .symbol, 157), - (40, [.accepted, .symbol], 157), - (2, .symbol, 158), - (9, .symbol, 158), - (23, .symbol, 158), - (40, [.accepted, .symbol], 158), - - /* 160 */ - - (3, .symbol, 152), - (6, .symbol, 152), - (10, .symbol, 152), - (15, .symbol, 152), - (24, .symbol, 152), - (31, .symbol, 152), - (41, .symbol, 152), - (56, [.accepted, .symbol], 152), - (3, .symbol, 155), - (6, .symbol, 155), - (10, .symbol, 155), - (15, .symbol, 155), - (24, .symbol, 155), - (31, .symbol, 155), - (41, .symbol, 155), - (56, [.accepted, .symbol], 155), - - /* 161 */ - - (3, .symbol, 157), - (6, .symbol, 157), - (10, .symbol, 157), - (15, .symbol, 157), - (24, .symbol, 157), - (31, .symbol, 157), - (41, .symbol, 157), - (56, [.accepted, .symbol], 157), - (3, .symbol, 158), - (6, .symbol, 158), - (10, .symbol, 158), - (15, .symbol, 158), - (24, .symbol, 158), - (31, .symbol, 158), - (41, .symbol, 158), - (56, [.accepted, .symbol], 158), - - /* 162 */ - - (1, .symbol, 165), - (22, [.accepted, .symbol], 165), - (1, .symbol, 166), - (22, [.accepted, .symbol], 166), - (1, .symbol, 168), - (22, [.accepted, .symbol], 168), - (1, .symbol, 174), - (22, [.accepted, .symbol], 174), - (1, .symbol, 175), - (22, [.accepted, .symbol], 175), - (1, .symbol, 180), - (22, [.accepted, .symbol], 180), - (1, .symbol, 182), - (22, [.accepted, .symbol], 182), - (1, .symbol, 183), - (22, [.accepted, .symbol], 183), - - /* 163 */ - - (2, .symbol, 165), - (9, .symbol, 165), - (23, .symbol, 165), - (40, [.accepted, .symbol], 165), - (2, .symbol, 166), - (9, .symbol, 166), - (23, .symbol, 166), - (40, [.accepted, .symbol], 166), - (2, .symbol, 168), - (9, .symbol, 168), - (23, .symbol, 168), - (40, [.accepted, .symbol], 168), - (2, .symbol, 174), - (9, .symbol, 174), - (23, .symbol, 174), - (40, [.accepted, .symbol], 174), - - /* 164 */ - - (3, .symbol, 165), - (6, .symbol, 165), - (10, .symbol, 165), - (15, .symbol, 165), - (24, .symbol, 165), - (31, .symbol, 165), - (41, .symbol, 165), - (56, [.accepted, .symbol], 165), - (3, .symbol, 166), - (6, .symbol, 166), - (10, .symbol, 166), - (15, .symbol, 166), - (24, .symbol, 166), - (31, .symbol, 166), - (41, .symbol, 166), - (56, [.accepted, .symbol], 166), - - /* 165 */ - - (3, .symbol, 168), - (6, .symbol, 168), - (10, .symbol, 168), - (15, .symbol, 168), - (24, .symbol, 168), - (31, .symbol, 168), - (41, .symbol, 168), - (56, [.accepted, .symbol], 168), - (3, .symbol, 174), - (6, .symbol, 174), - (10, .symbol, 174), - (15, .symbol, 174), - (24, .symbol, 174), - (31, .symbol, 174), - (41, .symbol, 174), - (56, [.accepted, .symbol], 174), - - /* 166 */ - - (2, .symbol, 175), - (9, .symbol, 175), - (23, .symbol, 175), - (40, [.accepted, .symbol], 175), - (2, .symbol, 180), - (9, .symbol, 180), - (23, .symbol, 180), - (40, [.accepted, .symbol], 180), - (2, .symbol, 182), - (9, .symbol, 182), - (23, .symbol, 182), - (40, [.accepted, .symbol], 182), - (2, .symbol, 183), - (9, .symbol, 183), - (23, .symbol, 183), - (40, [.accepted, .symbol], 183), - - /* 167 */ - - (3, .symbol, 175), - (6, .symbol, 175), - (10, .symbol, 175), - (15, .symbol, 175), - (24, .symbol, 175), - (31, .symbol, 175), - (41, .symbol, 175), - (56, [.accepted, .symbol], 175), - (3, .symbol, 180), - (6, .symbol, 180), - (10, .symbol, 180), - (15, .symbol, 180), - (24, .symbol, 180), - (31, .symbol, 180), - (41, .symbol, 180), - (56, [.accepted, .symbol], 180), - - /* 168 */ - - (3, .symbol, 182), - (6, .symbol, 182), - (10, .symbol, 182), - (15, .symbol, 182), - (24, .symbol, 182), - (31, .symbol, 182), - (41, .symbol, 182), - (56, [.accepted, .symbol], 182), - (3, .symbol, 183), - (6, .symbol, 183), - (10, .symbol, 183), - (15, .symbol, 183), - (24, .symbol, 183), - (31, .symbol, 183), - (41, .symbol, 183), - (56, [.accepted, .symbol], 183), - - /* 169 */ - - (0, [.accepted, .symbol], 188), - (0, [.accepted, .symbol], 191), - (0, [.accepted, .symbol], 197), - (0, [.accepted, .symbol], 231), - (0, [.accepted, .symbol], 239), - (176, .none, 0), - (178, .none, 0), - (179, .none, 0), - (183, .none, 0), - (184, .none, 0), - (186, .none, 0), - (187, .none, 0), - (192, .none, 0), - (199, .none, 0), - (208, .none, 0), - (223, .none, 0), - - /* 170 */ - - (1, .symbol, 188), - (22, [.accepted, .symbol], 188), - (1, .symbol, 191), - (22, [.accepted, .symbol], 191), - (1, .symbol, 197), - (22, [.accepted, .symbol], 197), - (1, .symbol, 231), - (22, [.accepted, .symbol], 231), - (1, .symbol, 239), - (22, [.accepted, .symbol], 239), - (0, [.accepted, .symbol], 9), - (0, [.accepted, .symbol], 142), - (0, [.accepted, .symbol], 144), - (0, [.accepted, .symbol], 145), - (0, [.accepted, .symbol], 148), - (0, [.accepted, .symbol], 159), - - /* 171 */ - - (2, .symbol, 188), - (9, .symbol, 188), - (23, .symbol, 188), - (40, [.accepted, .symbol], 188), - (2, .symbol, 191), - (9, .symbol, 191), - (23, .symbol, 191), - (40, [.accepted, .symbol], 191), - (2, .symbol, 197), - (9, .symbol, 197), - (23, .symbol, 197), - (40, [.accepted, .symbol], 197), - (2, .symbol, 231), - (9, .symbol, 231), - (23, .symbol, 231), - (40, [.accepted, .symbol], 231), - - /* 172 */ - - (3, .symbol, 188), - (6, .symbol, 188), - (10, .symbol, 188), - (15, .symbol, 188), - (24, .symbol, 188), - (31, .symbol, 188), - (41, .symbol, 188), - (56, [.accepted, .symbol], 188), - (3, .symbol, 191), - (6, .symbol, 191), - (10, .symbol, 191), - (15, .symbol, 191), - (24, .symbol, 191), - (31, .symbol, 191), - (41, .symbol, 191), - (56, [.accepted, .symbol], 191), - - /* 173 */ - - (3, .symbol, 197), - (6, .symbol, 197), - (10, .symbol, 197), - (15, .symbol, 197), - (24, .symbol, 197), - (31, .symbol, 197), - (41, .symbol, 197), - (56, [.accepted, .symbol], 197), - (3, .symbol, 231), - (6, .symbol, 231), - (10, .symbol, 231), - (15, .symbol, 231), - (24, .symbol, 231), - (31, .symbol, 231), - (41, .symbol, 231), - (56, [.accepted, .symbol], 231), - - /* 174 */ - - (2, .symbol, 239), - (9, .symbol, 239), - (23, .symbol, 239), - (40, [.accepted, .symbol], 239), - (1, .symbol, 9), - (22, [.accepted, .symbol], 9), - (1, .symbol, 142), - (22, [.accepted, .symbol], 142), - (1, .symbol, 144), - (22, [.accepted, .symbol], 144), - (1, .symbol, 145), - (22, [.accepted, .symbol], 145), - (1, .symbol, 148), - (22, [.accepted, .symbol], 148), - (1, .symbol, 159), - (22, [.accepted, .symbol], 159), - - /* 175 */ - - (3, .symbol, 239), - (6, .symbol, 239), - (10, .symbol, 239), - (15, .symbol, 239), - (24, .symbol, 239), - (31, .symbol, 239), - (41, .symbol, 239), - (56, [.accepted, .symbol], 239), - (2, .symbol, 9), - (9, .symbol, 9), - (23, .symbol, 9), - (40, [.accepted, .symbol], 9), - (2, .symbol, 142), - (9, .symbol, 142), - (23, .symbol, 142), - (40, [.accepted, .symbol], 142), - - /* 176 */ - - (3, .symbol, 9), - (6, .symbol, 9), - (10, .symbol, 9), - (15, .symbol, 9), - (24, .symbol, 9), - (31, .symbol, 9), - (41, .symbol, 9), - (56, [.accepted, .symbol], 9), - (3, .symbol, 142), - (6, .symbol, 142), - (10, .symbol, 142), - (15, .symbol, 142), - (24, .symbol, 142), - (31, .symbol, 142), - (41, .symbol, 142), - (56, [.accepted, .symbol], 142), - - /* 177 */ - - (2, .symbol, 144), - (9, .symbol, 144), - (23, .symbol, 144), - (40, [.accepted, .symbol], 144), - (2, .symbol, 145), - (9, .symbol, 145), - (23, .symbol, 145), - (40, [.accepted, .symbol], 145), - (2, .symbol, 148), - (9, .symbol, 148), - (23, .symbol, 148), - (40, [.accepted, .symbol], 148), - (2, .symbol, 159), - (9, .symbol, 159), - (23, .symbol, 159), - (40, [.accepted, .symbol], 159), - - /* 178 */ - - (3, .symbol, 144), - (6, .symbol, 144), - (10, .symbol, 144), - (15, .symbol, 144), - (24, .symbol, 144), - (31, .symbol, 144), - (41, .symbol, 144), - (56, [.accepted, .symbol], 144), - (3, .symbol, 145), - (6, .symbol, 145), - (10, .symbol, 145), - (15, .symbol, 145), - (24, .symbol, 145), - (31, .symbol, 145), - (41, .symbol, 145), - (56, [.accepted, .symbol], 145), - - /* 179 */ - - (3, .symbol, 148), - (6, .symbol, 148), - (10, .symbol, 148), - (15, .symbol, 148), - (24, .symbol, 148), - (31, .symbol, 148), - (41, .symbol, 148), - (56, [.accepted, .symbol], 148), - (3, .symbol, 159), - (6, .symbol, 159), - (10, .symbol, 159), - (15, .symbol, 159), - (24, .symbol, 159), - (31, .symbol, 159), - (41, .symbol, 159), - (56, [.accepted, .symbol], 159), - - /* 180 */ - - (0, [.accepted, .symbol], 171), - (0, [.accepted, .symbol], 206), - (0, [.accepted, .symbol], 215), - (0, [.accepted, .symbol], 225), - (0, [.accepted, .symbol], 236), - (0, [.accepted, .symbol], 237), - (188, .none, 0), - (189, .none, 0), - (193, .none, 0), - (196, .none, 0), - (200, .none, 0), - (203, .none, 0), - (209, .none, 0), - (216, .none, 0), - (224, .none, 0), - (238, .none, 0), - - /* 181 */ - - (1, .symbol, 171), - (22, [.accepted, .symbol], 171), - (1, .symbol, 206), - (22, [.accepted, .symbol], 206), - (1, .symbol, 215), - (22, [.accepted, .symbol], 215), - (1, .symbol, 225), - (22, [.accepted, .symbol], 225), - (1, .symbol, 236), - (22, [.accepted, .symbol], 236), - (1, .symbol, 237), - (22, [.accepted, .symbol], 237), - (0, [.accepted, .symbol], 199), - (0, [.accepted, .symbol], 207), - (0, [.accepted, .symbol], 234), - (0, [.accepted, .symbol], 235), - - /* 182 */ - - (2, .symbol, 171), - (9, .symbol, 171), - (23, .symbol, 171), - (40, [.accepted, .symbol], 171), - (2, .symbol, 206), - (9, .symbol, 206), - (23, .symbol, 206), - (40, [.accepted, .symbol], 206), - (2, .symbol, 215), - (9, .symbol, 215), - (23, .symbol, 215), - (40, [.accepted, .symbol], 215), - (2, .symbol, 225), - (9, .symbol, 225), - (23, .symbol, 225), - (40, [.accepted, .symbol], 225), - - /* 183 */ - - (3, .symbol, 171), - (6, .symbol, 171), - (10, .symbol, 171), - (15, .symbol, 171), - (24, .symbol, 171), - (31, .symbol, 171), - (41, .symbol, 171), - (56, [.accepted, .symbol], 171), - (3, .symbol, 206), - (6, .symbol, 206), - (10, .symbol, 206), - (15, .symbol, 206), - (24, .symbol, 206), - (31, .symbol, 206), - (41, .symbol, 206), - (56, [.accepted, .symbol], 206), - - /* 184 */ - - (3, .symbol, 215), - (6, .symbol, 215), - (10, .symbol, 215), - (15, .symbol, 215), - (24, .symbol, 215), - (31, .symbol, 215), - (41, .symbol, 215), - (56, [.accepted, .symbol], 215), - (3, .symbol, 225), - (6, .symbol, 225), - (10, .symbol, 225), - (15, .symbol, 225), - (24, .symbol, 225), - (31, .symbol, 225), - (41, .symbol, 225), - (56, [.accepted, .symbol], 225), - - /* 185 */ - - (2, .symbol, 236), - (9, .symbol, 236), - (23, .symbol, 236), - (40, [.accepted, .symbol], 236), - (2, .symbol, 237), - (9, .symbol, 237), - (23, .symbol, 237), - (40, [.accepted, .symbol], 237), - (1, .symbol, 199), - (22, [.accepted, .symbol], 199), - (1, .symbol, 207), - (22, [.accepted, .symbol], 207), - (1, .symbol, 234), - (22, [.accepted, .symbol], 234), - (1, .symbol, 235), - (22, [.accepted, .symbol], 235), - - /* 186 */ - - (3, .symbol, 236), - (6, .symbol, 236), - (10, .symbol, 236), - (15, .symbol, 236), - (24, .symbol, 236), - (31, .symbol, 236), - (41, .symbol, 236), - (56, [.accepted, .symbol], 236), - (3, .symbol, 237), - (6, .symbol, 237), - (10, .symbol, 237), - (15, .symbol, 237), - (24, .symbol, 237), - (31, .symbol, 237), - (41, .symbol, 237), - (56, [.accepted, .symbol], 237), - - /* 187 */ - - (2, .symbol, 199), - (9, .symbol, 199), - (23, .symbol, 199), - (40, [.accepted, .symbol], 199), - (2, .symbol, 207), - (9, .symbol, 207), - (23, .symbol, 207), - (40, [.accepted, .symbol], 207), - (2, .symbol, 234), - (9, .symbol, 234), - (23, .symbol, 234), - (40, [.accepted, .symbol], 234), - (2, .symbol, 235), - (9, .symbol, 235), - (23, .symbol, 235), - (40, [.accepted, .symbol], 235), - - /* 188 */ - - (3, .symbol, 199), - (6, .symbol, 199), - (10, .symbol, 199), - (15, .symbol, 199), - (24, .symbol, 199), - (31, .symbol, 199), - (41, .symbol, 199), - (56, [.accepted, .symbol], 199), - (3, .symbol, 207), - (6, .symbol, 207), - (10, .symbol, 207), - (15, .symbol, 207), - (24, .symbol, 207), - (31, .symbol, 207), - (41, .symbol, 207), - (56, [.accepted, .symbol], 207), - - /* 189 */ - - (3, .symbol, 234), - (6, .symbol, 234), - (10, .symbol, 234), - (15, .symbol, 234), - (24, .symbol, 234), - (31, .symbol, 234), - (41, .symbol, 234), - (56, [.accepted, .symbol], 234), - (3, .symbol, 235), - (6, .symbol, 235), - (10, .symbol, 235), - (15, .symbol, 235), - (24, .symbol, 235), - (31, .symbol, 235), - (41, .symbol, 235), - (56, [.accepted, .symbol], 235), - - /* 190 */ - - (194, .none, 0), - (195, .none, 0), - (197, .none, 0), - (198, .none, 0), - (201, .none, 0), - (202, .none, 0), - (204, .none, 0), - (205, .none, 0), - (210, .none, 0), - (213, .none, 0), - (217, .none, 0), - (220, .none, 0), - (225, .none, 0), - (231, .none, 0), - (239, .none, 0), - (246, .none, 0), - - /* 191 */ - - (0, [.accepted, .symbol], 192), - (0, [.accepted, .symbol], 193), - (0, [.accepted, .symbol], 200), - (0, [.accepted, .symbol], 201), - (0, [.accepted, .symbol], 202), - (0, [.accepted, .symbol], 205), - (0, [.accepted, .symbol], 210), - (0, [.accepted, .symbol], 213), - (0, [.accepted, .symbol], 218), - (0, [.accepted, .symbol], 219), - (0, [.accepted, .symbol], 238), - (0, [.accepted, .symbol], 240), - (0, [.accepted, .symbol], 242), - (0, [.accepted, .symbol], 243), - (0, [.accepted, .symbol], 255), - (206, .none, 0), - - /* 192 */ - - (1, .symbol, 192), - (22, [.accepted, .symbol], 192), - (1, .symbol, 193), - (22, [.accepted, .symbol], 193), - (1, .symbol, 200), - (22, [.accepted, .symbol], 200), - (1, .symbol, 201), - (22, [.accepted, .symbol], 201), - (1, .symbol, 202), - (22, [.accepted, .symbol], 202), - (1, .symbol, 205), - (22, [.accepted, .symbol], 205), - (1, .symbol, 210), - (22, [.accepted, .symbol], 210), - (1, .symbol, 213), - (22, [.accepted, .symbol], 213), - - /* 193 */ - - (2, .symbol, 192), - (9, .symbol, 192), - (23, .symbol, 192), - (40, [.accepted, .symbol], 192), - (2, .symbol, 193), - (9, .symbol, 193), - (23, .symbol, 193), - (40, [.accepted, .symbol], 193), - (2, .symbol, 200), - (9, .symbol, 200), - (23, .symbol, 200), - (40, [.accepted, .symbol], 200), - (2, .symbol, 201), - (9, .symbol, 201), - (23, .symbol, 201), - (40, [.accepted, .symbol], 201), - - /* 194 */ - - (3, .symbol, 192), - (6, .symbol, 192), - (10, .symbol, 192), - (15, .symbol, 192), - (24, .symbol, 192), - (31, .symbol, 192), - (41, .symbol, 192), - (56, [.accepted, .symbol], 192), - (3, .symbol, 193), - (6, .symbol, 193), - (10, .symbol, 193), - (15, .symbol, 193), - (24, .symbol, 193), - (31, .symbol, 193), - (41, .symbol, 193), - (56, [.accepted, .symbol], 193), - - /* 195 */ - - (3, .symbol, 200), - (6, .symbol, 200), - (10, .symbol, 200), - (15, .symbol, 200), - (24, .symbol, 200), - (31, .symbol, 200), - (41, .symbol, 200), - (56, [.accepted, .symbol], 200), - (3, .symbol, 201), - (6, .symbol, 201), - (10, .symbol, 201), - (15, .symbol, 201), - (24, .symbol, 201), - (31, .symbol, 201), - (41, .symbol, 201), - (56, [.accepted, .symbol], 201), - - /* 196 */ - - (2, .symbol, 202), - (9, .symbol, 202), - (23, .symbol, 202), - (40, [.accepted, .symbol], 202), - (2, .symbol, 205), - (9, .symbol, 205), - (23, .symbol, 205), - (40, [.accepted, .symbol], 205), - (2, .symbol, 210), - (9, .symbol, 210), - (23, .symbol, 210), - (40, [.accepted, .symbol], 210), - (2, .symbol, 213), - (9, .symbol, 213), - (23, .symbol, 213), - (40, [.accepted, .symbol], 213), - - /* 197 */ - - (3, .symbol, 202), - (6, .symbol, 202), - (10, .symbol, 202), - (15, .symbol, 202), - (24, .symbol, 202), - (31, .symbol, 202), - (41, .symbol, 202), - (56, [.accepted, .symbol], 202), - (3, .symbol, 205), - (6, .symbol, 205), - (10, .symbol, 205), - (15, .symbol, 205), - (24, .symbol, 205), - (31, .symbol, 205), - (41, .symbol, 205), - (56, [.accepted, .symbol], 205), - - /* 198 */ - - (3, .symbol, 210), - (6, .symbol, 210), - (10, .symbol, 210), - (15, .symbol, 210), - (24, .symbol, 210), - (31, .symbol, 210), - (41, .symbol, 210), - (56, [.accepted, .symbol], 210), - (3, .symbol, 213), - (6, .symbol, 213), - (10, .symbol, 213), - (15, .symbol, 213), - (24, .symbol, 213), - (31, .symbol, 213), - (41, .symbol, 213), - (56, [.accepted, .symbol], 213), - - /* 199 */ - - (1, .symbol, 218), - (22, [.accepted, .symbol], 218), - (1, .symbol, 219), - (22, [.accepted, .symbol], 219), - (1, .symbol, 238), - (22, [.accepted, .symbol], 238), - (1, .symbol, 240), - (22, [.accepted, .symbol], 240), - (1, .symbol, 242), - (22, [.accepted, .symbol], 242), - (1, .symbol, 243), - (22, [.accepted, .symbol], 243), - (1, .symbol, 255), - (22, [.accepted, .symbol], 255), - (0, [.accepted, .symbol], 203), - (0, [.accepted, .symbol], 204), - - /* 200 */ - - (2, .symbol, 218), - (9, .symbol, 218), - (23, .symbol, 218), - (40, [.accepted, .symbol], 218), - (2, .symbol, 219), - (9, .symbol, 219), - (23, .symbol, 219), - (40, [.accepted, .symbol], 219), - (2, .symbol, 238), - (9, .symbol, 238), - (23, .symbol, 238), - (40, [.accepted, .symbol], 238), - (2, .symbol, 240), - (9, .symbol, 240), - (23, .symbol, 240), - (40, [.accepted, .symbol], 240), - - /* 201 */ - - (3, .symbol, 218), - (6, .symbol, 218), - (10, .symbol, 218), - (15, .symbol, 218), - (24, .symbol, 218), - (31, .symbol, 218), - (41, .symbol, 218), - (56, [.accepted, .symbol], 218), - (3, .symbol, 219), - (6, .symbol, 219), - (10, .symbol, 219), - (15, .symbol, 219), - (24, .symbol, 219), - (31, .symbol, 219), - (41, .symbol, 219), - (56, [.accepted, .symbol], 219), - - /* 202 */ - - (3, .symbol, 238), - (6, .symbol, 238), - (10, .symbol, 238), - (15, .symbol, 238), - (24, .symbol, 238), - (31, .symbol, 238), - (41, .symbol, 238), - (56, [.accepted, .symbol], 238), - (3, .symbol, 240), - (6, .symbol, 240), - (10, .symbol, 240), - (15, .symbol, 240), - (24, .symbol, 240), - (31, .symbol, 240), - (41, .symbol, 240), - (56, [.accepted, .symbol], 240), - - /* 203 */ - - (2, .symbol, 242), - (9, .symbol, 242), - (23, .symbol, 242), - (40, [.accepted, .symbol], 242), - (2, .symbol, 243), - (9, .symbol, 243), - (23, .symbol, 243), - (40, [.accepted, .symbol], 243), - (2, .symbol, 255), - (9, .symbol, 255), - (23, .symbol, 255), - (40, [.accepted, .symbol], 255), - (1, .symbol, 203), - (22, [.accepted, .symbol], 203), - (1, .symbol, 204), - (22, [.accepted, .symbol], 204), - - /* 204 */ - - (3, .symbol, 242), - (6, .symbol, 242), - (10, .symbol, 242), - (15, .symbol, 242), - (24, .symbol, 242), - (31, .symbol, 242), - (41, .symbol, 242), - (56, [.accepted, .symbol], 242), - (3, .symbol, 243), - (6, .symbol, 243), - (10, .symbol, 243), - (15, .symbol, 243), - (24, .symbol, 243), - (31, .symbol, 243), - (41, .symbol, 243), - (56, [.accepted, .symbol], 243), - - /* 205 */ - - (3, .symbol, 255), - (6, .symbol, 255), - (10, .symbol, 255), - (15, .symbol, 255), - (24, .symbol, 255), - (31, .symbol, 255), - (41, .symbol, 255), - (56, [.accepted, .symbol], 255), - (2, .symbol, 203), - (9, .symbol, 203), - (23, .symbol, 203), - (40, [.accepted, .symbol], 203), - (2, .symbol, 204), - (9, .symbol, 204), - (23, .symbol, 204), - (40, [.accepted, .symbol], 204), - - /* 206 */ - - (3, .symbol, 203), - (6, .symbol, 203), - (10, .symbol, 203), - (15, .symbol, 203), - (24, .symbol, 203), - (31, .symbol, 203), - (41, .symbol, 203), - (56, [.accepted, .symbol], 203), - (3, .symbol, 204), - (6, .symbol, 204), - (10, .symbol, 204), - (15, .symbol, 204), - (24, .symbol, 204), - (31, .symbol, 204), - (41, .symbol, 204), - (56, [.accepted, .symbol], 204), - - /* 207 */ - - (211, .none, 0), - (212, .none, 0), - (214, .none, 0), - (215, .none, 0), - (218, .none, 0), - (219, .none, 0), - (221, .none, 0), - (222, .none, 0), - (226, .none, 0), - (228, .none, 0), - (232, .none, 0), - (235, .none, 0), - (240, .none, 0), - (243, .none, 0), - (247, .none, 0), - (250, .none, 0), - - /* 208 */ - - (0, [.accepted, .symbol], 211), - (0, [.accepted, .symbol], 212), - (0, [.accepted, .symbol], 214), - (0, [.accepted, .symbol], 221), - (0, [.accepted, .symbol], 222), - (0, [.accepted, .symbol], 223), - (0, [.accepted, .symbol], 241), - (0, [.accepted, .symbol], 244), - (0, [.accepted, .symbol], 245), - (0, [.accepted, .symbol], 246), - (0, [.accepted, .symbol], 247), - (0, [.accepted, .symbol], 248), - (0, [.accepted, .symbol], 250), - (0, [.accepted, .symbol], 251), - (0, [.accepted, .symbol], 252), - (0, [.accepted, .symbol], 253), - - /* 209 */ - - (1, .symbol, 211), - (22, [.accepted, .symbol], 211), - (1, .symbol, 212), - (22, [.accepted, .symbol], 212), - (1, .symbol, 214), - (22, [.accepted, .symbol], 214), - (1, .symbol, 221), - (22, [.accepted, .symbol], 221), - (1, .symbol, 222), - (22, [.accepted, .symbol], 222), - (1, .symbol, 223), - (22, [.accepted, .symbol], 223), - (1, .symbol, 241), - (22, [.accepted, .symbol], 241), - (1, .symbol, 244), - (22, [.accepted, .symbol], 244), - - /* 210 */ - - (2, .symbol, 211), - (9, .symbol, 211), - (23, .symbol, 211), - (40, [.accepted, .symbol], 211), - (2, .symbol, 212), - (9, .symbol, 212), - (23, .symbol, 212), - (40, [.accepted, .symbol], 212), - (2, .symbol, 214), - (9, .symbol, 214), - (23, .symbol, 214), - (40, [.accepted, .symbol], 214), - (2, .symbol, 221), - (9, .symbol, 221), - (23, .symbol, 221), - (40, [.accepted, .symbol], 221), - - /* 211 */ - - (3, .symbol, 211), - (6, .symbol, 211), - (10, .symbol, 211), - (15, .symbol, 211), - (24, .symbol, 211), - (31, .symbol, 211), - (41, .symbol, 211), - (56, [.accepted, .symbol], 211), - (3, .symbol, 212), - (6, .symbol, 212), - (10, .symbol, 212), - (15, .symbol, 212), - (24, .symbol, 212), - (31, .symbol, 212), - (41, .symbol, 212), - (56, [.accepted, .symbol], 212), - - /* 212 */ - - (3, .symbol, 214), - (6, .symbol, 214), - (10, .symbol, 214), - (15, .symbol, 214), - (24, .symbol, 214), - (31, .symbol, 214), - (41, .symbol, 214), - (56, [.accepted, .symbol], 214), - (3, .symbol, 221), - (6, .symbol, 221), - (10, .symbol, 221), - (15, .symbol, 221), - (24, .symbol, 221), - (31, .symbol, 221), - (41, .symbol, 221), - (56, [.accepted, .symbol], 221), - - /* 213 */ - - (2, .symbol, 222), - (9, .symbol, 222), - (23, .symbol, 222), - (40, [.accepted, .symbol], 222), - (2, .symbol, 223), - (9, .symbol, 223), - (23, .symbol, 223), - (40, [.accepted, .symbol], 223), - (2, .symbol, 241), - (9, .symbol, 241), - (23, .symbol, 241), - (40, [.accepted, .symbol], 241), - (2, .symbol, 244), - (9, .symbol, 244), - (23, .symbol, 244), - (40, [.accepted, .symbol], 244), - - /* 214 */ - - (3, .symbol, 222), - (6, .symbol, 222), - (10, .symbol, 222), - (15, .symbol, 222), - (24, .symbol, 222), - (31, .symbol, 222), - (41, .symbol, 222), - (56, [.accepted, .symbol], 222), - (3, .symbol, 223), - (6, .symbol, 223), - (10, .symbol, 223), - (15, .symbol, 223), - (24, .symbol, 223), - (31, .symbol, 223), - (41, .symbol, 223), - (56, [.accepted, .symbol], 223), - - /* 215 */ - - (3, .symbol, 241), - (6, .symbol, 241), - (10, .symbol, 241), - (15, .symbol, 241), - (24, .symbol, 241), - (31, .symbol, 241), - (41, .symbol, 241), - (56, [.accepted, .symbol], 241), - (3, .symbol, 244), - (6, .symbol, 244), - (10, .symbol, 244), - (15, .symbol, 244), - (24, .symbol, 244), - (31, .symbol, 244), - (41, .symbol, 244), - (56, [.accepted, .symbol], 244), - - /* 216 */ - - (1, .symbol, 245), - (22, [.accepted, .symbol], 245), - (1, .symbol, 246), - (22, [.accepted, .symbol], 246), - (1, .symbol, 247), - (22, [.accepted, .symbol], 247), - (1, .symbol, 248), - (22, [.accepted, .symbol], 248), - (1, .symbol, 250), - (22, [.accepted, .symbol], 250), - (1, .symbol, 251), - (22, [.accepted, .symbol], 251), - (1, .symbol, 252), - (22, [.accepted, .symbol], 252), - (1, .symbol, 253), - (22, [.accepted, .symbol], 253), - - /* 217 */ - - (2, .symbol, 245), - (9, .symbol, 245), - (23, .symbol, 245), - (40, [.accepted, .symbol], 245), - (2, .symbol, 246), - (9, .symbol, 246), - (23, .symbol, 246), - (40, [.accepted, .symbol], 246), - (2, .symbol, 247), - (9, .symbol, 247), - (23, .symbol, 247), - (40, [.accepted, .symbol], 247), - (2, .symbol, 248), - (9, .symbol, 248), - (23, .symbol, 248), - (40, [.accepted, .symbol], 248), - - /* 218 */ - - (3, .symbol, 245), - (6, .symbol, 245), - (10, .symbol, 245), - (15, .symbol, 245), - (24, .symbol, 245), - (31, .symbol, 245), - (41, .symbol, 245), - (56, [.accepted, .symbol], 245), - (3, .symbol, 246), - (6, .symbol, 246), - (10, .symbol, 246), - (15, .symbol, 246), - (24, .symbol, 246), - (31, .symbol, 246), - (41, .symbol, 246), - (56, [.accepted, .symbol], 246), - - /* 219 */ - - (3, .symbol, 247), - (6, .symbol, 247), - (10, .symbol, 247), - (15, .symbol, 247), - (24, .symbol, 247), - (31, .symbol, 247), - (41, .symbol, 247), - (56, [.accepted, .symbol], 247), - (3, .symbol, 248), - (6, .symbol, 248), - (10, .symbol, 248), - (15, .symbol, 248), - (24, .symbol, 248), - (31, .symbol, 248), - (41, .symbol, 248), - (56, [.accepted, .symbol], 248), - - /* 220 */ - - (2, .symbol, 250), - (9, .symbol, 250), - (23, .symbol, 250), - (40, [.accepted, .symbol], 250), - (2, .symbol, 251), - (9, .symbol, 251), - (23, .symbol, 251), - (40, [.accepted, .symbol], 251), - (2, .symbol, 252), - (9, .symbol, 252), - (23, .symbol, 252), - (40, [.accepted, .symbol], 252), - (2, .symbol, 253), - (9, .symbol, 253), - (23, .symbol, 253), - (40, [.accepted, .symbol], 253), - - /* 221 */ - - (3, .symbol, 250), - (6, .symbol, 250), - (10, .symbol, 250), - (15, .symbol, 250), - (24, .symbol, 250), - (31, .symbol, 250), - (41, .symbol, 250), - (56, [.accepted, .symbol], 250), - (3, .symbol, 251), - (6, .symbol, 251), - (10, .symbol, 251), - (15, .symbol, 251), - (24, .symbol, 251), - (31, .symbol, 251), - (41, .symbol, 251), - (56, [.accepted, .symbol], 251), - - /* 222 */ - - (3, .symbol, 252), - (6, .symbol, 252), - (10, .symbol, 252), - (15, .symbol, 252), - (24, .symbol, 252), - (31, .symbol, 252), - (41, .symbol, 252), - (56, [.accepted, .symbol], 252), - (3, .symbol, 253), - (6, .symbol, 253), - (10, .symbol, 253), - (15, .symbol, 253), - (24, .symbol, 253), - (31, .symbol, 253), - (41, .symbol, 253), - (56, [.accepted, .symbol], 253), - - /* 223 */ - - (0, [.accepted, .symbol], 254), - (227, .none, 0), - (229, .none, 0), - (230, .none, 0), - (233, .none, 0), - (234, .none, 0), - (236, .none, 0), - (237, .none, 0), - (241, .none, 0), - (242, .none, 0), - (244, .none, 0), - (245, .none, 0), - (248, .none, 0), - (249, .none, 0), - (251, .none, 0), - (252, .none, 0), - - /* 224 */ - - (1, .symbol, 254), - (22, [.accepted, .symbol], 254), - (0, [.accepted, .symbol], 2), - (0, [.accepted, .symbol], 3), - (0, [.accepted, .symbol], 4), - (0, [.accepted, .symbol], 5), - (0, [.accepted, .symbol], 6), - (0, [.accepted, .symbol], 7), - (0, [.accepted, .symbol], 8), - (0, [.accepted, .symbol], 11), - (0, [.accepted, .symbol], 12), - (0, [.accepted, .symbol], 14), - (0, [.accepted, .symbol], 15), - (0, [.accepted, .symbol], 16), - (0, [.accepted, .symbol], 17), - (0, [.accepted, .symbol], 18), - - /* 225 */ - - (2, .symbol, 254), - (9, .symbol, 254), - (23, .symbol, 254), - (40, [.accepted, .symbol], 254), - (1, .symbol, 2), - (22, [.accepted, .symbol], 2), - (1, .symbol, 3), - (22, [.accepted, .symbol], 3), - (1, .symbol, 4), - (22, [.accepted, .symbol], 4), - (1, .symbol, 5), - (22, [.accepted, .symbol], 5), - (1, .symbol, 6), - (22, [.accepted, .symbol], 6), - (1, .symbol, 7), - (22, [.accepted, .symbol], 7), - - /* 226 */ - - (3, .symbol, 254), - (6, .symbol, 254), - (10, .symbol, 254), - (15, .symbol, 254), - (24, .symbol, 254), - (31, .symbol, 254), - (41, .symbol, 254), - (56, [.accepted, .symbol], 254), - (2, .symbol, 2), - (9, .symbol, 2), - (23, .symbol, 2), - (40, [.accepted, .symbol], 2), - (2, .symbol, 3), - (9, .symbol, 3), - (23, .symbol, 3), - (40, [.accepted, .symbol], 3), - - /* 227 */ - - (3, .symbol, 2), - (6, .symbol, 2), - (10, .symbol, 2), - (15, .symbol, 2), - (24, .symbol, 2), - (31, .symbol, 2), - (41, .symbol, 2), - (56, [.accepted, .symbol], 2), - (3, .symbol, 3), - (6, .symbol, 3), - (10, .symbol, 3), - (15, .symbol, 3), - (24, .symbol, 3), - (31, .symbol, 3), - (41, .symbol, 3), - (56, [.accepted, .symbol], 3), - - /* 228 */ - - (2, .symbol, 4), - (9, .symbol, 4), - (23, .symbol, 4), - (40, [.accepted, .symbol], 4), - (2, .symbol, 5), - (9, .symbol, 5), - (23, .symbol, 5), - (40, [.accepted, .symbol], 5), - (2, .symbol, 6), - (9, .symbol, 6), - (23, .symbol, 6), - (40, [.accepted, .symbol], 6), - (2, .symbol, 7), - (9, .symbol, 7), - (23, .symbol, 7), - (40, [.accepted, .symbol], 7), - - /* 229 */ - - (3, .symbol, 4), - (6, .symbol, 4), - (10, .symbol, 4), - (15, .symbol, 4), - (24, .symbol, 4), - (31, .symbol, 4), - (41, .symbol, 4), - (56, [.accepted, .symbol], 4), - (3, .symbol, 5), - (6, .symbol, 5), - (10, .symbol, 5), - (15, .symbol, 5), - (24, .symbol, 5), - (31, .symbol, 5), - (41, .symbol, 5), - (56, [.accepted, .symbol], 5), - - /* 230 */ - - (3, .symbol, 6), - (6, .symbol, 6), - (10, .symbol, 6), - (15, .symbol, 6), - (24, .symbol, 6), - (31, .symbol, 6), - (41, .symbol, 6), - (56, [.accepted, .symbol], 6), - (3, .symbol, 7), - (6, .symbol, 7), - (10, .symbol, 7), - (15, .symbol, 7), - (24, .symbol, 7), - (31, .symbol, 7), - (41, .symbol, 7), - (56, [.accepted, .symbol], 7), - - /* 231 */ - - (1, .symbol, 8), - (22, [.accepted, .symbol], 8), - (1, .symbol, 11), - (22, [.accepted, .symbol], 11), - (1, .symbol, 12), - (22, [.accepted, .symbol], 12), - (1, .symbol, 14), - (22, [.accepted, .symbol], 14), - (1, .symbol, 15), - (22, [.accepted, .symbol], 15), - (1, .symbol, 16), - (22, [.accepted, .symbol], 16), - (1, .symbol, 17), - (22, [.accepted, .symbol], 17), - (1, .symbol, 18), - (22, [.accepted, .symbol], 18), - - /* 232 */ - - (2, .symbol, 8), - (9, .symbol, 8), - (23, .symbol, 8), - (40, [.accepted, .symbol], 8), - (2, .symbol, 11), - (9, .symbol, 11), - (23, .symbol, 11), - (40, [.accepted, .symbol], 11), - (2, .symbol, 12), - (9, .symbol, 12), - (23, .symbol, 12), - (40, [.accepted, .symbol], 12), - (2, .symbol, 14), - (9, .symbol, 14), - (23, .symbol, 14), - (40, [.accepted, .symbol], 14), - - /* 233 */ - - (3, .symbol, 8), - (6, .symbol, 8), - (10, .symbol, 8), - (15, .symbol, 8), - (24, .symbol, 8), - (31, .symbol, 8), - (41, .symbol, 8), - (56, [.accepted, .symbol], 8), - (3, .symbol, 11), - (6, .symbol, 11), - (10, .symbol, 11), - (15, .symbol, 11), - (24, .symbol, 11), - (31, .symbol, 11), - (41, .symbol, 11), - (56, [.accepted, .symbol], 11), - - /* 234 */ - - (3, .symbol, 12), - (6, .symbol, 12), - (10, .symbol, 12), - (15, .symbol, 12), - (24, .symbol, 12), - (31, .symbol, 12), - (41, .symbol, 12), - (56, [.accepted, .symbol], 12), - (3, .symbol, 14), - (6, .symbol, 14), - (10, .symbol, 14), - (15, .symbol, 14), - (24, .symbol, 14), - (31, .symbol, 14), - (41, .symbol, 14), - (56, [.accepted, .symbol], 14), - - /* 235 */ - - (2, .symbol, 15), - (9, .symbol, 15), - (23, .symbol, 15), - (40, [.accepted, .symbol], 15), - (2, .symbol, 16), - (9, .symbol, 16), - (23, .symbol, 16), - (40, [.accepted, .symbol], 16), - (2, .symbol, 17), - (9, .symbol, 17), - (23, .symbol, 17), - (40, [.accepted, .symbol], 17), - (2, .symbol, 18), - (9, .symbol, 18), - (23, .symbol, 18), - (40, [.accepted, .symbol], 18), - - /* 236 */ - - (3, .symbol, 15), - (6, .symbol, 15), - (10, .symbol, 15), - (15, .symbol, 15), - (24, .symbol, 15), - (31, .symbol, 15), - (41, .symbol, 15), - (56, [.accepted, .symbol], 15), - (3, .symbol, 16), - (6, .symbol, 16), - (10, .symbol, 16), - (15, .symbol, 16), - (24, .symbol, 16), - (31, .symbol, 16), - (41, .symbol, 16), - (56, [.accepted, .symbol], 16), - - /* 237 */ - - (3, .symbol, 17), - (6, .symbol, 17), - (10, .symbol, 17), - (15, .symbol, 17), - (24, .symbol, 17), - (31, .symbol, 17), - (41, .symbol, 17), - (56, [.accepted, .symbol], 17), - (3, .symbol, 18), - (6, .symbol, 18), - (10, .symbol, 18), - (15, .symbol, 18), - (24, .symbol, 18), - (31, .symbol, 18), - (41, .symbol, 18), - (56, [.accepted, .symbol], 18), - - /* 238 */ - - (0, [.accepted, .symbol], 19), - (0, [.accepted, .symbol], 20), - (0, [.accepted, .symbol], 21), - (0, [.accepted, .symbol], 23), - (0, [.accepted, .symbol], 24), - (0, [.accepted, .symbol], 25), - (0, [.accepted, .symbol], 26), - (0, [.accepted, .symbol], 27), - (0, [.accepted, .symbol], 28), - (0, [.accepted, .symbol], 29), - (0, [.accepted, .symbol], 30), - (0, [.accepted, .symbol], 31), - (0, [.accepted, .symbol], 127), - (0, [.accepted, .symbol], 220), - (0, [.accepted, .symbol], 249), - (253, .none, 0), - - /* 239 */ - - (1, .symbol, 19), - (22, [.accepted, .symbol], 19), - (1, .symbol, 20), - (22, [.accepted, .symbol], 20), - (1, .symbol, 21), - (22, [.accepted, .symbol], 21), - (1, .symbol, 23), - (22, [.accepted, .symbol], 23), - (1, .symbol, 24), - (22, [.accepted, .symbol], 24), - (1, .symbol, 25), - (22, [.accepted, .symbol], 25), - (1, .symbol, 26), - (22, [.accepted, .symbol], 26), - (1, .symbol, 27), - (22, [.accepted, .symbol], 27), - - /* 240 */ - - (2, .symbol, 19), - (9, .symbol, 19), - (23, .symbol, 19), - (40, [.accepted, .symbol], 19), - (2, .symbol, 20), - (9, .symbol, 20), - (23, .symbol, 20), - (40, [.accepted, .symbol], 20), - (2, .symbol, 21), - (9, .symbol, 21), - (23, .symbol, 21), - (40, [.accepted, .symbol], 21), - (2, .symbol, 23), - (9, .symbol, 23), - (23, .symbol, 23), - (40, [.accepted, .symbol], 23), - - /* 241 */ - - (3, .symbol, 19), - (6, .symbol, 19), - (10, .symbol, 19), - (15, .symbol, 19), - (24, .symbol, 19), - (31, .symbol, 19), - (41, .symbol, 19), - (56, [.accepted, .symbol], 19), - (3, .symbol, 20), - (6, .symbol, 20), - (10, .symbol, 20), - (15, .symbol, 20), - (24, .symbol, 20), - (31, .symbol, 20), - (41, .symbol, 20), - (56, [.accepted, .symbol], 20), - - /* 242 */ - - (3, .symbol, 21), - (6, .symbol, 21), - (10, .symbol, 21), - (15, .symbol, 21), - (24, .symbol, 21), - (31, .symbol, 21), - (41, .symbol, 21), - (56, [.accepted, .symbol], 21), - (3, .symbol, 23), - (6, .symbol, 23), - (10, .symbol, 23), - (15, .symbol, 23), - (24, .symbol, 23), - (31, .symbol, 23), - (41, .symbol, 23), - (56, [.accepted, .symbol], 23), - - /* 243 */ - - (2, .symbol, 24), - (9, .symbol, 24), - (23, .symbol, 24), - (40, [.accepted, .symbol], 24), - (2, .symbol, 25), - (9, .symbol, 25), - (23, .symbol, 25), - (40, [.accepted, .symbol], 25), - (2, .symbol, 26), - (9, .symbol, 26), - (23, .symbol, 26), - (40, [.accepted, .symbol], 26), - (2, .symbol, 27), - (9, .symbol, 27), - (23, .symbol, 27), - (40, [.accepted, .symbol], 27), - - /* 244 */ - - (3, .symbol, 24), - (6, .symbol, 24), - (10, .symbol, 24), - (15, .symbol, 24), - (24, .symbol, 24), - (31, .symbol, 24), - (41, .symbol, 24), - (56, [.accepted, .symbol], 24), - (3, .symbol, 25), - (6, .symbol, 25), - (10, .symbol, 25), - (15, .symbol, 25), - (24, .symbol, 25), - (31, .symbol, 25), - (41, .symbol, 25), - (56, [.accepted, .symbol], 25), - - /* 245 */ - - (3, .symbol, 26), - (6, .symbol, 26), - (10, .symbol, 26), - (15, .symbol, 26), - (24, .symbol, 26), - (31, .symbol, 26), - (41, .symbol, 26), - (56, [.accepted, .symbol], 26), - (3, .symbol, 27), - (6, .symbol, 27), - (10, .symbol, 27), - (15, .symbol, 27), - (24, .symbol, 27), - (31, .symbol, 27), - (41, .symbol, 27), - (56, [.accepted, .symbol], 27), - - /* 246 */ - - (1, .symbol, 28), - (22, [.accepted, .symbol], 28), - (1, .symbol, 29), - (22, [.accepted, .symbol], 29), - (1, .symbol, 30), - (22, [.accepted, .symbol], 30), - (1, .symbol, 31), - (22, [.accepted, .symbol], 31), - (1, .symbol, 127), - (22, [.accepted, .symbol], 127), - (1, .symbol, 220), - (22, [.accepted, .symbol], 220), - (1, .symbol, 249), - (22, [.accepted, .symbol], 249), - (254, .none, 0), - (255, .none, 0), - - /* 247 */ - - (2, .symbol, 28), - (9, .symbol, 28), - (23, .symbol, 28), - (40, [.accepted, .symbol], 28), - (2, .symbol, 29), - (9, .symbol, 29), - (23, .symbol, 29), - (40, [.accepted, .symbol], 29), - (2, .symbol, 30), - (9, .symbol, 30), - (23, .symbol, 30), - (40, [.accepted, .symbol], 30), - (2, .symbol, 31), - (9, .symbol, 31), - (23, .symbol, 31), - (40, [.accepted, .symbol], 31), - - /* 248 */ - - (3, .symbol, 28), - (6, .symbol, 28), - (10, .symbol, 28), - (15, .symbol, 28), - (24, .symbol, 28), - (31, .symbol, 28), - (41, .symbol, 28), - (56, [.accepted, .symbol], 28), - (3, .symbol, 29), - (6, .symbol, 29), - (10, .symbol, 29), - (15, .symbol, 29), - (24, .symbol, 29), - (31, .symbol, 29), - (41, .symbol, 29), - (56, [.accepted, .symbol], 29), - - /* 249 */ - - (3, .symbol, 30), - (6, .symbol, 30), - (10, .symbol, 30), - (15, .symbol, 30), - (24, .symbol, 30), - (31, .symbol, 30), - (41, .symbol, 30), - (56, [.accepted, .symbol], 30), - (3, .symbol, 31), - (6, .symbol, 31), - (10, .symbol, 31), - (15, .symbol, 31), - (24, .symbol, 31), - (31, .symbol, 31), - (41, .symbol, 31), - (56, [.accepted, .symbol], 31), - - /* 250 */ - - (2, .symbol, 127), - (9, .symbol, 127), - (23, .symbol, 127), - (40, [.accepted, .symbol], 127), - (2, .symbol, 220), - (9, .symbol, 220), - (23, .symbol, 220), - (40, [.accepted, .symbol], 220), - (2, .symbol, 249), - (9, .symbol, 249), - (23, .symbol, 249), - (40, [.accepted, .symbol], 249), - (0, [.accepted, .symbol], 10), - (0, [.accepted, .symbol], 13), - (0, [.accepted, .symbol], 22), - (0, .failure, 0), - - /* 251 */ - - (3, .symbol, 127), - (6, .symbol, 127), - (10, .symbol, 127), - (15, .symbol, 127), - (24, .symbol, 127), - (31, .symbol, 127), - (41, .symbol, 127), - (56, [.accepted, .symbol], 127), - (3, .symbol, 220), - (6, .symbol, 220), - (10, .symbol, 220), - (15, .symbol, 220), - (24, .symbol, 220), - (31, .symbol, 220), - (41, .symbol, 220), - (56, [.accepted, .symbol], 220), - - /* 252 */ - - (3, .symbol, 249), - (6, .symbol, 249), - (10, .symbol, 249), - (15, .symbol, 249), - (24, .symbol, 249), - (31, .symbol, 249), - (41, .symbol, 249), - (56, [.accepted, .symbol], 249), - (1, .symbol, 10), - (22, [.accepted, .symbol], 10), - (1, .symbol, 13), - (22, [.accepted, .symbol], 13), - (1, .symbol, 22), - (22, [.accepted, .symbol], 22), - (0, .failure, 0), - (0, .failure, 0), - - /* 253 */ - - (2, .symbol, 10), - (9, .symbol, 10), - (23, .symbol, 10), - (40, [.accepted, .symbol], 10), - (2, .symbol, 13), - (9, .symbol, 13), - (23, .symbol, 13), - (40, [.accepted, .symbol], 13), - (2, .symbol, 22), - (9, .symbol, 22), - (23, .symbol, 22), - (40, [.accepted, .symbol], 22), - (0, .failure, 0), - (0, .failure, 0), - (0, .failure, 0), - (0, .failure, 0), - - /* 254 */ - - (3, .symbol, 10), - (6, .symbol, 10), - (10, .symbol, 10), - (15, .symbol, 10), - (24, .symbol, 10), - (31, .symbol, 10), - (41, .symbol, 10), - (56, [.accepted, .symbol], 10), - (3, .symbol, 13), - (6, .symbol, 13), - (10, .symbol, 13), - (15, .symbol, 13), - (24, .symbol, 13), - (31, .symbol, 13), - (41, .symbol, 13), - (56, [.accepted, .symbol], 13), - - /* 255 */ - - (3, .symbol, 22), - (6, .symbol, 22), - (10, .symbol, 22), - (15, .symbol, 22), - (24, .symbol, 22), - (31, .symbol, 22), - (41, .symbol, 22), - (56, [.accepted, .symbol], 22), - (0, .failure, 0), - (0, .failure, 0), - (0, .failure, 0), - (0, .failure, 0), - (0, .failure, 0), - (0, .failure, 0), - (0, .failure, 0), - (0, .failure, 0), - ] - */ + // + // private static let rawTable: [HuffmanDecodeEntry] = [ + // + // // 0 + // + // (4, .none, 0), + // (5, .none, 0), + // (7, .none, 0), + // (8, .none, 0), + // (11, .none, 0), + // (12, .none, 0), + // (16, .none, 0), + // (19, .none, 0), + // (25, .none, 0), + // (28, .none, 0), + // (32, .none, 0), + // (35, .none, 0), + // (42, .none, 0), + // (49, .none, 0), + // (57, .none, 0), + // (64, .accepted, 0), + // + // // 1 + // + // (0, [.accepted, .symbol], 48), + // (0, [.accepted, .symbol], 49), + // (0, [.accepted, .symbol], 50), + // (0, [.accepted, .symbol], 97), + // (0, [.accepted, .symbol], 99), + // (0, [.accepted, .symbol], 101), + // (0, [.accepted, .symbol], 105), + // (0, [.accepted, .symbol], 111), + // (0, [.accepted, .symbol], 115), + // (0, [.accepted, .symbol], 116), + // (13, .none, 0), + // (14, .none, 0), + // (17, .none, 0), + // (18, .none, 0), + // (20, .none, 0), + // (21, .none, 0), + // + // // 2 + // + // (1, .symbol, 48), + // (22, [.accepted, .symbol], 48), + // (1, .symbol, 49), + // (22, [.accepted, .symbol], 49), + // (1, .symbol, 50), + // (22, [.accepted, .symbol], 50), + // (1, .symbol, 97), + // (22, [.accepted, .symbol], 97), + // (1, .symbol, 99), + // (22, [.accepted, .symbol], 99), + // (1, .symbol, 101), + // (22, [.accepted, .symbol], 101), + // (1, .symbol, 105), + // (22, [.accepted, .symbol], 105), + // (1, .symbol, 111), + // (22, [.accepted, .symbol], 111), + // + // // 3 + // + // (2, .symbol, 48), + // (9, .symbol, 48), + // (23, .symbol, 48), + // (40, [.accepted, .symbol], 48), + // (2, .symbol, 49), + // (9, .symbol, 49), + // (23, .symbol, 49), + // (40, [.accepted, .symbol], 49), + // (2, .symbol, 50), + // (9, .symbol, 50), + // (23, .symbol, 50), + // (40, [.accepted, .symbol], 50), + // (2, .symbol, 97), + // (9, .symbol, 97), + // (23, .symbol, 97), + // (40, [.accepted, .symbol], 97), + // + // // 4 + // + // (3, .symbol, 48), + // (6, .symbol, 48), + // (10, .symbol, 48), + // (15, .symbol, 48), + // (24, .symbol, 48), + // (31, .symbol, 48), + // (41, .symbol, 48), + // (56, [.accepted, .symbol], 48), + // (3, .symbol, 49), + // (6, .symbol, 49), + // (10, .symbol, 49), + // (15, .symbol, 49), + // (24, .symbol, 49), + // (31, .symbol, 49), + // (41, .symbol, 49), + // (56, [.accepted, .symbol], 49), + // + // // 5 + // + // (3, .symbol, 50), + // (6, .symbol, 50), + // (10, .symbol, 50), + // (15, .symbol, 50), + // (24, .symbol, 50), + // (31, .symbol, 50), + // (41, .symbol, 50), + // (56, [.accepted, .symbol], 50), + // (3, .symbol, 97), + // (6, .symbol, 97), + // (10, .symbol, 97), + // (15, .symbol, 97), + // (24, .symbol, 97), + // (31, .symbol, 97), + // (41, .symbol, 97), + // (56, [.accepted, .symbol], 97), + // + // // 6 + // + // (2, .symbol, 99), + // (9, .symbol, 99), + // (23, .symbol, 99), + // (40, [.accepted, .symbol], 99), + // (2, .symbol, 101), + // (9, .symbol, 101), + // (23, .symbol, 101), + // (40, [.accepted, .symbol], 101), + // (2, .symbol, 105), + // (9, .symbol, 105), + // (23, .symbol, 105), + // (40, [.accepted, .symbol], 105), + // (2, .symbol, 111), + // (9, .symbol, 111), + // (23, .symbol, 111), + // (40, [.accepted, .symbol], 111), + // + // // 7 + // + // (3, .symbol, 99), + // (6, .symbol, 99), + // (10, .symbol, 99), + // (15, .symbol, 99), + // (24, .symbol, 99), + // (31, .symbol, 99), + // (41, .symbol, 99), + // (56, [.accepted, .symbol], 99), + // (3, .symbol, 101), + // (6, .symbol, 101), + // (10, .symbol, 101), + // (15, .symbol, 101), + // (24, .symbol, 101), + // (31, .symbol, 101), + // (41, .symbol, 101), + // (56, [.accepted, .symbol], 101), + // + // // 8 + // + // (3, .symbol, 105), + // (6, .symbol, 105), + // (10, .symbol, 105), + // (15, .symbol, 105), + // (24, .symbol, 105), + // (31, .symbol, 105), + // (41, .symbol, 105), + // (56, [.accepted, .symbol], 105), + // (3, .symbol, 111), + // (6, .symbol, 111), + // (10, .symbol, 111), + // (15, .symbol, 111), + // (24, .symbol, 111), + // (31, .symbol, 111), + // (41, .symbol, 111), + // (56, [.accepted, .symbol], 111), + // + // // 9 + // + // (1, .symbol, 115), + // (22, [.accepted, .symbol], 115), + // (1, .symbol, 116), + // (22, [.accepted, .symbol], 116), + // (0, [.accepted, .symbol], 32), + // (0, [.accepted, .symbol], 37), + // (0, [.accepted, .symbol], 45), + // (0, [.accepted, .symbol], 46), + // (0, [.accepted, .symbol], 47), + // (0, [.accepted, .symbol], 51), + // (0, [.accepted, .symbol], 52), + // (0, [.accepted, .symbol], 53), + // (0, [.accepted, .symbol], 54), + // (0, [.accepted, .symbol], 55), + // (0, [.accepted, .symbol], 56), + // (0, [.accepted, .symbol], 57), + // + // // 10 + // + // (2, .symbol, 115), + // (9, .symbol, 115), + // (23, .symbol, 115), + // (40, [.accepted, .symbol], 115), + // (2, .symbol, 116), + // (9, .symbol, 116), + // (23, .symbol, 116), + // (40, [.accepted, .symbol], 116), + // (1, .symbol, 32), + // (22, [.accepted, .symbol], 32), + // (1, .symbol, 37), + // (22, [.accepted, .symbol], 37), + // (1, .symbol, 45), + // (22, [.accepted, .symbol], 45), + // (1, .symbol, 46), + // (22, [.accepted, .symbol], 46), + // + // // 11 + // + // (3, .symbol, 115), + // (6, .symbol, 115), + // (10, .symbol, 115), + // (15, .symbol, 115), + // (24, .symbol, 115), + // (31, .symbol, 115), + // (41, .symbol, 115), + // (56, [.accepted, .symbol], 115), + // (3, .symbol, 116), + // (6, .symbol, 116), + // (10, .symbol, 116), + // (15, .symbol, 116), + // (24, .symbol, 116), + // (31, .symbol, 116), + // (41, .symbol, 116), + // (56, [.accepted, .symbol], 116), + // + // // 12 + // + // (2, .symbol, 32), + // (9, .symbol, 32), + // (23, .symbol, 32), + // (40, [.accepted, .symbol], 32), + // (2, .symbol, 37), + // (9, .symbol, 37), + // (23, .symbol, 37), + // (40, [.accepted, .symbol], 37), + // (2, .symbol, 45), + // (9, .symbol, 45), + // (23, .symbol, 45), + // (40, [.accepted, .symbol], 45), + // (2, .symbol, 46), + // (9, .symbol, 46), + // (23, .symbol, 46), + // (40, [.accepted, .symbol], 46), + // + // // 13 + // + // (3, .symbol, 32), + // (6, .symbol, 32), + // (10, .symbol, 32), + // (15, .symbol, 32), + // (24, .symbol, 32), + // (31, .symbol, 32), + // (41, .symbol, 32), + // (56, [.accepted, .symbol], 32), + // (3, .symbol, 37), + // (6, .symbol, 37), + // (10, .symbol, 37), + // (15, .symbol, 37), + // (24, .symbol, 37), + // (31, .symbol, 37), + // (41, .symbol, 37), + // (56, [.accepted, .symbol], 37), + // + // // 14 + // + // (3, .symbol, 45), + // (6, .symbol, 45), + // (10, .symbol, 45), + // (15, .symbol, 45), + // (24, .symbol, 45), + // (31, .symbol, 45), + // (41, .symbol, 45), + // (56, [.accepted, .symbol], 45), + // (3, .symbol, 46), + // (6, .symbol, 46), + // (10, .symbol, 46), + // (15, .symbol, 46), + // (24, .symbol, 46), + // (31, .symbol, 46), + // (41, .symbol, 46), + // (56, [.accepted, .symbol], 46), + // + // // 15 + // + // (1, .symbol, 47), + // (22, [.accepted, .symbol], 47), + // (1, .symbol, 51), + // (22, [.accepted, .symbol], 51), + // (1, .symbol, 52), + // (22, [.accepted, .symbol], 52), + // (1, .symbol, 53), + // (22, [.accepted, .symbol], 53), + // (1, .symbol, 54), + // (22, [.accepted, .symbol], 54), + // (1, .symbol, 55), + // (22, [.accepted, .symbol], 55), + // (1, .symbol, 56), + // (22, [.accepted, .symbol], 56), + // (1, .symbol, 57), + // (22, [.accepted, .symbol], 57), + // + // // 16 + // + // (2, .symbol, 47), + // (9, .symbol, 47), + // (23, .symbol, 47), + // (40, [.accepted, .symbol], 47), + // (2, .symbol, 51), + // (9, .symbol, 51), + // (23, .symbol, 51), + // (40, [.accepted, .symbol], 51), + // (2, .symbol, 52), + // (9, .symbol, 52), + // (23, .symbol, 52), + // (40, [.accepted, .symbol], 52), + // (2, .symbol, 53), + // (9, .symbol, 53), + // (23, .symbol, 53), + // (40, [.accepted, .symbol], 53), + // + // // 17 + // + // (3, .symbol, 47), + // (6, .symbol, 47), + // (10, .symbol, 47), + // (15, .symbol, 47), + // (24, .symbol, 47), + // (31, .symbol, 47), + // (41, .symbol, 47), + // (56, [.accepted, .symbol], 47), + // (3, .symbol, 51), + // (6, .symbol, 51), + // (10, .symbol, 51), + // (15, .symbol, 51), + // (24, .symbol, 51), + // (31, .symbol, 51), + // (41, .symbol, 51), + // (56, [.accepted, .symbol], 51), + // + // // 18 + // + // (3, .symbol, 52), + // (6, .symbol, 52), + // (10, .symbol, 52), + // (15, .symbol, 52), + // (24, .symbol, 52), + // (31, .symbol, 52), + // (41, .symbol, 52), + // (56, [.accepted, .symbol], 52), + // (3, .symbol, 53), + // (6, .symbol, 53), + // (10, .symbol, 53), + // (15, .symbol, 53), + // (24, .symbol, 53), + // (31, .symbol, 53), + // (41, .symbol, 53), + // (56, [.accepted, .symbol], 53), + // + // // 19 + // + // (2, .symbol, 54), + // (9, .symbol, 54), + // (23, .symbol, 54), + // (40, [.accepted, .symbol], 54), + // (2, .symbol, 55), + // (9, .symbol, 55), + // (23, .symbol, 55), + // (40, [.accepted, .symbol], 55), + // (2, .symbol, 56), + // (9, .symbol, 56), + // (23, .symbol, 56), + // (40, [.accepted, .symbol], 56), + // (2, .symbol, 57), + // (9, .symbol, 57), + // (23, .symbol, 57), + // (40, [.accepted, .symbol], 57), + // + // // 20 + // + // (3, .symbol, 54), + // (6, .symbol, 54), + // (10, .symbol, 54), + // (15, .symbol, 54), + // (24, .symbol, 54), + // (31, .symbol, 54), + // (41, .symbol, 54), + // (56, [.accepted, .symbol], 54), + // (3, .symbol, 55), + // (6, .symbol, 55), + // (10, .symbol, 55), + // (15, .symbol, 55), + // (24, .symbol, 55), + // (31, .symbol, 55), + // (41, .symbol, 55), + // (56, [.accepted, .symbol], 55), + // + // // 21 + // + // (3, .symbol, 56), + // (6, .symbol, 56), + // (10, .symbol, 56), + // (15, .symbol, 56), + // (24, .symbol, 56), + // (31, .symbol, 56), + // (41, .symbol, 56), + // (56, [.accepted, .symbol], 56), + // (3, .symbol, 57), + // (6, .symbol, 57), + // (10, .symbol, 57), + // (15, .symbol, 57), + // (24, .symbol, 57), + // (31, .symbol, 57), + // (41, .symbol, 57), + // (56, [.accepted, .symbol], 57), + // + // // 22 + // + // (26, .none, 0), + // (27, .none, 0), + // (29, .none, 0), + // (30, .none, 0), + // (33, .none, 0), + // (34, .none, 0), + // (36, .none, 0), + // (37, .none, 0), + // (43, .none, 0), + // (46, .none, 0), + // (50, .none, 0), + // (53, .none, 0), + // (58, .none, 0), + // (61, .none, 0), + // (65, .none, 0), + // (68, .accepted, 0), + // + // // 23 + // + // (0, [.accepted, .symbol], 61), + // (0, [.accepted, .symbol], 65), + // (0, [.accepted, .symbol], 95), + // (0, [.accepted, .symbol], 98), + // (0, [.accepted, .symbol], 100), + // (0, [.accepted, .symbol], 102), + // (0, [.accepted, .symbol], 103), + // (0, [.accepted, .symbol], 104), + // (0, [.accepted, .symbol], 108), + // (0, [.accepted, .symbol], 109), + // (0, [.accepted, .symbol], 110), + // (0, [.accepted, .symbol], 112), + // (0, [.accepted, .symbol], 114), + // (0, [.accepted, .symbol], 117), + // (38, .none, 0), + // (39, .none, 0), + // + // // 24 + // + // (1, .symbol, 61), + // (22, [.accepted, .symbol], 61), + // (1, .symbol, 65), + // (22, [.accepted, .symbol], 65), + // (1, .symbol, 95), + // (22, [.accepted, .symbol], 95), + // (1, .symbol, 98), + // (22, [.accepted, .symbol], 98), + // (1, .symbol, 100), + // (22, [.accepted, .symbol], 100), + // (1, .symbol, 102), + // (22, [.accepted, .symbol], 102), + // (1, .symbol, 103), + // (22, [.accepted, .symbol], 103), + // (1, .symbol, 104), + // (22, [.accepted, .symbol], 104), + // + // // 25 + // + // (2, .symbol, 61), + // (9, .symbol, 61), + // (23, .symbol, 61), + // (40, [.accepted, .symbol], 61), + // (2, .symbol, 65), + // (9, .symbol, 65), + // (23, .symbol, 65), + // (40, [.accepted, .symbol], 65), + // (2, .symbol, 95), + // (9, .symbol, 95), + // (23, .symbol, 95), + // (40, [.accepted, .symbol], 95), + // (2, .symbol, 98), + // (9, .symbol, 98), + // (23, .symbol, 98), + // (40, [.accepted, .symbol], 98), + // + // // 26 + // + // (3, .symbol, 61), + // (6, .symbol, 61), + // (10, .symbol, 61), + // (15, .symbol, 61), + // (24, .symbol, 61), + // (31, .symbol, 61), + // (41, .symbol, 61), + // (56, [.accepted, .symbol], 61), + // (3, .symbol, 65), + // (6, .symbol, 65), + // (10, .symbol, 65), + // (15, .symbol, 65), + // (24, .symbol, 65), + // (31, .symbol, 65), + // (41, .symbol, 65), + // (56, [.accepted, .symbol], 65), + // + // // 27 + // + // (3, .symbol, 95), + // (6, .symbol, 95), + // (10, .symbol, 95), + // (15, .symbol, 95), + // (24, .symbol, 95), + // (31, .symbol, 95), + // (41, .symbol, 95), + // (56, [.accepted, .symbol], 95), + // (3, .symbol, 98), + // (6, .symbol, 98), + // (10, .symbol, 98), + // (15, .symbol, 98), + // (24, .symbol, 98), + // (31, .symbol, 98), + // (41, .symbol, 98), + // (56, [.accepted, .symbol], 98), + // + // // 28 + // + // (2, .symbol, 100), + // (9, .symbol, 100), + // (23, .symbol, 100), + // (40, [.accepted, .symbol], 100), + // (2, .symbol, 102), + // (9, .symbol, 102), + // (23, .symbol, 102), + // (40, [.accepted, .symbol], 102), + // (2, .symbol, 103), + // (9, .symbol, 103), + // (23, .symbol, 103), + // (40, [.accepted, .symbol], 103), + // (2, .symbol, 104), + // (9, .symbol, 104), + // (23, .symbol, 104), + // (40, [.accepted, .symbol], 104), + // + // // 29 + // + // (3, .symbol, 100), + // (6, .symbol, 100), + // (10, .symbol, 100), + // (15, .symbol, 100), + // (24, .symbol, 100), + // (31, .symbol, 100), + // (41, .symbol, 100), + // (56, [.accepted, .symbol], 100), + // (3, .symbol, 102), + // (6, .symbol, 102), + // (10, .symbol, 102), + // (15, .symbol, 102), + // (24, .symbol, 102), + // (31, .symbol, 102), + // (41, .symbol, 102), + // (56, [.accepted, .symbol], 102), + // + // // 30 + // + // (3, .symbol, 103), + // (6, .symbol, 103), + // (10, .symbol, 103), + // (15, .symbol, 103), + // (24, .symbol, 103), + // (31, .symbol, 103), + // (41, .symbol, 103), + // (56, [.accepted, .symbol], 103), + // (3, .symbol, 104), + // (6, .symbol, 104), + // (10, .symbol, 104), + // (15, .symbol, 104), + // (24, .symbol, 104), + // (31, .symbol, 104), + // (41, .symbol, 104), + // (56, [.accepted, .symbol], 104), + // + // // 31 + // + // (1, .symbol, 108), + // (22, [.accepted, .symbol], 108), + // (1, .symbol, 109), + // (22, [.accepted, .symbol], 109), + // (1, .symbol, 110), + // (22, [.accepted, .symbol], 110), + // (1, .symbol, 112), + // (22, [.accepted, .symbol], 112), + // (1, .symbol, 114), + // (22, [.accepted, .symbol], 114), + // (1, .symbol, 117), + // (22, [.accepted, .symbol], 117), + // (0, [.accepted, .symbol], 58), + // (0, [.accepted, .symbol], 66), + // (0, [.accepted, .symbol], 67), + // (0, [.accepted, .symbol], 68), + // + // // 32 + // + // (2, .symbol, 108), + // (9, .symbol, 108), + // (23, .symbol, 108), + // (40, [.accepted, .symbol], 108), + // (2, .symbol, 109), + // (9, .symbol, 109), + // (23, .symbol, 109), + // (40, [.accepted, .symbol], 109), + // (2, .symbol, 110), + // (9, .symbol, 110), + // (23, .symbol, 110), + // (40, [.accepted, .symbol], 110), + // (2, .symbol, 112), + // (9, .symbol, 112), + // (23, .symbol, 112), + // (40, [.accepted, .symbol], 112), + // + // // 33 + // + // (3, .symbol, 108), + // (6, .symbol, 108), + // (10, .symbol, 108), + // (15, .symbol, 108), + // (24, .symbol, 108), + // (31, .symbol, 108), + // (41, .symbol, 108), + // (56, [.accepted, .symbol], 108), + // (3, .symbol, 109), + // (6, .symbol, 109), + // (10, .symbol, 109), + // (15, .symbol, 109), + // (24, .symbol, 109), + // (31, .symbol, 109), + // (41, .symbol, 109), + // (56, [.accepted, .symbol], 109), + // + // // 34 + // + // (3, .symbol, 110), + // (6, .symbol, 110), + // (10, .symbol, 110), + // (15, .symbol, 110), + // (24, .symbol, 110), + // (31, .symbol, 110), + // (41, .symbol, 110), + // (56, [.accepted, .symbol], 110), + // (3, .symbol, 112), + // (6, .symbol, 112), + // (10, .symbol, 112), + // (15, .symbol, 112), + // (24, .symbol, 112), + // (31, .symbol, 112), + // (41, .symbol, 112), + // (56, [.accepted, .symbol], 112), + // + // // 35 + // + // (2, .symbol, 114), + // (9, .symbol, 114), + // (23, .symbol, 114), + // (40, [.accepted, .symbol], 114), + // (2, .symbol, 117), + // (9, .symbol, 117), + // (23, .symbol, 117), + // (40, [.accepted, .symbol], 117), + // (1, .symbol, 58), + // (22, [.accepted, .symbol], 58), + // (1, .symbol, 66), + // (22, [.accepted, .symbol], 66), + // (1, .symbol, 67), + // (22, [.accepted, .symbol], 67), + // (1, .symbol, 68), + // (22, [.accepted, .symbol], 68), + // + // // 36 + // + // (3, .symbol, 114), + // (6, .symbol, 114), + // (10, .symbol, 114), + // (15, .symbol, 114), + // (24, .symbol, 114), + // (31, .symbol, 114), + // (41, .symbol, 114), + // (56, [.accepted, .symbol], 114), + // (3, .symbol, 117), + // (6, .symbol, 117), + // (10, .symbol, 117), + // (15, .symbol, 117), + // (24, .symbol, 117), + // (31, .symbol, 117), + // (41, .symbol, 117), + // (56, [.accepted, .symbol], 117), + // + // // 37 + // + // (2, .symbol, 58), + // (9, .symbol, 58), + // (23, .symbol, 58), + // (40, [.accepted, .symbol], 58), + // (2, .symbol, 66), + // (9, .symbol, 66), + // (23, .symbol, 66), + // (40, [.accepted, .symbol], 66), + // (2, .symbol, 67), + // (9, .symbol, 67), + // (23, .symbol, 67), + // (40, [.accepted, .symbol], 67), + // (2, .symbol, 68), + // (9, .symbol, 68), + // (23, .symbol, 68), + // (40, [.accepted, .symbol], 68), + // + // // 38 + // + // (3, .symbol, 58), + // (6, .symbol, 58), + // (10, .symbol, 58), + // (15, .symbol, 58), + // (24, .symbol, 58), + // (31, .symbol, 58), + // (41, .symbol, 58), + // (56, [.accepted, .symbol], 58), + // (3, .symbol, 66), + // (6, .symbol, 66), + // (10, .symbol, 66), + // (15, .symbol, 66), + // (24, .symbol, 66), + // (31, .symbol, 66), + // (41, .symbol, 66), + // (56, [.accepted, .symbol], 66), + // + // // 39 + // + // (3, .symbol, 67), + // (6, .symbol, 67), + // (10, .symbol, 67), + // (15, .symbol, 67), + // (24, .symbol, 67), + // (31, .symbol, 67), + // (41, .symbol, 67), + // (56, [.accepted, .symbol], 67), + // (3, .symbol, 68), + // (6, .symbol, 68), + // (10, .symbol, 68), + // (15, .symbol, 68), + // (24, .symbol, 68), + // (31, .symbol, 68), + // (41, .symbol, 68), + // (56, [.accepted, .symbol], 68), + // + // // 40 + // + // (44, .none, 0), + // (45, .none, 0), + // (47, .none, 0), + // (48, .none, 0), + // (51, .none, 0), + // (52, .none, 0), + // (54, .none, 0), + // (55, .none, 0), + // (59, .none, 0), + // (60, .none, 0), + // (62, .none, 0), + // (63, .none, 0), + // (66, .none, 0), + // (67, .none, 0), + // (69, .none, 0), + // (72, .accepted, 0), + // + // // 41 + // + // (0, [.accepted, .symbol], 69), + // (0, [.accepted, .symbol], 70), + // (0, [.accepted, .symbol], 71), + // (0, [.accepted, .symbol], 72), + // (0, [.accepted, .symbol], 73), + // (0, [.accepted, .symbol], 74), + // (0, [.accepted, .symbol], 75), + // (0, [.accepted, .symbol], 76), + // (0, [.accepted, .symbol], 77), + // (0, [.accepted, .symbol], 78), + // (0, [.accepted, .symbol], 79), + // (0, [.accepted, .symbol], 80), + // (0, [.accepted, .symbol], 81), + // (0, [.accepted, .symbol], 82), + // (0, [.accepted, .symbol], 83), + // (0, [.accepted, .symbol], 84), + // + // // 42 + // + // (1, .symbol, 69), + // (22, [.accepted, .symbol], 69), + // (1, .symbol, 70), + // (22, [.accepted, .symbol], 70), + // (1, .symbol, 71), + // (22, [.accepted, .symbol], 71), + // (1, .symbol, 72), + // (22, [.accepted, .symbol], 72), + // (1, .symbol, 73), + // (22, [.accepted, .symbol], 73), + // (1, .symbol, 74), + // (22, [.accepted, .symbol], 74), + // (1, .symbol, 75), + // (22, [.accepted, .symbol], 75), + // (1, .symbol, 76), + // (22, [.accepted, .symbol], 76), + // + // // 43 + // + // (2, .symbol, 69), + // (9, .symbol, 69), + // (23, .symbol, 69), + // (40, [.accepted, .symbol], 69), + // (2, .symbol, 70), + // (9, .symbol, 70), + // (23, .symbol, 70), + // (40, [.accepted, .symbol], 70), + // (2, .symbol, 71), + // (9, .symbol, 71), + // (23, .symbol, 71), + // (40, [.accepted, .symbol], 71), + // (2, .symbol, 72), + // (9, .symbol, 72), + // (23, .symbol, 72), + // (40, [.accepted, .symbol], 72), + // + // // 44 + // + // (3, .symbol, 69), + // (6, .symbol, 69), + // (10, .symbol, 69), + // (15, .symbol, 69), + // (24, .symbol, 69), + // (31, .symbol, 69), + // (41, .symbol, 69), + // (56, [.accepted, .symbol], 69), + // (3, .symbol, 70), + // (6, .symbol, 70), + // (10, .symbol, 70), + // (15, .symbol, 70), + // (24, .symbol, 70), + // (31, .symbol, 70), + // (41, .symbol, 70), + // (56, [.accepted, .symbol], 70), + // + // // 45 + // + // (3, .symbol, 71), + // (6, .symbol, 71), + // (10, .symbol, 71), + // (15, .symbol, 71), + // (24, .symbol, 71), + // (31, .symbol, 71), + // (41, .symbol, 71), + // (56, [.accepted, .symbol], 71), + // (3, .symbol, 72), + // (6, .symbol, 72), + // (10, .symbol, 72), + // (15, .symbol, 72), + // (24, .symbol, 72), + // (31, .symbol, 72), + // (41, .symbol, 72), + // (56, [.accepted, .symbol], 72), + // + // // 46 + // + // (2, .symbol, 73), + // (9, .symbol, 73), + // (23, .symbol, 73), + // (40, [.accepted, .symbol], 73), + // (2, .symbol, 74), + // (9, .symbol, 74), + // (23, .symbol, 74), + // (40, [.accepted, .symbol], 74), + // (2, .symbol, 75), + // (9, .symbol, 75), + // (23, .symbol, 75), + // (40, [.accepted, .symbol], 75), + // (2, .symbol, 76), + // (9, .symbol, 76), + // (23, .symbol, 76), + // (40, [.accepted, .symbol], 76), + // + // // 47 + // + // (3, .symbol, 73), + // (6, .symbol, 73), + // (10, .symbol, 73), + // (15, .symbol, 73), + // (24, .symbol, 73), + // (31, .symbol, 73), + // (41, .symbol, 73), + // (56, [.accepted, .symbol], 73), + // (3, .symbol, 74), + // (6, .symbol, 74), + // (10, .symbol, 74), + // (15, .symbol, 74), + // (24, .symbol, 74), + // (31, .symbol, 74), + // (41, .symbol, 74), + // (56, [.accepted, .symbol], 74), + // + // // 48 + // + // (3, .symbol, 75), + // (6, .symbol, 75), + // (10, .symbol, 75), + // (15, .symbol, 75), + // (24, .symbol, 75), + // (31, .symbol, 75), + // (41, .symbol, 75), + // (56, [.accepted, .symbol], 75), + // (3, .symbol, 76), + // (6, .symbol, 76), + // (10, .symbol, 76), + // (15, .symbol, 76), + // (24, .symbol, 76), + // (31, .symbol, 76), + // (41, .symbol, 76), + // (56, [.accepted, .symbol], 76), + // + // // 49 + // + // (1, .symbol, 77), + // (22, [.accepted, .symbol], 77), + // (1, .symbol, 78), + // (22, [.accepted, .symbol], 78), + // (1, .symbol, 79), + // (22, [.accepted, .symbol], 79), + // (1, .symbol, 80), + // (22, [.accepted, .symbol], 80), + // (1, .symbol, 81), + // (22, [.accepted, .symbol], 81), + // (1, .symbol, 82), + // (22, [.accepted, .symbol], 82), + // (1, .symbol, 83), + // (22, [.accepted, .symbol], 83), + // (1, .symbol, 84), + // (22, [.accepted, .symbol], 84), + // + // // 50 + // + // (2, .symbol, 77), + // (9, .symbol, 77), + // (23, .symbol, 77), + // (40, [.accepted, .symbol], 77), + // (2, .symbol, 78), + // (9, .symbol, 78), + // (23, .symbol, 78), + // (40, [.accepted, .symbol], 78), + // (2, .symbol, 79), + // (9, .symbol, 79), + // (23, .symbol, 79), + // (40, [.accepted, .symbol], 79), + // (2, .symbol, 80), + // (9, .symbol, 80), + // (23, .symbol, 80), + // (40, [.accepted, .symbol], 80), + // + // // 51 + // + // (3, .symbol, 77), + // (6, .symbol, 77), + // (10, .symbol, 77), + // (15, .symbol, 77), + // (24, .symbol, 77), + // (31, .symbol, 77), + // (41, .symbol, 77), + // (56, [.accepted, .symbol], 77), + // (3, .symbol, 78), + // (6, .symbol, 78), + // (10, .symbol, 78), + // (15, .symbol, 78), + // (24, .symbol, 78), + // (31, .symbol, 78), + // (41, .symbol, 78), + // (56, [.accepted, .symbol], 78), + // + // // 52 + // + // (3, .symbol, 79), + // (6, .symbol, 79), + // (10, .symbol, 79), + // (15, .symbol, 79), + // (24, .symbol, 79), + // (31, .symbol, 79), + // (41, .symbol, 79), + // (56, [.accepted, .symbol], 79), + // (3, .symbol, 80), + // (6, .symbol, 80), + // (10, .symbol, 80), + // (15, .symbol, 80), + // (24, .symbol, 80), + // (31, .symbol, 80), + // (41, .symbol, 80), + // (56, [.accepted, .symbol], 80), + // + // // 53 + // + // (2, .symbol, 81), + // (9, .symbol, 81), + // (23, .symbol, 81), + // (40, [.accepted, .symbol], 81), + // (2, .symbol, 82), + // (9, .symbol, 82), + // (23, .symbol, 82), + // (40, [.accepted, .symbol], 82), + // (2, .symbol, 83), + // (9, .symbol, 83), + // (23, .symbol, 83), + // (40, [.accepted, .symbol], 83), + // (2, .symbol, 84), + // (9, .symbol, 84), + // (23, .symbol, 84), + // (40, [.accepted, .symbol], 84), + // + // // 54 + // + // (3, .symbol, 81), + // (6, .symbol, 81), + // (10, .symbol, 81), + // (15, .symbol, 81), + // (24, .symbol, 81), + // (31, .symbol, 81), + // (41, .symbol, 81), + // (56, [.accepted, .symbol], 81), + // (3, .symbol, 82), + // (6, .symbol, 82), + // (10, .symbol, 82), + // (15, .symbol, 82), + // (24, .symbol, 82), + // (31, .symbol, 82), + // (41, .symbol, 82), + // (56, [.accepted, .symbol], 82), + // + // // 55 + // + // (3, .symbol, 83), + // (6, .symbol, 83), + // (10, .symbol, 83), + // (15, .symbol, 83), + // (24, .symbol, 83), + // (31, .symbol, 83), + // (41, .symbol, 83), + // (56, [.accepted, .symbol], 83), + // (3, .symbol, 84), + // (6, .symbol, 84), + // (10, .symbol, 84), + // (15, .symbol, 84), + // (24, .symbol, 84), + // (31, .symbol, 84), + // (41, .symbol, 84), + // (56, [.accepted, .symbol], 84), + // + // // 56 + // + // (0, [.accepted, .symbol], 85), + // (0, [.accepted, .symbol], 86), + // (0, [.accepted, .symbol], 87), + // (0, [.accepted, .symbol], 89), + // (0, [.accepted, .symbol], 106), + // (0, [.accepted, .symbol], 107), + // (0, [.accepted, .symbol], 113), + // (0, [.accepted, .symbol], 118), + // (0, [.accepted, .symbol], 119), + // (0, [.accepted, .symbol], 120), + // (0, [.accepted, .symbol], 121), + // (0, [.accepted, .symbol], 122), + // (70, .none, 0), + // (71, .none, 0), + // (73, .none, 0), + // (74, .accepted, 0), + // + // // 57 + // + // (1, .symbol, 85), + // (22, [.accepted, .symbol], 85), + // (1, .symbol, 86), + // (22, [.accepted, .symbol], 86), + // (1, .symbol, 87), + // (22, [.accepted, .symbol], 87), + // (1, .symbol, 89), + // (22, [.accepted, .symbol], 89), + // (1, .symbol, 106), + // (22, [.accepted, .symbol], 106), + // (1, .symbol, 107), + // (22, [.accepted, .symbol], 107), + // (1, .symbol, 113), + // (22, [.accepted, .symbol], 113), + // (1, .symbol, 118), + // (22, [.accepted, .symbol], 118), + // + // // 58 + // + // (2, .symbol, 85), + // (9, .symbol, 85), + // (23, .symbol, 85), + // (40, [.accepted, .symbol], 85), + // (2, .symbol, 86), + // (9, .symbol, 86), + // (23, .symbol, 86), + // (40, [.accepted, .symbol], 86), + // (2, .symbol, 87), + // (9, .symbol, 87), + // (23, .symbol, 87), + // (40, [.accepted, .symbol], 87), + // (2, .symbol, 89), + // (9, .symbol, 89), + // (23, .symbol, 89), + // (40, [.accepted, .symbol], 89), + // + // // 59 + // + // (3, .symbol, 85), + // (6, .symbol, 85), + // (10, .symbol, 85), + // (15, .symbol, 85), + // (24, .symbol, 85), + // (31, .symbol, 85), + // (41, .symbol, 85), + // (56, [.accepted, .symbol], 85), + // (3, .symbol, 86), + // (6, .symbol, 86), + // (10, .symbol, 86), + // (15, .symbol, 86), + // (24, .symbol, 86), + // (31, .symbol, 86), + // (41, .symbol, 86), + // (56, [.accepted, .symbol], 86), + // + // // 60 + // + // (3, .symbol, 87), + // (6, .symbol, 87), + // (10, .symbol, 87), + // (15, .symbol, 87), + // (24, .symbol, 87), + // (31, .symbol, 87), + // (41, .symbol, 87), + // (56, [.accepted, .symbol], 87), + // (3, .symbol, 89), + // (6, .symbol, 89), + // (10, .symbol, 89), + // (15, .symbol, 89), + // (24, .symbol, 89), + // (31, .symbol, 89), + // (41, .symbol, 89), + // (56, [.accepted, .symbol], 89), + // + // // 61 + // + // (2, .symbol, 106), + // (9, .symbol, 106), + // (23, .symbol, 106), + // (40, [.accepted, .symbol], 106), + // (2, .symbol, 107), + // (9, .symbol, 107), + // (23, .symbol, 107), + // (40, [.accepted, .symbol], 107), + // (2, .symbol, 113), + // (9, .symbol, 113), + // (23, .symbol, 113), + // (40, [.accepted, .symbol], 113), + // (2, .symbol, 118), + // (9, .symbol, 118), + // (23, .symbol, 118), + // (40, [.accepted, .symbol], 118), + // + // // 62 + // + // (3, .symbol, 106), + // (6, .symbol, 106), + // (10, .symbol, 106), + // (15, .symbol, 106), + // (24, .symbol, 106), + // (31, .symbol, 106), + // (41, .symbol, 106), + // (56, [.accepted, .symbol], 106), + // (3, .symbol, 107), + // (6, .symbol, 107), + // (10, .symbol, 107), + // (15, .symbol, 107), + // (24, .symbol, 107), + // (31, .symbol, 107), + // (41, .symbol, 107), + // (56, [.accepted, .symbol], 107), + // + // // 63 + // + // (3, .symbol, 113), + // (6, .symbol, 113), + // (10, .symbol, 113), + // (15, .symbol, 113), + // (24, .symbol, 113), + // (31, .symbol, 113), + // (41, .symbol, 113), + // (56, [.accepted, .symbol], 113), + // (3, .symbol, 118), + // (6, .symbol, 118), + // (10, .symbol, 118), + // (15, .symbol, 118), + // (24, .symbol, 118), + // (31, .symbol, 118), + // (41, .symbol, 118), + // (56, [.accepted, .symbol], 118), + // + // // 64 + // + // (1, .symbol, 119), + // (22, [.accepted, .symbol], 119), + // (1, .symbol, 120), + // (22, [.accepted, .symbol], 120), + // (1, .symbol, 121), + // (22, [.accepted, .symbol], 121), + // (1, .symbol, 122), + // (22, [.accepted, .symbol], 122), + // (0, [.accepted, .symbol], 38), + // (0, [.accepted, .symbol], 42), + // (0, [.accepted, .symbol], 44), + // (0, [.accepted, .symbol], 59), + // (0, [.accepted, .symbol], 88), + // (0, [.accepted, .symbol], 90), + // (75, .none, 0), + // (78, .none, 0), + // + // // 65 + // + // (2, .symbol, 119), + // (9, .symbol, 119), + // (23, .symbol, 119), + // (40, [.accepted, .symbol], 119), + // (2, .symbol, 120), + // (9, .symbol, 120), + // (23, .symbol, 120), + // (40, [.accepted, .symbol], 120), + // (2, .symbol, 121), + // (9, .symbol, 121), + // (23, .symbol, 121), + // (40, [.accepted, .symbol], 121), + // (2, .symbol, 122), + // (9, .symbol, 122), + // (23, .symbol, 122), + // (40, [.accepted, .symbol], 122), + // + // // 66 + // + // (3, .symbol, 119), + // (6, .symbol, 119), + // (10, .symbol, 119), + // (15, .symbol, 119), + // (24, .symbol, 119), + // (31, .symbol, 119), + // (41, .symbol, 119), + // (56, [.accepted, .symbol], 119), + // (3, .symbol, 120), + // (6, .symbol, 120), + // (10, .symbol, 120), + // (15, .symbol, 120), + // (24, .symbol, 120), + // (31, .symbol, 120), + // (41, .symbol, 120), + // (56, [.accepted, .symbol], 120), + // + // // 67 + // + // (3, .symbol, 121), + // (6, .symbol, 121), + // (10, .symbol, 121), + // (15, .symbol, 121), + // (24, .symbol, 121), + // (31, .symbol, 121), + // (41, .symbol, 121), + // (56, [.accepted, .symbol], 121), + // (3, .symbol, 122), + // (6, .symbol, 122), + // (10, .symbol, 122), + // (15, .symbol, 122), + // (24, .symbol, 122), + // (31, .symbol, 122), + // (41, .symbol, 122), + // (56, [.accepted, .symbol], 122), + // + // // 68 + // + // (1, .symbol, 38), + // (22, [.accepted, .symbol], 38), + // (1, .symbol, 42), + // (22, [.accepted, .symbol], 42), + // (1, .symbol, 44), + // (22, [.accepted, .symbol], 44), + // (1, .symbol, 59), + // (22, [.accepted, .symbol], 59), + // (1, .symbol, 88), + // (22, [.accepted, .symbol], 88), + // (1, .symbol, 90), + // (22, [.accepted, .symbol], 90), + // (76, .none, 0), + // (77, .none, 0), + // (79, .none, 0), + // (81, .none, 0), + // + // // 69 + // + // (2, .symbol, 38), + // (9, .symbol, 38), + // (23, .symbol, 38), + // (40, [.accepted, .symbol], 38), + // (2, .symbol, 42), + // (9, .symbol, 42), + // (23, .symbol, 42), + // (40, [.accepted, .symbol], 42), + // (2, .symbol, 44), + // (9, .symbol, 44), + // (23, .symbol, 44), + // (40, [.accepted, .symbol], 44), + // (2, .symbol, 59), + // (9, .symbol, 59), + // (23, .symbol, 59), + // (40, [.accepted, .symbol], 59), + // + // // 70 + // + // (3, .symbol, 38), + // (6, .symbol, 38), + // (10, .symbol, 38), + // (15, .symbol, 38), + // (24, .symbol, 38), + // (31, .symbol, 38), + // (41, .symbol, 38), + // (56, [.accepted, .symbol], 38), + // (3, .symbol, 42), + // (6, .symbol, 42), + // (10, .symbol, 42), + // (15, .symbol, 42), + // (24, .symbol, 42), + // (31, .symbol, 42), + // (41, .symbol, 42), + // (56, [.accepted, .symbol], 42), + // + // // 71 + // + // (3, .symbol, 44), + // (6, .symbol, 44), + // (10, .symbol, 44), + // (15, .symbol, 44), + // (24, .symbol, 44), + // (31, .symbol, 44), + // (41, .symbol, 44), + // (56, [.accepted, .symbol], 44), + // (3, .symbol, 59), + // (6, .symbol, 59), + // (10, .symbol, 59), + // (15, .symbol, 59), + // (24, .symbol, 59), + // (31, .symbol, 59), + // (41, .symbol, 59), + // (56, [.accepted, .symbol], 59), + // + // // 72 + // + // (2, .symbol, 88), + // (9, .symbol, 88), + // (23, .symbol, 88), + // (40, [.accepted, .symbol], 88), + // (2, .symbol, 90), + // (9, .symbol, 90), + // (23, .symbol, 90), + // (40, [.accepted, .symbol], 90), + // (0, [.accepted, .symbol], 33), + // (0, [.accepted, .symbol], 34), + // (0, [.accepted, .symbol], 40), + // (0, [.accepted, .symbol], 41), + // (0, [.accepted, .symbol], 63), + // (80, .none, 0), + // (82, .none, 0), + // (84, .none, 0), + // + // // 73 + // + // (3, .symbol, 88), + // (6, .symbol, 88), + // (10, .symbol, 88), + // (15, .symbol, 88), + // (24, .symbol, 88), + // (31, .symbol, 88), + // (41, .symbol, 88), + // (56, [.accepted, .symbol], 88), + // (3, .symbol, 90), + // (6, .symbol, 90), + // (10, .symbol, 90), + // (15, .symbol, 90), + // (24, .symbol, 90), + // (31, .symbol, 90), + // (41, .symbol, 90), + // (56, [.accepted, .symbol], 90), + // + // // 74 + // + // (1, .symbol, 33), + // (22, [.accepted, .symbol], 33), + // (1, .symbol, 34), + // (22, [.accepted, .symbol], 34), + // (1, .symbol, 40), + // (22, [.accepted, .symbol], 40), + // (1, .symbol, 41), + // (22, [.accepted, .symbol], 41), + // (1, .symbol, 63), + // (22, [.accepted, .symbol], 63), + // (0, [.accepted, .symbol], 39), + // (0, [.accepted, .symbol], 43), + // (0, [.accepted, .symbol], 124), + // (83, .none, 0), + // (85, .none, 0), + // (88, .none, 0), + // + // // 75 + // + // (2, .symbol, 33), + // (9, .symbol, 33), + // (23, .symbol, 33), + // (40, [.accepted, .symbol], 33), + // (2, .symbol, 34), + // (9, .symbol, 34), + // (23, .symbol, 34), + // (40, [.accepted, .symbol], 34), + // (2, .symbol, 40), + // (9, .symbol, 40), + // (23, .symbol, 40), + // (40, [.accepted, .symbol], 40), + // (2, .symbol, 41), + // (9, .symbol, 41), + // (23, .symbol, 41), + // (40, [.accepted, .symbol], 41), + // + // // 76 + // + // (3, .symbol, 33), + // (6, .symbol, 33), + // (10, .symbol, 33), + // (15, .symbol, 33), + // (24, .symbol, 33), + // (31, .symbol, 33), + // (41, .symbol, 33), + // (56, [.accepted, .symbol], 33), + // (3, .symbol, 34), + // (6, .symbol, 34), + // (10, .symbol, 34), + // (15, .symbol, 34), + // (24, .symbol, 34), + // (31, .symbol, 34), + // (41, .symbol, 34), + // (56, [.accepted, .symbol], 34), + // + // // 77 + // + // (3, .symbol, 40), + // (6, .symbol, 40), + // (10, .symbol, 40), + // (15, .symbol, 40), + // (24, .symbol, 40), + // (31, .symbol, 40), + // (41, .symbol, 40), + // (56, [.accepted, .symbol], 40), + // (3, .symbol, 41), + // (6, .symbol, 41), + // (10, .symbol, 41), + // (15, .symbol, 41), + // (24, .symbol, 41), + // (31, .symbol, 41), + // (41, .symbol, 41), + // (56, [.accepted, .symbol], 41), + // + // // 78 + // + // (2, .symbol, 63), + // (9, .symbol, 63), + // (23, .symbol, 63), + // (40, [.accepted, .symbol], 63), + // (1, .symbol, 39), + // (22, [.accepted, .symbol], 39), + // (1, .symbol, 43), + // (22, [.accepted, .symbol], 43), + // (1, .symbol, 124), + // (22, [.accepted, .symbol], 124), + // (0, [.accepted, .symbol], 35), + // (0, [.accepted, .symbol], 62), + // (86, .none, 0), + // (87, .none, 0), + // (89, .none, 0), + // (90, .none, 0), + // + // // 79 + // + // (3, .symbol, 63), + // (6, .symbol, 63), + // (10, .symbol, 63), + // (15, .symbol, 63), + // (24, .symbol, 63), + // (31, .symbol, 63), + // (41, .symbol, 63), + // (56, [.accepted, .symbol], 63), + // (2, .symbol, 39), + // (9, .symbol, 39), + // (23, .symbol, 39), + // (40, [.accepted, .symbol], 39), + // (2, .symbol, 43), + // (9, .symbol, 43), + // (23, .symbol, 43), + // (40, [.accepted, .symbol], 43), + // + // // 80 + // + // (3, .symbol, 39), + // (6, .symbol, 39), + // (10, .symbol, 39), + // (15, .symbol, 39), + // (24, .symbol, 39), + // (31, .symbol, 39), + // (41, .symbol, 39), + // (56, [.accepted, .symbol], 39), + // (3, .symbol, 43), + // (6, .symbol, 43), + // (10, .symbol, 43), + // (15, .symbol, 43), + // (24, .symbol, 43), + // (31, .symbol, 43), + // (41, .symbol, 43), + // (56, [.accepted, .symbol], 43), + // + // // 81 + // + // (2, .symbol, 124), + // (9, .symbol, 124), + // (23, .symbol, 124), + // (40, [.accepted, .symbol], 124), + // (1, .symbol, 35), + // (22, [.accepted, .symbol], 35), + // (1, .symbol, 62), + // (22, [.accepted, .symbol], 62), + // (0, [.accepted, .symbol], 0), + // (0, [.accepted, .symbol], 36), + // (0, [.accepted, .symbol], 64), + // (0, [.accepted, .symbol], 91), + // (0, [.accepted, .symbol], 93), + // (0, [.accepted, .symbol], 126), + // (91, .none, 0), + // (92, .none, 0), + // + // // 82 + // + // (3, .symbol, 124), + // (6, .symbol, 124), + // (10, .symbol, 124), + // (15, .symbol, 124), + // (24, .symbol, 124), + // (31, .symbol, 124), + // (41, .symbol, 124), + // (56, [.accepted, .symbol], 124), + // (2, .symbol, 35), + // (9, .symbol, 35), + // (23, .symbol, 35), + // (40, [.accepted, .symbol], 35), + // (2, .symbol, 62), + // (9, .symbol, 62), + // (23, .symbol, 62), + // (40, [.accepted, .symbol], 62), + // + // // 83 + // + // (3, .symbol, 35), + // (6, .symbol, 35), + // (10, .symbol, 35), + // (15, .symbol, 35), + // (24, .symbol, 35), + // (31, .symbol, 35), + // (41, .symbol, 35), + // (56, [.accepted, .symbol], 35), + // (3, .symbol, 62), + // (6, .symbol, 62), + // (10, .symbol, 62), + // (15, .symbol, 62), + // (24, .symbol, 62), + // (31, .symbol, 62), + // (41, .symbol, 62), + // (56, [.accepted, .symbol], 62), + // + // // 84 + // + // (1, .symbol, 0), + // (22, [.accepted, .symbol], 0), + // (1, .symbol, 36), + // (22, [.accepted, .symbol], 36), + // (1, .symbol, 64), + // (22, [.accepted, .symbol], 64), + // (1, .symbol, 91), + // (22, [.accepted, .symbol], 91), + // (1, .symbol, 93), + // (22, [.accepted, .symbol], 93), + // (1, .symbol, 126), + // (22, [.accepted, .symbol], 126), + // (0, [.accepted, .symbol], 94), + // (0, [.accepted, .symbol], 125), + // (93, .none, 0), + // (94, .none, 0), + // + // // 85 + // + // (2, .symbol, 0), + // (9, .symbol, 0), + // (23, .symbol, 0), + // (40, [.accepted, .symbol], 0), + // (2, .symbol, 36), + // (9, .symbol, 36), + // (23, .symbol, 36), + // (40, [.accepted, .symbol], 36), + // (2, .symbol, 64), + // (9, .symbol, 64), + // (23, .symbol, 64), + // (40, [.accepted, .symbol], 64), + // (2, .symbol, 91), + // (9, .symbol, 91), + // (23, .symbol, 91), + // (40, [.accepted, .symbol], 91), + // + // // 86 + // + // (3, .symbol, 0), + // (6, .symbol, 0), + // (10, .symbol, 0), + // (15, .symbol, 0), + // (24, .symbol, 0), + // (31, .symbol, 0), + // (41, .symbol, 0), + // (56, [.accepted, .symbol], 0), + // (3, .symbol, 36), + // (6, .symbol, 36), + // (10, .symbol, 36), + // (15, .symbol, 36), + // (24, .symbol, 36), + // (31, .symbol, 36), + // (41, .symbol, 36), + // (56, [.accepted, .symbol], 36), + // + // // 87 + // + // (3, .symbol, 64), + // (6, .symbol, 64), + // (10, .symbol, 64), + // (15, .symbol, 64), + // (24, .symbol, 64), + // (31, .symbol, 64), + // (41, .symbol, 64), + // (56, [.accepted, .symbol], 64), + // (3, .symbol, 91), + // (6, .symbol, 91), + // (10, .symbol, 91), + // (15, .symbol, 91), + // (24, .symbol, 91), + // (31, .symbol, 91), + // (41, .symbol, 91), + // (56, [.accepted, .symbol], 91), + // + // // 88 + // + // (2, .symbol, 93), + // (9, .symbol, 93), + // (23, .symbol, 93), + // (40, [.accepted, .symbol], 93), + // (2, .symbol, 126), + // (9, .symbol, 126), + // (23, .symbol, 126), + // (40, [.accepted, .symbol], 126), + // (1, .symbol, 94), + // (22, [.accepted, .symbol], 94), + // (1, .symbol, 125), + // (22, [.accepted, .symbol], 125), + // (0, [.accepted, .symbol], 60), + // (0, [.accepted, .symbol], 96), + // (0, [.accepted, .symbol], 123), + // (95, .none, 0), + // + // // 89 + // + // (3, .symbol, 93), + // (6, .symbol, 93), + // (10, .symbol, 93), + // (15, .symbol, 93), + // (24, .symbol, 93), + // (31, .symbol, 93), + // (41, .symbol, 93), + // (56, [.accepted, .symbol], 93), + // (3, .symbol, 126), + // (6, .symbol, 126), + // (10, .symbol, 126), + // (15, .symbol, 126), + // (24, .symbol, 126), + // (31, .symbol, 126), + // (41, .symbol, 126), + // (56, [.accepted, .symbol], 126), + // + // // 90 + // + // (2, .symbol, 94), + // (9, .symbol, 94), + // (23, .symbol, 94), + // (40, [.accepted, .symbol], 94), + // (2, .symbol, 125), + // (9, .symbol, 125), + // (23, .symbol, 125), + // (40, [.accepted, .symbol], 125), + // (1, .symbol, 60), + // (22, [.accepted, .symbol], 60), + // (1, .symbol, 96), + // (22, [.accepted, .symbol], 96), + // (1, .symbol, 123), + // (22, [.accepted, .symbol], 123), + // (96, .none, 0), + // (110, .none, 0), + // + // // 91 + // + // (3, .symbol, 94), + // (6, .symbol, 94), + // (10, .symbol, 94), + // (15, .symbol, 94), + // (24, .symbol, 94), + // (31, .symbol, 94), + // (41, .symbol, 94), + // (56, [.accepted, .symbol], 94), + // (3, .symbol, 125), + // (6, .symbol, 125), + // (10, .symbol, 125), + // (15, .symbol, 125), + // (24, .symbol, 125), + // (31, .symbol, 125), + // (41, .symbol, 125), + // (56, [.accepted, .symbol], 125), + // + // // 92 + // + // (2, .symbol, 60), + // (9, .symbol, 60), + // (23, .symbol, 60), + // (40, [.accepted, .symbol], 60), + // (2, .symbol, 96), + // (9, .symbol, 96), + // (23, .symbol, 96), + // (40, [.accepted, .symbol], 96), + // (2, .symbol, 123), + // (9, .symbol, 123), + // (23, .symbol, 123), + // (40, [.accepted, .symbol], 123), + // (97, .none, 0), + // (101, .none, 0), + // (111, .none, 0), + // (133, .none, 0), + // + // // 93 + // + // (3, .symbol, 60), + // (6, .symbol, 60), + // (10, .symbol, 60), + // (15, .symbol, 60), + // (24, .symbol, 60), + // (31, .symbol, 60), + // (41, .symbol, 60), + // (56, [.accepted, .symbol], 60), + // (3, .symbol, 96), + // (6, .symbol, 96), + // (10, .symbol, 96), + // (15, .symbol, 96), + // (24, .symbol, 96), + // (31, .symbol, 96), + // (41, .symbol, 96), + // (56, [.accepted, .symbol], 96), + // + // // 94 + // + // (3, .symbol, 123), + // (6, .symbol, 123), + // (10, .symbol, 123), + // (15, .symbol, 123), + // (24, .symbol, 123), + // (31, .symbol, 123), + // (41, .symbol, 123), + // (56, [.accepted, .symbol], 123), + // (98, .none, 0), + // (99, .none, 0), + // (102, .none, 0), + // (105, .none, 0), + // (112, .none, 0), + // (119, .none, 0), + // (134, .none, 0), + // (153, .none, 0), + // + // // 95 + // + // (0, [.accepted, .symbol], 92), + // (0, [.accepted, .symbol], 195), + // (0, [.accepted, .symbol], 208), + // (100, .none, 0), + // (103, .none, 0), + // (104, .none, 0), + // (106, .none, 0), + // (107, .none, 0), + // (113, .none, 0), + // (116, .none, 0), + // (120, .none, 0), + // (126, .none, 0), + // (135, .none, 0), + // (142, .none, 0), + // (154, .none, 0), + // (169, .none, 0), + // + // // 96 + // + // (1, .symbol, 92), + // (22, [.accepted, .symbol], 92), + // (1, .symbol, 195), + // (22, [.accepted, .symbol], 195), + // (1, .symbol, 208), + // (22, [.accepted, .symbol], 208), + // (0, [.accepted, .symbol], 128), + // (0, [.accepted, .symbol], 130), + // (0, [.accepted, .symbol], 131), + // (0, [.accepted, .symbol], 162), + // (0, [.accepted, .symbol], 184), + // (0, [.accepted, .symbol], 194), + // (0, [.accepted, .symbol], 224), + // (0, [.accepted, .symbol], 226), + // (108, .none, 0), + // (109, .none, 0), + // + // // 97 + // + // (2, .symbol, 92), + // (9, .symbol, 92), + // (23, .symbol, 92), + // (40, [.accepted, .symbol], 92), + // (2, .symbol, 195), + // (9, .symbol, 195), + // (23, .symbol, 195), + // (40, [.accepted, .symbol], 195), + // (2, .symbol, 208), + // (9, .symbol, 208), + // (23, .symbol, 208), + // (40, [.accepted, .symbol], 208), + // (1, .symbol, 128), + // (22, [.accepted, .symbol], 128), + // (1, .symbol, 130), + // (22, [.accepted, .symbol], 130), + // + // // 98 + // + // (3, .symbol, 92), + // (6, .symbol, 92), + // (10, .symbol, 92), + // (15, .symbol, 92), + // (24, .symbol, 92), + // (31, .symbol, 92), + // (41, .symbol, 92), + // (56, [.accepted, .symbol], 92), + // (3, .symbol, 195), + // (6, .symbol, 195), + // (10, .symbol, 195), + // (15, .symbol, 195), + // (24, .symbol, 195), + // (31, .symbol, 195), + // (41, .symbol, 195), + // (56, [.accepted, .symbol], 195), + // + // // 99 + // + // (3, .symbol, 208), + // (6, .symbol, 208), + // (10, .symbol, 208), + // (15, .symbol, 208), + // (24, .symbol, 208), + // (31, .symbol, 208), + // (41, .symbol, 208), + // (56, [.accepted, .symbol], 208), + // (2, .symbol, 128), + // (9, .symbol, 128), + // (23, .symbol, 128), + // (40, [.accepted, .symbol], 128), + // (2, .symbol, 130), + // (9, .symbol, 130), + // (23, .symbol, 130), + // (40, [.accepted, .symbol], 130), + // + // // 100 + // + // (3, .symbol, 128), + // (6, .symbol, 128), + // (10, .symbol, 128), + // (15, .symbol, 128), + // (24, .symbol, 128), + // (31, .symbol, 128), + // (41, .symbol, 128), + // (56, [.accepted, .symbol], 128), + // (3, .symbol, 130), + // (6, .symbol, 130), + // (10, .symbol, 130), + // (15, .symbol, 130), + // (24, .symbol, 130), + // (31, .symbol, 130), + // (41, .symbol, 130), + // (56, [.accepted, .symbol], 130), + // + // // 101 + // + // (1, .symbol, 131), + // (22, [.accepted, .symbol], 131), + // (1, .symbol, 162), + // (22, [.accepted, .symbol], 162), + // (1, .symbol, 184), + // (22, [.accepted, .symbol], 184), + // (1, .symbol, 194), + // (22, [.accepted, .symbol], 194), + // (1, .symbol, 224), + // (22, [.accepted, .symbol], 224), + // (1, .symbol, 226), + // (22, [.accepted, .symbol], 226), + // (0, [.accepted, .symbol], 153), + // (0, [.accepted, .symbol], 161), + // (0, [.accepted, .symbol], 167), + // (0, [.accepted, .symbol], 172), + // + // // 102 + // + // (2, .symbol, 131), + // (9, .symbol, 131), + // (23, .symbol, 131), + // (40, [.accepted, .symbol], 131), + // (2, .symbol, 162), + // (9, .symbol, 162), + // (23, .symbol, 162), + // (40, [.accepted, .symbol], 162), + // (2, .symbol, 184), + // (9, .symbol, 184), + // (23, .symbol, 184), + // (40, [.accepted, .symbol], 184), + // (2, .symbol, 194), + // (9, .symbol, 194), + // (23, .symbol, 194), + // (40, [.accepted, .symbol], 194), + // + // // 103 + // + // (3, .symbol, 131), + // (6, .symbol, 131), + // (10, .symbol, 131), + // (15, .symbol, 131), + // (24, .symbol, 131), + // (31, .symbol, 131), + // (41, .symbol, 131), + // (56, [.accepted, .symbol], 131), + // (3, .symbol, 162), + // (6, .symbol, 162), + // (10, .symbol, 162), + // (15, .symbol, 162), + // (24, .symbol, 162), + // (31, .symbol, 162), + // (41, .symbol, 162), + // (56, [.accepted, .symbol], 162), + // + // // 104 + // + // (3, .symbol, 184), + // (6, .symbol, 184), + // (10, .symbol, 184), + // (15, .symbol, 184), + // (24, .symbol, 184), + // (31, .symbol, 184), + // (41, .symbol, 184), + // (56, [.accepted, .symbol], 184), + // (3, .symbol, 194), + // (6, .symbol, 194), + // (10, .symbol, 194), + // (15, .symbol, 194), + // (24, .symbol, 194), + // (31, .symbol, 194), + // (41, .symbol, 194), + // (56, [.accepted, .symbol], 194), + // + // // 105 + // + // (2, .symbol, 224), + // (9, .symbol, 224), + // (23, .symbol, 224), + // (40, [.accepted, .symbol], 224), + // (2, .symbol, 226), + // (9, .symbol, 226), + // (23, .symbol, 226), + // (40, [.accepted, .symbol], 226), + // (1, .symbol, 153), + // (22, [.accepted, .symbol], 153), + // (1, .symbol, 161), + // (22, [.accepted, .symbol], 161), + // (1, .symbol, 167), + // (22, [.accepted, .symbol], 167), + // (1, .symbol, 172), + // (22, [.accepted, .symbol], 172), + // + // // 106 + // + // (3, .symbol, 224), + // (6, .symbol, 224), + // (10, .symbol, 224), + // (15, .symbol, 224), + // (24, .symbol, 224), + // (31, .symbol, 224), + // (41, .symbol, 224), + // (56, [.accepted, .symbol], 224), + // (3, .symbol, 226), + // (6, .symbol, 226), + // (10, .symbol, 226), + // (15, .symbol, 226), + // (24, .symbol, 226), + // (31, .symbol, 226), + // (41, .symbol, 226), + // (56, [.accepted, .symbol], 226), + // + // // 107 + // + // (2, .symbol, 153), + // (9, .symbol, 153), + // (23, .symbol, 153), + // (40, [.accepted, .symbol], 153), + // (2, .symbol, 161), + // (9, .symbol, 161), + // (23, .symbol, 161), + // (40, [.accepted, .symbol], 161), + // (2, .symbol, 167), + // (9, .symbol, 167), + // (23, .symbol, 167), + // (40, [.accepted, .symbol], 167), + // (2, .symbol, 172), + // (9, .symbol, 172), + // (23, .symbol, 172), + // (40, [.accepted, .symbol], 172), + // + // // 108 + // + // (3, .symbol, 153), + // (6, .symbol, 153), + // (10, .symbol, 153), + // (15, .symbol, 153), + // (24, .symbol, 153), + // (31, .symbol, 153), + // (41, .symbol, 153), + // (56, [.accepted, .symbol], 153), + // (3, .symbol, 161), + // (6, .symbol, 161), + // (10, .symbol, 161), + // (15, .symbol, 161), + // (24, .symbol, 161), + // (31, .symbol, 161), + // (41, .symbol, 161), + // (56, [.accepted, .symbol], 161), + // + // // 109 + // + // (3, .symbol, 167), + // (6, .symbol, 167), + // (10, .symbol, 167), + // (15, .symbol, 167), + // (24, .symbol, 167), + // (31, .symbol, 167), + // (41, .symbol, 167), + // (56, [.accepted, .symbol], 167), + // (3, .symbol, 172), + // (6, .symbol, 172), + // (10, .symbol, 172), + // (15, .symbol, 172), + // (24, .symbol, 172), + // (31, .symbol, 172), + // (41, .symbol, 172), + // (56, [.accepted, .symbol], 172), + // + // // 110 + // + // (114, .none, 0), + // (115, .none, 0), + // (117, .none, 0), + // (118, .none, 0), + // (121, .none, 0), + // (123, .none, 0), + // (127, .none, 0), + // (130, .none, 0), + // (136, .none, 0), + // (139, .none, 0), + // (143, .none, 0), + // (146, .none, 0), + // (155, .none, 0), + // (162, .none, 0), + // (170, .none, 0), + // (180, .none, 0), + // + // // 111 + // + // (0, [.accepted, .symbol], 176), + // (0, [.accepted, .symbol], 177), + // (0, [.accepted, .symbol], 179), + // (0, [.accepted, .symbol], 209), + // (0, [.accepted, .symbol], 216), + // (0, [.accepted, .symbol], 217), + // (0, [.accepted, .symbol], 227), + // (0, [.accepted, .symbol], 229), + // (0, [.accepted, .symbol], 230), + // (122, .none, 0), + // (124, .none, 0), + // (125, .none, 0), + // (128, .none, 0), + // (129, .none, 0), + // (131, .none, 0), + // (132, .none, 0), + // + // // 112 + // + // (1, .symbol, 176), + // (22, [.accepted, .symbol], 176), + // (1, .symbol, 177), + // (22, [.accepted, .symbol], 177), + // (1, .symbol, 179), + // (22, [.accepted, .symbol], 179), + // (1, .symbol, 209), + // (22, [.accepted, .symbol], 209), + // (1, .symbol, 216), + // (22, [.accepted, .symbol], 216), + // (1, .symbol, 217), + // (22, [.accepted, .symbol], 217), + // (1, .symbol, 227), + // (22, [.accepted, .symbol], 227), + // (1, .symbol, 229), + // (22, [.accepted, .symbol], 229), + // + // // 113 + // + // (2, .symbol, 176), + // (9, .symbol, 176), + // (23, .symbol, 176), + // (40, [.accepted, .symbol], 176), + // (2, .symbol, 177), + // (9, .symbol, 177), + // (23, .symbol, 177), + // (40, [.accepted, .symbol], 177), + // (2, .symbol, 179), + // (9, .symbol, 179), + // (23, .symbol, 179), + // (40, [.accepted, .symbol], 179), + // (2, .symbol, 209), + // (9, .symbol, 209), + // (23, .symbol, 209), + // (40, [.accepted, .symbol], 209), + // + // // 114 + // + // (3, .symbol, 176), + // (6, .symbol, 176), + // (10, .symbol, 176), + // (15, .symbol, 176), + // (24, .symbol, 176), + // (31, .symbol, 176), + // (41, .symbol, 176), + // (56, [.accepted, .symbol], 176), + // (3, .symbol, 177), + // (6, .symbol, 177), + // (10, .symbol, 177), + // (15, .symbol, 177), + // (24, .symbol, 177), + // (31, .symbol, 177), + // (41, .symbol, 177), + // (56, [.accepted, .symbol], 177), + // + // // 115 + // + // (3, .symbol, 179), + // (6, .symbol, 179), + // (10, .symbol, 179), + // (15, .symbol, 179), + // (24, .symbol, 179), + // (31, .symbol, 179), + // (41, .symbol, 179), + // (56, [.accepted, .symbol], 179), + // (3, .symbol, 209), + // (6, .symbol, 209), + // (10, .symbol, 209), + // (15, .symbol, 209), + // (24, .symbol, 209), + // (31, .symbol, 209), + // (41, .symbol, 209), + // (56, [.accepted, .symbol], 209), + // + // // 116 + // + // (2, .symbol, 216), + // (9, .symbol, 216), + // (23, .symbol, 216), + // (40, [.accepted, .symbol], 216), + // (2, .symbol, 217), + // (9, .symbol, 217), + // (23, .symbol, 217), + // (40, [.accepted, .symbol], 217), + // (2, .symbol, 227), + // (9, .symbol, 227), + // (23, .symbol, 227), + // (40, [.accepted, .symbol], 227), + // (2, .symbol, 229), + // (9, .symbol, 229), + // (23, .symbol, 229), + // (40, [.accepted, .symbol], 229), + // + // // 117 + // + // (3, .symbol, 216), + // (6, .symbol, 216), + // (10, .symbol, 216), + // (15, .symbol, 216), + // (24, .symbol, 216), + // (31, .symbol, 216), + // (41, .symbol, 216), + // (56, [.accepted, .symbol], 216), + // (3, .symbol, 217), + // (6, .symbol, 217), + // (10, .symbol, 217), + // (15, .symbol, 217), + // (24, .symbol, 217), + // (31, .symbol, 217), + // (41, .symbol, 217), + // (56, [.accepted, .symbol], 217), + // + // // 118 + // + // (3, .symbol, 227), + // (6, .symbol, 227), + // (10, .symbol, 227), + // (15, .symbol, 227), + // (24, .symbol, 227), + // (31, .symbol, 227), + // (41, .symbol, 227), + // (56, [.accepted, .symbol], 227), + // (3, .symbol, 229), + // (6, .symbol, 229), + // (10, .symbol, 229), + // (15, .symbol, 229), + // (24, .symbol, 229), + // (31, .symbol, 229), + // (41, .symbol, 229), + // (56, [.accepted, .symbol], 229), + // + // // 119 + // + // (1, .symbol, 230), + // (22, [.accepted, .symbol], 230), + // (0, [.accepted, .symbol], 129), + // (0, [.accepted, .symbol], 132), + // (0, [.accepted, .symbol], 133), + // (0, [.accepted, .symbol], 134), + // (0, [.accepted, .symbol], 136), + // (0, [.accepted, .symbol], 146), + // (0, [.accepted, .symbol], 154), + // (0, [.accepted, .symbol], 156), + // (0, [.accepted, .symbol], 160), + // (0, [.accepted, .symbol], 163), + // (0, [.accepted, .symbol], 164), + // (0, [.accepted, .symbol], 169), + // (0, [.accepted, .symbol], 170), + // (0, [.accepted, .symbol], 173), + // + // // 120 + // + // (2, .symbol, 230), + // (9, .symbol, 230), + // (23, .symbol, 230), + // (40, [.accepted, .symbol], 230), + // (1, .symbol, 129), + // (22, [.accepted, .symbol], 129), + // (1, .symbol, 132), + // (22, [.accepted, .symbol], 132), + // (1, .symbol, 133), + // (22, [.accepted, .symbol], 133), + // (1, .symbol, 134), + // (22, [.accepted, .symbol], 134), + // (1, .symbol, 136), + // (22, [.accepted, .symbol], 136), + // (1, .symbol, 146), + // (22, [.accepted, .symbol], 146), + // + // // 121 + // + // (3, .symbol, 230), + // (6, .symbol, 230), + // (10, .symbol, 230), + // (15, .symbol, 230), + // (24, .symbol, 230), + // (31, .symbol, 230), + // (41, .symbol, 230), + // (56, [.accepted, .symbol], 230), + // (2, .symbol, 129), + // (9, .symbol, 129), + // (23, .symbol, 129), + // (40, [.accepted, .symbol], 129), + // (2, .symbol, 132), + // (9, .symbol, 132), + // (23, .symbol, 132), + // (40, [.accepted, .symbol], 132), + // + // // 122 + // + // (3, .symbol, 129), + // (6, .symbol, 129), + // (10, .symbol, 129), + // (15, .symbol, 129), + // (24, .symbol, 129), + // (31, .symbol, 129), + // (41, .symbol, 129), + // (56, [.accepted, .symbol], 129), + // (3, .symbol, 132), + // (6, .symbol, 132), + // (10, .symbol, 132), + // (15, .symbol, 132), + // (24, .symbol, 132), + // (31, .symbol, 132), + // (41, .symbol, 132), + // (56, [.accepted, .symbol], 132), + // + // // 123 + // + // (2, .symbol, 133), + // (9, .symbol, 133), + // (23, .symbol, 133), + // (40, [.accepted, .symbol], 133), + // (2, .symbol, 134), + // (9, .symbol, 134), + // (23, .symbol, 134), + // (40, [.accepted, .symbol], 134), + // (2, .symbol, 136), + // (9, .symbol, 136), + // (23, .symbol, 136), + // (40, [.accepted, .symbol], 136), + // (2, .symbol, 146), + // (9, .symbol, 146), + // (23, .symbol, 146), + // (40, [.accepted, .symbol], 146), + // + // // 124 + // + // (3, .symbol, 133), + // (6, .symbol, 133), + // (10, .symbol, 133), + // (15, .symbol, 133), + // (24, .symbol, 133), + // (31, .symbol, 133), + // (41, .symbol, 133), + // (56, [.accepted, .symbol], 133), + // (3, .symbol, 134), + // (6, .symbol, 134), + // (10, .symbol, 134), + // (15, .symbol, 134), + // (24, .symbol, 134), + // (31, .symbol, 134), + // (41, .symbol, 134), + // (56, [.accepted, .symbol], 134), + // + // // 125 + // + // (3, .symbol, 136), + // (6, .symbol, 136), + // (10, .symbol, 136), + // (15, .symbol, 136), + // (24, .symbol, 136), + // (31, .symbol, 136), + // (41, .symbol, 136), + // (56, [.accepted, .symbol], 136), + // (3, .symbol, 146), + // (6, .symbol, 146), + // (10, .symbol, 146), + // (15, .symbol, 146), + // (24, .symbol, 146), + // (31, .symbol, 146), + // (41, .symbol, 146), + // (56, [.accepted, .symbol], 146), + // + // // 126 + // + // (1, .symbol, 154), + // (22, [.accepted, .symbol], 154), + // (1, .symbol, 156), + // (22, [.accepted, .symbol], 156), + // (1, .symbol, 160), + // (22, [.accepted, .symbol], 160), + // (1, .symbol, 163), + // (22, [.accepted, .symbol], 163), + // (1, .symbol, 164), + // (22, [.accepted, .symbol], 164), + // (1, .symbol, 169), + // (22, [.accepted, .symbol], 169), + // (1, .symbol, 170), + // (22, [.accepted, .symbol], 170), + // (1, .symbol, 173), + // (22, [.accepted, .symbol], 173), + // + // // 127 + // + // (2, .symbol, 154), + // (9, .symbol, 154), + // (23, .symbol, 154), + // (40, [.accepted, .symbol], 154), + // (2, .symbol, 156), + // (9, .symbol, 156), + // (23, .symbol, 156), + // (40, [.accepted, .symbol], 156), + // (2, .symbol, 160), + // (9, .symbol, 160), + // (23, .symbol, 160), + // (40, [.accepted, .symbol], 160), + // (2, .symbol, 163), + // (9, .symbol, 163), + // (23, .symbol, 163), + // (40, [.accepted, .symbol], 163), + // + // // 128 + // + // (3, .symbol, 154), + // (6, .symbol, 154), + // (10, .symbol, 154), + // (15, .symbol, 154), + // (24, .symbol, 154), + // (31, .symbol, 154), + // (41, .symbol, 154), + // (56, [.accepted, .symbol], 154), + // (3, .symbol, 156), + // (6, .symbol, 156), + // (10, .symbol, 156), + // (15, .symbol, 156), + // (24, .symbol, 156), + // (31, .symbol, 156), + // (41, .symbol, 156), + // (56, [.accepted, .symbol], 156), + // + // // 129 + // + // (3, .symbol, 160), + // (6, .symbol, 160), + // (10, .symbol, 160), + // (15, .symbol, 160), + // (24, .symbol, 160), + // (31, .symbol, 160), + // (41, .symbol, 160), + // (56, [.accepted, .symbol], 160), + // (3, .symbol, 163), + // (6, .symbol, 163), + // (10, .symbol, 163), + // (15, .symbol, 163), + // (24, .symbol, 163), + // (31, .symbol, 163), + // (41, .symbol, 163), + // (56, [.accepted, .symbol], 163), + // + // // 130 + // + // (2, .symbol, 164), + // (9, .symbol, 164), + // (23, .symbol, 164), + // (40, [.accepted, .symbol], 164), + // (2, .symbol, 169), + // (9, .symbol, 169), + // (23, .symbol, 169), + // (40, [.accepted, .symbol], 169), + // (2, .symbol, 170), + // (9, .symbol, 170), + // (23, .symbol, 170), + // (40, [.accepted, .symbol], 170), + // (2, .symbol, 173), + // (9, .symbol, 173), + // (23, .symbol, 173), + // (40, [.accepted, .symbol], 173), + // + // // 131 + // + // (3, .symbol, 164), + // (6, .symbol, 164), + // (10, .symbol, 164), + // (15, .symbol, 164), + // (24, .symbol, 164), + // (31, .symbol, 164), + // (41, .symbol, 164), + // (56, [.accepted, .symbol], 164), + // (3, .symbol, 169), + // (6, .symbol, 169), + // (10, .symbol, 169), + // (15, .symbol, 169), + // (24, .symbol, 169), + // (31, .symbol, 169), + // (41, .symbol, 169), + // (56, [.accepted, .symbol], 169), + // + // // 132 + // + // (3, .symbol, 170), + // (6, .symbol, 170), + // (10, .symbol, 170), + // (15, .symbol, 170), + // (24, .symbol, 170), + // (31, .symbol, 170), + // (41, .symbol, 170), + // (56, [.accepted, .symbol], 170), + // (3, .symbol, 173), + // (6, .symbol, 173), + // (10, .symbol, 173), + // (15, .symbol, 173), + // (24, .symbol, 173), + // (31, .symbol, 173), + // (41, .symbol, 173), + // (56, [.accepted, .symbol], 173), + // + // // 133 + // + // (137, .none, 0), + // (138, .none, 0), + // (140, .none, 0), + // (141, .none, 0), + // (144, .none, 0), + // (145, .none, 0), + // (147, .none, 0), + // (150, .none, 0), + // (156, .none, 0), + // (159, .none, 0), + // (163, .none, 0), + // (166, .none, 0), + // (171, .none, 0), + // (174, .none, 0), + // (181, .none, 0), + // (190, .none, 0), + // + // // 134 + // + // (0, [.accepted, .symbol], 178), + // (0, [.accepted, .symbol], 181), + // (0, [.accepted, .symbol], 185), + // (0, [.accepted, .symbol], 186), + // (0, [.accepted, .symbol], 187), + // (0, [.accepted, .symbol], 189), + // (0, [.accepted, .symbol], 190), + // (0, [.accepted, .symbol], 196), + // (0, [.accepted, .symbol], 198), + // (0, [.accepted, .symbol], 228), + // (0, [.accepted, .symbol], 232), + // (0, [.accepted, .symbol], 233), + // (148, .none, 0), + // (149, .none, 0), + // (151, .none, 0), + // (152, .none, 0), + // + // // 135 + // + // (1, .symbol, 178), + // (22, [.accepted, .symbol], 178), + // (1, .symbol, 181), + // (22, [.accepted, .symbol], 181), + // (1, .symbol, 185), + // (22, [.accepted, .symbol], 185), + // (1, .symbol, 186), + // (22, [.accepted, .symbol], 186), + // (1, .symbol, 187), + // (22, [.accepted, .symbol], 187), + // (1, .symbol, 189), + // (22, [.accepted, .symbol], 189), + // (1, .symbol, 190), + // (22, [.accepted, .symbol], 190), + // (1, .symbol, 196), + // (22, [.accepted, .symbol], 196), + // + // // 136 + // + // (2, .symbol, 178), + // (9, .symbol, 178), + // (23, .symbol, 178), + // (40, [.accepted, .symbol], 178), + // (2, .symbol, 181), + // (9, .symbol, 181), + // (23, .symbol, 181), + // (40, [.accepted, .symbol], 181), + // (2, .symbol, 185), + // (9, .symbol, 185), + // (23, .symbol, 185), + // (40, [.accepted, .symbol], 185), + // (2, .symbol, 186), + // (9, .symbol, 186), + // (23, .symbol, 186), + // (40, [.accepted, .symbol], 186), + // + // // 137 + // + // (3, .symbol, 178), + // (6, .symbol, 178), + // (10, .symbol, 178), + // (15, .symbol, 178), + // (24, .symbol, 178), + // (31, .symbol, 178), + // (41, .symbol, 178), + // (56, [.accepted, .symbol], 178), + // (3, .symbol, 181), + // (6, .symbol, 181), + // (10, .symbol, 181), + // (15, .symbol, 181), + // (24, .symbol, 181), + // (31, .symbol, 181), + // (41, .symbol, 181), + // (56, [.accepted, .symbol], 181), + // + // // 138 + // + // (3, .symbol, 185), + // (6, .symbol, 185), + // (10, .symbol, 185), + // (15, .symbol, 185), + // (24, .symbol, 185), + // (31, .symbol, 185), + // (41, .symbol, 185), + // (56, [.accepted, .symbol], 185), + // (3, .symbol, 186), + // (6, .symbol, 186), + // (10, .symbol, 186), + // (15, .symbol, 186), + // (24, .symbol, 186), + // (31, .symbol, 186), + // (41, .symbol, 186), + // (56, [.accepted, .symbol], 186), + // + // // 139 + // + // (2, .symbol, 187), + // (9, .symbol, 187), + // (23, .symbol, 187), + // (40, [.accepted, .symbol], 187), + // (2, .symbol, 189), + // (9, .symbol, 189), + // (23, .symbol, 189), + // (40, [.accepted, .symbol], 189), + // (2, .symbol, 190), + // (9, .symbol, 190), + // (23, .symbol, 190), + // (40, [.accepted, .symbol], 190), + // (2, .symbol, 196), + // (9, .symbol, 196), + // (23, .symbol, 196), + // (40, [.accepted, .symbol], 196), + // + // // 140 + // + // (3, .symbol, 187), + // (6, .symbol, 187), + // (10, .symbol, 187), + // (15, .symbol, 187), + // (24, .symbol, 187), + // (31, .symbol, 187), + // (41, .symbol, 187), + // (56, [.accepted, .symbol], 187), + // (3, .symbol, 189), + // (6, .symbol, 189), + // (10, .symbol, 189), + // (15, .symbol, 189), + // (24, .symbol, 189), + // (31, .symbol, 189), + // (41, .symbol, 189), + // (56, [.accepted, .symbol], 189), + // + // // 141 + // + // (3, .symbol, 190), + // (6, .symbol, 190), + // (10, .symbol, 190), + // (15, .symbol, 190), + // (24, .symbol, 190), + // (31, .symbol, 190), + // (41, .symbol, 190), + // (56, [.accepted, .symbol], 190), + // (3, .symbol, 196), + // (6, .symbol, 196), + // (10, .symbol, 196), + // (15, .symbol, 196), + // (24, .symbol, 196), + // (31, .symbol, 196), + // (41, .symbol, 196), + // (56, [.accepted, .symbol], 196), + // + // // 142 + // + // (1, .symbol, 198), + // (22, [.accepted, .symbol], 198), + // (1, .symbol, 228), + // (22, [.accepted, .symbol], 228), + // (1, .symbol, 232), + // (22, [.accepted, .symbol], 232), + // (1, .symbol, 233), + // (22, [.accepted, .symbol], 233), + // (0, [.accepted, .symbol], 1), + // (0, [.accepted, .symbol], 135), + // (0, [.accepted, .symbol], 137), + // (0, [.accepted, .symbol], 138), + // (0, [.accepted, .symbol], 139), + // (0, [.accepted, .symbol], 140), + // (0, [.accepted, .symbol], 141), + // (0, [.accepted, .symbol], 143), + // + // // 143 + // + // (2, .symbol, 198), + // (9, .symbol, 198), + // (23, .symbol, 198), + // (40, [.accepted, .symbol], 198), + // (2, .symbol, 228), + // (9, .symbol, 228), + // (23, .symbol, 228), + // (40, [.accepted, .symbol], 228), + // (2, .symbol, 232), + // (9, .symbol, 232), + // (23, .symbol, 232), + // (40, [.accepted, .symbol], 232), + // (2, .symbol, 233), + // (9, .symbol, 233), + // (23, .symbol, 233), + // (40, [.accepted, .symbol], 233), + // + // // 144 + // + // (3, .symbol, 198), + // (6, .symbol, 198), + // (10, .symbol, 198), + // (15, .symbol, 198), + // (24, .symbol, 198), + // (31, .symbol, 198), + // (41, .symbol, 198), + // (56, [.accepted, .symbol], 198), + // (3, .symbol, 228), + // (6, .symbol, 228), + // (10, .symbol, 228), + // (15, .symbol, 228), + // (24, .symbol, 228), + // (31, .symbol, 228), + // (41, .symbol, 228), + // (56, [.accepted, .symbol], 228), + // + // // 145 + // + // (3, .symbol, 232), + // (6, .symbol, 232), + // (10, .symbol, 232), + // (15, .symbol, 232), + // (24, .symbol, 232), + // (31, .symbol, 232), + // (41, .symbol, 232), + // (56, [.accepted, .symbol], 232), + // (3, .symbol, 233), + // (6, .symbol, 233), + // (10, .symbol, 233), + // (15, .symbol, 233), + // (24, .symbol, 233), + // (31, .symbol, 233), + // (41, .symbol, 233), + // (56, [.accepted, .symbol], 233), + // + // // 146 + // + // (1, .symbol, 1), + // (22, [.accepted, .symbol], 1), + // (1, .symbol, 135), + // (22, [.accepted, .symbol], 135), + // (1, .symbol, 137), + // (22, [.accepted, .symbol], 137), + // (1, .symbol, 138), + // (22, [.accepted, .symbol], 138), + // (1, .symbol, 139), + // (22, [.accepted, .symbol], 139), + // (1, .symbol, 140), + // (22, [.accepted, .symbol], 140), + // (1, .symbol, 141), + // (22, [.accepted, .symbol], 141), + // (1, .symbol, 143), + // (22, [.accepted, .symbol], 143), + // + // // 147 + // + // (2, .symbol, 1), + // (9, .symbol, 1), + // (23, .symbol, 1), + // (40, [.accepted, .symbol], 1), + // (2, .symbol, 135), + // (9, .symbol, 135), + // (23, .symbol, 135), + // (40, [.accepted, .symbol], 135), + // (2, .symbol, 137), + // (9, .symbol, 137), + // (23, .symbol, 137), + // (40, [.accepted, .symbol], 137), + // (2, .symbol, 138), + // (9, .symbol, 138), + // (23, .symbol, 138), + // (40, [.accepted, .symbol], 138), + // + // // 148 + // + // (3, .symbol, 1), + // (6, .symbol, 1), + // (10, .symbol, 1), + // (15, .symbol, 1), + // (24, .symbol, 1), + // (31, .symbol, 1), + // (41, .symbol, 1), + // (56, [.accepted, .symbol], 1), + // (3, .symbol, 135), + // (6, .symbol, 135), + // (10, .symbol, 135), + // (15, .symbol, 135), + // (24, .symbol, 135), + // (31, .symbol, 135), + // (41, .symbol, 135), + // (56, [.accepted, .symbol], 135), + // + // // 149 + // + // (3, .symbol, 137), + // (6, .symbol, 137), + // (10, .symbol, 137), + // (15, .symbol, 137), + // (24, .symbol, 137), + // (31, .symbol, 137), + // (41, .symbol, 137), + // (56, [.accepted, .symbol], 137), + // (3, .symbol, 138), + // (6, .symbol, 138), + // (10, .symbol, 138), + // (15, .symbol, 138), + // (24, .symbol, 138), + // (31, .symbol, 138), + // (41, .symbol, 138), + // (56, [.accepted, .symbol], 138), + // + // // 150 + // + // (2, .symbol, 139), + // (9, .symbol, 139), + // (23, .symbol, 139), + // (40, [.accepted, .symbol], 139), + // (2, .symbol, 140), + // (9, .symbol, 140), + // (23, .symbol, 140), + // (40, [.accepted, .symbol], 140), + // (2, .symbol, 141), + // (9, .symbol, 141), + // (23, .symbol, 141), + // (40, [.accepted, .symbol], 141), + // (2, .symbol, 143), + // (9, .symbol, 143), + // (23, .symbol, 143), + // (40, [.accepted, .symbol], 143), + // + // // 151 + // + // (3, .symbol, 139), + // (6, .symbol, 139), + // (10, .symbol, 139), + // (15, .symbol, 139), + // (24, .symbol, 139), + // (31, .symbol, 139), + // (41, .symbol, 139), + // (56, [.accepted, .symbol], 139), + // (3, .symbol, 140), + // (6, .symbol, 140), + // (10, .symbol, 140), + // (15, .symbol, 140), + // (24, .symbol, 140), + // (31, .symbol, 140), + // (41, .symbol, 140), + // (56, [.accepted, .symbol], 140), + // + // // 152 + // + // (3, .symbol, 141), + // (6, .symbol, 141), + // (10, .symbol, 141), + // (15, .symbol, 141), + // (24, .symbol, 141), + // (31, .symbol, 141), + // (41, .symbol, 141), + // (56, [.accepted, .symbol], 141), + // (3, .symbol, 143), + // (6, .symbol, 143), + // (10, .symbol, 143), + // (15, .symbol, 143), + // (24, .symbol, 143), + // (31, .symbol, 143), + // (41, .symbol, 143), + // (56, [.accepted, .symbol], 143), + // + // // 153 + // + // (157, .none, 0), + // (158, .none, 0), + // (160, .none, 0), + // (161, .none, 0), + // (164, .none, 0), + // (165, .none, 0), + // (167, .none, 0), + // (168, .none, 0), + // (172, .none, 0), + // (173, .none, 0), + // (175, .none, 0), + // (177, .none, 0), + // (182, .none, 0), + // (185, .none, 0), + // (191, .none, 0), + // (207, .none, 0), + // + // // 154 + // + // (0, [.accepted, .symbol], 147), + // (0, [.accepted, .symbol], 149), + // (0, [.accepted, .symbol], 150), + // (0, [.accepted, .symbol], 151), + // (0, [.accepted, .symbol], 152), + // (0, [.accepted, .symbol], 155), + // (0, [.accepted, .symbol], 157), + // (0, [.accepted, .symbol], 158), + // (0, [.accepted, .symbol], 165), + // (0, [.accepted, .symbol], 166), + // (0, [.accepted, .symbol], 168), + // (0, [.accepted, .symbol], 174), + // (0, [.accepted, .symbol], 175), + // (0, [.accepted, .symbol], 180), + // (0, [.accepted, .symbol], 182), + // (0, [.accepted, .symbol], 183), + // + // // 155 + // + // (1, .symbol, 147), + // (22, [.accepted, .symbol], 147), + // (1, .symbol, 149), + // (22, [.accepted, .symbol], 149), + // (1, .symbol, 150), + // (22, [.accepted, .symbol], 150), + // (1, .symbol, 151), + // (22, [.accepted, .symbol], 151), + // (1, .symbol, 152), + // (22, [.accepted, .symbol], 152), + // (1, .symbol, 155), + // (22, [.accepted, .symbol], 155), + // (1, .symbol, 157), + // (22, [.accepted, .symbol], 157), + // (1, .symbol, 158), + // (22, [.accepted, .symbol], 158), + // + // // 156 + // + // (2, .symbol, 147), + // (9, .symbol, 147), + // (23, .symbol, 147), + // (40, [.accepted, .symbol], 147), + // (2, .symbol, 149), + // (9, .symbol, 149), + // (23, .symbol, 149), + // (40, [.accepted, .symbol], 149), + // (2, .symbol, 150), + // (9, .symbol, 150), + // (23, .symbol, 150), + // (40, [.accepted, .symbol], 150), + // (2, .symbol, 151), + // (9, .symbol, 151), + // (23, .symbol, 151), + // (40, [.accepted, .symbol], 151), + // + // // 157 + // + // (3, .symbol, 147), + // (6, .symbol, 147), + // (10, .symbol, 147), + // (15, .symbol, 147), + // (24, .symbol, 147), + // (31, .symbol, 147), + // (41, .symbol, 147), + // (56, [.accepted, .symbol], 147), + // (3, .symbol, 149), + // (6, .symbol, 149), + // (10, .symbol, 149), + // (15, .symbol, 149), + // (24, .symbol, 149), + // (31, .symbol, 149), + // (41, .symbol, 149), + // (56, [.accepted, .symbol], 149), + // + // // 158 + // + // (3, .symbol, 150), + // (6, .symbol, 150), + // (10, .symbol, 150), + // (15, .symbol, 150), + // (24, .symbol, 150), + // (31, .symbol, 150), + // (41, .symbol, 150), + // (56, [.accepted, .symbol], 150), + // (3, .symbol, 151), + // (6, .symbol, 151), + // (10, .symbol, 151), + // (15, .symbol, 151), + // (24, .symbol, 151), + // (31, .symbol, 151), + // (41, .symbol, 151), + // (56, [.accepted, .symbol], 151), + // + // // 159 + // + // (2, .symbol, 152), + // (9, .symbol, 152), + // (23, .symbol, 152), + // (40, [.accepted, .symbol], 152), + // (2, .symbol, 155), + // (9, .symbol, 155), + // (23, .symbol, 155), + // (40, [.accepted, .symbol], 155), + // (2, .symbol, 157), + // (9, .symbol, 157), + // (23, .symbol, 157), + // (40, [.accepted, .symbol], 157), + // (2, .symbol, 158), + // (9, .symbol, 158), + // (23, .symbol, 158), + // (40, [.accepted, .symbol], 158), + // + // // 160 + // + // (3, .symbol, 152), + // (6, .symbol, 152), + // (10, .symbol, 152), + // (15, .symbol, 152), + // (24, .symbol, 152), + // (31, .symbol, 152), + // (41, .symbol, 152), + // (56, [.accepted, .symbol], 152), + // (3, .symbol, 155), + // (6, .symbol, 155), + // (10, .symbol, 155), + // (15, .symbol, 155), + // (24, .symbol, 155), + // (31, .symbol, 155), + // (41, .symbol, 155), + // (56, [.accepted, .symbol], 155), + // + // // 161 + // + // (3, .symbol, 157), + // (6, .symbol, 157), + // (10, .symbol, 157), + // (15, .symbol, 157), + // (24, .symbol, 157), + // (31, .symbol, 157), + // (41, .symbol, 157), + // (56, [.accepted, .symbol], 157), + // (3, .symbol, 158), + // (6, .symbol, 158), + // (10, .symbol, 158), + // (15, .symbol, 158), + // (24, .symbol, 158), + // (31, .symbol, 158), + // (41, .symbol, 158), + // (56, [.accepted, .symbol], 158), + // + // // 162 + // + // (1, .symbol, 165), + // (22, [.accepted, .symbol], 165), + // (1, .symbol, 166), + // (22, [.accepted, .symbol], 166), + // (1, .symbol, 168), + // (22, [.accepted, .symbol], 168), + // (1, .symbol, 174), + // (22, [.accepted, .symbol], 174), + // (1, .symbol, 175), + // (22, [.accepted, .symbol], 175), + // (1, .symbol, 180), + // (22, [.accepted, .symbol], 180), + // (1, .symbol, 182), + // (22, [.accepted, .symbol], 182), + // (1, .symbol, 183), + // (22, [.accepted, .symbol], 183), + // + // // 163 + // + // (2, .symbol, 165), + // (9, .symbol, 165), + // (23, .symbol, 165), + // (40, [.accepted, .symbol], 165), + // (2, .symbol, 166), + // (9, .symbol, 166), + // (23, .symbol, 166), + // (40, [.accepted, .symbol], 166), + // (2, .symbol, 168), + // (9, .symbol, 168), + // (23, .symbol, 168), + // (40, [.accepted, .symbol], 168), + // (2, .symbol, 174), + // (9, .symbol, 174), + // (23, .symbol, 174), + // (40, [.accepted, .symbol], 174), + // + // // 164 + // + // (3, .symbol, 165), + // (6, .symbol, 165), + // (10, .symbol, 165), + // (15, .symbol, 165), + // (24, .symbol, 165), + // (31, .symbol, 165), + // (41, .symbol, 165), + // (56, [.accepted, .symbol], 165), + // (3, .symbol, 166), + // (6, .symbol, 166), + // (10, .symbol, 166), + // (15, .symbol, 166), + // (24, .symbol, 166), + // (31, .symbol, 166), + // (41, .symbol, 166), + // (56, [.accepted, .symbol], 166), + // + // // 165 + // + // (3, .symbol, 168), + // (6, .symbol, 168), + // (10, .symbol, 168), + // (15, .symbol, 168), + // (24, .symbol, 168), + // (31, .symbol, 168), + // (41, .symbol, 168), + // (56, [.accepted, .symbol], 168), + // (3, .symbol, 174), + // (6, .symbol, 174), + // (10, .symbol, 174), + // (15, .symbol, 174), + // (24, .symbol, 174), + // (31, .symbol, 174), + // (41, .symbol, 174), + // (56, [.accepted, .symbol], 174), + // + // // 166 + // + // (2, .symbol, 175), + // (9, .symbol, 175), + // (23, .symbol, 175), + // (40, [.accepted, .symbol], 175), + // (2, .symbol, 180), + // (9, .symbol, 180), + // (23, .symbol, 180), + // (40, [.accepted, .symbol], 180), + // (2, .symbol, 182), + // (9, .symbol, 182), + // (23, .symbol, 182), + // (40, [.accepted, .symbol], 182), + // (2, .symbol, 183), + // (9, .symbol, 183), + // (23, .symbol, 183), + // (40, [.accepted, .symbol], 183), + // + // // 167 + // + // (3, .symbol, 175), + // (6, .symbol, 175), + // (10, .symbol, 175), + // (15, .symbol, 175), + // (24, .symbol, 175), + // (31, .symbol, 175), + // (41, .symbol, 175), + // (56, [.accepted, .symbol], 175), + // (3, .symbol, 180), + // (6, .symbol, 180), + // (10, .symbol, 180), + // (15, .symbol, 180), + // (24, .symbol, 180), + // (31, .symbol, 180), + // (41, .symbol, 180), + // (56, [.accepted, .symbol], 180), + // + // // 168 + // + // (3, .symbol, 182), + // (6, .symbol, 182), + // (10, .symbol, 182), + // (15, .symbol, 182), + // (24, .symbol, 182), + // (31, .symbol, 182), + // (41, .symbol, 182), + // (56, [.accepted, .symbol], 182), + // (3, .symbol, 183), + // (6, .symbol, 183), + // (10, .symbol, 183), + // (15, .symbol, 183), + // (24, .symbol, 183), + // (31, .symbol, 183), + // (41, .symbol, 183), + // (56, [.accepted, .symbol], 183), + // + // // 169 + // + // (0, [.accepted, .symbol], 188), + // (0, [.accepted, .symbol], 191), + // (0, [.accepted, .symbol], 197), + // (0, [.accepted, .symbol], 231), + // (0, [.accepted, .symbol], 239), + // (176, .none, 0), + // (178, .none, 0), + // (179, .none, 0), + // (183, .none, 0), + // (184, .none, 0), + // (186, .none, 0), + // (187, .none, 0), + // (192, .none, 0), + // (199, .none, 0), + // (208, .none, 0), + // (223, .none, 0), + // + // // 170 + // + // (1, .symbol, 188), + // (22, [.accepted, .symbol], 188), + // (1, .symbol, 191), + // (22, [.accepted, .symbol], 191), + // (1, .symbol, 197), + // (22, [.accepted, .symbol], 197), + // (1, .symbol, 231), + // (22, [.accepted, .symbol], 231), + // (1, .symbol, 239), + // (22, [.accepted, .symbol], 239), + // (0, [.accepted, .symbol], 9), + // (0, [.accepted, .symbol], 142), + // (0, [.accepted, .symbol], 144), + // (0, [.accepted, .symbol], 145), + // (0, [.accepted, .symbol], 148), + // (0, [.accepted, .symbol], 159), + // + // // 171 + // + // (2, .symbol, 188), + // (9, .symbol, 188), + // (23, .symbol, 188), + // (40, [.accepted, .symbol], 188), + // (2, .symbol, 191), + // (9, .symbol, 191), + // (23, .symbol, 191), + // (40, [.accepted, .symbol], 191), + // (2, .symbol, 197), + // (9, .symbol, 197), + // (23, .symbol, 197), + // (40, [.accepted, .symbol], 197), + // (2, .symbol, 231), + // (9, .symbol, 231), + // (23, .symbol, 231), + // (40, [.accepted, .symbol], 231), + // + // // 172 + // + // (3, .symbol, 188), + // (6, .symbol, 188), + // (10, .symbol, 188), + // (15, .symbol, 188), + // (24, .symbol, 188), + // (31, .symbol, 188), + // (41, .symbol, 188), + // (56, [.accepted, .symbol], 188), + // (3, .symbol, 191), + // (6, .symbol, 191), + // (10, .symbol, 191), + // (15, .symbol, 191), + // (24, .symbol, 191), + // (31, .symbol, 191), + // (41, .symbol, 191), + // (56, [.accepted, .symbol], 191), + // + // // 173 + // + // (3, .symbol, 197), + // (6, .symbol, 197), + // (10, .symbol, 197), + // (15, .symbol, 197), + // (24, .symbol, 197), + // (31, .symbol, 197), + // (41, .symbol, 197), + // (56, [.accepted, .symbol], 197), + // (3, .symbol, 231), + // (6, .symbol, 231), + // (10, .symbol, 231), + // (15, .symbol, 231), + // (24, .symbol, 231), + // (31, .symbol, 231), + // (41, .symbol, 231), + // (56, [.accepted, .symbol], 231), + // + // // 174 + // + // (2, .symbol, 239), + // (9, .symbol, 239), + // (23, .symbol, 239), + // (40, [.accepted, .symbol], 239), + // (1, .symbol, 9), + // (22, [.accepted, .symbol], 9), + // (1, .symbol, 142), + // (22, [.accepted, .symbol], 142), + // (1, .symbol, 144), + // (22, [.accepted, .symbol], 144), + // (1, .symbol, 145), + // (22, [.accepted, .symbol], 145), + // (1, .symbol, 148), + // (22, [.accepted, .symbol], 148), + // (1, .symbol, 159), + // (22, [.accepted, .symbol], 159), + // + // // 175 + // + // (3, .symbol, 239), + // (6, .symbol, 239), + // (10, .symbol, 239), + // (15, .symbol, 239), + // (24, .symbol, 239), + // (31, .symbol, 239), + // (41, .symbol, 239), + // (56, [.accepted, .symbol], 239), + // (2, .symbol, 9), + // (9, .symbol, 9), + // (23, .symbol, 9), + // (40, [.accepted, .symbol], 9), + // (2, .symbol, 142), + // (9, .symbol, 142), + // (23, .symbol, 142), + // (40, [.accepted, .symbol], 142), + // + // // 176 + // + // (3, .symbol, 9), + // (6, .symbol, 9), + // (10, .symbol, 9), + // (15, .symbol, 9), + // (24, .symbol, 9), + // (31, .symbol, 9), + // (41, .symbol, 9), + // (56, [.accepted, .symbol], 9), + // (3, .symbol, 142), + // (6, .symbol, 142), + // (10, .symbol, 142), + // (15, .symbol, 142), + // (24, .symbol, 142), + // (31, .symbol, 142), + // (41, .symbol, 142), + // (56, [.accepted, .symbol], 142), + // + // // 177 + // + // (2, .symbol, 144), + // (9, .symbol, 144), + // (23, .symbol, 144), + // (40, [.accepted, .symbol], 144), + // (2, .symbol, 145), + // (9, .symbol, 145), + // (23, .symbol, 145), + // (40, [.accepted, .symbol], 145), + // (2, .symbol, 148), + // (9, .symbol, 148), + // (23, .symbol, 148), + // (40, [.accepted, .symbol], 148), + // (2, .symbol, 159), + // (9, .symbol, 159), + // (23, .symbol, 159), + // (40, [.accepted, .symbol], 159), + // + // // 178 + // + // (3, .symbol, 144), + // (6, .symbol, 144), + // (10, .symbol, 144), + // (15, .symbol, 144), + // (24, .symbol, 144), + // (31, .symbol, 144), + // (41, .symbol, 144), + // (56, [.accepted, .symbol], 144), + // (3, .symbol, 145), + // (6, .symbol, 145), + // (10, .symbol, 145), + // (15, .symbol, 145), + // (24, .symbol, 145), + // (31, .symbol, 145), + // (41, .symbol, 145), + // (56, [.accepted, .symbol], 145), + // + // // 179 + // + // (3, .symbol, 148), + // (6, .symbol, 148), + // (10, .symbol, 148), + // (15, .symbol, 148), + // (24, .symbol, 148), + // (31, .symbol, 148), + // (41, .symbol, 148), + // (56, [.accepted, .symbol], 148), + // (3, .symbol, 159), + // (6, .symbol, 159), + // (10, .symbol, 159), + // (15, .symbol, 159), + // (24, .symbol, 159), + // (31, .symbol, 159), + // (41, .symbol, 159), + // (56, [.accepted, .symbol], 159), + // + // // 180 + // + // (0, [.accepted, .symbol], 171), + // (0, [.accepted, .symbol], 206), + // (0, [.accepted, .symbol], 215), + // (0, [.accepted, .symbol], 225), + // (0, [.accepted, .symbol], 236), + // (0, [.accepted, .symbol], 237), + // (188, .none, 0), + // (189, .none, 0), + // (193, .none, 0), + // (196, .none, 0), + // (200, .none, 0), + // (203, .none, 0), + // (209, .none, 0), + // (216, .none, 0), + // (224, .none, 0), + // (238, .none, 0), + // + // // 181 + // + // (1, .symbol, 171), + // (22, [.accepted, .symbol], 171), + // (1, .symbol, 206), + // (22, [.accepted, .symbol], 206), + // (1, .symbol, 215), + // (22, [.accepted, .symbol], 215), + // (1, .symbol, 225), + // (22, [.accepted, .symbol], 225), + // (1, .symbol, 236), + // (22, [.accepted, .symbol], 236), + // (1, .symbol, 237), + // (22, [.accepted, .symbol], 237), + // (0, [.accepted, .symbol], 199), + // (0, [.accepted, .symbol], 207), + // (0, [.accepted, .symbol], 234), + // (0, [.accepted, .symbol], 235), + // + // // 182 + // + // (2, .symbol, 171), + // (9, .symbol, 171), + // (23, .symbol, 171), + // (40, [.accepted, .symbol], 171), + // (2, .symbol, 206), + // (9, .symbol, 206), + // (23, .symbol, 206), + // (40, [.accepted, .symbol], 206), + // (2, .symbol, 215), + // (9, .symbol, 215), + // (23, .symbol, 215), + // (40, [.accepted, .symbol], 215), + // (2, .symbol, 225), + // (9, .symbol, 225), + // (23, .symbol, 225), + // (40, [.accepted, .symbol], 225), + // + // // 183 + // + // (3, .symbol, 171), + // (6, .symbol, 171), + // (10, .symbol, 171), + // (15, .symbol, 171), + // (24, .symbol, 171), + // (31, .symbol, 171), + // (41, .symbol, 171), + // (56, [.accepted, .symbol], 171), + // (3, .symbol, 206), + // (6, .symbol, 206), + // (10, .symbol, 206), + // (15, .symbol, 206), + // (24, .symbol, 206), + // (31, .symbol, 206), + // (41, .symbol, 206), + // (56, [.accepted, .symbol], 206), + // + // // 184 + // + // (3, .symbol, 215), + // (6, .symbol, 215), + // (10, .symbol, 215), + // (15, .symbol, 215), + // (24, .symbol, 215), + // (31, .symbol, 215), + // (41, .symbol, 215), + // (56, [.accepted, .symbol], 215), + // (3, .symbol, 225), + // (6, .symbol, 225), + // (10, .symbol, 225), + // (15, .symbol, 225), + // (24, .symbol, 225), + // (31, .symbol, 225), + // (41, .symbol, 225), + // (56, [.accepted, .symbol], 225), + // + // // 185 + // + // (2, .symbol, 236), + // (9, .symbol, 236), + // (23, .symbol, 236), + // (40, [.accepted, .symbol], 236), + // (2, .symbol, 237), + // (9, .symbol, 237), + // (23, .symbol, 237), + // (40, [.accepted, .symbol], 237), + // (1, .symbol, 199), + // (22, [.accepted, .symbol], 199), + // (1, .symbol, 207), + // (22, [.accepted, .symbol], 207), + // (1, .symbol, 234), + // (22, [.accepted, .symbol], 234), + // (1, .symbol, 235), + // (22, [.accepted, .symbol], 235), + // + // // 186 + // + // (3, .symbol, 236), + // (6, .symbol, 236), + // (10, .symbol, 236), + // (15, .symbol, 236), + // (24, .symbol, 236), + // (31, .symbol, 236), + // (41, .symbol, 236), + // (56, [.accepted, .symbol], 236), + // (3, .symbol, 237), + // (6, .symbol, 237), + // (10, .symbol, 237), + // (15, .symbol, 237), + // (24, .symbol, 237), + // (31, .symbol, 237), + // (41, .symbol, 237), + // (56, [.accepted, .symbol], 237), + // + // // 187 + // + // (2, .symbol, 199), + // (9, .symbol, 199), + // (23, .symbol, 199), + // (40, [.accepted, .symbol], 199), + // (2, .symbol, 207), + // (9, .symbol, 207), + // (23, .symbol, 207), + // (40, [.accepted, .symbol], 207), + // (2, .symbol, 234), + // (9, .symbol, 234), + // (23, .symbol, 234), + // (40, [.accepted, .symbol], 234), + // (2, .symbol, 235), + // (9, .symbol, 235), + // (23, .symbol, 235), + // (40, [.accepted, .symbol], 235), + // + // // 188 + // + // (3, .symbol, 199), + // (6, .symbol, 199), + // (10, .symbol, 199), + // (15, .symbol, 199), + // (24, .symbol, 199), + // (31, .symbol, 199), + // (41, .symbol, 199), + // (56, [.accepted, .symbol], 199), + // (3, .symbol, 207), + // (6, .symbol, 207), + // (10, .symbol, 207), + // (15, .symbol, 207), + // (24, .symbol, 207), + // (31, .symbol, 207), + // (41, .symbol, 207), + // (56, [.accepted, .symbol], 207), + // + // // 189 + // + // (3, .symbol, 234), + // (6, .symbol, 234), + // (10, .symbol, 234), + // (15, .symbol, 234), + // (24, .symbol, 234), + // (31, .symbol, 234), + // (41, .symbol, 234), + // (56, [.accepted, .symbol], 234), + // (3, .symbol, 235), + // (6, .symbol, 235), + // (10, .symbol, 235), + // (15, .symbol, 235), + // (24, .symbol, 235), + // (31, .symbol, 235), + // (41, .symbol, 235), + // (56, [.accepted, .symbol], 235), + // + // // 190 + // + // (194, .none, 0), + // (195, .none, 0), + // (197, .none, 0), + // (198, .none, 0), + // (201, .none, 0), + // (202, .none, 0), + // (204, .none, 0), + // (205, .none, 0), + // (210, .none, 0), + // (213, .none, 0), + // (217, .none, 0), + // (220, .none, 0), + // (225, .none, 0), + // (231, .none, 0), + // (239, .none, 0), + // (246, .none, 0), + // + // // 191 + // + // (0, [.accepted, .symbol], 192), + // (0, [.accepted, .symbol], 193), + // (0, [.accepted, .symbol], 200), + // (0, [.accepted, .symbol], 201), + // (0, [.accepted, .symbol], 202), + // (0, [.accepted, .symbol], 205), + // (0, [.accepted, .symbol], 210), + // (0, [.accepted, .symbol], 213), + // (0, [.accepted, .symbol], 218), + // (0, [.accepted, .symbol], 219), + // (0, [.accepted, .symbol], 238), + // (0, [.accepted, .symbol], 240), + // (0, [.accepted, .symbol], 242), + // (0, [.accepted, .symbol], 243), + // (0, [.accepted, .symbol], 255), + // (206, .none, 0), + // + // // 192 + // + // (1, .symbol, 192), + // (22, [.accepted, .symbol], 192), + // (1, .symbol, 193), + // (22, [.accepted, .symbol], 193), + // (1, .symbol, 200), + // (22, [.accepted, .symbol], 200), + // (1, .symbol, 201), + // (22, [.accepted, .symbol], 201), + // (1, .symbol, 202), + // (22, [.accepted, .symbol], 202), + // (1, .symbol, 205), + // (22, [.accepted, .symbol], 205), + // (1, .symbol, 210), + // (22, [.accepted, .symbol], 210), + // (1, .symbol, 213), + // (22, [.accepted, .symbol], 213), + // + // // 193 + // + // (2, .symbol, 192), + // (9, .symbol, 192), + // (23, .symbol, 192), + // (40, [.accepted, .symbol], 192), + // (2, .symbol, 193), + // (9, .symbol, 193), + // (23, .symbol, 193), + // (40, [.accepted, .symbol], 193), + // (2, .symbol, 200), + // (9, .symbol, 200), + // (23, .symbol, 200), + // (40, [.accepted, .symbol], 200), + // (2, .symbol, 201), + // (9, .symbol, 201), + // (23, .symbol, 201), + // (40, [.accepted, .symbol], 201), + // + // // 194 + // + // (3, .symbol, 192), + // (6, .symbol, 192), + // (10, .symbol, 192), + // (15, .symbol, 192), + // (24, .symbol, 192), + // (31, .symbol, 192), + // (41, .symbol, 192), + // (56, [.accepted, .symbol], 192), + // (3, .symbol, 193), + // (6, .symbol, 193), + // (10, .symbol, 193), + // (15, .symbol, 193), + // (24, .symbol, 193), + // (31, .symbol, 193), + // (41, .symbol, 193), + // (56, [.accepted, .symbol], 193), + // + // // 195 + // + // (3, .symbol, 200), + // (6, .symbol, 200), + // (10, .symbol, 200), + // (15, .symbol, 200), + // (24, .symbol, 200), + // (31, .symbol, 200), + // (41, .symbol, 200), + // (56, [.accepted, .symbol], 200), + // (3, .symbol, 201), + // (6, .symbol, 201), + // (10, .symbol, 201), + // (15, .symbol, 201), + // (24, .symbol, 201), + // (31, .symbol, 201), + // (41, .symbol, 201), + // (56, [.accepted, .symbol], 201), + // + // // 196 + // + // (2, .symbol, 202), + // (9, .symbol, 202), + // (23, .symbol, 202), + // (40, [.accepted, .symbol], 202), + // (2, .symbol, 205), + // (9, .symbol, 205), + // (23, .symbol, 205), + // (40, [.accepted, .symbol], 205), + // (2, .symbol, 210), + // (9, .symbol, 210), + // (23, .symbol, 210), + // (40, [.accepted, .symbol], 210), + // (2, .symbol, 213), + // (9, .symbol, 213), + // (23, .symbol, 213), + // (40, [.accepted, .symbol], 213), + // + // // 197 + // + // (3, .symbol, 202), + // (6, .symbol, 202), + // (10, .symbol, 202), + // (15, .symbol, 202), + // (24, .symbol, 202), + // (31, .symbol, 202), + // (41, .symbol, 202), + // (56, [.accepted, .symbol], 202), + // (3, .symbol, 205), + // (6, .symbol, 205), + // (10, .symbol, 205), + // (15, .symbol, 205), + // (24, .symbol, 205), + // (31, .symbol, 205), + // (41, .symbol, 205), + // (56, [.accepted, .symbol], 205), + // + // // 198 + // + // (3, .symbol, 210), + // (6, .symbol, 210), + // (10, .symbol, 210), + // (15, .symbol, 210), + // (24, .symbol, 210), + // (31, .symbol, 210), + // (41, .symbol, 210), + // (56, [.accepted, .symbol], 210), + // (3, .symbol, 213), + // (6, .symbol, 213), + // (10, .symbol, 213), + // (15, .symbol, 213), + // (24, .symbol, 213), + // (31, .symbol, 213), + // (41, .symbol, 213), + // (56, [.accepted, .symbol], 213), + // + // // 199 + // + // (1, .symbol, 218), + // (22, [.accepted, .symbol], 218), + // (1, .symbol, 219), + // (22, [.accepted, .symbol], 219), + // (1, .symbol, 238), + // (22, [.accepted, .symbol], 238), + // (1, .symbol, 240), + // (22, [.accepted, .symbol], 240), + // (1, .symbol, 242), + // (22, [.accepted, .symbol], 242), + // (1, .symbol, 243), + // (22, [.accepted, .symbol], 243), + // (1, .symbol, 255), + // (22, [.accepted, .symbol], 255), + // (0, [.accepted, .symbol], 203), + // (0, [.accepted, .symbol], 204), + // + // // 200 + // + // (2, .symbol, 218), + // (9, .symbol, 218), + // (23, .symbol, 218), + // (40, [.accepted, .symbol], 218), + // (2, .symbol, 219), + // (9, .symbol, 219), + // (23, .symbol, 219), + // (40, [.accepted, .symbol], 219), + // (2, .symbol, 238), + // (9, .symbol, 238), + // (23, .symbol, 238), + // (40, [.accepted, .symbol], 238), + // (2, .symbol, 240), + // (9, .symbol, 240), + // (23, .symbol, 240), + // (40, [.accepted, .symbol], 240), + // + // // 201 + // + // (3, .symbol, 218), + // (6, .symbol, 218), + // (10, .symbol, 218), + // (15, .symbol, 218), + // (24, .symbol, 218), + // (31, .symbol, 218), + // (41, .symbol, 218), + // (56, [.accepted, .symbol], 218), + // (3, .symbol, 219), + // (6, .symbol, 219), + // (10, .symbol, 219), + // (15, .symbol, 219), + // (24, .symbol, 219), + // (31, .symbol, 219), + // (41, .symbol, 219), + // (56, [.accepted, .symbol], 219), + // + // // 202 + // + // (3, .symbol, 238), + // (6, .symbol, 238), + // (10, .symbol, 238), + // (15, .symbol, 238), + // (24, .symbol, 238), + // (31, .symbol, 238), + // (41, .symbol, 238), + // (56, [.accepted, .symbol], 238), + // (3, .symbol, 240), + // (6, .symbol, 240), + // (10, .symbol, 240), + // (15, .symbol, 240), + // (24, .symbol, 240), + // (31, .symbol, 240), + // (41, .symbol, 240), + // (56, [.accepted, .symbol], 240), + // + // // 203 + // + // (2, .symbol, 242), + // (9, .symbol, 242), + // (23, .symbol, 242), + // (40, [.accepted, .symbol], 242), + // (2, .symbol, 243), + // (9, .symbol, 243), + // (23, .symbol, 243), + // (40, [.accepted, .symbol], 243), + // (2, .symbol, 255), + // (9, .symbol, 255), + // (23, .symbol, 255), + // (40, [.accepted, .symbol], 255), + // (1, .symbol, 203), + // (22, [.accepted, .symbol], 203), + // (1, .symbol, 204), + // (22, [.accepted, .symbol], 204), + // + // // 204 + // + // (3, .symbol, 242), + // (6, .symbol, 242), + // (10, .symbol, 242), + // (15, .symbol, 242), + // (24, .symbol, 242), + // (31, .symbol, 242), + // (41, .symbol, 242), + // (56, [.accepted, .symbol], 242), + // (3, .symbol, 243), + // (6, .symbol, 243), + // (10, .symbol, 243), + // (15, .symbol, 243), + // (24, .symbol, 243), + // (31, .symbol, 243), + // (41, .symbol, 243), + // (56, [.accepted, .symbol], 243), + // + // // 205 + // + // (3, .symbol, 255), + // (6, .symbol, 255), + // (10, .symbol, 255), + // (15, .symbol, 255), + // (24, .symbol, 255), + // (31, .symbol, 255), + // (41, .symbol, 255), + // (56, [.accepted, .symbol], 255), + // (2, .symbol, 203), + // (9, .symbol, 203), + // (23, .symbol, 203), + // (40, [.accepted, .symbol], 203), + // (2, .symbol, 204), + // (9, .symbol, 204), + // (23, .symbol, 204), + // (40, [.accepted, .symbol], 204), + // + // // 206 + // + // (3, .symbol, 203), + // (6, .symbol, 203), + // (10, .symbol, 203), + // (15, .symbol, 203), + // (24, .symbol, 203), + // (31, .symbol, 203), + // (41, .symbol, 203), + // (56, [.accepted, .symbol], 203), + // (3, .symbol, 204), + // (6, .symbol, 204), + // (10, .symbol, 204), + // (15, .symbol, 204), + // (24, .symbol, 204), + // (31, .symbol, 204), + // (41, .symbol, 204), + // (56, [.accepted, .symbol], 204), + // + // // 207 + // + // (211, .none, 0), + // (212, .none, 0), + // (214, .none, 0), + // (215, .none, 0), + // (218, .none, 0), + // (219, .none, 0), + // (221, .none, 0), + // (222, .none, 0), + // (226, .none, 0), + // (228, .none, 0), + // (232, .none, 0), + // (235, .none, 0), + // (240, .none, 0), + // (243, .none, 0), + // (247, .none, 0), + // (250, .none, 0), + // + // // 208 + // + // (0, [.accepted, .symbol], 211), + // (0, [.accepted, .symbol], 212), + // (0, [.accepted, .symbol], 214), + // (0, [.accepted, .symbol], 221), + // (0, [.accepted, .symbol], 222), + // (0, [.accepted, .symbol], 223), + // (0, [.accepted, .symbol], 241), + // (0, [.accepted, .symbol], 244), + // (0, [.accepted, .symbol], 245), + // (0, [.accepted, .symbol], 246), + // (0, [.accepted, .symbol], 247), + // (0, [.accepted, .symbol], 248), + // (0, [.accepted, .symbol], 250), + // (0, [.accepted, .symbol], 251), + // (0, [.accepted, .symbol], 252), + // (0, [.accepted, .symbol], 253), + // + // // 209 + // + // (1, .symbol, 211), + // (22, [.accepted, .symbol], 211), + // (1, .symbol, 212), + // (22, [.accepted, .symbol], 212), + // (1, .symbol, 214), + // (22, [.accepted, .symbol], 214), + // (1, .symbol, 221), + // (22, [.accepted, .symbol], 221), + // (1, .symbol, 222), + // (22, [.accepted, .symbol], 222), + // (1, .symbol, 223), + // (22, [.accepted, .symbol], 223), + // (1, .symbol, 241), + // (22, [.accepted, .symbol], 241), + // (1, .symbol, 244), + // (22, [.accepted, .symbol], 244), + // + // // 210 + // + // (2, .symbol, 211), + // (9, .symbol, 211), + // (23, .symbol, 211), + // (40, [.accepted, .symbol], 211), + // (2, .symbol, 212), + // (9, .symbol, 212), + // (23, .symbol, 212), + // (40, [.accepted, .symbol], 212), + // (2, .symbol, 214), + // (9, .symbol, 214), + // (23, .symbol, 214), + // (40, [.accepted, .symbol], 214), + // (2, .symbol, 221), + // (9, .symbol, 221), + // (23, .symbol, 221), + // (40, [.accepted, .symbol], 221), + // + // // 211 + // + // (3, .symbol, 211), + // (6, .symbol, 211), + // (10, .symbol, 211), + // (15, .symbol, 211), + // (24, .symbol, 211), + // (31, .symbol, 211), + // (41, .symbol, 211), + // (56, [.accepted, .symbol], 211), + // (3, .symbol, 212), + // (6, .symbol, 212), + // (10, .symbol, 212), + // (15, .symbol, 212), + // (24, .symbol, 212), + // (31, .symbol, 212), + // (41, .symbol, 212), + // (56, [.accepted, .symbol], 212), + // + // // 212 + // + // (3, .symbol, 214), + // (6, .symbol, 214), + // (10, .symbol, 214), + // (15, .symbol, 214), + // (24, .symbol, 214), + // (31, .symbol, 214), + // (41, .symbol, 214), + // (56, [.accepted, .symbol], 214), + // (3, .symbol, 221), + // (6, .symbol, 221), + // (10, .symbol, 221), + // (15, .symbol, 221), + // (24, .symbol, 221), + // (31, .symbol, 221), + // (41, .symbol, 221), + // (56, [.accepted, .symbol], 221), + // + // // 213 + // + // (2, .symbol, 222), + // (9, .symbol, 222), + // (23, .symbol, 222), + // (40, [.accepted, .symbol], 222), + // (2, .symbol, 223), + // (9, .symbol, 223), + // (23, .symbol, 223), + // (40, [.accepted, .symbol], 223), + // (2, .symbol, 241), + // (9, .symbol, 241), + // (23, .symbol, 241), + // (40, [.accepted, .symbol], 241), + // (2, .symbol, 244), + // (9, .symbol, 244), + // (23, .symbol, 244), + // (40, [.accepted, .symbol], 244), + // + // // 214 + // + // (3, .symbol, 222), + // (6, .symbol, 222), + // (10, .symbol, 222), + // (15, .symbol, 222), + // (24, .symbol, 222), + // (31, .symbol, 222), + // (41, .symbol, 222), + // (56, [.accepted, .symbol], 222), + // (3, .symbol, 223), + // (6, .symbol, 223), + // (10, .symbol, 223), + // (15, .symbol, 223), + // (24, .symbol, 223), + // (31, .symbol, 223), + // (41, .symbol, 223), + // (56, [.accepted, .symbol], 223), + // + // // 215 + // + // (3, .symbol, 241), + // (6, .symbol, 241), + // (10, .symbol, 241), + // (15, .symbol, 241), + // (24, .symbol, 241), + // (31, .symbol, 241), + // (41, .symbol, 241), + // (56, [.accepted, .symbol], 241), + // (3, .symbol, 244), + // (6, .symbol, 244), + // (10, .symbol, 244), + // (15, .symbol, 244), + // (24, .symbol, 244), + // (31, .symbol, 244), + // (41, .symbol, 244), + // (56, [.accepted, .symbol], 244), + // + // // 216 + // + // (1, .symbol, 245), + // (22, [.accepted, .symbol], 245), + // (1, .symbol, 246), + // (22, [.accepted, .symbol], 246), + // (1, .symbol, 247), + // (22, [.accepted, .symbol], 247), + // (1, .symbol, 248), + // (22, [.accepted, .symbol], 248), + // (1, .symbol, 250), + // (22, [.accepted, .symbol], 250), + // (1, .symbol, 251), + // (22, [.accepted, .symbol], 251), + // (1, .symbol, 252), + // (22, [.accepted, .symbol], 252), + // (1, .symbol, 253), + // (22, [.accepted, .symbol], 253), + // + // // 217 + // + // (2, .symbol, 245), + // (9, .symbol, 245), + // (23, .symbol, 245), + // (40, [.accepted, .symbol], 245), + // (2, .symbol, 246), + // (9, .symbol, 246), + // (23, .symbol, 246), + // (40, [.accepted, .symbol], 246), + // (2, .symbol, 247), + // (9, .symbol, 247), + // (23, .symbol, 247), + // (40, [.accepted, .symbol], 247), + // (2, .symbol, 248), + // (9, .symbol, 248), + // (23, .symbol, 248), + // (40, [.accepted, .symbol], 248), + // + // // 218 + // + // (3, .symbol, 245), + // (6, .symbol, 245), + // (10, .symbol, 245), + // (15, .symbol, 245), + // (24, .symbol, 245), + // (31, .symbol, 245), + // (41, .symbol, 245), + // (56, [.accepted, .symbol], 245), + // (3, .symbol, 246), + // (6, .symbol, 246), + // (10, .symbol, 246), + // (15, .symbol, 246), + // (24, .symbol, 246), + // (31, .symbol, 246), + // (41, .symbol, 246), + // (56, [.accepted, .symbol], 246), + // + // // 219 + // + // (3, .symbol, 247), + // (6, .symbol, 247), + // (10, .symbol, 247), + // (15, .symbol, 247), + // (24, .symbol, 247), + // (31, .symbol, 247), + // (41, .symbol, 247), + // (56, [.accepted, .symbol], 247), + // (3, .symbol, 248), + // (6, .symbol, 248), + // (10, .symbol, 248), + // (15, .symbol, 248), + // (24, .symbol, 248), + // (31, .symbol, 248), + // (41, .symbol, 248), + // (56, [.accepted, .symbol], 248), + // + // // 220 + // + // (2, .symbol, 250), + // (9, .symbol, 250), + // (23, .symbol, 250), + // (40, [.accepted, .symbol], 250), + // (2, .symbol, 251), + // (9, .symbol, 251), + // (23, .symbol, 251), + // (40, [.accepted, .symbol], 251), + // (2, .symbol, 252), + // (9, .symbol, 252), + // (23, .symbol, 252), + // (40, [.accepted, .symbol], 252), + // (2, .symbol, 253), + // (9, .symbol, 253), + // (23, .symbol, 253), + // (40, [.accepted, .symbol], 253), + // + // // 221 + // + // (3, .symbol, 250), + // (6, .symbol, 250), + // (10, .symbol, 250), + // (15, .symbol, 250), + // (24, .symbol, 250), + // (31, .symbol, 250), + // (41, .symbol, 250), + // (56, [.accepted, .symbol], 250), + // (3, .symbol, 251), + // (6, .symbol, 251), + // (10, .symbol, 251), + // (15, .symbol, 251), + // (24, .symbol, 251), + // (31, .symbol, 251), + // (41, .symbol, 251), + // (56, [.accepted, .symbol], 251), + // + // // 222 + // + // (3, .symbol, 252), + // (6, .symbol, 252), + // (10, .symbol, 252), + // (15, .symbol, 252), + // (24, .symbol, 252), + // (31, .symbol, 252), + // (41, .symbol, 252), + // (56, [.accepted, .symbol], 252), + // (3, .symbol, 253), + // (6, .symbol, 253), + // (10, .symbol, 253), + // (15, .symbol, 253), + // (24, .symbol, 253), + // (31, .symbol, 253), + // (41, .symbol, 253), + // (56, [.accepted, .symbol], 253), + // + // // 223 + // + // (0, [.accepted, .symbol], 254), + // (227, .none, 0), + // (229, .none, 0), + // (230, .none, 0), + // (233, .none, 0), + // (234, .none, 0), + // (236, .none, 0), + // (237, .none, 0), + // (241, .none, 0), + // (242, .none, 0), + // (244, .none, 0), + // (245, .none, 0), + // (248, .none, 0), + // (249, .none, 0), + // (251, .none, 0), + // (252, .none, 0), + // + // // 224 + // + // (1, .symbol, 254), + // (22, [.accepted, .symbol], 254), + // (0, [.accepted, .symbol], 2), + // (0, [.accepted, .symbol], 3), + // (0, [.accepted, .symbol], 4), + // (0, [.accepted, .symbol], 5), + // (0, [.accepted, .symbol], 6), + // (0, [.accepted, .symbol], 7), + // (0, [.accepted, .symbol], 8), + // (0, [.accepted, .symbol], 11), + // (0, [.accepted, .symbol], 12), + // (0, [.accepted, .symbol], 14), + // (0, [.accepted, .symbol], 15), + // (0, [.accepted, .symbol], 16), + // (0, [.accepted, .symbol], 17), + // (0, [.accepted, .symbol], 18), + // + // // 225 + // + // (2, .symbol, 254), + // (9, .symbol, 254), + // (23, .symbol, 254), + // (40, [.accepted, .symbol], 254), + // (1, .symbol, 2), + // (22, [.accepted, .symbol], 2), + // (1, .symbol, 3), + // (22, [.accepted, .symbol], 3), + // (1, .symbol, 4), + // (22, [.accepted, .symbol], 4), + // (1, .symbol, 5), + // (22, [.accepted, .symbol], 5), + // (1, .symbol, 6), + // (22, [.accepted, .symbol], 6), + // (1, .symbol, 7), + // (22, [.accepted, .symbol], 7), + // + // // 226 + // + // (3, .symbol, 254), + // (6, .symbol, 254), + // (10, .symbol, 254), + // (15, .symbol, 254), + // (24, .symbol, 254), + // (31, .symbol, 254), + // (41, .symbol, 254), + // (56, [.accepted, .symbol], 254), + // (2, .symbol, 2), + // (9, .symbol, 2), + // (23, .symbol, 2), + // (40, [.accepted, .symbol], 2), + // (2, .symbol, 3), + // (9, .symbol, 3), + // (23, .symbol, 3), + // (40, [.accepted, .symbol], 3), + // + // // 227 + // + // (3, .symbol, 2), + // (6, .symbol, 2), + // (10, .symbol, 2), + // (15, .symbol, 2), + // (24, .symbol, 2), + // (31, .symbol, 2), + // (41, .symbol, 2), + // (56, [.accepted, .symbol], 2), + // (3, .symbol, 3), + // (6, .symbol, 3), + // (10, .symbol, 3), + // (15, .symbol, 3), + // (24, .symbol, 3), + // (31, .symbol, 3), + // (41, .symbol, 3), + // (56, [.accepted, .symbol], 3), + // + // // 228 + // + // (2, .symbol, 4), + // (9, .symbol, 4), + // (23, .symbol, 4), + // (40, [.accepted, .symbol], 4), + // (2, .symbol, 5), + // (9, .symbol, 5), + // (23, .symbol, 5), + // (40, [.accepted, .symbol], 5), + // (2, .symbol, 6), + // (9, .symbol, 6), + // (23, .symbol, 6), + // (40, [.accepted, .symbol], 6), + // (2, .symbol, 7), + // (9, .symbol, 7), + // (23, .symbol, 7), + // (40, [.accepted, .symbol], 7), + // + // // 229 + // + // (3, .symbol, 4), + // (6, .symbol, 4), + // (10, .symbol, 4), + // (15, .symbol, 4), + // (24, .symbol, 4), + // (31, .symbol, 4), + // (41, .symbol, 4), + // (56, [.accepted, .symbol], 4), + // (3, .symbol, 5), + // (6, .symbol, 5), + // (10, .symbol, 5), + // (15, .symbol, 5), + // (24, .symbol, 5), + // (31, .symbol, 5), + // (41, .symbol, 5), + // (56, [.accepted, .symbol], 5), + // + // // 230 + // + // (3, .symbol, 6), + // (6, .symbol, 6), + // (10, .symbol, 6), + // (15, .symbol, 6), + // (24, .symbol, 6), + // (31, .symbol, 6), + // (41, .symbol, 6), + // (56, [.accepted, .symbol], 6), + // (3, .symbol, 7), + // (6, .symbol, 7), + // (10, .symbol, 7), + // (15, .symbol, 7), + // (24, .symbol, 7), + // (31, .symbol, 7), + // (41, .symbol, 7), + // (56, [.accepted, .symbol], 7), + // + // // 231 + // + // (1, .symbol, 8), + // (22, [.accepted, .symbol], 8), + // (1, .symbol, 11), + // (22, [.accepted, .symbol], 11), + // (1, .symbol, 12), + // (22, [.accepted, .symbol], 12), + // (1, .symbol, 14), + // (22, [.accepted, .symbol], 14), + // (1, .symbol, 15), + // (22, [.accepted, .symbol], 15), + // (1, .symbol, 16), + // (22, [.accepted, .symbol], 16), + // (1, .symbol, 17), + // (22, [.accepted, .symbol], 17), + // (1, .symbol, 18), + // (22, [.accepted, .symbol], 18), + // + // // 232 + // + // (2, .symbol, 8), + // (9, .symbol, 8), + // (23, .symbol, 8), + // (40, [.accepted, .symbol], 8), + // (2, .symbol, 11), + // (9, .symbol, 11), + // (23, .symbol, 11), + // (40, [.accepted, .symbol], 11), + // (2, .symbol, 12), + // (9, .symbol, 12), + // (23, .symbol, 12), + // (40, [.accepted, .symbol], 12), + // (2, .symbol, 14), + // (9, .symbol, 14), + // (23, .symbol, 14), + // (40, [.accepted, .symbol], 14), + // + // // 233 + // + // (3, .symbol, 8), + // (6, .symbol, 8), + // (10, .symbol, 8), + // (15, .symbol, 8), + // (24, .symbol, 8), + // (31, .symbol, 8), + // (41, .symbol, 8), + // (56, [.accepted, .symbol], 8), + // (3, .symbol, 11), + // (6, .symbol, 11), + // (10, .symbol, 11), + // (15, .symbol, 11), + // (24, .symbol, 11), + // (31, .symbol, 11), + // (41, .symbol, 11), + // (56, [.accepted, .symbol], 11), + // + // // 234 + // + // (3, .symbol, 12), + // (6, .symbol, 12), + // (10, .symbol, 12), + // (15, .symbol, 12), + // (24, .symbol, 12), + // (31, .symbol, 12), + // (41, .symbol, 12), + // (56, [.accepted, .symbol], 12), + // (3, .symbol, 14), + // (6, .symbol, 14), + // (10, .symbol, 14), + // (15, .symbol, 14), + // (24, .symbol, 14), + // (31, .symbol, 14), + // (41, .symbol, 14), + // (56, [.accepted, .symbol], 14), + // + // // 235 + // + // (2, .symbol, 15), + // (9, .symbol, 15), + // (23, .symbol, 15), + // (40, [.accepted, .symbol], 15), + // (2, .symbol, 16), + // (9, .symbol, 16), + // (23, .symbol, 16), + // (40, [.accepted, .symbol], 16), + // (2, .symbol, 17), + // (9, .symbol, 17), + // (23, .symbol, 17), + // (40, [.accepted, .symbol], 17), + // (2, .symbol, 18), + // (9, .symbol, 18), + // (23, .symbol, 18), + // (40, [.accepted, .symbol], 18), + // + // // 236 + // + // (3, .symbol, 15), + // (6, .symbol, 15), + // (10, .symbol, 15), + // (15, .symbol, 15), + // (24, .symbol, 15), + // (31, .symbol, 15), + // (41, .symbol, 15), + // (56, [.accepted, .symbol], 15), + // (3, .symbol, 16), + // (6, .symbol, 16), + // (10, .symbol, 16), + // (15, .symbol, 16), + // (24, .symbol, 16), + // (31, .symbol, 16), + // (41, .symbol, 16), + // (56, [.accepted, .symbol], 16), + // + // // 237 + // + // (3, .symbol, 17), + // (6, .symbol, 17), + // (10, .symbol, 17), + // (15, .symbol, 17), + // (24, .symbol, 17), + // (31, .symbol, 17), + // (41, .symbol, 17), + // (56, [.accepted, .symbol], 17), + // (3, .symbol, 18), + // (6, .symbol, 18), + // (10, .symbol, 18), + // (15, .symbol, 18), + // (24, .symbol, 18), + // (31, .symbol, 18), + // (41, .symbol, 18), + // (56, [.accepted, .symbol], 18), + // + // // 238 + // + // (0, [.accepted, .symbol], 19), + // (0, [.accepted, .symbol], 20), + // (0, [.accepted, .symbol], 21), + // (0, [.accepted, .symbol], 23), + // (0, [.accepted, .symbol], 24), + // (0, [.accepted, .symbol], 25), + // (0, [.accepted, .symbol], 26), + // (0, [.accepted, .symbol], 27), + // (0, [.accepted, .symbol], 28), + // (0, [.accepted, .symbol], 29), + // (0, [.accepted, .symbol], 30), + // (0, [.accepted, .symbol], 31), + // (0, [.accepted, .symbol], 127), + // (0, [.accepted, .symbol], 220), + // (0, [.accepted, .symbol], 249), + // (253, .none, 0), + // + // // 239 + // + // (1, .symbol, 19), + // (22, [.accepted, .symbol], 19), + // (1, .symbol, 20), + // (22, [.accepted, .symbol], 20), + // (1, .symbol, 21), + // (22, [.accepted, .symbol], 21), + // (1, .symbol, 23), + // (22, [.accepted, .symbol], 23), + // (1, .symbol, 24), + // (22, [.accepted, .symbol], 24), + // (1, .symbol, 25), + // (22, [.accepted, .symbol], 25), + // (1, .symbol, 26), + // (22, [.accepted, .symbol], 26), + // (1, .symbol, 27), + // (22, [.accepted, .symbol], 27), + // + // // 240 + // + // (2, .symbol, 19), + // (9, .symbol, 19), + // (23, .symbol, 19), + // (40, [.accepted, .symbol], 19), + // (2, .symbol, 20), + // (9, .symbol, 20), + // (23, .symbol, 20), + // (40, [.accepted, .symbol], 20), + // (2, .symbol, 21), + // (9, .symbol, 21), + // (23, .symbol, 21), + // (40, [.accepted, .symbol], 21), + // (2, .symbol, 23), + // (9, .symbol, 23), + // (23, .symbol, 23), + // (40, [.accepted, .symbol], 23), + // + // // 241 + // + // (3, .symbol, 19), + // (6, .symbol, 19), + // (10, .symbol, 19), + // (15, .symbol, 19), + // (24, .symbol, 19), + // (31, .symbol, 19), + // (41, .symbol, 19), + // (56, [.accepted, .symbol], 19), + // (3, .symbol, 20), + // (6, .symbol, 20), + // (10, .symbol, 20), + // (15, .symbol, 20), + // (24, .symbol, 20), + // (31, .symbol, 20), + // (41, .symbol, 20), + // (56, [.accepted, .symbol], 20), + // + // // 242 + // + // (3, .symbol, 21), + // (6, .symbol, 21), + // (10, .symbol, 21), + // (15, .symbol, 21), + // (24, .symbol, 21), + // (31, .symbol, 21), + // (41, .symbol, 21), + // (56, [.accepted, .symbol], 21), + // (3, .symbol, 23), + // (6, .symbol, 23), + // (10, .symbol, 23), + // (15, .symbol, 23), + // (24, .symbol, 23), + // (31, .symbol, 23), + // (41, .symbol, 23), + // (56, [.accepted, .symbol], 23), + // + // // 243 + // + // (2, .symbol, 24), + // (9, .symbol, 24), + // (23, .symbol, 24), + // (40, [.accepted, .symbol], 24), + // (2, .symbol, 25), + // (9, .symbol, 25), + // (23, .symbol, 25), + // (40, [.accepted, .symbol], 25), + // (2, .symbol, 26), + // (9, .symbol, 26), + // (23, .symbol, 26), + // (40, [.accepted, .symbol], 26), + // (2, .symbol, 27), + // (9, .symbol, 27), + // (23, .symbol, 27), + // (40, [.accepted, .symbol], 27), + // + // // 244 + // + // (3, .symbol, 24), + // (6, .symbol, 24), + // (10, .symbol, 24), + // (15, .symbol, 24), + // (24, .symbol, 24), + // (31, .symbol, 24), + // (41, .symbol, 24), + // (56, [.accepted, .symbol], 24), + // (3, .symbol, 25), + // (6, .symbol, 25), + // (10, .symbol, 25), + // (15, .symbol, 25), + // (24, .symbol, 25), + // (31, .symbol, 25), + // (41, .symbol, 25), + // (56, [.accepted, .symbol], 25), + // + // // 245 + // + // (3, .symbol, 26), + // (6, .symbol, 26), + // (10, .symbol, 26), + // (15, .symbol, 26), + // (24, .symbol, 26), + // (31, .symbol, 26), + // (41, .symbol, 26), + // (56, [.accepted, .symbol], 26), + // (3, .symbol, 27), + // (6, .symbol, 27), + // (10, .symbol, 27), + // (15, .symbol, 27), + // (24, .symbol, 27), + // (31, .symbol, 27), + // (41, .symbol, 27), + // (56, [.accepted, .symbol], 27), + // + // // 246 + // + // (1, .symbol, 28), + // (22, [.accepted, .symbol], 28), + // (1, .symbol, 29), + // (22, [.accepted, .symbol], 29), + // (1, .symbol, 30), + // (22, [.accepted, .symbol], 30), + // (1, .symbol, 31), + // (22, [.accepted, .symbol], 31), + // (1, .symbol, 127), + // (22, [.accepted, .symbol], 127), + // (1, .symbol, 220), + // (22, [.accepted, .symbol], 220), + // (1, .symbol, 249), + // (22, [.accepted, .symbol], 249), + // (254, .none, 0), + // (255, .none, 0), + // + // // 247 + // + // (2, .symbol, 28), + // (9, .symbol, 28), + // (23, .symbol, 28), + // (40, [.accepted, .symbol], 28), + // (2, .symbol, 29), + // (9, .symbol, 29), + // (23, .symbol, 29), + // (40, [.accepted, .symbol], 29), + // (2, .symbol, 30), + // (9, .symbol, 30), + // (23, .symbol, 30), + // (40, [.accepted, .symbol], 30), + // (2, .symbol, 31), + // (9, .symbol, 31), + // (23, .symbol, 31), + // (40, [.accepted, .symbol], 31), + // + // // 248 + // + // (3, .symbol, 28), + // (6, .symbol, 28), + // (10, .symbol, 28), + // (15, .symbol, 28), + // (24, .symbol, 28), + // (31, .symbol, 28), + // (41, .symbol, 28), + // (56, [.accepted, .symbol], 28), + // (3, .symbol, 29), + // (6, .symbol, 29), + // (10, .symbol, 29), + // (15, .symbol, 29), + // (24, .symbol, 29), + // (31, .symbol, 29), + // (41, .symbol, 29), + // (56, [.accepted, .symbol], 29), + // + // // 249 + // + // (3, .symbol, 30), + // (6, .symbol, 30), + // (10, .symbol, 30), + // (15, .symbol, 30), + // (24, .symbol, 30), + // (31, .symbol, 30), + // (41, .symbol, 30), + // (56, [.accepted, .symbol], 30), + // (3, .symbol, 31), + // (6, .symbol, 31), + // (10, .symbol, 31), + // (15, .symbol, 31), + // (24, .symbol, 31), + // (31, .symbol, 31), + // (41, .symbol, 31), + // (56, [.accepted, .symbol], 31), + // + // // 250 + // + // (2, .symbol, 127), + // (9, .symbol, 127), + // (23, .symbol, 127), + // (40, [.accepted, .symbol], 127), + // (2, .symbol, 220), + // (9, .symbol, 220), + // (23, .symbol, 220), + // (40, [.accepted, .symbol], 220), + // (2, .symbol, 249), + // (9, .symbol, 249), + // (23, .symbol, 249), + // (40, [.accepted, .symbol], 249), + // (0, [.accepted, .symbol], 10), + // (0, [.accepted, .symbol], 13), + // (0, [.accepted, .symbol], 22), + // (0, .failure, 0), + // + // // 251 + // + // (3, .symbol, 127), + // (6, .symbol, 127), + // (10, .symbol, 127), + // (15, .symbol, 127), + // (24, .symbol, 127), + // (31, .symbol, 127), + // (41, .symbol, 127), + // (56, [.accepted, .symbol], 127), + // (3, .symbol, 220), + // (6, .symbol, 220), + // (10, .symbol, 220), + // (15, .symbol, 220), + // (24, .symbol, 220), + // (31, .symbol, 220), + // (41, .symbol, 220), + // (56, [.accepted, .symbol], 220), + // + // // 252 + // + // (3, .symbol, 249), + // (6, .symbol, 249), + // (10, .symbol, 249), + // (15, .symbol, 249), + // (24, .symbol, 249), + // (31, .symbol, 249), + // (41, .symbol, 249), + // (56, [.accepted, .symbol], 249), + // (1, .symbol, 10), + // (22, [.accepted, .symbol], 10), + // (1, .symbol, 13), + // (22, [.accepted, .symbol], 13), + // (1, .symbol, 22), + // (22, [.accepted, .symbol], 22), + // (0, .failure, 0), + // (0, .failure, 0), + // + // // 253 + // + // (2, .symbol, 10), + // (9, .symbol, 10), + // (23, .symbol, 10), + // (40, [.accepted, .symbol], 10), + // (2, .symbol, 13), + // (9, .symbol, 13), + // (23, .symbol, 13), + // (40, [.accepted, .symbol], 13), + // (2, .symbol, 22), + // (9, .symbol, 22), + // (23, .symbol, 22), + // (40, [.accepted, .symbol], 22), + // (0, .failure, 0), + // (0, .failure, 0), + // (0, .failure, 0), + // (0, .failure, 0), + // + // // 254 + // + // (3, .symbol, 10), + // (6, .symbol, 10), + // (10, .symbol, 10), + // (15, .symbol, 10), + // (24, .symbol, 10), + // (31, .symbol, 10), + // (41, .symbol, 10), + // (56, [.accepted, .symbol], 10), + // (3, .symbol, 13), + // (6, .symbol, 13), + // (10, .symbol, 13), + // (15, .symbol, 13), + // (24, .symbol, 13), + // (31, .symbol, 13), + // (41, .symbol, 13), + // (56, [.accepted, .symbol], 13), + // + // // 255 + // + // (3, .symbol, 22), + // (6, .symbol, 22), + // (10, .symbol, 22), + // (15, .symbol, 22), + // (24, .symbol, 22), + // (31, .symbol, 22), + // (41, .symbol, 22), + // (56, [.accepted, .symbol], 22), + // (0, .failure, 0), + // (0, .failure, 0), + // (0, .failure, 0), + // (0, .failure, 0), + // (0, .failure, 0), + // (0, .failure, 0), + // (0, .failure, 0), + // (0, .failure, 0), + // ] } diff --git a/Sources/NIOHPACK/IndexedHeaderTable.swift b/Sources/NIOHPACK/IndexedHeaderTable.swift index dbc6ce8..6b9d1e7 100644 --- a/Sources/NIOHPACK/IndexedHeaderTable.swift +++ b/Sources/NIOHPACK/IndexedHeaderTable.swift @@ -24,7 +24,7 @@ public struct IndexedHeaderTable { // TODO(cory): This property should be removed, we only keep it for use in headerViews(at:). private var allocator: ByteBufferAllocator - + /// Creates a new header table, optionally specifying a maximum size for the dynamic /// portion of the table. /// @@ -34,7 +34,7 @@ public struct IndexedHeaderTable { self.dynamicTable = DynamicHeaderTable(maximumLength: maxDynamicTableSize) self.allocator = allocator } - + /// Obtains the header key/value pair at the given index within the table. /// /// - note: Per RFC 7541, this uses a *1-based* index. @@ -48,12 +48,15 @@ public struct IndexedHeaderTable { } else if index - self.staticTable.count < self.dynamicTable.count { result = self.dynamicTable[index - self.staticTable.count] } else { - throw NIOHPACKErrors.InvalidHeaderIndex(suppliedIndex: index, availableIndex: self.staticTable.count + self.dynamicTable.count - 1) + throw NIOHPACKErrors.InvalidHeaderIndex( + suppliedIndex: index, + availableIndex: self.staticTable.count + self.dynamicTable.count - 1 + ) } return (name: result.name, value: result.value) } - + /// Obtains the header key/value pair at the given index within the table as sequences of /// raw bytes. /// @@ -74,7 +77,7 @@ public struct IndexedHeaderTable { return (nameBuffer.readableBytesView, valueBuffer.readableBytesView) } - + /// Searches the table to locate an existing header with the given name and value. If /// no item exists that contains a matching value, it will return the index of the first /// item with a matching header name instead, to be encoded as index+value. @@ -107,7 +110,7 @@ public struct IndexedHeaderTable { return (index, false) } } - + // no complete match: search the dynamic table now if let result = self.dynamicTable.findExistingHeader(named: name, value: value) { if let staticIndex = firstHeaderIndex, result.containsValue == false { @@ -127,7 +130,7 @@ public struct IndexedHeaderTable { return nil } } - + /// Appends a header to the table. /// /// This call may result in an empty table, as per RFC 7541 ยง 4.4: @@ -142,7 +145,7 @@ public struct IndexedHeaderTable { // This function is unnecessarily marked throws, but none of its underlying functions throw anymore. self.dynamicTable.addHeader(named: name, value: value) } - + /// Appends a header to the table. /// /// This call may result in an empty table, as per RFC 7541 ยง 4.4: @@ -157,38 +160,38 @@ public struct IndexedHeaderTable { /// - name: A sequence of contiguous bytes containing the name of the header to insert. /// - value: A sequence of contiguous bytes containing the value of the header to insert. @available(*, deprecated, renamed: "add(headerNamed:value:)") - public mutating func add(headerNamed name: Name, value: Value) throws where Name.Element == UInt8, Value.Element == UInt8 { + public mutating func add(headerNamed name: Name, value: Value) throws + where Name.Element == UInt8, Value.Element == UInt8 { let nameString = String(decoding: name, as: UTF8.self) let valueString = String(decoding: value, as: UTF8.self) - + try self.add(headerNamed: nameString, value: valueString) } - + /// Internal for test access. internal func dumpHeaders() -> String { - return "\(staticTable.dumpHeaders())\n\(dynamicTable.dumpHeaders())" + "\(staticTable.dumpHeaders())\n\(dynamicTable.dumpHeaders())" } - + /// The length, in bytes, of the dynamic portion of the header table. public var dynamicTableLength: Int { - return self.dynamicTable.length + self.dynamicTable.length } - + /// The current allowed length of the dynamic portion of the header table. May be /// less than the current protocol-assigned maximum supplied by a SETTINGS frame. public var dynamicTableAllowedLength: Int { - get { return self.dynamicTable.allowedLength } + get { self.dynamicTable.allowedLength } set { self.dynamicTable.allowedLength = newValue } } - + /// The hard limit on the size to which the dynamic table may grow. Only a SETTINGS /// frame can change this: it can't grow beyond this size due to changes within /// header blocks. public var maxDynamicTableLength: Int { - get { return self.dynamicTable.maximumTableLength } + get { self.dynamicTable.maximumTableLength } set { self.dynamicTable.maximumTableLength = newValue } } } - extension IndexedHeaderTable: Sendable {} diff --git a/Sources/NIOHPACK/IntegerCoding.swift b/Sources/NIOHPACK/IntegerCoding.swift index dcbff43..a784d94 100644 --- a/Sources/NIOHPACK/IntegerCoding.swift +++ b/Sources/NIOHPACK/IntegerCoding.swift @@ -14,7 +14,7 @@ import NIOCore -/* private but tests */ +// private but tests /// Encodes an integer value into a provided memory location. /// /// - Parameters: @@ -24,8 +24,12 @@ import NIOCore /// - prefixBits: Existing bits to place in that first byte of `buffer` before encoding `value`. /// - Returns: Returns the number of bytes used to encode the integer. @discardableResult -func encodeInteger(_ value: UInt64, to buffer: inout ByteBuffer, - prefix: Int, prefixBits: UInt8 = 0) -> Int { +func encodeInteger( + _ value: UInt64, + to buffer: inout ByteBuffer, + prefix: Int, + prefixBits: UInt8 = 0 +) -> Int { assert(prefix <= 8) assert(prefix >= 1) @@ -62,16 +66,16 @@ func encodeInteger(_ value: UInt64, to buffer: inout ByteBuffer, return buffer.writerIndex &- start } -fileprivate let valueMask: UInt8 = 127 -fileprivate let continuationMask: UInt8 = 128 +private let valueMask: UInt8 = 127 +private let continuationMask: UInt8 = 128 -/* private but tests */ +// private but tests struct DecodedInteger { var value: Int var bytesRead: Int } -/* private but tests */ +// private but tests func decodeInteger(from bytes: ByteBufferView, prefix: Int) throws -> DecodedInteger { precondition((1...8).contains(prefix)) if bytes.isEmpty { diff --git a/Sources/NIOHPACK/StaticHeaderTable.swift b/Sources/NIOHPACK/StaticHeaderTable.swift index fa216ed..df1cb97 100644 --- a/Sources/NIOHPACK/StaticHeaderTable.swift +++ b/Sources/NIOHPACK/StaticHeaderTable.swift @@ -13,7 +13,7 @@ //===----------------------------------------------------------------------===// internal let StaticHeaderTable: [(String, String)] = [ - ("", ""), // real indexing begins at 1 + ("", ""), // real indexing begins at 1 (":authority", ""), (":method", "GET"), (":method", "POST"), @@ -74,5 +74,5 @@ internal let StaticHeaderTable: [(String, String)] = [ ("user-agent", ""), ("vary", ""), ("via", ""), - ("www-authenticate", "") + ("www-authenticate", ""), ] diff --git a/Sources/NIOHTTP2/ConnectionStateMachine/ConnectionStateMachine.swift b/Sources/NIOHTTP2/ConnectionStateMachine/ConnectionStateMachine.swift index 95857e4..900ac97 100644 --- a/Sources/NIOHTTP2/ConnectionStateMachine/ConnectionStateMachine.swift +++ b/Sources/NIOHTTP2/ConnectionStateMachine/ConnectionStateMachine.swift @@ -70,7 +70,9 @@ struct HTTP2ConnectionStateMachine { } /// The state required for a connection that has sent a connection preface. - fileprivate struct PrefaceSentState: ConnectionStateWithRole, ConnectionStateWithConfiguration, MaySendFrames, HasLocalSettings, HasFlowControlWindows { + fileprivate struct PrefaceSentState: ConnectionStateWithRole, ConnectionStateWithConfiguration, MaySendFrames, + HasLocalSettings, HasFlowControlWindows + { let role: ConnectionRole var headerBlockValidation: ValidationState var contentLengthValidation: ValidationState @@ -80,11 +82,11 @@ struct HTTP2ConnectionStateMachine { var outboundFlowControlWindow: HTTP2FlowControlWindow var localInitialWindowSize: UInt32 { - return HTTP2SettingsState.defaultInitialWindowSize + HTTP2SettingsState.defaultInitialWindowSize } var remoteInitialWindowSize: UInt32 { - return self.localSettings.initialWindowSize + self.localSettings.initialWindowSize } var remoteSupportsExtendedConnect: Bool { @@ -99,12 +101,16 @@ struct HTTP2ConnectionStateMachine { self.streamState = ConnectionStreamState() self.inboundFlowControlWindow = HTTP2FlowControlWindow(initialValue: settings.initialWindowSize) - self.outboundFlowControlWindow = HTTP2FlowControlWindow(initialValue: HTTP2SettingsState.defaultInitialWindowSize) + self.outboundFlowControlWindow = HTTP2FlowControlWindow( + initialValue: HTTP2SettingsState.defaultInitialWindowSize + ) } } /// The state required for a connection that has received a connection preface. - fileprivate struct PrefaceReceivedState: ConnectionStateWithRole, ConnectionStateWithConfiguration, MayReceiveFrames, HasRemoteSettings, HasFlowControlWindows { + fileprivate struct PrefaceReceivedState: ConnectionStateWithRole, ConnectionStateWithConfiguration, + MayReceiveFrames, HasRemoteSettings, HasFlowControlWindows + { let role: ConnectionRole var headerBlockValidation: ValidationState var contentLengthValidation: ValidationState @@ -114,11 +120,11 @@ struct HTTP2ConnectionStateMachine { var outboundFlowControlWindow: HTTP2FlowControlWindow var localInitialWindowSize: UInt32 { - return self.remoteSettings.initialWindowSize + self.remoteSettings.initialWindowSize } var remoteInitialWindowSize: UInt32 { - return HTTP2SettingsState.defaultInitialWindowSize + HTTP2SettingsState.defaultInitialWindowSize } var localSupportsExtendedConnect: Bool { @@ -132,13 +138,17 @@ struct HTTP2ConnectionStateMachine { self.remoteSettings = settings self.streamState = ConnectionStreamState() - self.inboundFlowControlWindow = HTTP2FlowControlWindow(initialValue: HTTP2SettingsState.defaultInitialWindowSize) + self.inboundFlowControlWindow = HTTP2FlowControlWindow( + initialValue: HTTP2SettingsState.defaultInitialWindowSize + ) self.outboundFlowControlWindow = HTTP2FlowControlWindow(initialValue: settings.initialWindowSize) } } /// The state required for a connection that is active. - fileprivate struct ActiveConnectionState: ConnectionStateWithRole, ConnectionStateWithConfiguration, MaySendFrames, MayReceiveFrames, HasLocalSettings, HasRemoteSettings, HasFlowControlWindows { + fileprivate struct ActiveConnectionState: ConnectionStateWithRole, ConnectionStateWithConfiguration, MaySendFrames, + MayReceiveFrames, HasLocalSettings, HasRemoteSettings, HasFlowControlWindows + { let role: ConnectionRole var headerBlockValidation: ValidationState var contentLengthValidation: ValidationState @@ -149,11 +159,11 @@ struct HTTP2ConnectionStateMachine { var outboundFlowControlWindow: HTTP2FlowControlWindow var localInitialWindowSize: UInt32 { - return self.remoteSettings.initialWindowSize + self.remoteSettings.initialWindowSize } var remoteInitialWindowSize: UInt32 { - return self.localSettings.initialWindowSize + self.localSettings.initialWindowSize } init(fromPrefaceReceived state: PrefaceReceivedState, localSettings settings: HTTP2SettingsState) { @@ -183,7 +193,9 @@ struct HTTP2ConnectionStateMachine { /// The state required for a connection that is quiescing, but where the local peer has not yet sent its /// preface. - fileprivate struct QuiescingPrefaceReceivedState: ConnectionStateWithRole, ConnectionStateWithConfiguration, RemotelyQuiescingState, MayReceiveFrames, HasRemoteSettings, QuiescingState, HasFlowControlWindows { + fileprivate struct QuiescingPrefaceReceivedState: ConnectionStateWithRole, ConnectionStateWithConfiguration, + RemotelyQuiescingState, MayReceiveFrames, HasRemoteSettings, QuiescingState, HasFlowControlWindows + { let role: ConnectionRole var headerBlockValidation: ValidationState var contentLengthValidation: ValidationState @@ -195,15 +207,15 @@ struct HTTP2ConnectionStateMachine { var lastLocalStreamID: HTTP2StreamID var localInitialWindowSize: UInt32 { - return self.remoteSettings.initialWindowSize + self.remoteSettings.initialWindowSize } var remoteInitialWindowSize: UInt32 { - return HTTP2SettingsState.defaultInitialWindowSize + HTTP2SettingsState.defaultInitialWindowSize } var quiescedByServer: Bool { - return self.role == .client + self.role == .client } var localSupportsExtendedConnect: Bool { @@ -225,7 +237,9 @@ struct HTTP2ConnectionStateMachine { /// The state required for a connection that is quiescing, but where the remote peer has not yet sent its /// preface. - fileprivate struct QuiescingPrefaceSentState: ConnectionStateWithRole, ConnectionStateWithConfiguration, LocallyQuiescingState, MaySendFrames, HasLocalSettings, QuiescingState, HasFlowControlWindows { + fileprivate struct QuiescingPrefaceSentState: ConnectionStateWithRole, ConnectionStateWithConfiguration, + LocallyQuiescingState, MaySendFrames, HasLocalSettings, QuiescingState, HasFlowControlWindows + { let role: ConnectionRole var headerBlockValidation: ValidationState var contentLengthValidation: ValidationState @@ -237,15 +251,15 @@ struct HTTP2ConnectionStateMachine { var lastRemoteStreamID: HTTP2StreamID var localInitialWindowSize: UInt32 { - return HTTP2SettingsState.defaultInitialWindowSize + HTTP2SettingsState.defaultInitialWindowSize } var remoteInitialWindowSize: UInt32 { - return self.localSettings.initialWindowSize + self.localSettings.initialWindowSize } var quiescedByServer: Bool { - return self.role == .server + self.role == .server } var remoteSupportsExtendedConnect: Bool { @@ -266,7 +280,10 @@ struct HTTP2ConnectionStateMachine { } /// The state required for a connection that is quiescing due to the remote peer quiescing the connection. - fileprivate struct RemotelyQuiescedState: ConnectionStateWithRole, ConnectionStateWithConfiguration, RemotelyQuiescingState, MayReceiveFrames, MaySendFrames, HasLocalSettings, HasRemoteSettings, QuiescingState, HasFlowControlWindows { + fileprivate struct RemotelyQuiescedState: ConnectionStateWithRole, ConnectionStateWithConfiguration, + RemotelyQuiescingState, MayReceiveFrames, MaySendFrames, HasLocalSettings, HasRemoteSettings, QuiescingState, + HasFlowControlWindows + { let role: ConnectionRole var headerBlockValidation: ValidationState var contentLengthValidation: ValidationState @@ -279,15 +296,15 @@ struct HTTP2ConnectionStateMachine { var lastLocalStreamID: HTTP2StreamID var localInitialWindowSize: UInt32 { - return self.remoteSettings.initialWindowSize + self.remoteSettings.initialWindowSize } var remoteInitialWindowSize: UInt32 { - return self.localSettings.initialWindowSize + self.localSettings.initialWindowSize } var quiescedByServer: Bool { - return self.role == .client + self.role == .client } init(fromActive state: ActiveConnectionState, lastLocalStreamID streamID: HTTP2StreamID) { @@ -302,7 +319,10 @@ struct HTTP2ConnectionStateMachine { self.lastLocalStreamID = streamID } - init(fromQuiescingPrefaceReceived state: QuiescingPrefaceReceivedState, localSettings settings: HTTP2SettingsState) { + init( + fromQuiescingPrefaceReceived state: QuiescingPrefaceReceivedState, + localSettings settings: HTTP2SettingsState + ) { self.role = state.role self.headerBlockValidation = state.headerBlockValidation self.contentLengthValidation = state.contentLengthValidation @@ -316,7 +336,10 @@ struct HTTP2ConnectionStateMachine { } /// The state required for a connection that is quiescing due to the local user quiescing the connection. - fileprivate struct LocallyQuiescedState: ConnectionStateWithRole, ConnectionStateWithConfiguration, LocallyQuiescingState, MaySendFrames, MayReceiveFrames, HasLocalSettings, HasRemoteSettings, QuiescingState, HasFlowControlWindows { + fileprivate struct LocallyQuiescedState: ConnectionStateWithRole, ConnectionStateWithConfiguration, + LocallyQuiescingState, MaySendFrames, MayReceiveFrames, HasLocalSettings, HasRemoteSettings, QuiescingState, + HasFlowControlWindows + { let role: ConnectionRole var headerBlockValidation: ValidationState var contentLengthValidation: ValidationState @@ -329,15 +352,15 @@ struct HTTP2ConnectionStateMachine { var lastRemoteStreamID: HTTP2StreamID var localInitialWindowSize: UInt32 { - return self.remoteSettings.initialWindowSize + self.remoteSettings.initialWindowSize } var remoteInitialWindowSize: UInt32 { - return self.localSettings.initialWindowSize + self.localSettings.initialWindowSize } var quiescedByServer: Bool { - return self.role == .server + self.role == .server } init(fromActive state: ActiveConnectionState, lastRemoteStreamID streamID: HTTP2StreamID) { @@ -366,7 +389,10 @@ struct HTTP2ConnectionStateMachine { } /// The state required for a connection that is quiescing due to both peers sending GOAWAY. - fileprivate struct BothQuiescingState: ConnectionStateWithRole, ConnectionStateWithConfiguration, LocallyQuiescingState, RemotelyQuiescingState, MaySendFrames, MayReceiveFrames, HasLocalSettings, HasRemoteSettings, QuiescingState, HasFlowControlWindows { + fileprivate struct BothQuiescingState: ConnectionStateWithRole, ConnectionStateWithConfiguration, + LocallyQuiescingState, RemotelyQuiescingState, MaySendFrames, MayReceiveFrames, HasLocalSettings, + HasRemoteSettings, QuiescingState, HasFlowControlWindows + { let role: ConnectionRole var headerBlockValidation: ValidationState var contentLengthValidation: ValidationState @@ -379,15 +405,15 @@ struct HTTP2ConnectionStateMachine { var lastRemoteStreamID: HTTP2StreamID var localInitialWindowSize: UInt32 { - return self.remoteSettings.initialWindowSize + self.remoteSettings.initialWindowSize } var remoteInitialWindowSize: UInt32 { - return self.localSettings.initialWindowSize + self.localSettings.initialWindowSize } var quiescedByServer: Bool { - return true + true } init(fromRemotelyQuiesced state: RemotelyQuiescedState, lastRemoteStreamID streamID: HTTP2StreamID) { @@ -420,7 +446,9 @@ struct HTTP2ConnectionStateMachine { } /// The state required for a connection that has completely quiesced. - fileprivate struct FullyQuiescedState: ConnectionStateWithRole, ConnectionStateWithConfiguration, LocallyQuiescingState, RemotelyQuiescingState, SendAndReceiveGoawayState { + fileprivate struct FullyQuiescedState: ConnectionStateWithRole, ConnectionStateWithConfiguration, + LocallyQuiescingState, RemotelyQuiescingState, SendAndReceiveGoawayState + { let role: ConnectionRole var headerBlockValidation: ValidationState var contentLengthValidation: ValidationState @@ -436,7 +464,10 @@ struct HTTP2ConnectionStateMachine { false } - init(previousState: PreviousState) { + init< + PreviousState: LocallyQuiescingState & RemotelyQuiescingState & SendAndReceiveGoawayState + & ConnectionStateWithRole & ConnectionStateWithConfiguration + >(previousState: PreviousState) { self.role = previousState.role self.headerBlockValidation = previousState.headerBlockValidation self.contentLengthValidation = previousState.contentLengthValidation @@ -445,7 +476,10 @@ struct HTTP2ConnectionStateMachine { self.lastRemoteStreamID = previousState.lastRemoteStreamID } - init(previousState: PreviousState) { + init< + PreviousState: LocallyQuiescingState & SendAndReceiveGoawayState & ConnectionStateWithRole + & ConnectionStateWithConfiguration + >(previousState: PreviousState) { self.role = previousState.role self.headerBlockValidation = previousState.headerBlockValidation self.contentLengthValidation = previousState.contentLengthValidation @@ -454,7 +488,10 @@ struct HTTP2ConnectionStateMachine { self.lastRemoteStreamID = previousState.lastRemoteStreamID } - init(previousState: PreviousState) { + init< + PreviousState: RemotelyQuiescingState & SendAndReceiveGoawayState & ConnectionStateWithRole + & ConnectionStateWithConfiguration + >(previousState: PreviousState) { self.role = previousState.role self.headerBlockValidation = previousState.headerBlockValidation self.contentLengthValidation = previousState.contentLengthValidation @@ -531,8 +568,18 @@ struct HTTP2ConnectionStateMachine { private var state: State - init(role: ConnectionRole, headerBlockValidation: ValidationState = .enabled, contentLengthValidation: ValidationState = .enabled) { - self.state = .idle(.init(role: role, headerBlockValidation: headerBlockValidation, contentLengthValidation: contentLengthValidation)) + init( + role: ConnectionRole, + headerBlockValidation: ValidationState = .enabled, + contentLengthValidation: ValidationState = .enabled + ) { + self.state = .idle( + .init( + role: role, + headerBlockValidation: headerBlockValidation, + contentLengthValidation: contentLengthValidation + ) + ) } /// Whether this connection is closed. @@ -562,7 +609,11 @@ struct HTTP2ConnectionStateMachine { // performs a state transition, and can be used to validate that a specific action is acceptable on a connection in this state. extension HTTP2ConnectionStateMachine { /// Called when a SETTINGS frame has been received from the remote peer - mutating func receiveSettings(_ payload: HTTP2Frame.FramePayload.Settings, frameEncoder: inout HTTP2FrameEncoder, frameDecoder: inout HTTP2FrameDecoder) -> (StateMachineResultWithEffect, PostFrameOperation) { + mutating func receiveSettings( + _ payload: HTTP2Frame.FramePayload.Settings, + frameEncoder: inout HTTP2FrameEncoder, + frameDecoder: inout HTTP2FrameDecoder + ) -> (StateMachineResultWithEffect, PostFrameOperation) { switch payload { case .ack: // No action is ever required after receiving a settings ACK @@ -642,7 +693,10 @@ extension HTTP2ConnectionStateMachine { } case .fullyQuiesced: - return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.ioOnClosedConnection(), type: .protocolError), effect: nil) + return .init( + result: .connectionError(underlyingError: NIOHTTP2Errors.ioOnClosedConnection(), type: .protocolError), + effect: nil + ) case .modifying: preconditionFailure("Must not be left in modifying state") @@ -652,7 +706,11 @@ extension HTTP2ConnectionStateMachine { } /// Called when a HEADERS frame has been received from the remote peer. - mutating func receiveHeaders(streamID: HTTP2StreamID, headers: HPACKHeaders, isEndStreamSet endStream: Bool) -> StateMachineResultWithEffect { + mutating func receiveHeaders( + streamID: HTTP2StreamID, + headers: HPACKHeaders, + isEndStreamSet endStream: Bool + ) -> StateMachineResultWithEffect { switch self.state { case .prefaceReceived(var state): return self.avoidingStateMachineCoW { newState in @@ -701,10 +759,23 @@ extension HTTP2ConnectionStateMachine { case .idle, .prefaceSent, .quiescingPrefaceSent: // If we're still waiting for the remote preface, they are not allowed to send us a HEADERS frame yet! - return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.missingPreface(), type: .protocolError), effect: nil) + return .init( + result: .connectionError(underlyingError: NIOHTTP2Errors.missingPreface(), type: .protocolError), + effect: nil + ) case .fullyQuiesced: - return .init(result: .streamError(streamID: streamID, underlyingError: NIOHTTP2Errors.streamError(streamID: streamID, baseError: NIOHTTP2Errors.createdStreamAfterGoaway()), type: .refusedStream), effect: nil) + return .init( + result: .streamError( + streamID: streamID, + underlyingError: NIOHTTP2Errors.streamError( + streamID: streamID, + baseError: NIOHTTP2Errors.createdStreamAfterGoaway() + ), + type: .refusedStream + ), + effect: nil + ) case .modifying: preconditionFailure("Must not be left in modifying state") @@ -712,7 +783,11 @@ extension HTTP2ConnectionStateMachine { } // Called when a HEADERS frame has been sent by the local user. - mutating func sendHeaders(streamID: HTTP2StreamID, headers: HPACKHeaders, isEndStreamSet endStream: Bool) -> StateMachineResultWithEffect { + mutating func sendHeaders( + streamID: HTTP2StreamID, + headers: HPACKHeaders, + isEndStreamSet endStream: Bool + ) -> StateMachineResultWithEffect { switch self.state { case .prefaceSent(var state): return self.avoidingStateMachineCoW { newState in @@ -761,10 +836,16 @@ extension HTTP2ConnectionStateMachine { case .idle, .prefaceReceived, .quiescingPrefaceReceived: // If we're still waiting for the local preface, we are not allowed to send a HEADERS frame yet! - return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.missingPreface(), type: .protocolError), effect: nil) + return .init( + result: .connectionError(underlyingError: NIOHTTP2Errors.missingPreface(), type: .protocolError), + effect: nil + ) case .fullyQuiesced: - return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.ioOnClosedConnection(), type: .protocolError), effect: nil) + return .init( + result: .connectionError(underlyingError: NIOHTTP2Errors.ioOnClosedConnection(), type: .protocolError), + effect: nil + ) case .modifying: preconditionFailure("Must not be left in modifying state") @@ -772,25 +853,45 @@ extension HTTP2ConnectionStateMachine { } /// Called when a DATA frame has been received. - mutating func receiveData(streamID: HTTP2StreamID, contentLength: Int, flowControlledBytes: Int, isEndStreamSet endStream: Bool) -> StateMachineResultWithEffect { + mutating func receiveData( + streamID: HTTP2StreamID, + contentLength: Int, + flowControlledBytes: Int, + isEndStreamSet endStream: Bool + ) -> StateMachineResultWithEffect { switch self.state { case .prefaceReceived(var state): return self.avoidingStateMachineCoW { newState in - let result = state.receiveData(streamID: streamID, contentLength: contentLength, flowControlledBytes: flowControlledBytes, isEndStreamSet: endStream) + let result = state.receiveData( + streamID: streamID, + contentLength: contentLength, + flowControlledBytes: flowControlledBytes, + isEndStreamSet: endStream + ) newState = .prefaceReceived(state) return result } case .active(var state): return self.avoidingStateMachineCoW { newState in - let result = state.receiveData(streamID: streamID, contentLength: contentLength, flowControlledBytes: flowControlledBytes, isEndStreamSet: endStream) + let result = state.receiveData( + streamID: streamID, + contentLength: contentLength, + flowControlledBytes: flowControlledBytes, + isEndStreamSet: endStream + ) newState = .active(state) return result } case .locallyQuiesced(var state): return self.avoidingStateMachineCoW { newState in - let result = state.receiveData(streamID: streamID, contentLength: contentLength, flowControlledBytes: flowControlledBytes, isEndStreamSet: endStream) + let result = state.receiveData( + streamID: streamID, + contentLength: contentLength, + flowControlledBytes: flowControlledBytes, + isEndStreamSet: endStream + ) newState = .locallyQuiesced(state) newState.closeIfNeeded(state) return result @@ -798,7 +899,12 @@ extension HTTP2ConnectionStateMachine { case .remotelyQuiesced(var state): return self.avoidingStateMachineCoW { newState in - let result = state.receiveData(streamID: streamID, contentLength: contentLength, flowControlledBytes: flowControlledBytes, isEndStreamSet: endStream) + let result = state.receiveData( + streamID: streamID, + contentLength: contentLength, + flowControlledBytes: flowControlledBytes, + isEndStreamSet: endStream + ) newState = .remotelyQuiesced(state) newState.closeIfNeeded(state) return result @@ -806,7 +912,12 @@ extension HTTP2ConnectionStateMachine { case .bothQuiescing(var state): return self.avoidingStateMachineCoW { newState in - let result = state.receiveData(streamID: streamID, contentLength: contentLength, flowControlledBytes: flowControlledBytes, isEndStreamSet: endStream) + let result = state.receiveData( + streamID: streamID, + contentLength: contentLength, + flowControlledBytes: flowControlledBytes, + isEndStreamSet: endStream + ) newState = .bothQuiescing(state) newState.closeIfNeeded(state) return result @@ -814,17 +925,28 @@ extension HTTP2ConnectionStateMachine { case .quiescingPrefaceReceived(var state): return self.avoidingStateMachineCoW { newState in - let result = state.receiveData(streamID: streamID, contentLength: contentLength, flowControlledBytes: flowControlledBytes, isEndStreamSet: endStream) + let result = state.receiveData( + streamID: streamID, + contentLength: contentLength, + flowControlledBytes: flowControlledBytes, + isEndStreamSet: endStream + ) newState = .quiescingPrefaceReceived(state) return result } case .idle, .prefaceSent, .quiescingPrefaceSent: // If we're still waiting for the remote preface, we are not allowed to receive a DATA frame yet! - return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.missingPreface(), type: .protocolError), effect: nil) + return .init( + result: .connectionError(underlyingError: NIOHTTP2Errors.missingPreface(), type: .protocolError), + effect: nil + ) case .fullyQuiesced: - return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.ioOnClosedConnection(), type: .protocolError), effect: nil) + return .init( + result: .connectionError(underlyingError: NIOHTTP2Errors.ioOnClosedConnection(), type: .protocolError), + effect: nil + ) case .modifying: preconditionFailure("Must not be left in modifying state") @@ -832,25 +954,45 @@ extension HTTP2ConnectionStateMachine { } /// Called when a user is trying to send a DATA frame. - mutating func sendData(streamID: HTTP2StreamID, contentLength: Int, flowControlledBytes: Int, isEndStreamSet endStream: Bool) -> StateMachineResultWithEffect { + mutating func sendData( + streamID: HTTP2StreamID, + contentLength: Int, + flowControlledBytes: Int, + isEndStreamSet endStream: Bool + ) -> StateMachineResultWithEffect { switch self.state { case .prefaceSent(var state): return self.avoidingStateMachineCoW { newState in - let result = state.sendData(streamID: streamID, contentLength: contentLength, flowControlledBytes: flowControlledBytes, isEndStreamSet: endStream) + let result = state.sendData( + streamID: streamID, + contentLength: contentLength, + flowControlledBytes: flowControlledBytes, + isEndStreamSet: endStream + ) newState = .prefaceSent(state) return result } case .active(var state): return self.avoidingStateMachineCoW { newState in - let result = state.sendData(streamID: streamID, contentLength: contentLength, flowControlledBytes: flowControlledBytes, isEndStreamSet: endStream) + let result = state.sendData( + streamID: streamID, + contentLength: contentLength, + flowControlledBytes: flowControlledBytes, + isEndStreamSet: endStream + ) newState = .active(state) return result } case .locallyQuiesced(var state): return self.avoidingStateMachineCoW { newState in - let result = state.sendData(streamID: streamID, contentLength: contentLength, flowControlledBytes: flowControlledBytes, isEndStreamSet: endStream) + let result = state.sendData( + streamID: streamID, + contentLength: contentLength, + flowControlledBytes: flowControlledBytes, + isEndStreamSet: endStream + ) newState = .locallyQuiesced(state) newState.closeIfNeeded(state) return result @@ -858,7 +1000,12 @@ extension HTTP2ConnectionStateMachine { case .remotelyQuiesced(var state): return self.avoidingStateMachineCoW { newState in - let result = state.sendData(streamID: streamID, contentLength: contentLength, flowControlledBytes: flowControlledBytes, isEndStreamSet: endStream) + let result = state.sendData( + streamID: streamID, + contentLength: contentLength, + flowControlledBytes: flowControlledBytes, + isEndStreamSet: endStream + ) newState = .remotelyQuiesced(state) newState.closeIfNeeded(state) return result @@ -866,7 +1013,12 @@ extension HTTP2ConnectionStateMachine { case .bothQuiescing(var state): return self.avoidingStateMachineCoW { newState in - let result = state.sendData(streamID: streamID, contentLength: contentLength, flowControlledBytes: flowControlledBytes, isEndStreamSet: endStream) + let result = state.sendData( + streamID: streamID, + contentLength: contentLength, + flowControlledBytes: flowControlledBytes, + isEndStreamSet: endStream + ) newState = .bothQuiescing(state) newState.closeIfNeeded(state) return result @@ -874,17 +1026,28 @@ extension HTTP2ConnectionStateMachine { case .quiescingPrefaceSent(var state): return self.avoidingStateMachineCoW { newState in - let result = state.sendData(streamID: streamID, contentLength: contentLength, flowControlledBytes: flowControlledBytes, isEndStreamSet: endStream) + let result = state.sendData( + streamID: streamID, + contentLength: contentLength, + flowControlledBytes: flowControlledBytes, + isEndStreamSet: endStream + ) newState = .quiescingPrefaceSent(state) return result } case .idle, .prefaceReceived, .quiescingPrefaceReceived: // If we're still waiting for the local preface, we are not allowed to send a DATA frame yet! - return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.missingPreface(), type: .protocolError), effect: nil) + return .init( + result: .connectionError(underlyingError: NIOHTTP2Errors.missingPreface(), type: .protocolError), + effect: nil + ) case .fullyQuiesced: - return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.ioOnClosedConnection(), type: .protocolError), effect: nil) + return .init( + result: .connectionError(underlyingError: NIOHTTP2Errors.ioOnClosedConnection(), type: .protocolError), + effect: nil + ) case .modifying: preconditionFailure("Must not be left in modifying state") @@ -900,10 +1063,16 @@ extension HTTP2ConnectionStateMachine { return StateMachineResultWithEffect(result: .succeed, effect: nil) case .idle, .prefaceSent, .quiescingPrefaceSent: - return StateMachineResultWithEffect(result: .connectionError(underlyingError: NIOHTTP2Errors.missingPreface(), type: .protocolError), effect: nil) + return StateMachineResultWithEffect( + result: .connectionError(underlyingError: NIOHTTP2Errors.missingPreface(), type: .protocolError), + effect: nil + ) case .fullyQuiesced: - return StateMachineResultWithEffect(result: .connectionError(underlyingError: NIOHTTP2Errors.ioOnClosedConnection(), type: .protocolError), effect: nil) + return StateMachineResultWithEffect( + result: .connectionError(underlyingError: NIOHTTP2Errors.ioOnClosedConnection(), type: .protocolError), + effect: nil + ) case .modifying: preconditionFailure("Must not be left in modifying state") @@ -919,10 +1088,16 @@ extension HTTP2ConnectionStateMachine { return .init(result: .succeed, effect: nil) case .idle, .prefaceReceived, .quiescingPrefaceReceived: - return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.missingPreface(), type: .protocolError), effect: nil) + return .init( + result: .connectionError(underlyingError: NIOHTTP2Errors.missingPreface(), type: .protocolError), + effect: nil + ) case .fullyQuiesced: - return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.ioOnClosedConnection(), type: .protocolError), effect: nil) + return .init( + result: .connectionError(underlyingError: NIOHTTP2Errors.ioOnClosedConnection(), type: .protocolError), + effect: nil + ) case .modifying: preconditionFailure("Must not be left in modifying state") @@ -979,10 +1154,16 @@ extension HTTP2ConnectionStateMachine { case .idle, .prefaceSent, .quiescingPrefaceSent: // We're waiting for the remote preface. - return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.missingPreface(), type: .protocolError), effect: nil) + return .init( + result: .connectionError(underlyingError: NIOHTTP2Errors.missingPreface(), type: .protocolError), + effect: nil + ) case .fullyQuiesced: - return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.ioOnClosedConnection(), type: .protocolError), effect: nil) + return .init( + result: .connectionError(underlyingError: NIOHTTP2Errors.ioOnClosedConnection(), type: .protocolError), + effect: nil + ) case .modifying: preconditionFailure("Must not be left in modifying state") @@ -1039,7 +1220,10 @@ extension HTTP2ConnectionStateMachine { case .idle, .prefaceReceived, .quiescingPrefaceReceived: // We're waiting for the local preface. - return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.missingPreface(), type: .protocolError), effect: nil) + return .init( + result: .connectionError(underlyingError: NIOHTTP2Errors.missingPreface(), type: .protocolError), + effect: nil + ) case .fullyQuiesced: // We allow RST_STREAM frames to be sent because when a server receives a HEADERS frame in this state (say, a client sends @@ -1056,7 +1240,11 @@ extension HTTP2ConnectionStateMachine { /// /// If this method returns a stream error, the stream error should be assumed to apply to both the original /// and child stream. - mutating func receivePushPromise(originalStreamID: HTTP2StreamID, childStreamID: HTTP2StreamID, headers: HPACKHeaders) -> StateMachineResultWithEffect { + mutating func receivePushPromise( + originalStreamID: HTTP2StreamID, + childStreamID: HTTP2StreamID, + headers: HPACKHeaders + ) -> StateMachineResultWithEffect { // In states that support a push promise we have two steps. Firstly, we want to create the child stream; then we want to // pass the PUSH_PROMISE frame through the stream state machine for the parent stream. // @@ -1068,98 +1256,160 @@ extension HTTP2ConnectionStateMachine { switch self.state { case .prefaceReceived(var state): return self.avoidingStateMachineCoW { newState in - let result = state.receivePushPromise(originalStreamID: originalStreamID, childStreamID: childStreamID, headers: headers) + let result = state.receivePushPromise( + originalStreamID: originalStreamID, + childStreamID: childStreamID, + headers: headers + ) newState = .prefaceReceived(state) return result } case .active(var state): return self.avoidingStateMachineCoW { newState in - let result = state.receivePushPromise(originalStreamID: originalStreamID, childStreamID: childStreamID, headers: headers) + let result = state.receivePushPromise( + originalStreamID: originalStreamID, + childStreamID: childStreamID, + headers: headers + ) newState = .active(state) return result } case .locallyQuiesced(var state): return self.avoidingStateMachineCoW { newState in - let result = state.receivePushPromise(originalStreamID: originalStreamID, childStreamID: childStreamID, headers: headers) + let result = state.receivePushPromise( + originalStreamID: originalStreamID, + childStreamID: childStreamID, + headers: headers + ) newState = .locallyQuiesced(state) return result } case .remotelyQuiesced(var state): return self.avoidingStateMachineCoW { newState in - let result = state.receivePushPromise(originalStreamID: originalStreamID, childStreamID: childStreamID, headers: headers) + let result = state.receivePushPromise( + originalStreamID: originalStreamID, + childStreamID: childStreamID, + headers: headers + ) newState = .remotelyQuiesced(state) return result } case .bothQuiescing(var state): return self.avoidingStateMachineCoW { newState in - let result = state.receivePushPromise(originalStreamID: originalStreamID, childStreamID: childStreamID, headers: headers) + let result = state.receivePushPromise( + originalStreamID: originalStreamID, + childStreamID: childStreamID, + headers: headers + ) newState = .bothQuiescing(state) return result } case .quiescingPrefaceReceived(var state): return self.avoidingStateMachineCoW { newState in - let result = state.receivePushPromise(originalStreamID: originalStreamID, childStreamID: childStreamID, headers: headers) + let result = state.receivePushPromise( + originalStreamID: originalStreamID, + childStreamID: childStreamID, + headers: headers + ) newState = .quiescingPrefaceReceived(state) return result } case .idle, .prefaceSent, .quiescingPrefaceSent: // We're waiting for the remote preface. - return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.missingPreface(), type: .protocolError), effect: nil) + return .init( + result: .connectionError(underlyingError: NIOHTTP2Errors.missingPreface(), type: .protocolError), + effect: nil + ) case .fullyQuiesced: - return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.ioOnClosedConnection(), type: .protocolError), effect: nil) + return .init( + result: .connectionError(underlyingError: NIOHTTP2Errors.ioOnClosedConnection(), type: .protocolError), + effect: nil + ) case .modifying: preconditionFailure("Must not be left in modifying state") } } - mutating func sendPushPromise(originalStreamID: HTTP2StreamID, childStreamID: HTTP2StreamID, headers: HPACKHeaders) -> StateMachineResultWithEffect { + mutating func sendPushPromise( + originalStreamID: HTTP2StreamID, + childStreamID: HTTP2StreamID, + headers: HPACKHeaders + ) -> StateMachineResultWithEffect { switch self.state { case .prefaceSent(var state): return self.avoidingStateMachineCoW { newState in - let result = state.sendPushPromise(originalStreamID: originalStreamID, childStreamID: childStreamID, headers: headers) + let result = state.sendPushPromise( + originalStreamID: originalStreamID, + childStreamID: childStreamID, + headers: headers + ) newState = .prefaceSent(state) return result } case .active(var state): return self.avoidingStateMachineCoW { newState in - let result = state.sendPushPromise(originalStreamID: originalStreamID, childStreamID: childStreamID, headers: headers) + let result = state.sendPushPromise( + originalStreamID: originalStreamID, + childStreamID: childStreamID, + headers: headers + ) newState = .active(state) return result } case .locallyQuiesced(var state): return self.avoidingStateMachineCoW { newState in - let result = state.sendPushPromise(originalStreamID: originalStreamID, childStreamID: childStreamID, headers: headers) + let result = state.sendPushPromise( + originalStreamID: originalStreamID, + childStreamID: childStreamID, + headers: headers + ) newState = .locallyQuiesced(state) return result } case .remotelyQuiesced, .bothQuiescing: // We have been quiesced, and may not create new streams. - return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.createdStreamAfterGoaway(), type: .protocolError), effect: nil) + return .init( + result: .connectionError( + underlyingError: NIOHTTP2Errors.createdStreamAfterGoaway(), + type: .protocolError + ), + effect: nil + ) case .quiescingPrefaceSent(var state): return self.avoidingStateMachineCoW { newState in - let result = state.sendPushPromise(originalStreamID: originalStreamID, childStreamID: childStreamID, headers: headers) + let result = state.sendPushPromise( + originalStreamID: originalStreamID, + childStreamID: childStreamID, + headers: headers + ) newState = .quiescingPrefaceSent(state) return result } case .idle, .prefaceReceived, .quiescingPrefaceReceived: // We're waiting for the local preface. - return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.missingPreface(), type: .protocolError), effect: nil) + return .init( + result: .connectionError(underlyingError: NIOHTTP2Errors.missingPreface(), type: .protocolError), + effect: nil + ) case .fullyQuiesced: - return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.ioOnClosedConnection(), type: .protocolError), effect: nil) + return .init( + result: .connectionError(underlyingError: NIOHTTP2Errors.ioOnClosedConnection(), type: .protocolError), + effect: nil + ) case .modifying: preconditionFailure("Must not be left in modifying state") @@ -1172,12 +1422,18 @@ extension HTTP2ConnectionStateMachine { // RFC 7540 that says that receiving PINGs with ACK flags set when no PING ACKs are expected is forbidden. This is // very strange, but we allow it. switch self.state { - case .prefaceReceived, .active, .locallyQuiesced, .remotelyQuiesced, .bothQuiescing, .quiescingPrefaceReceived, .fullyQuiesced: + case .prefaceReceived, .active, .locallyQuiesced, .remotelyQuiesced, .bothQuiescing, .quiescingPrefaceReceived, + .fullyQuiesced: return (.init(result: .succeed, effect: nil), ackFlagSet ? .nothing : .sendAck) case .idle, .prefaceSent, .quiescingPrefaceSent: // We're waiting for the remote preface. - return (.init(result: .connectionError(underlyingError: NIOHTTP2Errors.missingPreface(), type: .protocolError), effect: nil), .nothing) + return ( + .init( + result: .connectionError(underlyingError: NIOHTTP2Errors.missingPreface(), type: .protocolError), + effect: nil + ), .nothing + ) case .modifying: preconditionFailure("Must not be left in modifying state") @@ -1190,19 +1446,22 @@ extension HTTP2ConnectionStateMachine { // RFC 7540 that says that sending PINGs with ACK flags set when no PING ACKs are expected is forbidden. This is // very strange, but we allow it. switch self.state { - case .prefaceSent, .active, .locallyQuiesced, .remotelyQuiesced, .bothQuiescing, .quiescingPrefaceSent, .fullyQuiesced: + case .prefaceSent, .active, .locallyQuiesced, .remotelyQuiesced, .bothQuiescing, .quiescingPrefaceSent, + .fullyQuiesced: return .init(result: .succeed, effect: nil) case .idle, .prefaceReceived, .quiescingPrefaceReceived: // We're waiting for the local preface. - return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.missingPreface(), type: .protocolError), effect: nil) + return .init( + result: .connectionError(underlyingError: NIOHTTP2Errors.missingPreface(), type: .protocolError), + effect: nil + ) case .modifying: preconditionFailure("Must not be left in modifying state") } } - /// Called when we receive a GOAWAY frame. mutating func receiveGoaway(lastStreamID: HTTP2StreamID) -> StateMachineResultWithEffect { // GOAWAY frames are some of the most subtle frames in HTTP/2, they cause a number of state transitions all at once. @@ -1261,7 +1520,10 @@ extension HTTP2ConnectionStateMachine { case .idle, .prefaceSent, .quiescingPrefaceSent: // We're waiting for the preface. - return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.missingPreface(), type: .protocolError), effect: nil) + return .init( + result: .connectionError(underlyingError: NIOHTTP2Errors.missingPreface(), type: .protocolError), + effect: nil + ) case .fullyQuiesced(var state): return self.avoidingStateMachineCoW { newState in @@ -1334,7 +1596,10 @@ extension HTTP2ConnectionStateMachine { case .idle, .prefaceReceived, .quiescingPrefaceReceived: // We're waiting for the preface. - return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.missingPreface(), type: .protocolError), effect: nil) + return .init( + result: .connectionError(underlyingError: NIOHTTP2Errors.missingPreface(), type: .protocolError), + effect: nil + ) case .fullyQuiesced(var state): return self.avoidingStateMachineCoW { newState in @@ -1350,7 +1615,8 @@ extension HTTP2ConnectionStateMachine { } /// Called when a WINDOW_UPDATE frame has been received. - mutating func receiveWindowUpdate(streamID: HTTP2StreamID, windowIncrement: UInt32) -> StateMachineResultWithEffect { + mutating func receiveWindowUpdate(streamID: HTTP2StreamID, windowIncrement: UInt32) -> StateMachineResultWithEffect + { switch self.state { case .prefaceReceived(var state): return self.avoidingStateMachineCoW { newState in @@ -1396,10 +1662,16 @@ extension HTTP2ConnectionStateMachine { case .idle, .prefaceSent, .quiescingPrefaceSent: // We're waiting for the preface. - return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.missingPreface(), type: .protocolError), effect: nil) + return .init( + result: .connectionError(underlyingError: NIOHTTP2Errors.missingPreface(), type: .protocolError), + effect: nil + ) case .fullyQuiesced: - return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.ioOnClosedConnection(), type: .protocolError), effect: nil) + return .init( + result: .connectionError(underlyingError: NIOHTTP2Errors.ioOnClosedConnection(), type: .protocolError), + effect: nil + ) case .modifying: preconditionFailure("Must not be left in modifying state") @@ -1453,10 +1725,16 @@ extension HTTP2ConnectionStateMachine { case .idle, .prefaceReceived, .quiescingPrefaceReceived: // We're waiting for the preface. - return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.missingPreface(), type: .protocolError), effect: nil) + return .init( + result: .connectionError(underlyingError: NIOHTTP2Errors.missingPreface(), type: .protocolError), + effect: nil + ) case .fullyQuiesced: - return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.ioOnClosedConnection(), type: .protocolError), effect: nil) + return .init( + result: .connectionError(underlyingError: NIOHTTP2Errors.ioOnClosedConnection(), type: .protocolError), + effect: nil + ) case .modifying: preconditionFailure("Must not be left in modifying state") @@ -1473,7 +1751,7 @@ extension HTTP2ConnectionStateMachine { // > The ALTSVC frame is a non-critical extension to HTTP/2. Endpoints // > that do not support this frame will ignore it (as per the // > extensibility rules defined in Section 4.1 of RFC7540). - return .init(result: .ignoreFrame, effect: .none) + .init(result: .ignoreFrame, effect: .none) } /// Called when an ALTSVC frame is sent. @@ -1492,7 +1770,7 @@ extension HTTP2ConnectionStateMachine { // From RFC 8336 ยง 2.1: // > The ORIGIN frame is a non-critical extension to HTTP/2. Endpoints // > that do not support this frame can safely ignore it upon receipt. - return .init(result: .ignoreFrame, effect: .none) + .init(result: .ignoreFrame, effect: .none) } /// Called when an ORIGIN frame is sent. @@ -1506,7 +1784,10 @@ extension HTTP2ConnectionStateMachine { // Mark:- Private helper methods extension HTTP2ConnectionStateMachine { /// Called when we have received a SETTINGS frame from the remote peer. Applies the changes immediately. - private mutating func receiveSettingsChange(_ settings: HTTP2Settings, frameEncoder: inout HTTP2FrameEncoder) -> (StateMachineResultWithEffect, PostFrameOperation) { + private mutating func receiveSettingsChange( + _ settings: HTTP2Settings, + frameEncoder: inout HTTP2FrameEncoder + ) -> (StateMachineResultWithEffect, PostFrameOperation) { let validationResult = self.validateSettings(settings) guard case .succeed = validationResult else { @@ -1516,7 +1797,10 @@ extension HTTP2ConnectionStateMachine { switch self.state { case .idle(let state): return self.avoidingStateMachineCoW { newState in - var newStateData = PrefaceReceivedState(fromIdle: state, remoteSettings: HTTP2SettingsState(localState: false)) + var newStateData = PrefaceReceivedState( + fromIdle: state, + remoteSettings: HTTP2SettingsState(localState: false) + ) let result = newStateData.receiveSettingsChange(settings, frameEncoder: &frameEncoder) newState = .prefaceReceived(newStateData) return result @@ -1524,7 +1808,10 @@ extension HTTP2ConnectionStateMachine { case .prefaceSent(let state): return self.avoidingStateMachineCoW { newState in - var newStateData = ActiveConnectionState(fromPrefaceSent: state, remoteSettings: HTTP2SettingsState(localState: false)) + var newStateData = ActiveConnectionState( + fromPrefaceSent: state, + remoteSettings: HTTP2SettingsState(localState: false) + ) let result = newStateData.receiveSettingsChange(settings, frameEncoder: &frameEncoder) newState = .active(newStateData) return result @@ -1567,7 +1854,10 @@ extension HTTP2ConnectionStateMachine { case .quiescingPrefaceSent(let state): return self.avoidingStateMachineCoW { newState in - var newStateData = LocallyQuiescedState(fromQuiescingPrefaceSent: state, remoteSettings: HTTP2SettingsState(localState: false)) + var newStateData = LocallyQuiescedState( + fromQuiescingPrefaceSent: state, + remoteSettings: HTTP2SettingsState(localState: false) + ) let result = newStateData.receiveSettingsChange(settings, frameEncoder: &frameEncoder) newState = .locallyQuiesced(newStateData) return result @@ -1581,7 +1871,15 @@ extension HTTP2ConnectionStateMachine { } case .fullyQuiesced: - return (.init(result: .connectionError(underlyingError: NIOHTTP2Errors.ioOnClosedConnection(), type: .protocolError), effect: nil), .nothing) + return ( + .init( + result: .connectionError( + underlyingError: NIOHTTP2Errors.ioOnClosedConnection(), + type: .protocolError + ), + effect: nil + ), .nothing + ) case .modifying: preconditionFailure("Must not be left in modifying state") @@ -1621,10 +1919,16 @@ extension HTTP2ConnectionStateMachine { } case .idle, .prefaceSent, .prefaceReceived, .quiescingPrefaceReceived, .quiescingPrefaceSent: - return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.receivedBadSettings(), type: .protocolError), effect: nil) + return .init( + result: .connectionError(underlyingError: NIOHTTP2Errors.receivedBadSettings(), type: .protocolError), + effect: nil + ) case .fullyQuiesced: - return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.ioOnClosedConnection(), type: .protocolError), effect: nil) + return .init( + result: .connectionError(underlyingError: NIOHTTP2Errors.ioOnClosedConnection(), type: .protocolError), + effect: nil + ) case .modifying: preconditionFailure("Must not be left in modifying state") @@ -1641,20 +1945,32 @@ extension HTTP2ConnectionStateMachine { switch setting.parameter { case .enablePush: guard setting._value == 0 || setting._value == 1 else { - return .connectionError(underlyingError: NIOHTTP2Errors.invalidSetting(setting: setting), type: .protocolError) + return .connectionError( + underlyingError: NIOHTTP2Errors.invalidSetting(setting: setting), + type: .protocolError + ) } case .initialWindowSize: guard setting._value <= HTTP2FlowControlWindow.maxSize else { - return .connectionError(underlyingError: NIOHTTP2Errors.invalidSetting(setting: setting), type: .flowControlError) + return .connectionError( + underlyingError: NIOHTTP2Errors.invalidSetting(setting: setting), + type: .flowControlError + ) } case .maxFrameSize: guard setting._value >= (1 << 14) && setting._value <= ((1 << 24) - 1) else { - return .connectionError(underlyingError: NIOHTTP2Errors.invalidSetting(setting: setting), type: .protocolError) + return .connectionError( + underlyingError: NIOHTTP2Errors.invalidSetting(setting: setting), + type: .protocolError + ) } case .enableConnectProtocol: // Must be 0 or 1 guard setting._value <= 1 else { - return .connectionError(underlyingError: NIOHTTP2Errors.invalidSetting(setting: setting), type: .protocolError) + return .connectionError( + underlyingError: NIOHTTP2Errors.invalidSetting(setting: setting), + type: .protocolError + ) } default: // All other settings have unrestricted ranges. @@ -1671,7 +1987,10 @@ extension HTTP2ConnectionStateMachine.State { // // We should only call this when a server has quiesced the connection. As long as only the client has quiesced the // connection more work can always be done. - mutating func closeIfNeeded(_ state: CurrentState) { + mutating func closeIfNeeded< + CurrentState: QuiescingState & LocallyQuiescingState & RemotelyQuiescingState & SendAndReceiveGoawayState + & ConnectionStateWithRole & ConnectionStateWithConfiguration + >(_ state: CurrentState) { if state.quiescedByServer && state.streamState.openStreams == 0 { self = .fullyQuiesced(.init(previousState: state)) } @@ -1681,7 +2000,10 @@ extension HTTP2ConnectionStateMachine.State { // // We should only call this when a server has quiesced the connection. As long as only the client has quiesced the // connection more work can always be done. - mutating func closeIfNeeded(_ state: CurrentState) { + mutating func closeIfNeeded< + CurrentState: QuiescingState & LocallyQuiescingState & SendAndReceiveGoawayState & ConnectionStateWithRole + & ConnectionStateWithConfiguration + >(_ state: CurrentState) { if state.quiescedByServer && state.streamState.openStreams == 0 { self = .fullyQuiesced(.init(previousState: state)) } @@ -1691,7 +2013,10 @@ extension HTTP2ConnectionStateMachine.State { // // We should only call this when a server has quiesced the connection. As long as only the client has quiesced the // connection more work can always be done. - mutating func closeIfNeeded(_ state: CurrentState) { + mutating func closeIfNeeded< + CurrentState: QuiescingState & RemotelyQuiescingState & SendAndReceiveGoawayState & ConnectionStateWithRole + & ConnectionStateWithConfiguration + >(_ state: CurrentState) { if state.quiescedByServer && state.streamState.openStreams == 0 { self = .fullyQuiesced(.init(previousState: state)) } @@ -1734,7 +2059,6 @@ extension HTTP2ConnectionStateMachine { } } - extension HTTP2StreamID { /// Confirms that this kind of stream ID may be initiated by a peer in the specific role. /// @@ -1750,7 +2074,6 @@ extension HTTP2StreamID { } } - /// A simple protocol that provides helpers that apply to all connection states that keep track of a role. protocol ConnectionStateWithRole { var role: HTTP2ConnectionStateMachine.ConnectionRole { get } @@ -1771,5 +2094,5 @@ extension ConnectionStateWithRole { private protocol ConnectionStateWithConfiguration { var headerBlockValidation: HTTP2ConnectionStateMachine.ValidationState { get } - var contentLengthValidation: HTTP2ConnectionStateMachine.ValidationState { get} + var contentLengthValidation: HTTP2ConnectionStateMachine.ValidationState { get } } diff --git a/Sources/NIOHTTP2/ConnectionStateMachine/ConnectionStreamsState.swift b/Sources/NIOHTTP2/ConnectionStateMachine/ConnectionStreamsState.swift index 46b5be4..3060d75 100644 --- a/Sources/NIOHTTP2/ConnectionStateMachine/ConnectionStreamsState.swift +++ b/Sources/NIOHTTP2/ConnectionStateMachine/ConnectionStreamsState.swift @@ -13,7 +13,6 @@ //===----------------------------------------------------------------------===// import NIOCore - /// A representation of the state of the HTTP/2 streams in a single HTTP/2 connection. struct ConnectionStreamState { /// The "safe" default value of SETTINGS_MAX_CONCURRENT_STREAMS. @@ -61,7 +60,7 @@ struct ConnectionStreamState { /// The total number of streams currently active. var openStreams: Int { - return Int(self.clientStreamCount) + Int(self.serverStreamCount) + Int(self.clientStreamCount) + Int(self.serverStreamCount) } init() { @@ -79,9 +78,17 @@ struct ConnectionStreamState { /// - remoteInitialWindowSize: The initial window size of the remote peer. /// - requestVerb: the HTTP method used on the request /// - throws: If the stream ID is invalid. - mutating func createRemotelyPushedStream(streamID: HTTP2StreamID, remoteInitialWindowSize: UInt32, requestVerb: String?) throws { + mutating func createRemotelyPushedStream( + streamID: HTTP2StreamID, + remoteInitialWindowSize: UInt32, + requestVerb: String? + ) throws { try self.reserveServerStreamID(streamID) - let streamState = HTTP2StreamStateMachine(receivedPushPromiseCreatingStreamID: streamID, remoteInitialWindowSize: remoteInitialWindowSize, requestVerb: requestVerb) + let streamState = HTTP2StreamStateMachine( + receivedPushPromiseCreatingStreamID: streamID, + remoteInitialWindowSize: remoteInitialWindowSize, + requestVerb: requestVerb + ) self.activeStreams.insert(streamState) } @@ -94,9 +101,17 @@ struct ConnectionStreamState { /// - streamID: The ID of the pushed stream. /// - localInitialWindowSize: Our initial window size.. /// - throws: If the stream ID is invalid. - mutating func createLocallyPushedStream(streamID: HTTP2StreamID, localInitialWindowSize: UInt32, requestVerb: String?) throws { + mutating func createLocallyPushedStream( + streamID: HTTP2StreamID, + localInitialWindowSize: UInt32, + requestVerb: String? + ) throws { try self.reserveServerStreamID(streamID) - let streamState = HTTP2StreamStateMachine(sentPushPromiseCreatingStreamID: streamID, localInitialWindowSize: localInitialWindowSize, requestVerb: requestVerb) + let streamState = HTTP2StreamStateMachine( + sentPushPromiseCreatingStreamID: streamID, + localInitialWindowSize: localInitialWindowSize, + requestVerb: requestVerb + ) self.activeStreams.insert(streamState) } @@ -113,17 +128,21 @@ struct ConnectionStreamState { /// - modifier: A block that will be invoked to modify the stream state, if present. /// - throws: Any errors thrown from the creator. /// - Returns: The result of the state modification, as well as any state change that occurred to the stream. - mutating func modifyStreamStateCreateIfNeeded(streamID: HTTP2StreamID, - localRole: HTTP2StreamStateMachine.StreamRole, - localInitialWindowSize: UInt32, - remoteInitialWindowSize: UInt32, - modifier: (inout HTTP2StreamStateMachine) -> StateMachineResultWithStreamEffect) throws -> StateMachineResultWithStreamEffect { + mutating func modifyStreamStateCreateIfNeeded( + streamID: HTTP2StreamID, + localRole: HTTP2StreamStateMachine.StreamRole, + localInitialWindowSize: UInt32, + remoteInitialWindowSize: UInt32, + modifier: (inout HTTP2StreamStateMachine) -> StateMachineResultWithStreamEffect + ) throws -> StateMachineResultWithStreamEffect { func creator() throws -> HTTP2StreamStateMachine { try self.reserveClientStreamID(streamID) - let initialValue = HTTP2StreamStateMachine(streamID: streamID, - localRole: localRole, - localInitialWindowSize: localInitialWindowSize, - remoteInitialWindowSize: remoteInitialWindowSize) + let initialValue = HTTP2StreamStateMachine( + streamID: streamID, + localRole: localRole, + localInitialWindowSize: localInitialWindowSize, + remoteInitialWindowSize: remoteInitialWindowSize + ) return initialValue } @@ -158,12 +177,21 @@ struct ConnectionStreamState { /// - ignoreClosed: Whether a closed stream should be ignored. Should be set to `true` when receiving window update or reset stream frames. /// - modifier: A block that will be invoked to modify the stream state, if present. /// - Returns: The result of the state modification, as well as any state change that occurred to the stream. - mutating func modifyStreamState(streamID: HTTP2StreamID, - ignoreRecentlyReset: Bool, - ignoreClosed: Bool = false, - _ modifier: (inout HTTP2StreamStateMachine) -> StateMachineResultWithStreamEffect) -> StateMachineResultWithStreamEffect { + mutating func modifyStreamState( + streamID: HTTP2StreamID, + ignoreRecentlyReset: Bool, + ignoreClosed: Bool = false, + _ modifier: (inout HTTP2StreamStateMachine) -> StateMachineResultWithStreamEffect + ) -> StateMachineResultWithStreamEffect { guard let result = self.activeStreams.autoClosingTransform(streamID: streamID, modifier) else { - return StateMachineResultWithStreamEffect(result: self.streamMissing(streamID: streamID, ignoreRecentlyReset: ignoreRecentlyReset, ignoreClosed: ignoreClosed), effect: nil) + return StateMachineResultWithStreamEffect( + result: self.streamMissing( + streamID: streamID, + ignoreRecentlyReset: ignoreRecentlyReset, + ignoreClosed: ignoreClosed + ), + effect: nil + ) } if let effect = result.effect, effect.closedStream { @@ -185,14 +213,18 @@ struct ConnectionStreamState { /// - modifier: A block that will be invoked to modify the stream state, if present. /// - Returns: The result of the state modification, as well as any state change that occurred to the stream. @inline(__always) - mutating func locallyResetStreamState(streamID: HTTP2StreamID, - _ modifier: (inout HTTP2StreamStateMachine) -> StateMachineResultWithStreamEffect) -> StateMachineResultWithStreamEffect { + mutating func locallyResetStreamState( + streamID: HTTP2StreamID, + _ modifier: (inout HTTP2StreamStateMachine) -> StateMachineResultWithStreamEffect + ) -> StateMachineResultWithStreamEffect { guard let result = self.activeStreams.autoClosingTransform(streamID: streamID, modifier) else { // We never ignore recently reset streams here, as this should only ever be used when *sending* frames. - return StateMachineResultWithStreamEffect(result: self.streamMissing(streamID: streamID, ignoreRecentlyReset: false, ignoreClosed: false), effect: nil) + return StateMachineResultWithStreamEffect( + result: self.streamMissing(streamID: streamID, ignoreRecentlyReset: false, ignoreClosed: false), + effect: nil + ) } - guard let effect = result.effect, effect.closedStream else { preconditionFailure("Locally resetting stream state did not close it!") } @@ -254,9 +286,11 @@ struct ConnectionStreamState { /// - droppedLocally: Whether this drop was caused by sending a GOAWAY frame or receiving it. /// - initiator: The peer that sent the GOAWAY frame. /// - Returns: the stream IDs closed by this operation. - mutating func dropAllStreamsWithIDHigherThan(_ streamID: HTTP2StreamID, - droppedLocally: Bool, - initiatedBy initiator: HTTP2ConnectionStateMachine.ConnectionRole) -> [HTTP2StreamID]? { + mutating func dropAllStreamsWithIDHigherThan( + _ streamID: HTTP2StreamID, + droppedLocally: Bool, + initiatedBy initiator: HTTP2ConnectionStateMachine.ConnectionRole + ) -> [HTTP2StreamID]? { var droppedIDs: [HTTP2StreamID] = [] self.activeStreams.dropDataWithStreamIDGreaterThan(streamID, initiatedBy: initiator) { data in droppedIDs = data.map { $0.streamID } @@ -287,22 +321,32 @@ struct ConnectionStreamState { /// - ignoreRecentlyReset: Whether a recently reset stream should be ignored. /// - ignoreClosed: Whether a closed stream should be ignored. /// - Returns: A `StateMachineResult` for this frame error. - private func streamMissing(streamID: HTTP2StreamID, ignoreRecentlyReset: Bool, ignoreClosed: Bool) -> StateMachineResult { + private func streamMissing( + streamID: HTTP2StreamID, + ignoreRecentlyReset: Bool, + ignoreClosed: Bool + ) -> StateMachineResult { if ignoreRecentlyReset && self.recentlyResetStreams.contains(streamID) { return .ignoreFrame } switch streamID.mayBeInitiatedBy(.client) { case true where streamID > self.lastClientStreamID, - false where streamID > self.lastServerStreamID: + false where streamID > self.lastServerStreamID: // The stream in question is idle. - return .connectionError(underlyingError: NIOHTTP2Errors.noSuchStream(streamID: streamID), type: .protocolError) + return .connectionError( + underlyingError: NIOHTTP2Errors.noSuchStream(streamID: streamID), + type: .protocolError + ) default: // This stream must have already been closed. if ignoreClosed { return .ignoreFrame } else { - return .connectionError(underlyingError: NIOHTTP2Errors.noSuchStream(streamID: streamID), type: .streamClosed) + return .connectionError( + underlyingError: NIOHTTP2Errors.noSuchStream(streamID: streamID), + type: .streamClosed + ) } } } @@ -317,11 +361,10 @@ struct ConnectionStreamState { } } - extension CircularBuffer { // CircularBuffer may never be "full": that is, capacity may never equal count. var effectiveCapacity: Int { - return self.capacity - 1 + self.capacity - 1 } /// Prepends `element` without expanding the capacity, by dropping the @@ -357,7 +400,6 @@ extension CircularBuffer { } } - extension StreamStateChange { fileprivate var closedStream: Bool { switch self { diff --git a/Sources/NIOHTTP2/ConnectionStateMachine/FrameReceivingStates/MayReceiveFrames.swift b/Sources/NIOHTTP2/ConnectionStateMachine/FrameReceivingStates/MayReceiveFrames.swift index a90ed0a..d12dbc5 100644 --- a/Sources/NIOHTTP2/ConnectionStateMachine/FrameReceivingStates/MayReceiveFrames.swift +++ b/Sources/NIOHTTP2/ConnectionStateMachine/FrameReceivingStates/MayReceiveFrames.swift @@ -22,4 +22,5 @@ protocol MayReceiveFrames: ReceivingPushPromiseState, ReceivingWindowUpdateState, ReceivingRstStreamState, - ReceivingGoawayState { } + ReceivingGoawayState +{} diff --git a/Sources/NIOHTTP2/ConnectionStateMachine/FrameReceivingStates/ReceivingDataState.swift b/Sources/NIOHTTP2/ConnectionStateMachine/FrameReceivingStates/ReceivingDataState.swift index 3becaf1..8e1ac09 100644 --- a/Sources/NIOHTTP2/ConnectionStateMachine/FrameReceivingStates/ReceivingDataState.swift +++ b/Sources/NIOHTTP2/ConnectionStateMachine/FrameReceivingStates/ReceivingDataState.swift @@ -24,17 +24,29 @@ protocol ReceivingDataState: HasFlowControlWindows { extension ReceivingDataState { /// Called to receive a DATA frame. - mutating func receiveData(streamID: HTTP2StreamID, contentLength: Int, flowControlledBytes: Int, isEndStreamSet endStream: Bool) -> StateMachineResultWithEffect { + mutating func receiveData( + streamID: HTTP2StreamID, + contentLength: Int, + flowControlledBytes: Int, + isEndStreamSet endStream: Bool + ) -> StateMachineResultWithEffect { do { try self.inboundFlowControlWindow.consume(flowControlledBytes: flowControlledBytes) } catch let error where error is NIOHTTP2Errors.FlowControlViolation { - return StateMachineResultWithEffect(result: .connectionError(underlyingError: error, type: .flowControlError), effect: nil) + return StateMachineResultWithEffect( + result: .connectionError(underlyingError: error, type: .flowControlError), + effect: nil + ) } catch { preconditionFailure("Unexpected error: \(error)") } let result = self.streamState.modifyStreamState(streamID: streamID, ignoreRecentlyReset: true) { - $0.receiveData(contentLength: contentLength, flowControlledBytes: flowControlledBytes, isEndStreamSet: endStream) + $0.receiveData( + contentLength: contentLength, + flowControlledBytes: flowControlledBytes, + isEndStreamSet: endStream + ) } // We need to be a bit careful here. The backing code may have triggered either an ignoreFrame or streamError. While both of these @@ -43,16 +55,26 @@ extension ReceivingDataState { } } - -private extension StateMachineResultWithEffect { - static func withGuaranteedFlowControlEffect(_ result: StateMachineResultWithStreamEffect, connectionState: ConnectionState) -> StateMachineResultWithEffect { +extension StateMachineResultWithEffect { + fileprivate static func withGuaranteedFlowControlEffect( + _ result: StateMachineResultWithStreamEffect, + connectionState: ConnectionState + ) -> StateMachineResultWithEffect { // In most cases, this will update the underlying effect with the new flow control window info. - var newResult = StateMachineResultWithEffect(result, - inboundFlowControlWindow: connectionState.inboundFlowControlWindow, - outboundFlowControlWindow: connectionState.outboundFlowControlWindow) + var newResult = StateMachineResultWithEffect( + result, + inboundFlowControlWindow: connectionState.inboundFlowControlWindow, + outboundFlowControlWindow: connectionState.outboundFlowControlWindow + ) if newResult.effect == nil { // But if we aren't noting it anywhere else, we note it here. - newResult.effect = .flowControlChange(.init(localConnectionWindowSize: Int(connectionState.outboundFlowControlWindow), remoteConnectionWindowSize: Int(connectionState.inboundFlowControlWindow), localStreamWindowSize: nil)) + newResult.effect = .flowControlChange( + .init( + localConnectionWindowSize: Int(connectionState.outboundFlowControlWindow), + remoteConnectionWindowSize: Int(connectionState.inboundFlowControlWindow), + localStreamWindowSize: nil + ) + ) } return newResult diff --git a/Sources/NIOHTTP2/ConnectionStateMachine/FrameReceivingStates/ReceivingGoAwayState.swift b/Sources/NIOHTTP2/ConnectionStateMachine/FrameReceivingStates/ReceivingGoAwayState.swift index ee4db49..fd13fdd 100644 --- a/Sources/NIOHTTP2/ConnectionStateMachine/FrameReceivingStates/ReceivingGoAwayState.swift +++ b/Sources/NIOHTTP2/ConnectionStateMachine/FrameReceivingStates/ReceivingGoAwayState.swift @@ -26,10 +26,20 @@ extension ReceivingGoawayState { mutating func receiveGoAwayFrame(lastStreamID: HTTP2StreamID) -> StateMachineResultWithEffect { guard lastStreamID.mayBeInitiatedBy(self.role) || lastStreamID == .rootStream || lastStreamID == .maxID else { // The remote peer has sent a GOAWAY with an invalid stream ID. - return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.invalidStreamIDForPeer(), type: .protocolError), effect: nil) + return .init( + result: .connectionError( + underlyingError: NIOHTTP2Errors.invalidStreamIDForPeer(), + type: .protocolError + ), + effect: nil + ) } - let droppedStreams = self.streamState.dropAllStreamsWithIDHigherThan(lastStreamID, droppedLocally: false, initiatedBy: self.role) + let droppedStreams = self.streamState.dropAllStreamsWithIDHigherThan( + lastStreamID, + droppedLocally: false, + initiatedBy: self.role + ) let effect: NIOHTTP2ConnectionStateChange? = droppedStreams.map { .bulkStreamClosure(.init(closedStreams: $0)) } return .init(result: .succeed, effect: effect) } @@ -39,18 +49,33 @@ extension ReceivingGoawayState where Self: RemotelyQuiescingState { mutating func receiveGoAwayFrame(lastStreamID: HTTP2StreamID) -> StateMachineResultWithEffect { guard lastStreamID.mayBeInitiatedBy(self.role) || lastStreamID == .rootStream || lastStreamID == .maxID else { // The remote peer has sent a GOAWAY with an invalid stream ID. - return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.invalidStreamIDForPeer(), type: .protocolError), effect: nil) + return .init( + result: .connectionError( + underlyingError: NIOHTTP2Errors.invalidStreamIDForPeer(), + type: .protocolError + ), + effect: nil + ) } if lastStreamID > self.lastLocalStreamID { // The remote peer has attempted to raise the lastStreamID. - return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.raisedGoawayLastStreamID(), type: .protocolError), effect: nil) + return .init( + result: .connectionError( + underlyingError: NIOHTTP2Errors.raisedGoawayLastStreamID(), + type: .protocolError + ), + effect: nil + ) } - let droppedStreams = self.streamState.dropAllStreamsWithIDHigherThan(lastStreamID, droppedLocally: false, initiatedBy: self.role) + let droppedStreams = self.streamState.dropAllStreamsWithIDHigherThan( + lastStreamID, + droppedLocally: false, + initiatedBy: self.role + ) let effect: NIOHTTP2ConnectionStateChange? = droppedStreams.map { .bulkStreamClosure(.init(closedStreams: $0)) } self.lastLocalStreamID = lastStreamID return .init(result: .succeed, effect: effect) } } - diff --git a/Sources/NIOHTTP2/ConnectionStateMachine/FrameReceivingStates/ReceivingHeadersState.swift b/Sources/NIOHTTP2/ConnectionStateMachine/FrameReceivingStates/ReceivingHeadersState.swift index b8d53e0..6a8d4fa 100644 --- a/Sources/NIOHTTP2/ConnectionStateMachine/FrameReceivingStates/ReceivingHeadersState.swift +++ b/Sources/NIOHTTP2/ConnectionStateMachine/FrameReceivingStates/ReceivingHeadersState.swift @@ -17,7 +17,9 @@ import NIOHPACK /// can validly accept headers. /// /// This protocol should only be conformed to by states for the HTTP/2 connection state machine. -protocol ReceivingHeadersState: HasFlowControlWindows, HasLocalExtendedConnectSettings, HasRemoteExtendedConnectSettings, ConnectionStateWithRole { +protocol ReceivingHeadersState: HasFlowControlWindows, HasLocalExtendedConnectSettings, + HasRemoteExtendedConnectSettings, ConnectionStateWithRole +{ var role: HTTP2ConnectionStateMachine.ConnectionRole { get } var headerBlockValidation: HTTP2ConnectionStateMachine.ValidationState { get } @@ -33,7 +35,11 @@ protocol ReceivingHeadersState: HasFlowControlWindows, HasLocalExtendedConnectSe extension ReceivingHeadersState { /// Called when we receive a HEADERS frame in this state. - mutating func receiveHeaders(streamID: HTTP2StreamID, headers: HPACKHeaders, isEndStreamSet endStream: Bool) -> StateMachineResultWithEffect { + mutating func receiveHeaders( + streamID: HTTP2StreamID, + headers: HPACKHeaders, + isEndStreamSet endStream: Bool + ) -> StateMachineResultWithEffect { let result: StateMachineResultWithStreamEffect let validateHeaderBlock = self.headerBlockValidation == .enabled let validateContentLength = self.contentLengthValidation == .enabled @@ -42,33 +48,60 @@ extension ReceivingHeadersState { if self.role == .server && streamID.mayBeInitiatedBy(.client) { do { - result = try self.streamState.modifyStreamStateCreateIfNeeded(streamID: streamID, localRole: .server, localInitialWindowSize: self.localInitialWindowSize, remoteInitialWindowSize: self.remoteInitialWindowSize) { - $0.receiveHeaders(headers: headers, validateHeaderBlock: validateHeaderBlock, validateContentLength: validateContentLength, localSupportsExtendedConnect: localSupportsExtendedConnect, remoteSupportsExtendedConnect: remoteSupportsExtendedConnect, isEndStreamSet: endStream) + result = try self.streamState.modifyStreamStateCreateIfNeeded( + streamID: streamID, + localRole: .server, + localInitialWindowSize: self.localInitialWindowSize, + remoteInitialWindowSize: self.remoteInitialWindowSize + ) { + $0.receiveHeaders( + headers: headers, + validateHeaderBlock: validateHeaderBlock, + validateContentLength: validateContentLength, + localSupportsExtendedConnect: localSupportsExtendedConnect, + remoteSupportsExtendedConnect: remoteSupportsExtendedConnect, + isEndStreamSet: endStream + ) } } catch { - return StateMachineResultWithEffect(result: .connectionError(underlyingError: error, type: .protocolError), effect: nil) + return StateMachineResultWithEffect( + result: .connectionError(underlyingError: error, type: .protocolError), + effect: nil + ) } } else { // HEADERS cannot create streams for servers, so this must be for a stream we already know about. result = self.streamState.modifyStreamState(streamID: streamID, ignoreRecentlyReset: true) { - $0.receiveHeaders(headers: headers, validateHeaderBlock: validateHeaderBlock, validateContentLength: validateContentLength, localSupportsExtendedConnect: localSupportsExtendedConnect, remoteSupportsExtendedConnect: remoteSupportsExtendedConnect, isEndStreamSet: endStream) + $0.receiveHeaders( + headers: headers, + validateHeaderBlock: validateHeaderBlock, + validateContentLength: validateContentLength, + localSupportsExtendedConnect: localSupportsExtendedConnect, + remoteSupportsExtendedConnect: remoteSupportsExtendedConnect, + isEndStreamSet: endStream + ) } } - return StateMachineResultWithEffect(result, - inboundFlowControlWindow: self.inboundFlowControlWindow, - outboundFlowControlWindow: self.outboundFlowControlWindow) + return StateMachineResultWithEffect( + result, + inboundFlowControlWindow: self.inboundFlowControlWindow, + outboundFlowControlWindow: self.outboundFlowControlWindow + ) } } - extension ReceivingHeadersState where Self: LocallyQuiescingState { /// Called when we receive a HEADERS frame in this state. /// /// If we've quiesced this connection, the remote peer is no longer allowed to create new streams. /// We ignore any frame that appears to be creating a new stream, and then prevent this from creating /// new streams. - mutating func receiveHeaders(streamID: HTTP2StreamID, headers: HPACKHeaders, isEndStreamSet endStream: Bool) -> StateMachineResultWithEffect { + mutating func receiveHeaders( + streamID: HTTP2StreamID, + headers: HPACKHeaders, + isEndStreamSet endStream: Bool + ) -> StateMachineResultWithEffect { let validateHeaderBlock = self.headerBlockValidation == .enabled let validateContentLength = self.contentLengthValidation == .enabled let localSupportsExtendedConnect = self.localSupportsExtendedConnect @@ -83,10 +116,19 @@ extension ReceivingHeadersState where Self: LocallyQuiescingState { // At this stage we've quiesced, so the remote peer is not allowed to create new streams. let result = self.streamState.modifyStreamState(streamID: streamID, ignoreRecentlyReset: true) { - $0.receiveHeaders(headers: headers, validateHeaderBlock: validateHeaderBlock, validateContentLength: validateContentLength, localSupportsExtendedConnect: localSupportsExtendedConnect, remoteSupportsExtendedConnect: remoteSupportsExtendedConnect, isEndStreamSet: endStream) + $0.receiveHeaders( + headers: headers, + validateHeaderBlock: validateHeaderBlock, + validateContentLength: validateContentLength, + localSupportsExtendedConnect: localSupportsExtendedConnect, + remoteSupportsExtendedConnect: remoteSupportsExtendedConnect, + isEndStreamSet: endStream + ) } - return StateMachineResultWithEffect(result, - inboundFlowControlWindow: self.inboundFlowControlWindow, - outboundFlowControlWindow: self.outboundFlowControlWindow) + return StateMachineResultWithEffect( + result, + inboundFlowControlWindow: self.inboundFlowControlWindow, + outboundFlowControlWindow: self.outboundFlowControlWindow + ) } } diff --git a/Sources/NIOHTTP2/ConnectionStateMachine/FrameReceivingStates/ReceivingPushPromiseState.swift b/Sources/NIOHTTP2/ConnectionStateMachine/FrameReceivingStates/ReceivingPushPromiseState.swift index 9037669..cbdad76 100644 --- a/Sources/NIOHTTP2/ConnectionStateMachine/FrameReceivingStates/ReceivingPushPromiseState.swift +++ b/Sources/NIOHTTP2/ConnectionStateMachine/FrameReceivingStates/ReceivingPushPromiseState.swift @@ -30,11 +30,19 @@ protocol ReceivingPushPromiseState: HasFlowControlWindows { } extension ReceivingPushPromiseState { - mutating func receivePushPromise(originalStreamID: HTTP2StreamID, childStreamID: HTTP2StreamID, headers: HPACKHeaders) -> StateMachineResultWithEffect { - return self._receivePushPromise(originalStreamID: originalStreamID, childStreamID: childStreamID, headers: headers) + mutating func receivePushPromise( + originalStreamID: HTTP2StreamID, + childStreamID: HTTP2StreamID, + headers: HPACKHeaders + ) -> StateMachineResultWithEffect { + self._receivePushPromise(originalStreamID: originalStreamID, childStreamID: childStreamID, headers: headers) } - fileprivate mutating func _receivePushPromise(originalStreamID: HTTP2StreamID, childStreamID: HTTP2StreamID, headers: HPACKHeaders) -> StateMachineResultWithEffect { + fileprivate mutating func _receivePushPromise( + originalStreamID: HTTP2StreamID, + childStreamID: HTTP2StreamID, + headers: HPACKHeaders + ) -> StateMachineResultWithEffect { // In states that support a push promise we have two steps. Firstly, we want to create the child stream; then we want to // pass the PUSH_PROMISE frame through the stream state machine for the parent stream. // @@ -46,38 +54,62 @@ extension ReceivingPushPromiseState { // // Before any of this, though, we need to check whether the remote peer is even allowed to push! guard self.peerMayPush else { - return StateMachineResultWithEffect(result: .connectionError(underlyingError: NIOHTTP2Errors.pushInViolationOfSetting(), type: .protocolError), effect: nil) + return StateMachineResultWithEffect( + result: .connectionError( + underlyingError: NIOHTTP2Errors.pushInViolationOfSetting(), + type: .protocolError + ), + effect: nil + ) } let validateHeaderBlock = self.headerBlockValidation == .enabled let requestVerb = headers.first(name: ":method") do { - try self.streamState.createRemotelyPushedStream(streamID: childStreamID, - remoteInitialWindowSize: self.remoteInitialWindowSize, requestVerb: requestVerb) + try self.streamState.createRemotelyPushedStream( + streamID: childStreamID, + remoteInitialWindowSize: self.remoteInitialWindowSize, + requestVerb: requestVerb + ) let result = self.streamState.modifyStreamState(streamID: originalStreamID, ignoreRecentlyReset: true) { $0.receivePushPromise(headers: headers, validateHeaderBlock: validateHeaderBlock) } - return StateMachineResultWithEffect(result, - inboundFlowControlWindow: self.inboundFlowControlWindow, - outboundFlowControlWindow: self.outboundFlowControlWindow) + return StateMachineResultWithEffect( + result, + inboundFlowControlWindow: self.inboundFlowControlWindow, + outboundFlowControlWindow: self.outboundFlowControlWindow + ) } catch { - return StateMachineResultWithEffect(result: .connectionError(underlyingError: error, type: .protocolError), effect: nil) + return StateMachineResultWithEffect( + result: .connectionError(underlyingError: error, type: .protocolError), + effect: nil + ) } } /// Whether the remote peer may push. var peerMayPush: Bool { // In the case where we don't have local settings, we have to assume the default value, in which servers may push and clients may not. - return self.role == .client + self.role == .client } } extension ReceivingPushPromiseState where Self: LocallyQuiescingState { - mutating func receivePushPromise(originalStreamID: HTTP2StreamID, childStreamID: HTTP2StreamID, headers: HPACKHeaders) -> StateMachineResultWithEffect { + mutating func receivePushPromise( + originalStreamID: HTTP2StreamID, + childStreamID: HTTP2StreamID, + headers: HPACKHeaders + ) -> StateMachineResultWithEffect { // This check is duplicated here, because the protocol error of violating this setting is more important than ignoring the frame. guard self.peerMayPush else { - return StateMachineResultWithEffect(result: .connectionError(underlyingError: NIOHTTP2Errors.pushInViolationOfSetting(), type: .protocolError), effect: nil) + return StateMachineResultWithEffect( + result: .connectionError( + underlyingError: NIOHTTP2Errors.pushInViolationOfSetting(), + type: .protocolError + ), + effect: nil + ) } // If we're a client, the server is forbidden from initiating new streams, as we quiesced. However, RFC 7540 wants us to ignore this. @@ -87,12 +119,16 @@ extension ReceivingPushPromiseState where Self: LocallyQuiescingState { // We're a server, so the remote peer can't initiate a stream with a PUSH_PROMISE, but that's ok, the stream state machine // will forbid this as it normally does. - return self._receivePushPromise(originalStreamID: originalStreamID, childStreamID: childStreamID, headers: headers) + return self._receivePushPromise( + originalStreamID: originalStreamID, + childStreamID: childStreamID, + headers: headers + ) } } extension ReceivingPushPromiseState where Self: HasLocalSettings { var peerMayPush: Bool { - return self.localSettings.enablePush == 1 && self.role == .client + self.localSettings.enablePush == 1 && self.role == .client } } diff --git a/Sources/NIOHTTP2/ConnectionStateMachine/FrameReceivingStates/ReceivingRstStreamState.swift b/Sources/NIOHTTP2/ConnectionStateMachine/FrameReceivingStates/ReceivingRstStreamState.swift index ac84dec..f3aa4f1 100644 --- a/Sources/NIOHTTP2/ConnectionStateMachine/FrameReceivingStates/ReceivingRstStreamState.swift +++ b/Sources/NIOHTTP2/ConnectionStateMachine/FrameReceivingStates/ReceivingRstStreamState.swift @@ -25,11 +25,17 @@ extension ReceivingRstStreamState { mutating func receiveRstStream(streamID: HTTP2StreamID, reason: HTTP2ErrorCode) -> StateMachineResultWithEffect { // RFC 7540 ยง 6.4 does not explicitly forbid a peer sending // multiple RST_STREAMs for the same stream which means we should ignore subsequent RST_STREAMs. - let result = self.streamState.modifyStreamState(streamID: streamID, ignoreRecentlyReset: true, ignoreClosed: true) { + let result = self.streamState.modifyStreamState( + streamID: streamID, + ignoreRecentlyReset: true, + ignoreClosed: true + ) { $0.receiveRstStream(reason: reason) } - return StateMachineResultWithEffect(result, - inboundFlowControlWindow: self.inboundFlowControlWindow, - outboundFlowControlWindow: self.outboundFlowControlWindow) + return StateMachineResultWithEffect( + result, + inboundFlowControlWindow: self.inboundFlowControlWindow, + outboundFlowControlWindow: self.outboundFlowControlWindow + ) } } diff --git a/Sources/NIOHTTP2/ConnectionStateMachine/FrameReceivingStates/ReceivingWindowUpdateState.swift b/Sources/NIOHTTP2/ConnectionStateMachine/FrameReceivingStates/ReceivingWindowUpdateState.swift index ec8d1e0..18fdec2 100644 --- a/Sources/NIOHTTP2/ConnectionStateMachine/FrameReceivingStates/ReceivingWindowUpdateState.swift +++ b/Sources/NIOHTTP2/ConnectionStateMachine/FrameReceivingStates/ReceivingWindowUpdateState.swift @@ -28,25 +28,41 @@ extension ReceivingWindowUpdateState { // This is an update for the connection. We police the errors here. do { try self.outboundFlowControlWindow.windowUpdate(by: increment) - let flowControlSize: NIOHTTP2ConnectionStateChange = .flowControlChange(.init(localConnectionWindowSize: Int(self.outboundFlowControlWindow), - remoteConnectionWindowSize: Int(self.inboundFlowControlWindow), - localStreamWindowSize: nil)) + let flowControlSize: NIOHTTP2ConnectionStateChange = .flowControlChange( + .init( + localConnectionWindowSize: Int(self.outboundFlowControlWindow), + remoteConnectionWindowSize: Int(self.inboundFlowControlWindow), + localStreamWindowSize: nil + ) + ) return StateMachineResultWithEffect(result: .succeed, effect: flowControlSize) } catch let error where error is NIOHTTP2Errors.InvalidFlowControlWindowSize { - return StateMachineResultWithEffect(result: .connectionError(underlyingError: error, type: .flowControlError), effect: nil) + return StateMachineResultWithEffect( + result: .connectionError(underlyingError: error, type: .flowControlError), + effect: nil + ) } catch let error where error is NIOHTTP2Errors.InvalidWindowIncrementSize { - return StateMachineResultWithEffect(result: .connectionError(underlyingError: error, type: .protocolError), effect: nil) + return StateMachineResultWithEffect( + result: .connectionError(underlyingError: error, type: .protocolError), + effect: nil + ) } catch { preconditionFailure("Unexpected error: \(error)") } } else { // This is an update for a specific stream: it's responsible for policing any errors. - let result = self.streamState.modifyStreamState(streamID: streamID, ignoreRecentlyReset: true, ignoreClosed: true) { + let result = self.streamState.modifyStreamState( + streamID: streamID, + ignoreRecentlyReset: true, + ignoreClosed: true + ) { $0.receiveWindowUpdate(windowIncrement: increment) } - return StateMachineResultWithEffect(result, - inboundFlowControlWindow: self.inboundFlowControlWindow, - outboundFlowControlWindow: self.outboundFlowControlWindow) + return StateMachineResultWithEffect( + result, + inboundFlowControlWindow: self.inboundFlowControlWindow, + outboundFlowControlWindow: self.outboundFlowControlWindow + ) } } } diff --git a/Sources/NIOHTTP2/ConnectionStateMachine/FrameSendingStates/MaySendFrames.swift b/Sources/NIOHTTP2/ConnectionStateMachine/FrameSendingStates/MaySendFrames.swift index 886be79..8c5a616 100644 --- a/Sources/NIOHTTP2/ConnectionStateMachine/FrameSendingStates/MaySendFrames.swift +++ b/Sources/NIOHTTP2/ConnectionStateMachine/FrameSendingStates/MaySendFrames.swift @@ -22,4 +22,5 @@ protocol MaySendFrames: SendingPushPromiseState, SendingWindowUpdateState, SendingRstStreamState, - SendingGoawayState { } + SendingGoawayState +{} diff --git a/Sources/NIOHTTP2/ConnectionStateMachine/FrameSendingStates/SendingDataState.swift b/Sources/NIOHTTP2/ConnectionStateMachine/FrameSendingStates/SendingDataState.swift index 87f7e2d..cef4878 100644 --- a/Sources/NIOHTTP2/ConnectionStateMachine/FrameSendingStates/SendingDataState.swift +++ b/Sources/NIOHTTP2/ConnectionStateMachine/FrameSendingStates/SendingDataState.swift @@ -24,20 +24,34 @@ protocol SendingDataState: HasFlowControlWindows { extension SendingDataState { /// Called to send a DATA frame. - mutating func sendData(streamID: HTTP2StreamID, contentLength: Int, flowControlledBytes: Int, isEndStreamSet endStream: Bool) -> StateMachineResultWithEffect { + mutating func sendData( + streamID: HTTP2StreamID, + contentLength: Int, + flowControlledBytes: Int, + isEndStreamSet endStream: Bool + ) -> StateMachineResultWithEffect { do { try self.outboundFlowControlWindow.consume(flowControlledBytes: flowControlledBytes) } catch let error where error is NIOHTTP2Errors.FlowControlViolation { - return StateMachineResultWithEffect(result: .connectionError(underlyingError: error, type: .flowControlError), effect: nil) + return StateMachineResultWithEffect( + result: .connectionError(underlyingError: error, type: .flowControlError), + effect: nil + ) } catch { preconditionFailure("Unexpected error: \(error)") } let result = self.streamState.modifyStreamState(streamID: streamID, ignoreRecentlyReset: false) { - $0.sendData(contentLength: contentLength, flowControlledBytes: flowControlledBytes, isEndStreamSet: endStream) + $0.sendData( + contentLength: contentLength, + flowControlledBytes: flowControlledBytes, + isEndStreamSet: endStream + ) } - return StateMachineResultWithEffect(result, - inboundFlowControlWindow: self.inboundFlowControlWindow, - outboundFlowControlWindow: self.outboundFlowControlWindow) + return StateMachineResultWithEffect( + result, + inboundFlowControlWindow: self.inboundFlowControlWindow, + outboundFlowControlWindow: self.outboundFlowControlWindow + ) } } diff --git a/Sources/NIOHTTP2/ConnectionStateMachine/FrameSendingStates/SendingGoawayState.swift b/Sources/NIOHTTP2/ConnectionStateMachine/FrameSendingStates/SendingGoawayState.swift index 018080f..f5211f0 100644 --- a/Sources/NIOHTTP2/ConnectionStateMachine/FrameSendingStates/SendingGoawayState.swift +++ b/Sources/NIOHTTP2/ConnectionStateMachine/FrameSendingStates/SendingGoawayState.swift @@ -24,12 +24,23 @@ protocol SendingGoawayState { extension SendingGoawayState { mutating func sendGoAwayFrame(lastStreamID: HTTP2StreamID) -> StateMachineResultWithEffect { - guard lastStreamID.mayBeInitiatedBy(self.peerRole) || lastStreamID == .rootStream || lastStreamID == .maxID else { + guard lastStreamID.mayBeInitiatedBy(self.peerRole) || lastStreamID == .rootStream || lastStreamID == .maxID + else { // The user has sent a GOAWAY with an invalid stream ID. - return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.invalidStreamIDForPeer(), type: .protocolError), effect: nil) + return .init( + result: .connectionError( + underlyingError: NIOHTTP2Errors.invalidStreamIDForPeer(), + type: .protocolError + ), + effect: nil + ) } - let droppedStreams = self.streamState.dropAllStreamsWithIDHigherThan(lastStreamID, droppedLocally: true, initiatedBy: self.peerRole) + let droppedStreams = self.streamState.dropAllStreamsWithIDHigherThan( + lastStreamID, + droppedLocally: true, + initiatedBy: self.peerRole + ) let effect: NIOHTTP2ConnectionStateChange? = droppedStreams.map { .bulkStreamClosure(.init(closedStreams: $0)) } return .init(result: .succeed, effect: effect) } @@ -37,18 +48,35 @@ extension SendingGoawayState { extension SendingGoawayState where Self: LocallyQuiescingState { mutating func sendGoAwayFrame(lastStreamID: HTTP2StreamID) -> StateMachineResultWithEffect { - guard lastStreamID.mayBeInitiatedBy(self.peerRole) || lastStreamID == .rootStream || lastStreamID == .maxID else { + guard lastStreamID.mayBeInitiatedBy(self.peerRole) || lastStreamID == .rootStream || lastStreamID == .maxID + else { // The user has sent a GOAWAY with an invalid stream ID. - return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.invalidStreamIDForPeer(), type: .protocolError), effect: nil) + return .init( + result: .connectionError( + underlyingError: NIOHTTP2Errors.invalidStreamIDForPeer(), + type: .protocolError + ), + effect: nil + ) } if lastStreamID > self.lastRemoteStreamID { // The user has attempted to raise the lastStreamID. - return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.raisedGoawayLastStreamID(), type: .protocolError), effect: nil) + return .init( + result: .connectionError( + underlyingError: NIOHTTP2Errors.raisedGoawayLastStreamID(), + type: .protocolError + ), + effect: nil + ) } // Ok, this is a valid request, so we can now process it like .active. - let droppedStreams = self.streamState.dropAllStreamsWithIDHigherThan(lastStreamID, droppedLocally: true, initiatedBy: self.peerRole) + let droppedStreams = self.streamState.dropAllStreamsWithIDHigherThan( + lastStreamID, + droppedLocally: true, + initiatedBy: self.peerRole + ) let effect: NIOHTTP2ConnectionStateChange? = droppedStreams.map { .bulkStreamClosure(.init(closedStreams: $0)) } self.lastRemoteStreamID = lastStreamID return .init(result: .succeed, effect: effect) diff --git a/Sources/NIOHTTP2/ConnectionStateMachine/FrameSendingStates/SendingHeadersState.swift b/Sources/NIOHTTP2/ConnectionStateMachine/FrameSendingStates/SendingHeadersState.swift index bcbdfff..059d877 100644 --- a/Sources/NIOHTTP2/ConnectionStateMachine/FrameSendingStates/SendingHeadersState.swift +++ b/Sources/NIOHTTP2/ConnectionStateMachine/FrameSendingStates/SendingHeadersState.swift @@ -13,7 +13,6 @@ //===----------------------------------------------------------------------===// import NIOHPACK - /// A protocol that provides implementation for sending HEADERS frames, for those states that /// can validly send headers. /// @@ -34,7 +33,11 @@ protocol SendingHeadersState: HasFlowControlWindows, HasLocalExtendedConnectSett extension SendingHeadersState { /// Called when we send a HEADERS frame in this state. - mutating func sendHeaders(streamID: HTTP2StreamID, headers: HPACKHeaders, isEndStreamSet endStream: Bool) -> StateMachineResultWithEffect { + mutating func sendHeaders( + streamID: HTTP2StreamID, + headers: HPACKHeaders, + isEndStreamSet endStream: Bool + ) -> StateMachineResultWithEffect { let result: StateMachineResultWithStreamEffect let validateHeaderBlock = self.headerBlockValidation == .enabled let validateContentLength = self.contentLengthValidation == .enabled @@ -43,48 +46,83 @@ extension SendingHeadersState { if self.role == .client && streamID.mayBeInitiatedBy(.client) { do { - result = try self.streamState.modifyStreamStateCreateIfNeeded(streamID: streamID, - localRole: .client, - localInitialWindowSize: self.localInitialWindowSize, - remoteInitialWindowSize: self.remoteInitialWindowSize) { - $0.sendHeaders(headers: headers, validateHeaderBlock: validateHeaderBlock, validateContentLength: validateContentLength, localSupportsExtendedConnect: localSupportsExtendedConnect, remoteSupportsExtendedConnect: remoteSupportsExtendedConnect, isEndStreamSet: endStream) + result = try self.streamState.modifyStreamStateCreateIfNeeded( + streamID: streamID, + localRole: .client, + localInitialWindowSize: self.localInitialWindowSize, + remoteInitialWindowSize: self.remoteInitialWindowSize + ) { + $0.sendHeaders( + headers: headers, + validateHeaderBlock: validateHeaderBlock, + validateContentLength: validateContentLength, + localSupportsExtendedConnect: localSupportsExtendedConnect, + remoteSupportsExtendedConnect: remoteSupportsExtendedConnect, + isEndStreamSet: endStream + ) } } catch { - return StateMachineResultWithEffect(result: .connectionError(underlyingError: error, type: .protocolError), effect: nil) + return StateMachineResultWithEffect( + result: .connectionError(underlyingError: error, type: .protocolError), + effect: nil + ) } } else { // HEADERS cannot create streams for servers, so this must be for a stream we already know about. result = self.streamState.modifyStreamState(streamID: streamID, ignoreRecentlyReset: false) { - $0.sendHeaders(headers: headers, validateHeaderBlock: validateHeaderBlock, validateContentLength: validateContentLength, localSupportsExtendedConnect: localSupportsExtendedConnect, remoteSupportsExtendedConnect: remoteSupportsExtendedConnect, isEndStreamSet: endStream) + $0.sendHeaders( + headers: headers, + validateHeaderBlock: validateHeaderBlock, + validateContentLength: validateContentLength, + localSupportsExtendedConnect: localSupportsExtendedConnect, + remoteSupportsExtendedConnect: remoteSupportsExtendedConnect, + isEndStreamSet: endStream + ) } } - return StateMachineResultWithEffect(result, - inboundFlowControlWindow: self.inboundFlowControlWindow, - outboundFlowControlWindow: self.outboundFlowControlWindow) + return StateMachineResultWithEffect( + result, + inboundFlowControlWindow: self.inboundFlowControlWindow, + outboundFlowControlWindow: self.outboundFlowControlWindow + ) } } - extension SendingHeadersState where Self: RemotelyQuiescingState { /// If we've been remotely quiesced, we're forbidden from creating new streams. So we can only possibly /// be modifying an existing one. - mutating func sendHeaders(streamID: HTTP2StreamID, headers: HPACKHeaders, isEndStreamSet endStream: Bool) -> StateMachineResultWithEffect { + mutating func sendHeaders( + streamID: HTTP2StreamID, + headers: HPACKHeaders, + isEndStreamSet endStream: Bool + ) -> StateMachineResultWithEffect { let validateHeaderBlock = self.headerBlockValidation == .enabled let validateContentLength = self.contentLengthValidation == .enabled let localSupportsExtendedConnect = self.localSupportsExtendedConnect let remoteSupportsExtendedConnect = self.remoteSupportsExtendedConnect - if streamID.mayBeInitiatedBy(.client) && - self.role == .client && - streamID > self.streamState.lastClientStreamID { + if streamID.mayBeInitiatedBy(.client) && self.role == .client && streamID > self.streamState.lastClientStreamID + { let error = NIOHTTP2Errors.createdStreamAfterGoaway() - return StateMachineResultWithEffect(result: .connectionError(underlyingError: error, type: .protocolError), effect: nil) + return StateMachineResultWithEffect( + result: .connectionError(underlyingError: error, type: .protocolError), + effect: nil + ) } let result = self.streamState.modifyStreamState(streamID: streamID, ignoreRecentlyReset: false) { - $0.sendHeaders(headers: headers, validateHeaderBlock: validateHeaderBlock, validateContentLength: validateContentLength, localSupportsExtendedConnect: localSupportsExtendedConnect, remoteSupportsExtendedConnect: remoteSupportsExtendedConnect, isEndStreamSet: endStream) + $0.sendHeaders( + headers: headers, + validateHeaderBlock: validateHeaderBlock, + validateContentLength: validateContentLength, + localSupportsExtendedConnect: localSupportsExtendedConnect, + remoteSupportsExtendedConnect: remoteSupportsExtendedConnect, + isEndStreamSet: endStream + ) } - return StateMachineResultWithEffect(result, - inboundFlowControlWindow: self.inboundFlowControlWindow, - outboundFlowControlWindow: self.outboundFlowControlWindow) + return StateMachineResultWithEffect( + result, + inboundFlowControlWindow: self.inboundFlowControlWindow, + outboundFlowControlWindow: self.outboundFlowControlWindow + ) } } diff --git a/Sources/NIOHTTP2/ConnectionStateMachine/FrameSendingStates/SendingPushPromiseState.swift b/Sources/NIOHTTP2/ConnectionStateMachine/FrameSendingStates/SendingPushPromiseState.swift index b97f311..c9128c4 100644 --- a/Sources/NIOHTTP2/ConnectionStateMachine/FrameSendingStates/SendingPushPromiseState.swift +++ b/Sources/NIOHTTP2/ConnectionStateMachine/FrameSendingStates/SendingPushPromiseState.swift @@ -30,11 +30,19 @@ protocol SendingPushPromiseState: HasFlowControlWindows { } extension SendingPushPromiseState { - mutating func sendPushPromise(originalStreamID: HTTP2StreamID, childStreamID: HTTP2StreamID, headers: HPACKHeaders) -> StateMachineResultWithEffect { - return self._sendPushPromise(originalStreamID: originalStreamID, childStreamID: childStreamID, headers: headers) + mutating func sendPushPromise( + originalStreamID: HTTP2StreamID, + childStreamID: HTTP2StreamID, + headers: HPACKHeaders + ) -> StateMachineResultWithEffect { + self._sendPushPromise(originalStreamID: originalStreamID, childStreamID: childStreamID, headers: headers) } - fileprivate mutating func _sendPushPromise(originalStreamID: HTTP2StreamID, childStreamID: HTTP2StreamID, headers: HPACKHeaders) -> StateMachineResultWithEffect { + fileprivate mutating func _sendPushPromise( + originalStreamID: HTTP2StreamID, + childStreamID: HTTP2StreamID, + headers: HPACKHeaders + ) -> StateMachineResultWithEffect { let validateHeaderBlock = self.headerBlockValidation == .enabled // While receivePushPromise has a two step process involving creating the child stream first, here we do it the other @@ -42,17 +50,27 @@ extension SendingPushPromiseState { // we don't have to emit a frame to report the error (we just return it to the user), we don't have to have a stream // whose state we can modify. func parentStateModifier(stateMachine: inout HTTP2StreamStateMachine) -> StateMachineResultWithStreamEffect { - return stateMachine.sendPushPromise(headers: headers, validateHeaderBlock: validateHeaderBlock) + stateMachine.sendPushPromise(headers: headers, validateHeaderBlock: validateHeaderBlock) } // First, however, we need to check we can push at all! guard self.mayPush else { - return StateMachineResultWithEffect(result: .connectionError(underlyingError: NIOHTTP2Errors.pushInViolationOfSetting(), type: .protocolError), effect: nil) + return StateMachineResultWithEffect( + result: .connectionError( + underlyingError: NIOHTTP2Errors.pushInViolationOfSetting(), + type: .protocolError + ), + effect: nil + ) } do { let result = StateMachineResultWithEffect( - self.streamState.modifyStreamState(streamID: originalStreamID, ignoreRecentlyReset: false, parentStateModifier), + self.streamState.modifyStreamState( + streamID: originalStreamID, + ignoreRecentlyReset: false, + parentStateModifier + ), inboundFlowControlWindow: self.inboundFlowControlWindow, outboundFlowControlWindow: self.outboundFlowControlWindow ) @@ -60,23 +78,34 @@ extension SendingPushPromiseState { return result } let requestVerb = headers.first(name: ":method") - try self.streamState.createLocallyPushedStream(streamID: childStreamID, localInitialWindowSize: self.localInitialWindowSize, requestVerb: requestVerb) + try self.streamState.createLocallyPushedStream( + streamID: childStreamID, + localInitialWindowSize: self.localInitialWindowSize, + requestVerb: requestVerb + ) return result } catch { - return StateMachineResultWithEffect(result: .connectionError(underlyingError: error, type: .protocolError), effect: nil) + return StateMachineResultWithEffect( + result: .connectionError(underlyingError: error, type: .protocolError), + effect: nil + ) } } /// Whether we may push. var mayPush: Bool { // In the case where we don't have remote settings, we have to assume the default value, in which case if we're a server we may push. - return self.role == .server + self.role == .server } } extension SendingPushPromiseState where Self: RemotelyQuiescingState { - mutating func sendPushPromise(originalStreamID: HTTP2StreamID, childStreamID: HTTP2StreamID, headers: HPACKHeaders) -> StateMachineResultWithEffect { + mutating func sendPushPromise( + originalStreamID: HTTP2StreamID, + childStreamID: HTTP2StreamID, + headers: HPACKHeaders + ) -> StateMachineResultWithEffect { // This call should never be used, but we do want to ensure that conforming types cannot enter the above method. // The state machine should return early in all cases where we might end up calling this function. preconditionFailure("Must not be called") @@ -85,6 +114,6 @@ extension SendingPushPromiseState where Self: RemotelyQuiescingState { extension SendingPushPromiseState where Self: HasRemoteSettings { var mayPush: Bool { - return self.remoteSettings.enablePush == 1 && self.role == .server + self.remoteSettings.enablePush == 1 && self.role == .server } } diff --git a/Sources/NIOHTTP2/ConnectionStateMachine/FrameSendingStates/SendingRstStreamState.swift b/Sources/NIOHTTP2/ConnectionStateMachine/FrameSendingStates/SendingRstStreamState.swift index 2d52fbc..6058d14 100644 --- a/Sources/NIOHTTP2/ConnectionStateMachine/FrameSendingStates/SendingRstStreamState.swift +++ b/Sources/NIOHTTP2/ConnectionStateMachine/FrameSendingStates/SendingRstStreamState.swift @@ -26,8 +26,10 @@ extension SendingRstStreamState { let result = self.streamState.locallyResetStreamState(streamID: streamID) { $0.sendRstStream(reason: reason) } - return StateMachineResultWithEffect(result, - inboundFlowControlWindow: self.inboundFlowControlWindow, - outboundFlowControlWindow: self.outboundFlowControlWindow) + return StateMachineResultWithEffect( + result, + inboundFlowControlWindow: self.inboundFlowControlWindow, + outboundFlowControlWindow: self.outboundFlowControlWindow + ) } } diff --git a/Sources/NIOHTTP2/ConnectionStateMachine/FrameSendingStates/SendingWindowUpdateState.swift b/Sources/NIOHTTP2/ConnectionStateMachine/FrameSendingStates/SendingWindowUpdateState.swift index 72440bd..e58245d 100644 --- a/Sources/NIOHTTP2/ConnectionStateMachine/FrameSendingStates/SendingWindowUpdateState.swift +++ b/Sources/NIOHTTP2/ConnectionStateMachine/FrameSendingStates/SendingWindowUpdateState.swift @@ -30,9 +30,15 @@ extension SendingWindowUpdateState { try self.inboundFlowControlWindow.windowUpdate(by: increment) return StateMachineResultWithEffect(result: .succeed, effect: nil) } catch let error where error is NIOHTTP2Errors.InvalidFlowControlWindowSize { - return StateMachineResultWithEffect(result: .connectionError(underlyingError: error, type: .flowControlError), effect: nil) + return StateMachineResultWithEffect( + result: .connectionError(underlyingError: error, type: .flowControlError), + effect: nil + ) } catch let error where error is NIOHTTP2Errors.InvalidWindowIncrementSize { - return StateMachineResultWithEffect(result: .connectionError(underlyingError: error, type: .protocolError), effect: nil) + return StateMachineResultWithEffect( + result: .connectionError(underlyingError: error, type: .protocolError), + effect: nil + ) } catch { preconditionFailure("Unexpected error: \(error)") } @@ -41,9 +47,11 @@ extension SendingWindowUpdateState { let result = self.streamState.modifyStreamState(streamID: streamID, ignoreRecentlyReset: false) { $0.sendWindowUpdate(windowIncrement: increment) } - return StateMachineResultWithEffect(result, - inboundFlowControlWindow: self.inboundFlowControlWindow, - outboundFlowControlWindow: self.outboundFlowControlWindow) + return StateMachineResultWithEffect( + result, + inboundFlowControlWindow: self.inboundFlowControlWindow, + outboundFlowControlWindow: self.outboundFlowControlWindow + ) } } } diff --git a/Sources/NIOHTTP2/ConnectionStateMachine/HTTP2SettingsState.swift b/Sources/NIOHTTP2/ConnectionStateMachine/HTTP2SettingsState.swift index e579615..20e5bf1 100644 --- a/Sources/NIOHTTP2/ConnectionStateMachine/HTTP2SettingsState.swift +++ b/Sources/NIOHTTP2/ConnectionStateMachine/HTTP2SettingsState.swift @@ -27,11 +27,15 @@ struct HTTP2SettingsState { private var unacknowlegedSettingsFrames: [HTTP2Settings] /// A callback that is invoked whenever a setting value has changed. - typealias OnValueChangeCallback = (_ setting: HTTP2SettingsParameter, _ oldValue: UInt32?, _ newValue: UInt32) throws -> Void + typealias OnValueChangeCallback = (_ setting: HTTP2SettingsParameter, _ oldValue: UInt32?, _ newValue: UInt32) + throws -> Void init(localState: Bool) { // Create the settings dictionary, and ensure it has space for the known SETTINGS values. - self.currentSettingsValues = [.headerTableSize: 4096, .enablePush: 1, .initialWindowSize: HTTP2SettingsState.defaultInitialWindowSize, .maxFrameSize: 1<<14] + self.currentSettingsValues = [ + .headerTableSize: 4096, .enablePush: 1, .initialWindowSize: HTTP2SettingsState.defaultInitialWindowSize, + .maxFrameSize: 1 << 14, + ] self.currentSettingsValues.reserveCapacity(8) // Create space for the unacknowledged SETTINGS frame data to be stored. In general this will be empty, @@ -54,25 +58,25 @@ struct HTTP2SettingsState { /// Obtain the current value of a settings parameter. subscript(_ parameter: HTTP2SettingsParameter) -> UInt32? { get { - return self.currentSettingsValues[parameter] + self.currentSettingsValues[parameter] } } /// The current value of SETTINGS_INITIAL_WINDOW_SIZE. var initialWindowSize: UInt32 { // We can force-unwrap here as this setting always has a value. - return self[.initialWindowSize]! + self[.initialWindowSize]! } /// The current value of SETTINGS_ENABLE_PUSH. var enablePush: UInt32 { // We can force-unwrap here as this setting always has a value. - return self[.enablePush]! + self[.enablePush]! } /// The current value of SETTINGS_ENABLE_CONNECT_PROTOCOL var enableConnectProtocol: UInt32? { - return self[.enableConnectProtocol] + self[.enableConnectProtocol] } /// The default value of SETTINGS_INITIAL_WINDOW_SIZE. @@ -112,7 +116,7 @@ struct HTTP2SettingsState { /// - settings: The received settings. /// - onValueChange: A callback that will be invoked once for each setting change. mutating func receiveSettings(_ settings: HTTP2Settings, onValueChange: OnValueChangeCallback) rethrows { - return try self.applySettings(settings, onValueChange: onValueChange) + try self.applySettings(settings, onValueChange: onValueChange) } /// Applies the given HTTP/2 settings to this state. @@ -131,6 +135,6 @@ struct HTTP2SettingsState { /// Obtain an empty dummy value, suitable for using as a temporary to avoid CoW operations. static func dummyValue() -> HTTP2SettingsState { - return HTTP2SettingsState() + HTTP2SettingsState() } } diff --git a/Sources/NIOHTTP2/ConnectionStateMachine/HasRemoteSettings.swift b/Sources/NIOHTTP2/ConnectionStateMachine/HasRemoteSettings.swift index 93281a6..511e8bd 100644 --- a/Sources/NIOHTTP2/ConnectionStateMachine/HasRemoteSettings.swift +++ b/Sources/NIOHTTP2/ConnectionStateMachine/HasRemoteSettings.swift @@ -32,7 +32,10 @@ extension HasRemoteExtendedConnectSettings where Self: HasRemoteSettings { } extension HasRemoteSettings { - mutating func receiveSettingsChange(_ settings: HTTP2Settings, frameEncoder: inout HTTP2FrameEncoder) -> (StateMachineResultWithEffect, PostFrameOperation) { + mutating func receiveSettingsChange( + _ settings: HTTP2Settings, + frameEncoder: inout HTTP2FrameEncoder + ) -> (StateMachineResultWithEffect, PostFrameOperation) { // We do a little switcheroo here to avoid problems with overlapping accesses to // self. It's a little more complex than normal because HTTP2SettingsState has // two CoWable objects, and we don't want to CoW either of them, so we shove a dummy @@ -74,7 +77,9 @@ extension HasRemoteSettings { case .enableConnectProtocol: // Must not transition from 1 -> 0 if originalValue == 1 && newValue == 0 { - throw NIOHTTP2Errors.invalidSetting(setting: HTTP2Setting(parameter: setting, value: Int(newValue))) + throw NIOHTTP2Errors.invalidSetting( + setting: HTTP2Setting(parameter: setting, value: Int(newValue)) + ) } effect.enableConnectProtocol = newValue == 1 default: @@ -84,7 +89,9 @@ extension HasRemoteSettings { } return (.init(result: .succeed, effect: .remoteSettingsChanged(effect)), .sendAck) } catch let err where err is NIOHTTP2Errors.InvalidFlowControlWindowSize { - return (.init(result: .connectionError(underlyingError: err, type: .flowControlError), effect: nil), .nothing) + return ( + .init(result: .connectionError(underlyingError: err, type: .flowControlError), effect: nil), .nothing + ) } catch let err where err is NIOHTTP2Errors.InvalidSetting { return (.init(result: .connectionError(underlyingError: err, type: .protocolError), effect: nil), .nothing) } catch { diff --git a/Sources/NIOHTTP2/ConnectionStateMachine/QuiescingState.swift b/Sources/NIOHTTP2/ConnectionStateMachine/QuiescingState.swift index af0eb33..0dcbf9c 100644 --- a/Sources/NIOHTTP2/ConnectionStateMachine/QuiescingState.swift +++ b/Sources/NIOHTTP2/ConnectionStateMachine/QuiescingState.swift @@ -17,6 +17,6 @@ /// This protocol should only be conformed to by states for the HTTP/2 connection state machine. protocol QuiescingState { var streamState: ConnectionStreamState { get } - + var quiescedByServer: Bool { get } } diff --git a/Sources/NIOHTTP2/ConnectionStateMachine/StateMachineResult.swift b/Sources/NIOHTTP2/ConnectionStateMachine/StateMachineResult.swift index 03dfd10..85113d1 100644 --- a/Sources/NIOHTTP2/ConnectionStateMachine/StateMachineResult.swift +++ b/Sources/NIOHTTP2/ConnectionStateMachine/StateMachineResult.swift @@ -44,7 +44,6 @@ enum StateMachineResult { case succeed } - /// Operations that may need to be performed after receiving a frame. enum PostFrameOperation { /// An appropriate ACK must be sent. @@ -54,7 +53,6 @@ enum PostFrameOperation { case nothing } - /// An encapsulation of a state machine result along with a possible triggered state change. struct StateMachineResultWithEffect { var result: StateMachineResult @@ -66,12 +64,18 @@ struct StateMachineResultWithEffect { self.effect = effect } - init(_ streamEffect: StateMachineResultWithStreamEffect, - inboundFlowControlWindow: HTTP2FlowControlWindow, - outboundFlowControlWindow: HTTP2FlowControlWindow) { + init( + _ streamEffect: StateMachineResultWithStreamEffect, + inboundFlowControlWindow: HTTP2FlowControlWindow, + outboundFlowControlWindow: HTTP2FlowControlWindow + ) { self.result = streamEffect.result self.effect = streamEffect.effect.map { - NIOHTTP2ConnectionStateChange($0, inboundFlowControlWindow: inboundFlowControlWindow, outboundFlowControlWindow: outboundFlowControlWindow) + NIOHTTP2ConnectionStateChange( + $0, + inboundFlowControlWindow: inboundFlowControlWindow, + outboundFlowControlWindow: outboundFlowControlWindow + ) } } } diff --git a/Sources/NIOHTTP2/ContentLengthVerifier.swift b/Sources/NIOHTTP2/ContentLengthVerifier.swift index fdb89f9..f639586 100644 --- a/Sources/NIOHTTP2/ContentLengthVerifier.swift +++ b/Sources/NIOHTTP2/ContentLengthVerifier.swift @@ -49,7 +49,7 @@ extension ContentLengthVerifier { extension ContentLengthVerifier { internal init(_ headers: HPACKHeaders, requestMethod: String?) throws { - if let requestMethod = requestMethod { + if let requestMethod = requestMethod { if let status = headers.first(name: ":status"), status == "304" { self.expectedContentLength = 0 return @@ -82,13 +82,12 @@ extension ContentLengthVerifier { /// The verifier for use when content length verification is disabled. internal static var disabled: ContentLengthVerifier { - return ContentLengthVerifier(expectedContentLength: nil) + ContentLengthVerifier(expectedContentLength: nil) } } extension ContentLengthVerifier: CustomStringConvertible { var description: String { - return "ContentLengthVerifier(length: \(String(describing: self.expectedContentLength)))" + "ContentLengthVerifier(length: \(String(describing: self.expectedContentLength)))" } } - diff --git a/Sources/NIOHTTP2/DOSHeuristics.swift b/Sources/NIOHTTP2/DOSHeuristics.swift index 7e5f3ae..7ab661d 100644 --- a/Sources/NIOHTTP2/DOSHeuristics.swift +++ b/Sources/NIOHTTP2/DOSHeuristics.swift @@ -30,16 +30,26 @@ struct DOSHeuristics { private var resetFrameRateControlStateMachine: HTTP2ResetFrameRateControlStateMachine - internal init(maximumSequentialEmptyDataFrames: Int, maximumResetFrameCount: Int, resetFrameCounterWindow: TimeAmount, clock: DeadlineClock = RealNIODeadlineClock()) { - precondition(maximumSequentialEmptyDataFrames >= 0, - "maximum sequential empty data frames must be positive, got \(maximumSequentialEmptyDataFrames)") + internal init( + maximumSequentialEmptyDataFrames: Int, + maximumResetFrameCount: Int, + resetFrameCounterWindow: TimeAmount, + clock: DeadlineClock = RealNIODeadlineClock() + ) { + precondition( + maximumSequentialEmptyDataFrames >= 0, + "maximum sequential empty data frames must be positive, got \(maximumSequentialEmptyDataFrames)" + ) self.maximumSequentialEmptyDataFrames = maximumSequentialEmptyDataFrames self.receivedEmptyDataFrames = 0 - self.resetFrameRateControlStateMachine = .init(countThreshold: maximumResetFrameCount, timeWindow: resetFrameCounterWindow, clock: clock) + self.resetFrameRateControlStateMachine = .init( + countThreshold: maximumResetFrameCount, + timeWindow: resetFrameCounterWindow, + clock: clock + ) } } - extension DOSHeuristics { mutating func process(_ frame: HTTP2Frame) throws { switch frame.payload { @@ -120,7 +130,7 @@ extension DOSHeuristics { self._state = .rateTooHigh } case .rateTooHigh: - break // no-op, there is no way to de-escalate from an excessive rate + break // no-op, there is no way to de-escalate from an excessive rate } } } diff --git a/Sources/NIOHTTP2/Frame Buffers/ConcurrentStreamBuffer.swift b/Sources/NIOHTTP2/Frame Buffers/ConcurrentStreamBuffer.swift index 7b15044..bd6fb7a 100644 --- a/Sources/NIOHTTP2/Frame Buffers/ConcurrentStreamBuffer.swift +++ b/Sources/NIOHTTP2/Frame Buffers/ConcurrentStreamBuffer.swift @@ -13,7 +13,6 @@ //===----------------------------------------------------------------------===// import NIOCore - /// An object that buffers new stream creation attempts to avoid violating /// the HTTP/2 setting `SETTINGS_MAX_CONCURRENT_STREAMS`. /// @@ -64,7 +63,9 @@ struct ConcurrentStreamBuffer { /// /// Notes that the current number of outbound streams may have gone down, which is useful information /// when flushing writes. - mutating func streamClosed(_ streamID: HTTP2StreamID) -> MarkedCircularBuffer<(HTTP2Frame, EventLoopPromise?)>? { + mutating func streamClosed( + _ streamID: HTTP2StreamID + ) -> MarkedCircularBuffer<(HTTP2Frame, EventLoopPromise?)>? { // We only care about outbound streams. if streamID.mayBeInitiatedBy(self.mode) { self.currentOutboundStreams -= 1 @@ -105,7 +106,11 @@ struct ConcurrentStreamBuffer { self.bufferedFrames.markFlushPoint() } - mutating func processOutboundFrame(_ frame: HTTP2Frame, promise: EventLoopPromise?, channelWritable: Bool) throws -> OutboundFrameAction { + mutating func processOutboundFrame( + _ frame: HTTP2Frame, + promise: EventLoopPromise?, + channelWritable: Bool + ) throws -> OutboundFrameAction { // If this frame is not for a locally initiated stream, then that's fine, just pass it on. Even if the channel isn't // writable, one of the other two buffers should catch this. guard frame.streamID != .rootStream && frame.streamID.mayBeInitiatedBy(self.mode) else { @@ -124,7 +129,8 @@ struct ConcurrentStreamBuffer { // Again, we choose to ignore channel writability here because one of the other buffers should catch this frame. if let firstElement = self.bufferedFrames.first, frame.streamID >= firstElement.streamID, - let bufferIndex = self.bufferedFrames.binarySearch(key: { $0.streamID }, needle: frame.streamID) { + let bufferIndex = self.bufferedFrames.binarySearch(key: { $0.streamID }, needle: frame.streamID) + { return self.bufferFrame(frame, promise: promise, bufferIndex: bufferIndex) } @@ -211,7 +217,11 @@ struct ConcurrentStreamBuffer { return self.bufferedFrames.nextWriteFor(index) } - private mutating func bufferFrame(_ frame: HTTP2Frame, promise: EventLoopPromise?, bufferIndex index: SortedCircularBuffer.Index) -> OutboundFrameAction { + private mutating func bufferFrame( + _ frame: HTTP2Frame, + promise: EventLoopPromise?, + bufferIndex index: SortedCircularBuffer.Index + ) -> OutboundFrameAction { // Ok, we need to buffer this frame, and we know we have the index for it. What we do here depends on this frame type. For // almost all frames, we just append them to the buffer. For RST_STREAM, however, we're in a different spot. RST_STREAM is a // request to drop all resources for a given stream. We know we have some, but we shouldn't wait to unblock them, we should @@ -223,9 +233,15 @@ struct ConcurrentStreamBuffer { // If we're currently unbuffering this stream, we need to pass the RST_STREAM frame on for correctness. If we aren't, just // drop it. if writeBuffer.currentlyUnblocking { - return .forwardAndDrop(writeBuffer.frames, NIOHTTP2Errors.streamClosed(streamID: frame.streamID, errorCode: reason)) + return .forwardAndDrop( + writeBuffer.frames, + NIOHTTP2Errors.streamClosed(streamID: frame.streamID, errorCode: reason) + ) } else { - return .succeedAndDrop(writeBuffer.frames, NIOHTTP2Errors.streamClosed(streamID: frame.streamID, errorCode: reason)) + return .succeedAndDrop( + writeBuffer.frames, + NIOHTTP2Errors.streamClosed(streamID: frame.streamID, errorCode: reason) + ) } } @@ -310,7 +326,7 @@ private struct SortedCircularBuffer { mutating func remove(at index: Index) -> Element { // This one is easy: simple removal does what we need here. - return self._base.remove(at: index) + self._base.remove(at: index) } mutating func markFlushPoint() { @@ -330,19 +346,19 @@ extension SortedCircularBuffer: RandomAccessCollection { typealias Indices = CircularBuffer.Indices var startIndex: Index { - return self._base.startIndex + self._base.startIndex } var endIndex: Index { - return self._base.endIndex + self._base.endIndex } var indices: Indices { - return self._base.indices + self._base.indices } func distance(from start: Index, to end: Index) -> Int { - return self._base.distance(from: start, to: end) + self._base.distance(from: start, to: end) } func formIndex(after i: inout Index) { @@ -354,27 +370,27 @@ extension SortedCircularBuffer: RandomAccessCollection { } func index(_ i: Index, offsetBy distance: Int) -> Index { - return self._base.index(i, offsetBy: distance) + self._base.index(i, offsetBy: distance) } func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { - return self._base.index(i, offsetBy: distance, limitedBy: limit) + self._base.index(i, offsetBy: distance, limitedBy: limit) } func index(after i: Index) -> Index { - return self._base.index(after: i) + self._base.index(after: i) } func index(before i: Index) -> Index { - return self._base.index(before: i) + self._base.index(before: i) } subscript(_ i: Index) -> Element { - return self._base[i] + self._base[i] } subscript(_ range: Range) -> SubSequence { - return self._base[range] + self._base[range] } } @@ -407,9 +423,8 @@ extension SortedCircularBuffer { } } - -private extension HTTP2StreamID { - func mayBeInitiatedBy(_ mode: NIOHTTP2Handler.ParserMode) -> Bool { +extension HTTP2StreamID { + fileprivate func mayBeInitiatedBy(_ mode: NIOHTTP2Handler.ParserMode) -> Bool { switch mode { case .client: return self.networkStreamID % 2 == 1 diff --git a/Sources/NIOHTTP2/Frame Buffers/ControlFrameBuffer.swift b/Sources/NIOHTTP2/Frame Buffers/ControlFrameBuffer.swift index 4bec20e..309d13e 100644 --- a/Sources/NIOHTTP2/Frame Buffers/ControlFrameBuffer.swift +++ b/Sources/NIOHTTP2/Frame Buffers/ControlFrameBuffer.swift @@ -13,7 +13,6 @@ //===----------------------------------------------------------------------===// import NIOCore - /// A buffer that stores outbound control frames. /// /// In general it is preferential to buffer outbound frames instead of passing them into the channel. @@ -35,7 +34,6 @@ struct ControlFrameBuffer { internal var maximumBufferSize: Int } - // MARK:- ControlFrameBuffer initializers extension ControlFrameBuffer { internal init(maximumBufferSize: Int) { @@ -46,10 +44,13 @@ extension ControlFrameBuffer { } } - // MARK:- ControlFrameBuffer frame processing extension ControlFrameBuffer { - internal mutating func processOutboundFrame(_ frame: HTTP2Frame, promise: EventLoopPromise?, channelWritable: Bool) throws -> OutboundFrameAction { + internal mutating func processOutboundFrame( + _ frame: HTTP2Frame, + promise: EventLoopPromise?, + channelWritable: Bool + ) throws -> OutboundFrameAction { switch frame.payload { case .data: // These frames are not buffered here. If it reached us, it's because we believe the channel is writable, @@ -97,7 +98,6 @@ extension ControlFrameBuffer { } } - // MARK:- ControlFrameBuffer.PendingControlFrame definition extension ControlFrameBuffer { /// A buffered control frame write and its associated promise. diff --git a/Sources/NIOHTTP2/Frame Buffers/OutboundFlowControlBuffer.swift b/Sources/NIOHTTP2/Frame Buffers/OutboundFlowControlBuffer.swift index 7bc7ea3..b9c36f4 100644 --- a/Sources/NIOHTTP2/Frame Buffers/OutboundFlowControlBuffer.swift +++ b/Sources/NIOHTTP2/Frame Buffers/OutboundFlowControlBuffer.swift @@ -61,7 +61,7 @@ internal struct OutboundFlowControlBuffer { /// The current value of SETTINGS_MAX_FRAME_SIZE set by the peer. internal var maxFrameSize: Int - internal init(initialConnectionWindowSize: Int = 65535, initialMaxFrameSize: Int = 1<<14) { + internal init(initialConnectionWindowSize: Int = 65535, initialMaxFrameSize: Int = 1 << 14) { // TODO(cory): HEAP! This should be a heap, sorted off the number of pending bytes! self.streamDataBuffers = StreamMap() self.connectionWindowSize = initialConnectionWindowSize @@ -72,7 +72,10 @@ internal struct OutboundFlowControlBuffer { self.flushableStreams.reserveCapacity(16) } - internal mutating func processOutboundFrame(_ frame: HTTP2Frame, promise: EventLoopPromise?) throws -> OutboundFrameAction { + internal mutating func processOutboundFrame( + _ frame: HTTP2Frame, + promise: EventLoopPromise? + ) throws -> OutboundFrameAction { // A side note: there is no special handling for RST_STREAM frames here, unlike in the concurrent streams buffer. This is because // RST_STREAM frames will cause stream closure notifications, which will force us to drop our buffers. For this reason we can // simplify our code here, which helps a lot. @@ -93,7 +96,8 @@ internal struct OutboundFlowControlBuffer { // Headers are special. If we have a data frame buffered, we buffer behind it to avoid frames // being reordered. However, if we don't have a data frame buffered we pass the headers frame on // immediately, as there is no risk of violating ordering guarantees. - let bufferResult = self.streamDataBuffers.modify(streamID: streamID) { (state: inout StreamFlowControlState) -> Bool in + let bufferResult = self.streamDataBuffers.modify(streamID: streamID) { + (state: inout StreamFlowControlState) -> Bool in if state.haveBufferedDataFrame { state.bufferWrite((frame.payload, promise)) return true @@ -135,7 +139,7 @@ internal struct OutboundFlowControlBuffer { } private func nextStreamToSend() -> HTTP2StreamID? { - return self.flushableStreams.first + self.flushableStreams.first } internal mutating func updateWindowOfStream(_ streamID: HTTP2StreamID, newSize: Int32) { @@ -172,7 +176,9 @@ internal struct OutboundFlowControlBuffer { // We received a stream closed event. Drop any stream state we're holding. // // - returns: Any buffered stream state we may have been holding so their promises can be failed. - internal mutating func streamClosed(_ streamID: HTTP2StreamID) -> MarkedCircularBuffer<(HTTP2Frame.FramePayload, EventLoopPromise?)>? { + internal mutating func streamClosed( + _ streamID: HTTP2StreamID + ) -> MarkedCircularBuffer<(HTTP2Frame.FramePayload, EventLoopPromise?)>? { self.flushableStreams.remove(streamID) guard var streamData = self.streamDataBuffers.removeValue(forStreamID: streamID) else { // Huh, we didn't have any data for this stream. Oh well. That was easy. @@ -194,8 +200,11 @@ internal struct OutboundFlowControlBuffer { return nil } - let nextWrite = self.streamDataBuffers.modify(streamID: nextStreamID) { (state: inout StreamFlowControlState) -> DataBuffer.BufferElement in - let (nextWrite, writabilityState) = state.nextWrite(maxSize: min(self.connectionWindowSize, self.maxFrameSize)) + let nextWrite = self.streamDataBuffers.modify(streamID: nextStreamID) { + (state: inout StreamFlowControlState) -> DataBuffer.BufferElement in + let (nextWrite, writabilityState) = state.nextWrite( + maxSize: min(self.connectionWindowSize, self.maxFrameSize) + ) switch writabilityState { case .changed(newValue: false): @@ -233,7 +242,6 @@ internal struct OutboundFlowControlBuffer { } } - // MARK: Priority API extension OutboundFlowControlBuffer { /// A frame with new priority data has been received that affects prioritisation of outbound frames. @@ -247,18 +255,17 @@ extension OutboundFlowControlBuffer { } } - private struct StreamFlowControlState: PerStreamData { let streamID: HTTP2StreamID internal private(set) var currentWindowSize: Int private var dataBuffer: DataBuffer var haveBufferedDataFrame: Bool { - return self.dataBuffer.haveBufferedDataFrame + self.dataBuffer.haveBufferedDataFrame } var hasFlowControlWindowSpaceForNextWrite: Bool { - return self.currentWindowSize > 0 || self.dataBuffer.nextWriteIsZeroSized + self.currentWindowSize > 0 || self.dataBuffer.nextWriteIsZeroSized } init(streamID: HTTP2StreamID, initialWindowSize: Int) { @@ -303,7 +310,7 @@ private struct StreamFlowControlState: PerStreamData { /// Removes all pending writes, invalidating this structure as it does so. mutating func evacuatePendingWrites() -> MarkedCircularBuffer { - return self.dataBuffer.evacuatePendingWrites() + self.dataBuffer.evacuatePendingWrites() } func failAllWrites(error: ChannelError) { @@ -336,22 +343,21 @@ private struct StreamFlowControlState: PerStreamData { } } - private struct DataBuffer { typealias BufferElement = (HTTP2Frame.FramePayload, EventLoopPromise?) private var bufferedChunks: MarkedCircularBuffer var haveBufferedDataFrame: Bool { - return self.bufferedChunks.count > 0 + self.bufferedChunks.count > 0 } var nextWriteIsZeroSized: Bool { - return self.bufferedChunks.first?.0.isZeroSizedWrite ?? false + self.bufferedChunks.first?.0.isZeroSizedWrite ?? false } var hasMark: Bool { - return self.bufferedChunks.hasMark + self.bufferedChunks.hasMark } /// An empty buffer, we use this avoid an allocation in 'evacuatePendingWrites'. @@ -410,16 +416,14 @@ private struct DataBuffer { } } - /// Used to communicate whether a stream has had its writability state change. -fileprivate enum WritabilityState { +private enum WritabilityState { case changed(newValue: Bool) case unchanged } - -private extension IOData { - mutating func slicePrefix(_ length: Int) -> IOData { +extension IOData { + fileprivate mutating func slicePrefix(_ length: Int) -> IOData { assert(length < self.readableBytes) switch self { @@ -430,7 +434,11 @@ private extension IOData { return .byteBuffer(newBuf) case .fileRegion(var region): - let newRegion = FileRegion(fileHandle: region.fileHandle, readerIndex: region.readerIndex, endIndex: region.readerIndex + length) + let newRegion = FileRegion( + fileHandle: region.fileHandle, + readerIndex: region.readerIndex, + endIndex: region.readerIndex + length + ) region.moveReaderIndex(forwardBy: length) self = .fileRegion(region) return .fileRegion(newRegion) @@ -438,7 +446,6 @@ private extension IOData { } } - extension HTTP2Frame.FramePayload { fileprivate var isZeroSizedWrite: Bool { switch self { @@ -450,7 +457,6 @@ extension HTTP2Frame.FramePayload { } } - extension StreamMap where Element == StreamFlowControlState { // /// Apply a transform to a wrapped DataBuffer. @@ -461,6 +467,6 @@ extension StreamMap where Element == StreamFlowControlState { /// - Returns: Whether the value was present or not. @discardableResult fileprivate mutating func apply(streamID: HTTP2StreamID, _ body: (inout Element) -> Void) -> Bool { - return self.modify(streamID: streamID, body) != nil + self.modify(streamID: streamID, body) != nil } } diff --git a/Sources/NIOHTTP2/Frame Buffers/OutboundFrameBuffer.swift b/Sources/NIOHTTP2/Frame Buffers/OutboundFrameBuffer.swift index 1f86a6e..ddad13f 100644 --- a/Sources/NIOHTTP2/Frame Buffers/OutboundFrameBuffer.swift +++ b/Sources/NIOHTTP2/Frame Buffers/OutboundFrameBuffer.swift @@ -53,11 +53,13 @@ internal struct CompoundOutboundBuffer { private var controlFrameBuffer: ControlFrameBuffer } - // MARK: CompoundOutboundBuffer initializers extension CompoundOutboundBuffer { internal init(mode: NIOHTTP2Handler.ParserMode, initialMaxOutboundStreams: Int, maxBufferedControlFrames: Int) { - self.concurrentStreamsBuffer = ConcurrentStreamBuffer(mode: mode, initialMaxOutboundStreams: initialMaxOutboundStreams) + self.concurrentStreamsBuffer = ConcurrentStreamBuffer( + mode: mode, + initialMaxOutboundStreams: initialMaxOutboundStreams + ) self.flowControlBuffer = OutboundFlowControlBuffer() self.controlFrameBuffer = ControlFrameBuffer(maximumBufferSize: maxBufferedControlFrames) } @@ -72,9 +74,15 @@ extension CompoundOutboundBuffer { /// which MarkedCircularBuffer is based, has internal invariants which require it to have a non-zero capacity). /// This static empty buffer allows us to avoid that allocation in each `processOutboundFrame` call when there /// are no frames to drop. - private static let emptyFramesToDrop = MarkedCircularBuffer<(HTTP2Frame, EventLoopPromise?)>(initialCapacity: 0) + private static let emptyFramesToDrop = MarkedCircularBuffer<(HTTP2Frame, EventLoopPromise?)>( + initialCapacity: 0 + ) - mutating func processOutboundFrame(_ frame: HTTP2Frame, promise: EventLoopPromise?, channelWritable: Bool) throws -> OutboundFrameAction { + mutating func processOutboundFrame( + _ frame: HTTP2Frame, + promise: EventLoopPromise?, + channelWritable: Bool + ) throws -> OutboundFrameAction { var framesToDrop = Self.emptyFramesToDrop var error: NIOHTTP2Errors.StreamClosed? = nil @@ -86,7 +94,11 @@ extension CompoundOutboundBuffer { // to the dropped frames. // 4. If a buffer returns .succeedAndDrop, return .succeedAndDrop. // The return value of the last buffer is the return value of the compound buffer, unless we returned early. - switch try self.concurrentStreamsBuffer.processOutboundFrame(frame, promise: promise, channelWritable: channelWritable) { + switch try self.concurrentStreamsBuffer.processOutboundFrame( + frame, + promise: promise, + channelWritable: channelWritable + ) { case .nothing: return .nothing case .succeedAndDrop(let framesToDrop, let error): @@ -116,7 +128,11 @@ extension CompoundOutboundBuffer { break } - switch try self.controlFrameBuffer.processOutboundFrame(frame, promise: promise, channelWritable: channelWritable) { + switch try self.controlFrameBuffer.processOutboundFrame( + frame, + promise: promise, + channelWritable: channelWritable + ) { case .nothing: return .nothing case .forward: @@ -177,8 +193,13 @@ extension CompoundOutboundBuffer { // Ok, now to move on to work on the concurrent streams buffer. while let (frame, promise) = self.concurrentStreamsBuffer.nextFlushedWritableFrame() { do { - if try self.flowControlBuffer.processOutboundFrame(frame, promise: promise).shouldForward && - self.controlFrameBuffer.processOutboundFrame(frame, promise: promise, channelWritable: channelWritable).shouldForward { + if try self.flowControlBuffer.processOutboundFrame(frame, promise: promise).shouldForward + && self.controlFrameBuffer.processOutboundFrame( + frame, + promise: promise, + channelWritable: channelWritable + ).shouldForward + { return .frame(frame, promise) } } catch { @@ -191,7 +212,11 @@ extension CompoundOutboundBuffer { while let (frame, promise) = self.flowControlBuffer.nextFlushedWritableFrame() { do { - if try self.controlFrameBuffer.processOutboundFrame(frame, promise: promise, channelWritable: channelWritable).shouldForward { + if try self.controlFrameBuffer.processOutboundFrame( + frame, + promise: promise, + channelWritable: channelWritable + ).shouldForward { return .frame(frame, promise) } } catch { @@ -244,7 +269,7 @@ extension CompoundOutboundBuffer { var maxFrameSize: Int { get { - return self.flowControlBuffer.maxFrameSize + self.flowControlBuffer.maxFrameSize } set { self.flowControlBuffer.maxFrameSize = newValue @@ -253,7 +278,7 @@ extension CompoundOutboundBuffer { var connectionWindowSize: Int { get { - return self.flowControlBuffer.connectionWindowSize + self.flowControlBuffer.connectionWindowSize } set { self.flowControlBuffer.connectionWindowSize = newValue @@ -262,7 +287,7 @@ extension CompoundOutboundBuffer { var maxOutboundStreams: Int { get { - return self.concurrentStreamsBuffer.maxOutboundStreams + self.concurrentStreamsBuffer.maxOutboundStreams } set { self.concurrentStreamsBuffer.maxOutboundStreams = newValue @@ -301,7 +326,7 @@ extension CompoundOutboundBuffer.DroppedPromisesCollection: Collection { static func < (lhs: Index, rhs: Index) -> Bool { switch (lhs.backingIndex, rhs.backingIndex) { case (.concurrentStreams, .flowControl), - (.concurrentStreams, .endIndex): + (.concurrentStreams, .endIndex): return true case (.concurrentStreams(let lhsBackingIndex), .concurrentStreams(let rhsBackingIndex)): return lhsBackingIndex < rhsBackingIndex @@ -328,7 +353,7 @@ extension CompoundOutboundBuffer.DroppedPromisesCollection: Collection { } var endIndex: Index { - return Index(.endIndex) + Index(.endIndex) } func index(after index: Index) -> Index { @@ -377,7 +402,6 @@ extension CompoundOutboundBuffer.DroppedPromisesCollection: Collection { } } - extension OutboundFrameAction { /// Whether this frame should be forwarded. Must only be used in cases where the frame /// cannot lead to drops. diff --git a/Sources/NIOHTTP2/HPACKHeaders+Validation.swift b/Sources/NIOHTTP2/HPACKHeaders+Validation.swift index 88887f4..31044dc 100644 --- a/Sources/NIOHTTP2/HPACKHeaders+Validation.swift +++ b/Sources/NIOHTTP2/HPACKHeaders+Validation.swift @@ -18,36 +18,35 @@ extension HPACKHeaders { /// /// If the header block is not valid, throws an error. internal func validateRequestBlock(supportsExtendedConnect: Bool) throws { - return try RequestBlockValidator.validateBlock(self, supportsExtendedConnect: supportsExtendedConnect) + try RequestBlockValidator.validateBlock(self, supportsExtendedConnect: supportsExtendedConnect) } /// Checks that a given HPACKHeaders block is a valid response header block, meeting all of the constraints of RFC 7540. /// /// If the header block is not valid, throws an error. internal func validateResponseBlock() throws { - return try ResponseBlockValidator.validateBlock(self) + try ResponseBlockValidator.validateBlock(self) } /// Checks that a given HPACKHeaders block is a valid trailer block, meeting all of the constraints of RFC 7540. /// /// If the header block is not valid, throws an error. internal func validateTrailersBlock() throws { - return try TrailersValidator.validateBlock(self) + try TrailersValidator.validateBlock(self) } } - /// A HTTP/2 header block is divided into two sections: the leading section, containing pseudo-headers, and /// the regular header section. Once the first regular header has been seen and we have transitioned into the /// header section, it is an error to see a pseudo-header again in this block. -fileprivate enum BlockSection { +private enum BlockSection { case pseudoHeaders case headers fileprivate mutating func validField(_ field: HeaderFieldName) throws { switch (self, field.fieldType) { case (.pseudoHeaders, .pseudoHeaderField), - (.headers, .regularHeaderField): + (.headers, .regularHeaderField): // Another header of the same type we're expecting. Do nothing. break @@ -63,9 +62,8 @@ fileprivate enum BlockSection { } } - /// A `HeaderBlockValidator` is an object that can confirm that a HPACK block meets certain constraints. -fileprivate protocol HeaderBlockValidator { +private protocol HeaderBlockValidator { init() var allowedPseudoHeaderFields: PseudoHeaders { get } @@ -75,7 +73,6 @@ fileprivate protocol HeaderBlockValidator { mutating func validateNextField(name: HeaderFieldName, value: String, pseudoHeaderType: PseudoHeaders?) throws } - extension HeaderBlockValidator { /// Validates that a header block meets the requirements of this `HeaderBlockValidator`. fileprivate static func validateBlock(_ block: HPACKHeaders, supportsExtendedConnect: Bool = false) throws { @@ -88,29 +85,37 @@ extension HeaderBlockValidator { try blockSection.validField(fieldName) try fieldName.legalHeaderField(value: value) - let thisPseudoHeaderFieldType = try seenPseudoHeaders.seenNewHeaderField(fieldName, supportsExtendedConnect: supportsExtendedConnect) + let thisPseudoHeaderFieldType = try seenPseudoHeaders.seenNewHeaderField( + fieldName, + supportsExtendedConnect: supportsExtendedConnect + ) try validator.validateNextField(name: fieldName, value: value, pseudoHeaderType: thisPseudoHeaderFieldType) } // We must only have seen pseudo-header fields allowed on this type of header block, // and at least the mandatory set. - guard validator.allowedPseudoHeaderFields.isSuperset(of: seenPseudoHeaders) && - validator.mandatoryPseudoHeaderFields.isSubset(of: seenPseudoHeaders) else { + guard + validator.allowedPseudoHeaderFields.isSuperset(of: seenPseudoHeaders) + && validator.mandatoryPseudoHeaderFields.isSubset(of: seenPseudoHeaders) + else { throw NIOHTTP2Errors.invalidPseudoHeaders(block) } } } - /// An object that can be used to validate if a given header block is a valid request header block. -fileprivate struct RequestBlockValidator { +private struct RequestBlockValidator { private var isConnectRequest: Bool = false private var containsProtocolPseudoHeader: Bool = false } extension RequestBlockValidator: HeaderBlockValidator { - fileprivate mutating func validateNextField(name: HeaderFieldName, value: String, pseudoHeaderType: PseudoHeaders?) throws { + fileprivate mutating func validateNextField( + name: HeaderFieldName, + value: String, + pseudoHeaderType: PseudoHeaders? + ) throws { // We have a wrinkle here: the set of allowed and mandatory pseudo headers for requests depends on whether this request is a CONNECT request. // If it isn't, RFC 7540 ยง 8.1.2.3 rules, and says that: // @@ -192,40 +197,45 @@ extension RequestBlockValidator: HeaderBlockValidator { } } - /// An object that can be used to validate if a given header block is a valid response header block. -fileprivate struct ResponseBlockValidator { +private struct ResponseBlockValidator { let allowedPseudoHeaderFields: PseudoHeaders = .allowedResponseHeaders let mandatoryPseudoHeaderFields: PseudoHeaders = .mandatoryResponseHeaders } extension ResponseBlockValidator: HeaderBlockValidator { - fileprivate mutating func validateNextField(name: HeaderFieldName, value: String, pseudoHeaderType: PseudoHeaders?) throws { + fileprivate mutating func validateNextField( + name: HeaderFieldName, + value: String, + pseudoHeaderType: PseudoHeaders? + ) throws { return } } - /// An object that can be used to validate if a given header block is a valid trailer block. -fileprivate struct TrailersValidator { +private struct TrailersValidator { let allowedPseudoHeaderFields: PseudoHeaders = [] let mandatoryPseudoHeaderFields: PseudoHeaders = [] } extension TrailersValidator: HeaderBlockValidator { - fileprivate mutating func validateNextField(name: HeaderFieldName, value: String, pseudoHeaderType: PseudoHeaders?) throws { + fileprivate mutating func validateNextField( + name: HeaderFieldName, + value: String, + pseudoHeaderType: PseudoHeaders? + ) throws { return } } - /// A structure that carries the details of a specific header field name. /// /// Used to validate the correctness of a specific header field name at a given /// point in a header block. -fileprivate struct HeaderFieldName { +private struct HeaderFieldName { /// The type of this header-field: pseudo-header or regular. fileprivate var fieldType: FieldType @@ -284,7 +294,6 @@ extension HeaderFieldName { } } - extension Substring.UTF8View { /// Whether this is a valid HTTP/2 header field name. fileprivate var isValidFieldName: Bool { @@ -322,10 +331,10 @@ extension Substring.UTF8View { /// /// We can then translate this into a straightforward switch statement to check whether the code /// units are valid. - return self.allSatisfy { codeUnit in + self.allSatisfy { codeUnit in switch codeUnit { case 0x21, 0x23...0x27, 0x2a, 0x2b, 0x2d, 0x2e, 0x30...0x39, - 0x5e...0x7a, 0x7c, 0x7e: + 0x5e...0x7a, 0x7c, 0x7e: return true default: return false @@ -334,9 +343,8 @@ extension Substring.UTF8View { } } - /// A set of all pseudo-headers defined in HTTP/2. -fileprivate struct PseudoHeaders: OptionSet { +private struct PseudoHeaders: OptionSet { var rawValue: UInt8 static let path = PseudoHeaders(rawValue: 1 << 0) @@ -348,7 +356,9 @@ fileprivate struct PseudoHeaders: OptionSet { static let mandatoryRequestHeaders: PseudoHeaders = [.path, .method, .scheme] static let allowedRequestHeaders: PseudoHeaders = [.path, .method, .scheme, .authority] - static let allowedExtendedConnectRequestHeaders: PseudoHeaders = [.path, .method, .scheme, .authority, .extConnectProtocol] + static let allowedExtendedConnectRequestHeaders: PseudoHeaders = [ + .path, .method, .scheme, .authority, .extConnectProtocol, + ] static let mandatoryConnectRequestHeaders: PseudoHeaders = [.method, .authority] static let allowedConnectRequestHeaders: PseudoHeaders = [.method, .authority] static let mandatoryResponseHeaders: PseudoHeaders = [.status] diff --git a/Sources/NIOHTTP2/HTTP2ChannelHandler+InboundStreamMultiplexer.swift b/Sources/NIOHTTP2/HTTP2ChannelHandler+InboundStreamMultiplexer.swift index 9ec9507..818e5fa 100644 --- a/Sources/NIOHTTP2/HTTP2ChannelHandler+InboundStreamMultiplexer.swift +++ b/Sources/NIOHTTP2/HTTP2ChannelHandler+InboundStreamMultiplexer.swift @@ -106,7 +106,7 @@ extension NIOHTTP2Handler.InboundStreamMultiplexer { case .inline(let inlineStreamMultiplexer): inlineStreamMultiplexer.propagateChannelActive() case .legacy: - break // do nothing + break // do nothing } } @@ -115,7 +115,7 @@ extension NIOHTTP2Handler.InboundStreamMultiplexer { case .inline(let inlineStreamMultiplexer): inlineStreamMultiplexer.propagateChannelInactive() case .legacy: - break // do nothing + break // do nothing } } @@ -133,7 +133,7 @@ extension NIOHTTP2Handler.InboundStreamMultiplexer { case .inline(let inlineStreamMultiplexer): inlineStreamMultiplexer.propagateChannelWritabilityChanged() case .legacy: - break // do nothing + break // do nothing } } @@ -142,7 +142,7 @@ extension NIOHTTP2Handler.InboundStreamMultiplexer { case .inline(let inlineStreamMultiplexer): inlineStreamMultiplexer.propagateReadComplete() case .legacy: - break // do nothing + break // do nothing } } @@ -151,7 +151,7 @@ extension NIOHTTP2Handler.InboundStreamMultiplexer { case .inline(let inlineStreamMultiplexer): inlineStreamMultiplexer.processedFrame(frame: frame) case .legacy: - break // do nothing + break // do nothing } } } @@ -164,7 +164,6 @@ internal struct LegacyInboundStreamMultiplexer { let context: ChannelHandlerContext } - extension LegacyInboundStreamMultiplexer: HTTP2InboundStreamMultiplexer { func receivedFrame(_ frame: HTTP2Frame) { self.context.fireChannelRead(NIOAny(frame)) diff --git a/Sources/NIOHTTP2/HTTP2ChannelHandler+InlineStreamMultiplexer.swift b/Sources/NIOHTTP2/HTTP2ChannelHandler+InlineStreamMultiplexer.swift index 52d8791..511fc32 100644 --- a/Sources/NIOHTTP2/HTTP2ChannelHandler+InlineStreamMultiplexer.swift +++ b/Sources/NIOHTTP2/HTTP2ChannelHandler+InlineStreamMultiplexer.swift @@ -26,7 +26,16 @@ internal struct InlineStreamMultiplexer { /// The delegate to be notified upon stream creation and close. private var streamDelegate: NIOHTTP2StreamDelegate? - init(context: ChannelHandlerContext, outboundView: NIOHTTP2Handler.OutboundView, mode: NIOHTTP2Handler.ParserMode, inboundStreamStateInitializer: MultiplexerAbstractChannel.InboundStreamStateInitializer, targetWindowSize: Int, streamChannelOutboundBytesHighWatermark: Int, streamChannelOutboundBytesLowWatermark: Int, streamDelegate: NIOHTTP2StreamDelegate?) { + init( + context: ChannelHandlerContext, + outboundView: NIOHTTP2Handler.OutboundView, + mode: NIOHTTP2Handler.ParserMode, + inboundStreamStateInitializer: MultiplexerAbstractChannel.InboundStreamStateInitializer, + targetWindowSize: Int, + streamChannelOutboundBytesHighWatermark: Int, + streamChannelOutboundBytesLowWatermark: Int, + streamDelegate: NIOHTTP2StreamDelegate? + ) { self.context = context self._commonStreamMultiplexer = HTTP2CommonInboundStreamMultiplexer( mode: mode, @@ -101,7 +110,7 @@ extension InlineStreamMultiplexer: HTTP2OutboundStreamMultiplexer { case .proceed: self.outboundView.flush(context: self.context) case .waitForReadsToComplete: - break // flush will be executed on `readComplete` + break // flush will be executed on `readComplete` } } @@ -147,21 +156,35 @@ extension InlineStreamMultiplexer { } extension InlineStreamMultiplexer { - internal func createStreamChannel(promise: EventLoopPromise?, _ streamStateInitializer: @escaping NIOChannelInitializer) { - self._commonStreamMultiplexer.createStreamChannel(multiplexer: .inline(self), promise: promise, streamStateInitializer) + internal func createStreamChannel( + promise: EventLoopPromise?, + _ streamStateInitializer: @escaping NIOChannelInitializer + ) { + self._commonStreamMultiplexer.createStreamChannel( + multiplexer: .inline(self), + promise: promise, + streamStateInitializer + ) } - internal func createStreamChannel(_ streamStateInitializer: @escaping NIOChannelInitializer) -> EventLoopFuture { + internal func createStreamChannel( + _ streamStateInitializer: @escaping NIOChannelInitializer + ) -> EventLoopFuture { self._commonStreamMultiplexer.createStreamChannel(multiplexer: .inline(self), streamStateInitializer) } @inlinable - internal func createStreamChannel(promise: EventLoopPromise?, _ initializer: @escaping NIOChannelInitializerWithOutput) { + internal func createStreamChannel( + promise: EventLoopPromise?, + _ initializer: @escaping NIOChannelInitializerWithOutput + ) { self._commonStreamMultiplexer.createStreamChannel(multiplexer: .inline(self), promise: promise, initializer) } @inlinable - internal func createStreamChannel(_ initializer: @escaping NIOChannelInitializerWithOutput) -> EventLoopFuture { + internal func createStreamChannel( + _ initializer: @escaping NIOChannelInitializerWithOutput + ) -> EventLoopFuture { self._commonStreamMultiplexer.createStreamChannel(multiplexer: .inline(self), initializer) } } @@ -184,7 +207,10 @@ extension NIOHTTP2Handler { /// Cannot be created by users. internal init(_ inlineStreamMultiplexer: InlineStreamMultiplexer, eventLoop: EventLoop) { - self.inlineStreamMultiplexer = InlineStreamMultiplexer.SendableView(inlineStreamMultiplexer, eventLoop: eventLoop) + self.inlineStreamMultiplexer = InlineStreamMultiplexer.SendableView( + inlineStreamMultiplexer, + eventLoop: eventLoop + ) self.eventLoop = eventLoop } @@ -200,7 +226,10 @@ extension NIOHTTP2Handler { /// failed if an error occurs. /// - streamStateInitializer: A callback that will be invoked to allow you to configure the /// `ChannelPipeline` for the newly created channel. - public func createStreamChannel(promise: EventLoopPromise?, _ streamStateInitializer: @escaping StreamInitializer) { + public func createStreamChannel( + promise: EventLoopPromise?, + _ streamStateInitializer: @escaping StreamInitializer + ) { self.inlineStreamMultiplexer.createStreamChannel(promise: promise, streamStateInitializer) } @@ -214,7 +243,9 @@ extension NIOHTTP2Handler { /// - Parameter streamStateInitializer: A callback that will be invoked to allow you to configure the /// `ChannelPipeline` for the newly created channel. /// - Returns: An `EventLoopFuture` containing the created `Channel`, fulfilled after the supplied `streamStateInitializer` has been executed on it. - public func createStreamChannel(_ streamStateInitializer: @escaping StreamInitializer) -> EventLoopFuture { + public func createStreamChannel( + _ streamStateInitializer: @escaping StreamInitializer + ) -> EventLoopFuture { self.inlineStreamMultiplexer.createStreamChannel(streamStateInitializer) } } @@ -238,7 +269,7 @@ extension NIOHTTP2Handler { /// and `IOData`. /// /// Inbound (remotely-initiated) streams are accessible via the ``inbound`` property, having been initialized and - /// returned as the `InboundStreamOutput` type. + /// returned as the `InboundStreamOutput` type. /// /// You can open a stream by calling ``openStream(_:)``. Locally-initiated stream channel objects are initialized upon creation using the supplied `initializer` which returns a type /// `Output`. This type may be `HTTP2Frame` or changed to any other type. @@ -249,8 +280,16 @@ extension NIOHTTP2Handler { // Cannot be created by users. @usableFromInline - internal init(_ inlineStreamMultiplexer: InlineStreamMultiplexer, eventLoop: EventLoop, continuation: any AnyContinuation, inboundStreamChannels: NIOHTTP2AsyncSequence) { - self._inlineStreamMultiplexer = InlineStreamMultiplexer.SendableView(inlineStreamMultiplexer, eventLoop: eventLoop) + internal init( + _ inlineStreamMultiplexer: InlineStreamMultiplexer, + eventLoop: EventLoop, + continuation: any AnyContinuation, + inboundStreamChannels: NIOHTTP2AsyncSequence + ) { + self._inlineStreamMultiplexer = InlineStreamMultiplexer.SendableView( + inlineStreamMultiplexer, + eventLoop: eventLoop + ) self._inlineStreamMultiplexer.setChannelContinuation(continuation) self.inbound = inboundStreamChannels } @@ -259,8 +298,10 @@ extension NIOHTTP2Handler { /// initializing the stream's `Channel`. /// - Returns: The result of the `initializer`. @inlinable - public func openStream(_ initializer: @escaping NIOChannelInitializerWithOutput) async throws -> Output { - return try await self._inlineStreamMultiplexer.createStreamChannel(initializer).get() + public func openStream( + _ initializer: @escaping NIOChannelInitializerWithOutput + ) async throws -> Output { + try await self._inlineStreamMultiplexer.createStreamChannel(initializer).get() } } } @@ -280,7 +321,10 @@ extension InlineStreamMultiplexer { self._eventLoop = eventLoop } - internal func createStreamChannel(promise: EventLoopPromise?, _ streamStateInitializer: @escaping NIOHTTP2Handler.StreamInitializer) { + internal func createStreamChannel( + promise: EventLoopPromise?, + _ streamStateInitializer: @escaping NIOHTTP2Handler.StreamInitializer + ) { // Always create streams channels on the next event loop tick. This avoids re-entrancy // issues where handlers interposed between the two HTTP/2 handlers could create streams // in channel active which become activated twice. @@ -301,7 +345,9 @@ extension InlineStreamMultiplexer { } @inlinable - internal func createStreamChannel(_ initializer: @escaping NIOChannelInitializerWithOutput) -> EventLoopFuture { + internal func createStreamChannel( + _ initializer: @escaping NIOChannelInitializerWithOutput + ) -> EventLoopFuture { // Always create streams channels on the next event loop tick. This avoids re-entrancy // issues where handlers interposed between the two HTTP/2 handlers could create streams // in channel active which become activated twice. @@ -317,7 +363,7 @@ extension InlineStreamMultiplexer { return self._inlineStreamMultiplexer.setChannelContinuation(streamChannels) } else { self._eventLoop.execute { - return self._inlineStreamMultiplexer.setChannelContinuation(streamChannels) + self._inlineStreamMultiplexer.setChannelContinuation(streamChannels) } } } diff --git a/Sources/NIOHTTP2/HTTP2ChannelHandler.swift b/Sources/NIOHTTP2/HTTP2ChannelHandler.swift index 459debc..d514259 100644 --- a/Sources/NIOHTTP2/HTTP2ChannelHandler.swift +++ b/Sources/NIOHTTP2/HTTP2ChannelHandler.swift @@ -14,7 +14,6 @@ import NIOCore import NIOHPACK - /// NIO's default settings used for initial settings values on HTTP/2 streams, when the user hasn't /// overridden that. This limits the max concurrent streams to 100, and limits the max header list /// size to 16kB, to avoid trivial resource exhaustion on NIO HTTP/2 users. @@ -112,7 +111,7 @@ public final class NIOHTTP2Handler: ChannelDuplexHandler { @usableFromInline internal var inboundStreamMultiplexer: InboundStreamMultiplexer? { - return self.inboundStreamMultiplexerState.multiplexer + self.inboundStreamMultiplexerState.multiplexer } /// Holds and tracks the state of the ``InboundStreamMultiplexer``. @@ -141,43 +140,55 @@ public final class NIOHTTP2Handler: ChannelDuplexHandler { } } - mutating func initialize(context: ChannelHandlerContext, http2Handler: NIOHTTP2Handler, mode: NIOHTTP2Handler.ParserMode) { + mutating func initialize( + context: ChannelHandlerContext, + http2Handler: NIOHTTP2Handler, + mode: NIOHTTP2Handler.ParserMode + ) { switch self { case .deinitialized: - preconditionFailure("This multiplexer has been de-initialized without being reconfigured with a new context.") + preconditionFailure( + "This multiplexer has been de-initialized without being reconfigured with a new context." + ) case .uninitializedLegacy: self = .initialized(.legacy(LegacyInboundStreamMultiplexer(context: context))) case .uninitializedInline(let streamConfiguration, let inboundStreamInitializer, let streamDelegate): - self = .initialized(.inline( - InlineStreamMultiplexer( - context: context, - outboundView: .init(http2Handler: http2Handler), - mode: mode, - inboundStreamStateInitializer: .excludesStreamID(inboundStreamInitializer), - targetWindowSize: max(0, min(streamConfiguration.targetWindowSize, Int(Int32.max))), - streamChannelOutboundBytesHighWatermark: streamConfiguration.outboundBufferSizeHighWatermark, - streamChannelOutboundBytesLowWatermark: streamConfiguration.outboundBufferSizeLowWatermark, - streamDelegate: streamDelegate + self = .initialized( + .inline( + InlineStreamMultiplexer( + context: context, + outboundView: .init(http2Handler: http2Handler), + mode: mode, + inboundStreamStateInitializer: .excludesStreamID(inboundStreamInitializer), + targetWindowSize: max(0, min(streamConfiguration.targetWindowSize, Int(Int32.max))), + streamChannelOutboundBytesHighWatermark: streamConfiguration + .outboundBufferSizeHighWatermark, + streamChannelOutboundBytesLowWatermark: streamConfiguration.outboundBufferSizeLowWatermark, + streamDelegate: streamDelegate + ) ) - )) + ) case .uninitializedAsync(let streamConfiguration, let inboundStreamInitializer, let streamDelegate): - self = .initialized(.inline( - InlineStreamMultiplexer( - context: context, - outboundView: .init(http2Handler: http2Handler), - mode: mode, - inboundStreamStateInitializer: .returnsAny(inboundStreamInitializer), - targetWindowSize: max(0, min(streamConfiguration.targetWindowSize, Int(Int32.max))), - streamChannelOutboundBytesHighWatermark: streamConfiguration.outboundBufferSizeHighWatermark, - streamChannelOutboundBytesLowWatermark: streamConfiguration.outboundBufferSizeLowWatermark, - streamDelegate: streamDelegate + self = .initialized( + .inline( + InlineStreamMultiplexer( + context: context, + outboundView: .init(http2Handler: http2Handler), + mode: mode, + inboundStreamStateInitializer: .returnsAny(inboundStreamInitializer), + targetWindowSize: max(0, min(streamConfiguration.targetWindowSize, Int(Int32.max))), + streamChannelOutboundBytesHighWatermark: streamConfiguration + .outboundBufferSizeHighWatermark, + streamChannelOutboundBytesLowWatermark: streamConfiguration.outboundBufferSizeLowWatermark, + streamDelegate: streamDelegate + ) ) - )) + ) case .initialized: - break //no-op + break //no-op } } } @@ -207,20 +218,24 @@ public final class NIOHTTP2Handler: ChannelDuplexHandler { /// - initialSettings: The settings that will be advertised to the peer in the preamble. Defaults to ``nioDefaultSettings``. /// - headerBlockValidation: Whether to validate sent and received HTTP/2 header blocks. Defaults to ``ValidationState/enabled``. /// - contentLengthValidation: Whether to validate the content length of sent and received streams. Defaults to ``ValidationState/enabled``. - public convenience init(mode: ParserMode, - initialSettings: HTTP2Settings = nioDefaultSettings, - headerBlockValidation: ValidationState = .enabled, - contentLengthValidation: ValidationState = .enabled) { - self.init(mode: mode, - eventLoop: nil, - initialSettings: initialSettings, - headerBlockValidation: headerBlockValidation, - contentLengthValidation: contentLengthValidation, - maximumSequentialEmptyDataFrames: 1, - maximumBufferedControlFrames: 10000, - maximumSequentialContinuationFrames: NIOHTTP2Handler.defaultMaximumSequentialContinuationFrames, - maximumResetFrameCount: 200, - resetFrameCounterWindow: .seconds(30)) + public convenience init( + mode: ParserMode, + initialSettings: HTTP2Settings = nioDefaultSettings, + headerBlockValidation: ValidationState = .enabled, + contentLengthValidation: ValidationState = .enabled + ) { + self.init( + mode: mode, + eventLoop: nil, + initialSettings: initialSettings, + headerBlockValidation: headerBlockValidation, + contentLengthValidation: contentLengthValidation, + maximumSequentialEmptyDataFrames: 1, + maximumBufferedControlFrames: 10000, + maximumSequentialContinuationFrames: NIOHTTP2Handler.defaultMaximumSequentialContinuationFrames, + maximumResetFrameCount: 200, + resetFrameCounterWindow: .seconds(30) + ) } /// Constructs a ``NIOHTTP2Handler``. @@ -235,62 +250,84 @@ public final class NIOHTTP2Handler: ChannelDuplexHandler { /// - maximumBufferedControlFrames: Controls the maximum buffer size of buffered outbound control frames. If we are unable to send control frames as /// fast as we produce them we risk building up an unbounded buffer and exhausting our memory. To protect against this DoS vector, we put an /// upper limit on the depth of this queue. Defaults to 10,000. - public convenience init(mode: ParserMode, - initialSettings: HTTP2Settings = nioDefaultSettings, - headerBlockValidation: ValidationState = .enabled, - contentLengthValidation: ValidationState = .enabled, - maximumSequentialEmptyDataFrames: Int = 1, - maximumBufferedControlFrames: Int = 10000) { - self.init(mode: mode, - eventLoop: nil, - initialSettings: initialSettings, - headerBlockValidation: headerBlockValidation, - contentLengthValidation: contentLengthValidation, - maximumSequentialEmptyDataFrames: maximumSequentialEmptyDataFrames, - maximumBufferedControlFrames: maximumBufferedControlFrames, - maximumSequentialContinuationFrames: NIOHTTP2Handler.defaultMaximumSequentialContinuationFrames, - maximumResetFrameCount: 200, - resetFrameCounterWindow: .seconds(30)) + public convenience init( + mode: ParserMode, + initialSettings: HTTP2Settings = nioDefaultSettings, + headerBlockValidation: ValidationState = .enabled, + contentLengthValidation: ValidationState = .enabled, + maximumSequentialEmptyDataFrames: Int = 1, + maximumBufferedControlFrames: Int = 10000 + ) { + self.init( + mode: mode, + eventLoop: nil, + initialSettings: initialSettings, + headerBlockValidation: headerBlockValidation, + contentLengthValidation: contentLengthValidation, + maximumSequentialEmptyDataFrames: maximumSequentialEmptyDataFrames, + maximumBufferedControlFrames: maximumBufferedControlFrames, + maximumSequentialContinuationFrames: NIOHTTP2Handler.defaultMaximumSequentialContinuationFrames, + maximumResetFrameCount: 200, + resetFrameCounterWindow: .seconds(30) + ) } /// Constructs a ``NIOHTTP2Handler``. - /// + /// /// - Parameters: /// - mode: The mode for this handler, client or server. /// - connectionConfiguration: The settings that will be used when establishing the connection. /// - streamConfiguration: The settings that will be used when establishing new streams. - public convenience init(mode: ParserMode, - connectionConfiguration: ConnectionConfiguration = .init(), - streamConfiguration: StreamConfiguration = .init()) { - self.init(mode: mode, - eventLoop: nil, - initialSettings: connectionConfiguration.initialSettings, - headerBlockValidation: connectionConfiguration.headerBlockValidation, - contentLengthValidation: connectionConfiguration.contentLengthValidation, - maximumSequentialEmptyDataFrames: connectionConfiguration.maximumSequentialEmptyDataFrames, - maximumBufferedControlFrames: connectionConfiguration.maximumBufferedControlFrames, - maximumSequentialContinuationFrames: connectionConfiguration.maximumSequentialContinuationFrames, - maximumResetFrameCount: streamConfiguration.streamResetFrameRateLimit.maximumCount, - resetFrameCounterWindow: streamConfiguration.streamResetFrameRateLimit.windowLength) + public convenience init( + mode: ParserMode, + connectionConfiguration: ConnectionConfiguration = .init(), + streamConfiguration: StreamConfiguration = .init() + ) { + self.init( + mode: mode, + eventLoop: nil, + initialSettings: connectionConfiguration.initialSettings, + headerBlockValidation: connectionConfiguration.headerBlockValidation, + contentLengthValidation: connectionConfiguration.contentLengthValidation, + maximumSequentialEmptyDataFrames: connectionConfiguration.maximumSequentialEmptyDataFrames, + maximumBufferedControlFrames: connectionConfiguration.maximumBufferedControlFrames, + maximumSequentialContinuationFrames: connectionConfiguration.maximumSequentialContinuationFrames, + maximumResetFrameCount: streamConfiguration.streamResetFrameRateLimit.maximumCount, + resetFrameCounterWindow: streamConfiguration.streamResetFrameRateLimit.windowLength + ) } - private init(mode: ParserMode, - eventLoop: EventLoop?, - initialSettings: HTTP2Settings, - headerBlockValidation: ValidationState, - contentLengthValidation: ValidationState, - maximumSequentialEmptyDataFrames: Int, - maximumBufferedControlFrames: Int, - maximumSequentialContinuationFrames: Int, - maximumResetFrameCount: Int, - resetFrameCounterWindow: TimeAmount) { + private init( + mode: ParserMode, + eventLoop: EventLoop?, + initialSettings: HTTP2Settings, + headerBlockValidation: ValidationState, + contentLengthValidation: ValidationState, + maximumSequentialEmptyDataFrames: Int, + maximumBufferedControlFrames: Int, + maximumSequentialContinuationFrames: Int, + maximumResetFrameCount: Int, + resetFrameCounterWindow: TimeAmount + ) { self._eventLoop = eventLoop - self.stateMachine = HTTP2ConnectionStateMachine(role: .init(mode), headerBlockValidation: .init(headerBlockValidation), contentLengthValidation: .init(contentLengthValidation)) + self.stateMachine = HTTP2ConnectionStateMachine( + role: .init(mode), + headerBlockValidation: .init(headerBlockValidation), + contentLengthValidation: .init(contentLengthValidation) + ) self.mode = mode self.initialSettings = initialSettings - self.outboundBuffer = CompoundOutboundBuffer(mode: mode, initialMaxOutboundStreams: 100, maxBufferedControlFrames: maximumBufferedControlFrames) - self.denialOfServiceValidator = DOSHeuristics(maximumSequentialEmptyDataFrames: maximumSequentialEmptyDataFrames, maximumResetFrameCount: maximumResetFrameCount, resetFrameCounterWindow: resetFrameCounterWindow) + self.outboundBuffer = CompoundOutboundBuffer( + mode: mode, + initialMaxOutboundStreams: 100, + maxBufferedControlFrames: maximumBufferedControlFrames + ) + self.denialOfServiceValidator = DOSHeuristics( + maximumSequentialEmptyDataFrames: maximumSequentialEmptyDataFrames, + maximumResetFrameCount: maximumResetFrameCount, + resetFrameCounterWindow: resetFrameCounterWindow + ) self.tolerateImpossibleStateTransitionsInDebugMode = false self.inboundStreamMultiplexerState = .uninitializedLegacy self.maximumSequentialContinuationFrames = maximumSequentialContinuationFrames @@ -315,22 +352,36 @@ public final class NIOHTTP2Handler: ChannelDuplexHandler { /// against this DoS vector we put an upper limit on this rate. Defaults to 200. /// - resetFrameCounterWindow: Controls the sliding window used to enforce the maximum permitted reset frames rate. Too many may exhaust CPU resources. To protect /// against this DoS vector we put an upper limit on this rate. 30 seconds. - internal init(mode: ParserMode, - initialSettings: HTTP2Settings = nioDefaultSettings, - headerBlockValidation: ValidationState = .enabled, - contentLengthValidation: ValidationState = .enabled, - maximumSequentialEmptyDataFrames: Int = 1, - maximumBufferedControlFrames: Int = 10000, - maximumSequentialContinuationFrames: Int = NIOHTTP2Handler.defaultMaximumSequentialContinuationFrames, - tolerateImpossibleStateTransitionsInDebugMode: Bool = false, - maximumResetFrameCount: Int = 200, - resetFrameCounterWindow: TimeAmount = .seconds(30)) { - self.stateMachine = HTTP2ConnectionStateMachine(role: .init(mode), headerBlockValidation: .init(headerBlockValidation), contentLengthValidation: .init(contentLengthValidation)) + internal init( + mode: ParserMode, + initialSettings: HTTP2Settings = nioDefaultSettings, + headerBlockValidation: ValidationState = .enabled, + contentLengthValidation: ValidationState = .enabled, + maximumSequentialEmptyDataFrames: Int = 1, + maximumBufferedControlFrames: Int = 10000, + maximumSequentialContinuationFrames: Int = NIOHTTP2Handler.defaultMaximumSequentialContinuationFrames, + tolerateImpossibleStateTransitionsInDebugMode: Bool = false, + maximumResetFrameCount: Int = 200, + resetFrameCounterWindow: TimeAmount = .seconds(30) + ) { + self.stateMachine = HTTP2ConnectionStateMachine( + role: .init(mode), + headerBlockValidation: .init(headerBlockValidation), + contentLengthValidation: .init(contentLengthValidation) + ) self.mode = mode self._eventLoop = nil self.initialSettings = initialSettings - self.outboundBuffer = CompoundOutboundBuffer(mode: mode, initialMaxOutboundStreams: 100, maxBufferedControlFrames: maximumBufferedControlFrames) - self.denialOfServiceValidator = DOSHeuristics(maximumSequentialEmptyDataFrames: maximumSequentialEmptyDataFrames, maximumResetFrameCount: maximumResetFrameCount, resetFrameCounterWindow: resetFrameCounterWindow) + self.outboundBuffer = CompoundOutboundBuffer( + mode: mode, + initialMaxOutboundStreams: 100, + maxBufferedControlFrames: maximumBufferedControlFrames + ) + self.denialOfServiceValidator = DOSHeuristics( + maximumSequentialEmptyDataFrames: maximumSequentialEmptyDataFrames, + maximumResetFrameCount: maximumResetFrameCount, + resetFrameCounterWindow: resetFrameCounterWindow + ) self.tolerateImpossibleStateTransitionsInDebugMode = tolerateImpossibleStateTransitionsInDebugMode self.inboundStreamMultiplexerState = .uninitializedLegacy self.maximumSequentialContinuationFrames = maximumSequentialContinuationFrames @@ -349,7 +400,11 @@ public final class NIOHTTP2Handler: ChannelDuplexHandler { if context.channel.isActive { // We jump immediately to activated here, as channelActive has probably already passed. if self.activationState != .idle { - self.impossibleActivationStateTransition(state: self.activationState, activating: true, context: context) + self.impossibleActivationStateTransition( + state: self.activationState, + activating: true, + context: context + ) } self.activationState = .activated self.writeAndFlushPreamble(context: context) @@ -391,7 +446,9 @@ public final class NIOHTTP2Handler: ChannelDuplexHandler { // // We'll throw an error and then close. In debug builds, we crash. self.impossibleActivationStateTransition( - state: self.activationState, activating: true, context: context + state: self.activationState, + activating: true, + context: context ) return } @@ -418,7 +475,9 @@ public final class NIOHTTP2Handler: ChannelDuplexHandler { // - .activated implies that the above code didn't prevent us re-entrantly getting to this point. // - .inactive implies that somehow we hit channelInactive but didn't enter .inactiveWhileActivating. self.impossibleActivationStateTransition( - state: self.activationState, activating: true, context: context + state: self.activationState, + activating: true, + context: context ) } } @@ -493,7 +552,6 @@ public final class NIOHTTP2Handler: ChannelDuplexHandler { } } - /// Inbound frame handling. extension NIOHTTP2Handler { /// Spins over the frame decoder parsing frames and sending them down the channel pipeline. @@ -510,16 +568,32 @@ extension NIOHTTP2Handler { do { return try self.frameDecoder.nextFrame() } catch InternalError.codecError(let code) { - self.inboundConnectionErrorTriggered(context: context, underlyingError: NIOHTTP2Errors.unableToParseFrame(), reason: code) + self.inboundConnectionErrorTriggered( + context: context, + underlyingError: NIOHTTP2Errors.unableToParseFrame(), + reason: code + ) return nil } catch is NIOHTTP2Errors.BadClientMagic { - self.inboundConnectionErrorTriggered(context: context, underlyingError: NIOHTTP2Errors.badClientMagic(), reason: .protocolError) + self.inboundConnectionErrorTriggered( + context: context, + underlyingError: NIOHTTP2Errors.badClientMagic(), + reason: .protocolError + ) return nil } catch is NIOHTTP2Errors.ExcessivelyLargeHeaderBlock { - self.inboundConnectionErrorTriggered(context: context, underlyingError: NIOHTTP2Errors.excessivelyLargeHeaderBlock(), reason: .protocolError) + self.inboundConnectionErrorTriggered( + context: context, + underlyingError: NIOHTTP2Errors.excessivelyLargeHeaderBlock(), + reason: .protocolError + ) return nil } catch is NIOHTTP2Errors.ExcessiveContinuationFrames { - self.inboundConnectionErrorTriggered(context: context, underlyingError: NIOHTTP2Errors.excessiveContinuationFrames(), reason: .enhanceYourCalm) + self.inboundConnectionErrorTriggered( + context: context, + underlyingError: NIOHTTP2Errors.excessiveContinuationFrames(), + reason: .enhanceYourCalm + ) return nil } catch { self.inboundConnectionErrorTriggered(context: context, underlyingError: error, reason: .internalError) @@ -532,7 +606,11 @@ extension NIOHTTP2Handler { case stop } - private func processFrame(_ frame: HTTP2Frame, flowControlledLength: Int, context: ChannelHandlerContext) -> FrameProcessResult { + private func processFrame( + _ frame: HTTP2Frame, + flowControlledLength: Int, + context: ChannelHandlerContext + ) -> FrameProcessResult { // All frames have one basic processing step: do we send them on, or drop them? // Some frames have further processing steps, regarding triggering user events or other operations. // Here we centralise this processing. @@ -544,18 +622,30 @@ extension NIOHTTP2Handler { case .origin(let origins): result = self.stateMachine.receiveOrigin(origins: origins) case .data(let dataBody): - result = self.stateMachine.receiveData(streamID: frame.streamID, contentLength: dataBody.data.readableBytes, flowControlledBytes: flowControlledLength, isEndStreamSet: dataBody.endStream) + result = self.stateMachine.receiveData( + streamID: frame.streamID, + contentLength: dataBody.data.readableBytes, + flowControlledBytes: flowControlledLength, + isEndStreamSet: dataBody.endStream + ) case .goAway(let lastStreamID, _, _): result = self.stateMachine.receiveGoaway(lastStreamID: lastStreamID) case .headers(let headerBody): - result = self.stateMachine.receiveHeaders(streamID: frame.streamID, headers: headerBody.headers, isEndStreamSet: headerBody.endStream) + result = self.stateMachine.receiveHeaders( + streamID: frame.streamID, + headers: headerBody.headers, + isEndStreamSet: headerBody.endStream + ) // Apply a priority update if one is here. If this fails, it may cause a connection error. if let priorityData = headerBody.priorityData { do { try self.outboundBuffer.priorityUpdate(streamID: frame.streamID, priorityData: priorityData) } catch { - result = StateMachineResultWithEffect(result: .connectionError(underlyingError: error, type: .protocolError), effect: nil) + result = StateMachineResultWithEffect( + result: .connectionError(underlyingError: error, type: .protocolError), + effect: nil + ) } } @@ -577,23 +667,36 @@ extension NIOHTTP2Handler { do { try self.outboundBuffer.priorityUpdate(streamID: frame.streamID, priorityData: priorityData) } catch { - result = StateMachineResultWithEffect(result: .connectionError(underlyingError: error, type: .protocolError), effect: nil) + result = StateMachineResultWithEffect( + result: .connectionError(underlyingError: error, type: .protocolError), + effect: nil + ) } case .pushPromise(let pushedStreamData): - result = self.stateMachine.receivePushPromise(originalStreamID: frame.streamID, childStreamID: pushedStreamData.pushedStreamID, headers: pushedStreamData.headers) + result = self.stateMachine.receivePushPromise( + originalStreamID: frame.streamID, + childStreamID: pushedStreamData.pushedStreamID, + headers: pushedStreamData.headers + ) case .rstStream(let reason): result = self.stateMachine.receiveRstStream(streamID: frame.streamID, reason: reason) case .settings(let newSettings): - let (stateMachineResult, postSettingsOperation) = self.stateMachine.receiveSettings(newSettings, - frameEncoder: &self.frameEncoder, - frameDecoder: &self.frameDecoder) + let (stateMachineResult, postSettingsOperation) = self.stateMachine.receiveSettings( + newSettings, + frameEncoder: &self.frameEncoder, + frameDecoder: &self.frameDecoder + ) result = stateMachineResult switch postSettingsOperation { case .nothing: break case .sendAck: - self.writeBufferedFrame(context: context, frame: HTTP2Frame(streamID: .rootStream, payload: .settings(.ack)), promise: nil) + self.writeBufferedFrame( + context: context, + frame: HTTP2Frame(streamID: .rootStream, payload: .settings(.ack)), + promise: nil + ) } case .windowUpdate(let increment): @@ -618,7 +721,12 @@ extension NIOHTTP2Handler { returnValue = .stop case .streamError(let streamID, let underlyingError, let errorCode): // We can continue parsing on stream errors in most cases, the frame is just ignored. - self.inboundStreamErrorTriggered(context: context, streamID: streamID, underlyingError: underlyingError, reason: errorCode) + self.inboundStreamErrorTriggered( + context: context, + streamID: streamID, + underlyingError: underlyingError, + reason: errorCode + ) returnValue = .continue } @@ -630,19 +738,31 @@ extension NIOHTTP2Handler { } /// A connection error was hit while receiving a frame. - private func inboundConnectionErrorTriggered(context: ChannelHandlerContext, underlyingError: Error, reason: HTTP2ErrorCode) { + private func inboundConnectionErrorTriggered( + context: ChannelHandlerContext, + underlyingError: Error, + reason: HTTP2ErrorCode + ) { // A connection error brings the entire connection down. We attempt to write a GOAWAY frame, and then report this // error. It's possible that we'll be unable to write the GOAWAY frame, but that also just logs the error. // Because we don't know what data the user handled before we got this, we propose that they may have seen all of it. // The user may choose to fire a more specific error if they wish. - let goAwayFrame = HTTP2Frame(streamID: .rootStream, payload: .goAway(lastStreamID: .maxID, errorCode: reason, opaqueData: nil)) + let goAwayFrame = HTTP2Frame( + streamID: .rootStream, + payload: .goAway(lastStreamID: .maxID, errorCode: reason, opaqueData: nil) + ) self.writeUnbufferedFrame(context: context, frame: goAwayFrame) self.flushIfNecessary(context: context) context.fireErrorCaught(underlyingError) } /// A stream error was hit while receiving a frame. - private func inboundStreamErrorTriggered(context: ChannelHandlerContext, streamID: HTTP2StreamID, underlyingError: Error, reason: HTTP2ErrorCode) { + private func inboundStreamErrorTriggered( + context: ChannelHandlerContext, + streamID: HTTP2StreamID, + underlyingError: Error, + reason: HTTP2ErrorCode + ) { // A stream error brings down a single stream, causing a RST_STREAM frame. We attempt to write this, and then report // the error. It's possible that we'll be unable to write this, which will likely escalate this error, but that's // the user's issue. @@ -684,7 +804,6 @@ extension NIOHTTP2Handler.InboundStreamMultiplexer { } } - /// Outbound frame handling. extension NIOHTTP2Handler { /// Issues the preamble when necessary. @@ -699,15 +818,23 @@ extension NIOHTTP2Handler { context.write(self.wrapOutboundOut(.byteBuffer(self.writeBuffer)), promise: nil) } - let initialSettingsFrame = HTTP2Frame(streamID: .rootStream, payload: .settings(.settings(self.initialSettings))) + let initialSettingsFrame = HTTP2Frame( + streamID: .rootStream, + payload: .settings(.settings(self.initialSettings)) + ) self.writeUnbufferedFrame(context: context, frame: initialSettingsFrame) self.flushIfNecessary(context: context) } /// Write a frame that is allowed to be buffered (that is, that participates in the outbound frame buffer). - private func writeBufferedFrame(context: ChannelHandlerContext, frame: HTTP2Frame, promise: EventLoopPromise?) { + private func writeBufferedFrame(context: ChannelHandlerContext, frame: HTTP2Frame, promise: EventLoopPromise?) + { do { - switch try self.outboundBuffer.processOutboundFrame(frame, promise: promise, channelWritable: self.channelWritable) { + switch try self.outboundBuffer.processOutboundFrame( + frame, + promise: promise, + channelWritable: self.channelWritable + ) { case .nothing: // Nothing to do, got buffered. break @@ -745,7 +872,11 @@ extension NIOHTTP2Handler { self.processOutboundFrame(context: context, frame: frame, promise: nil) } - private func processOutboundFrame(context: ChannelHandlerContext, frame: HTTP2Frame, promise: EventLoopPromise?) { + private func processOutboundFrame( + context: ChannelHandlerContext, + frame: HTTP2Frame, + promise: EventLoopPromise? + ) { let result: StateMachineResultWithEffect switch frame.payload { @@ -757,17 +888,30 @@ extension NIOHTTP2Handler { self.stateMachine.sendOrigin(origins: origins) case .data(let data): // TODO(cory): Correctly account for padding data. - result = self.stateMachine.sendData(streamID: frame.streamID, contentLength: data.data.readableBytes, flowControlledBytes: data.data.readableBytes, isEndStreamSet: data.endStream) + result = self.stateMachine.sendData( + streamID: frame.streamID, + contentLength: data.data.readableBytes, + flowControlledBytes: data.data.readableBytes, + isEndStreamSet: data.endStream + ) case .goAway(let lastStreamID, _, _): result = self.stateMachine.sendGoaway(lastStreamID: lastStreamID) case .headers(let headerContent): - result = self.stateMachine.sendHeaders(streamID: frame.streamID, headers: headerContent.headers, isEndStreamSet: headerContent.endStream) + result = self.stateMachine.sendHeaders( + streamID: frame.streamID, + headers: headerContent.headers, + isEndStreamSet: headerContent.endStream + ) case .ping: result = self.stateMachine.sendPing() case .priority: result = self.stateMachine.sendPriority() case .pushPromise(let pushedContent): - result = self.stateMachine.sendPushPromise(originalStreamID: frame.streamID, childStreamID: pushedContent.pushedStreamID, headers: pushedContent.headers) + result = self.stateMachine.sendPushPromise( + originalStreamID: frame.streamID, + childStreamID: pushedContent.pushedStreamID, + headers: pushedContent.headers + ) case .rstStream(let reason): result = self.stateMachine.sendRstStream(streamID: frame.streamID, reason: reason) case .settings(.settings(let newSettings)): @@ -792,8 +936,13 @@ extension NIOHTTP2Handler { case .connectionError(let underlyingError, _): self.outboundConnectionErrorTriggered(context: context, promise: promise, underlyingError: underlyingError) return - case .streamError(streamID: let streamID, underlyingError: let underlyingError, _): - self.outboundStreamErrorTriggered(context: context, promise: promise, streamID: streamID, underlyingError: underlyingError) + case .streamError(let streamID, let underlyingError, _): + self.outboundStreamErrorTriggered( + context: context, + promise: promise, + streamID: streamID, + underlyingError: underlyingError + ) return case .succeed: self.writeBuffer.clear() @@ -805,13 +954,21 @@ extension NIOHTTP2Handler { } /// Encodes a frame and writes it to the network. - private func encodeAndWriteFrame(context: ChannelHandlerContext, frame: HTTP2Frame, promise: EventLoopPromise?) { + private func encodeAndWriteFrame( + context: ChannelHandlerContext, + frame: HTTP2Frame, + promise: EventLoopPromise? + ) { let extraFrameData: IOData? do { extraFrameData = try self.frameEncoder.encode(frame: frame, to: &self.writeBuffer) } catch InternalError.codecError { - self.outboundConnectionErrorTriggered(context: context, promise: promise, underlyingError: NIOHTTP2Errors.unableToSerializeFrame()) + self.outboundConnectionErrorTriggered( + context: context, + promise: promise, + underlyingError: NIOHTTP2Errors.unableToSerializeFrame() + ) return } catch { self.outboundConnectionErrorTriggered(context: context, promise: promise, underlyingError: error) @@ -830,19 +987,27 @@ extension NIOHTTP2Handler { } /// A connection error was hit while attempting to send a frame. - private func outboundConnectionErrorTriggered(context: ChannelHandlerContext, promise: EventLoopPromise?, underlyingError: Error) { + private func outboundConnectionErrorTriggered( + context: ChannelHandlerContext, + promise: EventLoopPromise?, + underlyingError: Error + ) { promise?.fail(underlyingError) context.fireErrorCaught(underlyingError) } /// A stream error was hit while attempting to send a frame. - private func outboundStreamErrorTriggered(context: ChannelHandlerContext, promise: EventLoopPromise?, streamID: HTTP2StreamID, underlyingError: Error) { + private func outboundStreamErrorTriggered( + context: ChannelHandlerContext, + promise: EventLoopPromise?, + streamID: HTTP2StreamID, + underlyingError: Error + ) { promise?.fail(underlyingError) self.inboundStreamMultiplexer?.streamError(streamID: streamID, error: underlyingError) } } - // MARK:- Helpers extension NIOHTTP2Handler { private func processStateChange(_ stateChange: NIOHTTP2ConnectionStateChange?) { @@ -853,17 +1018,35 @@ extension NIOHTTP2Handler { switch stateChange { case .streamClosed(let streamClosedData): self.outboundBuffer.connectionWindowSize = streamClosedData.localConnectionWindowSize - self.inboundEventBuffer.pendingUserEvent(StreamClosedEvent(streamID: streamClosedData.streamID, reason: streamClosedData.reason)) - self.inboundEventBuffer.pendingUserEvent(NIOHTTP2WindowUpdatedEvent(streamID: .rootStream, inboundWindowSize: streamClosedData.remoteConnectionWindowSize, outboundWindowSize: streamClosedData.localConnectionWindowSize)) + self.inboundEventBuffer.pendingUserEvent( + StreamClosedEvent(streamID: streamClosedData.streamID, reason: streamClosedData.reason) + ) + self.inboundEventBuffer.pendingUserEvent( + NIOHTTP2WindowUpdatedEvent( + streamID: .rootStream, + inboundWindowSize: streamClosedData.remoteConnectionWindowSize, + outboundWindowSize: streamClosedData.localConnectionWindowSize + ) + ) let droppedPromises = self.outboundBuffer.streamClosed(streamClosedData.streamID) - self.failDroppedPromises(droppedPromises, streamID: streamClosedData.streamID, errorCode: streamClosedData.reason ?? .cancel) + self.failDroppedPromises( + droppedPromises, + streamID: streamClosedData.streamID, + errorCode: streamClosedData.reason ?? .cancel + ) case .streamCreated(let streamCreatedData): - self.outboundBuffer.streamCreated(streamCreatedData.streamID, initialWindowSize: streamCreatedData.localStreamWindowSize.map(UInt32.init) ?? 0) + self.outboundBuffer.streamCreated( + streamCreatedData.streamID, + initialWindowSize: streamCreatedData.localStreamWindowSize.map(UInt32.init) ?? 0 + ) self.inboundEventBuffer.pendingUserEvent( - NIOHTTP2StreamCreatedEvent(streamID: streamCreatedData.streamID, - localInitialWindowSize: streamCreatedData.localStreamWindowSize.map(UInt32.init), - remoteInitialWindowSize: streamCreatedData.remoteStreamWindowSize.map(UInt32.init))) + NIOHTTP2StreamCreatedEvent( + streamID: streamCreatedData.streamID, + localInitialWindowSize: streamCreatedData.localStreamWindowSize.map(UInt32.init), + remoteInitialWindowSize: streamCreatedData.remoteStreamWindowSize.map(UInt32.init) + ) + ) case .bulkStreamClosure(let streamClosureData): for droppedStream in streamClosureData.closedStreams { self.inboundEventBuffer.pendingUserEvent(StreamClosedEvent(streamID: droppedStream, reason: .cancel)) @@ -873,10 +1056,25 @@ extension NIOHTTP2Handler { } case .flowControlChange(let change): self.outboundBuffer.connectionWindowSize = change.localConnectionWindowSize - self.inboundEventBuffer.pendingUserEvent(NIOHTTP2WindowUpdatedEvent(streamID: .rootStream, inboundWindowSize: change.remoteConnectionWindowSize, outboundWindowSize: change.localConnectionWindowSize)) + self.inboundEventBuffer.pendingUserEvent( + NIOHTTP2WindowUpdatedEvent( + streamID: .rootStream, + inboundWindowSize: change.remoteConnectionWindowSize, + outboundWindowSize: change.localConnectionWindowSize + ) + ) if let streamSize = change.localStreamWindowSize { - self.outboundBuffer.updateStreamWindow(streamSize.streamID, newSize: streamSize.localStreamWindowSize.map(Int32.init) ?? 0) - self.inboundEventBuffer.pendingUserEvent(NIOHTTP2WindowUpdatedEvent(streamID: streamSize.streamID, inboundWindowSize: streamSize.remoteStreamWindowSize, outboundWindowSize: streamSize.localStreamWindowSize)) + self.outboundBuffer.updateStreamWindow( + streamSize.streamID, + newSize: streamSize.localStreamWindowSize.map(Int32.init) ?? 0 + ) + self.inboundEventBuffer.pendingUserEvent( + NIOHTTP2WindowUpdatedEvent( + streamID: streamSize.streamID, + inboundWindowSize: streamSize.remoteStreamWindowSize, + outboundWindowSize: streamSize.localStreamWindowSize + ) + ) } case .streamCreatedAndClosed(let cAndCData): self.outboundBuffer.streamCreated(cAndCData.streamID, initialWindowSize: 0) @@ -895,7 +1093,9 @@ extension NIOHTTP2Handler { } case .localSettingsChanged(let settingsChange): if settingsChange.streamWindowSizeChange != 0 { - self.inboundEventBuffer.pendingUserEvent(NIOHTTP2BulkStreamWindowChangeEvent(delta: settingsChange.streamWindowSizeChange)) + self.inboundEventBuffer.pendingUserEvent( + NIOHTTP2BulkStreamWindowChangeEvent(delta: settingsChange.streamWindowSizeChange) + ) } if let newMaxFrameSize = settingsChange.newMaxFrameSize { self.frameDecoder.maxFrameSize = newMaxFrameSize @@ -938,10 +1138,13 @@ extension NIOHTTP2Handler { } /// Fails any promises in the given collection with a 'StreamClosed' error. - private func failDroppedPromises(_ promises: CompoundOutboundBuffer.DroppedPromisesCollection, - streamID: HTTP2StreamID, - errorCode: HTTP2ErrorCode, - file: String = #fileID, line: UInt = #line) { + private func failDroppedPromises( + _ promises: CompoundOutboundBuffer.DroppedPromisesCollection, + streamID: HTTP2StreamID, + errorCode: HTTP2ErrorCode, + file: String = #fileID, + line: UInt = #line + ) { // 'NIOHTTP2Errors.streamClosed' always allocates, if there are no promises then there's no // need to create the error. guard promises.contains(where: { $0 != nil }) else { @@ -955,9 +1158,8 @@ extension NIOHTTP2Handler { } } - -private extension HTTP2ConnectionStateMachine.ConnectionRole { - init(_ role: NIOHTTP2Handler.ParserMode) { +extension HTTP2ConnectionStateMachine.ConnectionRole { + fileprivate init(_ role: NIOHTTP2Handler.ParserMode) { switch role { case .client: self = .client @@ -967,7 +1169,6 @@ private extension HTTP2ConnectionStateMachine.ConnectionRole { } } - extension HTTP2ConnectionStateMachine.ValidationState { init(_ state: NIOHTTP2Handler.ValidationState) { switch state { @@ -979,37 +1180,34 @@ extension HTTP2ConnectionStateMachine.ValidationState { } } - extension NIOHTTP2Handler: CustomStringConvertible { public var description: String { - return "NIOHTTP2Handler(mode: \(String(describing: self.mode)))" + "NIOHTTP2Handler(mode: \(String(describing: self.mode)))" } } - extension NIOHTTP2Handler: CustomDebugStringConvertible { public var debugDescription: String { - return """ -NIOHTTP2Handler( - stateMachine: \(String(describing: self.stateMachine)), - frameDecoder: \(String(describing: self.frameDecoder)), - frameEncoder: \(String(describing: self.frameEncoder)), - writeBuffer: \(String(describing: self.writeBuffer)), - inboundEventBuffer: \(String(describing: self.inboundEventBuffer)), - outboundBuffer: \(String(describing: self.outboundBuffer)), - wroteFrame: \(String(describing: self.wroteFrame)), - denialOfServiceValidator: \(String(describing: self.denialOfServiceValidator)), - mode: \(String(describing: self.mode)), - initialSettings: \(String(describing: self.initialSettings)), - channelClosed: \(String(describing: self.channelClosed)), - channelWritable: \(String(describing: self.channelWritable)), - activationState: \(String(describing: self.activationState)) -) -""" + """ + NIOHTTP2Handler( + stateMachine: \(String(describing: self.stateMachine)), + frameDecoder: \(String(describing: self.frameDecoder)), + frameEncoder: \(String(describing: self.frameEncoder)), + writeBuffer: \(String(describing: self.writeBuffer)), + inboundEventBuffer: \(String(describing: self.inboundEventBuffer)), + outboundBuffer: \(String(describing: self.outboundBuffer)), + wroteFrame: \(String(describing: self.wroteFrame)), + denialOfServiceValidator: \(String(describing: self.denialOfServiceValidator)), + mode: \(String(describing: self.mode)), + initialSettings: \(String(describing: self.initialSettings)), + channelClosed: \(String(describing: self.channelClosed)), + channelWritable: \(String(describing: self.channelWritable)), + activationState: \(String(describing: self.activationState)) + ) + """ } } - extension NIOHTTP2Handler { /// Tracks the state of activation of the handler. enum ActivationState { @@ -1031,7 +1229,9 @@ extension NIOHTTP2Handler { } fileprivate func impossibleActivationStateTransition( - state: ActivationState, activating: Bool, context: ChannelHandlerContext + state: ActivationState, + activating: Bool, + context: ChannelHandlerContext ) { assert(self.tolerateImpossibleStateTransitionsInDebugMode, "Unexpected channelActive in state \(state)") context.fireErrorCaught(NIOHTTP2Errors.ActivationError(state: state, activating: activating)) @@ -1039,7 +1239,6 @@ extension NIOHTTP2Handler { } } - extension NIOHTTP2Handler { /// Exposes restricted API for use by the multiplexer internal struct OutboundView { @@ -1059,7 +1258,6 @@ extension NIOHTTP2Handler { } } - extension NIOHTTP2Handler { /// The type of all `inboundStreamInitializer` callbacks which do not need to return data. public typealias StreamInitializer = NIOChannelInitializer @@ -1100,7 +1298,11 @@ extension NIOHTTP2Handler { resetFrameCounterWindow: streamConfiguration.streamResetFrameRateLimit.windowLength ) - self.inboundStreamMultiplexerState = .uninitializedInline(streamConfiguration, inboundStreamInitializer, streamDelegate) + self.inboundStreamMultiplexerState = .uninitializedInline( + streamConfiguration, + inboundStreamInitializer, + streamDelegate + ) } @usableFromInline @@ -1124,7 +1326,11 @@ extension NIOHTTP2Handler { maximumResetFrameCount: streamConfiguration.streamResetFrameRateLimit.maximumCount, resetFrameCounterWindow: streamConfiguration.streamResetFrameRateLimit.windowLength ) - self.inboundStreamMultiplexerState = .uninitializedAsync(streamConfiguration, inboundStreamInitializerWithAnyOutput, streamDelegate) + self.inboundStreamMultiplexerState = .uninitializedAsync( + streamConfiguration, + inboundStreamInitializerWithAnyOutput, + streamDelegate + ) } /// Connection-level configuration. @@ -1151,7 +1357,7 @@ extension NIOHTTP2Handler { public var streamResetFrameRateLimit: StreamResetFrameRateLimitConfiguration = .init() public init() {} } - + /// Stream reset frame rate limit configuration. /// /// The settings that control the maximum permitted reset frames within a given time window. Too many may exhaust CPU resources. @@ -1189,12 +1395,12 @@ extension NIOHTTP2Handler { // We need to return a future here so that we can synchronize access on the underlying `self.inboundStreamMultiplexer` if self._eventLoop!.inEventLoop { return self._eventLoop!.makeCompletedFuture { - return try self.syncMultiplexer() + try self.syncMultiplexer() } } else { let unsafeSelf = UnsafeTransfer(self) return self._eventLoop!.submit { - return try unsafeSelf.wrappedValue.syncMultiplexer() + try unsafeSelf.wrappedValue.syncMultiplexer() } } } @@ -1220,7 +1426,10 @@ extension NIOHTTP2Handler { @inlinable @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) - internal func syncAsyncStreamMultiplexer(continuation: any AnyContinuation, inboundStreamChannels: NIOHTTP2AsyncSequence) throws -> AsyncStreamMultiplexer { + internal func syncAsyncStreamMultiplexer( + continuation: any AnyContinuation, + inboundStreamChannels: NIOHTTP2AsyncSequence + ) throws -> AsyncStreamMultiplexer { self._eventLoop!.preconditionInEventLoop() guard let inboundStreamMultiplexer = self.inboundStreamMultiplexer else { throw NIOHTTP2Errors.missingMultiplexer() @@ -1228,7 +1437,12 @@ extension NIOHTTP2Handler { switch inboundStreamMultiplexer { case let .inline(multiplexer): - return AsyncStreamMultiplexer(multiplexer, eventLoop: self._eventLoop!, continuation: continuation, inboundStreamChannels: inboundStreamChannels) + return AsyncStreamMultiplexer( + multiplexer, + eventLoop: self._eventLoop!, + continuation: continuation, + inboundStreamChannels: inboundStreamChannels + ) case .legacy: throw NIOHTTP2Errors.missingMultiplexer() } diff --git a/Sources/NIOHTTP2/HTTP2CommonInboundStreamMultiplexer.swift b/Sources/NIOHTTP2/HTTP2CommonInboundStreamMultiplexer.swift index 0c6f3ee..dcf9f53 100644 --- a/Sources/NIOHTTP2/HTTP2CommonInboundStreamMultiplexer.swift +++ b/Sources/NIOHTTP2/HTTP2CommonInboundStreamMultiplexer.swift @@ -68,7 +68,11 @@ internal class HTTP2CommonInboundStreamMultiplexer { // MARK:- inbound multiplexer functions // note this is intentionally not bound to `HTTP2InboundStreamMultiplexer` to allow for freedom in modifying the shared driver function signatures extension HTTP2CommonInboundStreamMultiplexer { - func receivedFrame(_ frame: HTTP2Frame, context: ChannelHandlerContext, multiplexer: HTTP2StreamChannel.OutboundStreamMultiplexer) { + func receivedFrame( + _ frame: HTTP2Frame, + context: ChannelHandlerContext, + multiplexer: HTTP2StreamChannel.OutboundStreamMultiplexer + ) { self._channel.eventLoop.preconditionInEventLoop() self.isReading = true @@ -333,7 +337,7 @@ extension HTTP2CommonInboundStreamMultiplexer { self._pendingStreams[channel.channelID] = channel let anyInitializer: NIOChannelInitializerWithOutput = { channel in - streamStateInitializer(channel).map { return $0 } + streamStateInitializer(channel).map { $0 } } let anyPromise: EventLoopPromise<(any Sendable)>? @@ -390,13 +394,18 @@ extension HTTP2CommonInboundStreamMultiplexer { internal func createStreamChannel( multiplexer: HTTP2StreamChannel.OutboundStreamMultiplexer, - _ streamStateInitializer: @escaping NIOChannelInitializer) -> EventLoopFuture { + _ streamStateInitializer: @escaping NIOChannelInitializer + ) -> EventLoopFuture { let promise = self._channel.eventLoop.makePromise(of: Channel.self) self.createStreamChannel(multiplexer: multiplexer, promise: promise, streamStateInitializer) return promise.futureResult } - @available(*, deprecated, message: "The signature of 'streamStateInitializer' has changed to '(Channel) -> EventLoopFuture'") + @available( + *, + deprecated, + message: "The signature of 'streamStateInitializer' has changed to '(Channel) -> EventLoopFuture'" + ) internal func createStreamChannel( multiplexer: HTTP2StreamChannel.OutboundStreamMultiplexer, promise: EventLoopPromise?, @@ -453,7 +462,6 @@ internal protocol AnyContinuation: Sendable { func finish(throwing error: Error) } - /// `NIOHTTP2AsyncSequence` is an implementation of the `AsyncSequence` protocol which allows iteration over a generic /// element type `Output`. @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) @@ -504,18 +512,20 @@ extension NIOHTTP2AsyncSequence { @usableFromInline func yield(any: Any) { let yieldResult = self.continuation.yield(any as! Output) - switch yieldResult { - case .enqueued: - break // success, nothing to do - case .terminated: - // this can happen if the task has been cancelled - // we can't do better than dropping the message at the moment - break - case .dropped: - preconditionFailure("Attempted to yield when AsyncThrowingStream is over capacity. This shouldn't be possible for an unbounded stream.") - default: - preconditionFailure("Attempt to yield to AsyncThrowingStream failed for unhandled reason.") - } + switch yieldResult { + case .enqueued: + break // success, nothing to do + case .terminated: + // this can happen if the task has been cancelled + // we can't do better than dropping the message at the moment + break + case .dropped: + preconditionFailure( + "Attempted to yield when AsyncThrowingStream is over capacity. This shouldn't be possible for an unbounded stream." + ) + default: + preconditionFailure("Attempt to yield to AsyncThrowingStream failed for unhandled reason.") + } } /// `finish` marks the continuation as finished. @@ -531,7 +541,6 @@ extension NIOHTTP2AsyncSequence { } } - /// `initialize` creates a new `Continuation` object and returns it along with its backing ``NIOHTTP2AsyncSequence``. /// The `Continuation` provides the ability to yield to the backing .``NIOHTTP2AsyncSequence``. /// @@ -539,7 +548,9 @@ extension NIOHTTP2AsyncSequence { /// - inboundStreamInitializerOutput: The type which is returned by the initializer operating on the inbound /// (remotely-initiated) HTTP/2 streams. @usableFromInline - static func initialize(inboundStreamInitializerOutput: Output.Type = Output.self) -> (NIOHTTP2AsyncSequence, Continuation) { + static func initialize( + inboundStreamInitializerOutput: Output.Type = Output.self + ) -> (NIOHTTP2AsyncSequence, Continuation) { let (stream, continuation) = AsyncThrowingStream.makeStream(of: Output.self) return (.init(stream), Continuation(wrapping: continuation)) } diff --git a/Sources/NIOHTTP2/HTTP2ConnectionStateChange.swift b/Sources/NIOHTTP2/HTTP2ConnectionStateChange.swift index 09b34fd..f5ad7db 100644 --- a/Sources/NIOHTTP2/HTTP2ConnectionStateChange.swift +++ b/Sources/NIOHTTP2/HTTP2ConnectionStateChange.swift @@ -73,7 +73,12 @@ internal enum NIOHTTP2ConnectionStateChange: Hashable { internal var reason: HTTP2ErrorCode? - internal init(streamID: HTTP2StreamID, localConnectionWindowSize: Int, remoteConnectionWindowSize: Int, reason: HTTP2ErrorCode?) { + internal init( + streamID: HTTP2StreamID, + localConnectionWindowSize: Int, + remoteConnectionWindowSize: Int, + reason: HTTP2ErrorCode? + ) { self.streamID = streamID self.localConnectionWindowSize = localConnectionWindowSize self.remoteConnectionWindowSize = remoteConnectionWindowSize @@ -124,7 +129,11 @@ internal enum NIOHTTP2ConnectionStateChange: Hashable { } } - internal init(localConnectionWindowSize: Int, remoteConnectionWindowSize: Int, localStreamWindowSize: StreamWindowSizeChange?) { + internal init( + localConnectionWindowSize: Int, + remoteConnectionWindowSize: Int, + localStreamWindowSize: StreamWindowSizeChange? + ) { self.localConnectionWindowSize = localConnectionWindowSize self.remoteConnectionWindowSize = remoteConnectionWindowSize self.localStreamWindowSize = localStreamWindowSize @@ -169,7 +178,6 @@ internal enum NIOHTTP2ConnectionStateChange: Hashable { } } - /// A representation of a state change at the level of a single stream. /// /// While the NIOHTTP2ConnectionStateChange is an object that affects an entire connection, @@ -195,23 +203,34 @@ internal enum StreamStateChange: Hashable { } } - -internal extension NIOHTTP2ConnectionStateChange { - init(_ streamChange: StreamStateChange, inboundFlowControlWindow: HTTP2FlowControlWindow, outboundFlowControlWindow: HTTP2FlowControlWindow) { +extension NIOHTTP2ConnectionStateChange { + init( + _ streamChange: StreamStateChange, + inboundFlowControlWindow: HTTP2FlowControlWindow, + outboundFlowControlWindow: HTTP2FlowControlWindow + ) { switch streamChange { case .streamClosed(let streamClosedState): - self = .streamClosed(.init(streamID: streamClosedState.streamID, - localConnectionWindowSize: Int(outboundFlowControlWindow), - remoteConnectionWindowSize: Int(inboundFlowControlWindow), - reason: streamClosedState.reason)) + self = .streamClosed( + .init( + streamID: streamClosedState.streamID, + localConnectionWindowSize: Int(outboundFlowControlWindow), + remoteConnectionWindowSize: Int(inboundFlowControlWindow), + reason: streamClosedState.reason + ) + ) case .streamCreated(let streamCreated): self = .streamCreated(streamCreated) case .streamCreatedAndClosed(let streamCreatedAndClosed): self = .streamCreatedAndClosed(streamCreatedAndClosed) case .windowSizeChange(let streamSizeChange): - self = .flowControlChange(.init(localConnectionWindowSize: Int(outboundFlowControlWindow), - remoteConnectionWindowSize: Int(inboundFlowControlWindow), - localStreamWindowSize: streamSizeChange)) + self = .flowControlChange( + .init( + localConnectionWindowSize: Int(outboundFlowControlWindow), + remoteConnectionWindowSize: Int(inboundFlowControlWindow), + localStreamWindowSize: streamSizeChange + ) + ) } } } diff --git a/Sources/NIOHTTP2/HTTP2Error.swift b/Sources/NIOHTTP2/HTTP2Error.swift index 48cf26b..3aaba60 100644 --- a/Sources/NIOHTTP2/HTTP2Error.swift +++ b/Sources/NIOHTTP2/HTTP2Error.swift @@ -16,21 +16,24 @@ import NIOHPACK /// The base protocol for all errors thrown by ``NIOHTTP2``. /// /// Users are recommended not to implement this protocol with their own types. -public protocol NIOHTTP2Error: Equatable, Error { } +public protocol NIOHTTP2Error: Equatable, Error {} /// An internal marker-protocol for errors to do with content-length. -protocol InvalidContentLengthError: NIOHTTP2Error { } +protocol InvalidContentLengthError: NIOHTTP2Error {} /// Errors that ``NIOHTTP2`` raises when handling HTTP/2 connections. public enum NIOHTTP2Errors { /// Creates an ``ExcessiveOutboundFrameBuffering`` error with appropriate source context. - public static func excessiveOutboundFrameBuffering(file: String = #fileID, line: UInt = #line) -> ExcessiveOutboundFrameBuffering { - return ExcessiveOutboundFrameBuffering(file: file, line: line) + public static func excessiveOutboundFrameBuffering( + file: String = #fileID, + line: UInt = #line + ) -> ExcessiveOutboundFrameBuffering { + ExcessiveOutboundFrameBuffering(file: file, line: line) } /// Creates an ``InvalidALPNToken`` error with appropriate source context public static func invalidALPNToken(file: String = #fileID, line: UInt = #line) -> InvalidALPNToken { - return InvalidALPNToken(file: file, line: line) + InvalidALPNToken(file: file, line: line) } /// Creates a ``NoSuchStream`` error with appropriate source context. @@ -39,8 +42,9 @@ public enum NIOHTTP2Errors { /// - streamID: The ``HTTP2StreamID`` for the stream that does not exist. /// - file: Source file of the caller. /// - line: Source line number of the caller. - public static func noSuchStream(streamID: HTTP2StreamID, file: String = #fileID, line: UInt = #line) -> NoSuchStream { - return NoSuchStream(streamID: streamID, file: file, line: line) + public static func noSuchStream(streamID: HTTP2StreamID, file: String = #fileID, line: UInt = #line) -> NoSuchStream + { + NoSuchStream(streamID: streamID, file: file, line: line) } /// Creates a ``StreamClosed`` error with appropriate source context. @@ -50,8 +54,13 @@ public enum NIOHTTP2Errors { /// - errorCode: The ``HTTP2ErrorCode`` representing the reason for closure of the stream. /// - file: Source file of the caller. /// - line: Source line number of the caller. - public static func streamClosed(streamID: HTTP2StreamID, errorCode: HTTP2ErrorCode, file: String = #fileID, line: UInt = #line) -> StreamClosed { - return StreamClosed(streamID: streamID, errorCode: errorCode, file: file, line: line) + public static func streamClosed( + streamID: HTTP2StreamID, + errorCode: HTTP2ErrorCode, + file: String = #fileID, + line: UInt = #line + ) -> StreamClosed { + StreamClosed(streamID: streamID, errorCode: errorCode, file: file, line: line) } /// Creates a ``BadClientMagic`` error with appropriate source context. @@ -60,7 +69,7 @@ public enum NIOHTTP2Errors { /// - file: Source file of the caller. /// - line: Source line number of the caller. public static func badClientMagic(file: String = #fileID, line: UInt = #line) -> BadClientMagic { - return BadClientMagic(file: file, line: line) + BadClientMagic(file: file, line: line) } /// Creates a ``BadStreamStateTransition`` error with appropriate source context @@ -69,8 +78,12 @@ public enum NIOHTTP2Errors { /// - state: The ``NIOHTTP2StreamState`` representing the state of the stream from which we were trying to transition /// - file: Source file of the caller. /// - line: Source line number of the caller. - public static func badStreamStateTransition(from state: NIOHTTP2StreamState? = nil, file: String = #fileID, line: UInt = #line) -> BadStreamStateTransition { - return BadStreamStateTransition(from: state, file: file, line: line) + public static func badStreamStateTransition( + from state: NIOHTTP2StreamState? = nil, + file: String = #fileID, + line: UInt = #line + ) -> BadStreamStateTransition { + BadStreamStateTransition(from: state, file: file, line: line) } /// Creates an ``InvalidFlowControlWindowSize`` error with appropriate source context. @@ -80,8 +93,13 @@ public enum NIOHTTP2Errors { /// - currentWindowSize: The current size of the stream flow control window /// - file: Source file of the caller. /// - line: Source line number of the caller. - public static func invalidFlowControlWindowSize(delta: Int, currentWindowSize: Int, file: String = #fileID, line: UInt = #line) -> InvalidFlowControlWindowSize { - return InvalidFlowControlWindowSize(delta: delta, currentWindowSize: currentWindowSize, file: file, line: line) + public static func invalidFlowControlWindowSize( + delta: Int, + currentWindowSize: Int, + file: String = #fileID, + line: UInt = #line + ) -> InvalidFlowControlWindowSize { + InvalidFlowControlWindowSize(delta: delta, currentWindowSize: currentWindowSize, file: file, line: line) } /// Creates a ``FlowControlViolation`` error with appropriate source context. @@ -90,7 +108,7 @@ public enum NIOHTTP2Errors { /// - file: Source file of the caller. /// - line: Source line number of the caller. public static func flowControlViolation(file: String = #fileID, line: UInt = #line) -> FlowControlViolation { - return FlowControlViolation(file: file, line: line) + FlowControlViolation(file: file, line: line) } /// Creates an ``InvalidSetting`` error with appropriate source context. @@ -99,8 +117,12 @@ public enum NIOHTTP2Errors { /// - setting: The invalid setting in question /// - file: Source file of the caller. /// - line: Source line number of the caller. - public static func invalidSetting(setting: HTTP2Setting, file: String = #fileID, line: UInt = #line) -> InvalidSetting { - return InvalidSetting(setting: setting, file: file, line: line) + public static func invalidSetting( + setting: HTTP2Setting, + file: String = #fileID, + line: UInt = #line + ) -> InvalidSetting { + InvalidSetting(setting: setting, file: file, line: line) } /// Creates an ``IOOnClosedConnection`` error with appropriate source context. @@ -109,7 +131,7 @@ public enum NIOHTTP2Errors { /// - file: Source file of the caller. /// - line: Source line number of the caller. public static func ioOnClosedConnection(file: String = #fileID, line: UInt = #line) -> IOOnClosedConnection { - return IOOnClosedConnection(file: file, line: line) + IOOnClosedConnection(file: file, line: line) } /// Creates a ``ReceivedBadSettings`` error with appropriate source context. @@ -118,7 +140,7 @@ public enum NIOHTTP2Errors { /// - file: Source file of the caller. /// - line: Source line number of the caller. public static func receivedBadSettings(file: String = #fileID, line: UInt = #line) -> ReceivedBadSettings { - return ReceivedBadSettings(file: file, line: line) + ReceivedBadSettings(file: file, line: line) } /// Creates a ``MaxStreamsViolation`` error with appropriate source context. @@ -127,7 +149,7 @@ public enum NIOHTTP2Errors { /// - file: Source file of the caller. /// - line: Source line number of the caller. public static func maxStreamsViolation(file: String = #fileID, line: UInt = #line) -> MaxStreamsViolation { - return MaxStreamsViolation(file: file, line: line) + MaxStreamsViolation(file: file, line: line) } /// Creates a ``StreamIDTooSmall`` error with appropriate source context. @@ -136,7 +158,7 @@ public enum NIOHTTP2Errors { /// - file: Source file of the caller. /// - line: Source line number of the caller. public static func streamIDTooSmall(file: String = #fileID, line: UInt = #line) -> StreamIDTooSmall { - return StreamIDTooSmall(file: file, line: line) + StreamIDTooSmall(file: file, line: line) } /// Creates a ``MissingPreface`` error with appropriate source context. @@ -145,7 +167,7 @@ public enum NIOHTTP2Errors { /// - file: Source file of the caller. /// - line: Source line number of the caller. public static func missingPreface(file: String = #fileID, line: UInt = #line) -> MissingPreface { - return MissingPreface(file: file, line: line) + MissingPreface(file: file, line: line) } /// Creates a ``CreatedStreamAfterGoaway`` error with appropriate source context. @@ -153,8 +175,9 @@ public enum NIOHTTP2Errors { /// - Parameters: /// - file: Source file of the caller. /// - line: Source line number of the caller. - public static func createdStreamAfterGoaway(file: String = #fileID, line: UInt = #line) -> CreatedStreamAfterGoaway { - return CreatedStreamAfterGoaway(file: file, line: line) + public static func createdStreamAfterGoaway(file: String = #fileID, line: UInt = #line) -> CreatedStreamAfterGoaway + { + CreatedStreamAfterGoaway(file: file, line: line) } /// Creates a ``InvalidStreamIDForPeer`` error with appropriate source context. @@ -163,7 +186,7 @@ public enum NIOHTTP2Errors { /// - file: Source file of the caller. /// - line: Source line number of the caller. public static func invalidStreamIDForPeer(file: String = #fileID, line: UInt = #line) -> InvalidStreamIDForPeer { - return InvalidStreamIDForPeer(file: file, line: line) + InvalidStreamIDForPeer(file: file, line: line) } /// Creates a ``RaisedGoawayLastStreamID`` error with appropriate source context. @@ -171,8 +194,9 @@ public enum NIOHTTP2Errors { /// - Parameters: /// - file: Source file of the caller. /// - line: Source line number of the caller. - public static func raisedGoawayLastStreamID(file: String = #fileID, line: UInt = #line) -> RaisedGoawayLastStreamID { - return RaisedGoawayLastStreamID(file: file, line: line) + public static func raisedGoawayLastStreamID(file: String = #fileID, line: UInt = #line) -> RaisedGoawayLastStreamID + { + RaisedGoawayLastStreamID(file: file, line: line) } /// Creates a ``InvalidWindowIncrementSize`` error with appropriate source context. @@ -180,8 +204,11 @@ public enum NIOHTTP2Errors { /// - Parameters: /// - file: Source file of the caller. /// - line: Source line number of the caller. - public static func invalidWindowIncrementSize(file: String = #fileID, line: UInt = #line) -> InvalidWindowIncrementSize { - return InvalidWindowIncrementSize(file: file, line: line) + public static func invalidWindowIncrementSize( + file: String = #fileID, + line: UInt = #line + ) -> InvalidWindowIncrementSize { + InvalidWindowIncrementSize(file: file, line: line) } /// Creates a ``PushInViolationOfSetting`` error with appropriate source context. @@ -189,8 +216,9 @@ public enum NIOHTTP2Errors { /// - Parameters: /// - file: Source file of the caller. /// - line: Source line number of the caller. - public static func pushInViolationOfSetting(file: String = #fileID, line: UInt = #line) -> PushInViolationOfSetting { - return PushInViolationOfSetting(file: file, line: line) + public static func pushInViolationOfSetting(file: String = #fileID, line: UInt = #line) -> PushInViolationOfSetting + { + PushInViolationOfSetting(file: file, line: line) } /// Creates a ``Unsupported`` error with appropriate source context. @@ -200,7 +228,7 @@ public enum NIOHTTP2Errors { /// - file: Source file of the caller. /// - line: Source line number of the caller. public static func unsupported(info: String, file: String = #fileID, line: UInt = #line) -> Unsupported { - return Unsupported(info: info, file: file, line: line) + Unsupported(info: info, file: file, line: line) } /// Creates a ``UnableToSerializeFrame`` error with appropriate source context. @@ -209,7 +237,7 @@ public enum NIOHTTP2Errors { /// - file: Source file of the caller. /// - line: Source line number of the caller. public static func unableToSerializeFrame(file: String = #fileID, line: UInt = #line) -> UnableToSerializeFrame { - return UnableToSerializeFrame(file: file, line: line) + UnableToSerializeFrame(file: file, line: line) } /// Creates a ``UnableToParseFrame`` error with appropriate source context. @@ -218,7 +246,7 @@ public enum NIOHTTP2Errors { /// - file: Source file of the caller. /// - line: Source line number of the caller. public static func unableToParseFrame(file: String = #fileID, line: UInt = #line) -> UnableToParseFrame { - return UnableToParseFrame(file: file, line: line) + UnableToParseFrame(file: file, line: line) } /// Creates a ``MissingPseudoHeader`` error with appropriate source context. @@ -227,8 +255,12 @@ public enum NIOHTTP2Errors { /// - name: The name of the pseudo-header that was missing from the header block. /// - file: Source file of the caller. /// - line: Source line number of the caller. - public static func missingPseudoHeader(_ name: String, file: String = #fileID, line: UInt = #line) -> MissingPseudoHeader { - return MissingPseudoHeader(name, file: file, line: line) + public static func missingPseudoHeader( + _ name: String, + file: String = #fileID, + line: UInt = #line + ) -> MissingPseudoHeader { + MissingPseudoHeader(name, file: file, line: line) } /// Creates a ``DuplicatePseudoHeader`` error with appropriate source context. @@ -237,8 +269,12 @@ public enum NIOHTTP2Errors { /// - name: The name of the pseudo-header that was duplicated within the header block. /// - file: Source file of the caller. /// - line: Source line number of the caller. - public static func duplicatePseudoHeader(_ name: String, file: String = #fileID, line: UInt = #line) -> DuplicatePseudoHeader { - return DuplicatePseudoHeader(name, file: file, line: line) + public static func duplicatePseudoHeader( + _ name: String, + file: String = #fileID, + line: UInt = #line + ) -> DuplicatePseudoHeader { + DuplicatePseudoHeader(name, file: file, line: line) } /// Creates a ``PseudoHeaderAfterRegularHeader`` error with appropriate source context. @@ -247,8 +283,12 @@ public enum NIOHTTP2Errors { /// - name: The name of the pseudo-header that appeared after a regular header in the header block. /// - file: Source file of the caller. /// - line: Source line number of the caller. - public static func pseudoHeaderAfterRegularHeader(_ name: String, file: String = #fileID, line: UInt = #line) -> PseudoHeaderAfterRegularHeader { - return PseudoHeaderAfterRegularHeader(name, file: file, line: line) + public static func pseudoHeaderAfterRegularHeader( + _ name: String, + file: String = #fileID, + line: UInt = #line + ) -> PseudoHeaderAfterRegularHeader { + PseudoHeaderAfterRegularHeader(name, file: file, line: line) } /// Creates a ``UnknownPseudoHeader`` error with appropriate source context. @@ -257,8 +297,12 @@ public enum NIOHTTP2Errors { /// - name: The name of the pseudo-header that was not recognised by ``NIOHTTP2``. /// - file: Source file of the caller. /// - line: Source line number of the caller. - public static func unknownPseudoHeader(_ name: String, file: String = #fileID, line: UInt = #line) -> UnknownPseudoHeader { - return UnknownPseudoHeader(name, file: file, line: line) + public static func unknownPseudoHeader( + _ name: String, + file: String = #fileID, + line: UInt = #line + ) -> UnknownPseudoHeader { + UnknownPseudoHeader(name, file: file, line: line) } /// Creates a ``UnsupportedPseudoHeader`` with with appropriate source context. @@ -267,8 +311,12 @@ public enum NIOHTTP2Errors { /// - name: The name of the pseudo-header that was not supported by ``NIOHTTP2``. /// - file: Source file of the caller. /// - line: Source line number of the caller. - public static func unsupportedPseudoHeader(_ name: String, file: String = #fileID, line: UInt = #line) -> UnsupportedPseudoHeader { - return UnsupportedPseudoHeader(name, file: file, line: line) + public static func unsupportedPseudoHeader( + _ name: String, + file: String = #fileID, + line: UInt = #line + ) -> UnsupportedPseudoHeader { + UnsupportedPseudoHeader(name, file: file, line: line) } /// Creates a ``InvalidPseudoHeaders`` error with appropriate source context. @@ -277,8 +325,12 @@ public enum NIOHTTP2Errors { /// - block: The block of `HPACKHeaders` that contain the invalid pseudo headers. /// - file: Source file of the caller. /// - line: Source line number of the caller. - public static func invalidPseudoHeaders(_ block: HPACKHeaders, file: String = #fileID, line: UInt = #line) -> InvalidPseudoHeaders { - return InvalidPseudoHeaders(block, file: file, line: line) + public static func invalidPseudoHeaders( + _ block: HPACKHeaders, + file: String = #fileID, + line: UInt = #line + ) -> InvalidPseudoHeaders { + InvalidPseudoHeaders(block, file: file, line: line) } /// Creates a ``MissingHostHeader`` error with appropriate source context. @@ -287,7 +339,7 @@ public enum NIOHTTP2Errors { /// - file: Source file of the caller. /// - line: Source line number of the caller. public static func missingHostHeader(file: String = #fileID, line: UInt = #line) -> MissingHostHeader { - return MissingHostHeader(file: file, line: line) + MissingHostHeader(file: file, line: line) } /// Creates a ``DuplicateHostHeader`` error with appropriate source context. @@ -296,7 +348,7 @@ public enum NIOHTTP2Errors { /// - file: Source file of the caller. /// - line: Source line number of the caller. public static func duplicateHostHeader(file: String = #fileID, line: UInt = #line) -> DuplicateHostHeader { - return DuplicateHostHeader(file: file, line: line) + DuplicateHostHeader(file: file, line: line) } /// Creates a ``EmptyPathHeader`` error with appropriate source context. @@ -305,7 +357,7 @@ public enum NIOHTTP2Errors { /// - file: Source file of the caller. /// - line: Source line number of the caller. public static func emptyPathHeader(file: String = #fileID, line: UInt = #line) -> EmptyPathHeader { - return EmptyPathHeader(file: file, line: line) + EmptyPathHeader(file: file, line: line) } /// Creates a ``InvalidStatusValue`` error with appropriate source context. @@ -314,8 +366,12 @@ public enum NIOHTTP2Errors { /// - value: The value of the `:status` header that is invalid. /// - file: Source file of the caller. /// - line: Source line number of the caller. - public static func invalidStatusValue(_ value: String, file: String = #fileID, line: UInt = #line) -> InvalidStatusValue { - return InvalidStatusValue(value, file: file, line: line) + public static func invalidStatusValue( + _ value: String, + file: String = #fileID, + line: UInt = #line + ) -> InvalidStatusValue { + InvalidStatusValue(value, file: file, line: line) } /// Creates a ``PriorityCycle`` error with appropriate source context. @@ -324,8 +380,12 @@ public enum NIOHTTP2Errors { /// - streamID: The ``HTTP2StreamID`` representing the stream that created the priority cycle. /// - file: Source file of the caller. /// - line: Source line number of the caller. - public static func priorityCycle(streamID: HTTP2StreamID, file: String = #fileID, line: UInt = #line) -> PriorityCycle { - return PriorityCycle(streamID: streamID, file: file, line: line) + public static func priorityCycle( + streamID: HTTP2StreamID, + file: String = #fileID, + line: UInt = #line + ) -> PriorityCycle { + PriorityCycle(streamID: streamID, file: file, line: line) } /// Creates a ``TrailersWithoutEndStream`` error with appropriate source context. @@ -334,8 +394,12 @@ public enum NIOHTTP2Errors { /// - streamID: The ``HTTP2StreamID`` on which the `HEADERS` frame without `END_STREAM` was received. /// - file: Source file of the caller. /// - line: Source line number of the caller. - public static func trailersWithoutEndStream(streamID: HTTP2StreamID, file: String = #fileID, line: UInt = #line) -> TrailersWithoutEndStream { - return TrailersWithoutEndStream(streamID: streamID, file: file, line: line) + public static func trailersWithoutEndStream( + streamID: HTTP2StreamID, + file: String = #fileID, + line: UInt = #line + ) -> TrailersWithoutEndStream { + TrailersWithoutEndStream(streamID: streamID, file: file, line: line) } /// Creates a ``InvalidHTTP2HeaderFieldName`` error with appropriate source context. @@ -344,8 +408,12 @@ public enum NIOHTTP2Errors { /// - fieldName: The invalid HTTP/2 header field name /// - file: Source file of the caller. /// - line: Source line number of the caller. - public static func invalidHTTP2HeaderFieldName(_ fieldName: String, file: String = #fileID, line: UInt = #line) -> InvalidHTTP2HeaderFieldName { - return InvalidHTTP2HeaderFieldName(fieldName, file: file, line: line) + public static func invalidHTTP2HeaderFieldName( + _ fieldName: String, + file: String = #fileID, + line: UInt = #line + ) -> InvalidHTTP2HeaderFieldName { + InvalidHTTP2HeaderFieldName(fieldName, file: file, line: line) } /// Creates a ``ForbiddenHeaderField`` error with appropriate source context. @@ -355,8 +423,13 @@ public enum NIOHTTP2Errors { /// - value: The field value for the forbidden header field /// - file: Source file of the caller. /// - line: Source line number of the caller. - public static func forbiddenHeaderField(name: String, value: String, file: String = #fileID, line: UInt = #line) -> ForbiddenHeaderField { - return ForbiddenHeaderField(name: name, value: value, file: file, line: line) + public static func forbiddenHeaderField( + name: String, + value: String, + file: String = #fileID, + line: UInt = #line + ) -> ForbiddenHeaderField { + ForbiddenHeaderField(name: name, value: value, file: file, line: line) } /// Creates a ``ContentLengthViolated`` error with appropriate source context. @@ -365,7 +438,7 @@ public enum NIOHTTP2Errors { /// - file: Source file of the caller. /// - line: Source line number of the caller. public static func contentLengthViolated(file: String = #fileID, line: UInt = #line) -> ContentLengthViolated { - return ContentLengthViolated(file: file, line: line) + ContentLengthViolated(file: file, line: line) } /// Creates a ``ContentLengthHeadersMismatch`` error with appropriate source context. @@ -373,8 +446,11 @@ public enum NIOHTTP2Errors { /// - Parameters: /// - file: Source file of the caller. /// - line: Source line number of the caller. - public static func contentLengthHeadersMismatch(file: String = #fileID, line: UInt = #line) -> ContentLengthHeadersMismatch { - return ContentLengthHeadersMismatch(file: file, line: line) + public static func contentLengthHeadersMismatch( + file: String = #fileID, + line: UInt = #line + ) -> ContentLengthHeadersMismatch { + ContentLengthHeadersMismatch(file: file, line: line) } /// Creates a ``ContentLengthHeaderNegative`` error with appropriate source context. @@ -382,8 +458,11 @@ public enum NIOHTTP2Errors { /// - Parameters: /// - file: Source file of the caller. /// - line: Source line number of the caller. - public static func contentLengthHeaderNegative(file: String = #fileID, line: UInt = #line) -> ContentLengthHeaderNegative { - return ContentLengthHeaderNegative(file: file, line: line) + public static func contentLengthHeaderNegative( + file: String = #fileID, + line: UInt = #line + ) -> ContentLengthHeaderNegative { + ContentLengthHeaderNegative(file: file, line: line) } /// Creates a ``ContentLengthHeaderMalformedValue`` error with appropriate source context. @@ -391,8 +470,11 @@ public enum NIOHTTP2Errors { /// - Parameters: /// - file: Source file of the caller. /// - line: Source line number of the caller. - public static func contentLengthHeaderMalformedValue(file: String = #fileID, line: UInt = #line) -> ContentLengthHeaderMalformedValue { - return ContentLengthHeaderMalformedValue(file: file, line: line) + public static func contentLengthHeaderMalformedValue( + file: String = #fileID, + line: UInt = #line + ) -> ContentLengthHeaderMalformedValue { + ContentLengthHeaderMalformedValue(file: file, line: line) } /// Creates a ``ExcessiveEmptyDataFrames`` error with appropriate source context. @@ -400,8 +482,9 @@ public enum NIOHTTP2Errors { /// - Parameters: /// - file: Source file of the caller. /// - line: Source line number of the caller. - public static func excessiveEmptyDataFrames(file: String = #fileID, line: UInt = #line) -> ExcessiveEmptyDataFrames { - return ExcessiveEmptyDataFrames(file: file, line: line) + public static func excessiveEmptyDataFrames(file: String = #fileID, line: UInt = #line) -> ExcessiveEmptyDataFrames + { + ExcessiveEmptyDataFrames(file: file, line: line) } /// Creates a ``ExcessivelyLargeHeaderBlock`` error with appropriate source context. @@ -409,8 +492,11 @@ public enum NIOHTTP2Errors { /// - Parameters: /// - file: Source file of the caller. /// - line: Source line number of the caller. - public static func excessivelyLargeHeaderBlock(file: String = #fileID, line: UInt = #line) -> ExcessivelyLargeHeaderBlock { - return ExcessivelyLargeHeaderBlock(file: file, line: line) + public static func excessivelyLargeHeaderBlock( + file: String = #fileID, + line: UInt = #line + ) -> ExcessivelyLargeHeaderBlock { + ExcessivelyLargeHeaderBlock(file: file, line: line) } /// Creates a ``NoStreamIDAvailable`` error with appropriate source context. @@ -419,7 +505,7 @@ public enum NIOHTTP2Errors { /// - file: Source file of the caller. /// - line: Source line number of the caller. public static func noStreamIDAvailable(file: String = #fileID, line: UInt = #line) -> NoStreamIDAvailable { - return NoStreamIDAvailable(file: file, line: line) + NoStreamIDAvailable(file: file, line: line) } /// Creates a ``MissingMultiplexer`` error with appropriate source context. @@ -428,7 +514,7 @@ public enum NIOHTTP2Errors { /// - file: Source file of the caller. /// - line: Source line number of the caller. public static func missingMultiplexer(file: String = #fileID, line: UInt = #line) -> MissingMultiplexer { - return MissingMultiplexer(file: file, line: line) + MissingMultiplexer(file: file, line: line) } /// Creates a ``ExcessiveRSTFrames`` error with appropriate source context. @@ -437,7 +523,7 @@ public enum NIOHTTP2Errors { /// - file: Source file of the caller. /// - line: Source line number of the caller. public static func excessiveRSTFrames(file: String = #fileID, line: UInt = #line) -> ExcessiveRSTFrames { - return ExcessiveRSTFrames(file: file, line: line) + ExcessiveRSTFrames(file: file, line: line) } /// Creates an ``ExcessiveContinuationFrames`` error with appropriate source context. @@ -445,8 +531,11 @@ public enum NIOHTTP2Errors { /// - Parameters: /// - file: Source file of the caller. /// - line: Source line number of the caller. - public static func excessiveContinuationFrames(file: String = #fileID, line: UInt = #line) -> ExcessiveContinuationFrames { - return ExcessiveContinuationFrames(file: file, line: line) + public static func excessiveContinuationFrames( + file: String = #fileID, + line: UInt = #line + ) -> ExcessiveContinuationFrames { + ExcessiveContinuationFrames(file: file, line: line) } /// Creates a ``StreamError`` error with appropriate source context. @@ -455,7 +544,7 @@ public enum NIOHTTP2Errors { /// - streamID: The ``HTTP2StreamID`` on which this error was triggered /// - baseError: The underlying `Error` that was thrown. public static func streamError(streamID: HTTP2StreamID, baseError: Error) -> StreamError { - return StreamError(streamID: streamID, baseError: baseError) + StreamError(streamID: streamID, baseError: baseError) } /// The outbound frame buffers have become filled, and it is not possible to buffer @@ -468,7 +557,7 @@ public enum NIOHTTP2Errors { /// The location where the error was thrown. public var location: String { - return _location(file: self.file, line: self.line) + _location(file: self.file, line: self.line) } @available(*, deprecated, renamed: "excessiveOutboundFrameBuffering") @@ -481,8 +570,8 @@ public enum NIOHTTP2Errors { self.line = line } - public static func ==(lhs: ExcessiveOutboundFrameBuffering, rhs: ExcessiveOutboundFrameBuffering) -> Bool { - return true + public static func == (lhs: ExcessiveOutboundFrameBuffering, rhs: ExcessiveOutboundFrameBuffering) -> Bool { + true } } @@ -494,7 +583,7 @@ public enum NIOHTTP2Errors { /// The location where the error was thrown. public var location: String { - return _location(file: self.file, line: self.line) + _location(file: self.file, line: self.line) } @available(*, deprecated, renamed: "invalidALPNToken") @@ -507,8 +596,8 @@ public enum NIOHTTP2Errors { self.line = line } - public static func ==(lhs: InvalidALPNToken, rhs: InvalidALPNToken) -> Bool { - return true + public static func == (lhs: InvalidALPNToken, rhs: InvalidALPNToken) -> Bool { + true } } @@ -530,8 +619,8 @@ public enum NIOHTTP2Errors { self.location = _location(file: file, line: line) } - public static func ==(lhs: NoSuchStream, rhs: NoSuchStream) -> Bool { - return lhs.streamID == rhs.streamID + public static func == (lhs: NoSuchStream, rhs: NoSuchStream) -> Bool { + lhs.streamID == rhs.streamID } } @@ -557,8 +646,8 @@ public enum NIOHTTP2Errors { self.location = _location(file: file, line: line) } - public static func ==(lhs: StreamClosed, rhs: StreamClosed) -> Bool { - return lhs.streamID == rhs.streamID && lhs.errorCode == rhs.errorCode + public static func == (lhs: StreamClosed, rhs: StreamClosed) -> Bool { + lhs.streamID == rhs.streamID && lhs.errorCode == rhs.errorCode } } @@ -569,7 +658,7 @@ public enum NIOHTTP2Errors { /// The location where the error was thrown. public var location: String { - return _location(file: self.file, line: self.line) + _location(file: self.file, line: self.line) } @available(*, deprecated, renamed: "badClientMagic") @@ -582,8 +671,8 @@ public enum NIOHTTP2Errors { self.line = line } - public static func ==(lhs: BadClientMagic, rhs: BadClientMagic) -> Bool { - return true + public static func == (lhs: BadClientMagic, rhs: BadClientMagic) -> Bool { + true } } @@ -610,8 +699,8 @@ public enum NIOHTTP2Errors { self.init(from: nil, file: #fileID, line: #line) } - public static func ==(lhs: BadStreamStateTransition, rhs: BadStreamStateTransition) -> Bool { - return lhs.fromState == rhs.fromState + public static func == (lhs: BadStreamStateTransition, rhs: BadStreamStateTransition) -> Bool { + lhs.fromState == rhs.fromState } } @@ -636,7 +725,7 @@ public enum NIOHTTP2Errors { var line: UInt var location: String { - return _location(file: self.file, line: self.line) + _location(file: self.file, line: self.line) } init(delta: Int, currentWindowSize: Int, file: String, line: UInt) { @@ -647,18 +736,18 @@ public enum NIOHTTP2Errors { } func copy() -> Storage { - return Storage(delta: self.delta, currentWindowSize: self.currentWindowSize, file: self.file, line: self.line) + Storage(delta: self.delta, currentWindowSize: self.currentWindowSize, file: self.file, line: self.line) } - static func ==(lhs: Storage, rhs: Storage) -> Bool { - return lhs.delta == rhs.delta && lhs.currentWindowSize == rhs.currentWindowSize + static func == (lhs: Storage, rhs: Storage) -> Bool { + lhs.delta == rhs.delta && lhs.currentWindowSize == rhs.currentWindowSize } } /// The delta being applied to the flow control window. public var delta: Int { get { - return self.storage.delta + self.storage.delta } set { self.copyStorageIfNotUniquelyReferenced() @@ -669,7 +758,7 @@ public enum NIOHTTP2Errors { /// The size of the flow control window before the delta was applied. public var currentWindowSize: Int { get { - return self.storage.currentWindowSize + self.storage.currentWindowSize } set { self.copyStorageIfNotUniquelyReferenced() @@ -680,12 +769,12 @@ public enum NIOHTTP2Errors { /// The file and line where the error was created. public var location: String { get { - return self.storage.location + self.storage.location } } public var description: String { - return "InvalidFlowControlWindowSize(delta: \(self.delta), currentWindowSize: \(self.currentWindowSize), location: \(self.location))" + "InvalidFlowControlWindowSize(delta: \(self.delta), currentWindowSize: \(self.currentWindowSize), location: \(self.location))" } @available(*, deprecated, renamed: "invalidFlowControlWindowSize") @@ -705,7 +794,7 @@ public enum NIOHTTP2Errors { /// The location where the error was thrown. public var location: String { - return _location(file: self.file, line: self.line) + _location(file: self.file, line: self.line) } @available(*, deprecated, renamed: "flowControlViolation") @@ -718,8 +807,8 @@ public enum NIOHTTP2Errors { self.line = line } - public static func ==(lhs: FlowControlViolation, rhs: FlowControlViolation) -> Bool { - return true + public static func == (lhs: FlowControlViolation, rhs: FlowControlViolation) -> Bool { + true } } @@ -741,8 +830,8 @@ public enum NIOHTTP2Errors { self.location = _location(file: file, line: line) } - public static func ==(lhs: InvalidSetting, rhs: InvalidSetting) -> Bool { - return lhs.setting == rhs.setting + public static func == (lhs: InvalidSetting, rhs: InvalidSetting) -> Bool { + lhs.setting == rhs.setting } } @@ -753,7 +842,7 @@ public enum NIOHTTP2Errors { /// The location where the error was thrown. public var location: String { - return _location(file: self.file, line: self.line) + _location(file: self.file, line: self.line) } @available(*, deprecated, renamed: "ioOnClosedConnection") @@ -766,8 +855,8 @@ public enum NIOHTTP2Errors { self.line = line } - public static func ==(lhs: IOOnClosedConnection, rhs: IOOnClosedConnection) -> Bool { - return true + public static func == (lhs: IOOnClosedConnection, rhs: IOOnClosedConnection) -> Bool { + true } } @@ -778,7 +867,7 @@ public enum NIOHTTP2Errors { /// The location where the error was thrown. public var location: String { - return _location(file: self.file, line: self.line) + _location(file: self.file, line: self.line) } @available(*, deprecated, renamed: "receivedBadSettings") @@ -791,8 +880,8 @@ public enum NIOHTTP2Errors { self.line = line } - public static func ==(lhs: ReceivedBadSettings, rhs: ReceivedBadSettings) -> Bool { - return true + public static func == (lhs: ReceivedBadSettings, rhs: ReceivedBadSettings) -> Bool { + true } } @@ -803,7 +892,7 @@ public enum NIOHTTP2Errors { /// The location where the error was thrown. public var location: String { - return _location(file: self.file, line: self.line) + _location(file: self.file, line: self.line) } @available(*, deprecated, renamed: "maxStreamsViolation") @@ -816,8 +905,8 @@ public enum NIOHTTP2Errors { self.line = line } - public static func ==(lhs: MaxStreamsViolation, rhs: MaxStreamsViolation) -> Bool { - return true + public static func == (lhs: MaxStreamsViolation, rhs: MaxStreamsViolation) -> Bool { + true } } @@ -828,7 +917,7 @@ public enum NIOHTTP2Errors { /// The location where the error was thrown. public var location: String { - return _location(file: self.file, line: self.line) + _location(file: self.file, line: self.line) } @available(*, deprecated, renamed: "streamIDTooSmall") @@ -841,8 +930,8 @@ public enum NIOHTTP2Errors { self.line = line } - public static func ==(lhs: StreamIDTooSmall, rhs: StreamIDTooSmall) -> Bool { - return true + public static func == (lhs: StreamIDTooSmall, rhs: StreamIDTooSmall) -> Bool { + true } } @@ -853,7 +942,7 @@ public enum NIOHTTP2Errors { /// The location where the error was thrown. public var location: String { - return _location(file: self.file, line: self.line) + _location(file: self.file, line: self.line) } @available(*, deprecated, renamed: "missingPreface") @@ -866,8 +955,8 @@ public enum NIOHTTP2Errors { self.line = line } - public static func ==(lhs: MissingPreface, rhs: MissingPreface) -> Bool { - return true + public static func == (lhs: MissingPreface, rhs: MissingPreface) -> Bool { + true } } @@ -879,7 +968,7 @@ public enum NIOHTTP2Errors { /// The location where the error was thrown. public var location: String { - return _location(file: self.file, line: self.line) + _location(file: self.file, line: self.line) } @available(*, deprecated, renamed: "createdStreamAfterGoaway") @@ -892,8 +981,8 @@ public enum NIOHTTP2Errors { self.line = line } - public static func ==(lhs: CreatedStreamAfterGoaway, rhs: CreatedStreamAfterGoaway) -> Bool { - return true + public static func == (lhs: CreatedStreamAfterGoaway, rhs: CreatedStreamAfterGoaway) -> Bool { + true } } @@ -904,7 +993,7 @@ public enum NIOHTTP2Errors { /// The location where the error was thrown. public var location: String { - return _location(file: self.file, line: self.line) + _location(file: self.file, line: self.line) } @available(*, deprecated, renamed: "invalidStreamIDForPeer") @@ -917,8 +1006,8 @@ public enum NIOHTTP2Errors { self.line = line } - public static func ==(lhs: InvalidStreamIDForPeer, rhs: InvalidStreamIDForPeer) -> Bool { - return true + public static func == (lhs: InvalidStreamIDForPeer, rhs: InvalidStreamIDForPeer) -> Bool { + true } } @@ -929,7 +1018,7 @@ public enum NIOHTTP2Errors { /// The location where the error was thrown. public var location: String { - return _location(file: self.file, line: self.line) + _location(file: self.file, line: self.line) } @available(*, deprecated, renamed: "raisedGoawayLastStreamID") @@ -942,8 +1031,8 @@ public enum NIOHTTP2Errors { self.line = line } - public static func ==(lhs: RaisedGoawayLastStreamID, rhs: RaisedGoawayLastStreamID) -> Bool { - return true + public static func == (lhs: RaisedGoawayLastStreamID, rhs: RaisedGoawayLastStreamID) -> Bool { + true } } @@ -954,7 +1043,7 @@ public enum NIOHTTP2Errors { /// The location where the error was thrown. public var location: String { - return _location(file: self.file, line: self.line) + _location(file: self.file, line: self.line) } @available(*, deprecated, renamed: "invalidWindowIncrementSize") @@ -967,8 +1056,8 @@ public enum NIOHTTP2Errors { self.line = line } - public static func ==(lhs: InvalidWindowIncrementSize, rhs: InvalidWindowIncrementSize) -> Bool { - return true + public static func == (lhs: InvalidWindowIncrementSize, rhs: InvalidWindowIncrementSize) -> Bool { + true } } @@ -979,7 +1068,7 @@ public enum NIOHTTP2Errors { /// The location where the error was thrown. public var location: String { - return _location(file: self.file, line: self.line) + _location(file: self.file, line: self.line) } @available(*, deprecated, renamed: "pushInViolationOfSetting") @@ -992,8 +1081,8 @@ public enum NIOHTTP2Errors { self.line = line } - public static func ==(lhs: PushInViolationOfSetting, rhs: PushInViolationOfSetting) -> Bool { - return true + public static func == (lhs: PushInViolationOfSetting, rhs: PushInViolationOfSetting) -> Bool { + true } } @@ -1012,7 +1101,7 @@ public enum NIOHTTP2Errors { /// A human-readable description of what unsupported feature was used. public var info: String { get { - return self.storage.value + self.storage.value } set { self.copyStorageIfNotUniquelyReferenced() @@ -1023,12 +1112,12 @@ public enum NIOHTTP2Errors { /// The file and line where the error was created. public var location: String { get { - return self.storage.location + self.storage.location } } public var description: String { - return "Unsupported(info: \(self.info), location: \(self.location))" + "Unsupported(info: \(self.info), location: \(self.location))" } @available(*, deprecated, renamed: "unsupported") @@ -1048,7 +1137,7 @@ public enum NIOHTTP2Errors { /// The location where the error was thrown. public var location: String { - return _location(file: self.file, line: self.line) + _location(file: self.file, line: self.line) } @available(*, deprecated, renamed: "unableToSerializeFrame") @@ -1061,8 +1150,8 @@ public enum NIOHTTP2Errors { self.line = line } - public static func ==(lhs: UnableToSerializeFrame, rhs: UnableToSerializeFrame) -> Bool { - return true + public static func == (lhs: UnableToSerializeFrame, rhs: UnableToSerializeFrame) -> Bool { + true } } @@ -1073,7 +1162,7 @@ public enum NIOHTTP2Errors { /// The location where the error was thrown. public var location: String { - return _location(file: self.file, line: self.line) + _location(file: self.file, line: self.line) } @available(*, deprecated, renamed: "unableToParseFrame") @@ -1086,14 +1175,14 @@ public enum NIOHTTP2Errors { self.line = line } - public static func ==(lhs: UnableToParseFrame, rhs: UnableToParseFrame) -> Bool { - return true + public static func == (lhs: UnableToParseFrame, rhs: UnableToParseFrame) -> Bool { + true } } /// A pseudo-header field is missing. public struct MissingPseudoHeader: NIOHTTP2Error, CustomStringConvertible, @unchecked Sendable { - // @unchecked Sendable because access is controlled by getters and copy-on-write setters giving this value semantics + // @unchecked Sendable because access is controlled by getters and copy-on-write setters giving this value semantics private var storage: StringAndLocationStorage @@ -1106,7 +1195,7 @@ public enum NIOHTTP2Errors { /// The name of the missing pseudo-header field public var name: String { get { - return self.storage.value + self.storage.value } set { self.copyStorageIfNotUniquelyReferenced() @@ -1117,12 +1206,12 @@ public enum NIOHTTP2Errors { /// The file and line where the error was created. public var location: String { get { - return self.storage.location + self.storage.location } } public var description: String { - return "MissingPseudoHeader(name: \(self.name), location: \(self.location))" + "MissingPseudoHeader(name: \(self.name), location: \(self.location))" } @available(*, deprecated, renamed: "missingPseudoHeader") @@ -1150,7 +1239,7 @@ public enum NIOHTTP2Errors { /// The name of the pseudo-header field that was duplicated public var name: String { get { - return self.storage.value + self.storage.value } set { self.copyStorageIfNotUniquelyReferenced() @@ -1161,12 +1250,12 @@ public enum NIOHTTP2Errors { /// The file and line where the error was created. public var location: String { get { - return self.storage.location + self.storage.location } } public var description: String { - return "DuplicatePseudoHeader(name: \(self.name), location: \(self.location))" + "DuplicatePseudoHeader(name: \(self.name), location: \(self.location))" } @available(*, deprecated, renamed: "duplicatePseudoHeader") @@ -1193,7 +1282,7 @@ public enum NIOHTTP2Errors { /// The name of the pseudo-header that occurred after the regular header. public var name: String { get { - return self.storage.value + self.storage.value } set { self.copyStorageIfNotUniquelyReferenced() @@ -1204,12 +1293,12 @@ public enum NIOHTTP2Errors { /// The file and line where the error was created. public var location: String { get { - return self.storage.location + self.storage.location } } public var description: String { - return "PseudoHeaderAfterRegularHeader(name: \(self.name), location: \(self.location))" + "PseudoHeaderAfterRegularHeader(name: \(self.name), location: \(self.location))" } @available(*, deprecated, renamed: "pseudoHeaderAfterRegularHeader") @@ -1237,7 +1326,7 @@ public enum NIOHTTP2Errors { /// The name of the unrecognised pseudo-header field. public var name: String { get { - return self.storage.value + self.storage.value } set { self.copyStorageIfNotUniquelyReferenced() @@ -1248,12 +1337,12 @@ public enum NIOHTTP2Errors { /// The file and line where the error was created. public var location: String { get { - return self.storage.location + self.storage.location } } public var description: String { - return "UnknownPseudoHeader(name: \(self.name), location: \(self.location))" + "UnknownPseudoHeader(name: \(self.name), location: \(self.location))" } @available(*, deprecated, renamed: "unknownPseudoHeader") @@ -1281,7 +1370,7 @@ public enum NIOHTTP2Errors { /// The name of the unsupported pseudo-header field. public var name: String { get { - return self.storage.value + self.storage.value } set { self.copyStorageIfNotUniquelyReferenced() @@ -1292,12 +1381,12 @@ public enum NIOHTTP2Errors { /// The file and line where the error was created. public var location: String { get { - return self.storage.location + self.storage.location } } public var description: String { - return "UnsupportedPseudoHeader(name: \(self.name), location: \(self.location))" + "UnsupportedPseudoHeader(name: \(self.name), location: \(self.location))" } fileprivate init(_ name: String, file: String, line: UInt) { @@ -1323,8 +1412,8 @@ public enum NIOHTTP2Errors { self.location = _location(file: file, line: line) } - public static func ==(lhs: InvalidPseudoHeaders, rhs: InvalidPseudoHeaders) -> Bool { - return lhs.headerBlock == rhs.headerBlock + public static func == (lhs: InvalidPseudoHeaders, rhs: InvalidPseudoHeaders) -> Bool { + lhs.headerBlock == rhs.headerBlock } } @@ -1335,7 +1424,7 @@ public enum NIOHTTP2Errors { /// The location where the error was thrown. public var location: String { - return _location(file: self.file, line: self.line) + _location(file: self.file, line: self.line) } @available(*, deprecated, renamed: "missingHostHeader") @@ -1348,8 +1437,8 @@ public enum NIOHTTP2Errors { self.line = line } - public static func ==(lhs: MissingHostHeader, rhs: MissingHostHeader) -> Bool { - return true + public static func == (lhs: MissingHostHeader, rhs: MissingHostHeader) -> Bool { + true } } @@ -1360,7 +1449,7 @@ public enum NIOHTTP2Errors { /// The location where the error was thrown. public var location: String { - return _location(file: self.file, line: self.line) + _location(file: self.file, line: self.line) } @available(*, deprecated, renamed: "duplicateHostHeader") @@ -1373,8 +1462,8 @@ public enum NIOHTTP2Errors { self.line = line } - public static func ==(lhs: DuplicateHostHeader, rhs: DuplicateHostHeader) -> Bool { - return true + public static func == (lhs: DuplicateHostHeader, rhs: DuplicateHostHeader) -> Bool { + true } } @@ -1385,7 +1474,7 @@ public enum NIOHTTP2Errors { /// The location where the error was thrown. public var location: String { - return _location(file: self.file, line: self.line) + _location(file: self.file, line: self.line) } @available(*, deprecated, renamed: "emptyPathHeader") @@ -1398,8 +1487,8 @@ public enum NIOHTTP2Errors { self.line = line } - public static func ==(lhs: EmptyPathHeader, rhs: EmptyPathHeader) -> Bool { - return true + public static func == (lhs: EmptyPathHeader, rhs: EmptyPathHeader) -> Bool { + true } } @@ -1418,7 +1507,7 @@ public enum NIOHTTP2Errors { /// The invalid value of the `:status` header. public var value: String { get { - return self.storage.value + self.storage.value } set { self.copyStorageIfNotUniquelyReferenced() @@ -1429,12 +1518,12 @@ public enum NIOHTTP2Errors { /// The file and line where the error was created. public var location: String { get { - return self.storage.location + self.storage.location } } public var description: String { - return "InvalidStatusValue(value: \(self.value), location: \(self.location))" + "InvalidStatusValue(value: \(self.value), location: \(self.location))" } @available(*, deprecated, renamed: "invalidStatusValue") @@ -1465,8 +1554,8 @@ public enum NIOHTTP2Errors { self.location = _location(file: file, line: line) } - public static func ==(lhs: PriorityCycle, rhs: PriorityCycle) -> Bool { - return lhs.streamID == rhs.streamID + public static func == (lhs: PriorityCycle, rhs: PriorityCycle) -> Bool { + lhs.streamID == rhs.streamID } } @@ -1488,8 +1577,8 @@ public enum NIOHTTP2Errors { self.location = _location(file: file, line: line) } - public static func ==(lhs: TrailersWithoutEndStream, rhs: TrailersWithoutEndStream) -> Bool { - return lhs.streamID == rhs.streamID + public static func == (lhs: TrailersWithoutEndStream, rhs: TrailersWithoutEndStream) -> Bool { + lhs.streamID == rhs.streamID } } @@ -1508,7 +1597,7 @@ public enum NIOHTTP2Errors { /// The name of the invalid header field. public var fieldName: String { get { - return self.storage.value + self.storage.value } set { self.copyStorageIfNotUniquelyReferenced() @@ -1519,12 +1608,12 @@ public enum NIOHTTP2Errors { /// The file and line where the error was created. public var location: String { get { - return self.storage.location + self.storage.location } } public var description: String { - return "InvalidHTTP2HeaderFieldName(fieldName: \(self.fieldName), location: \(self.location))" + "InvalidHTTP2HeaderFieldName(fieldName: \(self.fieldName), location: \(self.location))" } @available(*, deprecated, renamed: "invalidHTTP2HeaderFieldName") @@ -1557,7 +1646,7 @@ public enum NIOHTTP2Errors { var line: UInt var location: String { - return _location(file: self.file, line: self.line) + _location(file: self.file, line: self.line) } init(name: String, value: String, file: String, line: UInt) { @@ -1568,18 +1657,18 @@ public enum NIOHTTP2Errors { } func copy() -> Storage { - return Storage(name: self.name, value: self.value, file: self.file, line: self.line) + Storage(name: self.name, value: self.value, file: self.file, line: self.line) } - static func ==(lhs: Storage, rhs: Storage) -> Bool { - return lhs.name == rhs.name && lhs.value == rhs.value + static func == (lhs: Storage, rhs: Storage) -> Bool { + lhs.name == rhs.name && lhs.value == rhs.value } } /// The name of the forbidden header field. public var name: String { get { - return self.storage.name + self.storage.name } set { self.copyStorageIfNotUniquelyReferenced() @@ -1590,7 +1679,7 @@ public enum NIOHTTP2Errors { /// The value of the forbidden header field. public var value: String { get { - return self.storage.value + self.storage.value } set { self.copyStorageIfNotUniquelyReferenced() @@ -1601,12 +1690,12 @@ public enum NIOHTTP2Errors { /// The file and line where the error was created. public var location: String { get { - return self.storage.location + self.storage.location } } public var description: String { - return "ForbiddenHeaderField(name: \(self.name), value: \(self.value), location: \(self.location))" + "ForbiddenHeaderField(name: \(self.name), value: \(self.value), location: \(self.location))" } @available(*, deprecated, renamed: "forbiddenHeaderField") @@ -1626,7 +1715,7 @@ public enum NIOHTTP2Errors { /// The location where the error was thrown. public var location: String { - return _location(file: self.file, line: self.line) + _location(file: self.file, line: self.line) } @available(*, deprecated, renamed: "contentLengthViolated") @@ -1639,8 +1728,8 @@ public enum NIOHTTP2Errors { self.line = line } - public static func ==(lhs: ContentLengthViolated, rhs: ContentLengthViolated) -> Bool { - return true + public static func == (lhs: ContentLengthViolated, rhs: ContentLengthViolated) -> Bool { + true } } @@ -1651,7 +1740,7 @@ public enum NIOHTTP2Errors { /// The location where the error was thrown. public var location: String { - return _location(file: self.file, line: self.line) + _location(file: self.file, line: self.line) } fileprivate init(file: String, line: UInt) { @@ -1659,8 +1748,8 @@ public enum NIOHTTP2Errors { self.line = line } - public static func ==(lhs: ContentLengthHeadersMismatch, rhs: ContentLengthHeadersMismatch) -> Bool { - return true + public static func == (lhs: ContentLengthHeadersMismatch, rhs: ContentLengthHeadersMismatch) -> Bool { + true } } @@ -1671,7 +1760,7 @@ public enum NIOHTTP2Errors { /// The location where the error was thrown. public var location: String { - return _location(file: self.file, line: self.line) + _location(file: self.file, line: self.line) } fileprivate init(file: String, line: UInt) { @@ -1679,8 +1768,8 @@ public enum NIOHTTP2Errors { self.line = line } - public static func ==(lhs: ContentLengthHeaderNegative, rhs: ContentLengthHeaderNegative) -> Bool { - return true + public static func == (lhs: ContentLengthHeaderNegative, rhs: ContentLengthHeaderNegative) -> Bool { + true } } @@ -1692,7 +1781,7 @@ public enum NIOHTTP2Errors { /// The location where the error was thrown. public var location: String { - return _location(file: self.file, line: self.line) + _location(file: self.file, line: self.line) } fileprivate init(file: String, line: UInt) { @@ -1700,8 +1789,8 @@ public enum NIOHTTP2Errors { self.line = line } - public static func ==(lhs: ContentLengthHeaderMalformedValue, rhs: ContentLengthHeaderMalformedValue) -> Bool { - return true + public static func == (lhs: ContentLengthHeaderMalformedValue, rhs: ContentLengthHeaderMalformedValue) -> Bool { + true } } @@ -1713,7 +1802,7 @@ public enum NIOHTTP2Errors { /// The location where the error was thrown. public var location: String { - return _location(file: self.file, line: self.line) + _location(file: self.file, line: self.line) } @available(*, deprecated, renamed: "excessiveEmptyDataFrames") @@ -1726,8 +1815,8 @@ public enum NIOHTTP2Errors { self.line = line } - public static func ==(lhs: ExcessiveEmptyDataFrames, rhs: ExcessiveEmptyDataFrames) -> Bool { - return true + public static func == (lhs: ExcessiveEmptyDataFrames, rhs: ExcessiveEmptyDataFrames) -> Bool { + true } } @@ -1738,7 +1827,7 @@ public enum NIOHTTP2Errors { /// The location where the error was thrown. public var location: String { - return _location(file: self.file, line: self.line) + _location(file: self.file, line: self.line) } @available(*, deprecated, renamed: "excessivelyLargeHeaderBlock") @@ -1751,8 +1840,8 @@ public enum NIOHTTP2Errors { self.line = line } - public static func ==(lhs: ExcessivelyLargeHeaderBlock, rhs: ExcessivelyLargeHeaderBlock) -> Bool { - return true + public static func == (lhs: ExcessivelyLargeHeaderBlock, rhs: ExcessivelyLargeHeaderBlock) -> Bool { + true } } @@ -1763,7 +1852,7 @@ public enum NIOHTTP2Errors { /// The location where the error was thrown. public var location: String { - return _location(file: self.file, line: self.line) + _location(file: self.file, line: self.line) } @available(*, deprecated, renamed: "noStreamIDAvailable") @@ -1776,8 +1865,8 @@ public enum NIOHTTP2Errors { self.line = line } - public static func ==(lhs: NoStreamIDAvailable, rhs: NoStreamIDAvailable) -> Bool { - return true + public static func == (lhs: NoStreamIDAvailable, rhs: NoStreamIDAvailable) -> Bool { + true } } @@ -1800,7 +1889,7 @@ public enum NIOHTTP2Errors { } func copy() -> Storage { - return Storage( + Storage( streamID: self.streamID, baseError: self.baseError ) @@ -1818,7 +1907,7 @@ public enum NIOHTTP2Errors { /// The underlying thrown error. public var baseError: Error { get { - return self.storage.baseError + self.storage.baseError } set { self.copyStorageIfNotUniquelyReferenced() @@ -1829,7 +1918,7 @@ public enum NIOHTTP2Errors { /// The ``HTTP2StreamID`` on which the error was thrown. public var streamID: HTTP2StreamID { get { - return self.storage.streamID + self.storage.streamID } set { self.copyStorageIfNotUniquelyReferenced() @@ -1838,7 +1927,7 @@ public enum NIOHTTP2Errors { } public var description: String { - return "StreamError(streamID: \(self.streamID), baseError: \(self.baseError))" + "StreamError(streamID: \(self.streamID), baseError: \(self.baseError))" } fileprivate init(streamID: HTTP2StreamID, baseError: Error) { @@ -1872,7 +1961,7 @@ public enum NIOHTTP2Errors { /// The location where the error was thrown. public var location: String { - return _location(file: self.file, line: self.line) + _location(file: self.file, line: self.line) } fileprivate init(file: String, line: UInt) { @@ -1880,12 +1969,11 @@ public enum NIOHTTP2Errors { self.line = line } - public static func ==(lhs: Self, rhs: Self) -> Bool { - return true + public static func == (lhs: Self, rhs: Self) -> Bool { + true } } - /// The client has issued RST frames at an excessive rate resulting in the connection being defensively closed. public struct ExcessiveRSTFrames: NIOHTTP2Error { private let file: String @@ -1893,7 +1981,7 @@ public enum NIOHTTP2Errors { /// The location where the error was thrown. public var location: String { - return _location(file: self.file, line: self.line) + _location(file: self.file, line: self.line) } fileprivate init(file: String, line: UInt) { @@ -1901,8 +1989,8 @@ public enum NIOHTTP2Errors { self.line = line } - public static func ==(lhs: Self, rhs: Self) -> Bool { - return true + public static func == (lhs: Self, rhs: Self) -> Bool { + true } } @@ -1913,7 +2001,7 @@ public enum NIOHTTP2Errors { /// The location where the error was thrown. public var location: String { - return _location(file: self.file, line: self.line) + _location(file: self.file, line: self.line) } fileprivate init(file: String, line: UInt) { @@ -1921,13 +2009,12 @@ public enum NIOHTTP2Errors { self.line = line } - public static func ==(lhs: Self, rhs: Self) -> Bool { - return true + public static func == (lhs: Self, rhs: Self) -> Bool { + true } } } - /// This enum covers errors that are thrown internally for messaging reasons. These should /// not leak. internal enum InternalError: Error { @@ -1943,10 +2030,10 @@ internal enum InternalError: Error { } } -extension InternalError: Hashable { } +extension InternalError: Hashable {} private func _location(file: String, line: UInt) -> String { - return "\(file):\(line)" + "\(file):\(line)" } private final class StringAndLocationStorage: Equatable { @@ -1955,7 +2042,7 @@ private final class StringAndLocationStorage: Equatable { var line: UInt var location: String { - return _location(file: self.file, line: self.line) + _location(file: self.file, line: self.line) } init(_ value: String, file: String, line: UInt) { @@ -1965,11 +2052,11 @@ private final class StringAndLocationStorage: Equatable { } func copy() -> StringAndLocationStorage { - return StringAndLocationStorage(self.value, file: self.file, line: self.line) + StringAndLocationStorage(self.value, file: self.file, line: self.line) } - static func ==(lhs: StringAndLocationStorage, rhs: StringAndLocationStorage) -> Bool { + static func == (lhs: StringAndLocationStorage, rhs: StringAndLocationStorage) -> Bool { // Only compare the value. The 'file' is not relevant here. - return lhs.value == rhs.value + lhs.value == rhs.value } } diff --git a/Sources/NIOHTTP2/HTTP2ErrorCode.swift b/Sources/NIOHTTP2/HTTP2ErrorCode.swift index e319b7f..175c092 100644 --- a/Sources/NIOHTTP2/HTTP2ErrorCode.swift +++ b/Sources/NIOHTTP2/HTTP2ErrorCode.swift @@ -22,7 +22,7 @@ public struct HTTP2ErrorCode: Sendable { /// The underlying network representation of the error code. public var networkCode: Int { get { - return Int(self._networkCode) + Int(self._networkCode) } set { self._networkCode = UInt32(newValue) @@ -96,9 +96,9 @@ public struct HTTP2ErrorCode: Sendable { public static let http11Required = HTTP2ErrorCode(networkCode: 0x0d) } -extension HTTP2ErrorCode: Equatable { } +extension HTTP2ErrorCode: Equatable {} -extension HTTP2ErrorCode: Hashable { } +extension HTTP2ErrorCode: Hashable {} extension HTTP2ErrorCode: CustomDebugStringConvertible { public var debugDescription: String { @@ -140,28 +140,28 @@ extension HTTP2ErrorCode: CustomDebugStringConvertible { } } -public extension UInt32 { +extension UInt32 { /// Create a 32-bit integer corresponding to the given ``HTTP2ErrorCode``. - init(http2ErrorCode code: HTTP2ErrorCode) { + public init(http2ErrorCode code: HTTP2ErrorCode) { self = code._networkCode } } -public extension Int { +extension Int { /// Create an integer corresponding to the given ``HTTP2ErrorCode``. - init(http2ErrorCode code: HTTP2ErrorCode) { + public init(http2ErrorCode code: HTTP2ErrorCode) { self = code.networkCode } } -public extension ByteBuffer { +extension ByteBuffer { /// Serializes a ``HTTP2ErrorCode`` into a `ByteBuffer` in the appropriate endianness /// for use in HTTP/2. /// /// - Parameters: /// - code: The ``HTTP2ErrorCode`` to serialize. /// - Returns: The number of bytes written. - mutating func write(http2ErrorCode code: HTTP2ErrorCode) -> Int { - return self.writeInteger(UInt32(http2ErrorCode: code)) + public mutating func write(http2ErrorCode code: HTTP2ErrorCode) -> Int { + self.writeInteger(UInt32(http2ErrorCode: code)) } } diff --git a/Sources/NIOHTTP2/HTTP2FlowControlWindow.swift b/Sources/NIOHTTP2/HTTP2FlowControlWindow.swift index 80e7a6f..900f011 100644 --- a/Sources/NIOHTTP2/HTTP2FlowControlWindow.swift +++ b/Sources/NIOHTTP2/HTTP2FlowControlWindow.swift @@ -55,16 +55,20 @@ struct HTTP2FlowControlWindow { init(initialValue: Int) { precondition(initialValue >= 0, "Flow control windows may not begin negative") - precondition(initialValue <= HTTP2FlowControlWindow.maxSize, - "Flow control windows may not exceed \(HTTP2FlowControlWindow.maxSize) bytes") + precondition( + initialValue <= HTTP2FlowControlWindow.maxSize, + "Flow control windows may not exceed \(HTTP2FlowControlWindow.maxSize) bytes" + ) self.windowSize = Int32(initialValue) } init(initialValue: Int32) { precondition(initialValue >= 0, "Flow control windows may not begin negative") - precondition(initialValue <= HTTP2FlowControlWindow.maxSize, - "Flow control windows may not exceed \(HTTP2FlowControlWindow.maxSize) bytes") + precondition( + initialValue <= HTTP2FlowControlWindow.maxSize, + "Flow control windows may not exceed \(HTTP2FlowControlWindow.maxSize) bytes" + ) self.windowSize = initialValue } @@ -94,7 +98,10 @@ struct HTTP2FlowControlWindow { // subtraction to avoid integer overflow. Note that if the current window size is negative then all window // update increments are valid. guard (self.windowSize < 0) || (HTTP2FlowControlWindow.maxSize - self.windowSize >= amount) else { - throw NIOHTTP2Errors.invalidFlowControlWindowSize(delta: Int(amount), currentWindowSize: Int(self.windowSize)) + throw NIOHTTP2Errors.invalidFlowControlWindowSize( + delta: Int(amount), + currentWindowSize: Int(self.windowSize) + ) } self.windowSize += Int32(amount) @@ -116,7 +123,10 @@ struct HTTP2FlowControlWindow { assert(amount >= -(Int32.max)) guard (self.windowSize < 0) || (HTTP2FlowControlWindow.maxSize - self.windowSize >= amount) else { - throw NIOHTTP2Errors.invalidFlowControlWindowSize(delta: Int(amount), currentWindowSize: Int(self.windowSize)) + throw NIOHTTP2Errors.invalidFlowControlWindowSize( + delta: Int(amount), + currentWindowSize: Int(self.windowSize) + ) } self.windowSize += amount @@ -146,8 +156,10 @@ extension HTTP2FlowControlWindow: ExpressibleByIntegerLiteral { init(integerLiteral initialValue: Int32) { precondition(initialValue >= 0, "Flow control windows may not begin negative") - precondition(initialValue <= HTTP2FlowControlWindow.maxSize, - "Flow control windows may not exceed \(HTTP2FlowControlWindow.maxSize) bytes") + precondition( + initialValue <= HTTP2FlowControlWindow.maxSize, + "Flow control windows may not exceed \(HTTP2FlowControlWindow.maxSize) bytes" + ) self.windowSize = initialValue } @@ -155,29 +167,29 @@ extension HTTP2FlowControlWindow: ExpressibleByIntegerLiteral { extension HTTP2FlowControlWindow: CustomStringConvertible { var description: String { - return self.windowSize.description + self.windowSize.description } } -extension HTTP2FlowControlWindow: Equatable { } +extension HTTP2FlowControlWindow: Equatable {} -extension HTTP2FlowControlWindow: Hashable { } +extension HTTP2FlowControlWindow: Hashable {} extension HTTP2FlowControlWindow: Comparable { static func < (lhs: HTTP2FlowControlWindow, rhs: HTTP2FlowControlWindow) -> Bool { - return lhs.windowSize < rhs.windowSize + lhs.windowSize < rhs.windowSize } static func > (lhs: HTTP2FlowControlWindow, rhs: HTTP2FlowControlWindow) -> Bool { - return lhs.windowSize > rhs.windowSize + lhs.windowSize > rhs.windowSize } static func <= (lhs: HTTP2FlowControlWindow, rhs: HTTP2FlowControlWindow) -> Bool { - return lhs.windowSize <= rhs.windowSize + lhs.windowSize <= rhs.windowSize } static func >= (lhs: HTTP2FlowControlWindow, rhs: HTTP2FlowControlWindow) -> Bool { - return lhs.windowSize >= rhs.windowSize + lhs.windowSize >= rhs.windowSize } } diff --git a/Sources/NIOHTTP2/HTTP2Frame.swift b/Sources/NIOHTTP2/HTTP2Frame.swift index 4931cfe..a849e19 100644 --- a/Sources/NIOHTTP2/HTTP2Frame.swift +++ b/Sources/NIOHTTP2/HTTP2Frame.swift @@ -13,8 +13,8 @@ //===----------------------------------------------------------------------===// import NIOCore -import NIOHTTP1 import NIOHPACK +import NIOHTTP1 /// A representation of a single HTTP/2 frame. public struct HTTP2Frame: Sendable { @@ -44,7 +44,7 @@ public struct HTTP2Frame: Sendable { /// /// See [RFC 7540 ยง 6.1](https://httpwg.org/specs/rfc7540.html#rfc.section.6.1). case data(FramePayload.Data) - + /// A `HEADERS` frame, containing all headers or trailers associated with a request /// or response. /// @@ -53,25 +53,25 @@ public struct HTTP2Frame: Sendable { /// /// See [RFC 7540 ยง 6.2](https://httpwg.org/specs/rfc7540.html#rfc.section.6.2). case headers(Headers) - + /// A `PRIORITY` frame, used to change priority and dependency ordering among /// streams. /// /// See [RFC 7540 ยง 6.3](https://httpwg.org/specs/rfc7540.html#rfc.section.6.3). case priority(StreamPriorityData) - + /// A `RST_STREAM` (reset stream) frame, sent when a stream has encountered an error /// condition and needs to be terminated as a result. /// /// See [RFC 7540 ยง 6.4](https://httpwg.org/specs/rfc7540.html#rfc.section.6.4). case rstStream(HTTP2ErrorCode) - + /// A `SETTINGS` frame, containing various connection--level settings and their /// desired values. /// /// See [RFC 7540 ยง 6.5](https://httpwg.org/specs/rfc7540.html#rfc.section.6.5). case settings(Settings) - + /// A `PUSH_PROMISE` frame, used to notify a peer in advance of streams that a sender /// intends to initiate. It performs much like a request's `HEADERS` frame, informing /// a peer that the response for a theoretical request like the one in the promise @@ -86,12 +86,12 @@ public struct HTTP2Frame: Sendable { /// For more information on server push in HTTP/2, see /// [RFC 7540 ยง 8.2](https://httpwg.org/specs/rfc7540.html#rfc.section.8.2). indirect case pushPromise(PushPromise) - + /// A `PING` frame, used to measure round-trip time between endpoints. /// /// See [RFC 7540 ยง 6.7](https://httpwg.org/specs/rfc7540.html#rfc.section.6.7). case ping(HTTP2PingData, ack: Bool) - + /// A `GOAWAY` frame, used to request that a peer immediately cease communication with /// the sender. It contains a stream ID indicating the last stream that will be processed /// by the sender, an error code (if the shutdown was caused by an error), and optionally @@ -99,14 +99,14 @@ public struct HTTP2Frame: Sendable { /// /// See [RFC 7540 ยง 6.8](https://httpwg.org/specs/rfc7540.html#rfc.section.6.8). indirect case goAway(lastStreamID: HTTP2StreamID, errorCode: HTTP2ErrorCode, opaqueData: ByteBuffer?) - + /// A `WINDOW_UPDATE` frame. This is used to implement flow control of DATA frames, /// allowing peers to advertise and update the amount of data they are prepared to /// process at any given moment. /// /// See [RFC 7540 ยง 6.9](https://httpwg.org/specs/rfc7540.html#rfc.section.6.9). case windowUpdate(windowSizeIncrement: Int) - + /// An `ALTSVC` frame. This is sent by an HTTP server to indicate alternative origin /// locations for accessing the same resource, for instance via another protocol, /// or over TLS. It consists of an origin and a list of alternate protocols and @@ -117,7 +117,7 @@ public struct HTTP2Frame: Sendable { /// - Important: ALTSVC frames are not currently supported. Any received ALTSVC frames will /// be ignored. Attempting to send an ALTSVC frame will result in a fatal error. indirect case alternativeService(origin: String?, field: ByteBuffer?) - + /// An `ORIGIN` frame. This allows servers which allow access to multiple origins /// via the same socket connection to identify which origins may be accessed in /// this manner. @@ -134,7 +134,7 @@ public struct HTTP2Frame: Sendable { @inlinable public var data: IOData { get { - return self._backing.data + self._backing.data } set { self._copyIfNeeded() @@ -146,7 +146,7 @@ public struct HTTP2Frame: Sendable { @inlinable public var endStream: Bool { get { - return self._backing.endStream + self._backing.endStream } set { self._copyIfNeeded() @@ -158,12 +158,15 @@ public struct HTTP2Frame: Sendable { @inlinable public var paddingBytes: Int? { get { - return self._backing.paddingBytes.map { Int($0) } + self._backing.paddingBytes.map { Int($0) } } set { self._copyIfNeeded() if let newValue = newValue { - precondition(newValue >= 0 && newValue <= Int(UInt8.max), "Invalid padding byte length: \(newValue)") + precondition( + newValue >= 0 && newValue <= Int(UInt8.max), + "Invalid padding byte length: \(newValue)" + ) self._backing.paddingBytes = UInt8(newValue) } else { self._backing.paddingBytes = nil @@ -211,7 +214,7 @@ public struct HTTP2Frame: Sendable { @inlinable func copy() -> _Backing { - return _Backing(data: self.data, endStream: self.endStream, paddingBytes: self.paddingBytes) + _Backing(data: self.data, endStream: self.endStream, paddingBytes: self.paddingBytes) } } } @@ -303,7 +306,10 @@ public struct HTTP2Frame: Sendable { } set { if let newValue = newValue { - precondition(newValue >= 0 && newValue <= Int(UInt8.max), "Invalid padding byte length: \(newValue)") + precondition( + newValue >= 0 && newValue <= Int(UInt8.max), + "Invalid padding byte length: \(newValue)" + ) self._paddingBytes = UInt8(newValue) self.booleans.insert(.paddingPresent) } else { @@ -312,7 +318,12 @@ public struct HTTP2Frame: Sendable { } } - public init(headers: HPACKHeaders, priorityData: StreamPriorityData? = nil, endStream: Bool = false, paddingBytes: Int? = nil) { + public init( + headers: HPACKHeaders, + priorityData: StreamPriorityData? = nil, + endStream: Bool = false, + paddingBytes: Int? = nil + ) { self.headers = headers self.booleans = .init(rawValue: 0) self._paddingBytes = 0 @@ -347,11 +358,14 @@ public struct HTTP2Frame: Sendable { /// The number of padding bytes sent in this frame. If nil, this frame was not padded. public var paddingBytes: Int? { get { - return self._paddingBytes.map { Int($0) } + self._paddingBytes.map { Int($0) } } set { if let newValue = newValue { - precondition(newValue >= 0 && newValue <= Int(UInt8.max), "Invalid padding byte length: \(newValue)") + precondition( + newValue >= 0 && newValue <= Int(UInt8.max), + "Invalid padding byte length: \(newValue)" + ) self._paddingBytes = UInt8(newValue) } else { self._paddingBytes = nil @@ -365,21 +379,21 @@ public struct HTTP2Frame: Sendable { self.paddingBytes = paddingBytes } } - + /// The one-byte identifier used to indicate the type of a frame on the wire. var code: UInt8 { switch self { - case .data: return 0x0 - case .headers: return 0x1 - case .priority: return 0x2 - case .rstStream: return 0x3 - case .settings: return 0x4 - case .pushPromise: return 0x5 - case .ping: return 0x6 - case .goAway: return 0x7 - case .windowUpdate: return 0x8 - case .alternativeService: return 0xa - case .origin: return 0xc + case .data: return 0x0 + case .headers: return 0x1 + case .priority: return 0x2 + case .rstStream: return 0x3 + case .settings: return 0x4 + case .pushPromise: return 0x5 + case .ping: return 0x6 + case .goAway: return 0x7 + case .windowUpdate: return 0x8 + case .alternativeService: return 0xa + case .origin: return 0xc } } } @@ -417,4 +431,3 @@ extension HTTP2Frame.FramePayload { /// Marking them non-Sendable would sadly be API breaking. extension HTTP2Frame.FramePayload: @unchecked Sendable {} extension HTTP2Frame.FramePayload.Data: @unchecked Sendable {} - diff --git a/Sources/NIOHTTP2/HTTP2FrameEncoder.swift b/Sources/NIOHTTP2/HTTP2FrameEncoder.swift index 82953da..5a3f6af 100644 --- a/Sources/NIOHTTP2/HTTP2FrameEncoder.swift +++ b/Sources/NIOHTTP2/HTTP2FrameEncoder.swift @@ -19,7 +19,7 @@ struct HTTP2FrameEncoder { var headerEncoder: HPACKEncoder // RFC 7540 ยง 6.5.2 puts the initial value of SETTINGS_MAX_FRAME_SIZE at 2**14 octets - var maxFrameSize: UInt32 = 1<<14 + var maxFrameSize: UInt32 = 1 << 14 init(allocator: ByteBufferAllocator) { self.headerEncoder = HPACKEncoder(allocator: allocator) @@ -46,15 +46,15 @@ struct HTTP2FrameEncoder { // note our starting point let start = buf.writerIndex -// +-----------------------------------------------+ -// | Length (24) | -// +---------------+---------------+---------------+ -// | Type (8) | Flags (8) | -// +-+-------------+---------------+-------------------------------+ -// |R| Stream Identifier (31) | -// +=+=============================================================+ -// | Frame Payload (0...) ... -// +---------------------------------------------------------------+ + // +-----------------------------------------------+ + // | Length (24) | + // +---------------+---------------+---------------+ + // | Type (8) | Flags (8) | + // +-+-------------+---------------+-------------------------------+ + // |R| Stream Identifier (31) | + // +=+=============================================================+ + // | Frame Payload (0...) ... + // +---------------------------------------------------------------+ // skip 24-bit length for now, we'll fill that in later buf.moveWriterIndex(forwardBy: 3) @@ -240,11 +240,10 @@ extension ByteBuffer { // Yes, this performs better than running a UInt8 through the generic write(integer:) three times. var bytes: (UInt8, UInt8, UInt8) bytes.0 = UInt8((size & 0xff_00_00) >> 16) - bytes.1 = UInt8((size & 0x00_ff_00) >> 8) - bytes.2 = UInt8( size & 0x00_00_ff) + bytes.1 = UInt8((size & 0x00_ff_00) >> 8) + bytes.2 = UInt8(size & 0x00_00_ff) withUnsafeBytes(of: bytes) { ptr in _ = self.setBytes(ptr, at: location) } } } - diff --git a/Sources/NIOHTTP2/HTTP2FrameParser.swift b/Sources/NIOHTTP2/HTTP2FrameParser.swift index 15905c4..f24b114 100644 --- a/Sources/NIOHTTP2/HTTP2FrameParser.swift +++ b/Sources/NIOHTTP2/HTTP2FrameParser.swift @@ -39,7 +39,8 @@ struct HTTP2FrameDecoder { mutating func process() throws -> AccumulatingFrameHeaderParserState? { // The client magic is 24 octets long: If we don't have it, keep waiting. guard var pendingBytes = self.pendingBytes, - let clientMagic = pendingBytes.readSlice(length: 24) else { + let clientMagic = pendingBytes.readSlice(length: 24) + else { return nil } @@ -232,7 +233,12 @@ struct HTTP2FrameDecoder { enum ProcessResult { case accumulateHeaderBlockFragments(AccumulatingHeaderBlockFragmentsParserState) - case parseFrame(header: FrameHeader, payloadBytes: ByteBuffer, paddingBytes: Int?, nextState: AccumulatingFrameHeaderParserState) + case parseFrame( + header: FrameHeader, + payloadBytes: ByteBuffer, + paddingBytes: Int?, + nextState: AccumulatingFrameHeaderParserState + ) } /// Process a frame. @@ -289,7 +295,10 @@ struct HTTP2FrameDecoder { let nextState = AccumulatingFrameHeaderParserState(unusedBytes: self.accumulatedBytes) return .parseFrame( - header: syntheticHeader, payloadBytes: payloadBytes, paddingBytes: expectedPadding, nextState: nextState + header: syntheticHeader, + payloadBytes: payloadBytes, + paddingBytes: expectedPadding, + nextState: nextState ) } @@ -426,14 +435,14 @@ struct HTTP2FrameDecoder { // branch. precondition(self.payload.readableBytes > 0) - let frameBytes = self.payload // entire thing + let frameBytes = self.payload // entire thing self.remainingByteCount -= frameBytes.readableBytes self.payload.quietlyReset() return HTTP2Frame.FramePayload.Data( data: .byteBuffer(frameBytes), - endStream: false, // We're synthesising frames, there can't be END_STREAM here. - paddingBytes: nil // We put all the padding on the last frame in the sequence. + endStream: false, // We're synthesising frames, there can't be END_STREAM here. + paddingBytes: nil // We put all the padding on the last frame in the sequence. ) } @@ -452,7 +461,11 @@ struct HTTP2FrameDecoder { private var excessBytes: ByteBuffer private var expectedPadding: Int - init(fromSimulatingDataFramesState state: SimulatingDataFramesParserState, excessBytes: ByteBuffer, expectedPadding: Int) { + init( + fromSimulatingDataFramesState state: SimulatingDataFramesParserState, + excessBytes: ByteBuffer, + expectedPadding: Int + ) { precondition(expectedPadding > 0) self.header = state.header @@ -460,7 +473,11 @@ struct HTTP2FrameDecoder { self.expectedPadding = expectedPadding } - init(fromAccumulatingPayloadState state: AccumulatingPayloadParserState, excessBytes: ByteBuffer, expectedPadding: Int) { + init( + fromAccumulatingPayloadState state: AccumulatingPayloadParserState, + excessBytes: ByteBuffer, + expectedPadding: Int + ) { precondition(expectedPadding > 0) self.header = state.header @@ -507,8 +524,10 @@ struct HTTP2FrameDecoder { private var originalPaddingBytes: Int? private var continuationSequenceCount: Int - init(fromAccumulatingHeaderBlockFragments acc: AccumulatingHeaderBlockFragmentsParserState, - continuationHeader: FrameHeader) { + init( + fromAccumulatingHeaderBlockFragments acc: AccumulatingHeaderBlockFragmentsParserState, + continuationHeader: FrameHeader + ) { precondition(acc.header.beginsContinuationSequence) precondition(continuationHeader.type == .continuation) @@ -524,11 +543,17 @@ struct HTTP2FrameDecoder { /// or we continue accumulating enum ProcessResult { case accumulateContinuationHeader(AccumulatingHeaderBlockFragmentsParserState) - case parseFrame(header: FrameHeader, payloadBytes: ByteBuffer, paddingBytes: Int?, nextState: AccumulatingFrameHeaderParserState) + case parseFrame( + header: FrameHeader, + payloadBytes: ByteBuffer, + paddingBytes: Int?, + nextState: AccumulatingFrameHeaderParserState + ) } mutating func process() throws -> ProcessResult? { - guard let continuationPayload = self.continuationPayload.readSlice(length: self.continuationHeader.length) else { + guard let continuationPayload = self.continuationPayload.readSlice(length: self.continuationHeader.length) + else { return nil } @@ -568,7 +593,12 @@ struct HTTP2FrameDecoder { // It is! Let's add .endHeaders to our fake frame. header.flags.formUnion(.endHeaders) let nextState = AccumulatingFrameHeaderParserState(unusedBytes: self.continuationPayload) - return .parseFrame(header: header, payloadBytes: payload, paddingBytes: self.originalPaddingBytes, nextState: nextState) + return .parseFrame( + header: header, + payloadBytes: payload, + paddingBytes: self.originalPaddingBytes, + nextState: nextState + ) } mutating func accumulate(bytes: ByteBuffer) { @@ -634,7 +664,10 @@ struct HTTP2FrameDecoder { throw NIOHTTP2Errors.excessiveContinuationFrames() } - return AccumulatingContinuationPayloadParserState(fromAccumulatingHeaderBlockFragments: self, continuationHeader: header) + return AccumulatingContinuationPayloadParserState( + fromAccumulatingHeaderBlockFragments: self, + continuationHeader: header + ) } mutating func accumulate(bytes: ByteBuffer) { @@ -721,7 +754,7 @@ struct HTTP2FrameDecoder { private let maximumSequentialContinuationFrames: Int // RFC 7540 ยง 6.5.2 puts the initial value of SETTINGS_MAX_FRAME_SIZE at 2**14 octets - internal var maxFrameSize: UInt32 = 1<<14 + internal var maxFrameSize: UInt32 = 1 << 14 /// Creates a new HTTP2 frame decoder. /// @@ -809,7 +842,7 @@ struct HTTP2FrameDecoder { mutating func nextFrame() throws -> (HTTP2Frame, flowControlledLength: Int)? { // Start running through our state machine until we run out of bytes or we emit a frame. while true { - switch (try self.processNextState()) { + switch try self.processNextState() { case .needMoreData: return nil case .frame(let frame, let flowControlledLength): @@ -826,7 +859,7 @@ struct HTTP2FrameDecoder { case needMoreData case parseFrame(header: FrameHeader, payloadBytes: ByteBuffer, paddingBytes: Int?) } - + private mutating func processNextState() throws -> ParseResult { switch self.state { case .awaitingClientMagic(var state): @@ -847,7 +880,7 @@ struct HTTP2FrameDecoder { throw error } } - + case .initialized: // no bytes, no frame return .needMoreData @@ -857,15 +890,20 @@ struct HTTP2FrameDecoder { let maxHeaderListSize = self.headerDecoder.maxHeaderListSize return try self.avoidingParserCoW { newState in let result = Result { - guard let targetState = try state.process(maxFrameSize: maxFrameSize, maxHeaderListSize: maxHeaderListSize) else { + guard + let targetState = try state.process( + maxFrameSize: maxFrameSize, + maxHeaderListSize: maxHeaderListSize + ) + else { newState = .accumulatingFrameHeader(state) return .needMoreData } - + newState = .init(targetState) return .continue } - + switch result { case let .success(processResult): return processResult @@ -874,7 +912,7 @@ struct HTTP2FrameDecoder { throw error } } - + case .awaitingPaddingLengthByte(var state): return try self.avoidingParserCoW { newState in let result = Result { @@ -882,7 +920,7 @@ struct HTTP2FrameDecoder { newState = .awaitingPaddingLengthByte(state) return .needMoreData } - + newState = .init(targetState) return .continue } @@ -894,7 +932,7 @@ struct HTTP2FrameDecoder { throw error } } - + case .accumulatingPayload(var state): let accumulatingResult: ProcessAccumulatingResult = try self.avoidingParserCoW { newState in let result = Result { @@ -902,18 +940,18 @@ struct HTTP2FrameDecoder { newState = .accumulatingPayload(state) return .needMoreData } - + switch processResult { case .accumulateHeaderBlockFragments(let nextState): newState = .accumulatingHeaderBlockFragments(nextState) return .continue - case .parseFrame(header: let header, payloadBytes: let payloadBytes, paddingBytes: let paddingBytes, nextState: let nextState): + case .parseFrame(let header, let payloadBytes, let paddingBytes, let nextState): // Save off the state first, because if the frame payload parse throws we want to be able to skip over the frame. newState = .accumulatingFrameHeader(nextState) return .parseFrame(header: header, payloadBytes: payloadBytes, paddingBytes: paddingBytes) } } - + switch result { case let .success(processAccumulatingResult): return processAccumulatingResult @@ -922,9 +960,9 @@ struct HTTP2FrameDecoder { throw error } } - + switch accumulatingResult { - case .parseFrame(header: let header, payloadBytes: var payloadBytes, paddingBytes: let paddingBytes): + case .parseFrame(let header, var payloadBytes, let paddingBytes): // an entire frame's data, including HEADERS/PUSH_PROMISE with the END_HEADERS flag set // this may legitimately return nil if we ignore the frame let result = try self.readFrame(withHeader: header, from: &payloadBytes, paddingBytes: paddingBytes) @@ -971,7 +1009,7 @@ struct HTTP2FrameDecoder { newState = .strippingTrailingPadding(state) return .needMoreData } - + newState = .init(nextState) return .continue } @@ -987,7 +1025,7 @@ struct HTTP2FrameDecoder { case .accumulateContinuationHeader(let nextState): newState = .accumulatingHeaderBlockFragments(nextState) return .continue - case .parseFrame(header: let header, payloadBytes: let payloadBytes, paddingBytes: let paddingBytes, nextState: let nextState): + case .parseFrame(let header, let payloadBytes, let paddingBytes, let nextState): // Save off the state first, because if the frame payload parse throws we want to be able to skip over the frame. newState = .accumulatingFrameHeader(nextState) return .parseFrame(header: header, payloadBytes: payloadBytes, paddingBytes: paddingBytes) @@ -1001,9 +1039,9 @@ struct HTTP2FrameDecoder { throw error } } - + switch accumulatingResult { - case .parseFrame(header: let header, payloadBytes: var payloadBytes, paddingBytes: let paddingBytes): + case .parseFrame(let header, var payloadBytes, let paddingBytes): // an entire frame's data, including HEADERS/PUSH_PROMISE with the END_HEADERS flag set // this may legitimately return nil if we ignore the frame let result = try self.readFrame(withHeader: header, from: &payloadBytes, paddingBytes: paddingBytes) @@ -1032,10 +1070,12 @@ struct HTTP2FrameDecoder { return try self.avoidingParserCoW { newState in let result = Result { - guard let processResult = try state.process( - maxHeaderListSize: maxHeaderListSize, - maximumSequentialContinuationFrames: maximumSequentialContinuationFrames - ) else { + guard + let processResult = try state.process( + maxHeaderListSize: maxHeaderListSize, + maximumSequentialContinuationFrames: maximumSequentialContinuationFrames + ) + else { newState = .accumulatingHeaderBlockFragments(state) return .needMoreData } @@ -1050,13 +1090,17 @@ struct HTTP2FrameDecoder { throw error } } - + case .appending: preconditionFailure("Attempting to process in appending state") } } - private mutating func readFrame(withHeader header: FrameHeader, from bytes: inout ByteBuffer, paddingBytes: Int?) throws -> HTTP2Frame? { + private mutating func readFrame( + withHeader header: FrameHeader, + from bytes: inout ByteBuffer, + paddingBytes: Int? + ) throws -> HTTP2Frame? { assert(bytes.readableBytes == header.length, "Buffer should contain exactly \(header.length) bytes.") let flags = header.flags @@ -1119,7 +1163,12 @@ struct HTTP2FrameDecoder { return HTTP2Frame(streamID: streamID, payload: payload) } - private mutating func parseHeadersFramePayload(streamID: HTTP2StreamID, flags: FrameFlags, bytes: inout ByteBuffer, paddingBytes: Int?) throws -> HTTP2Frame.FramePayload { + private mutating func parseHeadersFramePayload( + streamID: HTTP2StreamID, + flags: FrameFlags, + bytes: inout ByteBuffer, + paddingBytes: Int? + ) throws -> HTTP2Frame.FramePayload { // HEADERS frame : RFC 7540 ยง 6.2 guard streamID != .rootStream else { // HEADERS frames MUST be associated with a stream. If a HEADERS frame is received whose @@ -1135,23 +1184,30 @@ struct HTTP2FrameDecoder { throw InternalError.codecError(code: .protocolError) } - priorityData = HTTP2Frame.StreamPriorityData(exclusive: (rawStreamID & 0x8000_0000 != 0), - dependency: HTTP2StreamID(networkID: rawStreamID), - weight: weight) + priorityData = HTTP2Frame.StreamPriorityData( + exclusive: (rawStreamID & 0x8000_0000 != 0), + dependency: HTTP2StreamID(networkID: rawStreamID), + weight: weight + ) } else { priorityData = nil } let headers = try self.headerDecoder.decodeHeaders(from: &bytes) - let headersPayload = HTTP2Frame.FramePayload.Headers(headers: headers, - priorityData: priorityData, - endStream: flags.contains(.endStream), - paddingBytes: paddingBytes) + let headersPayload = HTTP2Frame.FramePayload.Headers( + headers: headers, + priorityData: priorityData, + endStream: flags.contains(.endStream), + paddingBytes: paddingBytes + ) return .headers(headersPayload) } - private func parsePriorityFramePayload(streamID: HTTP2StreamID, bytes: inout ByteBuffer) throws -> HTTP2Frame.FramePayload { + private func parsePriorityFramePayload( + streamID: HTTP2StreamID, + bytes: inout ByteBuffer + ) throws -> HTTP2Frame.FramePayload { // PRIORITY frame : RFC 7540 ยง 6.3 guard streamID != .rootStream else { // The PRIORITY frame always identifies a stream. If a PRIORITY frame is received @@ -1165,13 +1221,18 @@ struct HTTP2FrameDecoder { throw InternalError.codecError(code: .frameSizeError) } - let priorityData = HTTP2Frame.StreamPriorityData(exclusive: rawStreamID & 0x8000_0000 != 0, - dependency: HTTP2StreamID(networkID: rawStreamID), - weight: weight) + let priorityData = HTTP2Frame.StreamPriorityData( + exclusive: rawStreamID & 0x8000_0000 != 0, + dependency: HTTP2StreamID(networkID: rawStreamID), + weight: weight + ) return .priority(priorityData) } - private func parseRstStreamFramePayload(streamID: HTTP2StreamID, bytes: inout ByteBuffer) throws -> HTTP2Frame.FramePayload { + private func parseRstStreamFramePayload( + streamID: HTTP2StreamID, + bytes: inout ByteBuffer + ) throws -> HTTP2Frame.FramePayload { // RST_STREAM frame : RFC 7540 ยง 6.4 guard streamID != .rootStream else { // RST_STREAM frames MUST be associated with a stream. If a RST_STREAM frame is @@ -1188,7 +1249,11 @@ struct HTTP2FrameDecoder { return .rstStream(HTTP2ErrorCode(errorCode)) } - private func parseSettingsFramePayload(streamID: HTTP2StreamID, flags: FrameFlags, bytes: inout ByteBuffer) throws -> HTTP2Frame.FramePayload { + private func parseSettingsFramePayload( + streamID: HTTP2StreamID, + flags: FrameFlags, + bytes: inout ByteBuffer + ) throws -> HTTP2Frame.FramePayload { // SETTINGS frame : RFC 7540 ยง 6.5 guard streamID == .rootStream else { // SETTINGS frames always apply to a connection, never a single stream. The stream @@ -1232,7 +1297,12 @@ struct HTTP2FrameDecoder { return .settings(.settings(settings)) } - private mutating func parsePushPromiseFramePayload(streamID: HTTP2StreamID, flags: FrameFlags, bytes: inout ByteBuffer, paddingBytes: Int?) throws -> HTTP2Frame.FramePayload { + private mutating func parsePushPromiseFramePayload( + streamID: HTTP2StreamID, + flags: FrameFlags, + bytes: inout ByteBuffer, + paddingBytes: Int? + ) throws -> HTTP2Frame.FramePayload { // PUSH_PROMISE frame : RFC 7540 ยง 6.6 guard streamID != .rootStream else { // The stream identifier of a PUSH_PROMISE frame indicates the stream it is associated with. @@ -1253,13 +1323,22 @@ struct HTTP2FrameDecoder { let headers = try self.headerDecoder.decodeHeaders(from: &bytes) - let pushPromiseContent = HTTP2Frame.FramePayload.PushPromise(pushedStreamID: promisedStreamID, headers: headers, paddingBytes: paddingBytes) + let pushPromiseContent = HTTP2Frame.FramePayload.PushPromise( + pushedStreamID: promisedStreamID, + headers: headers, + paddingBytes: paddingBytes + ) return .pushPromise(pushPromiseContent) } - private func parsePingFramePayload(streamID: HTTP2StreamID, flags: FrameFlags, bytes: inout ByteBuffer) throws -> HTTP2Frame.FramePayload { + private func parsePingFramePayload( + streamID: HTTP2StreamID, + flags: FrameFlags, + bytes: inout ByteBuffer + ) throws -> HTTP2Frame.FramePayload { // PING frame : RFC 7540 ยง 6.7 - guard let tuple = bytes.readMultipleIntegers(as: (UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8).self) else { + guard let tuple = bytes.readMultipleIntegers(as: (UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8).self) + else { // Receipt of a PING frame with a length field value other than 8 MUST be treated // as a connection error (Section 5.4.1) of type FRAME_SIZE_ERROR. throw InternalError.codecError(code: .frameSizeError) @@ -1274,7 +1353,10 @@ struct HTTP2FrameDecoder { return .ping(HTTP2PingData(withTuple: tuple), ack: flags.contains(.ack)) } - private func parseGoAwayFramePayload(streamID: HTTP2StreamID, bytes: inout ByteBuffer) throws -> HTTP2Frame.FramePayload { + private func parseGoAwayFramePayload( + streamID: HTTP2StreamID, + bytes: inout ByteBuffer + ) throws -> HTTP2Frame.FramePayload { // GOAWAY frame : RFC 7540 ยง 6.8 guard streamID == .rootStream else { // The GOAWAY frame applies to the connection, not a specific stream. An endpoint @@ -1292,9 +1374,11 @@ struct HTTP2FrameDecoder { let debugData = bytes.readableBytes > 0 ? bytes : nil bytes.moveReaderIndex(to: bytes.writerIndex) - return .goAway(lastStreamID: HTTP2StreamID(networkID: rawLastStreamID), - errorCode: HTTP2ErrorCode(errorCode), - opaqueData: debugData) + return .goAway( + lastStreamID: HTTP2StreamID(networkID: rawLastStreamID), + errorCode: HTTP2ErrorCode(errorCode), + opaqueData: debugData + ) } private func parseWindowUpdateFramePayload(bytes: inout ByteBuffer) throws -> HTTP2Frame.FramePayload { @@ -1308,7 +1392,10 @@ struct HTTP2FrameDecoder { return .windowUpdate(windowSizeIncrement: Int(rawWindowSizeIncrement & ~0x8000_0000)) } - private func parseAltSvcFramePayload(streamID: HTTP2StreamID, bytes: inout ByteBuffer) throws -> HTTP2Frame.FramePayload { + private func parseAltSvcFramePayload( + streamID: HTTP2StreamID, + bytes: inout ByteBuffer + ) throws -> HTTP2Frame.FramePayload { // ALTSVC frame : RFC 7838 ยง 4 guard let originLen = bytes.readInteger(as: UInt16.self) else { // Must be at least two bytes, to contain the length of the optional 'Origin' field. @@ -1351,7 +1438,10 @@ struct HTTP2FrameDecoder { return .alternativeService(origin: origin, field: value) } - private func parseOriginFramePayload(streamID: HTTP2StreamID, bytes: inout ByteBuffer) throws -> HTTP2Frame.FramePayload { + private func parseOriginFramePayload( + streamID: HTTP2StreamID, + bytes: inout ByteBuffer + ) throws -> HTTP2Frame.FramePayload { // ORIGIN frame : RFC 8336 ยง 2 var origins: [String] = [] while let originLen = bytes.readInteger(as: UInt16.self) { @@ -1377,8 +1467,8 @@ struct HTTP2FrameDecoder { } } -fileprivate struct FrameHeader { - var length: Int // actually 24-bits +private struct FrameHeader { + var length: Int // actually 24-bits var type: FrameType var flags: FrameFlags var streamID: HTTP2StreamID @@ -1404,18 +1494,22 @@ fileprivate struct FrameHeader { static let origin = FrameType(12) var supportsPadding: Bool { - return self == .data || self == .headers || self == .pushPromise + self == .data || self == .headers || self == .pushPromise } } var beginsContinuationSequence: Bool { - return (self.type == .headers || self.type == .pushPromise) && !self.flags.contains(.endHeaders) + (self.type == .headers || self.type == .pushPromise) && !self.flags.contains(.endHeaders) } } extension ByteBuffer { fileprivate mutating func readFrameHeader() -> FrameHeader? { - guard let (lenHigh, lenLow, type, flags, rawStreamID) = self.readMultipleIntegers(as: (UInt16, UInt8, UInt8, UInt8, UInt32).self) else { + guard + let (lenHigh, lenLow, type, flags, rawStreamID) = self.readMultipleIntegers( + as: (UInt16, UInt8, UInt8, UInt8, UInt32).self + ) + else { return nil } @@ -1433,7 +1527,6 @@ extension ByteBuffer { } } - /// The flags supported by the frame types understood by this protocol. struct FrameFlags: OptionSet, CustomStringConvertible { internal typealias RawValue = UInt8 @@ -1445,22 +1538,22 @@ struct FrameFlags: OptionSet, CustomStringConvertible { } /// END_STREAM flag. Valid on DATA and HEADERS frames. - internal static let endStream = FrameFlags(rawValue: 0x01) + internal static let endStream = FrameFlags(rawValue: 0x01) /// ACK flag. Valid on SETTINGS and PING frames. - internal static let ack = FrameFlags(rawValue: 0x01) + internal static let ack = FrameFlags(rawValue: 0x01) /// END_HEADERS flag. Valid on HEADERS, CONTINUATION, and PUSH_PROMISE frames. - internal static let endHeaders = FrameFlags(rawValue: 0x04) + internal static let endHeaders = FrameFlags(rawValue: 0x04) /// PADDED flag. Valid on DATA, HEADERS, CONTINUATION, and PUSH_PROMISE frames. /// /// NB: swift-nio-http2 does not automatically pad outgoing frames. - internal static let padded = FrameFlags(rawValue: 0x08) + internal static let padded = FrameFlags(rawValue: 0x08) /// PRIORITY flag. Valid on HEADERS frames, specifically as the first frame sent /// on a new stream. - internal static let priority = FrameFlags(rawValue: 0x20) + internal static let priority = FrameFlags(rawValue: 0x20) // useful for test cases internal static var allFlags: FrameFlags = [.endStream, .endHeaders, .padded, .priority] @@ -1477,7 +1570,6 @@ struct FrameFlags: OptionSet, CustomStringConvertible { } } - // MARK: CoW helpers extension HTTP2FrameDecoder { /// So, uh...this function needs some explaining. @@ -1495,7 +1587,9 @@ extension HTTP2FrameDecoder { /// Sadly, because it's generic and has a closure, we need to force it to be inlined at all call sites, which is /// not ideal. @inline(__always) - private mutating func avoidingParserCoW(_ body: (inout ParserState) throws -> ReturnType) rethrows -> ReturnType { + private mutating func avoidingParserCoW( + _ body: (inout ParserState) throws -> ReturnType + ) rethrows -> ReturnType { self.state = .appending defer { assert(!self.isAppending) diff --git a/Sources/NIOHTTP2/HTTP2PingData.swift b/Sources/NIOHTTP2/HTTP2PingData.swift index aad20f4..d0d50b9 100644 --- a/Sources/NIOHTTP2/HTTP2PingData.swift +++ b/Sources/NIOHTTP2/HTTP2PingData.swift @@ -69,14 +69,14 @@ public struct HTTP2PingData: Sendable { extension HTTP2PingData: RandomAccessCollection, MutableCollection { public typealias Index = Int - public typealias Element = UInt8 + public typealias Element = UInt8 public var startIndex: Index { - return 0 + 0 } public var endIndex: Index { - return 7 + 7 } public subscript(_ index: Index) -> Element { @@ -128,15 +128,10 @@ extension HTTP2PingData: RandomAccessCollection, MutableCollection { } extension HTTP2PingData: Equatable { - public static func ==(lhs: HTTP2PingData, rhs: HTTP2PingData) -> Bool { - return lhs.bytes.0 == rhs.bytes.0 && - lhs.bytes.1 == rhs.bytes.1 && - lhs.bytes.2 == rhs.bytes.2 && - lhs.bytes.3 == rhs.bytes.3 && - lhs.bytes.4 == rhs.bytes.4 && - lhs.bytes.5 == rhs.bytes.5 && - lhs.bytes.6 == rhs.bytes.6 && - lhs.bytes.7 == rhs.bytes.7 + public static func == (lhs: HTTP2PingData, rhs: HTTP2PingData) -> Bool { + lhs.bytes.0 == rhs.bytes.0 && lhs.bytes.1 == rhs.bytes.1 && lhs.bytes.2 == rhs.bytes.2 + && lhs.bytes.3 == rhs.bytes.3 && lhs.bytes.4 == rhs.bytes.4 && lhs.bytes.5 == rhs.bytes.5 + && lhs.bytes.6 == rhs.bytes.6 && lhs.bytes.7 == rhs.bytes.7 } } diff --git a/Sources/NIOHTTP2/HTTP2PipelineHelpers.swift b/Sources/NIOHTTP2/HTTP2PipelineHelpers.swift index e66f937..3bae69d 100644 --- a/Sources/NIOHTTP2/HTTP2PipelineHelpers.swift +++ b/Sources/NIOHTTP2/HTTP2PipelineHelpers.swift @@ -66,9 +66,15 @@ extension ChannelPipeline { /// negotiated, or if no protocol was negotiated. Must return a future that completes when the /// pipeline has been fully mutated. /// - Returns: An `EventLoopFuture` that completes when the pipeline is ready to negotiate. - @available(*, deprecated, renamed: "Channel.configureHTTP2SecureUpgrade(h2ChannelConfigurator:http1ChannelConfigurator:)") - public func configureHTTP2SecureUpgrade(h2PipelineConfigurator: @escaping (ChannelPipeline) -> EventLoopFuture, - http1PipelineConfigurator: @escaping (ChannelPipeline) -> EventLoopFuture) -> EventLoopFuture { + @available( + *, + deprecated, + renamed: "Channel.configureHTTP2SecureUpgrade(h2ChannelConfigurator:http1ChannelConfigurator:)" + ) + public func configureHTTP2SecureUpgrade( + h2PipelineConfigurator: @escaping (ChannelPipeline) -> EventLoopFuture, + http1PipelineConfigurator: @escaping (ChannelPipeline) -> EventLoopFuture + ) -> EventLoopFuture { let alpnHandler = ApplicationProtocolNegotiationHandler { result in switch result { case .negotiated("h2"): @@ -103,12 +109,24 @@ extension Channel { /// - inboundStreamStateInitializer: A closure that will be called whenever the remote peer initiates a new stream. This should almost always /// be provided, especially on servers. /// - Returns: An `EventLoopFuture` containing the `HTTP2StreamMultiplexer` inserted into this pipeline, which can be used to initiate new streams. - @available(*, deprecated, renamed: "configureHTTP2Pipeline(mode:initialLocalSettings:position:targetWindowSize:inboundStreamInitializer:)") - public func configureHTTP2Pipeline(mode: NIOHTTP2Handler.ParserMode, - initialLocalSettings: [HTTP2Setting] = nioDefaultSettings, - position: ChannelPipeline.Position = .last, - inboundStreamStateInitializer: NIOChannelInitializerWithStreamID? = nil) -> EventLoopFuture { - return self.configureHTTP2Pipeline(mode: mode, initialLocalSettings: initialLocalSettings, position: position, targetWindowSize: 65535, inboundStreamStateInitializer: inboundStreamStateInitializer) + @available( + *, + deprecated, + renamed: "configureHTTP2Pipeline(mode:initialLocalSettings:position:targetWindowSize:inboundStreamInitializer:)" + ) + public func configureHTTP2Pipeline( + mode: NIOHTTP2Handler.ParserMode, + initialLocalSettings: [HTTP2Setting] = nioDefaultSettings, + position: ChannelPipeline.Position = .last, + inboundStreamStateInitializer: NIOChannelInitializerWithStreamID? = nil + ) -> EventLoopFuture { + self.configureHTTP2Pipeline( + mode: mode, + initialLocalSettings: initialLocalSettings, + position: position, + targetWindowSize: 65535, + inboundStreamStateInitializer: inboundStreamStateInitializer + ) } /// Configures a `ChannelPipeline` to speak HTTP/2. @@ -126,18 +144,33 @@ extension Channel { /// - inboundStreamStateInitializer: A closure that will be called whenever the remote peer initiates a new stream. This should almost always /// be provided, especially on servers. /// - Returns: An `EventLoopFuture` containing the `HTTP2StreamMultiplexer` inserted into this pipeline, which can be used to initiate new streams. - @available(*, deprecated, renamed: "configureHTTP2Pipeline(mode:initialLocalSettings:position:targetWindowSize:inboundStreamInitializer:)") - public func configureHTTP2Pipeline(mode: NIOHTTP2Handler.ParserMode, - initialLocalSettings: [HTTP2Setting] = nioDefaultSettings, - position: ChannelPipeline.Position = .last, - targetWindowSize: Int, - inboundStreamStateInitializer: NIOChannelInitializerWithStreamID? = nil) -> EventLoopFuture { + @available( + *, + deprecated, + renamed: "configureHTTP2Pipeline(mode:initialLocalSettings:position:targetWindowSize:inboundStreamInitializer:)" + ) + public func configureHTTP2Pipeline( + mode: NIOHTTP2Handler.ParserMode, + initialLocalSettings: [HTTP2Setting] = nioDefaultSettings, + position: ChannelPipeline.Position = .last, + targetWindowSize: Int, + inboundStreamStateInitializer: NIOChannelInitializerWithStreamID? = nil + ) -> EventLoopFuture { var handlers = [ChannelHandler]() handlers.reserveCapacity(2) // Update this if we need to add more handlers, to avoid unnecessary reallocation. handlers.append(NIOHTTP2Handler(mode: mode, initialSettings: initialLocalSettings)) - handlers.append(HTTP2StreamMultiplexer(mode: mode, channel: self, targetWindowSize: targetWindowSize, inboundStreamStateInitializer: inboundStreamStateInitializer)) + handlers.append( + HTTP2StreamMultiplexer( + mode: mode, + channel: self, + targetWindowSize: targetWindowSize, + inboundStreamStateInitializer: inboundStreamStateInitializer + ) + ) - return self.pipeline.addHandlers(handlers, position: position).flatMap { self.pipeline.handler(type: HTTP2StreamMultiplexer.self) } + return self.pipeline.addHandlers(handlers, position: position).flatMap { + self.pipeline.handler(type: HTTP2StreamMultiplexer.self) + } } /// Configures a `ChannelPipeline` to speak HTTP/2. @@ -155,11 +188,13 @@ extension Channel { /// - inboundStreamInitializer: A closure that will be called whenever the remote peer initiates a new stream. This should almost always /// be provided, especially on servers. /// - Returns: An `EventLoopFuture` containing the `HTTP2StreamMultiplexer` inserted into this pipeline, which can be used to initiate new streams. - public func configureHTTP2Pipeline(mode: NIOHTTP2Handler.ParserMode, - initialLocalSettings: [HTTP2Setting] = nioDefaultSettings, - position: ChannelPipeline.Position = .last, - targetWindowSize: Int = 65535, - inboundStreamInitializer: NIOChannelInitializer?) -> EventLoopFuture { + public func configureHTTP2Pipeline( + mode: NIOHTTP2Handler.ParserMode, + initialLocalSettings: [HTTP2Setting] = nioDefaultSettings, + position: ChannelPipeline.Position = .last, + targetWindowSize: Int = 65535, + inboundStreamInitializer: NIOChannelInitializer? + ) -> EventLoopFuture { if self.eventLoop.inEventLoop { return self.eventLoop.makeCompletedFuture { @@ -201,15 +236,17 @@ extension Channel { /// - position: The position in the pipeline into which to insert this handler. /// - inboundStreamInitializer: A closure that will be called whenever the remote peer initiates a new stream. /// - Returns: An `EventLoopFuture` containing the `StreamMultiplexer` inserted into this pipeline, which can be used to initiate new streams. - public func configureHTTP2Pipeline(mode: NIOHTTP2Handler.ParserMode, - connectionConfiguration: NIOHTTP2Handler.ConnectionConfiguration, - streamConfiguration: NIOHTTP2Handler.StreamConfiguration, - streamDelegate: NIOHTTP2StreamDelegate? = nil, - position: ChannelPipeline.Position = .last, - inboundStreamInitializer: @escaping NIOChannelInitializer) -> EventLoopFuture { + public func configureHTTP2Pipeline( + mode: NIOHTTP2Handler.ParserMode, + connectionConfiguration: NIOHTTP2Handler.ConnectionConfiguration, + streamConfiguration: NIOHTTP2Handler.StreamConfiguration, + streamDelegate: NIOHTTP2StreamDelegate? = nil, + position: ChannelPipeline.Position = .last, + inboundStreamInitializer: @escaping NIOChannelInitializer + ) -> EventLoopFuture { if self.eventLoop.inEventLoop { return self.eventLoop.makeCompletedFuture { - return try self.pipeline.syncOperations.configureHTTP2Pipeline( + try self.pipeline.syncOperations.configureHTTP2Pipeline( mode: mode, connectionConfiguration: connectionConfiguration, streamConfiguration: streamConfiguration, @@ -220,7 +257,7 @@ extension Channel { } } else { return self.eventLoop.submit { - return try self.pipeline.syncOperations.configureHTTP2Pipeline( + try self.pipeline.syncOperations.configureHTTP2Pipeline( mode: mode, connectionConfiguration: connectionConfiguration, streamConfiguration: streamConfiguration, @@ -257,8 +294,10 @@ extension Channel { /// negotiated, or if no protocol was negotiated. Must return a future that completes when the /// channel has been fully mutated. /// - Returns: An `EventLoopFuture` that completes when the channel is ready to negotiate. - public func configureHTTP2SecureUpgrade(h2ChannelConfigurator: @escaping NIOChannelInitializer, - http1ChannelConfigurator: @escaping NIOChannelInitializer) -> EventLoopFuture { + public func configureHTTP2SecureUpgrade( + h2ChannelConfigurator: @escaping NIOChannelInitializer, + http1ChannelConfigurator: @escaping NIOChannelInitializer + ) -> EventLoopFuture { let alpnHandler = ApplicationProtocolNegotiationHandler { result in switch result { case .negotiated("h2"): @@ -297,7 +336,11 @@ extension Channel { h2ConnectionChannelConfigurator: NIOChannelInitializer? = nil, _ configurator: @escaping NIOChannelInitializer ) -> EventLoopFuture { - return self.configureCommonHTTPServerPipeline(h2ConnectionChannelConfigurator: h2ConnectionChannelConfigurator, targetWindowSize: 65535, configurator) + self.configureCommonHTTPServerPipeline( + h2ConnectionChannelConfigurator: h2ConnectionChannelConfigurator, + targetWindowSize: 65535, + configurator + ) } /// Configures a `ChannelPipeline` to speak either HTTP/1.1 or HTTP/2 according to what can be negotiated with the client. @@ -322,9 +365,14 @@ extension Channel { targetWindowSize: Int, _ configurator: @escaping NIOChannelInitializer ) -> EventLoopFuture { - return self._commonHTTPServerPipeline(configurator: configurator, h2ConnectionChannelConfigurator: h2ConnectionChannelConfigurator) { channel in - channel.configureHTTP2Pipeline(mode: .server, targetWindowSize: targetWindowSize) { streamChannel -> EventLoopFuture in - streamChannel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ServerCodec()).flatMap { () -> EventLoopFuture in + self._commonHTTPServerPipeline( + configurator: configurator, + h2ConnectionChannelConfigurator: h2ConnectionChannelConfigurator + ) { channel in + channel.configureHTTP2Pipeline(mode: .server, targetWindowSize: targetWindowSize) { + streamChannel -> EventLoopFuture in + streamChannel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ServerCodec()).flatMap { + () -> EventLoopFuture in configurator(streamChannel) } }.map { _ in () } @@ -358,14 +406,18 @@ extension Channel { h2ConnectionChannelConfigurator: NIOChannelInitializer? = nil, configurator: @escaping NIOChannelInitializer ) -> EventLoopFuture { - return self._commonHTTPServerPipeline(configurator: configurator, h2ConnectionChannelConfigurator: h2ConnectionChannelConfigurator) { channel in + self._commonHTTPServerPipeline( + configurator: configurator, + h2ConnectionChannelConfigurator: h2ConnectionChannelConfigurator + ) { channel in channel.configureHTTP2Pipeline( mode: .server, connectionConfiguration: connectionConfiguration, streamConfiguration: streamConfiguration, streamDelegate: streamDelegate ) { streamChannel -> EventLoopFuture in - streamChannel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ServerCodec()).flatMap { () -> EventLoopFuture in + streamChannel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ServerCodec()).flatMap { + () -> EventLoopFuture in configurator(streamChannel) } }.map { _ in () } @@ -391,8 +443,10 @@ extension Channel { configurator(channel) } } - return self.configureHTTP2SecureUpgrade(h2ChannelConfigurator: h2ChannelConfigurator, - http1ChannelConfigurator: http1ChannelConfigurator) + return self.configureHTTP2SecureUpgrade( + h2ChannelConfigurator: h2ChannelConfigurator, + http1ChannelConfigurator: http1ChannelConfigurator + ) } } @@ -414,12 +468,14 @@ extension ChannelPipeline.SynchronousOperations { /// - position: The position in the pipeline into which to insert this handler. /// - inboundStreamInitializer: A closure that will be called whenever the remote peer initiates a new stream. /// - Returns: The `StreamMultiplexer` inserted into this pipeline, which can be used to initiate new streams. - public func configureHTTP2Pipeline(mode: NIOHTTP2Handler.ParserMode, - connectionConfiguration: NIOHTTP2Handler.ConnectionConfiguration, - streamConfiguration: NIOHTTP2Handler.StreamConfiguration, - streamDelegate: NIOHTTP2StreamDelegate? = nil, - position: ChannelPipeline.Position = .last, - inboundStreamInitializer: @escaping NIOChannelInitializer) throws -> NIOHTTP2Handler.StreamMultiplexer { + public func configureHTTP2Pipeline( + mode: NIOHTTP2Handler.ParserMode, + connectionConfiguration: NIOHTTP2Handler.ConnectionConfiguration, + streamConfiguration: NIOHTTP2Handler.StreamConfiguration, + streamDelegate: NIOHTTP2StreamDelegate? = nil, + position: ChannelPipeline.Position = .last, + inboundStreamInitializer: @escaping NIOChannelInitializer + ) throws -> NIOHTTP2Handler.StreamMultiplexer { let handler = NIOHTTP2Handler( mode: mode, eventLoop: self.eventLoop, @@ -451,15 +507,22 @@ extension ChannelPipeline.SynchronousOperations { /// - inboundStreamInitializer: A closure that will be called whenever the remote peer initiates a new stream. This should almost always /// be provided, especially on servers. /// - Returns: An `EventLoopFuture` containing the `HTTP2StreamMultiplexer` inserted into this pipeline, which can be used to initiate new streams. - internal func configureHTTP2Pipeline(mode: NIOHTTP2Handler.ParserMode, - channel: Channel, - initialLocalSettings: [HTTP2Setting] = nioDefaultSettings, - position: ChannelPipeline.Position = .last, - targetWindowSize: Int = 65535, - inboundStreamInitializer: NIOChannelInitializer?) throws -> HTTP2StreamMultiplexer { + internal func configureHTTP2Pipeline( + mode: NIOHTTP2Handler.ParserMode, + channel: Channel, + initialLocalSettings: [HTTP2Setting] = nioDefaultSettings, + position: ChannelPipeline.Position = .last, + targetWindowSize: Int = 65535, + inboundStreamInitializer: NIOChannelInitializer? + ) throws -> HTTP2StreamMultiplexer { let http2Handler = NIOHTTP2Handler(mode: mode, initialSettings: initialLocalSettings) - let multiplexer = HTTP2StreamMultiplexer(mode: mode, channel: channel, targetWindowSize: targetWindowSize, inboundStreamInitializer: inboundStreamInitializer) + let multiplexer = HTTP2StreamMultiplexer( + mode: mode, + channel: channel, + targetWindowSize: targetWindowSize, + inboundStreamInitializer: inboundStreamInitializer + ) try self.addHandler(http2Handler, position: position) try self.addHandler(multiplexer, position: .after(http2Handler)) @@ -524,7 +587,7 @@ extension Channel { ) -> EventLoopFuture> { if self.eventLoop.inEventLoop { return self.eventLoop.makeCompletedFuture { - return try self.pipeline.syncOperations.configureAsyncHTTP2Pipeline( + try self.pipeline.syncOperations.configureAsyncHTTP2Pipeline( mode: mode, streamDelegate: streamDelegate, configuration: configuration, @@ -533,7 +596,7 @@ extension Channel { } } else { return self.eventLoop.submit { - return try self.pipeline.syncOperations.configureAsyncHTTP2Pipeline( + try self.pipeline.syncOperations.configureAsyncHTTP2Pipeline( mode: mode, streamDelegate: streamDelegate, configuration: configuration, @@ -543,7 +606,6 @@ extension Channel { } } - /// Configures a channel to perform an HTTP/2 secure upgrade with typed negotiation results. /// /// HTTP/2 secure upgrade uses the Application Layer Protocol Negotiation TLS extension to @@ -576,7 +638,9 @@ extension Channel { http2ConnectionInitializer: @escaping NIOChannelInitializerWithOutput ) -> EventLoopFuture>> { - let alpnHandler = NIOTypedApplicationProtocolNegotiationHandler>() { result in + let alpnHandler = NIOTypedApplicationProtocolNegotiationHandler< + NIONegotiatedHTTPVersion + > { result in switch result { case .negotiated("h2"): // Successful upgrade to HTTP/2. Let the user configure the pipeline. @@ -594,7 +658,11 @@ extension Channel { return self.pipeline .addHandler(alpnHandler) .flatMap { _ in - self.pipeline.handler(type: NIOTypedApplicationProtocolNegotiationHandler>.self).map { alpnHandler in + self.pipeline.handler( + type: NIOTypedApplicationProtocolNegotiationHandler< + NIONegotiatedHTTPVersion + >.self + ).map { alpnHandler in alpnHandler.protocolNegotiationResult } } @@ -621,26 +689,37 @@ extension Channel { /// be waited on to retrieve the result of the negotiation. @inlinable @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) - public func configureAsyncHTTPServerPipeline( + public func configureAsyncHTTPServerPipeline< + HTTP1ConnectionOutput: Sendable, + HTTP2ConnectionOutput: Sendable, + HTTP2StreamOutput: Sendable + >( http2Configuration: NIOHTTP2Handler.Configuration = .init(), http1ConnectionInitializer: @escaping NIOChannelInitializerWithOutput, http2ConnectionInitializer: @escaping NIOChannelInitializerWithOutput, http2StreamInitializer: @escaping NIOChannelInitializerWithOutput - ) -> EventLoopFuture) - >>> { - let http2ConnectionInitializer: NIOChannelInitializerWithOutput<(HTTP2ConnectionOutput, NIOHTTP2Handler.AsyncStreamMultiplexer)> = { channel in - channel.configureAsyncHTTP2Pipeline( - mode: .server, - configuration: http2Configuration, - streamInitializer: http2StreamInitializer - ).flatMap { multiplexer in - return http2ConnectionInitializer(channel).map { connectionChannel in - (connectionChannel, multiplexer) + ) -> EventLoopFuture< + EventLoopFuture< + NIONegotiatedHTTPVersion< + HTTP1ConnectionOutput, + (HTTP2ConnectionOutput, NIOHTTP2Handler.AsyncStreamMultiplexer) + > + > + > { + let http2ConnectionInitializer: + NIOChannelInitializerWithOutput< + (HTTP2ConnectionOutput, NIOHTTP2Handler.AsyncStreamMultiplexer) + > = { channel in + channel.configureAsyncHTTP2Pipeline( + mode: .server, + configuration: http2Configuration, + streamInitializer: http2StreamInitializer + ).flatMap { multiplexer in + http2ConnectionInitializer(channel).map { connectionChannel in + (connectionChannel, multiplexer) + } } } - } let http1ConnectionInitializer: NIOChannelInitializerWithOutput = { channel in channel.pipeline.configureHTTPServerPipeline().flatMap { _ in http1ConnectionInitializer(channel) @@ -717,15 +796,20 @@ extension ChannelPipeline.SynchronousOperations { streamConfiguration: configuration.stream, streamDelegate: streamDelegate, inboundStreamInitializerWithAnyOutput: { channel in - streamInitializer(channel).map { return $0 } + streamInitializer(channel).map { $0 } } ) try self.addHandler(handler) - let (inboundStreamChannels, continuation) = NIOHTTP2AsyncSequence.initialize(inboundStreamInitializerOutput: Output.self) + let (inboundStreamChannels, continuation) = NIOHTTP2AsyncSequence.initialize( + inboundStreamInitializerOutput: Output.self + ) - return try handler.syncAsyncStreamMultiplexer(continuation: continuation, inboundStreamChannels: inboundStreamChannels) + return try handler.syncAsyncStreamMultiplexer( + continuation: continuation, + inboundStreamChannels: inboundStreamChannels + ) } } diff --git a/Sources/NIOHTTP2/HTTP2Settings.swift b/Sources/NIOHTTP2/HTTP2Settings.swift index 91ba29d..2d4f081 100644 --- a/Sources/NIOHTTP2/HTTP2Settings.swift +++ b/Sources/NIOHTTP2/HTTP2Settings.swift @@ -35,7 +35,7 @@ public struct HTTP2SettingsParameter: Sendable { internal init(fromNetwork value: Int32) { self.networkRepresentation = UInt16(value) } - + /// Initialize a ``HTTP2SettingsParameter`` from a network `UInt16`. internal init(fromPayload value: UInt16) { self.networkRepresentation = value @@ -63,14 +63,14 @@ public struct HTTP2SettingsParameter: Sendable { /// Corresponds to `SETTINGS_MAX_HEADER_LIST_SIZE` public static let maxHeaderListSize = HTTP2SettingsParameter(6) - + /// Corresponds to `SETTINGS_ENABLE_CONNECT_PROTOCOL` from RFC 8441. public static let enableConnectProtocol = HTTP2SettingsParameter(8) } -extension HTTP2SettingsParameter: Equatable { } +extension HTTP2SettingsParameter: Equatable {} -extension HTTP2SettingsParameter: Hashable { } +extension HTTP2SettingsParameter: Hashable {} /// A single setting for HTTP/2, a combination of a ``HTTP2SettingsParameter`` and its value. public struct HTTP2Setting: Sendable { @@ -80,7 +80,7 @@ public struct HTTP2Setting: Sendable { /// The value of the settings parameter. This must be a 32-bit number. public var value: Int { get { - return Int(self._value) + Int(self._value) } set { self._value = UInt32(newValue) @@ -100,8 +100,8 @@ public struct HTTP2Setting: Sendable { } extension HTTP2Setting: Equatable { - public static func ==(lhs: HTTP2Setting, rhs: HTTP2Setting) -> Bool { - return lhs.parameter == rhs.parameter && lhs._value == rhs._value + public static func == (lhs: HTTP2Setting, rhs: HTTP2Setting) -> Bool { + lhs.parameter == rhs.parameter && lhs._value == rhs._value } } diff --git a/Sources/NIOHTTP2/HTTP2Stream.swift b/Sources/NIOHTTP2/HTTP2Stream.swift index 6b02398..64a6604 100644 --- a/Sources/NIOHTTP2/HTTP2Stream.swift +++ b/Sources/NIOHTTP2/HTTP2Stream.swift @@ -12,8 +12,8 @@ // //===----------------------------------------------------------------------===// -import NIOHTTP1 import NIOHPACK +import NIOHTTP1 extension HPACKHeaders { /// Whether this `HTTPHeaders` corresponds to a final response or not. @@ -21,7 +21,7 @@ extension HPACKHeaders { /// This function is only valid if called on a response header block. If the :status header /// is not present, this will throw. fileprivate func isInformationalResponse() throws -> Bool { - return try self.peekPseudoHeader(name: ":status").first! == "1" + try self.peekPseudoHeader(name: ":status").first! == "1" } } @@ -65,23 +65,23 @@ struct HTTP2HeadersStateMachine { // The first header block received on a server mode stream must be a request block. newType = .requestHead case (.client, .none), - (.client, .some(.informationalResponseHead)): + (.client, .some(.informationalResponseHead)): // The first header block received on a client mode stream may be either informational or final, // depending on the value of the :status pseudo-header. Alternatively, if the previous // header block was informational, the same possibilities apply. newType = try block.isInformationalResponse() ? .informationalResponseHead : .finalResponseHead case (.server, .some(.requestHead)), - (.client, .some(.finalResponseHead)): + (.client, .some(.finalResponseHead)): // If the sevrer has already received a request head, or the client has already received a final response, // this is a trailer block. newType = .trailer case (.server, .some(.informationalResponseHead)), - (.server, .some(.finalResponseHead)), - (.client, .some(.requestHead)): + (.server, .some(.finalResponseHead)), + (.client, .some(.requestHead)): // These states should not be reachable! preconditionFailure("Invalid internal state!") case (.server, .some(.trailer)), - (.client, .some(.trailer)): + (.client, .some(.trailer)): // TODO(cory): This should probably throw, as this can happen in malformed programs without the world ending. preconditionFailure("Sending too many header blocks.") } diff --git a/Sources/NIOHTTP2/HTTP2StreamChannel+OutboundStreamMultiplexer.swift b/Sources/NIOHTTP2/HTTP2StreamChannel+OutboundStreamMultiplexer.swift index 799946f..0e60aba 100644 --- a/Sources/NIOHTTP2/HTTP2StreamChannel+OutboundStreamMultiplexer.swift +++ b/Sources/NIOHTTP2/HTTP2StreamChannel+OutboundStreamMultiplexer.swift @@ -16,25 +16,25 @@ import NIOCore /// Multiplexes outbound HTTP/2 frames from an HTTP/2 stream into an HTTP/2 /// connection. internal protocol HTTP2OutboundStreamMultiplexer { - /// Write the frame into the HTTP/2 connection. Stream ID is included in the - /// frame. - func writeFrame(_ frame: HTTP2Frame, promise: EventLoopPromise?) + /// Write the frame into the HTTP/2 connection. Stream ID is included in the + /// frame. + func writeFrame(_ frame: HTTP2Frame, promise: EventLoopPromise?) - /// Flush the stream with the given ID. - func flushStream(_ id: HTTP2StreamID) + /// Flush the stream with the given ID. + func flushStream(_ id: HTTP2StreamID) - /// Request a stream ID for the given channel. - /// - /// Required to lazily assign a stream ID to a channel on first write. - func requestStreamID(forChannel: Channel) -> HTTP2StreamID + /// Request a stream ID for the given channel. + /// + /// Required to lazily assign a stream ID to a channel on first write. + func requestStreamID(forChannel: Channel) -> HTTP2StreamID - /// Notify the multiplexer that the channel with the given ID closed. - /// - /// Required as a channel may not have a stream ID when it closes. - func streamClosed(channelID: ObjectIdentifier) + /// Notify the multiplexer that the channel with the given ID closed. + /// + /// Required as a channel may not have a stream ID when it closes. + func streamClosed(channelID: ObjectIdentifier) - /// Notify the multiplexer that the stream with the given ID closed. - func streamClosed(id: HTTP2StreamID) + /// Notify the multiplexer that the stream with the given ID closed. + func streamClosed(id: HTTP2StreamID) } extension HTTP2StreamChannel { @@ -122,4 +122,3 @@ extension LegacyOutboundStreamMultiplexer: HTTP2OutboundStreamMultiplexer { self.multiplexer.childChannelClosed(streamID: id) } } - diff --git a/Sources/NIOHTTP2/HTTP2StreamChannel.swift b/Sources/NIOHTTP2/HTTP2StreamChannel.swift index 75e4696..9f22073 100644 --- a/Sources/NIOHTTP2/HTTP2StreamChannel.swift +++ b/Sources/NIOHTTP2/HTTP2StreamChannel.swift @@ -13,9 +13,8 @@ //===----------------------------------------------------------------------===// import Atomics -import NIOCore import NIOConcurrencyHelpers - +import NIOCore /// The various channel options specific to `HTTP2StreamChannel`s. /// @@ -46,7 +45,7 @@ extension HTTP2StreamChannelOptions.Types { public struct StreamIDOption: ChannelOption { public typealias Value = HTTP2StreamID - public init() { } + public init() {} } } @@ -152,14 +151,16 @@ final class HTTP2StreamChannel: Channel, ChannelCore, @unchecked Sendable { /// The stream data type of the channel. private let streamDataType: HTTP2StreamDataType - internal init(allocator: ByteBufferAllocator, - parent: Channel, - multiplexer: OutboundStreamMultiplexer, - streamID: HTTP2StreamID?, - targetWindowSize: Int32, - outboundBytesHighWatermark: Int, - outboundBytesLowWatermark: Int, - streamDataType: HTTP2StreamDataType) { + internal init( + allocator: ByteBufferAllocator, + parent: Channel, + multiplexer: OutboundStreamMultiplexer, + streamID: HTTP2StreamID?, + targetWindowSize: Int32, + outboundBytesHighWatermark: Int, + outboundBytesLowWatermark: Int, + streamDataType: HTTP2StreamDataType + ) { self.allocator = allocator self.closePromise = parent.eventLoop.makePromise() self.localAddress = parent.localAddress @@ -172,9 +173,11 @@ final class HTTP2StreamChannel: Channel, ChannelCore, @unchecked Sendable { self.flags = NIOLockedValueBox(Flags(isActive: false, isWritable: true)) self.state = .idle self.streamDataType = streamDataType - self.writabilityManager = StreamChannelFlowController(highWatermark: outboundBytesHighWatermark, - lowWatermark: outboundBytesLowWatermark, - parentIsWritable: parent.isWritable) + self.writabilityManager = StreamChannelFlowController( + highWatermark: outboundBytesHighWatermark, + lowWatermark: outboundBytesLowWatermark, + parentIsWritable: parent.isWritable + ) // To begin with we initialize autoRead to false, but we are going to fetch it from our parent before we // go much further. @@ -182,7 +185,10 @@ final class HTTP2StreamChannel: Channel, ChannelCore, @unchecked Sendable { self._pipeline = ChannelPipeline(channel: self) } - internal func configure(initializer: NIOChannelInitializerWithStreamID?, userPromise promise: EventLoopPromise?) { + internal func configure( + initializer: NIOChannelInitializerWithStreamID?, + userPromise promise: EventLoopPromise? + ) { assert(self.streamDataType == .frame) // We need to configure this channel. This involves doing four things: // 1. Setting our autoRead state from the parent @@ -235,7 +241,10 @@ final class HTTP2StreamChannel: Channel, ChannelCore, @unchecked Sendable { // This variant is used in the async stream case. // It uses `Any`s because when called from `configureInboundStream` it is passed the initializer stored on the handler // which can't be a typed generic without changing the handler API. - internal func configure(initializer: @escaping NIOChannelInitializerWithOutput, userPromise promise: EventLoopPromise?) { + internal func configure( + initializer: @escaping NIOChannelInitializerWithOutput, + userPromise promise: EventLoopPromise? + ) { assert(self.streamDataType == .framePayload) // We need to configure this channel. This involves doing four things: // 1. Setting our autoRead state from the parent @@ -255,7 +264,10 @@ final class HTTP2StreamChannel: Channel, ChannelCore, @unchecked Sendable { } } - func onInitializationResult(_ initializerResult: Result, promise: EventLoopPromise?) { + func onInitializationResult( + _ initializerResult: Result, + promise: EventLoopPromise? + ) { switch initializerResult { case .success(let output): self.postInitializerActivate(output: output, promise: promise) @@ -364,11 +376,11 @@ final class HTTP2StreamChannel: Channel, ChannelCore, @unchecked Sendable { private let multiplexer: OutboundStreamMultiplexer public var closeFuture: EventLoopFuture { - return self.closePromise.futureResult + self.closePromise.futureResult } public var pipeline: ChannelPipeline { - return self._pipeline + self._pipeline } public let localAddress: SocketAddress? @@ -452,7 +464,7 @@ final class HTTP2StreamChannel: Channel, ChannelCore, @unchecked Sendable { } private var _isActive: Bool { - return self.state == .active || self.state == .closing || self.state == .localActive + self.state == .active || self.state == .closing || self.state == .localActive } public var isActive: Bool { @@ -460,7 +472,7 @@ final class HTTP2StreamChannel: Channel, ChannelCore, @unchecked Sendable { } public var _channelCore: ChannelCore { - return self + self } public let eventLoop: EventLoop @@ -494,7 +506,9 @@ final class HTTP2StreamChannel: Channel, ChannelCore, @unchecked Sendable { /// /// To correctly respect flushes, we deliberately withold frames from the parent channel until this /// stream is flushed, at which time we deliver them all. This buffer holds the pending ones. - private var pendingWrites: MarkedCircularBuffer<(HTTP2StreamData, EventLoopPromise?)> = MarkedCircularBuffer(initialCapacity: 8) + private var pendingWrites: MarkedCircularBuffer<(HTTP2StreamData, EventLoopPromise?)> = MarkedCircularBuffer( + initialCapacity: 8 + ) /// A list node used to hold stream channels. internal var streamChannelListNode: StreamChannelListNode = StreamChannelListNode() @@ -549,7 +563,7 @@ final class HTTP2StreamChannel: Channel, ChannelCore, @unchecked Sendable { switch self.multiplexer { case .inline: promise = userPromise - break // do nothing at this stage, we'll be called back + break // do nothing at this stage, we'll be called back case .legacy: promise = userPromise ?? self.eventLoop.makePromise() promise!.futureResult.hop(to: self.eventLoop).whenComplete { (_: Result) in @@ -734,7 +748,7 @@ final class HTTP2StreamChannel: Channel, ChannelCore, @unchecked Sendable { } // MARK:- Functions used to manage pending reads and writes. -private extension HTTP2StreamChannel { +extension HTTP2StreamChannel { /// Drop all pending reads. private func dropPendingReads() { /// We don't need to report the dropped reads, just remove them all. @@ -816,7 +830,7 @@ private extension HTTP2StreamChannel { } // MARK:- Functions used to communicate between the `HTTP2StreamMultiplexer` and the `HTTP2StreamChannel`. -internal extension HTTP2StreamChannel { +extension HTTP2StreamChannel { /// Called when a frame is received from the network. /// /// - Parameters: @@ -915,7 +929,8 @@ internal extension HTTP2StreamChannel { // This is because in this case we really want user code to send a frame as soon as possible to avoid // issues with their stream ID becoming out of date. Once the state transitions we can update // the writability if needed. - guard case .changed(newValue: let localValue) = self.writabilityManager.parentWritabilityChanged(newValue) else { + guard case .changed(newValue: let localValue) = self.writabilityManager.parentWritabilityChanged(newValue) + else { return } @@ -938,7 +953,9 @@ internal extension HTTP2StreamChannel { extension HTTP2StreamChannel { // A helper function used to ensure that state modification leads to changes in the channel active atomic. - private func modifyingState(_ closure: (inout StreamChannelState) throws -> ReturnType) rethrows -> ReturnType { + private func modifyingState( + _ closure: (inout StreamChannelState) throws -> ReturnType + ) rethrows -> ReturnType { defer { self.flags.withLockedValue { $0.isActive = self._isActive } } @@ -949,7 +966,7 @@ extension HTTP2StreamChannel { // MARK: Custom String Convertible extension HTTP2StreamChannel { public var description: String { - return "HTTP2StreamChannel(streamID: \(String(describing: self.streamID)), isActive: \(self.isActive), isWritable: \(self.isWritable))" + "HTTP2StreamChannel(streamID: \(String(describing: self.streamID)), isActive: \(self.isActive), isWritable: \(self.isWritable))" } } @@ -972,12 +989,12 @@ extension HTTP2StreamChannel { /// /// - Important: Must be called on the `EventLoop` the `Channel` is running on. public func getOption(_ option: Option) throws -> Option.Value { - return try self.channel.getOption0(option) + try self.channel.getOption0(option) } } /// Returns a view of the `Channel` exposing synchronous versions of `setOption` and `getOption`. public var syncOptions: NIOSynchronousChannelOptions? { - return SynchronousOptions(channel: self) + SynchronousOptions(channel: self) } } diff --git a/Sources/NIOHTTP2/HTTP2StreamID.swift b/Sources/NIOHTTP2/HTTP2StreamID.swift index 5a7917a..625367a 100644 --- a/Sources/NIOHTTP2/HTTP2StreamID.swift +++ b/Sources/NIOHTTP2/HTTP2StreamID.swift @@ -41,13 +41,13 @@ public struct HTTP2StreamID: Sendable { /// Returns a boolean indicating whether this stream ID relates to a client initiated stream. public var isClientInitiated: Bool { - return self.networkStreamID % 2 == 1 + self.networkStreamID % 2 == 1 } /// Returns a boolean indicating whether this stream ID relates to a server initiated stream. public var isServerInitiated: Bool { // Noone may initiate the root stream. - return self.networkStreamID % 2 == 0 && self != .rootStream + self.networkStreamID % 2 == 0 && self != .rootStream } /// Create a ``HTTP2StreamID`` for a specific integer value. @@ -61,7 +61,7 @@ public struct HTTP2StreamID: Sendable { precondition(integerID >= 0, "\(integerID) is not a valid HTTP/2 stream ID value") self.networkStreamID = integerID } - + /// Create a ``HTTP2StreamID`` from a 32-bit value received as part of a frame. /// /// This will ignore the most significant bit of the provided value. @@ -71,41 +71,37 @@ public struct HTTP2StreamID: Sendable { } // MARK:- Equatable conformance for HTTP2StreamID -extension HTTP2StreamID: Equatable { } - +extension HTTP2StreamID: Equatable {} // MARK:- Hashable conformance for HTTP2StreamID -extension HTTP2StreamID: Hashable { } - +extension HTTP2StreamID: Hashable {} // MARK:- Comparable conformance for HTTP2StreamID extension HTTP2StreamID: Comparable { - public static func <(lhs: HTTP2StreamID, rhs: HTTP2StreamID) -> Bool { - return lhs.networkStreamID < rhs.networkStreamID + public static func < (lhs: HTTP2StreamID, rhs: HTTP2StreamID) -> Bool { + lhs.networkStreamID < rhs.networkStreamID } - public static func >(lhs: HTTP2StreamID, rhs: HTTP2StreamID) -> Bool { - return lhs.networkStreamID > rhs.networkStreamID + public static func > (lhs: HTTP2StreamID, rhs: HTTP2StreamID) -> Bool { + lhs.networkStreamID > rhs.networkStreamID } - public static func <=(lhs: HTTP2StreamID, rhs: HTTP2StreamID) -> Bool { - return lhs.networkStreamID <= rhs.networkStreamID + public static func <= (lhs: HTTP2StreamID, rhs: HTTP2StreamID) -> Bool { + lhs.networkStreamID <= rhs.networkStreamID } - public static func >=(lhs: HTTP2StreamID, rhs: HTTP2StreamID) -> Bool { - return lhs.networkStreamID >= rhs.networkStreamID + public static func >= (lhs: HTTP2StreamID, rhs: HTTP2StreamID) -> Bool { + lhs.networkStreamID >= rhs.networkStreamID } } - // MARK:- CustomStringConvertible conformance for HTTP2StreamID extension HTTP2StreamID: CustomStringConvertible { public var description: String { - return "HTTP2StreamID(\(String(describing: self.networkStreamID)))" + "HTTP2StreamID(\(String(describing: self.networkStreamID)))" } } - // MARK:- ExpressibleByIntegerLiteral conformance for HTTP2StreamID extension HTTP2StreamID: ExpressibleByIntegerLiteral { public typealias IntegerLiteralType = Int32 @@ -116,39 +112,35 @@ extension HTTP2StreamID: ExpressibleByIntegerLiteral { } } - // MARK:- Strideable conformance for HTTP2StreamID extension HTTP2StreamID: Strideable { public typealias Stride = Int public func advanced(by n: Stride) -> HTTP2StreamID { - return HTTP2StreamID(self.networkStreamID + Int32(n)) + HTTP2StreamID(self.networkStreamID + Int32(n)) } public func distance(to other: HTTP2StreamID) -> Stride { - return Int(other.networkStreamID - self.networkStreamID) + Int(other.networkStreamID - self.networkStreamID) } } - // MARK:- Helper initializers for integer conversion. -public extension Int { +extension Int { /// Create an Int holding the integer value of this streamID. - init(_ http2StreamID: HTTP2StreamID) { + public init(_ http2StreamID: HTTP2StreamID) { self = Int(http2StreamID.networkStreamID) } } - -public extension Int32 { +extension Int32 { /// Create an Int32 holding the integer value of this streamID. - init(_ http2StreamID: HTTP2StreamID) { + public init(_ http2StreamID: HTTP2StreamID) { self = http2StreamID.networkStreamID } } - -internal extension UInt32 { +extension UInt32 { /// Create a UInt32 holding the integer value of this streamID. init(_ http2StreamID: HTTP2StreamID) { self = UInt32(http2StreamID.networkStreamID) diff --git a/Sources/NIOHTTP2/HTTP2StreamMultiplexer.swift b/Sources/NIOHTTP2/HTTP2StreamMultiplexer.swift index cccd2fc..a1bec2a 100644 --- a/Sources/NIOHTTP2/HTTP2StreamMultiplexer.swift +++ b/Sources/NIOHTTP2/HTTP2StreamMultiplexer.swift @@ -47,7 +47,11 @@ public final class HTTP2StreamMultiplexer: ChannelInboundHandler, ChannelOutboun public func channelRead(context: ChannelHandlerContext, data: NIOAny) { let frame = self.unwrapInboundIn(data) - self.commonStreamMultiplexer.receivedFrame(frame, context: context, multiplexer: .legacy(LegacyOutboundStreamMultiplexer(multiplexer: self))) + self.commonStreamMultiplexer.receivedFrame( + frame, + context: context, + multiplexer: .legacy(LegacyOutboundStreamMultiplexer(multiplexer: self)) + ) } public func channelReadComplete(context: ChannelHandlerContext) { @@ -66,12 +70,12 @@ public final class HTTP2StreamMultiplexer: ChannelInboundHandler, ChannelOutboun case .proceed: context.flush() case .waitForReadsToComplete: - break // flush will be executed on `channelReadComplete` + break // flush will be executed on `channelReadComplete` } } public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { - /* for now just forward */ + // for now just forward context.write(data, promise: promise) } @@ -142,16 +146,28 @@ public final class HTTP2StreamMultiplexer: ChannelInboundHandler, ChannelOutboun /// receiving a `HEADERS` frame from a client. For clients, these are channels created by /// receiving a `PUSH_PROMISE` frame from a server. To initiate a new outbound channel, use /// ``createStreamChannel(promise:_:)-1jk0q``. - @available(*, deprecated, renamed: "init(mode:channel:targetWindowSize:outboundBufferSizeHighWatermark:outboundBufferSizeLowWatermark:inboundStreamInitializer:)") - public convenience init(mode: NIOHTTP2Handler.ParserMode, channel: Channel, targetWindowSize: Int = 65535, inboundStreamStateInitializer: NIOChannelInitializerWithStreamID? = nil) { + @available( + *, + deprecated, + renamed: + "init(mode:channel:targetWindowSize:outboundBufferSizeHighWatermark:outboundBufferSizeLowWatermark:inboundStreamInitializer:)" + ) + public convenience init( + mode: NIOHTTP2Handler.ParserMode, + channel: Channel, + targetWindowSize: Int = 65535, + inboundStreamStateInitializer: NIOChannelInitializerWithStreamID? = nil + ) { // We default to an 8kB outbound buffer size: this is a good trade off for avoiding excessive buffering while ensuring that decent // throughput can be maintained. We use 4kB as the low water mark. - self.init(mode: mode, - channel: channel, - targetWindowSize: targetWindowSize, - outboundBufferSizeHighWatermark: 8192, - outboundBufferSizeLowWatermark: 4096, - inboundStreamStateInitializer: .includesStreamID(inboundStreamStateInitializer)) + self.init( + mode: mode, + channel: channel, + targetWindowSize: targetWindowSize, + outboundBufferSizeHighWatermark: 8192, + outboundBufferSizeLowWatermark: 4096, + inboundStreamStateInitializer: .includesStreamID(inboundStreamStateInitializer) + ) } /// Create a new ``HTTP2StreamMultiplexer``. @@ -171,18 +187,22 @@ public final class HTTP2StreamMultiplexer: ChannelInboundHandler, ChannelOutboun /// receiving a `HEADERS` frame from a client. For clients, these are channels created by /// receiving a `PUSH_PROMISE` frame from a server. To initiate a new outbound channel, use /// ``createStreamChannel(promise:_:)-1jk0q``. - public convenience init(mode: NIOHTTP2Handler.ParserMode, - channel: Channel, - targetWindowSize: Int = 65535, - outboundBufferSizeHighWatermark: Int = 8196, - outboundBufferSizeLowWatermark: Int = 4092, - inboundStreamInitializer: NIOChannelInitializer?) { - self.init(mode: mode, - channel: channel, - targetWindowSize: targetWindowSize, - outboundBufferSizeHighWatermark: outboundBufferSizeHighWatermark, - outboundBufferSizeLowWatermark: outboundBufferSizeLowWatermark, - inboundStreamStateInitializer: .excludesStreamID(inboundStreamInitializer)) + public convenience init( + mode: NIOHTTP2Handler.ParserMode, + channel: Channel, + targetWindowSize: Int = 65535, + outboundBufferSizeHighWatermark: Int = 8196, + outboundBufferSizeLowWatermark: Int = 4092, + inboundStreamInitializer: NIOChannelInitializer? + ) { + self.init( + mode: mode, + channel: channel, + targetWindowSize: targetWindowSize, + outboundBufferSizeHighWatermark: outboundBufferSizeHighWatermark, + outboundBufferSizeLowWatermark: outboundBufferSizeLowWatermark, + inboundStreamStateInitializer: .excludesStreamID(inboundStreamInitializer) + ) } /// Create a new ``HTTP2StreamMultiplexer``. @@ -200,27 +220,38 @@ public final class HTTP2StreamMultiplexer: ChannelInboundHandler, ChannelOutboun /// receiving a `HEADERS` frame from a client. For clients, these are channels created by /// receiving a `PUSH_PROMISE` frame from a server. To initiate a new outbound channel, use /// ``createStreamChannel(promise:_:)-1jk0q``. - @available(*, deprecated, renamed: "init(mode:channel:targetWindowSize:outboundBufferSizeHighWatermark:outboundBufferSizeLowWatermark:inboundStreamInitializer:)") - public convenience init(mode: NIOHTTP2Handler.ParserMode, - channel: Channel, - targetWindowSize: Int = 65535, - outboundBufferSizeHighWatermark: Int, - outboundBufferSizeLowWatermark: Int, - inboundStreamStateInitializer: NIOChannelInitializerWithStreamID? = nil) { - self.init(mode: mode, - channel: channel, - targetWindowSize: targetWindowSize, - outboundBufferSizeHighWatermark: outboundBufferSizeHighWatermark, - outboundBufferSizeLowWatermark: outboundBufferSizeLowWatermark, - inboundStreamStateInitializer: .includesStreamID(inboundStreamStateInitializer)) + @available( + *, + deprecated, + renamed: + "init(mode:channel:targetWindowSize:outboundBufferSizeHighWatermark:outboundBufferSizeLowWatermark:inboundStreamInitializer:)" + ) + public convenience init( + mode: NIOHTTP2Handler.ParserMode, + channel: Channel, + targetWindowSize: Int = 65535, + outboundBufferSizeHighWatermark: Int, + outboundBufferSizeLowWatermark: Int, + inboundStreamStateInitializer: NIOChannelInitializerWithStreamID? = nil + ) { + self.init( + mode: mode, + channel: channel, + targetWindowSize: targetWindowSize, + outboundBufferSizeHighWatermark: outboundBufferSizeHighWatermark, + outboundBufferSizeLowWatermark: outboundBufferSizeLowWatermark, + inboundStreamStateInitializer: .includesStreamID(inboundStreamStateInitializer) + ) } - private init(mode: NIOHTTP2Handler.ParserMode, - channel: Channel, - targetWindowSize: Int = 65535, - outboundBufferSizeHighWatermark: Int, - outboundBufferSizeLowWatermark: Int, - inboundStreamStateInitializer: MultiplexerAbstractChannel.InboundStreamStateInitializer) { + private init( + mode: NIOHTTP2Handler.ParserMode, + channel: Channel, + targetWindowSize: Int = 65535, + outboundBufferSizeHighWatermark: Int, + outboundBufferSizeLowWatermark: Int, + inboundStreamStateInitializer: MultiplexerAbstractChannel.InboundStreamStateInitializer + ) { self.channel = channel self.commonStreamMultiplexer = HTTP2CommonInboundStreamMultiplexer( @@ -234,8 +265,6 @@ public final class HTTP2StreamMultiplexer: ChannelInboundHandler, ChannelOutboun } } - - extension HTTP2StreamMultiplexer { /// Create a new `Channel` for a new stream initiated by this peer. /// @@ -249,8 +278,14 @@ extension HTTP2StreamMultiplexer { /// failed if an error occurs. /// - streamStateInitializer: A callback that will be invoked to allow you to configure the /// `ChannelPipeline` for the newly created channel. - public func createStreamChannel(promise: EventLoopPromise?, _ streamStateInitializer: @escaping NIOChannelInitializer) { - let sendableView = HTTP2StreamMultiplexer.SendableView(http2StreamMultiplexer: self, eventLoop: self.channel.eventLoop) + public func createStreamChannel( + promise: EventLoopPromise?, + _ streamStateInitializer: @escaping NIOChannelInitializer + ) { + let sendableView = HTTP2StreamMultiplexer.SendableView( + http2StreamMultiplexer: self, + eventLoop: self.channel.eventLoop + ) if self.channel.eventLoop.inEventLoop { sendableView.createStreamChannel(promise: promise, streamStateInitializer) } else { @@ -289,9 +324,19 @@ extension HTTP2StreamMultiplexer { /// failed if an error occurs. /// - streamStateInitializer: A callback that will be invoked to allow you to configure the /// `ChannelPipeline` for the newly created channel. - @available(*, deprecated, message: "The signature of 'streamStateInitializer' has changed to '(Channel) -> EventLoopFuture'") - public func createStreamChannel(promise: EventLoopPromise?, _ streamStateInitializer: @escaping NIOChannelInitializerWithStreamID) { - let sendableView = HTTP2StreamMultiplexer.SendableView(http2StreamMultiplexer: self, eventLoop: self.channel.eventLoop) + @available( + *, + deprecated, + message: "The signature of 'streamStateInitializer' has changed to '(Channel) -> EventLoopFuture'" + ) + public func createStreamChannel( + promise: EventLoopPromise?, + _ streamStateInitializer: @escaping NIOChannelInitializerWithStreamID + ) { + let sendableView = HTTP2StreamMultiplexer.SendableView( + http2StreamMultiplexer: self, + eventLoop: self.channel.eventLoop + ) sendableView.createStreamChannel(promise: promise, streamStateInitializer) } } @@ -305,28 +350,45 @@ extension HTTP2StreamMultiplexer { let http2StreamMultiplexer: HTTP2StreamMultiplexer let eventLoop: EventLoop - func createStreamChannel(promise: EventLoopPromise?, _ streamStateInitializer: @escaping NIOChannelInitializer) { + func createStreamChannel( + promise: EventLoopPromise?, + _ streamStateInitializer: @escaping NIOChannelInitializer + ) { // Always create streams channels on the next event loop tick. This avoids re-entrancy // issues where handlers interposed between the two HTTP/2 handlers could create streams // in channel active which become activated twice. self.eventLoop.execute { - self.http2StreamMultiplexer.commonStreamMultiplexer.createStreamChannel(multiplexer: .legacy(LegacyOutboundStreamMultiplexer(multiplexer: self.http2StreamMultiplexer)), promise: promise, streamStateInitializer) + self.http2StreamMultiplexer.commonStreamMultiplexer.createStreamChannel( + multiplexer: .legacy(LegacyOutboundStreamMultiplexer(multiplexer: self.http2StreamMultiplexer)), + promise: promise, + streamStateInitializer + ) } } - @available(*, deprecated, message: "The signature of 'streamStateInitializer' has changed to '(Channel) -> EventLoopFuture'") - func createStreamChannel(promise: EventLoopPromise?, _ streamStateInitializer: @escaping NIOChannelInitializerWithStreamID) { + @available( + *, + deprecated, + message: "The signature of 'streamStateInitializer' has changed to '(Channel) -> EventLoopFuture'" + ) + func createStreamChannel( + promise: EventLoopPromise?, + _ streamStateInitializer: @escaping NIOChannelInitializerWithStreamID + ) { // Always create streams channels on the next event loop tick. This avoids re-entrancy // issues where handlers interposed between the two HTTP/2 handlers could create streams // in channel active which become activated twice. self.eventLoop.execute { - self.http2StreamMultiplexer.commonStreamMultiplexer.createStreamChannel(multiplexer: .legacy(LegacyOutboundStreamMultiplexer(multiplexer: self.http2StreamMultiplexer)), promise: promise, streamStateInitializer) + self.http2StreamMultiplexer.commonStreamMultiplexer.createStreamChannel( + multiplexer: .legacy(LegacyOutboundStreamMultiplexer(multiplexer: self.http2StreamMultiplexer)), + promise: promise, + streamStateInitializer + ) } } } } - // MARK:- Child to parent calls extension HTTP2StreamMultiplexer { internal func childChannelClosed(streamID: HTTP2StreamID) { diff --git a/Sources/NIOHTTP2/HTTP2ToHTTP1Codec.swift b/Sources/NIOHTTP2/HTTP2ToHTTP1Codec.swift index 2952a28..74302b4 100644 --- a/Sources/NIOHTTP2/HTTP2ToHTTP1Codec.swift +++ b/Sources/NIOHTTP2/HTTP2ToHTTP1Codec.swift @@ -13,17 +13,17 @@ //===----------------------------------------------------------------------===// import NIOCore -import NIOHTTP1 import NIOHPACK +import NIOHTTP1 // MARK: - Client -fileprivate struct BaseClientCodec { +private struct BaseClientCodec { private let protocolString: String private let normalizeHTTPHeaders: Bool private var headerStateMachine: HTTP2HeadersStateMachine = HTTP2HeadersStateMachine(mode: .client) - + private var outgoingHTTP1RequestHead: HTTPRequestHead? /// Initializes a `BaseClientCodec`. @@ -46,13 +46,15 @@ fileprivate struct BaseClientCodec { } } - mutating func processInboundData(_ data: HTTP2Frame.FramePayload) throws -> (first: HTTPClientResponsePart?, second: HTTPClientResponsePart?) { + mutating func processInboundData( + _ data: HTTP2Frame.FramePayload + ) throws -> (first: HTTPClientResponsePart?, second: HTTPClientResponsePart?) { switch data { case .headers(let headerContent): switch try self.headerStateMachine.newHeaders(block: headerContent.headers) { case .trailer: return (first: .end(HTTPHeaders(regularHeadersFrom: headerContent.headers)), second: nil) - + case .informationalResponseHead: return (first: .head(try HTTPResponseHead(http2HeaderBlock: headerContent.headers)), second: nil) @@ -72,7 +74,7 @@ fileprivate struct BaseClientCodec { second = .end(nil) } return (first: first, second: second) - + case .requestHead: preconditionFailure("A client can not receive request heads") } @@ -91,28 +93,42 @@ fileprivate struct BaseClientCodec { } } return (first: first, second: second) - case .alternativeService, .rstStream, .priority, .windowUpdate, .settings, .pushPromise, .ping, .goAway, .origin: + case .alternativeService, .rstStream, .priority, .windowUpdate, .settings, .pushPromise, .ping, .goAway, + .origin: // These don't have an HTTP/1 equivalent, so let's drop them. return (first: nil, second: nil) } } - mutating func processOutboundData(_ data: HTTPClientRequestPart, allocator: ByteBufferAllocator) throws -> HTTP2Frame.FramePayload { + mutating func processOutboundData( + _ data: HTTPClientRequestPart, + allocator: ByteBufferAllocator + ) throws -> HTTP2Frame.FramePayload { switch data { case .head(let head): precondition(self.outgoingHTTP1RequestHead == nil, "Only a single HTTP request allowed per HTTP2 stream") let h1Headers = try HTTPHeaders(requestHead: head, protocolString: self.protocolString) self.outgoingHTTP1RequestHead = head - let headerContent = HTTP2Frame.FramePayload.Headers(headers: HPACKHeaders(httpHeaders: h1Headers, - normalizeHTTPHeaders: self.normalizeHTTPHeaders)) + let headerContent = HTTP2Frame.FramePayload.Headers( + headers: HPACKHeaders( + httpHeaders: h1Headers, + normalizeHTTPHeaders: self.normalizeHTTPHeaders + ) + ) return .headers(headerContent) case .body(let body): return .data(HTTP2Frame.FramePayload.Data(data: body)) case .end(let trailers): if let trailers = trailers { - return .headers(.init(headers: HPACKHeaders(httpHeaders: trailers, - normalizeHTTPHeaders: self.normalizeHTTPHeaders), - endStream: true)) + return .headers( + .init( + headers: HPACKHeaders( + httpHeaders: trailers, + normalizeHTTPHeaders: self.normalizeHTTPHeaders + ), + endStream: true + ) + ) } else { return .data(.init(data: .byteBuffer(allocator.buffer(capacity: 0)), endStream: true)) } @@ -183,7 +199,10 @@ public final class HTTP2ToHTTP1ClientCodec: ChannelInboundHandler, ChannelOutbou let responsePart = self.unwrapOutboundIn(data) do { - let transformedPayload = try self.baseCodec.processOutboundData(responsePart, allocator: context.channel.allocator) + let transformedPayload = try self.baseCodec.processOutboundData( + responsePart, + allocator: context.channel.allocator + ) let part = HTTP2Frame(streamID: self.streamID, payload: transformedPayload) context.write(self.wrapOutboundOut(part), promise: promise) } catch { @@ -248,7 +267,10 @@ public final class HTTP2FramePayloadToHTTP1ClientCodec: ChannelInboundHandler, C let requestPart = self.unwrapOutboundIn(data) do { - let transformedPayload = try self.baseCodec.processOutboundData(requestPart, allocator: context.channel.allocator) + let transformedPayload = try self.baseCodec.processOutboundData( + requestPart, + allocator: context.channel.allocator + ) context.write(self.wrapOutboundOut(transformedPayload), promise: promise) } catch { promise?.fail(error) @@ -259,7 +281,7 @@ public final class HTTP2FramePayloadToHTTP1ClientCodec: ChannelInboundHandler, C // MARK: - Server -fileprivate struct BaseServerCodec { +private struct BaseServerCodec { private let normalizeHTTPHeaders: Bool private var headerStateMachine: HTTP2HeadersStateMachine = HTTP2HeadersStateMachine(mode: .server) @@ -267,13 +289,18 @@ fileprivate struct BaseServerCodec { self.normalizeHTTPHeaders = normalizeHTTPHeaders } - mutating func processInboundData(_ data: HTTP2Frame.FramePayload) throws -> (first: HTTPServerRequestPart?, second: HTTPServerRequestPart?) { + mutating func processInboundData( + _ data: HTTP2Frame.FramePayload + ) throws -> (first: HTTPServerRequestPart?, second: HTTPServerRequestPart?) { switch data { case .headers(let headerContent): if case .trailer = try self.headerStateMachine.newHeaders(block: headerContent.headers) { return (first: .end(HTTPHeaders(regularHeadersFrom: headerContent.headers)), second: nil) } else { - let reqHead = try HTTPRequestHead(http2HeaderBlock: headerContent.headers, isEndStream: headerContent.endStream) + let reqHead = try HTTPRequestHead( + http2HeaderBlock: headerContent.headers, + isEndStream: headerContent.endStream + ) let first = HTTPServerRequestPart.head(reqHead) var second: HTTPServerRequestPart? = nil @@ -302,21 +329,34 @@ fileprivate struct BaseServerCodec { } } - mutating func processOutboundData(_ data: HTTPServerResponsePart, allocator: ByteBufferAllocator) -> HTTP2Frame.FramePayload { + mutating func processOutboundData( + _ data: HTTPServerResponsePart, + allocator: ByteBufferAllocator + ) -> HTTP2Frame.FramePayload { switch data { case .head(let head): let h1 = HTTPHeaders(responseHead: head) - let payload = HTTP2Frame.FramePayload.Headers(headers: HPACKHeaders(httpHeaders: h1, - normalizeHTTPHeaders: self.normalizeHTTPHeaders)) + let payload = HTTP2Frame.FramePayload.Headers( + headers: HPACKHeaders( + httpHeaders: h1, + normalizeHTTPHeaders: self.normalizeHTTPHeaders + ) + ) return .headers(payload) case .body(let body): let payload = HTTP2Frame.FramePayload.Data(data: body) return .data(payload) case .end(let trailers): if let trailers = trailers { - return .headers(.init(headers: HPACKHeaders(httpHeaders: trailers, - normalizeHTTPHeaders: self.normalizeHTTPHeaders), - endStream: true)) + return .headers( + .init( + headers: HPACKHeaders( + httpHeaders: trailers, + normalizeHTTPHeaders: self.normalizeHTTPHeaders + ), + endStream: true + ) + ) } else { return .data(.init(data: .byteBuffer(allocator.buffer(capacity: 0)), endStream: true)) } @@ -324,7 +364,6 @@ fileprivate struct BaseServerCodec { } } - /// A simple channel handler that translates HTTP/2 concepts into HTTP/1 data types, /// and vice versa, for use on the server side. /// @@ -436,9 +475,9 @@ public final class HTTP2FramePayloadToHTTP1ServerCodec: ChannelInboundHandler, C } } -private extension HTTPMethod { +extension HTTPMethod { /// Create a `HTTPMethod` from the string representation of that method. - init(methodString: String) { + fileprivate init(methodString: String) { switch methodString { case "GET": self = .GET @@ -514,7 +553,7 @@ private extension HTTPMethod { // MARK:- Methods for creating `HTTPRequestHead`/`HTTPResponseHead` objects from // header blocks generated by the HTTP/2 layer. -internal extension HTTPRequestHead { +extension HTTPRequestHead { /// Create a `HTTPRequestHead` from the header block. init(http2HeaderBlock headers: HPACKHeaders, isEndStream: Bool) throws { // A request head should have only up to four psuedo-headers. @@ -567,8 +606,7 @@ internal extension HTTPRequestHead { } } - -internal extension HTTPResponseHead { +extension HTTPResponseHead { /// Create a `HTTPResponseHead` from the header block. Use this for informational responses. init(http2HeaderBlock headers: HPACKHeaders) throws { // A response head should have only one psuedo-header. We strip it off. @@ -579,15 +617,18 @@ internal extension HTTPResponseHead { let status = HTTPResponseStatus(statusCode: integerStatus) self.init(version: .init(major: 2, minor: 0), status: status, headers: HTTPHeaders(regularHeadersFrom: headers)) } - + /// Create a `HTTPResponseHead` from the header block. Use this for non-informational responses. init(http2HeaderBlock headers: HPACKHeaders, requestHead: HTTPRequestHead, endStream: Bool) throws { try self.init(http2HeaderBlock: headers) - + // NOTE: We don't need to create the header array here ourselves. The HTTP/1 response // headers, will not contain a :status field, but may contain a "Transfer-Encoding" // field. For this reason the default allocation works great for us. - if self.shouldAddContentLengthOrTransferEncodingHeaderToResponse(hpackHeaders: headers, requestHead: requestHead) { + if self.shouldAddContentLengthOrTransferEncodingHeaderToResponse( + hpackHeaders: headers, + requestHead: requestHead + ) { if endStream { self.headers.add(name: "content-length", value: "0") } else { @@ -595,9 +636,10 @@ internal extension HTTPResponseHead { } } } - + private func shouldAddContentLengthOrTransferEncodingHeaderToResponse( - hpackHeaders: HPACKHeaders, requestHead: HTTPRequestHead + hpackHeaders: HPACKHeaders, + requestHead: HTTPRequestHead ) -> Bool { let statusCode = self.status.code return !(100..<200).contains(statusCode) @@ -605,11 +647,10 @@ internal extension HTTPResponseHead { && statusCode != 304 && requestHead.method != .HEAD && requestHead.method != .CONNECT - && !hpackHeaders.contains(name: "content-length") // compare on h2 headers - for speed + && !hpackHeaders.contains(name: "content-length") // compare on h2 headers - for speed } } - extension HPACKHeaders { /// Grabs a pseudo-header from a header block. Does not remove it. /// @@ -638,7 +679,6 @@ extension HPACKHeaders { } } - extension HTTPHeaders { fileprivate init(requestHead: HTTPRequestHead, protocolString: String) throws { // To avoid too much allocation we create an array first, and then initialize the HTTPHeaders from it. @@ -686,7 +726,9 @@ extension HTTPHeaders { var newHeaders: [(String, String)] = [] newHeaders.reserveCapacity(responseHead.headers.count + 1) newHeaders.append((":status", String(responseHead.status.code))) - responseHead.headers.forEach { newHeaders.append(($0.name, $0.value)) } + for responseHeader in responseHead.headers { + newHeaders.append((responseHeader.name, responseHeader.value)) + } self.init(newHeaders) } @@ -700,7 +742,6 @@ extension HTTPHeaders { } } - extension Array where Element == (String, String) { mutating func appendRegularHeaders(from headers: HPACKHeaders) { for (name, value, _) in headers { diff --git a/Sources/NIOHTTP2/HTTP2UserEvents.swift b/Sources/NIOHTTP2/HTTP2UserEvents.swift index b80cd6f..21f4659 100644 --- a/Sources/NIOHTTP2/HTTP2UserEvents.swift +++ b/Sources/NIOHTTP2/HTTP2UserEvents.swift @@ -35,8 +35,7 @@ public struct StreamClosedEvent: Sendable { } } -extension StreamClosedEvent: Hashable { } - +extension StreamClosedEvent: Hashable {} /// A ``NIOHTTP2WindowUpdatedEvent`` is fired whenever a flow control window is changed. /// This includes changes on the connection flow control window, which is signalled by @@ -49,7 +48,7 @@ public struct NIOHTTP2WindowUpdatedEvent { /// The new inbound window size for this stream, if any. May be nil if this stream is half-closed. public var inboundWindowSize: Int? { get { - return self._inboundWindowSize.map { Int($0) } + self._inboundWindowSize.map { Int($0) } } set { self._inboundWindowSize = newValue.map { Int32($0) } @@ -59,7 +58,7 @@ public struct NIOHTTP2WindowUpdatedEvent { /// The new outbound window size for this stream, if any. May be nil if this stream is half-closed. public var outboundWindowSize: Int? { get { - return self._outboundWindowSize.map { Int($0) } + self._outboundWindowSize.map { Int($0) } } set { self._outboundWindowSize = newValue.map { Int32($0) } @@ -83,8 +82,7 @@ public struct NIOHTTP2WindowUpdatedEvent { } } -extension NIOHTTP2WindowUpdatedEvent: Hashable { } - +extension NIOHTTP2WindowUpdatedEvent: Hashable {} /// A ``NIOHTTP2StreamCreatedEvent`` is fired whenever a HTTP/2 stream is created. public struct NIOHTTP2StreamCreatedEvent { @@ -110,7 +108,7 @@ public struct NIOHTTP2StreamCreatedEvent { } } -extension NIOHTTP2StreamCreatedEvent: Hashable { } +extension NIOHTTP2StreamCreatedEvent: Hashable {} /// A ``NIOHTTP2BulkStreamWindowChangeEvent`` is fired whenever all of the remote flow control windows for a given stream have been changed. /// @@ -125,4 +123,4 @@ public struct NIOHTTP2BulkStreamWindowChangeEvent { } } -extension NIOHTTP2BulkStreamWindowChangeEvent: Hashable { } +extension NIOHTTP2BulkStreamWindowChangeEvent: Hashable {} diff --git a/Sources/NIOHTTP2/InboundEventBuffer.swift b/Sources/NIOHTTP2/InboundEventBuffer.swift index 80193cf..a4e8e4b 100644 --- a/Sources/NIOHTTP2/InboundEventBuffer.swift +++ b/Sources/NIOHTTP2/InboundEventBuffer.swift @@ -53,13 +53,12 @@ class InboundEventBuffer { } } - // MARK:- Sequence conformance extension InboundEventBuffer: Sequence { typealias Element = BufferedHTTP2UserEvent func makeIterator() -> InboundEventBufferIterator { - return InboundEventBufferIterator(self) + InboundEventBufferIterator(self) } struct InboundEventBufferIterator: IteratorProtocol { @@ -81,10 +80,9 @@ extension InboundEventBuffer: Sequence { } } - // MARK:- CustomStringConvertible conformance extension InboundEventBuffer: CustomStringConvertible { var description: String { - return "InboundEventBuffer { \(self.buffer) }" + "InboundEventBuffer { \(self.buffer) }" } } diff --git a/Sources/NIOHTTP2/MultiplexerAbstractChannel.swift b/Sources/NIOHTTP2/MultiplexerAbstractChannel.swift index 1117980..7e77b37 100644 --- a/Sources/NIOHTTP2/MultiplexerAbstractChannel.swift +++ b/Sources/NIOHTTP2/MultiplexerAbstractChannel.swift @@ -28,35 +28,41 @@ struct MultiplexerAbstractChannel { @usableFromInline private(set) var baseChannel: HTTP2StreamChannel @usableFromInline - init(allocator: ByteBufferAllocator, - parent: Channel, - multiplexer: HTTP2StreamChannel.OutboundStreamMultiplexer, - streamID: HTTP2StreamID?, - targetWindowSize: Int32, - outboundBytesHighWatermark: Int, - outboundBytesLowWatermark: Int, - inboundStreamStateInitializer: InboundStreamStateInitializer) { + init( + allocator: ByteBufferAllocator, + parent: Channel, + multiplexer: HTTP2StreamChannel.OutboundStreamMultiplexer, + streamID: HTTP2StreamID?, + targetWindowSize: Int32, + outboundBytesHighWatermark: Int, + outboundBytesLowWatermark: Int, + inboundStreamStateInitializer: InboundStreamStateInitializer + ) { switch inboundStreamStateInitializer { case .includesStreamID: assert(streamID != nil) - self.baseChannel = .init(allocator: allocator, - parent: parent, - multiplexer: multiplexer, - streamID: streamID, - targetWindowSize: targetWindowSize, - outboundBytesHighWatermark: outboundBytesHighWatermark, - outboundBytesLowWatermark: outboundBytesLowWatermark, - streamDataType: .frame) + self.baseChannel = .init( + allocator: allocator, + parent: parent, + multiplexer: multiplexer, + streamID: streamID, + targetWindowSize: targetWindowSize, + outboundBytesHighWatermark: outboundBytesHighWatermark, + outboundBytesLowWatermark: outboundBytesLowWatermark, + streamDataType: .frame + ) case .excludesStreamID, .returnsAny: - self.baseChannel = .init(allocator: allocator, - parent: parent, - multiplexer: multiplexer, - streamID: streamID, - targetWindowSize: targetWindowSize, - outboundBytesHighWatermark: outboundBytesHighWatermark, - outboundBytesLowWatermark: outboundBytesLowWatermark, - streamDataType: .framePayload) + self.baseChannel = .init( + allocator: allocator, + parent: parent, + multiplexer: multiplexer, + streamID: streamID, + targetWindowSize: targetWindowSize, + outboundBytesHighWatermark: outboundBytesHighWatermark, + outboundBytesLowWatermark: outboundBytesLowWatermark, + streamDataType: .framePayload + ) } } } @@ -73,21 +79,21 @@ extension MultiplexerAbstractChannel { // MARK: API for HTTP2StreamMultiplexer extension MultiplexerAbstractChannel { var streamID: HTTP2StreamID? { - return self.baseChannel.streamID + self.baseChannel.streamID } @usableFromInline var channelID: ObjectIdentifier { - return ObjectIdentifier(self.baseChannel) + ObjectIdentifier(self.baseChannel) } var inList: Bool { - return self.baseChannel.inList + self.baseChannel.inList } var streamChannelListNode: StreamChannelListNode { get { - return self.baseChannel.streamChannelListNode + self.baseChannel.streamChannelListNode } nonmutating set { self.baseChannel.streamChannelListNode = newValue @@ -108,7 +114,9 @@ extension MultiplexerAbstractChannel { func configureInboundStream(initializer: InboundStreamStateInitializer, promise: EventLoopPromise?) { switch initializer { case .includesStreamID, .excludesStreamID: - preconditionFailure("Configuration with a supplied `Any` promise is not supported with this initializer type.") + preconditionFailure( + "Configuration with a supplied `Any` promise is not supported with this initializer type." + ) case .returnsAny(let initializer): self.baseChannel.configure(initializer: initializer, userPromise: promise) } @@ -126,7 +134,10 @@ extension MultiplexerAbstractChannel { // used for async multiplexer @usableFromInline - func configure(initializer: @escaping NIOChannelInitializerWithOutput, userPromise promise: EventLoopPromise?) { + func configure( + initializer: @escaping NIOChannelInitializerWithOutput, + userPromise promise: EventLoopPromise? + ) { self.baseChannel.configure(initializer: initializer, userPromise: promise) } @@ -173,8 +184,8 @@ extension MultiplexerAbstractChannel { extension MultiplexerAbstractChannel: Equatable { @inlinable - static func ==(lhs: MultiplexerAbstractChannel, rhs: MultiplexerAbstractChannel) -> Bool { - return lhs.baseChannel === rhs.baseChannel + static func == (lhs: MultiplexerAbstractChannel, rhs: MultiplexerAbstractChannel) -> Bool { + lhs.baseChannel === rhs.baseChannel } } diff --git a/Sources/NIOHTTP2/StreamChannelFlowController.swift b/Sources/NIOHTTP2/StreamChannelFlowController.swift index dd4a782..f620369 100644 --- a/Sources/NIOHTTP2/StreamChannelFlowController.swift +++ b/Sources/NIOHTTP2/StreamChannelFlowController.swift @@ -41,15 +41,13 @@ struct StreamChannelFlowController { } } - extension StreamChannelFlowController { /// Whether the `HTTP2StreamChannel` should be writable. var isWritable: Bool { - return self.watermarkedController.isWritable && self.parentIsWritable + self.watermarkedController.isWritable && self.parentIsWritable } } - extension StreamChannelFlowController { /// A value representing a change in writability. enum WritabilityChange: Hashable { @@ -61,29 +59,29 @@ extension StreamChannelFlowController { } } - extension StreamChannelFlowController { /// Notifies the flow controller that we have queued some bytes for writing to the network. mutating func bufferedBytes(_ bufferedBytes: Int) -> WritabilityChange { - return self.mayChangeWritability { + self.mayChangeWritability { $0.watermarkedController.bufferedBytes(bufferedBytes) } } /// Notifies the flow controller that we have successfully written some bytes to the network. mutating func wroteBytes(_ writtenBytes: Int) -> WritabilityChange { - return self.mayChangeWritability { + self.mayChangeWritability { $0.watermarkedController.wroteBytes(writtenBytes) } } mutating func parentWritabilityChanged(_ newWritability: Bool) -> WritabilityChange { - return self.mayChangeWritability { + self.mayChangeWritability { $0.parentIsWritable = newWritability } } - private mutating func mayChangeWritability(_ body: (inout StreamChannelFlowController) -> Void) -> WritabilityChange { + private mutating func mayChangeWritability(_ body: (inout StreamChannelFlowController) -> Void) -> WritabilityChange + { let wasWritable = self.isWritable body(&self) let isWritable = self.isWritable @@ -96,12 +94,10 @@ extension StreamChannelFlowController { } } - -extension StreamChannelFlowController: Equatable { } - +extension StreamChannelFlowController: Equatable {} extension StreamChannelFlowController: CustomDebugStringConvertible { var debugDescription: String { - return "StreamChannelFlowController(parentIsWritable: \(self.parentIsWritable), watermarkedController: \(self.watermarkedController.debugDescription))" + "StreamChannelFlowController(parentIsWritable: \(self.parentIsWritable), watermarkedController: \(self.watermarkedController.debugDescription))" } } diff --git a/Sources/NIOHTTP2/StreamChannelList.swift b/Sources/NIOHTTP2/StreamChannelList.swift index 87dae99..e8e1110 100644 --- a/Sources/NIOHTTP2/StreamChannelList.swift +++ b/Sources/NIOHTTP2/StreamChannelList.swift @@ -12,7 +12,6 @@ // //===----------------------------------------------------------------------===// - /// A linked list for storing MultiplexerAbstractChannels. /// /// Note that while this object *could* conform to `Sequence`, there is minimal value in doing @@ -34,10 +33,9 @@ struct StreamChannelListNode { fileprivate var state: ListState = .notInList - internal init() { } + internal init() {} } - extension StreamChannelList { /// Append an element to the linked list. mutating func append(_ element: MultiplexerAbstractChannel) { @@ -80,11 +78,10 @@ extension StreamChannelList { } mutating func removeAll() { - while self.removeFirst() != nil { } + while self.removeFirst() != nil {} } } - // MARK:- IntrusiveLinkedListElement helpers. extension HTTP2StreamChannel { /// Whether this element is currently in a list. diff --git a/Sources/NIOHTTP2/StreamMap.swift b/Sources/NIOHTTP2/StreamMap.swift index b3af050..cc2fb9f 100644 --- a/Sources/NIOHTTP2/StreamMap.swift +++ b/Sources/NIOHTTP2/StreamMap.swift @@ -14,7 +14,7 @@ import NIOCore -fileprivate let binarySearchThreshold = 200 +private let binarySearchThreshold = 200 /// StreamMap is a specialized data structure built to optimise lookups of per-stream state. /// @@ -75,7 +75,10 @@ struct StreamMap { } /// Calls the closure with the given element, if it is present. Returns nil if the element is not present. - mutating func modify(streamID: HTTP2StreamID, _ body: (inout Element) throws -> ReturnType) rethrows -> ReturnType? { + mutating func modify( + streamID: HTTP2StreamID, + _ body: (inout Element) throws -> ReturnType + ) rethrows -> ReturnType? { if streamID.mayBeInitiatedBy(.client) { guard let index = self.clientInitiated.findIndexForStreamID(streamID) else { return nil @@ -139,9 +142,11 @@ struct StreamMap { /// /// This helper can turn a complex operation that involves repeated resizing of the base objects into a much faster one that also avoids /// allocation. - mutating func dropDataWithStreamIDGreaterThan(_ streamID: HTTP2StreamID, - initiatedBy role: HTTP2ConnectionStateMachine.ConnectionRole, - _ block: (CircularBuffer.SubSequence) -> Void) { + mutating func dropDataWithStreamIDGreaterThan( + _ streamID: HTTP2StreamID, + initiatedBy role: HTTP2ConnectionStateMachine.ConnectionRole, + _ block: (CircularBuffer.SubSequence) -> Void + ) { switch role { case .client: let index = self.clientInitiated.findIndexForFirstStreamIDLargerThan(streamID) @@ -155,7 +160,7 @@ struct StreamMap { } } -internal extension StreamMap where Element == HTTP2StreamStateMachine { +extension StreamMap where Element == HTTP2StreamStateMachine { // This function exists as a performance optimisation: we can keep track of the index and where we are, and // thereby avoid searching the array twice. // @@ -173,12 +178,13 @@ internal extension StreamMap where Element == HTTP2StreamStateMachine { } } - // This function exists as a performance optimisation: we can keep track of the index and where we are, and // thereby avoid searching the array twice. - mutating func transformOrCreateAutoClose(streamID: HTTP2StreamID, - _ creator: () throws -> Element, - _ transformer: (inout Element) -> T) rethrows -> T? { + mutating func transformOrCreateAutoClose( + streamID: HTTP2StreamID, + _ creator: () throws -> Element, + _ transformer: (inout Element) -> T + ) rethrows -> T? { if streamID.mayBeInitiatedBy(.client) { return try self.clientInitiated.transformOrCreateAutoClose(streamID: streamID, creator, transformer) } else { @@ -299,7 +305,10 @@ extension CircularBuffer where Element == HTTP2StreamStateMachine { /// - modifier: A block that will modify the contained value in the /// map, if there is one present. /// - Returns: The return value of the block or `nil` if the element was not in the map. - mutating func autoClosingTransform(streamID: HTTP2StreamID, _ modifier: (inout Element) -> ResultType) -> ResultType? { + mutating func autoClosingTransform( + streamID: HTTP2StreamID, + _ modifier: (inout Element) -> ResultType + ) -> ResultType? { guard let index = self.findIndexForStreamID(streamID) else { return nil } @@ -309,9 +318,11 @@ extension CircularBuffer where Element == HTTP2StreamStateMachine { // This function exists as a performance optimisation: we can keep track of the index and where we are, and // thereby avoid searching the array twice. - mutating func transformOrCreateAutoClose(streamID: HTTP2StreamID, - _ creator: () throws -> Element, - _ transformer: (inout Element) -> ResultType) rethrows -> ResultType? { + mutating func transformOrCreateAutoClose( + streamID: HTTP2StreamID, + _ creator: () throws -> Element, + _ transformer: (inout Element) -> ResultType + ) rethrows -> ResultType? { if let index = self.findIndexForStreamID(streamID) { return self.modifyAutoClose(index: index, transformer) } else { @@ -321,7 +332,10 @@ extension CircularBuffer where Element == HTTP2StreamStateMachine { } } - private mutating func modifyAutoClose(index: Index, _ modifier: (inout Element) -> ResultType) -> ResultType { + private mutating func modifyAutoClose( + index: Index, + _ modifier: (inout Element) -> ResultType + ) -> ResultType { let (result, closed): (ResultType, HTTP2StreamStateMachine.StreamClosureState) = self.modify(index) { let result = modifier(&$0) return (result, $0.closed) diff --git a/Sources/NIOHTTP2/StreamStateMachine.swift b/Sources/NIOHTTP2/StreamStateMachine.swift index 35e1289..5b38393 100644 --- a/Sources/NIOHTTP2/StreamStateMachine.swift +++ b/Sources/NIOHTTP2/StreamStateMachine.swift @@ -11,8 +11,9 @@ // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -import NIOHPACK + import NIOCore +import NIOHPACK /// A HTTP/2 protocol implementation is fundamentally built on top of two interlocking finite /// state machines. The full description of this is in ConnectionStateMachine.swift. @@ -123,19 +124,35 @@ struct HTTP2StreamStateMachine { /// from the remote peer in this state, however. If we are in this state, we must be a client: servers /// initiating streams put them into reservedLocal, and then sending HEADERS transfers them directly to /// halfClosedRemoteLocalActive. - case halfOpenLocalPeerIdle(localWindow: HTTP2FlowControlWindow, localContentLength: ContentLengthVerifier, remoteWindow: HTTP2FlowControlWindow, requestVerb: String?) + case halfOpenLocalPeerIdle( + localWindow: HTTP2FlowControlWindow, + localContentLength: ContentLengthVerifier, + remoteWindow: HTTP2FlowControlWindow, + requestVerb: String? + ) /// This state does not exist on the diagram above. It encodes the notion that this stream has /// been opened by the remote user sending a HEADERS frame, but we have not yet sent our HEADERS frame /// in response. If we are in this state, we must be a server: clients receiving streams that were opened /// by servers put them into reservedRemote, and then receiving the response HEADERS transitions them directly /// to halfClosedLocalPeerActive. - case halfOpenRemoteLocalIdle(localWindow: HTTP2FlowControlWindow, remoteContentLength: ContentLengthVerifier, remoteWindow: HTTP2FlowControlWindow, requestVerb: String?) + case halfOpenRemoteLocalIdle( + localWindow: HTTP2FlowControlWindow, + remoteContentLength: ContentLengthVerifier, + remoteWindow: HTTP2FlowControlWindow, + requestVerb: String? + ) /// This state is when both peers have sent a HEADERS frame, but neither has sent a frame with END_STREAM /// set. Both peers may exchange data fully. In this state we keep track of whether we are a client or a /// server, as only servers may push new streams. - case fullyOpen(localRole: StreamRole, localContentLength: ContentLengthVerifier, remoteContentLength: ContentLengthVerifier, localWindow: HTTP2FlowControlWindow, remoteWindow: HTTP2FlowControlWindow) + case fullyOpen( + localRole: StreamRole, + localContentLength: ContentLengthVerifier, + remoteContentLength: ContentLengthVerifier, + localWindow: HTTP2FlowControlWindow, + remoteWindow: HTTP2FlowControlWindow + ) /// In the halfClosedLocalPeerIdle state, the local user has sent END_STREAM, but the remote peer has not /// yet sent its HEADERS frame. This mostly happens on GET requests, when END_HEADERS and END_STREAM are @@ -160,7 +177,12 @@ struct HTTP2StreamStateMachine { /// by us: if we're a server, it was initiated by the peer. This is because server-initiated streams never /// enter fullyOpen, as the client is never actually open on those streams. If we came here from /// reservedRemote, this stream must be peer initiated, as this is the client side of a pushed stream. - case halfClosedLocalPeerActive(localRole: StreamRole, initiatedBy: StreamRole, remoteContentLength: ContentLengthVerifier, remoteWindow: HTTP2FlowControlWindow) + case halfClosedLocalPeerActive( + localRole: StreamRole, + initiatedBy: StreamRole, + remoteContentLength: ContentLengthVerifier, + remoteWindow: HTTP2FlowControlWindow + ) /// In the halfClosedRemoteLocalIdle state, the remote peer has sent END_STREAM, but the local user has not /// yet sent its HEADERS frame. This mostly happens on GET requests, when END_HEADERS and END_STREAM are @@ -185,7 +207,12 @@ struct HTTP2StreamStateMachine { /// by us: if we're a server, it was initiated by the peer. This is because server-initiated streams never /// enter fullyOpen, as the client is never actually open on those streams. If we came here from /// reservedLocal, this stream must be initiated by us, as this is the server side of a pushed stream. - case halfClosedRemoteLocalActive(localRole: StreamRole, initiatedBy: StreamRole, localContentLength: ContentLengthVerifier, localWindow: HTTP2FlowControlWindow) + case halfClosedRemoteLocalActive( + localRole: StreamRole, + initiatedBy: StreamRole, + localContentLength: ContentLengthVerifier, + localWindow: HTTP2FlowControlWindow + ) /// Both peers have sent their END_STREAM flags, and the stream is closed. In this stage no further data /// may be exchanged. @@ -227,7 +254,12 @@ struct HTTP2StreamStateMachine { internal let streamID: HTTP2StreamID /// Creates a new, idle, HTTP/2 stream. - init(streamID: HTTP2StreamID, localRole: StreamRole, localInitialWindowSize: UInt32, remoteInitialWindowSize: UInt32) { + init( + streamID: HTTP2StreamID, + localRole: StreamRole, + localInitialWindowSize: UInt32, + remoteInitialWindowSize: UInt32 + ) { let localWindow = HTTP2FlowControlWindow(initialValue: localInitialWindowSize) let remoteWindow = HTTP2FlowControlWindow(initialValue: remoteInitialWindowSize) @@ -237,16 +269,27 @@ struct HTTP2StreamStateMachine { /// Creates a new HTTP/2 stream for a stream that was created by receiving a PUSH_PROMISE frame /// on another stream. - init(receivedPushPromiseCreatingStreamID streamID: HTTP2StreamID, remoteInitialWindowSize: UInt32, requestVerb: String?) { + init( + receivedPushPromiseCreatingStreamID streamID: HTTP2StreamID, + remoteInitialWindowSize: UInt32, + requestVerb: String? + ) { self.streamID = streamID - self.state = .reservedRemote(remoteWindow: HTTP2FlowControlWindow(initialValue: remoteInitialWindowSize), requestVerb: requestVerb) + self.state = .reservedRemote( + remoteWindow: HTTP2FlowControlWindow(initialValue: remoteInitialWindowSize), + requestVerb: requestVerb + ) } /// Creates a new HTTP/2 stream for a stream that was created by sending a PUSH_PROMISE frame on /// another stream. - init(sentPushPromiseCreatingStreamID streamID: HTTP2StreamID, localInitialWindowSize: UInt32, requestVerb: String?) { + init(sentPushPromiseCreatingStreamID streamID: HTTP2StreamID, localInitialWindowSize: UInt32, requestVerb: String?) + { self.streamID = streamID - self.state = .reservedLocal(localWindow: HTTP2FlowControlWindow(initialValue: localInitialWindowSize), requestVerb: requestVerb) + self.state = .reservedLocal( + localWindow: HTTP2FlowControlWindow(initialValue: localInitialWindowSize), + requestVerb: requestVerb + ) } } @@ -265,7 +308,14 @@ extension HTTP2StreamStateMachine { /// it meets the requirements of RFC 7540 for containing a well-formed header block, and additionally /// checks whether the value of the end stream bit is acceptable. If all checks pass, transitions the /// state to the appropriate next entry. - mutating func sendHeaders(headers: HPACKHeaders, validateHeaderBlock: Bool, validateContentLength: Bool, localSupportsExtendedConnect: Bool, remoteSupportsExtendedConnect: Bool, isEndStreamSet endStream: Bool) -> StateMachineResultWithStreamEffect { + mutating func sendHeaders( + headers: HPACKHeaders, + validateHeaderBlock: Bool, + validateContentLength: Bool, + localSupportsExtendedConnect: Bool, + remoteSupportsExtendedConnect: Bool, + isEndStreamSet endStream: Bool + ) -> StateMachineResultWithStreamEffect { do { // We can send headers in the following states: // @@ -282,103 +332,170 @@ extension HTTP2StreamStateMachine { // we may be closing the stream. The keen-eyed may notice that reservedLocal may both open *and* close a stream. This is a bit awkward // for us, and requires a separate event. switch self.state { - case .idle(.client, localWindow: let localWindow, remoteWindow: let remoteWindow): + case .idle(.client, let localWindow, let remoteWindow): let targetState: State - let localContentLength = validateContentLength ? try ContentLengthVerifier(headers, requestMethod: nil) : .disabled + let localContentLength = + validateContentLength ? try ContentLengthVerifier(headers, requestMethod: nil) : .disabled let requestVerb = headers.first(name: ":method") if endStream { try localContentLength.endOfStream() targetState = .halfClosedLocalPeerIdle(remoteWindow: remoteWindow, requestVerb: requestVerb) } else { - targetState = .halfOpenLocalPeerIdle(localWindow: localWindow, localContentLength: localContentLength, remoteWindow: remoteWindow, requestVerb: requestVerb) + targetState = .halfOpenLocalPeerIdle( + localWindow: localWindow, + localContentLength: localContentLength, + remoteWindow: remoteWindow, + requestVerb: requestVerb + ) } - let targetEffect: StreamStateChange = .streamCreated(.init(streamID: self.streamID, localStreamWindowSize: Int(localWindow), remoteStreamWindowSize: Int(remoteWindow))) - return self.processRequestHeaders(headers, - validateHeaderBlock: validateHeaderBlock, - localRole: .client, - localSupportsExtendedConnect: localSupportsExtendedConnect, - remoteSupportsExtendedConnect: remoteSupportsExtendedConnect, - targetState: targetState, - targetEffect: targetEffect) + let targetEffect: StreamStateChange = .streamCreated( + .init( + streamID: self.streamID, + localStreamWindowSize: Int(localWindow), + remoteStreamWindowSize: Int(remoteWindow) + ) + ) + return self.processRequestHeaders( + headers, + validateHeaderBlock: validateHeaderBlock, + localRole: .client, + localSupportsExtendedConnect: localSupportsExtendedConnect, + remoteSupportsExtendedConnect: remoteSupportsExtendedConnect, + targetState: targetState, + targetEffect: targetEffect + ) - case .halfOpenRemoteLocalIdle(localWindow: let localWindow, remoteContentLength: let remoteContentLength, remoteWindow: let remoteWindow, requestVerb: let requestVerb): + case .halfOpenRemoteLocalIdle(let localWindow, let remoteContentLength, let remoteWindow, let requestVerb): let targetState: State - let localContentLength = validateContentLength ? try ContentLengthVerifier(headers, requestMethod: requestVerb) : .disabled + let localContentLength = + validateContentLength ? try ContentLengthVerifier(headers, requestMethod: requestVerb) : .disabled if endStream { try localContentLength.endOfStream() - targetState = .halfClosedLocalPeerActive(localRole: .server, initiatedBy: .client, remoteContentLength: remoteContentLength, remoteWindow: remoteWindow) + targetState = .halfClosedLocalPeerActive( + localRole: .server, + initiatedBy: .client, + remoteContentLength: remoteContentLength, + remoteWindow: remoteWindow + ) } else { - targetState = .fullyOpen(localRole: .server, localContentLength: localContentLength, remoteContentLength: remoteContentLength, localWindow: localWindow, remoteWindow: remoteWindow) + targetState = .fullyOpen( + localRole: .server, + localContentLength: localContentLength, + remoteContentLength: remoteContentLength, + localWindow: localWindow, + remoteWindow: remoteWindow + ) } - return self.processResponseHeaders(headers, - validateHeaderBlock: validateHeaderBlock, - targetStateIfFinal: targetState, - targetEffectIfFinal: nil) + return self.processResponseHeaders( + headers, + validateHeaderBlock: validateHeaderBlock, + targetStateIfFinal: targetState, + targetEffectIfFinal: nil + ) - case .halfOpenLocalPeerIdle(localWindow: _, localContentLength: let localContentLength, remoteWindow: let remoteWindow, requestVerb: let requestVerb): + case .halfOpenLocalPeerIdle(localWindow: _, let localContentLength, let remoteWindow, let requestVerb): try localContentLength.endOfStream() - return self.processTrailers(headers, - validateHeaderBlock: validateHeaderBlock, - isEndStreamSet: endStream, - targetState: .halfClosedLocalPeerIdle(remoteWindow: remoteWindow, requestVerb: requestVerb), - targetEffect: nil) + return self.processTrailers( + headers, + validateHeaderBlock: validateHeaderBlock, + isEndStreamSet: endStream, + targetState: .halfClosedLocalPeerIdle(remoteWindow: remoteWindow, requestVerb: requestVerb), + targetEffect: nil + ) - case .reservedLocal(let localWindow, requestVerb: let requestVerb): + case .reservedLocal(let localWindow, let requestVerb): let targetState: State let targetEffect: StreamStateChange - let localContentLength = validateContentLength ? try ContentLengthVerifier(headers, requestMethod: requestVerb) : .disabled + let localContentLength = + validateContentLength ? try ContentLengthVerifier(headers, requestMethod: requestVerb) : .disabled if endStream { try localContentLength.endOfStream() targetState = .closed(reason: nil) targetEffect = .streamCreatedAndClosed(.init(streamID: self.streamID)) } else { - targetState = .halfClosedRemoteLocalActive(localRole: .server, initiatedBy: .server, localContentLength: localContentLength, localWindow: localWindow) - targetEffect = .streamCreated(.init(streamID: self.streamID, localStreamWindowSize: Int(localWindow), remoteStreamWindowSize: nil)) + targetState = .halfClosedRemoteLocalActive( + localRole: .server, + initiatedBy: .server, + localContentLength: localContentLength, + localWindow: localWindow + ) + targetEffect = .streamCreated( + .init( + streamID: self.streamID, + localStreamWindowSize: Int(localWindow), + remoteStreamWindowSize: nil + ) + ) } - return self.processResponseHeaders(headers, - validateHeaderBlock: validateHeaderBlock, - targetStateIfFinal: targetState, - targetEffectIfFinal: targetEffect) + return self.processResponseHeaders( + headers, + validateHeaderBlock: validateHeaderBlock, + targetStateIfFinal: targetState, + targetEffectIfFinal: targetEffect + ) - case .fullyOpen(let localRole, localContentLength: let localContentLength, remoteContentLength: let remoteContentLength, localWindow: _, remoteWindow: let remoteWindow): + case .fullyOpen( + let localRole, + let localContentLength, + let remoteContentLength, + localWindow: _, + let remoteWindow + ): try localContentLength.endOfStream() - return self.processTrailers(headers, - validateHeaderBlock: validateHeaderBlock, - isEndStreamSet: endStream, - targetState: .halfClosedLocalPeerActive(localRole: localRole, initiatedBy: .client, remoteContentLength: remoteContentLength, remoteWindow: remoteWindow), - targetEffect: nil) + return self.processTrailers( + headers, + validateHeaderBlock: validateHeaderBlock, + isEndStreamSet: endStream, + targetState: .halfClosedLocalPeerActive( + localRole: localRole, + initiatedBy: .client, + remoteContentLength: remoteContentLength, + remoteWindow: remoteWindow + ), + targetEffect: nil + ) - case .halfClosedRemoteLocalIdle(let localWindow, requestVerb: let requestVerb): + case .halfClosedRemoteLocalIdle(let localWindow, let requestVerb): let targetState: State let targetEffect: StreamStateChange? - let localContentLength = validateContentLength ? try ContentLengthVerifier(headers, requestMethod: requestVerb) : .disabled + let localContentLength = + validateContentLength ? try ContentLengthVerifier(headers, requestMethod: requestVerb) : .disabled if endStream { try localContentLength.endOfStream() targetState = .closed(reason: nil) targetEffect = .streamClosed(.init(streamID: self.streamID, reason: nil)) } else { - targetState = .halfClosedRemoteLocalActive(localRole: .server, initiatedBy: .client, localContentLength: localContentLength, localWindow: localWindow) + targetState = .halfClosedRemoteLocalActive( + localRole: .server, + initiatedBy: .client, + localContentLength: localContentLength, + localWindow: localWindow + ) targetEffect = nil } - return self.processResponseHeaders(headers, - validateHeaderBlock: validateHeaderBlock, - targetStateIfFinal: targetState, - targetEffectIfFinal: targetEffect) + return self.processResponseHeaders( + headers, + validateHeaderBlock: validateHeaderBlock, + targetStateIfFinal: targetState, + targetEffectIfFinal: targetEffect + ) - case .halfClosedRemoteLocalActive(localRole: _, initiatedBy: _, localContentLength: let localContentLength, localWindow: _): + case .halfClosedRemoteLocalActive(localRole: _, initiatedBy: _, let localContentLength, localWindow: _): try localContentLength.endOfStream() - return self.processTrailers(headers, - validateHeaderBlock: validateHeaderBlock, - isEndStreamSet: endStream, - targetState: .closed(reason: nil), - targetEffect: .streamClosed(.init(streamID: self.streamID, reason: nil))) + return self.processTrailers( + headers, + validateHeaderBlock: validateHeaderBlock, + isEndStreamSet: endStream, + targetState: .closed(reason: nil), + targetEffect: .streamClosed(.init(streamID: self.streamID, reason: nil)) + ) // Sending a HEADERS frame as an idle server, or on a closed stream, is a connection error // of type PROTOCOL_ERROR. In any other state, sending a HEADERS frame is a stream error of @@ -388,18 +505,45 @@ extension HTTP2StreamStateMachine { // seems reasonable to me: specifically, if we have a stream to fail, fail it, otherwise treat // the error as connection scoped.) case .idle(.server, _, _), .closed: - return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.badStreamStateTransition(from: NIOHTTP2StreamState.get(self.state)), type: .protocolError), effect: nil) + return .init( + result: .connectionError( + underlyingError: NIOHTTP2Errors.badStreamStateTransition( + from: NIOHTTP2StreamState.get(self.state) + ), + type: .protocolError + ), + effect: nil + ) case .reservedRemote, .halfClosedLocalPeerIdle, .halfClosedLocalPeerActive: - return .init(result: .streamError(streamID: self.streamID, underlyingError: NIOHTTP2Errors.badStreamStateTransition(from: NIOHTTP2StreamState.get(self.state)), type: .protocolError), effect: nil) + return .init( + result: .streamError( + streamID: self.streamID, + underlyingError: NIOHTTP2Errors.badStreamStateTransition( + from: NIOHTTP2StreamState.get(self.state) + ), + type: .protocolError + ), + effect: nil + ) } } catch let error where error is InvalidContentLengthError { - return .init(result: .streamError(streamID: self.streamID, underlyingError: error, type: .protocolError), effect: nil) + return .init( + result: .streamError(streamID: self.streamID, underlyingError: error, type: .protocolError), + effect: nil + ) } catch { preconditionFailure("Unexpected error: \(error)") } } - mutating func receiveHeaders(headers: HPACKHeaders, validateHeaderBlock: Bool, validateContentLength: Bool, localSupportsExtendedConnect: Bool, remoteSupportsExtendedConnect: Bool, isEndStreamSet endStream: Bool) -> StateMachineResultWithStreamEffect { + mutating func receiveHeaders( + headers: HPACKHeaders, + validateHeaderBlock: Bool, + validateContentLength: Bool, + localSupportsExtendedConnect: Bool, + remoteSupportsExtendedConnect: Bool, + isEndStreamSet endStream: Bool + ) -> StateMachineResultWithStreamEffect { do { // We can receive headers in the following states: // @@ -416,104 +560,171 @@ extension HTTP2StreamStateMachine { // we may be closing the stream. The keen-eyed may notice that reservedLocal may both open *and* close a stream. This is a bit awkward // for us, and requires a separate event. switch self.state { - case .idle(.server, localWindow: let localWindow, remoteWindow: let remoteWindow): + case .idle(.server, let localWindow, let remoteWindow): let targetState: State let requestVerb = headers.first(name: ":method") - let remoteContentLength = validateContentLength ? try ContentLengthVerifier(headers, requestMethod: nil) : .disabled + let remoteContentLength = + validateContentLength ? try ContentLengthVerifier(headers, requestMethod: nil) : .disabled if endStream { try remoteContentLength.endOfStream() targetState = .halfClosedRemoteLocalIdle(localWindow: localWindow, requestVerb: requestVerb) } else { - targetState = .halfOpenRemoteLocalIdle(localWindow: localWindow, remoteContentLength: remoteContentLength, remoteWindow: remoteWindow, requestVerb: requestVerb) + targetState = .halfOpenRemoteLocalIdle( + localWindow: localWindow, + remoteContentLength: remoteContentLength, + remoteWindow: remoteWindow, + requestVerb: requestVerb + ) } - let targetEffect: StreamStateChange = .streamCreated(.init(streamID: self.streamID, localStreamWindowSize: Int(localWindow), remoteStreamWindowSize: Int(remoteWindow))) - return self.processRequestHeaders(headers, - validateHeaderBlock: validateHeaderBlock, - localRole: .server, - localSupportsExtendedConnect: localSupportsExtendedConnect, - remoteSupportsExtendedConnect: remoteSupportsExtendedConnect, - targetState: targetState, - targetEffect: targetEffect) + let targetEffect: StreamStateChange = .streamCreated( + .init( + streamID: self.streamID, + localStreamWindowSize: Int(localWindow), + remoteStreamWindowSize: Int(remoteWindow) + ) + ) + return self.processRequestHeaders( + headers, + validateHeaderBlock: validateHeaderBlock, + localRole: .server, + localSupportsExtendedConnect: localSupportsExtendedConnect, + remoteSupportsExtendedConnect: remoteSupportsExtendedConnect, + targetState: targetState, + targetEffect: targetEffect + ) - case .halfOpenLocalPeerIdle(localWindow: let localWindow, localContentLength: let localContentLength, remoteWindow: let remoteWindow, requestVerb: let requestVerb): + case .halfOpenLocalPeerIdle(let localWindow, let localContentLength, let remoteWindow, let requestVerb): let targetState: State - let remoteContentLength = validateContentLength ? try ContentLengthVerifier(headers, requestMethod: requestVerb) : .disabled + let remoteContentLength = + validateContentLength ? try ContentLengthVerifier(headers, requestMethod: requestVerb) : .disabled if endStream { try remoteContentLength.endOfStream() - targetState = .halfClosedRemoteLocalActive(localRole: .client, initiatedBy: .client, localContentLength: localContentLength, localWindow: localWindow) + targetState = .halfClosedRemoteLocalActive( + localRole: .client, + initiatedBy: .client, + localContentLength: localContentLength, + localWindow: localWindow + ) } else { - targetState = .fullyOpen(localRole: .client, localContentLength: localContentLength, remoteContentLength: remoteContentLength, localWindow: localWindow, remoteWindow: remoteWindow) + targetState = .fullyOpen( + localRole: .client, + localContentLength: localContentLength, + remoteContentLength: remoteContentLength, + localWindow: localWindow, + remoteWindow: remoteWindow + ) } - return self.processResponseHeaders(headers, - validateHeaderBlock: validateHeaderBlock, - targetStateIfFinal: targetState, - targetEffectIfFinal: nil) + return self.processResponseHeaders( + headers, + validateHeaderBlock: validateHeaderBlock, + targetStateIfFinal: targetState, + targetEffectIfFinal: nil + ) - case .halfOpenRemoteLocalIdle(localWindow: let localWindow, remoteContentLength: let remoteContentLength, remoteWindow: _, requestVerb: let requestVerb): + case .halfOpenRemoteLocalIdle(let localWindow, let remoteContentLength, remoteWindow: _, let requestVerb): try remoteContentLength.endOfStream() - return self.processTrailers(headers, - validateHeaderBlock: validateHeaderBlock, - isEndStreamSet: endStream, - targetState: .halfClosedRemoteLocalIdle(localWindow: localWindow, requestVerb: requestVerb), - targetEffect: nil) + return self.processTrailers( + headers, + validateHeaderBlock: validateHeaderBlock, + isEndStreamSet: endStream, + targetState: .halfClosedRemoteLocalIdle(localWindow: localWindow, requestVerb: requestVerb), + targetEffect: nil + ) - case .reservedRemote(let remoteWindow, requestVerb: let requestVerb): + case .reservedRemote(let remoteWindow, let requestVerb): let targetState: State let targetEffect: StreamStateChange - let remoteContentLength = validateContentLength ? try ContentLengthVerifier(headers, requestMethod: requestVerb) : .disabled + let remoteContentLength = + validateContentLength ? try ContentLengthVerifier(headers, requestMethod: requestVerb) : .disabled if endStream { try remoteContentLength.endOfStream() targetState = .closed(reason: nil) targetEffect = .streamCreatedAndClosed(.init(streamID: self.streamID)) } else { - targetState = .halfClosedLocalPeerActive(localRole: .client, initiatedBy: .server, remoteContentLength: remoteContentLength, remoteWindow: remoteWindow) - targetEffect = .streamCreated(.init(streamID: self.streamID, localStreamWindowSize: nil, remoteStreamWindowSize: Int(remoteWindow))) + targetState = .halfClosedLocalPeerActive( + localRole: .client, + initiatedBy: .server, + remoteContentLength: remoteContentLength, + remoteWindow: remoteWindow + ) + targetEffect = .streamCreated( + .init( + streamID: self.streamID, + localStreamWindowSize: nil, + remoteStreamWindowSize: Int(remoteWindow) + ) + ) } - return self.processResponseHeaders(headers, - validateHeaderBlock: validateHeaderBlock, - targetStateIfFinal: targetState, - targetEffectIfFinal: targetEffect) + return self.processResponseHeaders( + headers, + validateHeaderBlock: validateHeaderBlock, + targetStateIfFinal: targetState, + targetEffectIfFinal: targetEffect + ) - case .fullyOpen(let localRole, localContentLength: let localContentLength, remoteContentLength: let remoteContentLength, localWindow: let localWindow, remoteWindow: _): + case .fullyOpen( + let localRole, + let localContentLength, + let remoteContentLength, + let localWindow, + remoteWindow: _ + ): try remoteContentLength.endOfStream() - return self.processTrailers(headers, - validateHeaderBlock: validateHeaderBlock, - isEndStreamSet: endStream, - targetState: .halfClosedRemoteLocalActive(localRole: localRole, initiatedBy: .client, localContentLength: localContentLength, localWindow: localWindow), - targetEffect: nil) + return self.processTrailers( + headers, + validateHeaderBlock: validateHeaderBlock, + isEndStreamSet: endStream, + targetState: .halfClosedRemoteLocalActive( + localRole: localRole, + initiatedBy: .client, + localContentLength: localContentLength, + localWindow: localWindow + ), + targetEffect: nil + ) - case .halfClosedLocalPeerIdle(let remoteWindow, requestVerb: let requestVerb): + case .halfClosedLocalPeerIdle(let remoteWindow, let requestVerb): let targetState: State let targetEffect: StreamStateChange? - let remoteContentLength = validateContentLength ? try ContentLengthVerifier(headers, requestMethod: requestVerb) : .disabled + let remoteContentLength = + validateContentLength ? try ContentLengthVerifier(headers, requestMethod: requestVerb) : .disabled if endStream { try remoteContentLength.endOfStream() targetState = .closed(reason: nil) targetEffect = .streamClosed(.init(streamID: self.streamID, reason: nil)) } else { - targetState = .halfClosedLocalPeerActive(localRole: .client, initiatedBy: .client, remoteContentLength: remoteContentLength, remoteWindow: remoteWindow) + targetState = .halfClosedLocalPeerActive( + localRole: .client, + initiatedBy: .client, + remoteContentLength: remoteContentLength, + remoteWindow: remoteWindow + ) targetEffect = nil } - return self.processResponseHeaders(headers, - validateHeaderBlock: validateHeaderBlock, - targetStateIfFinal: targetState, - targetEffectIfFinal: targetEffect) + return self.processResponseHeaders( + headers, + validateHeaderBlock: validateHeaderBlock, + targetStateIfFinal: targetState, + targetEffectIfFinal: targetEffect + ) - case .halfClosedLocalPeerActive(localRole: _, initiatedBy: _, remoteContentLength: let remoteContentLength, remoteWindow: _): + case .halfClosedLocalPeerActive(localRole: _, initiatedBy: _, let remoteContentLength, remoteWindow: _): try remoteContentLength.endOfStream() - return self.processTrailers(headers, - validateHeaderBlock: validateHeaderBlock, - isEndStreamSet: endStream, - targetState: .closed(reason: nil), - targetEffect: .streamClosed(.init(streamID: self.streamID, reason: nil))) + return self.processTrailers( + headers, + validateHeaderBlock: validateHeaderBlock, + isEndStreamSet: endStream, + targetState: .closed(reason: nil), + targetEffect: .streamClosed(.init(streamID: self.streamID, reason: nil)) + ) // Receiving a HEADERS frame as an idle client, or on a closed stream, is a connection error // of type PROTOCOL_ERROR. In any other state, receiving a HEADERS frame is a stream error of @@ -523,18 +734,42 @@ extension HTTP2StreamStateMachine { // seems reasonable to me: specifically, if we have a stream to fail, fail it, otherwise treat // the error as connection scoped.) case .idle(.client, _, _), .closed: - return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.badStreamStateTransition(from: NIOHTTP2StreamState.get(self.state)), type: .protocolError), effect: nil) + return .init( + result: .connectionError( + underlyingError: NIOHTTP2Errors.badStreamStateTransition( + from: NIOHTTP2StreamState.get(self.state) + ), + type: .protocolError + ), + effect: nil + ) case .reservedLocal, .halfClosedRemoteLocalIdle, .halfClosedRemoteLocalActive: - return .init(result: .streamError(streamID: self.streamID, underlyingError: NIOHTTP2Errors.badStreamStateTransition(from: NIOHTTP2StreamState.get(self.state)), type: .protocolError), effect: nil) + return .init( + result: .streamError( + streamID: self.streamID, + underlyingError: NIOHTTP2Errors.badStreamStateTransition( + from: NIOHTTP2StreamState.get(self.state) + ), + type: .protocolError + ), + effect: nil + ) } } catch let error where error is InvalidContentLengthError { - return .init(result: .streamError(streamID: self.streamID, underlyingError: error, type: .protocolError), effect: nil) + return .init( + result: .streamError(streamID: self.streamID, underlyingError: error, type: .protocolError), + effect: nil + ) } catch { preconditionFailure("Unexpected error: \(error)") } } - mutating func sendData(contentLength: Int, flowControlledBytes: Int, isEndStreamSet endStream: Bool) -> StateMachineResultWithStreamEffect { + mutating func sendData( + contentLength: Int, + flowControlledBytes: Int, + isEndStreamSet endStream: Bool + ) -> StateMachineResultWithStreamEffect { do { // We can send DATA frames in the following states: // @@ -545,7 +780,7 @@ extension HTTP2StreamStateMachine { // // Valid data frames always have a stream effect, because they consume flow control windows. switch self.state { - case .halfOpenLocalPeerIdle(localWindow: var localWindow, localContentLength: var localContentLength, remoteWindow: let remoteWindow, requestVerb: let requestVerb): + case .halfOpenLocalPeerIdle(var localWindow, var localContentLength, let remoteWindow, let requestVerb): try localWindow.consume(flowControlledBytes: flowControlledBytes) try localContentLength.receivedDataChunk(length: contentLength) @@ -553,25 +788,65 @@ extension HTTP2StreamStateMachine { if endStream { try localContentLength.endOfStream() self.state = .halfClosedLocalPeerIdle(remoteWindow: remoteWindow, requestVerb: requestVerb) - effect = .windowSizeChange(.init(streamID: self.streamID, localStreamWindowSize: nil, remoteStreamWindowSize: Int(remoteWindow))) + effect = .windowSizeChange( + .init( + streamID: self.streamID, + localStreamWindowSize: nil, + remoteStreamWindowSize: Int(remoteWindow) + ) + ) } else { - self.state = .halfOpenLocalPeerIdle(localWindow: localWindow, localContentLength: localContentLength, remoteWindow: remoteWindow, requestVerb: requestVerb) - effect = .windowSizeChange(.init(streamID: self.streamID, localStreamWindowSize: Int(localWindow), remoteStreamWindowSize: Int(remoteWindow))) + self.state = .halfOpenLocalPeerIdle( + localWindow: localWindow, + localContentLength: localContentLength, + remoteWindow: remoteWindow, + requestVerb: requestVerb + ) + effect = .windowSizeChange( + .init( + streamID: self.streamID, + localStreamWindowSize: Int(localWindow), + remoteStreamWindowSize: Int(remoteWindow) + ) + ) } return .init(result: .succeed, effect: effect) - case .fullyOpen(let localRole, localContentLength: var localContentLength, remoteContentLength: let remoteContentLength, localWindow: var localWindow, remoteWindow: let remoteWindow): + case .fullyOpen( + let localRole, + var localContentLength, + let remoteContentLength, + var localWindow, + let remoteWindow + ): try localWindow.consume(flowControlledBytes: flowControlledBytes) try localContentLength.receivedDataChunk(length: contentLength) - let effect: StreamStateChange = .windowSizeChange(.init(streamID: self.streamID, localStreamWindowSize: Int(localWindow), remoteStreamWindowSize: Int(remoteWindow))) + let effect: StreamStateChange = .windowSizeChange( + .init( + streamID: self.streamID, + localStreamWindowSize: Int(localWindow), + remoteStreamWindowSize: Int(remoteWindow) + ) + ) if endStream { try localContentLength.endOfStream() - self.state = .halfClosedLocalPeerActive(localRole: localRole, initiatedBy: .client, remoteContentLength: remoteContentLength, remoteWindow: remoteWindow) + self.state = .halfClosedLocalPeerActive( + localRole: localRole, + initiatedBy: .client, + remoteContentLength: remoteContentLength, + remoteWindow: remoteWindow + ) } else { - self.state = .fullyOpen(localRole: localRole, localContentLength: localContentLength, remoteContentLength: remoteContentLength, localWindow: localWindow, remoteWindow: remoteWindow) + self.state = .fullyOpen( + localRole: localRole, + localContentLength: localContentLength, + remoteContentLength: remoteContentLength, + localWindow: localWindow, + remoteWindow: remoteWindow + ) } return .init(result: .succeed, effect: effect) @@ -586,27 +861,57 @@ extension HTTP2StreamStateMachine { self.state = .closed(reason: nil) effect = .streamClosed(.init(streamID: self.streamID, reason: nil)) } else { - self.state = .halfClosedRemoteLocalActive(localRole: localRole, initiatedBy: initiatedBy, localContentLength: localContentLength, localWindow: localWindow) - effect = .windowSizeChange(.init(streamID: self.streamID, localStreamWindowSize: Int(localWindow), remoteStreamWindowSize: nil)) + self.state = .halfClosedRemoteLocalActive( + localRole: localRole, + initiatedBy: initiatedBy, + localContentLength: localContentLength, + localWindow: localWindow + ) + effect = .windowSizeChange( + .init( + streamID: self.streamID, + localStreamWindowSize: Int(localWindow), + remoteStreamWindowSize: nil + ) + ) } return .init(result: .succeed, effect: effect) // Sending a DATA frame outside any of these states is a stream error of type STREAM_CLOSED (RFC7540 ยง 6.1) case .idle, .halfOpenRemoteLocalIdle, .reservedLocal, .reservedRemote, .halfClosedLocalPeerIdle, - .halfClosedLocalPeerActive, .halfClosedRemoteLocalIdle, .closed: - return .init(result: .streamError(streamID: self.streamID, underlyingError: NIOHTTP2Errors.badStreamStateTransition(from: NIOHTTP2StreamState.get(self.state)), type: .streamClosed), effect: nil) + .halfClosedLocalPeerActive, .halfClosedRemoteLocalIdle, .closed: + return .init( + result: .streamError( + streamID: self.streamID, + underlyingError: NIOHTTP2Errors.badStreamStateTransition( + from: NIOHTTP2StreamState.get(self.state) + ), + type: .streamClosed + ), + effect: nil + ) } } catch let error where error is NIOHTTP2Errors.FlowControlViolation { - return .init(result: .streamError(streamID: self.streamID, underlyingError: error, type: .flowControlError), effect: nil) + return .init( + result: .streamError(streamID: self.streamID, underlyingError: error, type: .flowControlError), + effect: nil + ) } catch let error where error is NIOHTTP2Errors.ContentLengthViolated { - return .init(result: .streamError(streamID: self.streamID, underlyingError: error, type: .protocolError), effect: nil) + return .init( + result: .streamError(streamID: self.streamID, underlyingError: error, type: .protocolError), + effect: nil + ) } catch { preconditionFailure("Unexpected error: \(error)") } } - mutating func receiveData(contentLength: Int, flowControlledBytes: Int, isEndStreamSet endStream: Bool) -> StateMachineResultWithStreamEffect { + mutating func receiveData( + contentLength: Int, + flowControlledBytes: Int, + isEndStreamSet endStream: Bool + ) -> StateMachineResultWithStreamEffect { do { // We can receive DATA frames in the following states: // @@ -615,33 +920,79 @@ extension HTTP2StreamStateMachine { // - fullyOpen, where we could be either a client or a server using a fully bi-directional stream. // - halfClosedLocalPeerActive, whe have completed our data, but the remote peer has more to send. switch self.state { - case .halfOpenRemoteLocalIdle(localWindow: let localWindow, remoteContentLength: var remoteContentLength, remoteWindow: var remoteWindow, requestVerb: let requestVerb): + case .halfOpenRemoteLocalIdle(let localWindow, var remoteContentLength, var remoteWindow, let requestVerb): try remoteWindow.consume(flowControlledBytes: flowControlledBytes) try remoteContentLength.receivedDataChunk(length: contentLength) let effect: StreamStateChange if endStream { try remoteContentLength.endOfStream() self.state = .halfClosedRemoteLocalIdle(localWindow: localWindow, requestVerb: requestVerb) - effect = .windowSizeChange(.init(streamID: self.streamID, localStreamWindowSize: Int(localWindow), remoteStreamWindowSize: nil)) + effect = .windowSizeChange( + .init( + streamID: self.streamID, + localStreamWindowSize: Int(localWindow), + remoteStreamWindowSize: nil + ) + ) } else { - self.state = .halfOpenRemoteLocalIdle(localWindow: localWindow, remoteContentLength: remoteContentLength, remoteWindow: remoteWindow, requestVerb: requestVerb) - effect = .windowSizeChange(.init(streamID: self.streamID, localStreamWindowSize: Int(localWindow), remoteStreamWindowSize: Int(remoteWindow))) + self.state = .halfOpenRemoteLocalIdle( + localWindow: localWindow, + remoteContentLength: remoteContentLength, + remoteWindow: remoteWindow, + requestVerb: requestVerb + ) + effect = .windowSizeChange( + .init( + streamID: self.streamID, + localStreamWindowSize: Int(localWindow), + remoteStreamWindowSize: Int(remoteWindow) + ) + ) } return .init(result: .succeed, effect: effect) - case .fullyOpen(let localRole, localContentLength: let localContentLength, remoteContentLength: var remoteContentLength, localWindow: let localWindow, remoteWindow: var remoteWindow): + case .fullyOpen( + let localRole, + let localContentLength, + var remoteContentLength, + let localWindow, + var remoteWindow + ): try remoteWindow.consume(flowControlledBytes: flowControlledBytes) try remoteContentLength.receivedDataChunk(length: contentLength) let effect: StreamStateChange if endStream { try remoteContentLength.endOfStream() - self.state = .halfClosedRemoteLocalActive(localRole: localRole, initiatedBy: .client, localContentLength: localContentLength, localWindow: localWindow) - effect = .windowSizeChange(.init(streamID: self.streamID, localStreamWindowSize: Int(localWindow), remoteStreamWindowSize: nil)) + self.state = .halfClosedRemoteLocalActive( + localRole: localRole, + initiatedBy: .client, + localContentLength: localContentLength, + localWindow: localWindow + ) + effect = .windowSizeChange( + .init( + streamID: self.streamID, + localStreamWindowSize: Int(localWindow), + remoteStreamWindowSize: nil + ) + ) } else { - self.state = .fullyOpen(localRole: localRole, localContentLength: localContentLength, remoteContentLength: remoteContentLength, localWindow: localWindow, remoteWindow: remoteWindow) - effect = .windowSizeChange(.init(streamID: self.streamID, localStreamWindowSize: Int(localWindow), remoteStreamWindowSize: Int(remoteWindow))) + self.state = .fullyOpen( + localRole: localRole, + localContentLength: localContentLength, + remoteContentLength: remoteContentLength, + localWindow: localWindow, + remoteWindow: remoteWindow + ) + effect = .windowSizeChange( + .init( + streamID: self.streamID, + localStreamWindowSize: Int(localWindow), + remoteStreamWindowSize: Int(remoteWindow) + ) + ) } return .init(result: .succeed, effect: effect) @@ -656,27 +1007,56 @@ extension HTTP2StreamStateMachine { self.state = .closed(reason: nil) effect = .streamClosed(.init(streamID: self.streamID, reason: nil)) } else { - self.state = .halfClosedLocalPeerActive(localRole: localRole, initiatedBy: initiatedBy, remoteContentLength: remoteContentLength, remoteWindow: remoteWindow) - effect = .windowSizeChange(.init(streamID: self.streamID, localStreamWindowSize: nil, remoteStreamWindowSize: Int(remoteWindow))) + self.state = .halfClosedLocalPeerActive( + localRole: localRole, + initiatedBy: initiatedBy, + remoteContentLength: remoteContentLength, + remoteWindow: remoteWindow + ) + effect = .windowSizeChange( + .init( + streamID: self.streamID, + localStreamWindowSize: nil, + remoteStreamWindowSize: Int(remoteWindow) + ) + ) } return .init(result: .succeed, effect: effect) // Receiving a DATA frame outside any of these states is a stream error of type STREAM_CLOSED (RFC7540 ยง 6.1) case .idle, .halfOpenLocalPeerIdle, .reservedLocal, .reservedRemote, .halfClosedLocalPeerIdle, - .halfClosedRemoteLocalActive, .halfClosedRemoteLocalIdle, .closed: - return .init(result: .streamError(streamID: self.streamID, underlyingError: NIOHTTP2Errors.badStreamStateTransition(from: NIOHTTP2StreamState.get(self.state)), type: .streamClosed), effect: nil) + .halfClosedRemoteLocalActive, .halfClosedRemoteLocalIdle, .closed: + return .init( + result: .streamError( + streamID: self.streamID, + underlyingError: NIOHTTP2Errors.badStreamStateTransition( + from: NIOHTTP2StreamState.get(self.state) + ), + type: .streamClosed + ), + effect: nil + ) } } catch let error where error is NIOHTTP2Errors.FlowControlViolation { - return .init(result: .streamError(streamID: self.streamID, underlyingError: error, type: .flowControlError), effect: nil) + return .init( + result: .streamError(streamID: self.streamID, underlyingError: error, type: .flowControlError), + effect: nil + ) } catch let error where error is NIOHTTP2Errors.ContentLengthViolated { - return .init(result: .streamError(streamID: self.streamID, underlyingError: error, type: .protocolError), effect: nil) + return .init( + result: .streamError(streamID: self.streamID, underlyingError: error, type: .protocolError), + effect: nil + ) } catch { preconditionFailure("Unexpected error: \(error)") } } - mutating func sendPushPromise(headers: HPACKHeaders, validateHeaderBlock: Bool) -> StateMachineResultWithStreamEffect { + mutating func sendPushPromise( + headers: HPACKHeaders, + validateHeaderBlock: Bool + ) -> StateMachineResultWithStreamEffect { // We can send PUSH_PROMISE frames in the following states: // // - fullyOpen when we are a server. In this case we assert that the stream was initiated by the client. @@ -688,24 +1068,64 @@ extension HTTP2StreamStateMachine { // // PUSH_PROMISE frames never have stream effects: they cannot create or close streams, or affect flow control state. switch self.state { - case .fullyOpen(localRole: .server, localContentLength: _, remoteContentLength: _, localWindow: _, remoteWindow: _), + case .fullyOpen( + localRole: .server, + localContentLength: _, + remoteContentLength: _, + localWindow: _, + remoteWindow: _ + ), .halfOpenRemoteLocalIdle(localWindow: _, remoteContentLength: _, remoteWindow: _, requestVerb: _), - .halfClosedRemoteLocalIdle(localWindow: _), - .halfClosedRemoteLocalActive(localRole: .server, initiatedBy: .client, localContentLength: _, localWindow: _): - return self.processRequestHeaders(headers, validateHeaderBlock: validateHeaderBlock, localRole: .server, localSupportsExtendedConnect: false, remoteSupportsExtendedConnect: false, targetState: self.state, targetEffect: nil) + .halfClosedRemoteLocalIdle(localWindow: _), + .halfClosedRemoteLocalActive( + localRole: .server, + initiatedBy: .client, + localContentLength: _, + localWindow: _ + ): + return self.processRequestHeaders( + headers, + validateHeaderBlock: validateHeaderBlock, + localRole: .server, + localSupportsExtendedConnect: false, + remoteSupportsExtendedConnect: false, + targetState: self.state, + targetEffect: nil + ) // Sending a PUSH_PROMISE frame outside any of these states is a stream error of type PROTOCOL_ERROR. // Authors note: I cannot find a citation for this in RFC 7540, but this seems a sensible choice. case .idle, .reservedLocal, .reservedRemote, .halfClosedLocalPeerIdle, .halfClosedLocalPeerActive, - .halfOpenLocalPeerIdle, .closed, - .fullyOpen(localRole: .client, localContentLength: _, remoteContentLength: _, localWindow: _, remoteWindow: _), - .halfClosedRemoteLocalActive(localRole: .client, initiatedBy: _, localContentLength: _, localWindow: _), - .halfClosedRemoteLocalActive(localRole: .server, initiatedBy: .server, localContentLength: _, localWindow: _): - return .init(result: .streamError(streamID: self.streamID, underlyingError: NIOHTTP2Errors.badStreamStateTransition(from: NIOHTTP2StreamState.get(self.state)), type: .protocolError), effect: nil) + .halfOpenLocalPeerIdle, .closed, + .fullyOpen( + localRole: .client, + localContentLength: _, + remoteContentLength: _, + localWindow: _, + remoteWindow: _ + ), + .halfClosedRemoteLocalActive(localRole: .client, initiatedBy: _, localContentLength: _, localWindow: _), + .halfClosedRemoteLocalActive( + localRole: .server, + initiatedBy: .server, + localContentLength: _, + localWindow: _ + ): + return .init( + result: .streamError( + streamID: self.streamID, + underlyingError: NIOHTTP2Errors.badStreamStateTransition(from: NIOHTTP2StreamState.get(self.state)), + type: .protocolError + ), + effect: nil + ) } } - mutating func receivePushPromise(headers: HPACKHeaders, validateHeaderBlock: Bool) -> StateMachineResultWithStreamEffect { + mutating func receivePushPromise( + headers: HPACKHeaders, + validateHeaderBlock: Bool + ) -> StateMachineResultWithStreamEffect { // We can receive PUSH_PROMISE frames in the following states: // // - fullyOpen when we are a client. In this case we assert that the stream was initiated by us. @@ -715,20 +1135,57 @@ extension HTTP2StreamStateMachine { // // RFC 7540 ยง 6.6 forbids receiving PUSH_PROMISE frames on remotely-initiated streams. switch self.state { - case .fullyOpen(localRole: .client, localContentLength: _, remoteContentLength: _, localWindow: _, remoteWindow: _), + case .fullyOpen( + localRole: .client, + localContentLength: _, + remoteContentLength: _, + localWindow: _, + remoteWindow: _ + ), .halfOpenLocalPeerIdle(localWindow: _, localContentLength: _, remoteWindow: _, requestVerb: _), - .halfClosedLocalPeerIdle(remoteWindow: _), - .halfClosedLocalPeerActive(localRole: .client, initiatedBy: .client, remoteContentLength: _, remoteWindow: _): - return self.processRequestHeaders(headers, validateHeaderBlock: validateHeaderBlock, localRole: .client, localSupportsExtendedConnect: false, remoteSupportsExtendedConnect: false, targetState: self.state, targetEffect: nil) + .halfClosedLocalPeerIdle(remoteWindow: _), + .halfClosedLocalPeerActive( + localRole: .client, + initiatedBy: .client, + remoteContentLength: _, + remoteWindow: _ + ): + return self.processRequestHeaders( + headers, + validateHeaderBlock: validateHeaderBlock, + localRole: .client, + localSupportsExtendedConnect: false, + remoteSupportsExtendedConnect: false, + targetState: self.state, + targetEffect: nil + ) // Receiving a PUSH_PROMISE frame outside any of these states is a stream error of type PROTOCOL_ERROR. // Authors note: I cannot find a citation for this in RFC 7540, but this seems a sensible choice. case .idle, .reservedLocal, .reservedRemote, .halfClosedRemoteLocalIdle, - .halfClosedRemoteLocalActive, .halfOpenRemoteLocalIdle, .closed, - .fullyOpen(localRole: .server, localContentLength: _, remoteContentLength: _, localWindow: _, remoteWindow: _), - .halfClosedLocalPeerActive(localRole: .server, initiatedBy: _, remoteContentLength: _, remoteWindow: _), - .halfClosedLocalPeerActive(localRole: .client, initiatedBy: .server, remoteContentLength: _, remoteWindow: _): - return .init(result: .streamError(streamID: self.streamID, underlyingError: NIOHTTP2Errors.badStreamStateTransition(from: NIOHTTP2StreamState.get(self.state)), type: .protocolError), effect: nil) + .halfClosedRemoteLocalActive, .halfOpenRemoteLocalIdle, .closed, + .fullyOpen( + localRole: .server, + localContentLength: _, + remoteContentLength: _, + localWindow: _, + remoteWindow: _ + ), + .halfClosedLocalPeerActive(localRole: .server, initiatedBy: _, remoteContentLength: _, remoteWindow: _), + .halfClosedLocalPeerActive( + localRole: .client, + initiatedBy: .server, + remoteContentLength: _, + remoteWindow: _ + ): + return .init( + result: .streamError( + streamID: self.streamID, + underlyingError: NIOHTTP2Errors.badStreamStateTransition(from: NIOHTTP2StreamState.get(self.state)), + type: .protocolError + ), + effect: nil + ) } } @@ -746,43 +1203,121 @@ extension HTTP2StreamStateMachine { // can send no further data // - closed, because the entire stream is closed now switch self.state { - case .reservedRemote(remoteWindow: var remoteWindow, requestVerb: let requestVerb): + case .reservedRemote(var remoteWindow, let requestVerb): try remoteWindow.windowUpdate(by: windowIncrement) self.state = .reservedRemote(remoteWindow: remoteWindow, requestVerb: requestVerb) - windowEffect = .windowSizeChange(.init(streamID: self.streamID, localStreamWindowSize: nil, remoteStreamWindowSize: Int(remoteWindow))) + windowEffect = .windowSizeChange( + .init( + streamID: self.streamID, + localStreamWindowSize: nil, + remoteStreamWindowSize: Int(remoteWindow) + ) + ) - case .halfOpenLocalPeerIdle(localWindow: let localWindow, localContentLength: let localContentLength, remoteWindow: var remoteWindow, requestVerb: let requestVerb): + case .halfOpenLocalPeerIdle(let localWindow, let localContentLength, var remoteWindow, let requestVerb): try remoteWindow.windowUpdate(by: windowIncrement) - self.state = .halfOpenLocalPeerIdle(localWindow: localWindow, localContentLength: localContentLength, remoteWindow: remoteWindow, requestVerb: requestVerb) - windowEffect = .windowSizeChange(.init(streamID: self.streamID, localStreamWindowSize: Int(localWindow), remoteStreamWindowSize: Int(remoteWindow))) + self.state = .halfOpenLocalPeerIdle( + localWindow: localWindow, + localContentLength: localContentLength, + remoteWindow: remoteWindow, + requestVerb: requestVerb + ) + windowEffect = .windowSizeChange( + .init( + streamID: self.streamID, + localStreamWindowSize: Int(localWindow), + remoteStreamWindowSize: Int(remoteWindow) + ) + ) - case .halfOpenRemoteLocalIdle(localWindow: let localWindow, remoteContentLength: let remoteContentLength, remoteWindow: var remoteWindow, requestVerb: let requestVerb): + case .halfOpenRemoteLocalIdle(let localWindow, let remoteContentLength, var remoteWindow, let requestVerb): try remoteWindow.windowUpdate(by: windowIncrement) - self.state = .halfOpenRemoteLocalIdle(localWindow: localWindow, remoteContentLength: remoteContentLength, remoteWindow: remoteWindow, requestVerb: requestVerb) - windowEffect = .windowSizeChange(.init(streamID: self.streamID, localStreamWindowSize: Int(localWindow), remoteStreamWindowSize: Int(remoteWindow))) + self.state = .halfOpenRemoteLocalIdle( + localWindow: localWindow, + remoteContentLength: remoteContentLength, + remoteWindow: remoteWindow, + requestVerb: requestVerb + ) + windowEffect = .windowSizeChange( + .init( + streamID: self.streamID, + localStreamWindowSize: Int(localWindow), + remoteStreamWindowSize: Int(remoteWindow) + ) + ) - case .fullyOpen(localRole: let localRole, localContentLength: let localContentLength, remoteContentLength: let remoteContentLength, localWindow: let localWindow, remoteWindow: var remoteWindow): + case .fullyOpen( + let localRole, + let localContentLength, + let remoteContentLength, + let localWindow, + var remoteWindow + ): try remoteWindow.windowUpdate(by: windowIncrement) - self.state = .fullyOpen(localRole: localRole, localContentLength: localContentLength, remoteContentLength: remoteContentLength, localWindow: localWindow, remoteWindow: remoteWindow) - windowEffect = .windowSizeChange(.init(streamID: self.streamID, localStreamWindowSize: Int(localWindow), remoteStreamWindowSize: Int(remoteWindow))) + self.state = .fullyOpen( + localRole: localRole, + localContentLength: localContentLength, + remoteContentLength: remoteContentLength, + localWindow: localWindow, + remoteWindow: remoteWindow + ) + windowEffect = .windowSizeChange( + .init( + streamID: self.streamID, + localStreamWindowSize: Int(localWindow), + remoteStreamWindowSize: Int(remoteWindow) + ) + ) - case .halfClosedLocalPeerIdle(remoteWindow: var remoteWindow, requestVerb: let requestVerb): + case .halfClosedLocalPeerIdle(var remoteWindow, let requestVerb): try remoteWindow.windowUpdate(by: windowIncrement) self.state = .halfClosedLocalPeerIdle(remoteWindow: remoteWindow, requestVerb: requestVerb) - windowEffect = .windowSizeChange(.init(streamID: self.streamID, localStreamWindowSize: nil, remoteStreamWindowSize: Int(remoteWindow))) + windowEffect = .windowSizeChange( + .init( + streamID: self.streamID, + localStreamWindowSize: nil, + remoteStreamWindowSize: Int(remoteWindow) + ) + ) - case .halfClosedLocalPeerActive(localRole: let localRole, initiatedBy: let initiatedBy, remoteContentLength: let remoteContentLength, remoteWindow: var remoteWindow): + case .halfClosedLocalPeerActive(let localRole, let initiatedBy, let remoteContentLength, var remoteWindow): try remoteWindow.windowUpdate(by: windowIncrement) - self.state = .halfClosedLocalPeerActive(localRole: localRole, initiatedBy: initiatedBy, remoteContentLength: remoteContentLength, remoteWindow: remoteWindow) - windowEffect = .windowSizeChange(.init(streamID: self.streamID, localStreamWindowSize: nil, remoteStreamWindowSize: Int(remoteWindow))) + self.state = .halfClosedLocalPeerActive( + localRole: localRole, + initiatedBy: initiatedBy, + remoteContentLength: remoteContentLength, + remoteWindow: remoteWindow + ) + windowEffect = .windowSizeChange( + .init( + streamID: self.streamID, + localStreamWindowSize: nil, + remoteStreamWindowSize: Int(remoteWindow) + ) + ) case .idle, .reservedLocal, .halfClosedRemoteLocalIdle, .halfClosedRemoteLocalActive, .closed: - return .init(result: .streamError(streamID: self.streamID, underlyingError: NIOHTTP2Errors.badStreamStateTransition(from: NIOHTTP2StreamState.get(self.state)), type: .protocolError), effect: nil) + return .init( + result: .streamError( + streamID: self.streamID, + underlyingError: NIOHTTP2Errors.badStreamStateTransition( + from: NIOHTTP2StreamState.get(self.state) + ), + type: .protocolError + ), + effect: nil + ) } } catch let error where error is NIOHTTP2Errors.InvalidFlowControlWindowSize { - return .init(result: .streamError(streamID: self.streamID, underlyingError: error, type: .flowControlError), effect: nil) + return .init( + result: .streamError(streamID: self.streamID, underlyingError: error, type: .flowControlError), + effect: nil + ) } catch let error where error is NIOHTTP2Errors.InvalidWindowIncrementSize { - return .init(result: .streamError(streamID: self.streamID, underlyingError: error, type: .protocolError), effect: nil) + return .init( + result: .streamError(streamID: self.streamID, underlyingError: error, type: .protocolError), + effect: nil + ) } catch { preconditionFailure("Unexpected error: \(error)") } @@ -806,47 +1341,113 @@ extension HTTP2StreamStateMachine { // it is possible that those frames may have been in flight when we were closing the stream, and so we shouldn't cause // the stream to explode simply for that reason. In this case, we just ignore the data. switch self.state { - case .reservedLocal(localWindow: var localWindow, requestVerb: let requestVerb): + case .reservedLocal(var localWindow, let requestVerb): try localWindow.windowUpdate(by: windowIncrement) self.state = .reservedLocal(localWindow: localWindow, requestVerb: requestVerb) - windowEffect = .windowSizeChange(.init(streamID: self.streamID, localStreamWindowSize: Int(localWindow), remoteStreamWindowSize: nil)) + windowEffect = .windowSizeChange( + .init(streamID: self.streamID, localStreamWindowSize: Int(localWindow), remoteStreamWindowSize: nil) + ) - case .halfOpenLocalPeerIdle(localWindow: var localWindow, localContentLength: let localContentLength, remoteWindow: let remoteWindow, requestVerb: let requestVerb): + case .halfOpenLocalPeerIdle(var localWindow, let localContentLength, let remoteWindow, let requestVerb): try localWindow.windowUpdate(by: windowIncrement) - self.state = .halfOpenLocalPeerIdle(localWindow: localWindow, localContentLength: localContentLength, remoteWindow: remoteWindow, requestVerb: requestVerb) - windowEffect = .windowSizeChange(.init(streamID: self.streamID, localStreamWindowSize: Int(localWindow), remoteStreamWindowSize: Int(remoteWindow))) + self.state = .halfOpenLocalPeerIdle( + localWindow: localWindow, + localContentLength: localContentLength, + remoteWindow: remoteWindow, + requestVerb: requestVerb + ) + windowEffect = .windowSizeChange( + .init( + streamID: self.streamID, + localStreamWindowSize: Int(localWindow), + remoteStreamWindowSize: Int(remoteWindow) + ) + ) - case .halfOpenRemoteLocalIdle(localWindow: var localWindow, remoteContentLength: let remoteContentLength, remoteWindow: let remoteWindow, requestVerb: let requestVerb): + case .halfOpenRemoteLocalIdle(var localWindow, let remoteContentLength, let remoteWindow, let requestVerb): try localWindow.windowUpdate(by: windowIncrement) - self.state = .halfOpenRemoteLocalIdle(localWindow: localWindow, remoteContentLength: remoteContentLength, remoteWindow: remoteWindow, requestVerb: requestVerb) - windowEffect = .windowSizeChange(.init(streamID: self.streamID, localStreamWindowSize: Int(localWindow), remoteStreamWindowSize: Int(remoteWindow))) + self.state = .halfOpenRemoteLocalIdle( + localWindow: localWindow, + remoteContentLength: remoteContentLength, + remoteWindow: remoteWindow, + requestVerb: requestVerb + ) + windowEffect = .windowSizeChange( + .init( + streamID: self.streamID, + localStreamWindowSize: Int(localWindow), + remoteStreamWindowSize: Int(remoteWindow) + ) + ) - case .fullyOpen(localRole: let localRole, localContentLength: let localContentLength, remoteContentLength: let remoteContentLength, localWindow: var localWindow, remoteWindow: let remoteWindow): + case .fullyOpen( + let localRole, + let localContentLength, + let remoteContentLength, + var localWindow, + let remoteWindow + ): try localWindow.windowUpdate(by: windowIncrement) - self.state = .fullyOpen(localRole: localRole, localContentLength: localContentLength, remoteContentLength: remoteContentLength, localWindow: localWindow, remoteWindow: remoteWindow) - windowEffect = .windowSizeChange(.init(streamID: self.streamID, localStreamWindowSize: Int(localWindow), remoteStreamWindowSize: Int(remoteWindow))) + self.state = .fullyOpen( + localRole: localRole, + localContentLength: localContentLength, + remoteContentLength: remoteContentLength, + localWindow: localWindow, + remoteWindow: remoteWindow + ) + windowEffect = .windowSizeChange( + .init( + streamID: self.streamID, + localStreamWindowSize: Int(localWindow), + remoteStreamWindowSize: Int(remoteWindow) + ) + ) - case .halfClosedRemoteLocalIdle(localWindow: var localWindow, requestVerb: let requestVerb): + case .halfClosedRemoteLocalIdle(var localWindow, let requestVerb): try localWindow.windowUpdate(by: windowIncrement) self.state = .halfClosedRemoteLocalIdle(localWindow: localWindow, requestVerb: requestVerb) - windowEffect = .windowSizeChange(.init(streamID: self.streamID, localStreamWindowSize: Int(localWindow), remoteStreamWindowSize: nil)) + windowEffect = .windowSizeChange( + .init(streamID: self.streamID, localStreamWindowSize: Int(localWindow), remoteStreamWindowSize: nil) + ) - case .halfClosedRemoteLocalActive(localRole: let localRole, initiatedBy: let initiatedBy, localContentLength: let localContentLength, localWindow: var localWindow): + case .halfClosedRemoteLocalActive(let localRole, let initiatedBy, let localContentLength, var localWindow): try localWindow.windowUpdate(by: windowIncrement) - self.state = .halfClosedRemoteLocalActive(localRole: localRole, initiatedBy: initiatedBy, localContentLength: localContentLength, localWindow: localWindow) - windowEffect = .windowSizeChange(.init(streamID: self.streamID, localStreamWindowSize: Int(localWindow), remoteStreamWindowSize: nil)) + self.state = .halfClosedRemoteLocalActive( + localRole: localRole, + initiatedBy: initiatedBy, + localContentLength: localContentLength, + localWindow: localWindow + ) + windowEffect = .windowSizeChange( + .init(streamID: self.streamID, localStreamWindowSize: Int(localWindow), remoteStreamWindowSize: nil) + ) case .halfClosedLocalPeerIdle, .halfClosedLocalPeerActive: // No-op, see above windowEffect = nil case .idle, .reservedRemote, .closed: - return .init(result: .streamError(streamID: self.streamID, underlyingError: NIOHTTP2Errors.badStreamStateTransition(from: NIOHTTP2StreamState.get(self.state)), type: .protocolError), effect: nil) + return .init( + result: .streamError( + streamID: self.streamID, + underlyingError: NIOHTTP2Errors.badStreamStateTransition( + from: NIOHTTP2StreamState.get(self.state) + ), + type: .protocolError + ), + effect: nil + ) } } catch let error where error is NIOHTTP2Errors.InvalidFlowControlWindowSize { - return .init(result: .streamError(streamID: self.streamID, underlyingError: error, type: .flowControlError), effect: nil) + return .init( + result: .streamError(streamID: self.streamID, underlyingError: error, type: .flowControlError), + effect: nil + ) } catch let error where error is NIOHTTP2Errors.InvalidWindowIncrementSize { - return .init(result: .streamError(streamID: self.streamID, underlyingError: error, type: .protocolError), effect: nil) + return .init( + result: .streamError(streamID: self.streamID, underlyingError: error, type: .protocolError), + effect: nil + ) } catch { preconditionFailure("Unexpected error: \(error)") } @@ -864,7 +1465,13 @@ extension HTTP2StreamStateMachine { mutating func receiveRstStream(reason: HTTP2ErrorCode) -> StateMachineResultWithStreamEffect { // We can receive RST_STREAM frames in any state but idle. if case .idle = self.state { - return .init(result: .connectionError(underlyingError: NIOHTTP2Errors.badStreamStateTransition(from: NIOHTTP2StreamState.get(self.state)), type: .protocolError), effect: nil) + return .init( + result: .connectionError( + underlyingError: NIOHTTP2Errors.badStreamStateTransition(from: NIOHTTP2StreamState.get(self.state)), + type: .protocolError + ), + effect: nil + ) } self.state = .closed(reason: reason) @@ -876,33 +1483,60 @@ extension HTTP2StreamStateMachine { /// This change causes the remote flow control window to be resized. mutating func localInitialWindowSizeChanged(by change: Int32) throws { switch self.state { - case .idle(localRole: let role, localWindow: let localWindow, remoteWindow: var remoteWindow): + case .idle(localRole: let role, let localWindow, var remoteWindow): try remoteWindow.initialSizeChanged(by: change) self.state = .idle(localRole: role, localWindow: localWindow, remoteWindow: remoteWindow) - case .reservedRemote(remoteWindow: var remoteWindow, requestVerb: let requestVerb): + case .reservedRemote(var remoteWindow, let requestVerb): try remoteWindow.initialSizeChanged(by: change) self.state = .reservedRemote(remoteWindow: remoteWindow, requestVerb: requestVerb) - case .halfOpenLocalPeerIdle(localWindow: let localWindow, localContentLength: let localContentLength, remoteWindow: var remoteWindow, requestVerb: let requestVerb): + case .halfOpenLocalPeerIdle(let localWindow, let localContentLength, var remoteWindow, let requestVerb): try remoteWindow.initialSizeChanged(by: change) - self.state = .halfOpenLocalPeerIdle(localWindow: localWindow, localContentLength: localContentLength, remoteWindow: remoteWindow, requestVerb: requestVerb) + self.state = .halfOpenLocalPeerIdle( + localWindow: localWindow, + localContentLength: localContentLength, + remoteWindow: remoteWindow, + requestVerb: requestVerb + ) - case .halfOpenRemoteLocalIdle(localWindow: let localWindow, remoteContentLength: let remoteContentLength, remoteWindow: var remoteWindow, requestVerb: let requestVerb): + case .halfOpenRemoteLocalIdle(let localWindow, let remoteContentLength, var remoteWindow, let requestVerb): try remoteWindow.initialSizeChanged(by: change) - self.state = .halfOpenRemoteLocalIdle(localWindow: localWindow, remoteContentLength: remoteContentLength, remoteWindow: remoteWindow, requestVerb: requestVerb) + self.state = .halfOpenRemoteLocalIdle( + localWindow: localWindow, + remoteContentLength: remoteContentLength, + remoteWindow: remoteWindow, + requestVerb: requestVerb + ) - case .fullyOpen(localRole: let localRole, localContentLength: let localContentLength, remoteContentLength: let remoteContentLength, localWindow: let localWindow, remoteWindow: var remoteWindow): + case .fullyOpen( + let localRole, + let localContentLength, + let remoteContentLength, + let localWindow, + var remoteWindow + ): try remoteWindow.initialSizeChanged(by: change) - self.state = .fullyOpen(localRole: localRole, localContentLength: localContentLength, remoteContentLength: remoteContentLength, localWindow: localWindow, remoteWindow: remoteWindow) + self.state = .fullyOpen( + localRole: localRole, + localContentLength: localContentLength, + remoteContentLength: remoteContentLength, + localWindow: localWindow, + remoteWindow: remoteWindow + ) - case .halfClosedLocalPeerIdle(remoteWindow: var remoteWindow, requestVerb: let requestVerb): + case .halfClosedLocalPeerIdle(var remoteWindow, let requestVerb): try remoteWindow.initialSizeChanged(by: change) self.state = .halfClosedLocalPeerIdle(remoteWindow: remoteWindow, requestVerb: requestVerb) - case .halfClosedLocalPeerActive(localRole: let localRole, initiatedBy: let initiatedBy, remoteContentLength: let remoteContentLength, remoteWindow: var remoteWindow): + case .halfClosedLocalPeerActive(let localRole, let initiatedBy, let remoteContentLength, var remoteWindow): try remoteWindow.initialSizeChanged(by: change) - self.state = .halfClosedLocalPeerActive(localRole: localRole, initiatedBy: initiatedBy, remoteContentLength: remoteContentLength, remoteWindow: remoteWindow) + self.state = .halfClosedLocalPeerActive( + localRole: localRole, + initiatedBy: initiatedBy, + remoteContentLength: remoteContentLength, + remoteWindow: remoteWindow + ) case .reservedLocal, .halfClosedRemoteLocalIdle, .halfClosedRemoteLocalActive: // In these states the remote side of this stream is closed and will never be open, so its flow control window is not relevant. @@ -920,33 +1554,60 @@ extension HTTP2StreamStateMachine { /// This change causes the local flow control window to be resized. mutating func remoteInitialWindowSizeChanged(by change: Int32) throws { switch self.state { - case .idle(localRole: let role, localWindow: var localWindow, remoteWindow: let remoteWindow): + case .idle(localRole: let role, var localWindow, let remoteWindow): try localWindow.initialSizeChanged(by: change) self.state = .idle(localRole: role, localWindow: localWindow, remoteWindow: remoteWindow) - case .reservedLocal(localWindow: var localWindow, requestVerb: let requestVerb): + case .reservedLocal(var localWindow, let requestVerb): try localWindow.initialSizeChanged(by: change) self.state = .reservedLocal(localWindow: localWindow, requestVerb: requestVerb) - case .halfOpenLocalPeerIdle(localWindow: var localWindow, localContentLength: let localContentLength, remoteWindow: let remoteWindow, requestVerb: let requestVerb): + case .halfOpenLocalPeerIdle(var localWindow, let localContentLength, let remoteWindow, let requestVerb): try localWindow.initialSizeChanged(by: change) - self.state = .halfOpenLocalPeerIdle(localWindow: localWindow, localContentLength: localContentLength, remoteWindow: remoteWindow, requestVerb: requestVerb) + self.state = .halfOpenLocalPeerIdle( + localWindow: localWindow, + localContentLength: localContentLength, + remoteWindow: remoteWindow, + requestVerb: requestVerb + ) - case .halfOpenRemoteLocalIdle(localWindow: var localWindow, remoteContentLength: let remoteContentLength, remoteWindow: let remoteWindow, requestVerb: let requestVerb): + case .halfOpenRemoteLocalIdle(var localWindow, let remoteContentLength, let remoteWindow, let requestVerb): try localWindow.initialSizeChanged(by: change) - self.state = .halfOpenRemoteLocalIdle(localWindow: localWindow, remoteContentLength: remoteContentLength, remoteWindow: remoteWindow, requestVerb: requestVerb) + self.state = .halfOpenRemoteLocalIdle( + localWindow: localWindow, + remoteContentLength: remoteContentLength, + remoteWindow: remoteWindow, + requestVerb: requestVerb + ) - case .fullyOpen(localRole: let localRole, localContentLength: let localContentLength, remoteContentLength: let remoteContentLength, localWindow: var localWindow, remoteWindow: let remoteWindow): + case .fullyOpen( + let localRole, + let localContentLength, + let remoteContentLength, + var localWindow, + let remoteWindow + ): try localWindow.initialSizeChanged(by: change) - self.state = .fullyOpen(localRole: localRole, localContentLength: localContentLength, remoteContentLength: remoteContentLength, localWindow: localWindow, remoteWindow: remoteWindow) + self.state = .fullyOpen( + localRole: localRole, + localContentLength: localContentLength, + remoteContentLength: remoteContentLength, + localWindow: localWindow, + remoteWindow: remoteWindow + ) - case .halfClosedRemoteLocalIdle(localWindow: var localWindow, requestVerb: let requestVerb): + case .halfClosedRemoteLocalIdle(var localWindow, let requestVerb): try localWindow.initialSizeChanged(by: change) self.state = .halfClosedRemoteLocalIdle(localWindow: localWindow, requestVerb: requestVerb) - case .halfClosedRemoteLocalActive(localRole: let localRole, initiatedBy: let initiatedBy, localContentLength: let localContentLength, localWindow: var localWindow): + case .halfClosedRemoteLocalActive(let localRole, let initiatedBy, let localContentLength, var localWindow): try localWindow.initialSizeChanged(by: change) - self.state = .halfClosedRemoteLocalActive(localRole: localRole, initiatedBy: initiatedBy, localContentLength: localContentLength, localWindow: localWindow) + self.state = .halfClosedRemoteLocalActive( + localRole: localRole, + initiatedBy: initiatedBy, + localContentLength: localContentLength, + localWindow: localWindow + ) case .reservedRemote, .halfClosedLocalPeerIdle, .halfClosedLocalPeerActive: // In these states the local side of this stream is closed and will never be open, so its flow control window is not relevant. @@ -964,13 +1625,26 @@ extension HTTP2StreamStateMachine { extension HTTP2StreamStateMachine { /// Validate that the request headers meet the requirements of RFC 7540. If they do, /// transitions to the target state. - private mutating func processRequestHeaders(_ headers: HPACKHeaders, validateHeaderBlock: Bool, localRole: StreamRole, localSupportsExtendedConnect: Bool, remoteSupportsExtendedConnect: Bool, targetState target: State, targetEffect effect: StreamStateChange?) -> StateMachineResultWithStreamEffect { + private mutating func processRequestHeaders( + _ headers: HPACKHeaders, + validateHeaderBlock: Bool, + localRole: StreamRole, + localSupportsExtendedConnect: Bool, + remoteSupportsExtendedConnect: Bool, + targetState target: State, + targetEffect effect: StreamStateChange? + ) -> StateMachineResultWithStreamEffect { if validateHeaderBlock { do { - let supportsExtendedConnect = (localRole == .client && remoteSupportsExtendedConnect) || (localRole == .server && localSupportsExtendedConnect) + let supportsExtendedConnect = + (localRole == .client && remoteSupportsExtendedConnect) + || (localRole == .server && localSupportsExtendedConnect) try headers.validateRequestBlock(supportsExtendedConnect: supportsExtendedConnect) } catch { - return StateMachineResultWithStreamEffect(result: .streamError(streamID: self.streamID, underlyingError: error, type: .protocolError), effect: nil) + return StateMachineResultWithStreamEffect( + result: .streamError(streamID: self.streamID, underlyingError: error, type: .protocolError), + effect: nil + ) } } @@ -981,12 +1655,20 @@ extension HTTP2StreamStateMachine { /// Validate that the response headers meet the requirements of RFC 7540. Also characterises /// them to check whether the headers are informational or final, and if the headers are /// valid and correspond to a final response, transitions to the appropriate target state. - private mutating func processResponseHeaders(_ headers: HPACKHeaders, validateHeaderBlock: Bool, targetStateIfFinal finalState: State, targetEffectIfFinal finalEffect: StreamStateChange?) -> StateMachineResultWithStreamEffect { + private mutating func processResponseHeaders( + _ headers: HPACKHeaders, + validateHeaderBlock: Bool, + targetStateIfFinal finalState: State, + targetEffectIfFinal finalEffect: StreamStateChange? + ) -> StateMachineResultWithStreamEffect { if validateHeaderBlock { do { try headers.validateResponseBlock() } catch { - return StateMachineResultWithStreamEffect(result: .streamError(streamID: self.streamID, underlyingError: error, type: .protocolError), effect: nil) + return StateMachineResultWithStreamEffect( + result: .streamError(streamID: self.streamID, underlyingError: error, type: .protocolError), + effect: nil + ) } } @@ -1002,18 +1684,34 @@ extension HTTP2StreamStateMachine { /// Validates that the trailers meet the requirements of RFC 7540. If they do, transitions to the /// target final state. - private mutating func processTrailers(_ headers: HPACKHeaders, validateHeaderBlock: Bool, isEndStreamSet endStream: Bool, targetState target: State, targetEffect effect: StreamStateChange?) -> StateMachineResultWithStreamEffect { + private mutating func processTrailers( + _ headers: HPACKHeaders, + validateHeaderBlock: Bool, + isEndStreamSet endStream: Bool, + targetState target: State, + targetEffect effect: StreamStateChange? + ) -> StateMachineResultWithStreamEffect { if validateHeaderBlock { do { try headers.validateTrailersBlock() } catch { - return StateMachineResultWithStreamEffect(result: .streamError(streamID: self.streamID, underlyingError: error, type: .protocolError), effect: nil) + return StateMachineResultWithStreamEffect( + result: .streamError(streamID: self.streamID, underlyingError: error, type: .protocolError), + effect: nil + ) } } // End stream must be set on trailers. guard endStream else { - return StateMachineResultWithStreamEffect(result: .streamError(streamID: self.streamID, underlyingError: NIOHTTP2Errors.trailersWithoutEndStream(streamID: self.streamID), type: .protocolError), effect: nil) + return StateMachineResultWithStreamEffect( + result: .streamError( + streamID: self.streamID, + underlyingError: NIOHTTP2Errors.trailersWithoutEndStream(streamID: self.streamID), + type: .protocolError + ), + effect: nil + ) } self.state = target @@ -1021,16 +1719,15 @@ extension HTTP2StreamStateMachine { } } -extension HTTP2StreamStateMachine: PerStreamData { } +extension HTTP2StreamStateMachine: PerStreamData {} - -private extension HPACKHeaders { +extension HPACKHeaders { /// Whether this `HPACKHeaders` corresponds to a final response or not. /// /// This property is only valid if called on a response header block. If the :status header /// is not present, this will return "false" - var isInformationalResponse: Bool { - return self.first { $0.name == ":status" }?.value.first == "1" + fileprivate var isInformationalResponse: Bool { + self.first { $0.name == ":status" }?.value.first == "1" } } @@ -1058,7 +1755,7 @@ public struct NIOHTTP2StreamState: Hashable, CustomStringConvertible, Sendable { } public var description: String { - return "\(state)" + "\(state)" } public static let idle = NIOHTTP2StreamState(state: .idle) @@ -1072,7 +1769,7 @@ public struct NIOHTTP2StreamState: Hashable, CustomStringConvertible, Sendable { public static let halfClosedRemoteLocalIdle = NIOHTTP2StreamState(state: .halfClosedRemoteLocalIdle) public static let halfClosedRemoteLocalActive = NIOHTTP2StreamState(state: .halfClosedRemoteLocalActive) public static let closed = NIOHTTP2StreamState(state: .closed) - + fileprivate static func get(_ state: HTTP2StreamStateMachine.State) -> NIOHTTP2StreamState { switch state { case .idle: return idle diff --git a/Sources/NIOHTTP2/WatermarkedFlowController.swift b/Sources/NIOHTTP2/WatermarkedFlowController.swift index 9340593..e95b6c8 100644 --- a/Sources/NIOHTTP2/WatermarkedFlowController.swift +++ b/Sources/NIOHTTP2/WatermarkedFlowController.swift @@ -12,7 +12,6 @@ // //===----------------------------------------------------------------------===// - /// Keeps track of whether or not a `Channel` should be able to write based on watermarks. /// /// A `WatermarkedFlowController` is a straightforward object that keeps track of @@ -49,7 +48,10 @@ struct WatermarkedFlowController { internal private(set) var isWritable: Bool internal init(highWatermark: Int, lowWatermark: Int) { - precondition(lowWatermark < highWatermark, "Low watermark \(lowWatermark) exceeds or meets High watermark \(highWatermark)") + precondition( + lowWatermark < highWatermark, + "Low watermark \(lowWatermark) exceeds or meets High watermark \(highWatermark)" + ) precondition(lowWatermark >= 0, "Low watermark \(lowWatermark) is negative") self.highWatermark = highWatermark @@ -59,7 +61,6 @@ struct WatermarkedFlowController { } } - extension WatermarkedFlowController { /// Notifies the flow controller that we have buffered some bytes to send to the network. mutating func bufferedBytes(_ bufferedBytes: Int) { @@ -91,12 +92,10 @@ extension WatermarkedFlowController { } } - -extension WatermarkedFlowController: Equatable { } - +extension WatermarkedFlowController: Equatable {} extension WatermarkedFlowController: CustomDebugStringConvertible { var debugDescription: String { - return "WatermarkedFlowController(highWatermark: \(self.highWatermark), lowWatermark: \(self.lowWatermark), pendingBytes: \(self.pendingBytes), isWritable: \(self.isWritable))" + "WatermarkedFlowController(highWatermark: \(self.highWatermark), lowWatermark: \(self.lowWatermark), pendingBytes: \(self.pendingBytes), isWritable: \(self.isWritable))" } } diff --git a/Sources/NIOHTTP2PerformanceTester/Bench1Conn10kRequests.swift b/Sources/NIOHTTP2PerformanceTester/Bench1Conn10kRequests.swift index 0a371c7..4e0919b 100644 --- a/Sources/NIOHTTP2PerformanceTester/Bench1Conn10kRequests.swift +++ b/Sources/NIOHTTP2PerformanceTester/Bench1Conn10kRequests.swift @@ -13,9 +13,9 @@ //===----------------------------------------------------------------------===// import NIOCore -import NIOPosix import NIOHTTP1 import NIOHTTP2 +import NIOPosix final class Bench1Conn10kRequests: Benchmark { var group: MultiThreadedEventLoopGroup! @@ -40,7 +40,7 @@ final class Bench1Conn10kRequests: Benchmark { func run() throws -> Int { var bodyByteCount = 0 - for _ in 0 ..< 10_000 { + for _ in 0..<10_000 { bodyByteCount += try sendOneRequest(channel: self.client, multiplexer: self.clientMultiplexer) } return bodyByteCount @@ -55,14 +55,15 @@ func setupServer(group: EventLoopGroup) throws -> Channel { // Set the handlers that are applied to the accepted Channels .childChannelInitializer { channel in - return channel.configureHTTP2Pipeline(mode: .server) { streamChannel -> EventLoopFuture in - return streamChannel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ServerCodec()).flatMap { () -> EventLoopFuture in + channel.configureHTTP2Pipeline(mode: .server) { streamChannel -> EventLoopFuture in + streamChannel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ServerCodec()).flatMap { + () -> EventLoopFuture in streamChannel.pipeline.addHandler(HTTP1TestServer()) }.flatMap { () -> EventLoopFuture in streamChannel.pipeline.addHandler(ErrorHandler()) } }.flatMap { (_: HTTP2StreamMultiplexer) in - return channel.pipeline.addHandler(ErrorHandler()) + channel.pipeline.addHandler(ErrorHandler()) } } @@ -77,30 +78,39 @@ func setupServer(group: EventLoopGroup) throws -> Channel { func sendOneRequest(channel: Channel, multiplexer: HTTP2StreamMultiplexer) throws -> Int { let responseReceivedPromise = channel.eventLoop.makePromise(of: Int.self) let requestStreamInitializer: NIOChannelInitializer = { channel in - return channel.pipeline.addHandlers([HTTP2FramePayloadToHTTP1ClientCodec(httpProtocol: .https), - SendRequestHandler(host: "127.0.0.1", - request: .init(version: .init(major: 2, minor: 0), - method: .GET, - uri: "/", headers: ["host": "localhost"]), - responseReceivedPromise: responseReceivedPromise), - ErrorHandler()], - position: .last) + channel.pipeline.addHandlers( + [ + HTTP2FramePayloadToHTTP1ClientCodec(httpProtocol: .https), + SendRequestHandler( + host: "127.0.0.1", + request: .init( + version: .init(major: 2, minor: 0), + method: .GET, + uri: "/", + headers: ["host": "localhost"] + ), + responseReceivedPromise: responseReceivedPromise + ), + ErrorHandler(), + ], + position: .last + ) } channel.pipeline.handler(type: HTTP2StreamMultiplexer.self).whenSuccess { multiplexer in - multiplexer.createStreamChannel(promise: nil, requestStreamInitializer) + multiplexer.createStreamChannel(promise: nil, requestStreamInitializer) } return try responseReceivedPromise.futureResult.wait() } func setupClient(group: EventLoopGroup, address: SocketAddress) throws -> (Channel, HTTP2StreamMultiplexer) { - return try ClientBootstrap(group: group) + try ClientBootstrap(group: group) .channelOption(ChannelOptions.socket(IPPROTO_TCP, TCP_NODELAY), value: 1) .channelInitializer { channel in channel.pipeline.addHandler(ErrorHandler()) } .connect(to: address).flatMap { channel in channel.configureHTTP2Pipeline(mode: .client, position: .first) { channel -> EventLoopFuture in - return channel.eventLoop.makeSucceededFuture(()) + channel.eventLoop.makeSucceededFuture(()) }.map { (channel, $0) } }.wait() } @@ -125,11 +135,21 @@ final class HTTP1TestServer: ChannelInboundHandler { var headers = HTTPHeaders() headers.add(name: "content-length", value: "5") headers.add(name: "x-stream-id", value: String(Int(streamID))) - channel.write(loopBoundSelf.value.wrapOutboundOut(HTTPServerResponsePart.head(HTTPResponseHead(version: .init(major: 2, minor: 0), status: .ok, headers: headers))), promise: nil) + channel.write( + loopBoundSelf.value.wrapOutboundOut( + HTTPServerResponsePart.head( + HTTPResponseHead(version: .init(major: 2, minor: 0), status: .ok, headers: headers) + ) + ), + promise: nil + ) var buffer = channel.allocator.buffer(capacity: 12) buffer.writeStaticString("hello") - channel.write(loopBoundSelf.value.wrapOutboundOut(HTTPServerResponsePart.body(.byteBuffer(buffer))), promise: nil) + channel.write( + loopBoundSelf.value.wrapOutboundOut(HTTPServerResponsePart.body(.byteBuffer(buffer))), + promise: nil + ) return channel.writeAndFlush(loopBoundSelf.value.wrapOutboundOut(HTTPServerResponsePart.end(nil))) }.whenComplete { _ in loopBoundContext.value.close(promise: nil) diff --git a/Sources/NIOHTTP2PerformanceTester/HPACKHeaderCanonicalFormBenchmark.swift b/Sources/NIOHTTP2PerformanceTester/HPACKHeaderCanonicalFormBenchmark.swift index 2853c05..3dc4377 100644 --- a/Sources/NIOHTTP2PerformanceTester/HPACKHeaderCanonicalFormBenchmark.swift +++ b/Sources/NIOHTTP2PerformanceTester/HPACKHeaderCanonicalFormBenchmark.swift @@ -39,10 +39,9 @@ final class HPACKHeaderCanonicalFormBenchmark { } } - extension HPACKHeaderCanonicalFormBenchmark: Benchmark { - func setUp() throws { } - func tearDown() { } + func setUp() throws {} + func tearDown() {} func run() throws -> Int { var count = 0 diff --git a/Sources/NIOHTTP2PerformanceTester/HPACKHeaderDecodingBenchmark.swift b/Sources/NIOHTTP2PerformanceTester/HPACKHeaderDecodingBenchmark.swift index 422a362..a346c83 100644 --- a/Sources/NIOHTTP2PerformanceTester/HPACKHeaderDecodingBenchmark.swift +++ b/Sources/NIOHTTP2PerformanceTester/HPACKHeaderDecodingBenchmark.swift @@ -15,7 +15,6 @@ import NIOCore import NIOHPACK - final class HPACKHeaderDecodingBenchmark { private var headers: ByteBuffer private let loopCount: Int @@ -28,11 +27,10 @@ final class HPACKHeaderDecodingBenchmark { } } - extension HPACKHeaderDecodingBenchmark: Benchmark { - func setUp() throws { } + func setUp() throws {} - func tearDown() { } + func tearDown() {} func run() throws -> Int { for _ in 0.. Int { for _ in 0.. Int { var count = 0 - for _ in 0 ..< self.iterations { + for _ in 0.. Int { for _ in 0.. Int { for _ in 0.. EventLoopFuture in - return streamChannel.pipeline.addHandler(TestServer()) + streamChannel.pipeline.addHandler(TestServer()) }.wait() try channel.connect(to: .init(unixDomainSocketPath: "/fake"), promise: nil) @@ -126,7 +129,7 @@ final class ServerOnly10KRequestsBenchmark: Benchmark { initialBytes.writeImmutableBuffer(self.settingsACK) try channel.writeInbound(initialBytes) - while try channel.readOutbound(as: ByteBuffer.self) != nil { } + while try channel.readOutbound(as: ByteBuffer.self) != nil {} self.channel = channel } @@ -149,7 +152,7 @@ final class ServerOnly10KRequestsBenchmark: Benchmark { private func sendInterleavedRequests(_ interleavedRequests: Int) throws -> Int { var streamID = self.streamID - for _ in 0 ..< interleavedRequests { + for _ in 0.. EmbeddedChannel { let channel = EmbeddedChannel() _ = try channel.configureHTTP2Pipeline(mode: .server) { streamChannel -> EventLoopFuture in - return streamChannel.pipeline.addHandler(DoNothingServer()) + streamChannel.pipeline.addHandler(DoNothingServer()) }.wait() try channel.pipeline.addHandler(SendGoawayHandler(expectedStreams: self.concurrentStreams)).wait() @@ -106,7 +109,7 @@ final class StreamTeardownBenchmark: Benchmark { initialBytes.writeImmutableBuffer(self.settingsACK) try channel.writeInbound(initialBytes) - while try channel.readOutbound(as: ByteBuffer.self) != nil { } + while try channel.readOutbound(as: ByteBuffer.self) != nil {} return channel } @@ -127,10 +130,13 @@ final class StreamTeardownBenchmark: Benchmark { return bodyByteCount } - private func sendInterleavedRequestsAndTerminate(_ interleavedRequests: Int, _ channel: EmbeddedChannel) throws -> Int { + private func sendInterleavedRequestsAndTerminate( + _ interleavedRequests: Int, + _ channel: EmbeddedChannel + ) throws -> Int { var streamID = HTTP2StreamID(1) - for _ in 0 ..< interleavedRequests { + for _ in 0.. Int) rethrows -> [TimeInterval] { @@ -35,7 +37,7 @@ public func measure(_ fn: () throws -> Int) rethrows -> [TimeInterval] { return end.timeIntervalSince(start) } - _ = try measureOne(fn) /* pre-heat and throw away */ + _ = try measureOne(fn) // pre-heat and throw away var measurements = Array(repeating: 0.0, count: 10) for i in 0..<10 { measurements[i] = try measureOne(fn) @@ -46,7 +48,7 @@ public func measure(_ fn: () throws -> Int) rethrows -> [TimeInterval] { let limitSet = ProcessInfo.processInfo.arguments.dropFirst() -public func measureAndPrint(desc: String, fn: () throws -> Int) rethrows -> Void { +public func measureAndPrint(desc: String, fn: () throws -> Int) rethrows { #if CACHEGRIND // When CACHEGRIND is set we only run a single requested test, and we only run it once. No printing or other mess. if limitSet.contains(desc) { @@ -76,29 +78,89 @@ func measureAndPrint(desc: String, benchmark bench: @autoclosure ( bench.tearDown() } try measureAndPrint(desc: desc) { - return try bench.run() + try bench.run() } } // MARK: Utilities try measureAndPrint(desc: "1_conn_10k_reqs", benchmark: Bench1Conn10kRequests()) -try measureAndPrint(desc: "encode_100k_header_blocks_indexable", benchmark: HPACKHeaderEncodingBenchmark(headers: .indexable, loopCount: 100_000)) -try measureAndPrint(desc: "encode_100k_header_blocks_nonindexable", benchmark: HPACKHeaderEncodingBenchmark(headers: .nonIndexable, loopCount: 100_000)) -try measureAndPrint(desc: "encode_100k_header_blocks_neverIndexed", benchmark: HPACKHeaderEncodingBenchmark(headers: .neverIndexed, loopCount: 100_000)) -try measureAndPrint(desc: "decode_100k_header_blocks_indexable", benchmark: HPACKHeaderDecodingBenchmark(headers: .indexable, loopCount: 100_000)) -try measureAndPrint(desc: "decode_100k_header_blocks_nonindexable", benchmark: HPACKHeaderDecodingBenchmark(headers: .nonIndexable, loopCount: 100_000)) -try measureAndPrint(desc: "decode_100k_header_blocks_neverIndexed", benchmark: HPACKHeaderDecodingBenchmark(headers: .neverIndexed, loopCount: 100_000)) +try measureAndPrint( + desc: "encode_100k_header_blocks_indexable", + benchmark: HPACKHeaderEncodingBenchmark(headers: .indexable, loopCount: 100_000) +) +try measureAndPrint( + desc: "encode_100k_header_blocks_nonindexable", + benchmark: HPACKHeaderEncodingBenchmark(headers: .nonIndexable, loopCount: 100_000) +) +try measureAndPrint( + desc: "encode_100k_header_blocks_neverIndexed", + benchmark: HPACKHeaderEncodingBenchmark(headers: .neverIndexed, loopCount: 100_000) +) +try measureAndPrint( + desc: "decode_100k_header_blocks_indexable", + benchmark: HPACKHeaderDecodingBenchmark(headers: .indexable, loopCount: 100_000) +) +try measureAndPrint( + desc: "decode_100k_header_blocks_nonindexable", + benchmark: HPACKHeaderDecodingBenchmark(headers: .nonIndexable, loopCount: 100_000) +) +try measureAndPrint( + desc: "decode_100k_header_blocks_neverIndexed", + benchmark: HPACKHeaderDecodingBenchmark(headers: .neverIndexed, loopCount: 100_000) +) try measureAndPrint(desc: "hpackheaders_canonical_form", benchmark: HPACKHeaderCanonicalFormBenchmark(.noTrimming)) -try measureAndPrint(desc: "hpackheaders_canonical_form_trimming_whitespace", benchmark: HPACKHeaderCanonicalFormBenchmark(.trimmingWhitespace)) -try measureAndPrint(desc: "hpackheaders_canonical_form_trimming_whitespace_short_strings", benchmark: HPACKHeaderCanonicalFormBenchmark(.trimmingWhitespaceFromShortStrings)) -try measureAndPrint(desc: "hpackheaders_canonical_form_trimming_whitespace_long_strings", benchmark: HPACKHeaderCanonicalFormBenchmark(.trimmingWhitespaceFromLongStrings)) -try measureAndPrint(desc: "hpackheaders_normalize_httpheaders_removing_10k_conn_headers", benchmark: HPACKHeadersNormalizationOfHTTPHeadersBenchmark(headersKind: .manyUniqueConnectionHeaderValues(10_000), iterations: 10)) -try measureAndPrint(desc: "hpackheaders_normalize_httpheaders_keeping_10k_conn_headers", benchmark: HPACKHeadersNormalizationOfHTTPHeadersBenchmark(headersKind: .manyConnectionHeaderValuesWhichAreNotRemoved(10_000), iterations: 10)) -try measureAndPrint(desc: "huffman_encode_basic", benchmark: HuffmanEncodingBenchmark(huffmanString: .basicHuffmanString, loopCount: 100)) -try measureAndPrint(desc: "huffman_encode_complex", benchmark: HuffmanEncodingBenchmark(huffmanString: .complexHuffmanString, loopCount: 100)) -try measureAndPrint(desc: "huffman_decode_basic", benchmark: HuffmanDecodingBenchmark(huffmanBytes: .basicHuffmanBytes, loopCount: 25)) -try measureAndPrint(desc: "huffman_decode_complex", benchmark: HuffmanDecodingBenchmark(huffmanBytes: .complexHuffmanBytes, loopCount: 10)) -try measureAndPrint(desc: "server_only_10k_requests_1_concurrent", benchmark: ServerOnly10KRequestsBenchmark(concurrentStreams: 1)) -try measureAndPrint(desc: "server_only_10k_requests_100_concurrent", benchmark: ServerOnly10KRequestsBenchmark(concurrentStreams: 100)) -try measureAndPrint(desc: "stream_teardown_10k_requests_100_concurrent", benchmark: StreamTeardownBenchmark(concurrentStreams: 100)) +try measureAndPrint( + desc: "hpackheaders_canonical_form_trimming_whitespace", + benchmark: HPACKHeaderCanonicalFormBenchmark(.trimmingWhitespace) +) +try measureAndPrint( + desc: "hpackheaders_canonical_form_trimming_whitespace_short_strings", + benchmark: HPACKHeaderCanonicalFormBenchmark(.trimmingWhitespaceFromShortStrings) +) +try measureAndPrint( + desc: "hpackheaders_canonical_form_trimming_whitespace_long_strings", + benchmark: HPACKHeaderCanonicalFormBenchmark(.trimmingWhitespaceFromLongStrings) +) +try measureAndPrint( + desc: "hpackheaders_normalize_httpheaders_removing_10k_conn_headers", + benchmark: HPACKHeadersNormalizationOfHTTPHeadersBenchmark( + headersKind: .manyUniqueConnectionHeaderValues(10_000), + iterations: 10 + ) +) +try measureAndPrint( + desc: "hpackheaders_normalize_httpheaders_keeping_10k_conn_headers", + benchmark: HPACKHeadersNormalizationOfHTTPHeadersBenchmark( + headersKind: .manyConnectionHeaderValuesWhichAreNotRemoved(10_000), + iterations: 10 + ) +) +try measureAndPrint( + desc: "huffman_encode_basic", + benchmark: HuffmanEncodingBenchmark(huffmanString: .basicHuffman, loopCount: 100) +) +try measureAndPrint( + desc: "huffman_encode_complex", + benchmark: HuffmanEncodingBenchmark(huffmanString: .complexHuffman, loopCount: 100) +) +try measureAndPrint( + desc: "huffman_decode_basic", + benchmark: HuffmanDecodingBenchmark(huffmanBytes: .basicHuffmanBytes, loopCount: 25) +) +try measureAndPrint( + desc: "huffman_decode_complex", + benchmark: HuffmanDecodingBenchmark(huffmanBytes: .complexHuffmanBytes, loopCount: 10) +) +try measureAndPrint( + desc: "server_only_10k_requests_1_concurrent", + benchmark: ServerOnly10KRequestsBenchmark(concurrentStreams: 1) +) +try measureAndPrint( + desc: "server_only_10k_requests_100_concurrent", + benchmark: ServerOnly10KRequestsBenchmark(concurrentStreams: 100) +) +try measureAndPrint( + desc: "stream_teardown_10k_requests_100_concurrent", + benchmark: StreamTeardownBenchmark(concurrentStreams: 100) +) diff --git a/Sources/NIOHTTP2Server/main.swift b/Sources/NIOHTTP2Server/main.swift index 0c34f68..ebacd9e 100644 --- a/Sources/NIOHTTP2Server/main.swift +++ b/Sources/NIOHTTP2Server/main.swift @@ -16,11 +16,10 @@ // hit it with curl like so: curl --http2-prior-knowledge http://localhost:8888/ import Foundation - import NIOCore -import NIOPosix import NIOHTTP1 import NIOHTTP2 +import NIOPosix final class HTTP1TestServer: ChannelInboundHandler { public typealias InboundIn = HTTPServerRequestPart @@ -54,12 +53,22 @@ final class HTTP1TestServer: ChannelInboundHandler { var headers = HTTPHeaders() headers.add(name: "content-length", value: "5") headers.add(name: "x-stream-id", value: String(Int(streamID))) - channel.write(http1TestServer.wrapOutboundOut(HTTPServerResponsePart.head(HTTPResponseHead(version: .init(major: 2, minor: 0), status: .ok, headers: headers))), promise: nil) + channel.write( + http1TestServer.wrapOutboundOut( + HTTPServerResponsePart.head( + HTTPResponseHead(version: .init(major: 2, minor: 0), status: .ok, headers: headers) + ) + ), + promise: nil + ) if requestHead.method != .HEAD { var buffer = channel.allocator.buffer(capacity: 12) buffer.writeStaticString("hello") - channel.write(http1TestServer.wrapOutboundOut(HTTPServerResponsePart.body(.byteBuffer(buffer))), promise: nil) + channel.write( + http1TestServer.wrapOutboundOut(HTTPServerResponsePart.body(.byteBuffer(buffer))), + promise: nil + ) } return channel.writeAndFlush(http1TestServer.wrapOutboundOut(HTTPServerResponsePart.end(nil))) @@ -70,17 +79,15 @@ final class HTTP1TestServer: ChannelInboundHandler { } } - final class ErrorHandler: ChannelInboundHandler { typealias InboundIn = Never - + func errorCaught(context: ChannelHandlerContext, error: Error) { print("Server received error: \(error)") context.close(promise: nil) } } - // First argument is the program path let arguments = ProcessInfo.processInfo.arguments let arg1 = arguments.dropFirst().first @@ -99,16 +106,16 @@ enum BindTo { let htdocs: String let bindTarget: BindTo switch (arg1, arg1.flatMap { Int($0) }, arg2, arg2.flatMap { Int($0) }, arg3) { -case (.some(let h), _ , _, .some(let p), let maybeHtdocs): - /* second arg an integer --> host port [htdocs] */ +case (.some(let h), _, _, .some(let p), let maybeHtdocs): + // second arg an integer --> host port [htdocs] bindTarget = .ip(host: h, port: p) htdocs = maybeHtdocs ?? defaultHtdocs case (_, .some(let p), let maybeHtdocs, _, _): - /* first arg an integer --> port [htdocs] */ + // first arg an integer --> port [htdocs] bindTarget = .ip(host: defaultHost, port: p) htdocs = maybeHtdocs ?? defaultHtdocs case (.some(let portString), .none, let maybeHtdocs, .none, .none): - /* couldn't parse as number --> uds-path [htdocs] */ + // couldn't parse as number --> uds-path [htdocs] bindTarget = .unixDomainSocket(path: portString) htdocs = maybeHtdocs ?? defaultHtdocs default: @@ -124,14 +131,15 @@ let bootstrap = ServerBootstrap(group: group) // Set the handlers that are applied to the accepted Channels .childChannelInitializer { channel in - return channel.configureHTTP2Pipeline(mode: .server) { streamChannel -> EventLoopFuture in - return streamChannel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ServerCodec()).flatMap { () -> EventLoopFuture in + channel.configureHTTP2Pipeline(mode: .server) { streamChannel -> EventLoopFuture in + streamChannel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ServerCodec()).flatMap { + () -> EventLoopFuture in streamChannel.pipeline.addHandler(HTTP1TestServer()) }.flatMap { () -> EventLoopFuture in streamChannel.pipeline.addHandler(ErrorHandler()) } }.flatMap { (_: HTTP2StreamMultiplexer) in - return channel.pipeline.addHandler(ErrorHandler()) + channel.pipeline.addHandler(ErrorHandler()) } } @@ -153,7 +161,7 @@ let channel = try { () -> Channel in case .unixDomainSocket(let path): return try bootstrap.bind(unixDomainSocketPath: path).wait() } - }() +}() print("Server started and listening on \(channel.localAddress!), htdocs path \(htdocs)") diff --git a/Tests/NIOHPACKTests/HPACKCodingTests.swift b/Tests/NIOHPACKTests/HPACKCodingTests.swift index e484e75..95973b0 100644 --- a/Tests/NIOHPACKTests/HPACKCodingTests.swift +++ b/Tests/NIOHPACKTests/HPACKCodingTests.swift @@ -12,8 +12,9 @@ // //===----------------------------------------------------------------------===// -import XCTest import NIOCore +import XCTest + @testable import NIOHPACK class HPACKCodingTests: XCTestCase { @@ -29,29 +30,37 @@ class HPACKCodingTests: XCTestCase { // HPACK RFC7541 ยง C.3 // http://httpwg.org/specs/rfc7541.html#request.examples.without.huffman.coding func testRequestHeadersWithoutHuffmanCoding() throws { - var request1 = buffer(wrapping: [0x82, 0x86, 0x84, 0x41, 0x0f, 0x77, 0x77, 0x77, 0x2e, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x2e, 0x63, 0x6f, 0x6d]) - var request2 = buffer(wrapping: [0x82, 0x86, 0x84, 0xbe, 0x58, 0x08, 0x6e, 0x6f, 0x2d, 0x63, 0x61, 0x63, 0x68, 0x65]) - var request3 = buffer(wrapping: [0x82, 0x87, 0x85, 0xbf, 0x40, 0x0a, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x2d, 0x6b, 0x65, 0x79, 0x0c, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x2d, 0x76, 0x61, 0x6c, 0x75, 0x65]) + var request1 = buffer(wrapping: [ + 0x82, 0x86, 0x84, 0x41, 0x0f, 0x77, 0x77, 0x77, 0x2e, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x2e, 0x63, + 0x6f, 0x6d, + ]) + var request2 = buffer(wrapping: [ + 0x82, 0x86, 0x84, 0xbe, 0x58, 0x08, 0x6e, 0x6f, 0x2d, 0x63, 0x61, 0x63, 0x68, 0x65, + ]) + var request3 = buffer(wrapping: [ + 0x82, 0x87, 0x85, 0xbf, 0x40, 0x0a, 0x63, 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x2d, 0x6b, 0x65, 0x79, 0x0c, 0x63, + 0x75, 0x73, 0x74, 0x6f, 0x6d, 0x2d, 0x76, 0x61, 0x6c, 0x75, 0x65, + ]) let headers1 = HPACKHeaders([ (":method", "GET"), (":scheme", "http"), (":path", "/"), - (":authority", "www.example.com") + (":authority", "www.example.com"), ]) let headers2 = HPACKHeaders([ (":method", "GET"), (":scheme", "http"), (":path", "/"), (":authority", "www.example.com"), - ("cache-control", "no-cache") + ("cache-control", "no-cache"), ]) let headers3 = HPACKHeaders([ (":method", "GET"), (":scheme", "https"), (":path", "/index.html"), (":authority", "www.example.com"), - ("custom-key", "custom-value") + ("custom-key", "custom-value"), ]) var decoder = HPACKDecoder(allocator: ByteBufferAllocator()) @@ -79,29 +88,34 @@ class HPACKCodingTests: XCTestCase { // HPACK RFC7541 ยง C.4 // http://httpwg.org/specs/rfc7541.html#request.examples.with.huffman.coding func testRequestHeadersWithHuffmanCoding() throws { - var request1 = buffer(wrapping: [0x82, 0x86, 0x84, 0x41, 0x8c, 0xf1, 0xe3, 0xc2, 0xe5, 0xf2, 0x3a, 0x6b, 0xa0, 0xab, 0x90, 0xf4, 0xff]) + var request1 = buffer(wrapping: [ + 0x82, 0x86, 0x84, 0x41, 0x8c, 0xf1, 0xe3, 0xc2, 0xe5, 0xf2, 0x3a, 0x6b, 0xa0, 0xab, 0x90, 0xf4, 0xff, + ]) var request2 = buffer(wrapping: [0x82, 0x86, 0x84, 0xbe, 0x58, 0x86, 0xa8, 0xeb, 0x10, 0x64, 0x9c, 0xbf]) - var request3 = buffer(wrapping: [0x82, 0x87, 0x85, 0xbf, 0x40, 0x88, 0x25, 0xa8, 0x49, 0xe9, 0x5b, 0xa9, 0x7d, 0x7f, 0x89, 0x25, 0xa8, 0x49, 0xe9, 0x5b, 0xb8, 0xe8, 0xb4, 0xbf]) + var request3 = buffer(wrapping: [ + 0x82, 0x87, 0x85, 0xbf, 0x40, 0x88, 0x25, 0xa8, 0x49, 0xe9, 0x5b, 0xa9, 0x7d, 0x7f, 0x89, 0x25, 0xa8, 0x49, + 0xe9, 0x5b, 0xb8, 0xe8, 0xb4, 0xbf, + ]) let headers1 = HPACKHeaders([ (":method", "GET"), (":scheme", "http"), (":path", "/"), - (":authority", "www.example.com") + (":authority", "www.example.com"), ]) let headers2 = HPACKHeaders([ (":method", "GET"), (":scheme", "http"), (":path", "/"), (":authority", "www.example.com"), - ("cache-control", "no-cache") + ("cache-control", "no-cache"), ]) let headers3 = HPACKHeaders([ (":method", "GET"), (":scheme", "https"), (":path", "/index.html"), (":authority", "www.example.com"), - ("custom-key", "custom-value") + ("custom-key", "custom-value"), ]) var encoder = HPACKEncoder(allocator: allocator) @@ -158,9 +172,11 @@ class HPACKCodingTests: XCTestCase { // cache-control: private 0x58, 0x07, 0x70, 0x72, 0x69, 0x76, 0x61, 0x74, 0x65, // date: Mon, 21 Oct 2013 20:13:21 GMT - 0x61, 0x1d, 0x4d, 0x6f, 0x6e, 0x2c, 0x20, 0x32, 0x31, 0x20, 0x4f, 0x63, 0x74, 0x20, 0x32, 0x30, 0x31, 0x33, 0x20, 0x32, 0x30, 0x3a, 0x31, 0x33, 0x3a, 0x32, 0x31, 0x20, 0x47, 0x4d, 0x54, + 0x61, 0x1d, 0x4d, 0x6f, 0x6e, 0x2c, 0x20, 0x32, 0x31, 0x20, 0x4f, 0x63, 0x74, 0x20, 0x32, 0x30, 0x31, 0x33, + 0x20, 0x32, 0x30, 0x3a, 0x31, 0x33, 0x3a, 0x32, 0x31, 0x20, 0x47, 0x4d, 0x54, // location: https://www.example.com - 0x6e, 0x17, 0x68, 0x74, 0x74, 0x70, 0x73, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x2e, 0x63, 0x6f, 0x6d + 0x6e, 0x17, 0x68, 0x74, 0x74, 0x70, 0x73, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x65, 0x78, 0x61, 0x6d, + 0x70, 0x6c, 0x65, 0x2e, 0x63, 0x6f, 0x6d, ]) var response2 = buffer(wrapping: [ // :status: 307 @@ -170,7 +186,7 @@ class HPACKCodingTests: XCTestCase { // date: Mon, 21 Oct 2013 20:13:21 GMT 0xc0, // location: https://www.example.com - 0xbf + 0xbf, ]) var response3 = buffer(wrapping: [ // :status: 200 @@ -178,26 +194,30 @@ class HPACKCodingTests: XCTestCase { // cache-control: private 0xc1, // date: Mon, 21 Oct 2013 20:13:22 GMT - 0x61, 0x1d, 0x4d, 0x6f, 0x6e, 0x2c, 0x20, 0x32, 0x31, 0x20, 0x4f, 0x63, 0x74, 0x20, 0x32, 0x30, 0x31, 0x33, 0x20, 0x32, 0x30, 0x3a, 0x31, 0x33, 0x3a, 0x32, 0x32, 0x20, 0x47, 0x4d, 0x54, + 0x61, 0x1d, 0x4d, 0x6f, 0x6e, 0x2c, 0x20, 0x32, 0x31, 0x20, 0x4f, 0x63, 0x74, 0x20, 0x32, 0x30, 0x31, 0x33, + 0x20, 0x32, 0x30, 0x3a, 0x31, 0x33, 0x3a, 0x32, 0x32, 0x20, 0x47, 0x4d, 0x54, // location: https://www.example.com 0xc0, // content-encoding: gzip 0x5a, 0x04, 0x67, 0x7a, 0x69, 0x70, // set-cookie: foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1 - 0x77, 0x38, 0x66, 0x6f, 0x6f, 0x3d, 0x41, 0x53, 0x44, 0x4a, 0x4b, 0x48, 0x51, 0x4b, 0x42, 0x5a, 0x58, 0x4f, 0x51, 0x57, 0x45, 0x4f, 0x50, 0x49, 0x55, 0x41, 0x58, 0x51, 0x57, 0x45, 0x4f, 0x49, 0x55, 0x3b, 0x20, 0x6d, 0x61, 0x78, 0x2d, 0x61, 0x67, 0x65, 0x3d, 0x33, 0x36, 0x30, 0x30, 0x3b, 0x20, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x3d, 0x31 + 0x77, 0x38, 0x66, 0x6f, 0x6f, 0x3d, 0x41, 0x53, 0x44, 0x4a, 0x4b, 0x48, 0x51, 0x4b, 0x42, 0x5a, 0x58, 0x4f, + 0x51, 0x57, 0x45, 0x4f, 0x50, 0x49, 0x55, 0x41, 0x58, 0x51, 0x57, 0x45, 0x4f, 0x49, 0x55, 0x3b, 0x20, 0x6d, + 0x61, 0x78, 0x2d, 0x61, 0x67, 0x65, 0x3d, 0x33, 0x36, 0x30, 0x30, 0x3b, 0x20, 0x76, 0x65, 0x72, 0x73, 0x69, + 0x6f, 0x6e, 0x3d, 0x31, ]) let headers1 = HPACKHeaders([ (":status", "302"), ("cache-control", "private"), ("date", "Mon, 21 Oct 2013 20:13:21 GMT"), - ("location", "https://www.example.com") + ("location", "https://www.example.com"), ]) let headers2 = HPACKHeaders([ (":status", "307"), ("cache-control", "private"), ("date", "Mon, 21 Oct 2013 20:13:21 GMT"), - ("location", "https://www.example.com") + ("location", "https://www.example.com"), ]) let headers3 = HPACKHeaders([ (":status", "200"), @@ -205,7 +225,7 @@ class HPACKCodingTests: XCTestCase { ("date", "Mon, 21 Oct 2013 20:13:22 GMT"), ("location", "https://www.example.com"), ("content-encoding", "gzip"), - ("set-cookie", "foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1") + ("set-cookie", "foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1"), ]) var decoder = HPACKDecoder(allocator: ByteBufferAllocator(), maxDynamicTableSize: 256) @@ -239,26 +259,32 @@ class HPACKCodingTests: XCTestCase { // http://httpwg.org/specs/rfc7541.html#response.examples.with.huffman.coding func testResponseHeadersWithHuffmanCoding() throws { var response1 = buffer(wrapping: [ - 0x48, 0x82, 0x64, 0x02, 0x58, 0x85, 0xae, 0xc3, 0x77, 0x1a, 0x4b, 0x61, 0x96, 0xd0, 0x7a, 0xbe, 0x94, 0x10, 0x54, 0xd4, 0x44, 0xa8, 0x20, 0x05, 0x95, 0x04, 0x0b, 0x81, 0x66, 0xe0, 0x82, 0xa6, 0x2d, 0x1b, 0xff, 0x6e, 0x91, 0x9d, 0x29, 0xad, 0x17, 0x18, 0x63, 0xc7, 0x8f, 0x0b, 0x97, 0xc8, 0xe9, 0xae, 0x82, 0xae, 0x43, 0xd3 + 0x48, 0x82, 0x64, 0x02, 0x58, 0x85, 0xae, 0xc3, 0x77, 0x1a, 0x4b, 0x61, 0x96, 0xd0, 0x7a, 0xbe, 0x94, 0x10, + 0x54, 0xd4, 0x44, 0xa8, 0x20, 0x05, 0x95, 0x04, 0x0b, 0x81, 0x66, 0xe0, 0x82, 0xa6, 0x2d, 0x1b, 0xff, 0x6e, + 0x91, 0x9d, 0x29, 0xad, 0x17, 0x18, 0x63, 0xc7, 0x8f, 0x0b, 0x97, 0xc8, 0xe9, 0xae, 0x82, 0xae, 0x43, 0xd3, ]) var response2 = buffer(wrapping: [ - 0x48, 0x83, 0x64, 0x0e, 0xff, 0xc1, 0xc0, 0xbf + 0x48, 0x83, 0x64, 0x0e, 0xff, 0xc1, 0xc0, 0xbf, ]) var response3 = buffer(wrapping: [ - 0x88, 0xc1, 0x61, 0x96, 0xd0, 0x7a, 0xbe, 0x94, 0x10, 0x54, 0xd4, 0x44, 0xa8, 0x20, 0x05, 0x95, 0x04, 0x0b, 0x81, 0x66, 0xe0, 0x84, 0xa6, 0x2d, 0x1b, 0xff, 0xc0, 0x5a, 0x83, 0x9b, 0xd9, 0xab, 0x77, 0xad, 0x94, 0xe7, 0x82, 0x1d, 0xd7, 0xf2, 0xe6, 0xc7, 0xb3, 0x35, 0xdf, 0xdf, 0xcd, 0x5b, 0x39, 0x60, 0xd5, 0xaf, 0x27, 0x08, 0x7f, 0x36, 0x72, 0xc1, 0xab, 0x27, 0x0f, 0xb5, 0x29, 0x1f, 0x95, 0x87, 0x31, 0x60, 0x65, 0xc0, 0x03, 0xed, 0x4e, 0xe5, 0xb1, 0x06, 0x3d, 0x50, 0x07 + 0x88, 0xc1, 0x61, 0x96, 0xd0, 0x7a, 0xbe, 0x94, 0x10, 0x54, 0xd4, 0x44, 0xa8, 0x20, 0x05, 0x95, 0x04, 0x0b, + 0x81, 0x66, 0xe0, 0x84, 0xa6, 0x2d, 0x1b, 0xff, 0xc0, 0x5a, 0x83, 0x9b, 0xd9, 0xab, 0x77, 0xad, 0x94, 0xe7, + 0x82, 0x1d, 0xd7, 0xf2, 0xe6, 0xc7, 0xb3, 0x35, 0xdf, 0xdf, 0xcd, 0x5b, 0x39, 0x60, 0xd5, 0xaf, 0x27, 0x08, + 0x7f, 0x36, 0x72, 0xc1, 0xab, 0x27, 0x0f, 0xb5, 0x29, 0x1f, 0x95, 0x87, 0x31, 0x60, 0x65, 0xc0, 0x03, 0xed, + 0x4e, 0xe5, 0xb1, 0x06, 0x3d, 0x50, 0x07, ]) let headers1 = HPACKHeaders([ (":status", "302"), ("cache-control", "private"), ("date", "Mon, 21 Oct 2013 20:13:21 GMT"), - ("location", "https://www.example.com") + ("location", "https://www.example.com"), ]) let headers2 = HPACKHeaders([ (":status", "307"), ("cache-control", "private"), ("date", "Mon, 21 Oct 2013 20:13:21 GMT"), - ("location", "https://www.example.com") + ("location", "https://www.example.com"), ]) let headers3 = HPACKHeaders([ (":status", "200"), @@ -266,7 +292,7 @@ class HPACKCodingTests: XCTestCase { ("date", "Mon, 21 Oct 2013 20:13:22 GMT"), ("location", "https://www.example.com"), ("content-encoding", "gzip"), - ("set-cookie", "foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1") + ("set-cookie", "foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1"), ]) var encoder = HPACKEncoder(allocator: allocator) @@ -322,14 +348,24 @@ class HPACKCodingTests: XCTestCase { } func testNonIndexedRequest() throws { - var request1 = buffer(wrapping: [0x82, 0x86, 0x84, 0x01, 0x8c, 0xf1, 0xe3, 0xc2, 0xe5, 0xf2, 0x3a, 0x6b, 0xa0, 0xab, 0x90, 0xf4, 0xff]) - var request2 = buffer(wrapping: [0x82, 0x86, 0x84, 0x01, 0x8c, 0xf1, 0xe3, 0xc2, 0xe5, 0xf2, 0x3a, 0x6b, 0xa0, 0xab, 0x90, 0xf4, 0xff, 0x0f, 0x09, 0x86, 0xa8, 0xeb, 0x10, 0x64, 0x9c, 0xbf, 0x00, 0x88, 0x25, 0xa8, 0x49, 0xe9, 0x5b, 0xa9, 0x7d, 0x7f, 0x89, 0x25, 0xa8, 0x49, 0xe9, 0x5b, 0xb8, 0xe8, 0xb4, 0xbf]) - var request3 = buffer(wrapping: [0x82, 0x87, 0x85, 0x11, 0x8c, 0xf1, 0xe3, 0xc2, 0xe5, 0xf2, 0x3a, 0x6b, 0xa0, 0xab, 0x90, 0xf4, 0xff, 0x10, 0x88, 0x25, 0xa8, 0x49, 0xe9, 0x5b, 0xa9, 0x7d, 0x7f, 0x89, 0x25, 0xa8, 0x49, 0xe9, 0x5b, 0xb8, 0xe8, 0xb4, 0xbf]) + var request1 = buffer(wrapping: [ + 0x82, 0x86, 0x84, 0x01, 0x8c, 0xf1, 0xe3, 0xc2, 0xe5, 0xf2, 0x3a, 0x6b, 0xa0, 0xab, 0x90, 0xf4, 0xff, + ]) + var request2 = buffer(wrapping: [ + 0x82, 0x86, 0x84, 0x01, 0x8c, 0xf1, 0xe3, 0xc2, 0xe5, 0xf2, 0x3a, 0x6b, 0xa0, 0xab, 0x90, 0xf4, 0xff, 0x0f, + 0x09, 0x86, 0xa8, 0xeb, 0x10, 0x64, 0x9c, 0xbf, 0x00, 0x88, 0x25, 0xa8, 0x49, 0xe9, 0x5b, 0xa9, 0x7d, 0x7f, + 0x89, 0x25, 0xa8, 0x49, 0xe9, 0x5b, 0xb8, 0xe8, 0xb4, 0xbf, + ]) + var request3 = buffer(wrapping: [ + 0x82, 0x87, 0x85, 0x11, 0x8c, 0xf1, 0xe3, 0xc2, 0xe5, 0xf2, 0x3a, 0x6b, 0xa0, 0xab, 0x90, 0xf4, 0xff, 0x10, + 0x88, 0x25, 0xa8, 0x49, 0xe9, 0x5b, 0xa9, 0x7d, 0x7f, 0x89, 0x25, 0xa8, 0x49, 0xe9, 0x5b, 0xb8, 0xe8, 0xb4, + 0xbf, + ]) let headers1 = HPACKHeaders([ (":method", "GET"), (":scheme", "http"), - (":path", "/") + (":path", "/"), ]) let h1NoIndex = (name: ":authority", value: "www.example.com") let h2NoIndex = (name: "cache-control", value: "no-cache") @@ -337,7 +373,7 @@ class HPACKCodingTests: XCTestCase { let headers3 = HPACKHeaders([ (":method", "GET"), (":scheme", "https"), - (":path", "/index.html") + (":path", "/index.html"), ]) let h3NeverIndex = (name: "custom-key", value: "custom-value") @@ -371,7 +407,7 @@ class HPACKCodingTests: XCTestCase { (":method", "GET"), (":scheme", "http"), (":path", "/"), - (":authority", "www.example.com") + (":authority", "www.example.com"), ]) let fullHeaders2 = HPACKHeaders([ (":method", "GET"), @@ -379,14 +415,14 @@ class HPACKCodingTests: XCTestCase { (":path", "/"), (":authority", "www.example.com"), ("cache-control", "no-cache"), - ("custom-key", "custom-value") + ("custom-key", "custom-value"), ]) let fullHeaders3 = HPACKHeaders([ (":method", "GET"), (":scheme", "https"), (":path", "/index.html"), (":authority", "www.example.com"), - ("custom-key", "custom-value") + ("custom-key", "custom-value"), ]) let decoded1 = try decoder.decodeHeaders(from: &request1) @@ -403,16 +439,28 @@ class HPACKCodingTests: XCTestCase { } func testInlineDynamicTableResize() throws { - var request1 = buffer(wrapping: [0x3f, 0x32, 0x82, 0x86, 0x84, 0x41, 0x8c, 0xf1, 0xe3, 0xc2, 0xe5, 0xf2, 0x3a, 0x6b, 0xa0, 0xab, 0x90, 0xf4, 0xff]) - let request2 = buffer(wrapping: [0x3f, 0x21, 0x3f, 0x32, 0x82, 0x86, 0x84, 0x41, 0x8c, 0xf1, 0xe3, 0xc2, 0xe5, 0xf2, 0x3a, 0x6b, 0xa0, 0xab, 0x90, 0xf4, 0xff]) - var request3 = buffer(wrapping: [0x3f, 0xe1, 0x20, 0x82, 0x86, 0x84, 0x41, 0x8c, 0xf1, 0xe3, 0xc2, 0xe5, 0xf2, 0x3a, 0x6b, 0xa0, 0xab, 0x90, 0xf4, 0xff]) - var request4 = buffer(wrapping: [0x82, 0x86, 0x3f, 0x32, 0x84, 0x41, 0x8c, 0xf1, 0xe3, 0xc2, 0xe5, 0xf2, 0x3a, 0x6b, 0xa0, 0xab, 0x90, 0xf4, 0xff]) + var request1 = buffer(wrapping: [ + 0x3f, 0x32, 0x82, 0x86, 0x84, 0x41, 0x8c, 0xf1, 0xe3, 0xc2, 0xe5, 0xf2, 0x3a, 0x6b, 0xa0, 0xab, 0x90, 0xf4, + 0xff, + ]) + let request2 = buffer(wrapping: [ + 0x3f, 0x21, 0x3f, 0x32, 0x82, 0x86, 0x84, 0x41, 0x8c, 0xf1, 0xe3, 0xc2, 0xe5, 0xf2, 0x3a, 0x6b, 0xa0, 0xab, + 0x90, 0xf4, 0xff, + ]) + var request3 = buffer(wrapping: [ + 0x3f, 0xe1, 0x20, 0x82, 0x86, 0x84, 0x41, 0x8c, 0xf1, 0xe3, 0xc2, 0xe5, 0xf2, 0x3a, 0x6b, 0xa0, 0xab, 0x90, + 0xf4, 0xff, + ]) + var request4 = buffer(wrapping: [ + 0x82, 0x86, 0x3f, 0x32, 0x84, 0x41, 0x8c, 0xf1, 0xe3, 0xc2, 0xe5, 0xf2, 0x3a, 0x6b, 0xa0, 0xab, 0x90, 0xf4, + 0xff, + ]) let headers1 = HPACKHeaders([ (":method", "GET"), (":scheme", "http"), (":path", "/"), - (":authority", "www.example.com") + (":authority", "www.example.com"), ]) let oddMaxTableSize = 81 @@ -434,12 +482,12 @@ class HPACKCodingTests: XCTestCase { XCTAssertEqualTuple(headers1[3], try encoder.headerIndexTable.header(at: 62)) var decoder = HPACKDecoder(allocator: ByteBufferAllocator()) - decoder.maxDynamicTableLength = oddMaxTableSize // not enough to store the value we expect it to eventually store, but enough for the initial run + // not enough to store the value we expect it to eventually store, but enough for the initial run + decoder.maxDynamicTableLength = oddMaxTableSize let decoded: HPACKHeaders do { decoded = try decoder.decodeHeaders(from: &request1) - } - catch { + } catch { XCTFail("Failed to decode header set containing dynamic-table-resize command: \(error)") return } @@ -449,7 +497,7 @@ class HPACKCodingTests: XCTestCase { XCTAssertEqualTuple(headers1[3], try decoder.headerTable.header(at: 62)) // Now, ensure some special cases. - request1.moveReaderIndex(to: 0) // make the data available again in our sample buffer + request1.moveReaderIndex(to: 0) // make the data available again in our sample buffer // 1 - if we try to change the size mid-buffer, it'll throw an error. try encoder.setDynamicTableSize(4096) @@ -462,7 +510,7 @@ class HPACKCodingTests: XCTestCase { XCTAssertNoThrow(try encoder.append(header: ":method", value: "GET")) XCTAssertNoThrow(try encoder.append(header: ":scheme", value: "http")) XCTAssertNoThrow(try encoder.append(header: ":path", value: "/")) - XCTAssertThrowsError(try encoder.setDynamicTableSize(oddMaxTableSize)) // should throw + XCTAssertThrowsError(try encoder.setDynamicTableSize(oddMaxTableSize)) // should throw XCTAssertNoThrow(try encoder.append(header: ":authority", value: "www.example.com")) // No resize information, but the rest of the block will be there @@ -477,7 +525,7 @@ class HPACKCodingTests: XCTestCase { // 2 - We can set multiple sizes, and both the smallest and the latest will be sent. try encoder.setDynamicTableSize(64) try encoder.setDynamicTableSize(75) - try encoder.setDynamicTableSize(oddMaxTableSize /* 81 */) + try encoder.setDynamicTableSize(oddMaxTableSize) // 81 try encoder.beginEncoding(allocator: allocator) XCTAssertNoThrow(try encoder.append(header: ":method", value: "GET")) @@ -491,34 +539,40 @@ class HPACKCodingTests: XCTestCase { // NB: current size is 81 bytes. encoder.headerIndexTable.dynamicTable.clear() - XCTAssertThrowsError(try decoder.decodeHeaders(from: &request3)) {error in + XCTAssertThrowsError(try decoder.decodeHeaders(from: &request3)) { error in XCTAssertTrue(error is NIOHPACKErrors.InvalidDynamicTableSize) } // 4 - Decoder will not accept a table size update unless it appears at the start of a header block. decoder.headerTable.dynamicTable.clear() - XCTAssertThrowsError(try decoder.decodeHeaders(from: &request4)) {error in + XCTAssertThrowsError(try decoder.decodeHeaders(from: &request4)) { error in XCTAssertTrue(error is NIOHPACKErrors.IllegalDynamicTableSizeChange) } } func testHPACKHeadersDescription() throws { - let headerList1: [(String, String)] = [(":method", "GET"), - (":scheme", "http"), - (":path", "/"), - (":authority", "www.example.com")] - let headerList2: [(String, String)] = [(":method", "GET"), - (":scheme", "http"), - (":path", "/"), - (":authority", "www.example.com"), - ("cache-control", "no-cache")] - let headerList3: [(HPACKIndexing, String, String)] = [(.indexable, ":method", "POST"), - (.indexable, ":scheme", "https"), - (.indexable, ":path", "/send.html"), - (.indexable, ":authority", "www.example.com"), - (.indexable, "custom-key", "custom-value"), - (.nonIndexable, "content-length", "42")] + let headerList1: [(String, String)] = [ + (":method", "GET"), + (":scheme", "http"), + (":path", "/"), + (":authority", "www.example.com"), + ] + let headerList2: [(String, String)] = [ + (":method", "GET"), + (":scheme", "http"), + (":path", "/"), + (":authority", "www.example.com"), + ("cache-control", "no-cache"), + ] + let headerList3: [(HPACKIndexing, String, String)] = [ + (.indexable, ":method", "POST"), + (.indexable, ":scheme", "https"), + (.indexable, ":path", "/send.html"), + (.indexable, ":authority", "www.example.com"), + (.indexable, "custom-key", "custom-value"), + (.nonIndexable, "content-length", "42"), + ] let headers1 = HPACKHeaders(headerList1) let headers2 = HPACKHeaders(headerList2) @@ -533,7 +587,7 @@ class HPACKCodingTests: XCTestCase { XCTAssertEqual(description2, expected2) let description3 = headers3.description - let expected3 = headerList3.description // already contains indexing where we'd expect + let expected3 = headerList3.description // already contains indexing where we'd expect XCTAssertEqual(description3, expected3) } @@ -546,7 +600,7 @@ class HPACKCodingTests: XCTestCase { ("cache-control", "no-cache"), ("custom-key", "value-1,value-2"), ("set-cookie", "abcdefg,hijklmn,opqrst"), - ("custom-key", "value-3") + ("custom-key", "value-3"), ]) XCTAssertEqual(headers[":method"], ["GET"]) @@ -567,7 +621,7 @@ class HPACKCodingTests: XCTestCase { "no-whitespace": "foo,bar", "sp": " foo , bar ", "htab": "\tfoo\t,\t\tbar\t\t", - "sp-and-htab": " \t foo \t\t,\t bar\t " + "sp-and-htab": " \t foo \t\t,\t bar\t ", ] let expected = ["foo", "bar"] @@ -580,7 +634,7 @@ class HPACKCodingTests: XCTestCase { func testHPACKHeadersCanonicalFormDropsEmptyStrings() throws { let headers: HPACKHeaders = [ "no-whitespace": "foo,,bar", - "with-whitespace": "foo, ,bar" + "with-whitespace": "foo, ,bar", ] let expected = ["foo", "bar"] XCTAssertEqual(headers[canonicalForm: "no-whitespace"], expected) @@ -591,8 +645,8 @@ class HPACKCodingTests: XCTestCase { let shouldNotBeSplitOrStripped = "should, not , be , split, or, stripped" let headers: HPACKHeaders = ["set-cookie": shouldNotBeSplitOrStripped] - XCTAssertEqual(headers[canonicalForm: "set-cookie"], [shouldNotBeSplitOrStripped]) - XCTAssertEqual(headers[canonicalForm: "Set-Cookie"], [shouldNotBeSplitOrStripped]) + XCTAssertEqual(headers[canonicalForm: "set-cookie"], [shouldNotBeSplitOrStripped]) + XCTAssertEqual(headers[canonicalForm: "Set-Cookie"], [shouldNotBeSplitOrStripped]) } func testHPACKHeadersFirst() throws { @@ -600,7 +654,7 @@ class HPACKCodingTests: XCTestCase { (":method", "GET"), ("foo", "bar"), ("foo", "baz"), - ("custom-key", "value-1,value-2") + ("custom-key", "value-1,value-2"), ]) XCTAssertEqual(headers.first(name: ":method"), "GET") @@ -618,7 +672,7 @@ class HPACKCodingTests: XCTestCase { "cache-control": "no-cache", "custom-key": "value-1,value-2", "set-cookie": "abcdefg,hijklmn,opqrst", - "custom-key": "value-3" + "custom-key": "value-3", ] let headers2 = HPACKHeaders([ @@ -629,7 +683,7 @@ class HPACKCodingTests: XCTestCase { ("cache-control", "no-cache"), ("custom-key", "value-1,value-2"), ("set-cookie", "abcdefg,hijklmn,opqrst"), - ("custom-key", "value-3") + ("custom-key", "value-3"), ]) XCTAssertEqual(headers, headers2) @@ -702,7 +756,10 @@ class HPACKCodingTests: XCTestCase { XCTAssertEqual(decoder.maxHeaderListSize, 16 * 1024) XCTAssertThrowsError(try decoder.decodeHeaders(from: &request)) { error in - XCTAssertEqual(error as? NIOHPACKErrors.MaxHeaderListSizeViolation, NIOHPACKErrors.MaxHeaderListSizeViolation()) + XCTAssertEqual( + error as? NIOHPACKErrors.MaxHeaderListSizeViolation, + NIOHPACKErrors.MaxHeaderListSizeViolation() + ) } // Decoding a header block that is smaller than the max header list size is fine. @@ -713,8 +770,10 @@ class HPACKCodingTests: XCTestCase { } func testDifferentlyCasedHPACKHeadersAreNotEqual() { - let variants: [HPACKHeaders] = [HPACKHeaders([("foo", "foox")]), HPACKHeaders([("Foo", "foo")]), - HPACKHeaders([("foo", "Foo")]), HPACKHeaders([("Foo", "Foo")])] + let variants: [HPACKHeaders] = [ + HPACKHeaders([("foo", "foox")]), HPACKHeaders([("Foo", "foo")]), + HPACKHeaders([("foo", "Foo")]), HPACKHeaders([("Foo", "Foo")]), + ] for v1 in variants.indices { for v2 in variants.indices { @@ -734,8 +793,13 @@ class HPACKCodingTests: XCTestCase { // This will be placed into the header table, and will use an indexed name but a literal value. let firstHeaders = HPACKHeaders([("date", "Tue, 12 Nov 2019 09:48:43 GMT")]) XCTAssertNoThrow(try encoder.encode(headers: firstHeaders, to: &buffer)) - XCTAssertEqual(Array(buffer.readableBytesView), - [0x61, 0x96, 0xdf, 0x69, 0x7e, 0x94, 0x08, 0x94, 0xd2, 0x7e, 0xea, 0x08, 0x01, 0x7d, 0x40, 0x3f, 0x71, 0xa7, 0xae, 0x34, 0xca, 0x98, 0xb4, 0x6f]) + XCTAssertEqual( + Array(buffer.readableBytesView), + [ + 0x61, 0x96, 0xdf, 0x69, 0x7e, 0x94, 0x08, 0x94, 0xd2, 0x7e, 0xea, 0x08, 0x01, 0x7d, 0x40, 0x3f, 0x71, + 0xa7, 0xae, 0x34, 0xca, 0x98, 0xb4, 0x6f, + ] + ) // Now we're going to try to send that header again. This should be indexed fully, and sent trivially. buffer.clear() @@ -749,7 +813,12 @@ class HPACKCodingTests: XCTestCase { secondHeaders.add(name: "date", value: "Tue, 12 Nov 2019 09:48:43 GMT", indexing: .nonIndexable) buffer.clear() XCTAssertNoThrow(try encoder.encode(headers: secondHeaders, to: &buffer)) - XCTAssertEqual(Array(buffer.readableBytesView), - [0x0F, 0x12, 0x96, 0xdf, 0x69, 0x7e, 0x94, 0x08, 0x94, 0xd2, 0x7e, 0xea, 0x08, 0x01, 0x7d, 0x40, 0x3f, 0x71, 0xa7, 0xae, 0x34, 0xca, 0x98, 0xb4, 0x6f]) + XCTAssertEqual( + Array(buffer.readableBytesView), + [ + 0x0F, 0x12, 0x96, 0xdf, 0x69, 0x7e, 0x94, 0x08, 0x94, 0xd2, 0x7e, 0xea, 0x08, 0x01, 0x7d, 0x40, 0x3f, + 0x71, 0xa7, 0xae, 0x34, 0xca, 0x98, 0xb4, 0x6f, + ] + ) } } diff --git a/Tests/NIOHPACKTests/HPACKHeadersTests.swift b/Tests/NIOHPACKTests/HPACKHeadersTests.swift index 8c9b6ab..7259b12 100644 --- a/Tests/NIOHPACKTests/HPACKHeadersTests.swift +++ b/Tests/NIOHPACKTests/HPACKHeadersTests.swift @@ -12,10 +12,10 @@ // //===----------------------------------------------------------------------===// -import XCTest import NIOCore import NIOHPACK import NIOHTTP1 +import XCTest final class HPACKHeadersTests: XCTestCase { func testHPACKHeadersAreHashable() throws { @@ -84,7 +84,7 @@ final class HPACKHeadersTests: XCTestCase { "but-not-me": "", "keep-alive": "remove-me", "proxy-connection": "me too", - "transfer-encoding": "me three" + "transfer-encoding": "me three", ] let normalized = HPACKHeaders(httpHeaders: httpHeaders, normalizeHTTPHeaders: true) @@ -106,7 +106,7 @@ final class HPACKHeadersTests: XCTestCase { // Add a bunch of connection headers to remove. We add a large number because the // implementation of the normalizing init branches on the number of connection header // values. - for i in 0 ..< 512 { + for i in 0..<512 { let toRemove = "value-\(i)" httpHeaders.add(name: "connection", value: toRemove) httpHeaders.add(name: toRemove, value: "") @@ -127,7 +127,7 @@ final class HPACKHeadersTests: XCTestCase { "foo": "baz", "foo": "bar,baz", "foo": " bar ,baz ,,", - "bar": "foo" + "bar": "foo", ] let values = headers.values(forHeader: "foo", canonicalForm: false) @@ -137,7 +137,7 @@ final class HPACKHeadersTests: XCTestCase { XCTAssertEqual(iterator.next(), "bar,baz") XCTAssertEqual(iterator.next(), " bar ,baz ,,") XCTAssertNil(iterator.next()) - XCTAssertNil(iterator.next()) // Still nil + XCTAssertNil(iterator.next()) // Still nil } func testValuesSequenceInCanonicalForm() { @@ -147,7 +147,7 @@ final class HPACKHeadersTests: XCTestCase { "foo": "baz", "foo": "bar,baz", "foo": " bar ,baz ,,", - "bar": "foo" + "bar": "foo", ] let values = headers.values(forHeader: "foo", canonicalForm: true) @@ -159,13 +159,13 @@ final class HPACKHeadersTests: XCTestCase { XCTAssertEqual(iterator.next(), "bar") XCTAssertEqual(iterator.next(), "baz") XCTAssertNil(iterator.next()) - XCTAssertNil(iterator.next()) // Still nil + XCTAssertNil(iterator.next()) // Still nil } func testValuesSequenceIgnoresCanonicalFormForSetCookie() { let expected = [ "haha,you,wont,split,me,im,set-cookie", - "but we should still get multiple values" + "but we should still get multiple values", ] var headers = HPACKHeaders() @@ -188,7 +188,7 @@ final class HPACKHeadersTests: XCTestCase { "foo": "baz", "foo": "bar,baz", "foo": " bar ,baz ,,", - "bar": "foo" + "bar": "foo", ] let originalCapacity = original.capacity diff --git a/Tests/NIOHPACKTests/HPACKIntegrationTests.swift b/Tests/NIOHPACKTests/HPACKIntegrationTests.swift index 84b410f..5772615 100644 --- a/Tests/NIOHPACKTests/HPACKIntegrationTests.swift +++ b/Tests/NIOHPACKTests/HPACKIntegrationTests.swift @@ -12,11 +12,12 @@ // //===----------------------------------------------------------------------===// -import XCTest import NIOCore +import XCTest + @testable import NIOHPACK -class HPACKIntegrationTests : XCTestCase { +class HPACKIntegrationTests: XCTestCase { private let hpackTestsURL: URL = { let myURL = URL(fileURLWithPath: #filePath, isDirectory: false) let result: URL @@ -28,47 +29,53 @@ class HPACKIntegrationTests : XCTestCase { } return result }() - - private enum TestType : String { + + private enum TestType: String { case encoding = "raw-data" - + case swiftNIOPlain = "swift-nio-hpack-plain-text" case swiftNIOHuffman = "swift-nio-hpack-huffman" case node = "node-http2-hpack" case python = "python-hpack" case go = "go-hpack" - + case nghttp2 case nghttp2ChangeTableSize = "nghttp2-change-table-size" case nghttp2LargeTables = "nghttp2-16384-4096" - + case haskellStatic = "haskell-http2-static" case haskellStaticHuffman = "haskell-http2-static-huffman" case haskellNaive = "haskell-http2-naive" case haskellNaiveHuffman = "haskell-http2-naive-huffman" case haskellLinear = "haskell-http2-linear" case haskellLinearHuffman = "haskell-http2-linear-huffman" - + static let allCases: [TestType] = [ .encoding, .swiftNIOPlain, .swiftNIOHuffman, .node, .python, .go, .nghttp2, .nghttp2ChangeTableSize, .nghttp2LargeTables, .haskellStatic, .haskellStaticHuffman, .haskellNaive, .haskellNaiveHuffman, - .haskellLinear, .haskellLinearHuffman + .haskellLinear, .haskellLinearHuffman, ] } - + private func getSourceURL(for type: TestType) -> URL { - return self.hpackTestsURL.appendingPathComponent(type.rawValue, isDirectory: true).absoluteURL + self.hpackTestsURL.appendingPathComponent(type.rawValue, isDirectory: true).absoluteURL } - + private func loadStories(for test: TestType) -> [HPACKStory] { let url = self.getSourceURL(for: test) - guard let contents = try? FileManager.default.contentsOfDirectory(at: url, includingPropertiesForKeys: nil, options: []).sorted(by: {$0.lastPathComponent < $1.lastPathComponent}) else { + guard + let contents = try? FileManager.default.contentsOfDirectory( + at: url, + includingPropertiesForKeys: nil, + options: [] + ).sorted(by: { $0.lastPathComponent < $1.lastPathComponent }) + else { return [] } - + let decoder = JSONDecoder() - + do { var stories = try contents.compactMap { url -> HPACKStory? in // for some reason using filter({ $0.pathExtension == "json" }) throws the compiler type-checker for a loop @@ -76,7 +83,7 @@ class HPACKIntegrationTests : XCTestCase { let data = try Data(contentsOf: url, options: [.uncached, .mappedIfSafe]) return try decoder.decode(HPACKStory.self, from: data) } - + // ensure there are valid non-zero sequence numbers // to ensure we modify these value types in-place we apparently need to use collection subscripting for all accesses // it seems that if there are sequence numbers on any cases they're on all cases; we can optimize for that. @@ -91,7 +98,7 @@ class HPACKIntegrationTests : XCTestCase { return [] } } - + private func runEncodingTests(withOutput type: TestType) { let huffmanEncoded = type == .swiftNIOHuffman let stories = loadStories(for: .encoding) @@ -99,47 +106,47 @@ class HPACKIntegrationTests : XCTestCase { // we don't have the data, so don't go failing any tests return } - + let outputDir = getSourceURL(for: type) if FileManager.default.fileExists(atPath: outputDir.path) == false { try! FileManager.default.createDirectory(at: outputDir, withIntermediateDirectories: true, attributes: nil) } - + var outputs: [HPACKStory] = [] - + let start = Date() - + for (idx, story) in stories.enumerated() { let encoded = runEncodeStory(story, idx, huffmanEncoded: huffmanEncoded) outputs.append(encoded) } - + let end = Date() print("Encoding took \(String(format: "%.02f", end.timeIntervalSince(start))) seconds.") - + for (idx, story) in outputs.enumerated() { writeOutputStory(story, at: idx, to: outputDir) } } - + // funky names to ensure the encoder tests run before the decoder tests. func testAAEncoderWithoutHuffmanCoding() { runEncodingTests(withOutput: .swiftNIOPlain) } - + // funky names to ensure the encoder tests run before the decoder tests. func testABEncoderWithHuffmanCoding() { runEncodingTests(withOutput: .swiftNIOHuffman) } - + func testDecoder() { - var testTimings: [TestType : TimeInterval] = [:] - + var testTimings: [TestType: TimeInterval] = [:] + for test in TestType.allCases where test != .encoding { let duration = _testDecoder(for: test) testTimings[test] = duration } - + print("Test timing metrics:") for (test, duration) in testTimings { let testName = test.rawValue @@ -147,11 +154,11 @@ class HPACKIntegrationTests : XCTestCase { if firstPart.count < 40 { firstPart.append(String(repeating: " ", count: 40 - firstPart.count)) } - + print("\(firstPart) : \(String(format: "%.02f", duration)) seconds.") } } - + private func _testDecoder(for test: TestType) -> TimeInterval { let loadStart = Date() print("Loading \(test.rawValue)...", terminator: "") @@ -163,23 +170,23 @@ class HPACKIntegrationTests : XCTestCase { return 0 } print(" done. Load time = \(String(format: "%.02f", loadTime)) seconds.") - + // description comes from first test case if let description = stories.first!.description { print(description) } - + let start = Date() - + for (idx, story) in stories.enumerated() { var decoder = HPACKDecoder(allocator: ByteBufferAllocator()) - + for testCase in story.cases { do { if let size = testCase.headerTableSize { decoder.maxDynamicTableLength = size } - + guard var bytes = testCase.wire else { XCTFail("Decoder story case \(testCase.seqno) has no wire data to decode!") return Date().timeIntervalSince(start) @@ -192,17 +199,18 @@ class HPACKIntegrationTests : XCTestCase { } } } - + return Date().timeIntervalSince(start) } - + private func writeOutputStory(_ story: HPACKStory, at index: Int, to directory: URL) { - let outURL = directory + let outURL = + directory .appendingPathComponent(String(format: "story_%02d", index), isDirectory: false) .appendingPathExtension("json") let encoder = JSONEncoder() encoder.outputFormatting = .prettyPrinted - + do { let data = try encoder.encode(story) try data.write(to: outURL, options: [.atomic]) @@ -210,35 +218,37 @@ class HPACKIntegrationTests : XCTestCase { print("Error writing encoded test case: \(error)") } } - + private func runEncodeStory(_ story: HPACKStory, _ index: Int, huffmanEncoded: Bool = true) -> HPACKStory { // do we need to care about the context? var encoder = HPACKEncoder(allocator: ByteBufferAllocator(), useHuffmanEncoding: huffmanEncoded) var decoder = HPACKDecoder(allocator: ByteBufferAllocator()) - + var result = story result.cases.removeAll() if huffmanEncoded { - result.description = "Encoded using the HPACK implementation of swift-nio-http2, with static table, dynamic table, and huffman encoded strings: " + result.description = + "Encoded using the HPACK implementation of swift-nio-http2, with static table, dynamic table, and huffman encoded strings: " } else { - result.description = "Encoded using the HPACK implementation of swift-nio-http2, with static table, dynamic table, and plain-text encoded strings: " + result.description = + "Encoded using the HPACK implementation of swift-nio-http2, with static table, dynamic table, and plain-text encoded strings: " } - + for storyCase in story.cases { do { if let tableSize = storyCase.headerTableSize { try encoder.setDynamicTableSize(tableSize) decoder.maxDynamicTableLength = tableSize } - + try encoder.beginEncoding(allocator: ByteBufferAllocator()) try encoder.append(headers: storyCase.headers) - + var outputCase = storyCase var encoded = try encoder.endEncoding() outputCase.wire = encoded result.cases.append(outputCase) - + // now try to decode it let decoded = try decoder.decodeHeaders(from: &encoded) XCTAssertEqual(storyCase.headers, decoded) @@ -247,84 +257,84 @@ class HPACKIntegrationTests : XCTestCase { XCTFail("Failure in story \(index), case \(storyCase.seqno) - \(error)") } } - + // the output story now has all the wire values filled in return result } - + } -struct HPACKStory : Codable { +struct HPACKStory: Codable { var context: HPACKStoryContext? var description: String? var cases: [HPACKStoryCase] } -enum HPACKStoryContext : String, Codable { +enum HPACKStoryContext: String, Codable { case request case response } -struct HPACKStoryCase : Codable { +struct HPACKStoryCase: Codable { var seqno: Int var headerTableSize: Int? var wire: ByteBuffer? var headers: HPACKHeaders - - private enum Keys : String, CodingKey { + + private enum Keys: String, CodingKey { case seqno case headerTableSize = "header_table_size" case wire case headers } - + init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: Keys.self) self.seqno = try container.decodeIfPresent(Int.self, forKey: .seqno) ?? 0 self.headerTableSize = try container.decodeIfPresent(Int.self, forKey: .headerTableSize) - + if let wireString = try container.decodeIfPresent(String.self, forKey: .wire) { self.wire = decodeHexData(from: wireString) } else { self.wire = nil } - - let rawHeaders = try container.decode([[String : String]].self, forKey: .headers) + + let rawHeaders = try container.decode([[String: String]].self, forKey: .headers) let pairs = rawHeaders.map { ($0.first!.key, $0.first!.value) } self.headers = HPACKHeaders(pairs) } - + func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: Keys.self) try container.encode(self.seqno, forKey: .seqno) try container.encode(self.headerTableSize, forKey: .headerTableSize) - + if let bytes = self.wire { try container.encode(encodeHex(data: bytes), forKey: .wire) } - - let rawHeaders = self.headers.map { [$0.0 : $0.1] } + + let rawHeaders = self.headers.map { [$0.0: $0.1] } try container.encode(rawHeaders, forKey: .headers) } } -fileprivate func decodeHexData(from string: String) -> ByteBuffer { +private func decodeHexData(from string: String) -> ByteBuffer { var bytes: [UInt8] = [] var idx = string.startIndex - + repeat { let byteStr = string[idx...string.index(after: idx)] bytes.append(UInt8(byteStr, radix: 16)!) idx = string.index(idx, offsetBy: 2) - + } while string.distance(from: idx, to: string.endIndex) > 1 - + var buf = ByteBufferAllocator().buffer(capacity: bytes.count) _ = buf.writeBytes(bytes) return buf } -fileprivate func encodeHex(data: ByteBuffer) -> String { +private func encodeHex(data: ByteBuffer) -> String { var result = "" for byte in data.readableBytesView { let str = String(byte, radix: 16) diff --git a/Tests/NIOHPACKTests/HPACKRegressionTests.swift b/Tests/NIOHPACKTests/HPACKRegressionTests.swift index 097feb8..0d5885b 100644 --- a/Tests/NIOHPACKTests/HPACKRegressionTests.swift +++ b/Tests/NIOHPACKTests/HPACKRegressionTests.swift @@ -12,9 +12,9 @@ // //===----------------------------------------------------------------------===// -import XCTest import NIOCore import NIOHPACK +import XCTest class HPACKRegressionTests: XCTestCase { @@ -39,44 +39,46 @@ class HPACKRegressionTests: XCTestCase { XCTAssertEqual(decoded, HPACKHeaders([(":status", "200"), ("date", "Tue, 16 Apr 2019 08:43:34 GMT")])) } - func testHPACKDecoderForbidsZeroLengthFieldNames() throws { // This test validates the fix for CVE-XXXX: we reject header fields without a header field name. let request1 = buffer(wrapping: [ - 0x00, // Literal Header Field without Indexing - New Name - 0x00, // Empty header field name, no huffman. - 0x01, 0x42 // Header field value one character long, 'B', no huffman + 0x00, // Literal Header Field without Indexing - New Name + 0x00, // Empty header field name, no huffman. + 0x01, 0x42, // Header field value one character long, 'B', no huffman ]) let request2 = buffer(wrapping: [ - 0x00, // Literal Header Field without Indexing - New Name - 0x80, // Empty header field name with huffman. - 0x01, 0x42 // Header field value one character long, 'B', no huffman. + 0x00, // Literal Header Field without Indexing - New Name + 0x80, // Empty header field name with huffman. + 0x01, 0x42, // Header field value one character long, 'B', no huffman. ]) let request3 = buffer(wrapping: [ - 0x40, // Literal Header Field with Incremental Indexing - New Name - 0x00, // Empty header field name, no huffman. - 0x01, 0x42 // Header field value one character long, 'B', no huffman + 0x40, // Literal Header Field with Incremental Indexing - New Name + 0x00, // Empty header field name, no huffman. + 0x01, 0x42, // Header field value one character long, 'B', no huffman ]) let request4 = buffer(wrapping: [ - 0x40, // Literal Header Field with Incremental Indexing - New Name - 0x80, // Empty header field name with huffman. - 0x01, 0x42 // Header field value one character long, 'B', no huffman. + 0x40, // Literal Header Field with Incremental Indexing - New Name + 0x80, // Empty header field name with huffman. + 0x01, 0x42, // Header field value one character long, 'B', no huffman. ]) let request5 = buffer(wrapping: [ - 0x10, // Literal Header Field Never Indexed - New Name - 0x00, // Empty header field name, no huffman. - 0x01, 0x42 // Header field value one character long, 'B', no huffman - ]) + 0x10, // Literal Header Field Never Indexed - New Name + 0x00, // Empty header field name, no huffman. + 0x01, 0x42, // Header field value one character long, 'B', no huffman + ]) let request6 = buffer(wrapping: [ - 0x10, // Literal Header Field Never Indexed - New Name - 0x80, // Empty header field name with huffman. - 0x01, 0x42 // Header field value one character long, 'B', no huffman. + 0x10, // Literal Header Field Never Indexed - New Name + 0x80, // Empty header field name with huffman. + 0x01, 0x42, // Header field value one character long, 'B', no huffman. ]) for var request in [request1, request2, request3, request4, request5, request6] { var decoder = HPACKDecoder(allocator: ByteBufferAllocator()) XCTAssertThrowsError(try decoder.decodeHeaders(from: &request)) { error in - XCTAssertEqual(error as? NIOHPACKErrors.EmptyLiteralHeaderFieldName, NIOHPACKErrors.EmptyLiteralHeaderFieldName()) + XCTAssertEqual( + error as? NIOHPACKErrors.EmptyLiteralHeaderFieldName, + NIOHPACKErrors.EmptyLiteralHeaderFieldName() + ) } } } diff --git a/Tests/NIOHPACKTests/HeaderTableTests.swift b/Tests/NIOHPACKTests/HeaderTableTests.swift index 5d96f90..ff8034b 100644 --- a/Tests/NIOHPACKTests/HeaderTableTests.swift +++ b/Tests/NIOHPACKTests/HeaderTableTests.swift @@ -12,14 +12,18 @@ // //===----------------------------------------------------------------------===// -import XCTest import NIOCore +import XCTest + @testable import NIOHPACK -func XCTAssertEqualTuple(_ expression1: @autoclosure () throws -> (T1, T2)?, - _ expression2: @autoclosure () throws -> (T1, T2)?, - _ message: @autoclosure () -> String = "", - file: StaticString = #filePath, line: UInt = #line) { +func XCTAssertEqualTuple( + _ expression1: @autoclosure () throws -> (T1, T2)?, + _ expression2: @autoclosure () throws -> (T1, T2)?, + _ message: @autoclosure () -> String = "", + file: StaticString = #filePath, + line: UInt = #line +) { let ex1: (T1, T2)? let ex2: (T1, T2)? do { @@ -29,7 +33,7 @@ func XCTAssertEqualTuple(_ expression1: @autoclosu XCTFail("Unexpected exception: \(error) \(message())", file: (file), line: line) return } - + let left1 = ex1?.0 let right1 = ex2?.0 let left2 = ex1?.1 @@ -43,7 +47,7 @@ class HeaderTableTests: XCTestCase { func testStaticHeaderTable() { let table = IndexedHeaderTable(allocator: ByteBufferAllocator()) - + // headers with matching values XCTAssertEqualTuple((2, true), table.firstHeaderMatch(for: ":method", value: "GET")!) XCTAssertEqualTuple((3, true), table.firstHeaderMatch(for: ":method", value: "POST")!) @@ -53,99 +57,102 @@ class HeaderTableTests: XCTestCase { XCTAssertEqualTuple((13, true), table.firstHeaderMatch(for: ":status", value: "404")!) XCTAssertEqualTuple((14, true), table.firstHeaderMatch(for: ":status", value: "500")!) XCTAssertEqualTuple((16, true), table.firstHeaderMatch(for: "accept-encoding", value: "gzip, deflate")!) - + // headers with no values in the table XCTAssertEqualTuple((15, false), table.firstHeaderMatch(for: "accept-charset", value: "any")!) XCTAssertEqualTuple((24, false), table.firstHeaderMatch(for: "cache-control", value: "private")!) - + // header-only matches for table entries with a different value XCTAssertEqualTuple((8, false), table.firstHeaderMatch(for: ":status", value: "501")!) XCTAssertEqualTuple((4, false), table.firstHeaderMatch(for: ":path", value: "/test/path.html")!) XCTAssertEqualTuple((2, false), table.firstHeaderMatch(for: ":method", value: "CONNECT")!) - + // things that aren't in the table at all XCTAssertNil(table.firstHeaderMatch(for: "non-existent-key", value: "non-existent-value")) } - + func testDynamicTableInsertion() { // NB: I'm using the overall table class to verify the expected indices of dynamic table items. var table = IndexedHeaderTable(allocator: ByteBufferAllocator(), maxDynamicTableSize: 1024) XCTAssertEqual(table.dynamicTableLength, 0) - + XCTAssertNoThrow(try table.add(headerNamed: ":authority", value: "www.example.com")) XCTAssertEqual(table.dynamicTableLength, 57) XCTAssertEqualTuple((62, true), table.firstHeaderMatch(for: ":authority", value: "www.example.com")!) XCTAssertEqualTuple((1, false), table.firstHeaderMatch(for: ":authority", value: "www.something-else.com")!) - + XCTAssertNoThrow(try table.add(headerNamed: "cache-control", value: "no-cache")) XCTAssertEqual(table.dynamicTableLength, 110) XCTAssertEqualTuple((62, true), table.firstHeaderMatch(for: "cache-control", value: "no-cache")!) XCTAssertEqualTuple((63, true), table.firstHeaderMatch(for: ":authority", value: "www.example.com")!) - + // custom key not yet in the table, should return nil XCTAssertNil(table.firstHeaderMatch(for: "custom-key", value: "custom-value")) - + XCTAssertNoThrow(try table.add(headerNamed: "custom-key", value: "custom-value")) XCTAssertEqual(table.dynamicTableLength, 164) XCTAssertEqualTuple((62, true), table.firstHeaderMatch(for: "custom-key", value: "custom-value")!) XCTAssertEqualTuple((62, false), table.firstHeaderMatch(for: "custom-key", value: "other-value")!) XCTAssertEqualTuple((63, true), table.firstHeaderMatch(for: "cache-control", value: "no-cache")!) XCTAssertEqualTuple((64, true), table.firstHeaderMatch(for: ":authority", value: "www.example.com")!) - + // should evict the first-inserted value (:authority = www.example.com) table.dynamicTableAllowedLength = 128 XCTAssertEqual(table.dynamicTableLength, 164 - 57) XCTAssertEqualTuple((62, true), table.firstHeaderMatch(for: "custom-key", value: "custom-value")!) XCTAssertEqualTuple((62, false), table.firstHeaderMatch(for: "custom-key", value: "other-value")!) XCTAssertEqualTuple((63, true), table.firstHeaderMatch(for: "cache-control", value: "no-cache")!) - XCTAssertEqualTuple((1, false), table.firstHeaderMatch(for: ":authority", value: "www.example.com")!) // will find the header name in static table - + // will find the header name in static table + XCTAssertEqualTuple((1, false), table.firstHeaderMatch(for: ":authority", value: "www.example.com")!) + table.dynamicTableAllowedLength = 64 XCTAssertEqual(table.dynamicTableLength, 164 - 110) XCTAssertEqualTuple((62, true), table.firstHeaderMatch(for: "custom-key", value: "custom-value")!) XCTAssertEqualTuple((62, false), table.firstHeaderMatch(for: "custom-key", value: "other-value")!) - XCTAssertEqualTuple((24, false), table.firstHeaderMatch(for: "cache-control", value: "no-cache")!) // will find the header name in static table - XCTAssertEqualTuple((1, false), table.firstHeaderMatch(for: ":authority", value: "www.example.com")!) // will find the header name in static table - - table.dynamicTableAllowedLength = 164 - 110 // should cause no evictions + // will find the header name in static table + XCTAssertEqualTuple((24, false), table.firstHeaderMatch(for: "cache-control", value: "no-cache")!) + // will find the header name in static table + XCTAssertEqualTuple((1, false), table.firstHeaderMatch(for: ":authority", value: "www.example.com")!) + + table.dynamicTableAllowedLength = 164 - 110 // should cause no evictions XCTAssertEqual(table.dynamicTableLength, 164 - 110) XCTAssertEqualTuple((62, true), table.firstHeaderMatch(for: "custom-key", value: "custom-value")!) - + // get code coverage for dynamic table search with no value to match // Note that the resulting index is an index into the dynamic table only, so we // have to modify it to check that it's what we expect. if let found = table.dynamicTable.findExistingHeader(named: "custom-key", value: nil) { XCTAssertEqualTuple((62 - StaticHeaderTable.count, false), found) } - + // evict final entry table.dynamicTableAllowedLength = table.dynamicTableLength - 1 XCTAssertEqual(table.dynamicTableLength, 0) XCTAssertNil(table.firstHeaderMatch(for: "custom-key", value: "custom-value")) } - + func testHeaderDump() throws { var table = IndexedHeaderTable(allocator: ByteBufferAllocator()) let description = table.dumpHeaders() - + // construct what we expect var expected = StaticHeaderTable.enumerated().reduce("") { $0 + "\($1.0) - \($1.1.0) : \($1.1.1)\n" } - + // there will be a newline at the end, followed by no data for the dynamic table expected += "\n" - + XCTAssertEqual(description, expected) - + // add an item to the dynamic table try table.add(headerNamed: "custom-key", value: "custom-value") expected += "\(StaticHeaderTable.count) - custom-key : custom-value\n" - + let description2 = table.dumpHeaders() XCTAssertEqual(description2, expected) } - + func testHeaderDescription() throws { let table = IndexedHeaderTable(allocator: ByteBufferAllocator()) let staticDescription = table.staticTable.description diff --git a/Tests/NIOHPACKTests/HuffmanCodingTests.swift b/Tests/NIOHPACKTests/HuffmanCodingTests.swift index cfbc658..b299cc4 100644 --- a/Tests/NIOHPACKTests/HuffmanCodingTests.swift +++ b/Tests/NIOHPACKTests/HuffmanCodingTests.swift @@ -12,78 +12,139 @@ // //===----------------------------------------------------------------------===// -import XCTest +import Foundation import NIOCore import NIOFoundationCompat -import Foundation +import XCTest + @testable import NIOHPACK class HuffmanCodingTests: XCTestCase { var scratchBuffer: ByteBuffer = ByteBufferAllocator().buffer(capacity: 4096) - + // MARK: - Helper Methods - - func assertEqualContents(_ buffer: ByteBuffer, _ array: [UInt8], file: StaticString = #filePath, line: UInt = #line) { - XCTAssertEqual(buffer.readableBytes, array.count, "Buffer and array are different sizes", file: (file), line: line) + + func assertEqualContents(_ buffer: ByteBuffer, _ array: [UInt8], file: StaticString = #filePath, line: UInt = #line) + { + XCTAssertEqual( + buffer.readableBytes, + array.count, + "Buffer and array are different sizes", + file: (file), + line: line + ) buffer.withUnsafeReadableBytes { bufPtr in array.withUnsafeBytes { arrayPtr in - XCTAssertEqual(memcmp(bufPtr.baseAddress!, arrayPtr.baseAddress!, arrayPtr.count), 0, "Buffer contents don't match", file: (file), line: line) + XCTAssertEqual( + memcmp(bufPtr.baseAddress!, arrayPtr.baseAddress!, arrayPtr.count), + 0, + "Buffer contents don't match", + file: (file), + line: line + ) } } } - - func verifyHuffmanCoding(_ string: String, _ bytes: [UInt8], file: StaticString = #filePath, line: UInt = #line) throws { + + func verifyHuffmanCoding( + _ string: String, + _ bytes: [UInt8], + file: StaticString = #filePath, + line: UInt = #line + ) throws { self.scratchBuffer.clear() - + let utf8 = string.utf8 let numBytes = self.scratchBuffer.writeHuffmanEncoded(bytes: utf8) XCTAssertEqual(numBytes, bytes.count, "Wrong length encoding '\(string)'", file: (file), line: line) - + assertEqualContents(self.scratchBuffer, bytes, file: (file), line: line) - let decoded = try scratchBuffer.getHuffmanEncodedString(at: self.scratchBuffer.readerIndex, length: self.scratchBuffer.readableBytes) + let decoded = try scratchBuffer.getHuffmanEncodedString( + at: self.scratchBuffer.readerIndex, + length: self.scratchBuffer.readableBytes + ) XCTAssertEqual(decoded, string, "Failed to decode '\(string)'", file: (file), line: line) } func testBasicCoding() throws { // all these values come from http://httpwg.org/specs/rfc7541.html#request.examples.with.huffman.coding - try verifyHuffmanCoding("www.example.com", [0xf1, 0xe3, 0xc2, 0xe5, 0xf2, 0x3a, 0x6b, 0xa0, 0xab, 0x90, 0xf4, 0xff]) + try verifyHuffmanCoding( + "www.example.com", + [0xf1, 0xe3, 0xc2, 0xe5, 0xf2, 0x3a, 0x6b, 0xa0, 0xab, 0x90, 0xf4, 0xff] + ) try verifyHuffmanCoding("no-cache", [0xa8, 0xeb, 0x10, 0x64, 0x9c, 0xbf]) try verifyHuffmanCoding("custom-key", [0x25, 0xa8, 0x49, 0xe9, 0x5b, 0xa9, 0x7d, 0x7f]) try verifyHuffmanCoding("custom-value", [0x25, 0xa8, 0x49, 0xe9, 0x5b, 0xb8, 0xe8, 0xb4, 0xbf]) - + // these come from http://httpwg.org/specs/rfc7541.html#response.examples.with.huffman.coding try verifyHuffmanCoding("302", [0x64, 0x02]) try verifyHuffmanCoding("private", [0xae, 0xc3, 0x77, 0x1a, 0x4b]) - try verifyHuffmanCoding("Mon, 21 Oct 2013 20:13:21 GMT", [0xd0, 0x7a, 0xbe, 0x94, 0x10, 0x54, 0xd4, 0x44, 0xa8, 0x20, 0x05, 0x95, 0x04, 0x0b, 0x81, 0x66, 0xe0, 0x82, 0xa6, 0x2d, 0x1b, 0xff]) - try verifyHuffmanCoding("https://www.example.com", [0x9d, 0x29, 0xad, 0x17, 0x18, 0x63, 0xc7, 0x8f, 0x0b, 0x97, 0xc8, 0xe9, 0xae, 0x82, 0xae, 0x43, 0xd3]) + try verifyHuffmanCoding( + "Mon, 21 Oct 2013 20:13:21 GMT", + [ + 0xd0, 0x7a, 0xbe, 0x94, 0x10, 0x54, 0xd4, 0x44, 0xa8, 0x20, 0x05, 0x95, 0x04, 0x0b, 0x81, 0x66, 0xe0, + 0x82, 0xa6, 0x2d, 0x1b, 0xff, + ] + ) + try verifyHuffmanCoding( + "https://www.example.com", + [0x9d, 0x29, 0xad, 0x17, 0x18, 0x63, 0xc7, 0x8f, 0x0b, 0x97, 0xc8, 0xe9, 0xae, 0x82, 0xae, 0x43, 0xd3] + ) try verifyHuffmanCoding("307", [0x64, 0x0e, 0xff]) - try verifyHuffmanCoding("Mon, 21 Oct 2013 20:13:22 GMT", [0xd0, 0x7a, 0xbe, 0x94, 0x10, 0x54, 0xd4, 0x44, 0xa8, 0x20, 0x05, 0x95, 0x04, 0x0b, 0x81, 0x66, 0xe0, 0x84, 0xa6, 0x2d, 0x1b, 0xff]) + try verifyHuffmanCoding( + "Mon, 21 Oct 2013 20:13:22 GMT", + [ + 0xd0, 0x7a, 0xbe, 0x94, 0x10, 0x54, 0xd4, 0x44, 0xa8, 0x20, 0x05, 0x95, 0x04, 0x0b, 0x81, 0x66, 0xe0, + 0x84, 0xa6, 0x2d, 0x1b, 0xff, + ] + ) try verifyHuffmanCoding("gzip", [0x9b, 0xd9, 0xab]) - try verifyHuffmanCoding("foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1", [0x94, 0xe7, 0x82, 0x1d, 0xd7, 0xf2, 0xe6, 0xc7, 0xb3, 0x35, 0xdf, 0xdf, 0xcd, 0x5b, 0x39, 0x60, 0xd5, 0xaf, 0x27, 0x08, 0x7f, 0x36, 0x72, 0xc1, 0xab, 0x27, 0x0f, 0xb5, 0x29, 0x1f, 0x95, 0x87, 0x31, 0x60, 0x65, 0xc0, 0x03, 0xed, 0x4e, 0xe5, 0xb1, 0x06, 0x3d, 0x50, 0x07]) + try verifyHuffmanCoding( + "foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1", + [ + 0x94, 0xe7, 0x82, 0x1d, 0xd7, 0xf2, 0xe6, 0xc7, 0xb3, 0x35, 0xdf, 0xdf, 0xcd, 0x5b, 0x39, 0x60, 0xd5, + 0xaf, 0x27, 0x08, 0x7f, 0x36, 0x72, 0xc1, 0xab, 0x27, 0x0f, 0xb5, 0x29, 0x1f, 0x95, 0x87, 0x31, 0x60, + 0x65, 0xc0, 0x03, 0xed, 0x4e, 0xe5, 0xb1, 0x06, 0x3d, 0x50, 0x07, + ] + ) } - + func testComplexCoding() throws { - try verifyHuffmanCoding("้ฏ–ๅฏฉ", [0xff, 0xff, 0xaf, 0xff, 0xff, 0x67, 0xff, 0xfe, 0x2f, 0xff, 0xf3, 0xff, 0xff, 0xec, 0xff, 0xff, 0x77]) - - let text1 = "Hello, world. I am a header value; I have Teh Texts. I am going on for quite a long time because I want to ensure that the encoded data buffer needs to be expanded to test out that code. I'll try some meta-characters too: \r\t\n ought to do it, no?" - guard let encoded1Data = Data(base64Encoded: "xlooP9KeD2USLqZFB0qDUnKOQtincdFpftTIpOPuVTeWdTeXylC6mRQdKkxzVTKHqUlPYp2tMkqg1KD1TKJNSVSMpB2oKpkU8DqSok6hakW2FUTONKiZyqFqIeQsikg0jUjtllLYpUUsiFEnUjKoXzWOqQsiiTqJKhKh7UqJnGlQh5CrqZP9UUKJs9KIPSVSkqRrEnHYMiS2IUSc9xT////3//+r////xQ9s06VEnUkOoZP0pUf/Pw==") else { + try verifyHuffmanCoding( + "้ฏ–ๅฏฉ", + [0xff, 0xff, 0xaf, 0xff, 0xff, 0x67, 0xff, 0xfe, 0x2f, 0xff, 0xf3, 0xff, 0xff, 0xec, 0xff, 0xff, 0x77] + ) + + let text1 = + "Hello, world. I am a header value; I have Teh Texts. I am going on for quite a long time because I want to ensure that the encoded data buffer needs to be expanded to test out that code. I'll try some meta-characters too: \r\t\n ought to do it, no?" + guard + let encoded1Data = Data( + base64Encoded: + "xlooP9KeD2USLqZFB0qDUnKOQtincdFpftTIpOPuVTeWdTeXylC6mRQdKkxzVTKHqUlPYp2tMkqg1KD1TKJNSVSMpB2oKpkU8DqSok6hakW2FUTONKiZyqFqIeQsikg0jUjtllLYpUUsiFEnUjKoXzWOqQsiiTqJKhKh7UqJnGlQh5CrqZP9UUKJs9KIPSVSkqRrEnHYMiS2IUSc9xT////3//+r////xQ9s06VEnUkOoZP0pUf/Pw==" + ) + else { XCTFail("Unable to import base-64 result data") return } - + // oh if only Data could conform to ContiguousCollection... try verifyHuffmanCoding(text1, Array(encoded1Data)) - + // The encoder has a 256-byte encoding buffer to start with, and we want to overflow that to make it expand automatically // We also want to include some > 24-bit codes to test all the conditions. // So: here's a goodly-sized chunk of UTF-8 text. It won't compress worth a damn. let text2 = "ๅˆใ‚ปใ‚ค่ฐท้ซ˜ใใตใ‚ใƒˆ้ฃŸ71ๅ…ฅใƒ„ใ‚จใƒ˜ใƒŠๆดฅ็œŒใ‚’้กžๅŠใ‚ชใƒขๆ›œไธ€่ณผใ”ใใ‚่‡ดๆŽฒใŽใใšๆ•—ๆ–‡่ผชใธใ‘ใ‚Š้ฏ–ๅฏฉใƒ˜ๅกŠ็ฑณๅธๅ‘ชใŠใดใ€‚" - guard let encoded2Data = Data(base64Encoded: "//8///3v//W//83//P//8n//m//5///c//+r//wf//v//+v///D//8n//m//9L//+z//zf/+l//8P//m//9L//n//83//R//63//1//+3///e6H//z//+p//+j//zf/9H//p//+b//n///V//5v/+j//8n//m//6P//t//+j//9v//6P//5//+z//93//zf/8///r///X//3f//z//+f//7///2///N//z//+9//5v/+j//p//9H//5f//Z//+n//q//5v//q//8X//8P//N//6X//93//m//9L//73//m//5///v///V//9n//9v//o///r//+D//zf/+l///X//5v//S///s//83//pf/+x//6P//w///j//9H//4v//s///V///D//3v//N//6X//V//5v//S///t//83//P//9v//6///2f//i//8///7P//d//83//R//+T//z//93//7f//8///D//4v//P//97//q//8///9v//vf/+b//0v//t//+b//0v//2//+b//m//5/") else { + guard + let encoded2Data = Data( + base64Encoded: + "//8///3v//W//83//P//8n//m//5///c//+r//wf//v//+v///D//8n//m//9L//+z//zf/+l//8P//m//9L//n//83//R//63//1//+3///e6H//z//+p//+j//zf/9H//p//+b//n///V//5v/+j//8n//m//6P//t//+j//9v//6P//5//+z//93//zf/8///r///X//3f//z//+f//7///2///N//z//+9//5v/+j//p//9H//5f//Z//+n//q//5v//q//8X//8P//N//6X//93//m//9L//73//m//5///v///V//9n//9v//o///r//+D//zf/+l///X//5v//S///s//83//pf/+x//6P//w///j//9H//4v//s///V///D//3v//N//6X//V//5v//S///t//83//P//9v//6///2f//i//8///7P//d//83//R//+T//z//93//7f//8///D//4v//P//97//q//8///9v//vf/+b//0v//t//+b//0v//2//+b//m//5/" + ) + else { XCTFail("Unable to import base-64 result data") return } - + try verifyHuffmanCoding(text2, Array(encoded2Data)) } } diff --git a/Tests/NIOHPACKTests/IntegerCodingTests.swift b/Tests/NIOHPACKTests/IntegerCodingTests.swift index 10fef44..8213550 100644 --- a/Tests/NIOHPACKTests/IntegerCodingTests.swift +++ b/Tests/NIOHPACKTests/IntegerCodingTests.swift @@ -12,16 +12,17 @@ // //===----------------------------------------------------------------------===// -import XCTest import NIOCore +import XCTest + @testable import NIOHPACK -class IntegerCodingTests : XCTestCase { - +class IntegerCodingTests: XCTestCase { + var scratchBuffer = ByteBufferAllocator().buffer(capacity: 11) - + // MARK: - Array-based helpers - + private func encodeIntegerToArray(_ value: UInt64, prefix: Int) -> [UInt8] { var data = [UInt8]() scratchBuffer.clear() @@ -29,40 +30,40 @@ class IntegerCodingTests : XCTestCase { data.append(contentsOf: scratchBuffer.viewBytes(at: 0, length: len)!) return data } - + private func decodeInteger(from array: [UInt8], prefix: Int) throws -> Int { scratchBuffer.clear() scratchBuffer.writeBytes(array) let result = try NIOHPACK.decodeInteger(from: scratchBuffer.readableBytesView, prefix: prefix) return result.value } - + // MARK: - Tests - + func testIntegerEncoding() { // values from the standard: http://httpwg.org/specs/rfc7541.html#integer.representation.examples var data = encodeIntegerToArray(10, prefix: 5) // 0000 1010 XCTAssertEqual(data.count, 1) XCTAssertEqual(data[0], 0b00001010) - - data = encodeIntegerToArray(1337, prefix: 5) // 0000 0101 0011 1001 + + data = encodeIntegerToArray(1337, prefix: 5) // 0000 0101 0011 1001 XCTAssertEqual(data.count, 3) - + // prefix bits = 31 = 0001 1111, 1337 - 31 = 1306 = 0101 0001 1010 -> x0001010 x0011010 - XCTAssertEqual(data, [31, 154, 10]) // 00011111 , 10011010 , 00001010 - + XCTAssertEqual(data, [31, 154, 10]) // 00011111 , 10011010 , 00001010 + // prefix 8 == use the whole first octet - data = encodeIntegerToArray(42, prefix: 8) // 0010 1010 + data = encodeIntegerToArray(42, prefix: 8) // 0010 1010 XCTAssertEqual(data.count, 1) XCTAssertEqual(data[0], 42) - - data = encodeIntegerToArray(256, prefix: 8) // 0001 0000 0000 -> 1111 1111 + 0000 0001 + + data = encodeIntegerToArray(256, prefix: 8) // 0001 0000 0000 -> 1111 1111 + 0000 0001 XCTAssertEqual(data.count, 2) XCTAssertEqual(data, [255, 1]) - + // very large value, few bits set, 8-bit prefix - data = encodeIntegerToArray(17 << 57, prefix: 8) // 00010001 << 57 or 2449958197289549824 - + data = encodeIntegerToArray(17 << 57, prefix: 8) // 00010001 << 57 or 2449958197289549824 + // calculations: // subtract prefix: // 2449958197289549824 - 255 = 2449958197289549569 or 0010 0001 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 0000 0001 @@ -74,10 +75,10 @@ class IntegerCodingTests : XCTestCase { // 10000001 11111110 11111111 11111111 11111111 11111111 11111111 11111111 00100001 XCTAssertEqual(data.count, 10) XCTAssertEqual(data, [255, 129, 254, 255, 255, 255, 255, 255, 255, 33]) - + // same value, 1-bit prefix: data = encodeIntegerToArray(17 << 57, prefix: 1) - + // calculations: // subtract prefix: // 2449958197289549824 - 1 = 2449958197289549823 or 0010 0001 (1111 x14) @@ -89,10 +90,10 @@ class IntegerCodingTests : XCTestCase { // 11111111 11111111 11111111 11111111 11111111 11111111 11111111 11111111 00100001 XCTAssertEqual(data.count, 10) XCTAssertEqual(data, [1, 255, 255, 255, 255, 255, 255, 255, 255, 33]) - + // encoding max 64-bit unsigned integer, 1-bit prefix data = encodeIntegerToArray(UInt64.max, prefix: 1) - + // calculations: // subtract prefix: // 18446744073709551615 - 1 = 18446744073709551614 or (1111 x15) 1110 @@ -104,10 +105,10 @@ class IntegerCodingTests : XCTestCase { // 11111110 11111111 11111111 11111111 11111111 11111111 11111111 11111111 11111111 00000001 XCTAssertEqual(data.count, 11) XCTAssertEqual(data, [1, 254, 255, 255, 255, 255, 255, 255, 255, 255, 1]) - + // something carefully crafted to produce maximum number of output bytes with minimum number of // nonzero bits: - data = encodeIntegerToArray(9223372036854775809, prefix: 1) + data = encodeIntegerToArray(9_223_372_036_854_775_809, prefix: 1) // calculations: // subtract prefix: @@ -120,11 +121,11 @@ class IntegerCodingTests : XCTestCase { // 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 10000000 00000001 XCTAssertEqual(data.count, 11) XCTAssertEqual(data, [1, 128, 128, 128, 128, 128, 128, 128, 128, 128, 1]) - + // something similar, which uses an 8-bit prefix and still produces lots of zero bits: // for those interested: this is the previous value + 254; thus only the first byte should differ - data = encodeIntegerToArray(9223372036854776063, prefix: 8) - + data = encodeIntegerToArray(9_223_372_036_854_776_063, prefix: 8) + // calculations: // subtract prefix: // 9223372036854776063 - 255 = 9223372036854775808 or 1000 (0000 x15) @@ -137,12 +138,12 @@ class IntegerCodingTests : XCTestCase { XCTAssertEqual(data.count, 11) XCTAssertEqual(data, [255, 128, 128, 128, 128, 128, 128, 128, 128, 128, 1]) } - + func testIntegerDecoding() throws { // any bits above the prefix amount shouldn't affect the outcome. XCTAssertEqual(try decodeInteger(from: [0b00001010], prefix: 5), 10) XCTAssertEqual(try decodeInteger(from: [0b11101010], prefix: 5), 10) - + XCTAssertEqual(try decodeInteger(from: [0b00011111, 154, 10], prefix: 5), 1337) XCTAssertEqual(try decodeInteger(from: [0b11111111, 154, 10], prefix: 5), 1337) @@ -150,15 +151,30 @@ class IntegerCodingTests : XCTestCase { // Now some larger numbers: #if !os(watchOS) - XCTAssertEqual(try decodeInteger(from: [255, 129, 254, 255, 255, 255, 255, 255, 255, 33], prefix: 8), 2449958197289549824) - XCTAssertEqual(try decodeInteger(from: [1, 255, 255, 255, 255, 255, 255, 255, 255, 33], prefix: 1), 2449958197289549824) - XCTAssertEqual(try decodeInteger(from: [1, 254, 255, 255, 255, 255, 255, 255, 255, 127, 1], prefix: 1), Int.max) + XCTAssertEqual( + try decodeInteger(from: [255, 129, 254, 255, 255, 255, 255, 255, 255, 33], prefix: 8), + 2_449_958_197_289_549_824 + ) + XCTAssertEqual( + try decodeInteger(from: [1, 255, 255, 255, 255, 255, 255, 255, 255, 33], prefix: 1), + 2_449_958_197_289_549_824 + ) + XCTAssertEqual( + try decodeInteger(from: [1, 254, 255, 255, 255, 255, 255, 255, 255, 127, 1], prefix: 1), + Int.max + ) // lots of zeroes: each 128 yields zero - XCTAssertEqual(try decodeInteger(from: [1, 128, 128, 128, 128, 128, 128, 128, 128, 127, 1], prefix: 1), 9151314442816847873) + XCTAssertEqual( + try decodeInteger(from: [1, 128, 128, 128, 128, 128, 128, 128, 128, 127, 1], prefix: 1), + 9_151_314_442_816_847_873 + ) // almost the same bytes, but a different prefix: - XCTAssertEqual(try decodeInteger(from: [255, 128, 128, 128, 128, 128, 128, 128, 128, 127, 1], prefix: 8), 9151314442816848127) + XCTAssertEqual( + try decodeInteger(from: [255, 128, 128, 128, 128, 128, 128, 128, 128, 127, 1], prefix: 8), + 9_151_314_442_816_848_127 + ) #endif // now a silly version which should never have been encoded in so many bytes @@ -168,7 +184,9 @@ class IntegerCodingTests : XCTestCase { func testIntegerDecodingMultiplicationDoesNotOverflow() throws { // Zeros with continuation bits (e.g. 128) to increase the shift value (to 9 * 7 = 63), and then multiply by 127. for `prefix` in 1...8 { - XCTAssertThrowsError(try decodeInteger(from: [255, 128, 128, 128, 128, 128, 128, 128, 128, 128, 127], prefix: prefix)) { error in + XCTAssertThrowsError( + try decodeInteger(from: [255, 128, 128, 128, 128, 128, 128, 128, 128, 128, 127], prefix: prefix) + ) { error in XCTAssert(error is NIOHPACKErrors.UnrepresentableInteger) } } @@ -177,7 +195,9 @@ class IntegerCodingTests : XCTestCase { func testIntegerDecodingAdditionDoesNotOverflow() throws { // Zeros with continuation bits (e.g. 128) to increase the shift value (to 9 * 7 = 63), and then multiply by 127. for `prefix` in 1...8 { - XCTAssertThrowsError(try decodeInteger(from: [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 127], prefix: prefix)) { error in + XCTAssertThrowsError( + try decodeInteger(from: [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 127], prefix: prefix) + ) { error in XCTAssert(error is NIOHPACKErrors.UnrepresentableInteger) } } @@ -186,7 +206,9 @@ class IntegerCodingTests : XCTestCase { func testIntegerDecodingShiftDoesNotOverflow() throws { // With enough iterations we expect the shift to become greater >= 64. for `prefix` in 1...8 { - XCTAssertThrowsError(try decodeInteger(from: [255, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128], prefix: prefix)) { error in + XCTAssertThrowsError( + try decodeInteger(from: [255, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128], prefix: prefix) + ) { error in XCTAssert(error is NIOHPACKErrors.UnrepresentableInteger) } } diff --git a/Tests/NIOHTTP2Tests/CircularBufferExtensionsTests.swift b/Tests/NIOHTTP2Tests/CircularBufferExtensionsTests.swift index 349181b..d9beaf5 100644 --- a/Tests/NIOHTTP2Tests/CircularBufferExtensionsTests.swift +++ b/Tests/NIOHTTP2Tests/CircularBufferExtensionsTests.swift @@ -12,8 +12,9 @@ // //===----------------------------------------------------------------------===// -import XCTest import NIOCore +import XCTest + @testable import NIOHTTP2 final class CircularBufferExtensionsTests: XCTestCase { @@ -50,7 +51,6 @@ final class CircularBufferExtensionsTests: XCTestCase { XCTAssertEqual(buffer.count, 15) XCTAssertEqual(buffer.effectiveCapacity, 15) - buffer.prependWithoutExpanding(17) XCTAssertEqual(Array(buffer), [17, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]) XCTAssertEqual(buffer.count, 15) diff --git a/Tests/NIOHTTP2Tests/CompoundOutboundBufferTest.swift b/Tests/NIOHTTP2Tests/CompoundOutboundBufferTest.swift index 2f13d7b..fcabf0d 100644 --- a/Tests/NIOHTTP2Tests/CompoundOutboundBufferTest.swift +++ b/Tests/NIOHTTP2Tests/CompoundOutboundBufferTest.swift @@ -12,11 +12,12 @@ // //===----------------------------------------------------------------------===// -import XCTest import NIOConcurrencyHelpers import NIOCore import NIOEmbedded import NIOHPACK +import XCTest + @testable import NIOHTTP2 final class CompoundOutboundBufferTest: XCTestCase { @@ -32,11 +33,18 @@ final class CompoundOutboundBufferTest: XCTestCase { } func testSimpleControlFramePassthrough() { - var buffer = CompoundOutboundBuffer(mode: .client, initialMaxOutboundStreams: 100, maxBufferedControlFrames: 1000) + var buffer = CompoundOutboundBuffer( + mode: .client, + initialMaxOutboundStreams: 100, + maxBufferedControlFrames: 1000 + ) let frames: [HTTP2Frame] = [ HTTP2Frame(streamID: .rootStream, payload: .ping(.init(withInteger: 0), ack: true)), - HTTP2Frame(streamID: .rootStream, payload: .goAway(lastStreamID: 0, errorCode: .protocolError, opaqueData: nil)), + HTTP2Frame( + streamID: .rootStream, + payload: .goAway(lastStreamID: 0, errorCode: .protocolError, opaqueData: nil) + ), HTTP2Frame(streamID: .rootStream, payload: .settings(.settings([]))), HTTP2Frame(streamID: .rootStream, payload: .alternativeService(origin: nil, field: nil)), HTTP2Frame(streamID: .rootStream, payload: .origin([])), @@ -45,7 +53,10 @@ final class CompoundOutboundBufferTest: XCTestCase { ] for frame in frames { - XCTAssertNoThrow(try buffer.processOutboundFrame(frame, promise: nil, channelWritable: true).assertForward(), "Threw on \(frame)") + XCTAssertNoThrow( + try buffer.processOutboundFrame(frame, promise: nil, channelWritable: true).assertForward(), + "Threw on \(frame)" + ) } } @@ -55,14 +66,21 @@ final class CompoundOutboundBufferTest: XCTestCase { // Let's create 100 new outbound streams. let firstFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: HPACKHeaders([])))) let subsequentFrames: [HTTP2Frame] = stride(from: 3, to: 201, by: 2).map { streamID in - HTTP2Frame(streamID: HTTP2StreamID(streamID), payload: .headers(.init(headers: HPACKHeaders([]), endStream: true))) + HTTP2Frame( + streamID: HTTP2StreamID(streamID), + payload: .headers(.init(headers: HPACKHeaders([]), endStream: true)) + ) } // Write the first frame, and all the subsequent frames, and flush them. This will lead to one flushed frame. - XCTAssertNoThrow(try buffer.processOutboundFrame(firstFrame, promise: nil, channelWritable: true).assertForward()) + XCTAssertNoThrow( + try buffer.processOutboundFrame(firstFrame, promise: nil, channelWritable: true).assertForward() + ) buffer.streamCreated(1, initialWindowSize: 65535) for frame in subsequentFrames { - XCTAssertNoThrow(try buffer.processOutboundFrame(frame, promise: nil, channelWritable: true).assertNothing()) + XCTAssertNoThrow( + try buffer.processOutboundFrame(frame, promise: nil, channelWritable: true).assertNothing() + ) } buffer.flushReceived() buffer.nextFlushedWritableFrame(channelWritable: true).assertNoFrame() @@ -110,11 +128,13 @@ final class CompoundOutboundBufferTest: XCTestCase { let elevenFrame = HTTP2Frame(streamID: 11, payload: .headers(.init(headers: HPACKHeaders([])))) XCTAssertNoThrow(try buffer.processOutboundFrame(oneFrame, promise: nil, channelWritable: true).assertForward()) buffer.streamCreated(1, initialWindowSize: 15) - XCTAssertNoThrow(try buffer.processOutboundFrame(elevenFrame, promise: nil, channelWritable: true).assertNothing()) + XCTAssertNoThrow( + try buffer.processOutboundFrame(elevenFrame, promise: nil, channelWritable: true).assertNothing() + ) // Now we're going to try to write a frame for stream 5. This will fail. let fiveFrame = HTTP2Frame(streamID: 5, payload: .headers(.init(headers: HPACKHeaders([])))) - XCTAssertThrowsError(try buffer.processOutboundFrame(fiveFrame, promise: nil, channelWritable: true)) {error in + XCTAssertThrowsError(try buffer.processOutboundFrame(fiveFrame, promise: nil, channelWritable: true)) { error in XCTAssertTrue(error is NIOHTTP2Errors.StreamIDTooSmall) } } @@ -144,7 +164,9 @@ final class CompoundOutboundBufferTest: XCTestCase { let dataFrame = self.createDataFrame(3, byteBufferSize: 15) XCTAssertNoThrow(try buffer.processOutboundFrame(oneFrame, promise: nil, channelWritable: true).assertForward()) buffer.streamCreated(1, initialWindowSize: 15) - XCTAssertNoThrow(try buffer.processOutboundFrame(dataFrame, promise: nil, channelWritable: true).assertNothing()) + XCTAssertNoThrow( + try buffer.processOutboundFrame(dataFrame, promise: nil, channelWritable: true).assertNothing() + ) buffer.flushReceived() buffer.nextFlushedWritableFrame(channelWritable: true).assertNoFrame() @@ -168,14 +190,22 @@ final class CompoundOutboundBufferTest: XCTestCase { let startPromise = self.loop.makePromise(of: Void.self) let dataPromise = self.loop.makePromise(of: Void.self) if streamID == 1 { - XCTAssertNoThrow(try buffer.processOutboundFrame(startFrame, promise: startPromise, channelWritable: true).assertForward()) + XCTAssertNoThrow( + try buffer.processOutboundFrame(startFrame, promise: startPromise, channelWritable: true) + .assertForward() + ) startPromise.succeed(()) buffer.streamCreated(streamID, initialWindowSize: 65535) } else { - XCTAssertNoThrow(try buffer.processOutboundFrame(startFrame, promise: startPromise, channelWritable: true).assertNothing()) + XCTAssertNoThrow( + try buffer.processOutboundFrame(startFrame, promise: startPromise, channelWritable: true) + .assertNothing() + ) } - XCTAssertNoThrow(try buffer.processOutboundFrame(dataFrame, promise: dataPromise, channelWritable: true).assertNothing()) + XCTAssertNoThrow( + try buffer.processOutboundFrame(dataFrame, promise: dataPromise, channelWritable: true).assertNothing() + ) futures.append(contentsOf: [startPromise.futureResult, dataPromise.futureResult]) } @@ -185,7 +215,10 @@ final class CompoundOutboundBufferTest: XCTestCase { results[idx] = true } }.whenFailure { error in - XCTAssertEqual(error as? NIOHTTP2Errors.StreamClosed, NIOHTTP2Errors.streamClosed(streamID: 3, errorCode: .protocolError)) + XCTAssertEqual( + error as? NIOHTTP2Errors.StreamClosed, + NIOHTTP2Errors.streamClosed(streamID: 3, errorCode: .protocolError) + ) results.withLockedValue { results in results[idx] = false } @@ -218,10 +251,14 @@ final class CompoundOutboundBufferTest: XCTestCase { func testRejectsPrioritySelfDependency() { var buffer = CompoundOutboundBuffer(mode: .client, initialMaxOutboundStreams: 1, maxBufferedControlFrames: 1000) - XCTAssertThrowsError(try buffer.priorityUpdate(streamID: 1, priorityData: .init(exclusive: false, dependency: 1, weight: 36))) { error in + XCTAssertThrowsError( + try buffer.priorityUpdate(streamID: 1, priorityData: .init(exclusive: false, dependency: 1, weight: 36)) + ) { error in XCTAssertEqual(error as? NIOHTTP2Errors.PriorityCycle, NIOHTTP2Errors.priorityCycle(streamID: 1)) } - XCTAssertThrowsError(try buffer.priorityUpdate(streamID: 1, priorityData: .init(exclusive: true, dependency: 1, weight: 36))) { error in + XCTAssertThrowsError( + try buffer.priorityUpdate(streamID: 1, priorityData: .init(exclusive: true, dependency: 1, weight: 36)) + ) { error in XCTAssertEqual(error as? NIOHTTP2Errors.PriorityCycle, NIOHTTP2Errors.priorityCycle(streamID: 1)) } } @@ -244,12 +281,20 @@ final class CompoundOutboundBufferTest: XCTestCase { let secondHeaders = HTTP2Frame(streamID: 3, payload: .headers(.init(headers: HPACKHeaders([])))) let secondData = self.createDataFrame(3, byteBufferSize: 5) - XCTAssertNoThrow(try buffer.processOutboundFrame(firstHeaders, promise: nil, channelWritable: true).assertForward()) + XCTAssertNoThrow( + try buffer.processOutboundFrame(firstHeaders, promise: nil, channelWritable: true).assertForward() + ) buffer.streamCreated(1, initialWindowSize: 65535) - XCTAssertNoThrow(try buffer.processOutboundFrame(firstData, promise: nil, channelWritable: true).assertNothing()) + XCTAssertNoThrow( + try buffer.processOutboundFrame(firstData, promise: nil, channelWritable: true).assertNothing() + ) - XCTAssertNoThrow(try buffer.processOutboundFrame(secondHeaders, promise: nil, channelWritable: true).assertNothing()) - XCTAssertNoThrow(try buffer.processOutboundFrame(secondData, promise: nil, channelWritable: true).assertNothing()) + XCTAssertNoThrow( + try buffer.processOutboundFrame(secondHeaders, promise: nil, channelWritable: true).assertNothing() + ) + XCTAssertNoThrow( + try buffer.processOutboundFrame(secondData, promise: nil, channelWritable: true).assertNothing() + ) // Now mark them flushed. buffer.flushReceived() @@ -302,20 +347,30 @@ final class CompoundOutboundBufferTest: XCTestCase { let startPromise = self.loop.makePromise(of: Void.self) let dataPromise = self.loop.makePromise(of: Void.self) if streamID == 1 { - XCTAssertNoThrow(try buffer.processOutboundFrame(startFrame, promise: startPromise, channelWritable: true).assertForward()) + XCTAssertNoThrow( + try buffer.processOutboundFrame(startFrame, promise: startPromise, channelWritable: true) + .assertForward() + ) startPromise.succeed(()) buffer.streamCreated(streamID, initialWindowSize: 65535) } else { - XCTAssertNoThrow(try buffer.processOutboundFrame(startFrame, promise: startPromise, channelWritable: true).assertNothing()) + XCTAssertNoThrow( + try buffer.processOutboundFrame(startFrame, promise: startPromise, channelWritable: true) + .assertNothing() + ) } - XCTAssertNoThrow(try buffer.processOutboundFrame(dataFrame, promise: dataPromise, channelWritable: true).assertNothing()) + XCTAssertNoThrow( + try buffer.processOutboundFrame(dataFrame, promise: dataPromise, channelWritable: true).assertNothing() + ) futures.append(contentsOf: [startPromise.futureResult, dataPromise.futureResult]) } let pingFrame = HTTP2Frame(streamID: .rootStream, payload: .ping(.init(withInteger: 0), ack: false)) let pingPromise = self.loop.makePromise(of: Void.self) - XCTAssertNoThrow(try buffer.processOutboundFrame(pingFrame, promise: pingPromise, channelWritable: false).assertNothing()) + XCTAssertNoThrow( + try buffer.processOutboundFrame(pingFrame, promise: pingPromise, channelWritable: false).assertNothing() + ) futures.append(pingPromise.futureResult) for (idx, future) in futures.enumerated() { @@ -349,16 +404,22 @@ final class CompoundOutboundBufferTest: XCTestCase { // Send a HEADERS frame through to open up a space in the flow control buffer. let startFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: HPACKHeaders()))) - XCTAssertNoThrow(try buffer.processOutboundFrame(startFrame, promise: nil, channelWritable: true).assertForward()) + XCTAssertNoThrow( + try buffer.processOutboundFrame(startFrame, promise: nil, channelWritable: true).assertForward() + ) buffer.streamCreated(1, initialWindowSize: 65535) // Send a DATA frame. This is buffered. let dataFrame = self.createDataFrame(1, byteBufferSize: 50) - XCTAssertNoThrow(try buffer.processOutboundFrame(dataFrame, promise: nil, channelWritable: true).assertNothing()) + XCTAssertNoThrow( + try buffer.processOutboundFrame(dataFrame, promise: nil, channelWritable: true).assertNothing() + ) // Send in a PING frame which will be buffered. let pingFrame = HTTP2Frame(streamID: .rootStream, payload: .ping(.init(withInteger: 9), ack: false)) - XCTAssertNoThrow(try buffer.processOutboundFrame(pingFrame, promise: nil, channelWritable: false).assertNothing()) + XCTAssertNoThrow( + try buffer.processOutboundFrame(pingFrame, promise: nil, channelWritable: false).assertNothing() + ) buffer.flushReceived() @@ -377,7 +438,6 @@ final class CompoundOutboundBufferTest: XCTestCase { } } - extension CompoundOutboundBufferTest { func createDataFrame(_ streamID: HTTP2StreamID, byteBufferSize: Int) -> HTTP2Frame { var buffer = ByteBufferAllocator().buffer(capacity: byteBufferSize) @@ -390,18 +450,18 @@ extension CompoundOutboundBuffer { fileprivate mutating func receivedFrames(file: StaticString = #filePath, line: UInt = #line) -> [HTTP2Frame] { var receivedFrames: [HTTP2Frame] = Array() - loop: while true { - switch self.nextFlushedWritableFrame(channelWritable: true) { - case .noFrame: - break loop - case .frame(let bufferedFrame, let promise): - receivedFrames.append(bufferedFrame) - promise?.succeed(()) - case .error(let promise, let error): - promise?.fail(error) - XCTFail("Caught error: \(error)", file: (file), line: line) + loop: while true { + switch self.nextFlushedWritableFrame(channelWritable: true) { + case .noFrame: + break loop + case .frame(let bufferedFrame, let promise): + receivedFrames.append(bufferedFrame) + promise?.succeed(()) + case .error(let promise, let error): + promise?.fail(error) + XCTFail("Caught error: \(error)", file: (file), line: line) + } } - } return receivedFrames } @@ -415,7 +475,11 @@ extension CompoundOutboundBuffer.FlushedWritableFrameResult { } } - internal func assertError(_ error: ErrorType, file: StaticString = #filePath, line: UInt = #line) { + internal func assertError( + _ error: ErrorType, + file: StaticString = #filePath, + line: UInt = #line + ) { guard case .error(let promise, let thrownError) = self else { XCTFail("Expected .error, got \(self)", file: (file), line: line) return diff --git a/Tests/NIOHTTP2Tests/ConcurrentStreamBufferTest.swift b/Tests/NIOHTTP2Tests/ConcurrentStreamBufferTest.swift index 95e21f1..743945e 100644 --- a/Tests/NIOHTTP2Tests/ConcurrentStreamBufferTest.swift +++ b/Tests/NIOHTTP2Tests/ConcurrentStreamBufferTest.swift @@ -12,15 +12,15 @@ // //===----------------------------------------------------------------------===// -import XCTest import NIOConcurrencyHelpers import NIOCore import NIOEmbedded import NIOHPACK +import XCTest + @testable import NIOHTTP2 -struct TestCaseError: Error { } - +struct TestCaseError: Error {} // MARK: Helper assertions for outbound frame actions. // We need these to work around the fact that neither EventLoopPromise or MarkedCircularBuffer have equatable @@ -40,7 +40,10 @@ extension OutboundFrameAction { } } - internal func assertForwardAndDrop(file: StaticString = #filePath, line: UInt = #line) throws -> (MarkedCircularBuffer<(HTTP2Frame, EventLoopPromise?)>, NIOHTTP2Errors.StreamClosed) { + internal func assertForwardAndDrop( + file: StaticString = #filePath, + line: UInt = #line + ) throws -> (MarkedCircularBuffer<(HTTP2Frame, EventLoopPromise?)>, NIOHTTP2Errors.StreamClosed) { guard case .forwardAndDrop(let promises, let error) = self else { XCTFail("Expected .forwardAndDrop, got \(self)", file: (file), line: line) throw TestCaseError() @@ -49,7 +52,10 @@ extension OutboundFrameAction { return (promises, error) } - internal func assertSucceedAndDrop(file: StaticString = #filePath, line: UInt = #line) throws -> (MarkedCircularBuffer<(HTTP2Frame, EventLoopPromise?)>, NIOHTTP2Errors.StreamClosed) { + internal func assertSucceedAndDrop( + file: StaticString = #filePath, + line: UInt = #line + ) throws -> (MarkedCircularBuffer<(HTTP2Frame, EventLoopPromise?)>, NIOHTTP2Errors.StreamClosed) { guard case .succeedAndDrop(let promises, let error) = self else { XCTFail("Expected .succeedAndDrop, got \(self)", file: (file), line: line) throw TestCaseError() @@ -59,7 +65,6 @@ extension OutboundFrameAction { } } - final class ConcurrentStreamBufferTests: XCTestCase { var loop: EmbeddedEventLoop! @@ -76,14 +81,18 @@ final class ConcurrentStreamBufferTests: XCTestCase { var manager = ConcurrentStreamBuffer(mode: .client, initialMaxOutboundStreams: 2) // Write frames for three streams. - let frames = stride(from: 1, through: 5, by: 2).map { HTTP2Frame(streamID: HTTP2StreamID($0), payload: .headers(.init(headers: HPACKHeaders([])))) } - let results: [OutboundFrameAction] = try assertNoThrowWithValue(frames.map { - let result = try manager.processOutboundFrame($0, promise: nil, channelWritable: true) - if case .forward = result { - manager.streamCreated($0.streamID) + let frames = stride(from: 1, through: 5, by: 2).map { + HTTP2Frame(streamID: HTTP2StreamID($0), payload: .headers(.init(headers: HPACKHeaders([])))) + } + let results: [OutboundFrameAction] = try assertNoThrowWithValue( + frames.map { + let result = try manager.processOutboundFrame($0, promise: nil, channelWritable: true) + if case .forward = result { + manager.streamCreated($0.streamID) + } + return result } - return result - }) + ) // Only two of these should have been passed through. results[0].assertForward() @@ -113,14 +122,18 @@ final class ConcurrentStreamBufferTests: XCTestCase { var manager = ConcurrentStreamBuffer(mode: .client, initialMaxOutboundStreams: 2) // Write frames for three streams and flush them. - let frames = stride(from: 1, through: 5, by: 2).map { HTTP2Frame(streamID: HTTP2StreamID($0), payload: .headers(.init(headers: HPACKHeaders([])))) } - let results: [OutboundFrameAction] = try assertNoThrowWithValue(frames.map { - let result = try manager.processOutboundFrame($0, promise: nil, channelWritable: true) - if case .forward = result { - manager.streamCreated($0.streamID) + let frames = stride(from: 1, through: 5, by: 2).map { + HTTP2Frame(streamID: HTTP2StreamID($0), payload: .headers(.init(headers: HPACKHeaders([])))) + } + let results: [OutboundFrameAction] = try assertNoThrowWithValue( + frames.map { + let result = try manager.processOutboundFrame($0, promise: nil, channelWritable: true) + if case .forward = result { + manager.streamCreated($0.streamID) + } + return result } - return result - }) + ) // Only two of these should have been passed through. results[0].assertForward() @@ -138,8 +151,13 @@ final class ConcurrentStreamBufferTests: XCTestCase { XCTAssertNil(manager.nextFlushedWritableFrame()) // Write a new stream. This should be buffered. - let newStreamFrame = HTTP2Frame(streamID: 7, payload: .headers(.init(headers: HPACKHeaders([]), endStream: true))) - XCTAssertNoThrow(try manager.processOutboundFrame(newStreamFrame, promise: nil, channelWritable: true).assertNothing()) + let newStreamFrame = HTTP2Frame( + streamID: 7, + payload: .headers(.init(headers: HPACKHeaders([]), endStream: true)) + ) + XCTAssertNoThrow( + try manager.processOutboundFrame(newStreamFrame, promise: nil, channelWritable: true).assertNothing() + ) XCTAssertNil(manager.nextFlushedWritableFrame()) // Complete stream 1. Nothing should happen, as only one stream is allowed through. @@ -167,14 +185,21 @@ final class ConcurrentStreamBufferTests: XCTestCase { let firstFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: HPACKHeaders([])))) let subsequentFrames: [HTTP2Frame] = stride(from: 3, to: 201, by: 2).map { streamID in - HTTP2Frame(streamID: HTTP2StreamID(streamID), payload: .headers(.init(headers: HPACKHeaders([]), endStream: true))) + HTTP2Frame( + streamID: HTTP2StreamID(streamID), + payload: .headers(.init(headers: HPACKHeaders([]), endStream: true)) + ) } // Write the first frame, and all the subsequent frames, and flush them. This will lead to one flushed frame. - XCTAssertNoThrow(try manager.processOutboundFrame(firstFrame, promise: nil, channelWritable: true).assertForward()) + XCTAssertNoThrow( + try manager.processOutboundFrame(firstFrame, promise: nil, channelWritable: true).assertForward() + ) manager.streamCreated(1) for frame in subsequentFrames { - XCTAssertNoThrow(try manager.processOutboundFrame(frame, promise: nil, channelWritable: true).assertNothing()) + XCTAssertNoThrow( + try manager.processOutboundFrame(frame, promise: nil, channelWritable: true).assertNothing() + ) } manager.flushReceived() XCTAssertNil(manager.nextFlushedWritableFrame()) @@ -198,13 +223,28 @@ final class ConcurrentStreamBufferTests: XCTestCase { // We're going to start stream 1, and then arrange a buffer of a bunch of frames in stream 3. We'll flush some, but not all of them let firstFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: HPACKHeaders([])))) - let subsequentFrame = HTTP2Frame(streamID: 3, payload: .data(.init(data: .byteBuffer(ByteBufferAllocator().buffer(capacity: 0))))) - XCTAssertNoThrow(try manager.processOutboundFrame(firstFrame, promise: nil, channelWritable: true).assertForward()) + let subsequentFrame = HTTP2Frame( + streamID: 3, + payload: .data(.init(data: .byteBuffer(ByteBufferAllocator().buffer(capacity: 0)))) + ) + XCTAssertNoThrow( + try manager.processOutboundFrame(firstFrame, promise: nil, channelWritable: true).assertForward() + ) manager.streamCreated(1) - XCTAssertNoThrow(try (0..<15).forEach { _ in XCTAssertNoThrow(try manager.processOutboundFrame(subsequentFrame, promise: nil, channelWritable: true).assertNothing()) }) + for _ in 0..<15 { + XCTAssertNoThrow( + try manager.processOutboundFrame(subsequentFrame, promise: nil, channelWritable: true) + .assertNothing() + ) + } manager.flushReceived() - XCTAssertNoThrow(try (0..<15).forEach { _ in XCTAssertNoThrow(try manager.processOutboundFrame(subsequentFrame, promise: nil, channelWritable: true).assertNothing()) }) + for _ in 0..<15 { + XCTAssertNoThrow( + try manager.processOutboundFrame(subsequentFrame, promise: nil, channelWritable: true) + .assertNothing() + ) + } XCTAssertNil(manager.nextFlushedWritableFrame()) @@ -233,23 +273,39 @@ final class ConcurrentStreamBufferTests: XCTestCase { // We're going to start stream 1, and then arrange a buffer of a bunch of frames in stream 3. We'll flush some, but not all of them let firstFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: HPACKHeaders([])))) - let subsequentFrame = HTTP2Frame(streamID: 3, payload: .data(.init(data: .byteBuffer(ByteBufferAllocator().buffer(capacity: 0))))) - XCTAssertNoThrow(try manager.processOutboundFrame(firstFrame, promise: nil, channelWritable: true).assertForward()) + let subsequentFrame = HTTP2Frame( + streamID: 3, + payload: .data(.init(data: .byteBuffer(ByteBufferAllocator().buffer(capacity: 0)))) + ) + XCTAssertNoThrow( + try manager.processOutboundFrame(firstFrame, promise: nil, channelWritable: true).assertForward() + ) manager.streamCreated(1) let writeStatus = NIOLockedValueBox<[Bool?]>(Array(repeating: nil, count: 30)) - var writePromises: [EventLoopFuture] = try assertNoThrowWithValue((0..<15).map { _ in - let p = self.loop.makePromise(of: Void.self) - XCTAssertNoThrow(try manager.processOutboundFrame(subsequentFrame, promise: p, channelWritable: true).assertNothing()) - return p.futureResult - }) + var writePromises: [EventLoopFuture] = try assertNoThrowWithValue( + (0..<15).map { _ in + let p = self.loop.makePromise(of: Void.self) + XCTAssertNoThrow( + try manager.processOutboundFrame(subsequentFrame, promise: p, channelWritable: true).assertNothing() + ) + return p.futureResult + } + ) manager.flushReceived() - XCTAssertNoThrow(try writePromises.append(contentsOf: (0..<15).map { _ in - let p = self.loop.makePromise(of: Void.self) - XCTAssertNoThrow(try manager.processOutboundFrame(subsequentFrame, promise: p, channelWritable: true).assertNothing()) - return p.futureResult - })) + XCTAssertNoThrow( + try writePromises.append( + contentsOf: (0..<15).map { _ in + let p = self.loop.makePromise(of: Void.self) + XCTAssertNoThrow( + try manager.processOutboundFrame(subsequentFrame, promise: p, channelWritable: true) + .assertNothing() + ) + return p.futureResult + } + ) + ) for (idx, promise) in writePromises.enumerated() { promise.map { @@ -257,7 +313,10 @@ final class ConcurrentStreamBufferTests: XCTestCase { writeStatus[idx] = true } }.whenFailure { error in - XCTAssertEqual(error as? NIOHTTP2Errors.StreamClosed, NIOHTTP2Errors.streamClosed(streamID: 3, errorCode: .cancel)) + XCTAssertEqual( + error as? NIOHTTP2Errors.StreamClosed, + NIOHTTP2Errors.streamClosed(streamID: 3, errorCode: .cancel) + ) writeStatus.withLockedValue { writeStatus in writeStatus[idx] = false } @@ -280,12 +339,17 @@ final class ConcurrentStreamBufferTests: XCTestCase { // Only the first 15 are done. writeStatus.withLockedValue { writeStatus in - XCTAssertEqual(writeStatus, Array(repeating: true as Bool?, count: 15) + Array(repeating: nil as Bool?, count: 15)) + XCTAssertEqual( + writeStatus, + Array(repeating: true as Bool?, count: 15) + Array(repeating: nil as Bool?, count: 15) + ) } // Now we're going to write a RST_STREAM frame on stream 3 let rstStreamFrame = HTTP2Frame(streamID: 3, payload: .rstStream(.cancel)) - let (droppedWrites, error) = try assertNoThrowWithValue(manager.processOutboundFrame(rstStreamFrame, promise: nil, channelWritable: true).assertForwardAndDrop()) + let (droppedWrites, error) = try assertNoThrowWithValue( + manager.processOutboundFrame(rstStreamFrame, promise: nil, channelWritable: true).assertForwardAndDrop() + ) // Fail all these writes. for write in droppedWrites { @@ -294,7 +358,10 @@ final class ConcurrentStreamBufferTests: XCTestCase { XCTAssertEqual(error, NIOHTTP2Errors.streamClosed(streamID: 3, errorCode: .cancel)) writeStatus.withLockedValue { writeStatus in - XCTAssertEqual(writeStatus, Array(repeating: true as Bool?, count: 15) + Array(repeating: false as Bool?, count: 15)) + XCTAssertEqual( + writeStatus, + Array(repeating: true as Bool?, count: 15) + Array(repeating: false as Bool?, count: 15) + ) } } @@ -303,17 +370,26 @@ final class ConcurrentStreamBufferTests: XCTestCase { // We're going to start stream 1, and then arrange a buffer of a bunch of frames in stream 3. We won't flush stream 3. let firstFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: HPACKHeaders([])))) - let subsequentFrame = HTTP2Frame(streamID: 3, payload: .data(.init(data: .byteBuffer(ByteBufferAllocator().buffer(capacity: 0))))) - XCTAssertNoThrow(try manager.processOutboundFrame(firstFrame, promise: nil, channelWritable: true).assertForward()) + let subsequentFrame = HTTP2Frame( + streamID: 3, + payload: .data(.init(data: .byteBuffer(ByteBufferAllocator().buffer(capacity: 0)))) + ) + XCTAssertNoThrow( + try manager.processOutboundFrame(firstFrame, promise: nil, channelWritable: true).assertForward() + ) manager.streamCreated(1) let writeStatus = NIOLockedValueBox<[Bool?]>(Array(repeating: nil, count: 15)) - let writePromises: [EventLoopFuture] = try assertNoThrowWithValue((0..<15).map { _ in - let p = self.loop.makePromise(of: Void.self) - XCTAssertNoThrow(try manager.processOutboundFrame(subsequentFrame, promise: p, channelWritable: true).assertNothing()) - return p.futureResult - }) + let writePromises: [EventLoopFuture] = try assertNoThrowWithValue( + (0..<15).map { _ in + let p = self.loop.makePromise(of: Void.self) + XCTAssertNoThrow( + try manager.processOutboundFrame(subsequentFrame, promise: p, channelWritable: true).assertNothing() + ) + return p.futureResult + } + ) for (idx, promise) in writePromises.enumerated() { promise.map { @@ -321,7 +397,10 @@ final class ConcurrentStreamBufferTests: XCTestCase { writeStatus[idx] = true } }.whenFailure { error in - XCTAssertEqual(error as? NIOHTTP2Errors.StreamClosed, NIOHTTP2Errors.streamClosed(streamID: 3, errorCode: .cancel)) + XCTAssertEqual( + error as? NIOHTTP2Errors.StreamClosed, + NIOHTTP2Errors.streamClosed(streamID: 3, errorCode: .cancel) + ) writeStatus.withLockedValue { writeStatus in writeStatus[idx] = false } @@ -336,7 +415,9 @@ final class ConcurrentStreamBufferTests: XCTestCase { // Now we're going to send RST_STREAM on 3. All writes should fail, and we should be asked to drop the RST_STREAM frame. let rstStreamFrame = HTTP2Frame(streamID: 3, payload: .rstStream(.cancel)) - let (droppedWrites, error) = try assertNoThrowWithValue(manager.processOutboundFrame(rstStreamFrame, promise: nil, channelWritable: true).assertSucceedAndDrop()) + let (droppedWrites, error) = try assertNoThrowWithValue( + manager.processOutboundFrame(rstStreamFrame, promise: nil, channelWritable: true).assertSucceedAndDrop() + ) // Fail all these writes. for write in droppedWrites { @@ -358,14 +439,19 @@ final class ConcurrentStreamBufferTests: XCTestCase { // We're going to create stream 1 and stream 11. Stream 1 will be passed through, stream 11 will have to wait. let oneFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: HPACKHeaders([])))) let elevenFrame = HTTP2Frame(streamID: 11, payload: .headers(.init(headers: HPACKHeaders([])))) - XCTAssertNoThrow(try manager.processOutboundFrame(oneFrame, promise: nil, channelWritable: true).assertForward()) + XCTAssertNoThrow( + try manager.processOutboundFrame(oneFrame, promise: nil, channelWritable: true).assertForward() + ) manager.streamCreated(1) - XCTAssertNoThrow(try manager.processOutboundFrame(elevenFrame, promise: nil, channelWritable: true).assertNothing()) + XCTAssertNoThrow( + try manager.processOutboundFrame(elevenFrame, promise: nil, channelWritable: true).assertNothing() + ) // Now we're going to try to write a frame for stream 5. This will fail. let fiveFrame = HTTP2Frame(streamID: 5, payload: .headers(.init(headers: HPACKHeaders([])))) - XCTAssertThrowsError(try manager.processOutboundFrame(fiveFrame, promise: nil, channelWritable: true)) { error in + XCTAssertThrowsError(try manager.processOutboundFrame(fiveFrame, promise: nil, channelWritable: true)) { + error in XCTAssertTrue(error is NIOHTTP2Errors.StreamIDTooSmall) } } @@ -376,13 +462,19 @@ final class ConcurrentStreamBufferTests: XCTestCase { // We're going to create stream 1 and stream 3, which will be buffered. let oneFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: HPACKHeaders([])))) let threeFrame = HTTP2Frame(streamID: 3, payload: .headers(.init(headers: HPACKHeaders([])))) - XCTAssertNoThrow(try manager.processOutboundFrame(oneFrame, promise: nil, channelWritable: true).assertForward()) + XCTAssertNoThrow( + try manager.processOutboundFrame(oneFrame, promise: nil, channelWritable: true).assertForward() + ) manager.streamCreated(1) - XCTAssertNoThrow(try manager.processOutboundFrame(threeFrame, promise: nil, channelWritable: true).assertNothing()) + XCTAssertNoThrow( + try manager.processOutboundFrame(threeFrame, promise: nil, channelWritable: true).assertNothing() + ) // Now we're going to try to write a frame for stream 4, a server-initiated stream. This will be passed through safely. let fourFrame = HTTP2Frame(streamID: 4, payload: .headers(.init(headers: HPACKHeaders([])))) - XCTAssertNoThrow(try manager.processOutboundFrame(fourFrame, promise: nil, channelWritable: true).assertForward()) + XCTAssertNoThrow( + try manager.processOutboundFrame(fourFrame, promise: nil, channelWritable: true).assertForward() + ) manager.streamCreated(4) XCTAssertEqual(manager.currentOutboundStreams, 1) @@ -394,21 +486,37 @@ final class ConcurrentStreamBufferTests: XCTestCase { // We're going to create stream 2 and stream 4. First, however, we reserve them. These are not buffered, per RFC 7540 ยง 5.1.2: // // > Streams in either of the "reserved" states do not count toward the stream limit. - let twoFramePromise = HTTP2Frame(streamID: 1, payload: .pushPromise(.init(pushedStreamID: 2, headers: HPACKHeaders([])))) - let fourFramePromise = HTTP2Frame(streamID: 1, payload: .pushPromise(.init(pushedStreamID: 4, headers: HPACKHeaders([])))) - XCTAssertNoThrow(try manager.processOutboundFrame(twoFramePromise, promise: nil, channelWritable: true).assertForward()) - XCTAssertNoThrow(try manager.processOutboundFrame(fourFramePromise, promise: nil, channelWritable: true).assertForward()) + let twoFramePromise = HTTP2Frame( + streamID: 1, + payload: .pushPromise(.init(pushedStreamID: 2, headers: HPACKHeaders([]))) + ) + let fourFramePromise = HTTP2Frame( + streamID: 1, + payload: .pushPromise(.init(pushedStreamID: 4, headers: HPACKHeaders([]))) + ) + XCTAssertNoThrow( + try manager.processOutboundFrame(twoFramePromise, promise: nil, channelWritable: true).assertForward() + ) + XCTAssertNoThrow( + try manager.processOutboundFrame(fourFramePromise, promise: nil, channelWritable: true).assertForward() + ) // Now we're going to try to initiate these by sending HEADERS frames. This will buffer the second one. let twoFrame = HTTP2Frame(streamID: 2, payload: .headers(.init(headers: HPACKHeaders([])))) let fourFrame = HTTP2Frame(streamID: 4, payload: .headers(.init(headers: HPACKHeaders([])))) - XCTAssertNoThrow(try manager.processOutboundFrame(twoFrame, promise: nil, channelWritable: true).assertForward()) + XCTAssertNoThrow( + try manager.processOutboundFrame(twoFrame, promise: nil, channelWritable: true).assertForward() + ) manager.streamCreated(2) - XCTAssertNoThrow(try manager.processOutboundFrame(fourFrame, promise: nil, channelWritable: true).assertNothing()) + XCTAssertNoThrow( + try manager.processOutboundFrame(fourFrame, promise: nil, channelWritable: true).assertNothing() + ) // Now we're going to try to write a frame for stream 3, a client-initiated stream. This will be passed through safely. let threeFrame = HTTP2Frame(streamID: 3, payload: .headers(.init(headers: HPACKHeaders([])))) - XCTAssertNoThrow(try manager.processOutboundFrame(threeFrame, promise: nil, channelWritable: true).assertForward()) + XCTAssertNoThrow( + try manager.processOutboundFrame(threeFrame, promise: nil, channelWritable: true).assertForward() + ) manager.streamCreated(3) XCTAssertEqual(manager.currentOutboundStreams, 1) @@ -420,23 +528,35 @@ final class ConcurrentStreamBufferTests: XCTestCase { // We're going to start stream 1, and then arrange a buffer of a bunch of frames in stream 3. let firstFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: HPACKHeaders([])))) - let subsequentFrame = HTTP2Frame(streamID: 3, payload: .data(.init(data: .byteBuffer(ByteBufferAllocator().buffer(capacity: 0))))) - XCTAssertNoThrow(try manager.processOutboundFrame(firstFrame, promise: nil, channelWritable: true).assertForward()) + let subsequentFrame = HTTP2Frame( + streamID: 3, + payload: .data(.init(data: .byteBuffer(ByteBufferAllocator().buffer(capacity: 0)))) + ) + XCTAssertNoThrow( + try manager.processOutboundFrame(firstFrame, promise: nil, channelWritable: true).assertForward() + ) manager.streamCreated(1) let writeStatus = NIOLockedValueBox<[Bool?]>(Array(repeating: nil, count: 15)) - let writePromises: [EventLoopFuture] = try assertNoThrowWithValue((0..<15).map { _ in - let p = self.loop.makePromise(of: Void.self) - XCTAssertNoThrow(try manager.processOutboundFrame(subsequentFrame, promise: p, channelWritable: true).assertNothing()) - return p.futureResult - }) + let writePromises: [EventLoopFuture] = try assertNoThrowWithValue( + (0..<15).map { _ in + let p = self.loop.makePromise(of: Void.self) + XCTAssertNoThrow( + try manager.processOutboundFrame(subsequentFrame, promise: p, channelWritable: true).assertNothing() + ) + return p.futureResult + } + ) for (idx, promise) in writePromises.enumerated() { promise.map { writeStatus.withLockedValue { writeStatus in writeStatus[idx] = true } }.whenFailure { error in - XCTAssertEqual(error as? NIOHTTP2Errors.StreamClosed, NIOHTTP2Errors.streamClosed(streamID: 3, errorCode: .protocolError)) + XCTAssertEqual( + error as? NIOHTTP2Errors.StreamClosed, + NIOHTTP2Errors.streamClosed(streamID: 3, errorCode: .protocolError) + ) writeStatus.withLockedValue { writeStatus in writeStatus[idx] = false } @@ -470,11 +590,15 @@ final class ConcurrentStreamBufferTests: XCTestCase { // Write a frame for the first stream. This will be buffered, as the connection isn't writable. let firstFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: HPACKHeaders()))) - XCTAssertNoThrow(try manager.processOutboundFrame(firstFrame, promise: nil, channelWritable: false).assertNothing()) + XCTAssertNoThrow( + try manager.processOutboundFrame(firstFrame, promise: nil, channelWritable: false).assertNothing() + ) // Write a frame for the second stream. This should also be buffered, as the connection still isn't writable. let secondFrame = HTTP2Frame(streamID: 3, payload: .headers(.init(headers: HPACKHeaders()))) - XCTAssertNoThrow(try manager.processOutboundFrame(secondFrame, promise: nil, channelWritable: false).assertNothing()) + XCTAssertNoThrow( + try manager.processOutboundFrame(secondFrame, promise: nil, channelWritable: false).assertNothing() + ) manager.flushReceived() @@ -488,18 +612,35 @@ final class ConcurrentStreamBufferTests: XCTestCase { // Now write a frame for stream 5. Even though the connection is writable, this should be buffered. let thirdFrame = HTTP2Frame(streamID: 5, payload: .headers(.init(headers: HPACKHeaders()))) - XCTAssertNoThrow(try manager.processOutboundFrame(thirdFrame, promise: nil, channelWritable: true).assertNothing()) + XCTAssertNoThrow( + try manager.processOutboundFrame(thirdFrame, promise: nil, channelWritable: true).assertNothing() + ) // Now we're going to try to write data once to each stream, simulating the channel being blocked. Stream 1 should // progress, as the stream is actually open, while the writes for stream 3 and 5 should be buffered. - let fourthFrame = HTTP2Frame(streamID: 1, payload: .data(.init(data: .byteBuffer(ByteBufferAllocator().buffer(capacity: 0))))) - XCTAssertNoThrow(try manager.processOutboundFrame(fourthFrame, promise: nil, channelWritable: true).assertForward()) + let fourthFrame = HTTP2Frame( + streamID: 1, + payload: .data(.init(data: .byteBuffer(ByteBufferAllocator().buffer(capacity: 0)))) + ) + XCTAssertNoThrow( + try manager.processOutboundFrame(fourthFrame, promise: nil, channelWritable: true).assertForward() + ) - let fifthFrame = HTTP2Frame(streamID: 3, payload: .data(.init(data: .byteBuffer(ByteBufferAllocator().buffer(capacity: 0))))) - XCTAssertNoThrow(try manager.processOutboundFrame(fifthFrame, promise: nil, channelWritable: true).assertNothing()) + let fifthFrame = HTTP2Frame( + streamID: 3, + payload: .data(.init(data: .byteBuffer(ByteBufferAllocator().buffer(capacity: 0)))) + ) + XCTAssertNoThrow( + try manager.processOutboundFrame(fifthFrame, promise: nil, channelWritable: true).assertNothing() + ) - let sixthFrame = HTTP2Frame(streamID: 5, payload: .data(.init(data: .byteBuffer(ByteBufferAllocator().buffer(capacity: 0))))) - XCTAssertNoThrow(try manager.processOutboundFrame(sixthFrame, promise: nil, channelWritable: true).assertNothing()) + let sixthFrame = HTTP2Frame( + streamID: 5, + payload: .data(.init(data: .byteBuffer(ByteBufferAllocator().buffer(capacity: 0)))) + ) + XCTAssertNoThrow( + try manager.processOutboundFrame(sixthFrame, promise: nil, channelWritable: true).assertNothing() + ) manager.flushReceived() diff --git a/Tests/NIOHTTP2Tests/ConfiguringPipelineAsyncMultiplexerTests.swift b/Tests/NIOHTTP2Tests/ConfiguringPipelineAsyncMultiplexerTests.swift index 8aa3385..6243716 100644 --- a/Tests/NIOHTTP2Tests/ConfiguringPipelineAsyncMultiplexerTests.swift +++ b/Tests/NIOHTTP2Tests/ConfiguringPipelineAsyncMultiplexerTests.swift @@ -12,8 +12,6 @@ // //===----------------------------------------------------------------------===// -import XCTest - import NIOConcurrencyHelpers import NIOCore import NIOEmbedded @@ -21,6 +19,7 @@ import NIOHPACK import NIOHTTP1 import NIOHTTP2 import NIOTLS +import XCTest @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) final class ConfiguringPipelineAsyncMultiplexerTests: XCTestCase { @@ -37,11 +36,24 @@ final class ConfiguringPipelineAsyncMultiplexerTests: XCTestCase { self.serverChannel = nil } - static let requestFramePayload = HTTP2Frame.FramePayload.headers(.init(headers: HPACKHeaders([(":method", "GET"), (":authority", "localhost"), (":scheme", "https"), (":path", "/")]), endStream: true)) - static let responseFramePayload = HTTP2Frame.FramePayload.headers(.init(headers: HPACKHeaders([(":status", "200")]), endStream: true)) + static let requestFramePayload = HTTP2Frame.FramePayload.headers( + .init( + headers: HPACKHeaders([ + (":method", "GET"), (":authority", "localhost"), (":scheme", "https"), (":path", "/"), + ]), + endStream: true + ) + ) + static let responseFramePayload = HTTP2Frame.FramePayload.headers( + .init(headers: HPACKHeaders([(":status", "200")]), endStream: true) + ) static let requestHead = HTTPRequestHead(version: .init(major: 1, minor: 1), method: .GET, uri: "/testHTTP1") - static let responseHead = HTTPResponseHead(version: .init(major: 1, minor: 1), status: .ok, headers: HTTPHeaders([("transfer-encoding", "chunked")])) + static let responseHead = HTTPResponseHead( + version: .init(major: 1, minor: 1), + status: .ok, + headers: HTTPHeaders([("transfer-encoding", "chunked")]) + ) final class OKResponder: ChannelInboundHandler { typealias InboundIn = HTTP2Frame.FramePayload @@ -98,18 +110,22 @@ final class ConfiguringPipelineAsyncMultiplexerTests: XCTestCase { let serverRecorder = InboundFramePayloadRecorder() let clientMultiplexer = try await assertNoThrowWithValue( - try await self.clientChannel.configureAsyncHTTP2Pipeline(mode: .client) { channel -> EventLoopFuture in + try await self.clientChannel.configureAsyncHTTP2Pipeline(mode: .client) { + channel -> EventLoopFuture in channel.eventLoop.makeSucceededFuture(channel) }.get() ) let serverMultiplexer = try await assertNoThrowWithValue( - try await self.serverChannel.configureAsyncHTTP2Pipeline(mode: .server) { channel -> EventLoopFuture in + try await self.serverChannel.configureAsyncHTTP2Pipeline(mode: .server) { + channel -> EventLoopFuture in channel.pipeline.addHandlers([OKResponder(), serverRecorder]).map { _ in channel } }.get() ) - try await assertNoThrow(try await self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel)) + try await assertNoThrow( + try await self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel) + ) // Launch a server let serverTask = Task { @@ -124,11 +140,11 @@ final class ConfiguringPipelineAsyncMultiplexerTests: XCTestCase { } // client - for i in 0 ..< requestCount { + for i in 0.. EventLoopFuture in - return channel.pipeline.addHandlers([SimpleRequest(), InboundFramePayloadRecorder()]).map { - return channel + channel.pipeline.addHandlers([SimpleRequest(), InboundFramePayloadRecorder()]).map { + channel } } @@ -139,7 +155,9 @@ final class ConfiguringPipelineAsyncMultiplexerTests: XCTestCase { try await Self.deliverAllBytes(from: self.clientChannel, to: self.serverChannel) try await Self.deliverAllBytes(from: self.serverChannel, to: self.clientChannel) - clientRecorder.receivedFrames.assertFramePayloadsMatch([ConfiguringPipelineAsyncMultiplexerTests.responseFramePayload]) + clientRecorder.receivedFrames.assertFramePayloadsMatch([ + ConfiguringPipelineAsyncMultiplexerTests.responseFramePayload + ]) try await streamChannel.closeFuture.get() } @@ -164,18 +182,22 @@ final class ConfiguringPipelineAsyncMultiplexerTests: XCTestCase { let serverRecorder = InboundFramePayloadRecorder() let clientMultiplexer = try await assertNoThrowWithValue( - try await self.clientChannel.configureAsyncHTTP2Pipeline(mode: .client) { channel -> EventLoopFuture in + try await self.clientChannel.configureAsyncHTTP2Pipeline(mode: .client) { + channel -> EventLoopFuture in channel.eventLoop.makeSucceededFuture(channel) }.get() ) let serverMultiplexer = try await assertNoThrowWithValue( - try await self.serverChannel.configureAsyncHTTP2Pipeline(mode: .server) { channel -> EventLoopFuture in + try await self.serverChannel.configureAsyncHTTP2Pipeline(mode: .server) { + channel -> EventLoopFuture in channel.pipeline.addHandlers([OKResponder(), serverRecorder]).map { _ in channel } }.get() ) - try await assertNoThrow(try await self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel)) + try await assertNoThrow( + try await self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel) + ) try await withThrowingTaskGroup(of: Int.self, returning: Void.self) { group in // server @@ -188,18 +210,21 @@ final class ConfiguringPipelineAsyncMultiplexerTests: XCTestCase { } // client - for _ in 0 ..< requestCount { + for _ in 0.. EventLoopFuture in - return channel.pipeline.addHandlers([SimpleRequest(), InboundFramePayloadRecorder()]).map { - return channel + channel.pipeline.addHandlers([SimpleRequest(), InboundFramePayloadRecorder()]).map { + channel } } - let clientRecorder = try await streamChannel.pipeline.handler(type: InboundFramePayloadRecorder.self).get() + let clientRecorder = try await streamChannel.pipeline.handler(type: InboundFramePayloadRecorder.self) + .get() try await Self.deliverAllBytes(from: self.clientChannel, to: self.serverChannel) try await Self.deliverAllBytes(from: self.serverChannel, to: self.clientChannel) - clientRecorder.receivedFrames.assertFramePayloadsMatch([ConfiguringPipelineAsyncMultiplexerTests.responseFramePayload]) + clientRecorder.receivedFrames.assertFramePayloadsMatch([ + ConfiguringPipelineAsyncMultiplexerTests.responseFramePayload + ]) try await streamChannel.closeFuture.get() } @@ -207,10 +232,16 @@ final class ConfiguringPipelineAsyncMultiplexerTests: XCTestCase { try await assertNoThrow(try await self.serverChannel.finish()) let serverInboundChannelCount = try await assertNoThrowWithValue(try await group.next()!) - XCTAssertEqual(serverInboundChannelCount, requestCount, "We should have created one server-side channel as a result of the each HTTP/2 stream used.") + XCTAssertEqual( + serverInboundChannelCount, + requestCount, + "We should have created one server-side channel as a result of the each HTTP/2 stream used." + ) } - serverRecorder.receivedFrames.assertFramePayloadsMatch(Array(repeating: ConfiguringPipelineAsyncMultiplexerTests.requestFramePayload, count: requestCount)) + serverRecorder.receivedFrames.assertFramePayloadsMatch( + Array(repeating: ConfiguringPipelineAsyncMultiplexerTests.requestFramePayload, count: requestCount) + ) } // `testNIOAsyncConnectionStreamChannelPipelineCommunicates` ensures that a client-server system set up to use `NIOAsyncChannel` @@ -226,7 +257,10 @@ final class ConfiguringPipelineAsyncMultiplexerTests: XCTestCase { channel.eventLoop.makeCompletedFuture { try NIOAsyncChannel( synchronouslyWrapping: channel, - configuration: .init(inboundType: HTTP2Frame.FramePayload.self, outboundType: HTTP2Frame.FramePayload.self) + configuration: .init( + inboundType: HTTP2Frame.FramePayload.self, + outboundType: HTTP2Frame.FramePayload.self + ) ) } } @@ -239,13 +273,18 @@ final class ConfiguringPipelineAsyncMultiplexerTests: XCTestCase { channel.eventLoop.makeCompletedFuture { try NIOAsyncChannel( synchronouslyWrapping: channel, - configuration: .init(inboundType: HTTP2Frame.FramePayload.self, outboundType: HTTP2Frame.FramePayload.self) + configuration: .init( + inboundType: HTTP2Frame.FramePayload.self, + outboundType: HTTP2Frame.FramePayload.self + ) ) } } ) - try await assertNoThrow(try await self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel)) + try await assertNoThrow( + try await self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel) + ) let serverChannel = self.serverChannel! let clientChannel = self.clientChannel! @@ -256,9 +295,13 @@ final class ConfiguringPipelineAsyncMultiplexerTests: XCTestCase { var serverInboundChannelCount = 0 for try await streamChannel in serverMultiplexer.inbound { for try await receivedFrame in streamChannel.inbound { - receivedFrame.assertFramePayloadMatches(this: ConfiguringPipelineAsyncMultiplexerTests.requestFramePayload) + receivedFrame.assertFramePayloadMatches( + this: ConfiguringPipelineAsyncMultiplexerTests.requestFramePayload + ) - try await streamChannel.outbound.write(ConfiguringPipelineAsyncMultiplexerTests.responseFramePayload) + try await streamChannel.outbound.write( + ConfiguringPipelineAsyncMultiplexerTests.responseFramePayload + ) streamChannel.outbound.finish() try await Self.deliverAllBytes(from: serverChannel, to: clientChannel) @@ -269,8 +312,8 @@ final class ConfiguringPipelineAsyncMultiplexerTests: XCTestCase { } // client - for _ in 0 ..< requestCount { - let streamChannel = try await clientMultiplexer.openStream() { channel in + for _ in 0.. EventLoopFuture in + try await self.clientChannel.configureAsyncHTTP2Pipeline(mode: .client) { + channel -> EventLoopFuture in channel.eventLoop.makeSucceededFuture(channel) }.get() ) - let negotiationResultFuture = try await self.serverChannel.configureAsyncHTTPServerPipeline() { channel in + let negotiationResultFuture = try await self.serverChannel.configureAsyncHTTPServerPipeline { channel in channel.eventLoop.makeSucceededVoidFuture() } http2ConnectionInitializer: { channel in channel.eventLoop.makeSucceededVoidFuture() @@ -322,9 +372,13 @@ final class ConfiguringPipelineAsyncMultiplexerTests: XCTestCase { }.get() // Let's pretend the TLS handler did protocol negotiation for us - self.serverChannel.pipeline.fireUserInboundEventTriggered(TLSUserEvent.handshakeCompleted(negotiatedProtocol: "h2")) + self.serverChannel.pipeline.fireUserInboundEventTriggered( + TLSUserEvent.handshakeCompleted(negotiatedProtocol: "h2") + ) - try await assertNoThrow(try await self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel)) + try await assertNoThrow( + try await self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel) + ) try await withThrowingTaskGroup(of: Int.self, returning: Void.self) { group in // server @@ -346,20 +400,23 @@ final class ConfiguringPipelineAsyncMultiplexerTests: XCTestCase { } // client - for _ in 0 ..< requestCount { + for _ in 0.. EventLoopFuture in - return channel.pipeline.addHandlers([SimpleRequest(), InboundFramePayloadRecorder()]).map { - return channel + channel.pipeline.addHandlers([SimpleRequest(), InboundFramePayloadRecorder()]).map { + channel } } - let clientRecorder = try await streamChannel.pipeline.handler(type: InboundFramePayloadRecorder.self).get() + let clientRecorder = try await streamChannel.pipeline.handler(type: InboundFramePayloadRecorder.self) + .get() try await Self.deliverAllBytes(from: self.clientChannel, to: self.serverChannel) try await Self.deliverAllBytes(from: self.serverChannel, to: self.clientChannel) - clientRecorder.receivedFrames.assertFramePayloadsMatch([ConfiguringPipelineAsyncMultiplexerTests.responseFramePayload]) + clientRecorder.receivedFrames.assertFramePayloadsMatch([ + ConfiguringPipelineAsyncMultiplexerTests.responseFramePayload + ]) try await streamChannel.closeFuture.get() } @@ -367,10 +424,16 @@ final class ConfiguringPipelineAsyncMultiplexerTests: XCTestCase { try await assertNoThrow(try await self.serverChannel.finish()) let serverInboundChannelCount = try await assertNoThrowWithValue(try await group.next()!) - XCTAssertEqual(serverInboundChannelCount, requestCount, "We should have created one server-side channel as a result of the each HTTP/2 stream used.") + XCTAssertEqual( + serverInboundChannelCount, + requestCount, + "We should have created one server-side channel as a result of the each HTTP/2 stream used." + ) } - serverRecorder.receivedFrames.assertFramePayloadsMatch(Array(repeating: ConfiguringPipelineAsyncMultiplexerTests.requestFramePayload, count: requestCount)) + serverRecorder.receivedFrames.assertFramePayloadsMatch( + Array(repeating: ConfiguringPipelineAsyncMultiplexerTests.requestFramePayload, count: requestCount) + ) } // `testNegotiatedHTTP1BasicPipelineCommunicates` ensures that a client-server system set up to use async stream abstractions @@ -378,11 +441,14 @@ final class ConfiguringPipelineAsyncMultiplexerTests: XCTestCase { func testNegotiatedHTTP1BasicPipelineCommunicates() async throws { let requestCount = 100 - let _ = try await self.clientChannel.pipeline.addHTTPClientHandlers().map { [clientChannel = self.clientChannel!] _ in - clientChannel.pipeline.addHandlers([InboundRecorderHandler(), HTTP1ClientSendability()]) + let _ = try await self.clientChannel.pipeline.addHTTPClientHandlers().map { + [clientChannel = self.clientChannel!] _ in + clientChannel.pipeline.addHandlers([ + InboundRecorderHandler(), HTTP1ClientSendability(), + ]) }.get() - let negotiationResultFuture = try await self.serverChannel.configureAsyncHTTPServerPipeline() { channel in + let negotiationResultFuture = try await self.serverChannel.configureAsyncHTTPServerPipeline { channel in channel.pipeline.addHandlers([HTTP1OKResponder(), InboundRecorderHandler()]) } http2ConnectionInitializer: { channel in channel.eventLoop.makeSucceededVoidFuture() @@ -391,7 +457,9 @@ final class ConfiguringPipelineAsyncMultiplexerTests: XCTestCase { }.get() // Let's pretend the TLS handler did protocol negotiation for us - self.serverChannel.pipeline.fireUserInboundEventTriggered(TLSUserEvent.handshakeCompleted(negotiatedProtocol: "http/1.1")) + self.serverChannel.pipeline.fireUserInboundEventTriggered( + TLSUserEvent.handshakeCompleted(negotiatedProtocol: "http/1.1") + ) let negotiationResult = try await negotiationResultFuture.get() @@ -406,35 +474,57 @@ final class ConfiguringPipelineAsyncMultiplexerTests: XCTestCase { } // client - for _ in 0 ..< requestCount { + for _ in 0...self).get() - let serverRecorder = try await self.serverChannel.pipeline.handler(type: InboundRecorderHandler.self).get() + let clientRecorder = try await self.clientChannel.pipeline.handler( + type: InboundRecorderHandler.self + ).get() + let serverRecorder = try await self.serverChannel.pipeline.handler( + type: InboundRecorderHandler.self + ).get() serverRecorder.receivedParts.withLockedValue { receivedParts in - XCTAssertEqual(receivedParts.count, requestCount*2) + XCTAssertEqual(receivedParts.count, requestCount * 2) } clientRecorder.receivedParts.withLockedValue { receivedParts in - XCTAssertEqual(receivedParts.count, requestCount*2) + XCTAssertEqual(receivedParts.count, requestCount * 2) } - for i in 0 ..< requestCount { + for i in 0.. = self.clientChannel.eventLoop.makePromise() clientMultiplexer.createStreamChannel(promise: streamChannelPromise) { channel in - return channel.pipeline.addHandler(InactiveHandler(inactivePromise: inactivePromise)) + channel.pipeline.addHandler(InactiveHandler(inactivePromise: inactivePromise)) } (self.clientChannel.eventLoop as! EmbeddedEventLoop).run() @@ -340,11 +371,11 @@ class ConfiguringPipelineInlineMultiplexerTests: XCTestCase { clientChannel.eventLoop.makeSucceededVoidFuture() } ).wait() - _ = try self.serverChannel.configureHTTP2Pipeline( + _ = try self.serverChannel.configureHTTP2Pipeline( mode: .server, connectionConfiguration: .init(), streamConfiguration: .init(), - inboundStreamInitializer: { channel in channel.eventLoop.makeSucceededVoidFuture()} + inboundStreamInitializer: { channel in channel.eventLoop.makeSucceededVoidFuture() } ).wait() XCTAssertNoThrow(try self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel)) @@ -353,7 +384,7 @@ class ConfiguringPipelineInlineMultiplexerTests: XCTestCase { let streamChannelPromise: EventLoopPromise = self.clientChannel.eventLoop.makePromise() clientMultiplexer.createStreamChannel(promise: streamChannelPromise) { channel in - return channel.pipeline.addHandler(InactiveHandler(inactivePromise: inactivePromise)) + channel.pipeline.addHandler(InactiveHandler(inactivePromise: inactivePromise)) } (self.clientChannel.eventLoop as! EmbeddedEventLoop).run() @@ -402,23 +433,38 @@ class ConfiguringPipelineInlineMultiplexerTests: XCTestCase { } ).wait() - XCTAssertNoThrow(try self.serverChannel.configureCommonHTTPServerPipeline( - connectionConfiguration: .init(), - streamConfiguration: .init() - ) { channel in - channel.pipeline.addHandler(ErrorHandler()) - } configurator: { channel in - return channel.pipeline.addHandler(serverRecorder) - }.wait()) + XCTAssertNoThrow( + try self.serverChannel.configureCommonHTTPServerPipeline( + connectionConfiguration: .init(), + streamConfiguration: .init() + ) { channel in + channel.pipeline.addHandler(ErrorHandler()) + } configurator: { channel in + channel.pipeline.addHandler(serverRecorder) + }.wait() + ) // Let's pretend the TLS handler did protocol negotiation for us - self.serverChannel.pipeline.fireUserInboundEventTriggered (TLSUserEvent.handshakeCompleted(negotiatedProtocol: "h2")) + self.serverChannel.pipeline.fireUserInboundEventTriggered( + TLSUserEvent.handshakeCompleted(negotiatedProtocol: "h2") + ) XCTAssertNoThrow(try self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel)) // Let's try sending an h2 request. let requestPromise = self.clientChannel.eventLoop.makePromise(of: Void.self) - let reqFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: HPACKHeaders([(":method", "GET"), (":authority", "localhost"), (":scheme", "https"), (":path", "/testH2toHTTP1")]), endStream: true))) + let reqFrame = HTTP2Frame( + streamID: 1, + payload: .headers( + .init( + headers: HPACKHeaders([ + (":method", "GET"), (":authority", "localhost"), (":scheme", "https"), + (":path", "/testH2toHTTP1"), + ]), + endStream: true + ) + ) + ) clientMultiplexer.createStreamChannel(promise: nil) { channel in channel.writeAndFlush(reqFrame.payload).whenComplete { _ in channel.close(promise: requestPromise) } @@ -477,23 +523,38 @@ class ConfiguringPipelineInlineMultiplexerTests: XCTestCase { } ).wait() - XCTAssertNoThrow(try self.serverChannel.configureCommonHTTPServerPipeline( - connectionConfiguration: .init(), - streamConfiguration: .init() - ) { channel in - channel.pipeline.addHandler(ErrorHandler()) - } configurator: { channel in - return channel.pipeline.addHandler(serverRecorder) - }.wait()) + XCTAssertNoThrow( + try self.serverChannel.configureCommonHTTPServerPipeline( + connectionConfiguration: .init(), + streamConfiguration: .init() + ) { channel in + channel.pipeline.addHandler(ErrorHandler()) + } configurator: { channel in + channel.pipeline.addHandler(serverRecorder) + }.wait() + ) // Let's pretend the TLS handler did protocol negotiation for us - self.serverChannel.pipeline.fireUserInboundEventTriggered(TLSUserEvent.handshakeCompleted(negotiatedProtocol: "h2")) + self.serverChannel.pipeline.fireUserInboundEventTriggered( + TLSUserEvent.handshakeCompleted(negotiatedProtocol: "h2") + ) XCTAssertNoThrow(try self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel)) // Let's try sending an h2 request. let requestPromise = self.clientChannel.eventLoop.makePromise(of: Void.self) - let reqFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: HPACKHeaders([(":method", "GET"), (":authority", "localhost"), (":scheme", "https"), (":path", "/testH2toHTTP1")]), endStream: true))) + let reqFrame = HTTP2Frame( + streamID: 1, + payload: .headers( + .init( + headers: HPACKHeaders([ + (":method", "GET"), (":authority", "localhost"), (":scheme", "https"), + (":path", "/testH2toHTTP1"), + ]), + endStream: true + ) + ) + ) clientMultiplexer.createStreamChannel(promise: nil) { channel in channel.writeAndFlush(reqFrame.payload).whenComplete { _ in channel.close(promise: requestPromise) } @@ -544,24 +605,36 @@ class ConfiguringPipelineInlineMultiplexerTests: XCTestCase { let serverRecorder = HTTP1ServerRequestRecorderHandler() XCTAssertNoThrow(try self.clientChannel.pipeline.addHTTPClientHandlers().wait()) - XCTAssertNoThrow(try self.serverChannel.configureCommonHTTPServerPipeline( - connectionConfiguration: .init(), - streamConfiguration: .init() - ) { channel in - channel.pipeline.addHandler(ErrorHandler()) - } configurator: { channel in - return channel.pipeline.addHandler(serverRecorder) - }.wait()) + XCTAssertNoThrow( + try self.serverChannel.configureCommonHTTPServerPipeline( + connectionConfiguration: .init(), + streamConfiguration: .init() + ) { channel in + channel.pipeline.addHandler(ErrorHandler()) + } configurator: { channel in + channel.pipeline.addHandler(serverRecorder) + }.wait() + ) // Let's pretend the TLS handler did protocol negotiation for us - self.serverChannel.pipeline.fireUserInboundEventTriggered (TLSUserEvent.handshakeCompleted(negotiatedProtocol: "http/1.1")) + self.serverChannel.pipeline.fireUserInboundEventTriggered( + TLSUserEvent.handshakeCompleted(negotiatedProtocol: "http/1.1") + ) // Let's try sending an http/1.1 request. let requestPromise = self.clientChannel.eventLoop.makePromise(of: Void.self) - XCTAssertNoThrow(try self.clientChannel.writeOutbound(HTTPClientRequestPart.head(HTTPRequestHead(version: .init(major: 1, minor: 1), method: .GET, uri: "/testHTTP1")))) - self.clientChannel.writeAndFlush(HTTPClientRequestPart.end(nil), - promise: requestPromise) + XCTAssertNoThrow( + try self.clientChannel.writeOutbound( + HTTPClientRequestPart.head( + HTTPRequestHead(version: .init(major: 1, minor: 1), method: .GET, uri: "/testHTTP1") + ) + ) + ) + self.clientChannel.writeAndFlush( + HTTPClientRequestPart.end(nil), + promise: requestPromise + ) XCTAssertNoThrow(try requestPromise.futureResult.wait()) self.interactInMemory(self.clientChannel, self.serverChannel) diff --git a/Tests/NIOHTTP2Tests/ConfiguringPipelineTests.swift b/Tests/NIOHTTP2Tests/ConfiguringPipelineTests.swift index a284d34..e35cb33 100644 --- a/Tests/NIOHTTP2Tests/ConfiguringPipelineTests.swift +++ b/Tests/NIOHTTP2Tests/ConfiguringPipelineTests.swift @@ -12,8 +12,6 @@ // //===----------------------------------------------------------------------===// -import XCTest - import NIOConcurrencyHelpers import NIOCore import NIOEmbedded @@ -21,6 +19,7 @@ import NIOHPACK import NIOHTTP1 import NIOHTTP2 import NIOTLS +import XCTest class ConfiguringPipelineTests: XCTestCase { var clientChannel: EmbeddedChannel! @@ -40,15 +39,27 @@ class ConfiguringPipelineTests: XCTestCase { func testBasicPipelineCommunicates() throws { let serverRecorder = FrameRecorderHandler() let clientHandler = try assertNoThrowWithValue(self.clientChannel.configureHTTP2Pipeline(mode: .client).wait()) - XCTAssertNoThrow(try self.serverChannel.configureHTTP2Pipeline(mode: .server) { channel, streamID in - return channel.pipeline.addHandler(serverRecorder) - }.wait()) + XCTAssertNoThrow( + try self.serverChannel.configureHTTP2Pipeline(mode: .server) { channel, streamID in + channel.pipeline.addHandler(serverRecorder) + }.wait() + ) XCTAssertNoThrow(try self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel)) // Let's try sending a request. let requestPromise = self.clientChannel.eventLoop.makePromise(of: Void.self) - let reqFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: HPACKHeaders([(":method", "GET"), (":authority", "localhost"), (":scheme", "https"), (":path", "/")]), endStream: true))) + let reqFrame = HTTP2Frame( + streamID: 1, + payload: .headers( + .init( + headers: HPACKHeaders([ + (":method", "GET"), (":authority", "localhost"), (":scheme", "https"), (":path", "/"), + ]), + endStream: true + ) + ) + ) clientHandler.createStreamChannel(promise: nil) { channel, streamID in XCTAssertEqual(streamID, HTTP2StreamID(1)) @@ -80,16 +91,30 @@ class ConfiguringPipelineTests: XCTestCase { @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") func testBasicPipelineCommunicatesWithTargetWindowSize() throws { let serverRecorder = FrameRecorderHandler() - let clientHandler = try assertNoThrowWithValue(self.clientChannel.configureHTTP2Pipeline(mode: .client, targetWindowSize: 65535).wait()) - XCTAssertNoThrow(try self.serverChannel.configureHTTP2Pipeline(mode: .server, targetWindowSize: 65535) { channel, streamID in - return channel.pipeline.addHandler(serverRecorder) - }.wait()) + let clientHandler = try assertNoThrowWithValue( + self.clientChannel.configureHTTP2Pipeline(mode: .client, targetWindowSize: 65535).wait() + ) + XCTAssertNoThrow( + try self.serverChannel.configureHTTP2Pipeline(mode: .server, targetWindowSize: 65535) { channel, streamID in + channel.pipeline.addHandler(serverRecorder) + }.wait() + ) XCTAssertNoThrow(try self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel)) // Let's try sending a request. let requestPromise = self.clientChannel.eventLoop.makePromise(of: Void.self) - let reqFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: HPACKHeaders([(":method", "GET"), (":authority", "localhost"), (":scheme", "https"), (":path", "/")]), endStream: true))) + let reqFrame = HTTP2Frame( + streamID: 1, + payload: .headers( + .init( + headers: HPACKHeaders([ + (":method", "GET"), (":authority", "localhost"), (":scheme", "https"), (":path", "/"), + ]), + endStream: true + ) + ) + ) clientHandler.createStreamChannel(promise: nil) { channel, streamID in XCTAssertEqual(streamID, HTTP2StreamID(1)) @@ -139,7 +164,10 @@ class ConfiguringPipelineTests: XCTestCase { @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") func testPipelineRespectsPositionRequestWithTargetWindowSize() throws { XCTAssertNoThrow(try self.clientChannel.pipeline.addHandler(FailOnWriteHandler()).wait()) - XCTAssertNoThrow(try self.clientChannel.configureHTTP2Pipeline(mode: .client, position: .first, targetWindowSize: 65535).wait()) + XCTAssertNoThrow( + try self.clientChannel.configureHTTP2Pipeline(mode: .client, position: .first, targetWindowSize: 65535) + .wait() + ) XCTAssertNoThrow(try self.serverChannel.configureHTTP2Pipeline(mode: .server, targetWindowSize: 65535).wait()) XCTAssertNoThrow(try self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel)) @@ -243,7 +271,9 @@ class ConfiguringPipelineTests: XCTestCase { } } - let clientMultiplexer = try assertNoThrowWithValue(self.clientChannel.configureHTTP2Pipeline(mode: .client).wait()) + let clientMultiplexer = try assertNoThrowWithValue( + self.clientChannel.configureHTTP2Pipeline(mode: .client).wait() + ) XCTAssertNoThrow(try self.serverChannel.configureHTTP2Pipeline(mode: .server).wait()) XCTAssertNoThrow(try self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel)) @@ -252,7 +282,7 @@ class ConfiguringPipelineTests: XCTestCase { let streamChannelPromise: EventLoopPromise = self.clientChannel.eventLoop.makePromise() clientMultiplexer.createStreamChannel(promise: streamChannelPromise) { channel, _ in - return channel.pipeline.addHandler(InactiveHandler(inactivePromise: inactivePromise)) + channel.pipeline.addHandler(InactiveHandler(inactivePromise: inactivePromise)) } (self.clientChannel.eventLoop as! EmbeddedEventLoop).run() @@ -287,7 +317,9 @@ class ConfiguringPipelineTests: XCTestCase { } } - let clientMultiplexer = try assertNoThrowWithValue(self.clientChannel.configureHTTP2Pipeline(mode: .client, targetWindowSize: 65535).wait()) + let clientMultiplexer = try assertNoThrowWithValue( + self.clientChannel.configureHTTP2Pipeline(mode: .client, targetWindowSize: 65535).wait() + ) XCTAssertNoThrow(try self.serverChannel.configureHTTP2Pipeline(mode: .server, targetWindowSize: 65535).wait()) XCTAssertNoThrow(try self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel)) @@ -296,7 +328,7 @@ class ConfiguringPipelineTests: XCTestCase { let streamChannelPromise: EventLoopPromise = self.clientChannel.eventLoop.makePromise() clientMultiplexer.createStreamChannel(promise: streamChannelPromise) { channel, _ in - return channel.pipeline.addHandler(InactiveHandler(inactivePromise: inactivePromise)) + channel.pipeline.addHandler(InactiveHandler(inactivePromise: inactivePromise)) } (self.clientChannel.eventLoop as! EmbeddedEventLoop).run() @@ -340,19 +372,36 @@ class ConfiguringPipelineTests: XCTestCase { let clientHandler = try assertNoThrowWithValue(self.clientChannel.configureHTTP2Pipeline(mode: .client).wait()) let serverChildChannelPromise = self.serverChannel.eventLoop.makePromise(of: Channel.self) - XCTAssertNoThrow(try self.serverChannel.configureCommonHTTPServerPipeline(h2ConnectionChannelConfigurator: { $0.pipeline.addHandler(ErrorHandler()) }) { channel in - serverChildChannelPromise.succeed(channel) - return channel.pipeline.addHandler(HTTP1ServerRequestRecorderHandler()) - }.wait()) + XCTAssertNoThrow( + try self.serverChannel.configureCommonHTTPServerPipeline(h2ConnectionChannelConfigurator: { + $0.pipeline.addHandler(ErrorHandler()) + }) { channel in + serverChildChannelPromise.succeed(channel) + return channel.pipeline.addHandler(HTTP1ServerRequestRecorderHandler()) + }.wait() + ) // Let's pretend the TLS handler did protocol negotiation for us - self.serverChannel.pipeline.fireUserInboundEventTriggered (TLSUserEvent.handshakeCompleted(negotiatedProtocol: "h2")) + self.serverChannel.pipeline.fireUserInboundEventTriggered( + TLSUserEvent.handshakeCompleted(negotiatedProtocol: "h2") + ) XCTAssertNoThrow(try self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel)) // Let's try sending an h2 request. let requestPromise = self.clientChannel.eventLoop.makePromise(of: Void.self) - let reqFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: HPACKHeaders([(":method", "GET"), (":authority", "localhost"), (":scheme", "https"), (":path", "/testH2toHTTP1")]), endStream: true))) + let reqFrame = HTTP2Frame( + streamID: 1, + payload: .headers( + .init( + headers: HPACKHeaders([ + (":method", "GET"), (":authority", "localhost"), (":scheme", "https"), + (":path", "/testH2toHTTP1"), + ]), + endStream: true + ) + ) + ) clientHandler.createStreamChannel(promise: nil) { channel, streamID in XCTAssertEqual(streamID, HTTP2StreamID(1)) @@ -407,22 +456,41 @@ class ConfiguringPipelineTests: XCTestCase { } } - let clientHandler = try assertNoThrowWithValue(self.clientChannel.configureHTTP2Pipeline(mode: .client, targetWindowSize: 65535).wait()) + let clientHandler = try assertNoThrowWithValue( + self.clientChannel.configureHTTP2Pipeline(mode: .client, targetWindowSize: 65535).wait() + ) let serverChildChannelPromise = self.serverChannel.eventLoop.makePromise(of: Channel.self) - XCTAssertNoThrow(try self.serverChannel.configureCommonHTTPServerPipeline(h2ConnectionChannelConfigurator: { $0.pipeline.addHandler(ErrorHandler()) }) { channel in - serverChildChannelPromise.succeed(channel) - return channel.pipeline.addHandler(HTTP1ServerRequestRecorderHandler()) - }.wait()) + XCTAssertNoThrow( + try self.serverChannel.configureCommonHTTPServerPipeline(h2ConnectionChannelConfigurator: { + $0.pipeline.addHandler(ErrorHandler()) + }) { channel in + serverChildChannelPromise.succeed(channel) + return channel.pipeline.addHandler(HTTP1ServerRequestRecorderHandler()) + }.wait() + ) // Let's pretend the TLS handler did protocol negotiation for us - self.serverChannel.pipeline.fireUserInboundEventTriggered (TLSUserEvent.handshakeCompleted(negotiatedProtocol: "h2")) + self.serverChannel.pipeline.fireUserInboundEventTriggered( + TLSUserEvent.handshakeCompleted(negotiatedProtocol: "h2") + ) XCTAssertNoThrow(try self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel)) // Let's try sending an h2 request. let requestPromise = self.clientChannel.eventLoop.makePromise(of: Void.self) - let reqFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: HPACKHeaders([(":method", "GET"), (":authority", "localhost"), (":scheme", "https"), (":path", "/testH2toHTTP1")]), endStream: true))) + let reqFrame = HTTP2Frame( + streamID: 1, + payload: .headers( + .init( + headers: HPACKHeaders([ + (":method", "GET"), (":authority", "localhost"), (":scheme", "https"), + (":path", "/testH2toHTTP1"), + ]), + endStream: true + ) + ) + ) clientHandler.createStreamChannel(promise: nil) { channel, streamID in XCTAssertEqual(streamID, HTTP2StreamID(1)) diff --git a/Tests/NIOHTTP2Tests/ConfiguringPipelineWithFramePayloadStreamsTests.swift b/Tests/NIOHTTP2Tests/ConfiguringPipelineWithFramePayloadStreamsTests.swift index 5d7164c..4967007 100644 --- a/Tests/NIOHTTP2Tests/ConfiguringPipelineWithFramePayloadStreamsTests.swift +++ b/Tests/NIOHTTP2Tests/ConfiguringPipelineWithFramePayloadStreamsTests.swift @@ -12,15 +12,14 @@ // //===----------------------------------------------------------------------===// -import XCTest - -import NIOCore import NIOConcurrencyHelpers +import NIOCore import NIOEmbedded import NIOHPACK import NIOHTTP1 import NIOHTTP2 import NIOTLS +import XCTest /// A simple channel handler that can be inserted in a pipeline to ensure that it never sees a write. /// @@ -51,16 +50,30 @@ class ConfiguringPipelineWithFramePayloadStreamsTests: XCTestCase { func testBasicPipelineCommunicates() throws { let serverRecorder = InboundFramePayloadRecorder() - let clientHandler = try assertNoThrowWithValue(self.clientChannel.configureHTTP2Pipeline(mode: .client, inboundStreamInitializer: nil).wait()) - XCTAssertNoThrow(try self.serverChannel.configureHTTP2Pipeline(mode: .server) { channel in - return channel.pipeline.addHandler(serverRecorder) - }.wait()) + let clientHandler = try assertNoThrowWithValue( + self.clientChannel.configureHTTP2Pipeline(mode: .client, inboundStreamInitializer: nil).wait() + ) + XCTAssertNoThrow( + try self.serverChannel.configureHTTP2Pipeline(mode: .server) { channel in + channel.pipeline.addHandler(serverRecorder) + }.wait() + ) XCTAssertNoThrow(try self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel)) // Let's try sending a request. let requestPromise = self.clientChannel.eventLoop.makePromise(of: Void.self) - let reqFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: HPACKHeaders([(":method", "GET"), (":authority", "localhost"), (":scheme", "https"), (":path", "/")]), endStream: true))) + let reqFrame = HTTP2Frame( + streamID: 1, + payload: .headers( + .init( + headers: HPACKHeaders([ + (":method", "GET"), (":authority", "localhost"), (":scheme", "https"), (":path", "/"), + ]), + endStream: true + ) + ) + ) clientHandler.createStreamChannel(promise: nil) { channel in channel.writeAndFlush(reqFrame.payload).whenComplete { _ in channel.close(promise: requestPromise) } @@ -90,16 +103,34 @@ class ConfiguringPipelineWithFramePayloadStreamsTests: XCTestCase { func testBasicPipelineCommunicatesWithTargetWindowSize() throws { let serverRecorder = InboundFramePayloadRecorder() - let clientHandler = try assertNoThrowWithValue(self.clientChannel.configureHTTP2Pipeline(mode: .client, targetWindowSize: 65535, inboundStreamInitializer: nil).wait()) - XCTAssertNoThrow(try self.serverChannel.configureHTTP2Pipeline(mode: .server, targetWindowSize: 65535) { channel in - return channel.pipeline.addHandler(serverRecorder) - }.wait()) + let clientHandler = try assertNoThrowWithValue( + self.clientChannel.configureHTTP2Pipeline( + mode: .client, + targetWindowSize: 65535, + inboundStreamInitializer: nil + ).wait() + ) + XCTAssertNoThrow( + try self.serverChannel.configureHTTP2Pipeline(mode: .server, targetWindowSize: 65535) { channel in + channel.pipeline.addHandler(serverRecorder) + }.wait() + ) XCTAssertNoThrow(try self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel)) // Let's try sending a request. let requestPromise = self.clientChannel.eventLoop.makePromise(of: Void.self) - let reqFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: HPACKHeaders([(":method", "GET"), (":authority", "localhost"), (":scheme", "https"), (":path", "/")]), endStream: true))) + let reqFrame = HTTP2Frame( + streamID: 1, + payload: .headers( + .init( + headers: HPACKHeaders([ + (":method", "GET"), (":authority", "localhost"), (":scheme", "https"), (":path", "/"), + ]), + endStream: true + ) + ) + ) clientHandler.createStreamChannel(promise: nil) { channel in channel.writeAndFlush(reqFrame.payload).whenComplete { _ in channel.close(promise: requestPromise) } @@ -129,8 +160,16 @@ class ConfiguringPipelineWithFramePayloadStreamsTests: XCTestCase { func testPipelineRespectsPositionRequest() throws { XCTAssertNoThrow(try self.clientChannel.pipeline.addHandler(FailOnWriteHandler()).wait()) - XCTAssertNoThrow(try self.clientChannel.configureHTTP2Pipeline(mode: .client, position: .first, inboundStreamInitializer: nil).wait()) - XCTAssertNoThrow(try self.serverChannel.configureHTTP2Pipeline(mode: .server, inboundStreamInitializer: nil).wait()) + XCTAssertNoThrow( + try self.clientChannel.configureHTTP2Pipeline( + mode: .client, + position: .first, + inboundStreamInitializer: nil + ).wait() + ) + XCTAssertNoThrow( + try self.serverChannel.configureHTTP2Pipeline(mode: .server, inboundStreamInitializer: nil).wait() + ) XCTAssertNoThrow(try self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel)) @@ -146,8 +185,21 @@ class ConfiguringPipelineWithFramePayloadStreamsTests: XCTestCase { func testPipelineRespectsPositionRequestWithTargetWindowSize() throws { XCTAssertNoThrow(try self.clientChannel.pipeline.addHandler(FailOnWriteHandler()).wait()) - XCTAssertNoThrow(try self.clientChannel.configureHTTP2Pipeline(mode: .client, position: .first, targetWindowSize: 65535, inboundStreamInitializer: nil).wait()) - XCTAssertNoThrow(try self.serverChannel.configureHTTP2Pipeline(mode: .server, targetWindowSize: 65535, inboundStreamInitializer: nil).wait()) + XCTAssertNoThrow( + try self.clientChannel.configureHTTP2Pipeline( + mode: .client, + position: .first, + targetWindowSize: 65535, + inboundStreamInitializer: nil + ).wait() + ) + XCTAssertNoThrow( + try self.serverChannel.configureHTTP2Pipeline( + mode: .server, + targetWindowSize: 65535, + inboundStreamInitializer: nil + ).wait() + ) XCTAssertNoThrow(try self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel)) @@ -247,8 +299,12 @@ class ConfiguringPipelineWithFramePayloadStreamsTests: XCTestCase { } } - let clientMultiplexer = try assertNoThrowWithValue(self.clientChannel.configureHTTP2Pipeline(mode: .client, inboundStreamInitializer: nil).wait()) - XCTAssertNoThrow(try self.serverChannel.configureHTTP2Pipeline(mode: .server, inboundStreamInitializer: nil).wait()) + let clientMultiplexer = try assertNoThrowWithValue( + self.clientChannel.configureHTTP2Pipeline(mode: .client, inboundStreamInitializer: nil).wait() + ) + XCTAssertNoThrow( + try self.serverChannel.configureHTTP2Pipeline(mode: .server, inboundStreamInitializer: nil).wait() + ) XCTAssertNoThrow(try self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel)) @@ -256,7 +312,7 @@ class ConfiguringPipelineWithFramePayloadStreamsTests: XCTestCase { let streamChannelPromise: EventLoopPromise = self.clientChannel.eventLoop.makePromise() clientMultiplexer.createStreamChannel(promise: streamChannelPromise) { channel in - return channel.pipeline.addHandler(InactiveHandler(inactivePromise: inactivePromise)) + channel.pipeline.addHandler(InactiveHandler(inactivePromise: inactivePromise)) } (self.clientChannel.eventLoop as! EmbeddedEventLoop).run() @@ -290,8 +346,20 @@ class ConfiguringPipelineWithFramePayloadStreamsTests: XCTestCase { } } - let clientMultiplexer = try assertNoThrowWithValue(self.clientChannel.configureHTTP2Pipeline(mode: .client, targetWindowSize: 65535, inboundStreamInitializer: nil).wait()) - XCTAssertNoThrow(try self.serverChannel.configureHTTP2Pipeline(mode: .server, targetWindowSize: 65535, inboundStreamInitializer: nil).wait()) + let clientMultiplexer = try assertNoThrowWithValue( + self.clientChannel.configureHTTP2Pipeline( + mode: .client, + targetWindowSize: 65535, + inboundStreamInitializer: nil + ).wait() + ) + XCTAssertNoThrow( + try self.serverChannel.configureHTTP2Pipeline( + mode: .server, + targetWindowSize: 65535, + inboundStreamInitializer: nil + ).wait() + ) XCTAssertNoThrow(try self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel)) @@ -299,7 +367,7 @@ class ConfiguringPipelineWithFramePayloadStreamsTests: XCTestCase { let streamChannelPromise: EventLoopPromise = self.clientChannel.eventLoop.makePromise() clientMultiplexer.createStreamChannel(promise: streamChannelPromise) { channel in - return channel.pipeline.addHandler(InactiveHandler(inactivePromise: inactivePromise)) + channel.pipeline.addHandler(InactiveHandler(inactivePromise: inactivePromise)) } (self.clientChannel.eventLoop as! EmbeddedEventLoop).run() @@ -340,20 +408,39 @@ class ConfiguringPipelineWithFramePayloadStreamsTests: XCTestCase { } let serverRecorder = HTTP1ServerRequestRecorderHandler() - let clientHandler = try assertNoThrowWithValue(self.clientChannel.configureHTTP2Pipeline(mode: .client, inboundStreamInitializer: nil).wait()) + let clientHandler = try assertNoThrowWithValue( + self.clientChannel.configureHTTP2Pipeline(mode: .client, inboundStreamInitializer: nil).wait() + ) - XCTAssertNoThrow(try self.serverChannel.configureCommonHTTPServerPipeline(h2ConnectionChannelConfigurator: { $0.pipeline.addHandler(ErrorHandler()) }) { channel in - return channel.pipeline.addHandler(serverRecorder) - }.wait()) + XCTAssertNoThrow( + try self.serverChannel.configureCommonHTTPServerPipeline(h2ConnectionChannelConfigurator: { + $0.pipeline.addHandler(ErrorHandler()) + }) { channel in + channel.pipeline.addHandler(serverRecorder) + }.wait() + ) // Let's pretend the TLS handler did protocol negotiation for us - self.serverChannel.pipeline.fireUserInboundEventTriggered (TLSUserEvent.handshakeCompleted(negotiatedProtocol: "h2")) + self.serverChannel.pipeline.fireUserInboundEventTriggered( + TLSUserEvent.handshakeCompleted(negotiatedProtocol: "h2") + ) XCTAssertNoThrow(try self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel)) // Let's try sending an h2 request. let requestPromise = self.clientChannel.eventLoop.makePromise(of: Void.self) - let reqFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: HPACKHeaders([(":method", "GET"), (":authority", "localhost"), (":scheme", "https"), (":path", "/testH2toHTTP1")]), endStream: true))) + let reqFrame = HTTP2Frame( + streamID: 1, + payload: .headers( + .init( + headers: HPACKHeaders([ + (":method", "GET"), (":authority", "localhost"), (":scheme", "https"), + (":path", "/testH2toHTTP1"), + ]), + endStream: true + ) + ) + ) clientHandler.createStreamChannel(promise: nil) { channel in channel.writeAndFlush(reqFrame.payload).whenComplete { _ in channel.close(promise: requestPromise) } @@ -403,20 +490,43 @@ class ConfiguringPipelineWithFramePayloadStreamsTests: XCTestCase { } let serverRecorder = HTTP1ServerRequestRecorderHandler() - let clientHandler = try assertNoThrowWithValue(self.clientChannel.configureHTTP2Pipeline(mode: .client, targetWindowSize: 65535, inboundStreamInitializer: nil).wait()) + let clientHandler = try assertNoThrowWithValue( + self.clientChannel.configureHTTP2Pipeline( + mode: .client, + targetWindowSize: 65535, + inboundStreamInitializer: nil + ).wait() + ) - XCTAssertNoThrow(try self.serverChannel.configureCommonHTTPServerPipeline(h2ConnectionChannelConfigurator: { $0.pipeline.addHandler(ErrorHandler()) }) { channel in - return channel.pipeline.addHandler(serverRecorder) - }.wait()) + XCTAssertNoThrow( + try self.serverChannel.configureCommonHTTPServerPipeline(h2ConnectionChannelConfigurator: { + $0.pipeline.addHandler(ErrorHandler()) + }) { channel in + channel.pipeline.addHandler(serverRecorder) + }.wait() + ) // Let's pretend the TLS handler did protocol negotiation for us - self.serverChannel.pipeline.fireUserInboundEventTriggered(TLSUserEvent.handshakeCompleted(negotiatedProtocol: "h2")) + self.serverChannel.pipeline.fireUserInboundEventTriggered( + TLSUserEvent.handshakeCompleted(negotiatedProtocol: "h2") + ) XCTAssertNoThrow(try self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel)) // Let's try sending an h2 request. let requestPromise = self.clientChannel.eventLoop.makePromise(of: Void.self) - let reqFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: HPACKHeaders([(":method", "GET"), (":authority", "localhost"), (":scheme", "https"), (":path", "/testH2toHTTP1")]), endStream: true))) + let reqFrame = HTTP2Frame( + streamID: 1, + payload: .headers( + .init( + headers: HPACKHeaders([ + (":method", "GET"), (":authority", "localhost"), (":scheme", "https"), + (":path", "/testH2toHTTP1"), + ]), + endStream: true + ) + ) + ) clientHandler.createStreamChannel(promise: nil) { channel in channel.writeAndFlush(reqFrame.payload).whenComplete { _ in channel.close(promise: requestPromise) } @@ -467,19 +577,33 @@ class ConfiguringPipelineWithFramePayloadStreamsTests: XCTestCase { let serverRecorder = HTTP1ServerRequestRecorderHandler() XCTAssertNoThrow(try self.clientChannel.pipeline.addHTTPClientHandlers().wait()) - XCTAssertNoThrow(try self.serverChannel.configureCommonHTTPServerPipeline(h2ConnectionChannelConfigurator: { $0.pipeline.addHandler(ErrorHandler()) }) { channel in - return channel.pipeline.addHandler(serverRecorder) - }.wait()) + XCTAssertNoThrow( + try self.serverChannel.configureCommonHTTPServerPipeline(h2ConnectionChannelConfigurator: { + $0.pipeline.addHandler(ErrorHandler()) + }) { channel in + channel.pipeline.addHandler(serverRecorder) + }.wait() + ) // Let's pretend the TLS handler did protocol negotiation for us - self.serverChannel.pipeline.fireUserInboundEventTriggered (TLSUserEvent.handshakeCompleted(negotiatedProtocol: "http/1.1")) + self.serverChannel.pipeline.fireUserInboundEventTriggered( + TLSUserEvent.handshakeCompleted(negotiatedProtocol: "http/1.1") + ) // Let's try sending an http/1.1 request. let requestPromise = self.clientChannel.eventLoop.makePromise(of: Void.self) - XCTAssertNoThrow(try self.clientChannel.writeOutbound(HTTPClientRequestPart.head(HTTPRequestHead(version: .init(major: 1, minor: 1), method: .GET, uri: "/testHTTP1")))) - self.clientChannel.writeAndFlush(HTTPClientRequestPart.end(nil), - promise: requestPromise) + XCTAssertNoThrow( + try self.clientChannel.writeOutbound( + HTTPClientRequestPart.head( + HTTPRequestHead(version: .init(major: 1, minor: 1), method: .GET, uri: "/testHTTP1") + ) + ) + ) + self.clientChannel.writeAndFlush( + HTTPClientRequestPart.end(nil), + promise: requestPromise + ) XCTAssertNoThrow(try requestPromise.futureResult.wait()) self.interactInMemory(self.clientChannel, self.serverChannel) diff --git a/Tests/NIOHTTP2Tests/ConnectionStateMachineTests.swift b/Tests/NIOHTTP2Tests/ConnectionStateMachineTests.swift index 02932c9..30fd456 100644 --- a/Tests/NIOHTTP2Tests/ConnectionStateMachineTests.swift +++ b/Tests/NIOHTTP2Tests/ConnectionStateMachineTests.swift @@ -12,10 +12,10 @@ // //===----------------------------------------------------------------------===// -import XCTest - import NIOCore import NIOHPACK +import XCTest + @testable import NIOHTTP2 func assertSucceeds(_ body: @autoclosure () -> StateMachineResult, file: StaticString = #filePath, line: UInt = #line) { @@ -28,7 +28,12 @@ func assertSucceeds(_ body: @autoclosure () -> StateMachineResult, file: StaticS } @discardableResult -func assertConnectionError(type: HTTP2ErrorCode, _ body: @autoclosure () -> StateMachineResult, file: StaticString = #filePath, line: UInt = #line) -> Error? { +func assertConnectionError( + type: HTTP2ErrorCode, + _ body: @autoclosure () -> StateMachineResult, + file: StaticString = #filePath, + line: UInt = #line +) -> Error? { switch body() { case .connectionError(underlyingError: let error, type: type): return error @@ -39,7 +44,12 @@ func assertConnectionError(type: HTTP2ErrorCode, _ body: @autoclosure () -> Stat } @discardableResult -func assertStreamError(type: HTTP2ErrorCode, _ body: @autoclosure () -> StateMachineResult, file: StaticString = #filePath, line: UInt = #line) -> Error? { +func assertStreamError( + type: HTTP2ErrorCode, + _ body: @autoclosure () -> StateMachineResult, + file: StaticString = #filePath, + line: UInt = #line +) -> Error? { switch body() { case .streamError(streamID: _, underlyingError: let error, type: type): return error @@ -50,7 +60,12 @@ func assertStreamError(type: HTTP2ErrorCode, _ body: @autoclosure () -> StateMac } @discardableResult -func assertBadStreamStateTransition(type: NIOHTTP2StreamState, _ body: @autoclosure () -> StateMachineResultWithEffect, file: StaticString = #filePath, line: UInt = #line) -> NIOHTTP2Errors.BadStreamStateTransition? { +func assertBadStreamStateTransition( + type: NIOHTTP2StreamState, + _ body: @autoclosure () -> StateMachineResultWithEffect, + file: StaticString = #filePath, + line: UInt = #line +) -> NIOHTTP2Errors.BadStreamStateTransition? { let error: NIOHTTP2Errors.BadStreamStateTransition switch body().result { @@ -64,7 +79,7 @@ func assertBadStreamStateTransition(type: NIOHTTP2StreamState, _ body: @autoclos } XCTAssertEqual(error.fromState, type, file: (file), line: line) - + return error } @@ -77,52 +92,93 @@ func assertIgnored(_ body: @autoclosure () -> StateMachineResult, file: StaticSt } } -func assertSucceeds(_ body: @autoclosure () -> (StateMachineResultWithEffect, PostFrameOperation), file: StaticString = #filePath, line: UInt = #line) { - return assertSucceeds(body().0, file: (file), line: line) +func assertSucceeds( + _ body: @autoclosure () -> (StateMachineResultWithEffect, PostFrameOperation), + file: StaticString = #filePath, + line: UInt = #line +) { + assertSucceeds(body().0, file: (file), line: line) } -func assertConnectionError(type: HTTP2ErrorCode, _ body: @autoclosure () -> (StateMachineResultWithEffect, PostFrameOperation), file: StaticString = #filePath, line: UInt = #line) { +func assertConnectionError( + type: HTTP2ErrorCode, + _ body: @autoclosure () -> (StateMachineResultWithEffect, PostFrameOperation), + file: StaticString = #filePath, + line: UInt = #line +) { assertConnectionError(type: type, body().0, file: (file), line: line) } -func assertSucceeds(_ body: @autoclosure () -> StateMachineResultWithEffect, file: StaticString = #filePath, line: UInt = #line) { - return assertSucceeds(body().result, file: (file), line: line) +func assertSucceeds( + _ body: @autoclosure () -> StateMachineResultWithEffect, + file: StaticString = #filePath, + line: UInt = #line +) { + assertSucceeds(body().result, file: (file), line: line) } @discardableResult -func assertConnectionError(type: HTTP2ErrorCode, _ body: @autoclosure () -> StateMachineResultWithEffect, file: StaticString = #filePath, line: UInt = #line) -> Error? { +func assertConnectionError( + type: HTTP2ErrorCode, + _ body: @autoclosure () -> StateMachineResultWithEffect, + file: StaticString = #filePath, + line: UInt = #line +) -> Error? { // Errors must always lead to noChange. let result = body() return assertConnectionError(type: type, result.result, file: (file), line: line) } @discardableResult -func assertStreamError(type: HTTP2ErrorCode, _ body: @autoclosure () -> StateMachineResultWithEffect, file: StaticString = #filePath, line: UInt = #line) -> Error? { +func assertStreamError( + type: HTTP2ErrorCode, + _ body: @autoclosure () -> StateMachineResultWithEffect, + file: StaticString = #filePath, + line: UInt = #line +) -> Error? { // Errors must always lead to noChange. let result = body() return assertStreamError(type: type, result.result, file: (file), line: line) } -func assertIgnored(_ body: @autoclosure () -> StateMachineResultWithEffect, file: StaticString = #filePath, line: UInt = #line) { +func assertIgnored( + _ body: @autoclosure () -> StateMachineResultWithEffect, + file: StaticString = #filePath, + line: UInt = #line +) { // Ignored frames must always lead to noChange. let result = body() assertIgnored(result.result, file: (file), line: line) } -func assertGoawaySucceeds(_ body: @autoclosure () -> StateMachineResultWithEffect, droppingStreams: [HTTP2StreamID]?, file: StaticString = #filePath, line: UInt = #line) { +func assertGoawaySucceeds( + _ body: @autoclosure () -> StateMachineResultWithEffect, + droppingStreams: [HTTP2StreamID]?, + file: StaticString = #filePath, + line: UInt = #line +) { let result = body() if case .some(.bulkStreamClosure(let closedStreamsEvent)) = result.effect { - XCTAssertEqual(closedStreamsEvent.closedStreams.sorted(), droppingStreams?.sorted(), - "GOAWAY closed unexpected streams: expected \(String(describing: droppingStreams)), got \(closedStreamsEvent.closedStreams)", file: (file), line: line) + XCTAssertEqual( + closedStreamsEvent.closedStreams.sorted(), + droppingStreams?.sorted(), + "GOAWAY closed unexpected streams: expected \(String(describing: droppingStreams)), got \(closedStreamsEvent.closedStreams)", + file: (file), + line: line + ) } else { - XCTAssertNil(droppingStreams, "GOAWAY did not close streams, but expected \(String(describing: droppingStreams))", file: (file), line: line) + XCTAssertNil( + droppingStreams, + "GOAWAY did not close streams, but expected \(String(describing: droppingStreams))", + file: (file), + line: line + ) } assertSucceeds(result.result, file: (file), line: line) } - class ConnectionStateMachineTests: XCTestCase { var server: HTTP2ConnectionStateMachine! var client: HTTP2ConnectionStateMachine! @@ -136,15 +192,18 @@ class ConnectionStateMachineTests: XCTestCase { let maximumSequentialContinuationFrames: Int = 5 static let requestHeaders = { - return HPACKHeaders([(":method", "GET"), (":authority", "localhost"), (":scheme", "https"), (":path", "/"), ("user-agent", "test")]) + HPACKHeaders([ + (":method", "GET"), (":authority", "localhost"), (":scheme", "https"), (":path", "/"), + ("user-agent", "test"), + ]) }() static let responseHeaders = { - return HPACKHeaders([(":status", "200"), ("server", "NIO")]) + HPACKHeaders([(":status", "200"), ("server", "NIO")]) }() static let trailers = { - return HPACKHeaders([("x-trailers", "yes")]) + HPACKHeaders([("x-trailers", "yes")]) }() override func setUp() { @@ -167,42 +226,129 @@ class ConnectionStateMachineTests: XCTestCase { private func exchangePreamble(client: HTTP2Settings = HTTP2Settings(), server: HTTP2Settings = HTTP2Settings()) { assertSucceeds(self.client.sendSettings(client)) - assertSucceeds(self.server.receiveSettings(.settings(client), frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder)) + assertSucceeds( + self.server.receiveSettings( + .settings(client), + frameEncoder: &self.serverEncoder, + frameDecoder: &self.serverDecoder + ) + ) assertSucceeds(self.server.sendSettings(server)) - assertSucceeds(self.client.receiveSettings(.settings(server), frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder)) + assertSucceeds( + self.client.receiveSettings( + .settings(server), + frameEncoder: &self.serverEncoder, + frameDecoder: &self.serverDecoder + ) + ) - assertSucceeds(self.client.receiveSettings(.ack, frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder)) - assertSucceeds(self.server.receiveSettings(.ack, frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder)) + assertSucceeds( + self.client.receiveSettings(.ack, frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder) + ) + assertSucceeds( + self.server.receiveSettings(.ack, frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder) + ) } - private func setupServerGoaway(streamsToOpen: [HTTP2StreamID], lastStreamID: HTTP2StreamID, expectedToClose: [HTTP2StreamID]?, file: StaticString = #filePath, line: UInt = #line) { + private func setupServerGoaway( + streamsToOpen: [HTTP2StreamID], + lastStreamID: HTTP2StreamID, + expectedToClose: [HTTP2StreamID]?, + file: StaticString = #filePath, + line: UInt = #line + ) { self.exchangePreamble() // Client opens streams. for streamID in streamsToOpen { - assertSucceeds(self.client.sendHeaders(streamID: streamID, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: false)) - assertSucceeds(self.server.receiveHeaders(streamID: streamID, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: false)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamID, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamID, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: false + ) + ) } // Server sends a reset. - assertGoawaySucceeds(self.server.sendGoaway(lastStreamID: lastStreamID), droppingStreams: expectedToClose, file: (file), line: line) - assertGoawaySucceeds(self.client.receiveGoaway(lastStreamID: lastStreamID), droppingStreams: expectedToClose, file: (file), line: line) + assertGoawaySucceeds( + self.server.sendGoaway(lastStreamID: lastStreamID), + droppingStreams: expectedToClose, + file: (file), + line: line + ) + assertGoawaySucceeds( + self.client.receiveGoaway(lastStreamID: lastStreamID), + droppingStreams: expectedToClose, + file: (file), + line: line + ) } - private func setupClientGoaway(clientStreamID: HTTP2StreamID, streamsToOpen: [HTTP2StreamID], lastStreamID: HTTP2StreamID, expectedToClose: [HTTP2StreamID]?, file: StaticString = #filePath, line: UInt = #line) { + private func setupClientGoaway( + clientStreamID: HTTP2StreamID, + streamsToOpen: [HTTP2StreamID], + lastStreamID: HTTP2StreamID, + expectedToClose: [HTTP2StreamID]?, + file: StaticString = #filePath, + line: UInt = #line + ) { self.exchangePreamble() // Client opens its stream, server sends response. - assertSucceeds(self.client.sendHeaders(streamID: clientStreamID, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: false)) - assertSucceeds(self.server.receiveHeaders(streamID: clientStreamID, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: false)) - assertSucceeds(self.server.sendHeaders(streamID: clientStreamID, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.client.receiveHeaders(streamID: clientStreamID, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) + assertSucceeds( + self.client.sendHeaders( + streamID: clientStreamID, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: clientStreamID, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.server.sendHeaders( + streamID: clientStreamID, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: clientStreamID, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) // Server opens streams. for streamID in streamsToOpen { - assertSucceeds(self.server.sendPushPromise(originalStreamID: clientStreamID, childStreamID: streamID, headers: ConnectionStateMachineTests.requestHeaders)) - assertSucceeds(self.client.receivePushPromise(originalStreamID: clientStreamID, childStreamID: streamID, headers: ConnectionStateMachineTests.requestHeaders)) + assertSucceeds( + self.server.sendPushPromise( + originalStreamID: clientStreamID, + childStreamID: streamID, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) + assertSucceeds( + self.client.receivePushPromise( + originalStreamID: clientStreamID, + childStreamID: streamID, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) } // Client sends a reset. @@ -215,11 +361,35 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble() - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) - assertSucceeds(self.server.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: true)) - assertSucceeds(self.client.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: true)) + assertSucceeds( + self.server.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: true + ) + ) assertSucceeds(self.client.sendGoaway(lastStreamID: .rootStream)) assertSucceeds(self.server.receiveGoaway(lastStreamID: .rootStream)) @@ -239,13 +409,16 @@ class ConnectionStateMachineTests: XCTestCase { // Create the stream but leave the state in idle by not passing in the required headers let _ = self.server.receiveHeaders(streamID: streamOne, headers: .init(), isEndStreamSet: false) var savedServerState = self.server - + // Change the state to halfOpenRemoteLocalIdle let testHeaders: HPACKHeaders = [":method": "test", ":path": "test", ":scheme": "test"] let _ = self.server.receiveHeaders(streamID: streamOne, headers: testHeaders, isEndStreamSet: false) savedServerState = self.server - assertBadStreamStateTransition(type: .halfOpenRemoteLocalIdle, self.server.sendData(streamID: streamOne, contentLength: 0, flowControlledBytes: 0, isEndStreamSet: false)) + assertBadStreamStateTransition( + type: .halfOpenRemoteLocalIdle, + self.server.sendData(streamID: streamOne, contentLength: 0, flowControlledBytes: 0, isEndStreamSet: false) + ) self.server = savedServerState // Move state to fullyOpen @@ -254,44 +427,103 @@ class ConnectionStateMachineTests: XCTestCase { savedServerState = self.server // Move state to halfClosedLocalPeerActive - assertSucceeds(self.server.sendData(streamID: streamOne, contentLength: 0, flowControlledBytes: 0, isEndStreamSet: true)) + assertSucceeds( + self.server.sendData(streamID: streamOne, contentLength: 0, flowControlledBytes: 0, isEndStreamSet: true) + ) savedServerState = self.server - assertBadStreamStateTransition(type: .halfClosedLocalPeerActive, self.server.sendData(streamID: streamOne, contentLength: 0, flowControlledBytes: 0, isEndStreamSet: true)) + assertBadStreamStateTransition( + type: .halfClosedLocalPeerActive, + self.server.sendData(streamID: streamOne, contentLength: 0, flowControlledBytes: 0, isEndStreamSet: true) + ) self.server = savedServerState let testPushPromiseHeaders: HPACKHeaders = ["test": "value"] - assertBadStreamStateTransition(type: .halfClosedLocalPeerActive, self.server.sendPushPromise(originalStreamID: streamOne, childStreamID: streamTwo, headers: testPushPromiseHeaders)) + assertBadStreamStateTransition( + type: .halfClosedLocalPeerActive, + self.server.sendPushPromise( + originalStreamID: streamOne, + childStreamID: streamTwo, + headers: testPushPromiseHeaders + ) + ) self.server = savedServerState - let lastBadStreamStateTransition = assertBadStreamStateTransition(type: .halfClosedLocalPeerActive, self.server.sendHeaders(streamID: streamOne, headers: testPushPromiseHeaders, isEndStreamSet: false)) + let lastBadStreamStateTransition = assertBadStreamStateTransition( + type: .halfClosedLocalPeerActive, + self.server.sendHeaders(streamID: streamOne, headers: testPushPromiseHeaders, isEndStreamSet: false) + ) self.server = savedServerState - + // Test that BadStreamStateTransition conforms to CustomStringConvertible - XCTAssertTrue(lastBadStreamStateTransition!.description.starts(with: "BadStreamStateTransition(fromState: halfClosedLocalPeerActive")) -} + XCTAssertTrue( + lastBadStreamStateTransition!.description.starts( + with: "BadStreamStateTransition(fromState: halfClosedLocalPeerActive" + ) + ) + } func testOpeningConnectionWhileServerPreambleMissing() { let streamOne = HTTP2StreamID(1) // Here the client sends its SETTINGS frame, and then immediately sends its HEADERS. assertSucceeds(self.client.sendSettings(HTTP2Settings())) - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) // Server receives - assertSucceeds(self.server.receiveSettings(.settings(HTTP2Settings()), frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) + assertSucceeds( + self.server.receiveSettings( + .settings(HTTP2Settings()), + frameEncoder: &self.serverEncoder, + frameDecoder: &self.serverDecoder + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) // Server sends its preamble, then ACKs, then sends its response. assertSucceeds(self.server.sendSettings(HTTP2Settings())) - assertSucceeds(self.server.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: true)) + assertSucceeds( + self.server.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: true + ) + ) // Client receives. - assertSucceeds(self.client.receiveSettings(.settings(HTTP2Settings()), frameEncoder: &self.clientEncoder, frameDecoder: &self.clientDecoder)) - assertSucceeds(self.client.receiveSettings(.ack, frameEncoder: &self.clientEncoder, frameDecoder: &self.clientDecoder)) - assertSucceeds(self.client.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: true)) + assertSucceeds( + self.client.receiveSettings( + .settings(HTTP2Settings()), + frameEncoder: &self.clientEncoder, + frameDecoder: &self.clientDecoder + ) + ) + assertSucceeds( + self.client.receiveSettings(.ack, frameEncoder: &self.clientEncoder, frameDecoder: &self.clientDecoder) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: true + ) + ) // Client ACKs - assertSucceeds(self.server.receiveSettings(.ack, frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder)) + assertSucceeds( + self.server.receiveSettings(.ack, frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder) + ) // Cleanup assertSucceeds(self.client.sendGoaway(lastStreamID: .rootStream)) @@ -308,20 +540,58 @@ class ConnectionStateMachineTests: XCTestCase { // Here the server sends its SETTINGS frame and the client receives it before its even sent its own. assertSucceeds(self.server.sendSettings(HTTP2Settings())) - assertSucceeds(self.client.receiveSettings(.settings(HTTP2Settings()), frameEncoder: &self.clientEncoder, frameDecoder: &self.clientDecoder)) + assertSucceeds( + self.client.receiveSettings( + .settings(HTTP2Settings()), + frameEncoder: &self.clientEncoder, + frameDecoder: &self.clientDecoder + ) + ) // Now the client sends back with an ACK and then sends HEADERS assertSucceeds(self.client.sendSettings(HTTP2Settings())) - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) // Now the server receives, sends its ACK back, as well as its response. - assertSucceeds(self.server.receiveSettings(.settings(HTTP2Settings()), frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder)) - assertSucceeds(self.server.receiveSettings(.ack, frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: true)) + assertSucceeds( + self.server.receiveSettings( + .settings(HTTP2Settings()), + frameEncoder: &self.serverEncoder, + frameDecoder: &self.serverDecoder + ) + ) + assertSucceeds( + self.server.receiveSettings(.ack, frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: true + ) + ) // Client receives. - assertSucceeds(self.client.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: true)) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: true + ) + ) // Cleanup assertSucceeds(self.client.sendGoaway(lastStreamID: .rootStream)) @@ -338,26 +608,120 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble() - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: false)) - assertSucceeds(self.client.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: false)) - assertSucceeds(self.server.receiveData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.client.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.server.receiveData( + streamID: streamOne, + contentLength: 15, + flowControlledBytes: 15, + isEndStreamSet: false + ) + ) - assertSucceeds(self.server.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.server.sendData(streamID: streamOne, contentLength: 300, flowControlledBytes: 300, isEndStreamSet: false)) - assertSucceeds(self.client.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.client.receiveData(streamID: streamOne, contentLength: 300, flowControlledBytes: 300, isEndStreamSet: false)) + assertSucceeds( + self.server.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.server.sendData( + streamID: streamOne, + contentLength: 300, + flowControlledBytes: 300, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.client.receiveData( + streamID: streamOne, + contentLength: 300, + flowControlledBytes: 300, + isEndStreamSet: false + ) + ) // Now both sides send another DATA frame and then trailers. Oooooh, trailers. - assertSucceeds(self.client.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false)) - assertSucceeds(self.server.sendData(streamID: streamOne, contentLength: 300, flowControlledBytes: 300, isEndStreamSet: false)) - assertSucceeds(self.client.receiveData(streamID: streamOne, contentLength: 300, flowControlledBytes: 300, isEndStreamSet: false)) - assertSucceeds(self.server.receiveData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false)) + assertSucceeds( + self.client.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false) + ) + assertSucceeds( + self.server.sendData( + streamID: streamOne, + contentLength: 300, + flowControlledBytes: 300, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.client.receiveData( + streamID: streamOne, + contentLength: 300, + flowControlledBytes: 300, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.server.receiveData( + streamID: streamOne, + contentLength: 15, + flowControlledBytes: 15, + isEndStreamSet: false + ) + ) - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.trailers, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.trailers, isEndStreamSet: true)) - assertSucceeds(self.server.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.trailers, isEndStreamSet: true)) - assertSucceeds(self.client.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.trailers, isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.trailers, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.trailers, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.trailers, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.trailers, + isEndStreamSet: true + ) + ) // Cleanup assertSucceeds(self.client.sendGoaway(lastStreamID: .rootStream)) @@ -374,8 +738,22 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble() - assertConnectionError(type: .protocolError, self.server.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertConnectionError(type: .protocolError, self.client.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) + assertConnectionError( + type: .protocolError, + self.server.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertConnectionError( + type: .protocolError, + self.client.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) } func testSimpleServerPush() { @@ -387,38 +765,150 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble() - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) // Server can push right away - assertSucceeds(self.server.sendPushPromise(originalStreamID: streamOne, childStreamID: streamTwo, headers: ConnectionStateMachineTests.requestHeaders)) - assertSucceeds(self.client.receivePushPromise(originalStreamID: streamOne, childStreamID: streamTwo, headers: ConnectionStateMachineTests.requestHeaders)) + assertSucceeds( + self.server.sendPushPromise( + originalStreamID: streamOne, + childStreamID: streamTwo, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) + assertSucceeds( + self.client.receivePushPromise( + originalStreamID: streamOne, + childStreamID: streamTwo, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) // Server sends its headers - assertSucceeds(self.server.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.client.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) + assertSucceeds( + self.server.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) // Server pushes, suceeeds, and completes the pushed response. - assertSucceeds(self.server.sendPushPromise(originalStreamID: streamOne, childStreamID: streamFour, headers: ConnectionStateMachineTests.requestHeaders)) - assertSucceeds(self.client.receivePushPromise(originalStreamID: streamOne, childStreamID: streamFour, headers: ConnectionStateMachineTests.requestHeaders)) + assertSucceeds( + self.server.sendPushPromise( + originalStreamID: streamOne, + childStreamID: streamFour, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) + assertSucceeds( + self.client.receivePushPromise( + originalStreamID: streamOne, + childStreamID: streamFour, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) // Server attempts to push with invalid stream ID, fails. Client rejects it too. - assertConnectionError(type: .protocolError, self.server.sendPushPromise(originalStreamID: streamOne, childStreamID: streamThree, headers: ConnectionStateMachineTests.requestHeaders)) + assertConnectionError( + type: .protocolError, + self.server.sendPushPromise( + originalStreamID: streamOne, + childStreamID: streamThree, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) var tempClient = self.client! - assertConnectionError(type: .protocolError, tempClient.receivePushPromise(originalStreamID: streamOne, childStreamID: streamThree, headers: ConnectionStateMachineTests.requestHeaders)) + assertConnectionError( + type: .protocolError, + tempClient.receivePushPromise( + originalStreamID: streamOne, + childStreamID: streamThree, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) // Server attempts to push on stream two, fails. Client rejects it too. - assertStreamError(type: .protocolError, self.server.sendPushPromise(originalStreamID: streamTwo, childStreamID: streamSix, headers: ConnectionStateMachineTests.requestHeaders)) + assertStreamError( + type: .protocolError, + self.server.sendPushPromise( + originalStreamID: streamTwo, + childStreamID: streamSix, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) tempClient = self.client! - assertStreamError(type: .protocolError, tempClient.receivePushPromise(originalStreamID: streamTwo, childStreamID: streamSix, headers: ConnectionStateMachineTests.requestHeaders)) + assertStreamError( + type: .protocolError, + tempClient.receivePushPromise( + originalStreamID: streamTwo, + childStreamID: streamSix, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) // Server completes all streams. - assertSucceeds(self.server.sendHeaders(streamID: streamFour, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: true)) - assertSucceeds(self.client.receiveHeaders(streamID: streamFour, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.sendHeaders(streamID: streamTwo, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: true)) - assertSucceeds(self.client.receiveHeaders(streamID: streamTwo, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.trailers, isEndStreamSet: true)) - assertSucceeds(self.client.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.trailers, isEndStreamSet: true)) + assertSucceeds( + self.server.sendHeaders( + streamID: streamFour, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamFour, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.sendHeaders( + streamID: streamTwo, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamTwo, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.trailers, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.trailers, + isEndStreamSet: true + ) + ) // Cleanup assertSucceeds(self.client.sendGoaway(lastStreamID: streamTwo)) @@ -435,15 +925,37 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble() - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) assertSucceeds(self.server.sendRstStream(streamID: streamOne, reason: .noError)) assertSucceeds(self.client.receiveRstStream(streamID: streamOne, reason: .noError)) // Client attempts to send on this stream fail. Servers ignore the frame. - assertConnectionError(type: .streamClosed, self.client.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: true)) - assertIgnored(self.server.receiveData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: true)) + assertConnectionError( + type: .streamClosed, + self.client.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: true) + ) + assertIgnored( + self.server.receiveData( + streamID: streamOne, + contentLength: 15, + flowControlledBytes: 15, + isEndStreamSet: true + ) + ) assertSucceeds(self.client.sendGoaway(lastStreamID: .rootStream)) assertSucceeds(self.server.receiveGoaway(lastStreamID: .rootStream)) @@ -460,19 +972,50 @@ class ConnectionStateMachineTests: XCTestCase { let streamFive = HTTP2StreamID(5) let streamSeven = HTTP2StreamID(7) - self.setupServerGoaway(streamsToOpen: [streamOne, streamThree, streamFive, streamSeven], lastStreamID: streamThree, expectedToClose: [streamFive, streamSeven]) + self.setupServerGoaway( + streamsToOpen: [streamOne, streamThree, streamFive, streamSeven], + lastStreamID: streamThree, + expectedToClose: [streamFive, streamSeven] + ) // Server attempts to send on a closed stream fails, and clients reject that attempt as well. // Client attempts to send on a closed stream fails, but the server ignores such frames. var temporaryServer = self.server! var temporaryClient = self.client! - assertConnectionError(type: .streamClosed, temporaryServer.sendHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: true)) - assertConnectionError(type: .streamClosed, temporaryClient.receiveHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: true)) + assertConnectionError( + type: .streamClosed, + temporaryServer.sendHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: true + ) + ) + assertConnectionError( + type: .streamClosed, + temporaryClient.receiveHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: true + ) + ) temporaryServer = self.server! temporaryClient = self.client! - assertConnectionError(type: .streamClosed, temporaryClient.sendHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.trailers, isEndStreamSet: true)) - assertIgnored(temporaryServer.receiveHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.trailers, isEndStreamSet: true)) + assertConnectionError( + type: .streamClosed, + temporaryClient.sendHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.trailers, + isEndStreamSet: true + ) + ) + assertIgnored( + temporaryServer.receiveHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.trailers, + isEndStreamSet: true + ) + ) } func testDataOnClosedStreamAfterServerGoaway() { @@ -481,19 +1024,54 @@ class ConnectionStateMachineTests: XCTestCase { let streamFive = HTTP2StreamID(5) let streamSeven = HTTP2StreamID(7) - self.setupServerGoaway(streamsToOpen: [streamOne, streamThree, streamFive, streamSeven], lastStreamID: streamThree, expectedToClose: [streamFive, streamSeven]) + self.setupServerGoaway( + streamsToOpen: [streamOne, streamThree, streamFive, streamSeven], + lastStreamID: streamThree, + expectedToClose: [streamFive, streamSeven] + ) // Server attempts to send on a closed stream fails, and clients reject that attempt as well. // Client attempts to send on a closed stream fails, but the server ignores such frames. var temporaryServer = self.server! var temporaryClient = self.client! - assertConnectionError(type: .streamClosed, temporaryServer.sendData(streamID: streamFive, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: true)) - assertConnectionError(type: .streamClosed, temporaryClient.receiveData(streamID: streamFive, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: true)) + assertConnectionError( + type: .streamClosed, + temporaryServer.sendData( + streamID: streamFive, + contentLength: 15, + flowControlledBytes: 15, + isEndStreamSet: true + ) + ) + assertConnectionError( + type: .streamClosed, + temporaryClient.receiveData( + streamID: streamFive, + contentLength: 15, + flowControlledBytes: 15, + isEndStreamSet: true + ) + ) temporaryServer = self.server! temporaryClient = self.client! - assertConnectionError(type: .streamClosed, temporaryClient.sendData(streamID: streamFive, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: true)) - assertIgnored(temporaryServer.receiveData(streamID: streamFive, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: true)) + assertConnectionError( + type: .streamClosed, + temporaryClient.sendData( + streamID: streamFive, + contentLength: 15, + flowControlledBytes: 15, + isEndStreamSet: true + ) + ) + assertIgnored( + temporaryServer.receiveData( + streamID: streamFive, + contentLength: 15, + flowControlledBytes: 15, + isEndStreamSet: true + ) + ) } func testWindowUpdateOnClosedStreamAfterServerGoaway() { @@ -502,18 +1080,28 @@ class ConnectionStateMachineTests: XCTestCase { let streamFive = HTTP2StreamID(5) let streamSeven = HTTP2StreamID(7) - self.setupServerGoaway(streamsToOpen: [streamOne, streamThree, streamFive, streamSeven], lastStreamID: streamThree, expectedToClose: [streamFive, streamSeven]) + self.setupServerGoaway( + streamsToOpen: [streamOne, streamThree, streamFive, streamSeven], + lastStreamID: streamThree, + expectedToClose: [streamFive, streamSeven] + ) // Server attempts to send on a closed stream fails, and clients ignore that attempt. // Client attempts to send on a closed stream fails, but the server ignores such frames. var temporaryServer = self.server! var temporaryClient = self.client! - assertConnectionError(type: .streamClosed, temporaryServer.sendWindowUpdate(streamID: streamFive, windowIncrement: 15)) + assertConnectionError( + type: .streamClosed, + temporaryServer.sendWindowUpdate(streamID: streamFive, windowIncrement: 15) + ) assertIgnored(temporaryClient.receiveWindowUpdate(streamID: streamFive, windowIncrement: 15)) temporaryServer = self.server! temporaryClient = self.client! - assertConnectionError(type: .streamClosed, temporaryClient.sendWindowUpdate(streamID: streamFive, windowIncrement: 15)) + assertConnectionError( + type: .streamClosed, + temporaryClient.sendWindowUpdate(streamID: streamFive, windowIncrement: 15) + ) assertIgnored(temporaryServer.receiveWindowUpdate(streamID: streamFive, windowIncrement: 15)) } @@ -523,19 +1111,29 @@ class ConnectionStateMachineTests: XCTestCase { let streamFive = HTTP2StreamID(5) let streamSeven = HTTP2StreamID(7) - self.setupServerGoaway(streamsToOpen: [streamOne, streamThree, streamFive, streamSeven], lastStreamID: streamThree, expectedToClose: [streamFive, streamSeven]) + self.setupServerGoaway( + streamsToOpen: [streamOne, streamThree, streamFive, streamSeven], + lastStreamID: streamThree, + expectedToClose: [streamFive, streamSeven] + ) // Server attempts to send on a closed stream fails, and clients reject that attempt as well. // Client attempts to send on a closed stream fails, but the server ignores such frames. var temporaryServer = self.server! var temporaryClient = self.client! - assertConnectionError(type: .streamClosed, temporaryServer.sendRstStream(streamID: streamFive, reason: .noError)) + assertConnectionError( + type: .streamClosed, + temporaryServer.sendRstStream(streamID: streamFive, reason: .noError) + ) // We ignore RST_STREAM in the closed state because the RFC does not explicitly forbid that. assertIgnored(temporaryClient.receiveRstStream(streamID: streamFive, reason: .noError)) temporaryServer = self.server! temporaryClient = self.client! - assertConnectionError(type: .streamClosed, temporaryClient.sendRstStream(streamID: streamFive, reason: .noError)) + assertConnectionError( + type: .streamClosed, + temporaryClient.sendRstStream(streamID: streamFive, reason: .noError) + ) assertIgnored(temporaryServer.receiveRstStream(streamID: streamFive, reason: .noError)) } @@ -546,21 +1144,63 @@ class ConnectionStateMachineTests: XCTestCase { let streamSeven = HTTP2StreamID(7) let streamTwo = HTTP2StreamID(2) - self.setupServerGoaway(streamsToOpen: [streamOne, streamThree, streamFive, streamSeven], lastStreamID: streamThree, expectedToClose: [streamFive, streamSeven]) + self.setupServerGoaway( + streamsToOpen: [streamOne, streamThree, streamFive, streamSeven], + lastStreamID: streamThree, + expectedToClose: [streamFive, streamSeven] + ) // Server cannot push on the recently closed stream, client rejects it. var temporaryServer = self.server! var temporaryClient = self.client! - assertConnectionError(type: .streamClosed, temporaryServer.sendPushPromise(originalStreamID: streamFive, childStreamID: streamTwo, headers: ConnectionStateMachineTests.requestHeaders)) - assertConnectionError(type: .streamClosed, temporaryClient.receivePushPromise(originalStreamID: streamFive, childStreamID: streamTwo, headers: ConnectionStateMachineTests.requestHeaders)) + assertConnectionError( + type: .streamClosed, + temporaryServer.sendPushPromise( + originalStreamID: streamFive, + childStreamID: streamTwo, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) + assertConnectionError( + type: .streamClosed, + temporaryClient.receivePushPromise( + originalStreamID: streamFive, + childStreamID: streamTwo, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) // Server can successfully push on still-open stream. temporaryServer = self.server! temporaryClient = self.client! - assertSucceeds(temporaryServer.sendHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(temporaryClient.receiveHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(temporaryServer.sendPushPromise(originalStreamID: streamThree, childStreamID: streamTwo, headers: ConnectionStateMachineTests.requestHeaders)) - assertSucceeds(temporaryClient.receivePushPromise(originalStreamID: streamThree, childStreamID: streamTwo, headers: ConnectionStateMachineTests.requestHeaders)) + assertSucceeds( + temporaryServer.sendHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + temporaryClient.receiveHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + temporaryServer.sendPushPromise( + originalStreamID: streamThree, + childStreamID: streamTwo, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) + assertSucceeds( + temporaryClient.receivePushPromise( + originalStreamID: streamThree, + childStreamID: streamTwo, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) } func testClientMayNotInitiateNewStreamAfterServerGoaway() { @@ -569,13 +1209,30 @@ class ConnectionStateMachineTests: XCTestCase { let streamFive = HTTP2StreamID(5) let streamSeven = HTTP2StreamID(7) - self.setupServerGoaway(streamsToOpen: [streamOne, streamThree, streamFive], lastStreamID: streamThree, expectedToClose: [streamFive]) + self.setupServerGoaway( + streamsToOpen: [streamOne, streamThree, streamFive], + lastStreamID: streamThree, + expectedToClose: [streamFive] + ) // Client has received GOAWAY, cannot initiate new stream. Server ignores this, as it may have been in flight. var temporaryServer = self.server! var temporaryClient = self.client! - assertConnectionError(type: .protocolError, temporaryClient.sendHeaders(streamID: streamSeven, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertIgnored(temporaryServer.receiveHeaders(streamID: streamSeven, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) + assertConnectionError( + type: .protocolError, + temporaryClient.sendHeaders( + streamID: streamSeven, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertIgnored( + temporaryServer.receiveHeaders( + streamID: streamSeven, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) } func testClientInitiatesNewStreamBeforeReceivingAlreadySentGoaway() { @@ -587,11 +1244,24 @@ class ConnectionStateMachineTests: XCTestCase { var temporaryClient = self.client! assertSucceeds(temporaryServer.sendGoaway(lastStreamID: .maxID)) - assertSucceeds(temporaryClient.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: false)) + assertSucceeds( + temporaryClient.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: false + ) + ) assertSucceeds(temporaryClient.receiveGoaway(lastStreamID: .maxID)) // The server should throw a stream error (and as a result, respond with a RST_STREAM frame) when it receives the headers. - assertStreamError(type: .refusedStream, temporaryServer.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: false)) + assertStreamError( + type: .refusedStream, + temporaryServer.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: false + ) + ) assertSucceeds(temporaryServer.sendRstStream(streamID: streamOne, reason: .refusedStream)) assertSucceeds(temporaryClient.receiveRstStream(streamID: streamOne, reason: .refusedStream)) } @@ -602,19 +1272,51 @@ class ConnectionStateMachineTests: XCTestCase { let streamFour = HTTP2StreamID(4) let streamSix = HTTP2StreamID(6) - self.setupClientGoaway(clientStreamID: streamOne, streamsToOpen: [streamTwo, streamFour, streamSix], lastStreamID: streamTwo, expectedToClose: [streamFour, streamSix]) + self.setupClientGoaway( + clientStreamID: streamOne, + streamsToOpen: [streamTwo, streamFour, streamSix], + lastStreamID: streamTwo, + expectedToClose: [streamFour, streamSix] + ) // Server attempts to send on a closed stream fails, but clients ignore that attempt. // Client attempts to send on a closed stream fails, and the server rejects such frames. var temporaryServer = self.server! var temporaryClient = self.client! - assertConnectionError(type: .streamClosed, temporaryServer.sendHeaders(streamID: streamFour, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: true)) - assertIgnored(temporaryClient.receiveHeaders(streamID: streamFour, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: true)) + assertConnectionError( + type: .streamClosed, + temporaryServer.sendHeaders( + streamID: streamFour, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: true + ) + ) + assertIgnored( + temporaryClient.receiveHeaders( + streamID: streamFour, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: true + ) + ) temporaryServer = self.server! temporaryClient = self.client! - assertConnectionError(type: .streamClosed, temporaryClient.sendHeaders(streamID: streamFour, headers: ConnectionStateMachineTests.trailers, isEndStreamSet: true)) - assertConnectionError(type: .streamClosed, temporaryServer.receiveHeaders(streamID: streamFour, headers: ConnectionStateMachineTests.trailers, isEndStreamSet: true)) + assertConnectionError( + type: .streamClosed, + temporaryClient.sendHeaders( + streamID: streamFour, + headers: ConnectionStateMachineTests.trailers, + isEndStreamSet: true + ) + ) + assertConnectionError( + type: .streamClosed, + temporaryServer.receiveHeaders( + streamID: streamFour, + headers: ConnectionStateMachineTests.trailers, + isEndStreamSet: true + ) + ) } func testDataOnClosedStreamAfterClientGoaway() { @@ -623,19 +1325,55 @@ class ConnectionStateMachineTests: XCTestCase { let streamFour = HTTP2StreamID(4) let streamSix = HTTP2StreamID(6) - self.setupClientGoaway(clientStreamID: streamOne, streamsToOpen: [streamTwo, streamFour, streamSix], lastStreamID: streamTwo, expectedToClose: [streamFour, streamSix]) + self.setupClientGoaway( + clientStreamID: streamOne, + streamsToOpen: [streamTwo, streamFour, streamSix], + lastStreamID: streamTwo, + expectedToClose: [streamFour, streamSix] + ) // Server attempts to send on a closed stream fails, but clients ignore that attempt. // Client attempts to send on a closed stream fails, and the server rejects such frames. var temporaryServer = self.server! var temporaryClient = self.client! - assertConnectionError(type: .streamClosed, temporaryServer.sendData(streamID: streamFour, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: true)) - assertIgnored(temporaryClient.receiveData(streamID: streamFour, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: true)) + assertConnectionError( + type: .streamClosed, + temporaryServer.sendData( + streamID: streamFour, + contentLength: 15, + flowControlledBytes: 15, + isEndStreamSet: true + ) + ) + assertIgnored( + temporaryClient.receiveData( + streamID: streamFour, + contentLength: 15, + flowControlledBytes: 15, + isEndStreamSet: true + ) + ) temporaryServer = self.server! temporaryClient = self.client! - assertConnectionError(type: .streamClosed, temporaryClient.sendData(streamID: streamFour, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: true)) - assertConnectionError(type: .streamClosed, temporaryServer.receiveData(streamID: streamFour, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: true)) + assertConnectionError( + type: .streamClosed, + temporaryClient.sendData( + streamID: streamFour, + contentLength: 15, + flowControlledBytes: 15, + isEndStreamSet: true + ) + ) + assertConnectionError( + type: .streamClosed, + temporaryServer.receiveData( + streamID: streamFour, + contentLength: 15, + flowControlledBytes: 15, + isEndStreamSet: true + ) + ) } func testWindowUpdateOnClosedStreamAfterClientGoaway() { @@ -644,18 +1382,29 @@ class ConnectionStateMachineTests: XCTestCase { let streamFour = HTTP2StreamID(4) let streamSix = HTTP2StreamID(6) - self.setupClientGoaway(clientStreamID: streamOne, streamsToOpen: [streamTwo, streamFour, streamSix], lastStreamID: streamTwo, expectedToClose: [streamFour, streamSix]) + self.setupClientGoaway( + clientStreamID: streamOne, + streamsToOpen: [streamTwo, streamFour, streamSix], + lastStreamID: streamTwo, + expectedToClose: [streamFour, streamSix] + ) // Server attempts to send on a closed stream fails, but clients ignore that attempt. // Client attempts to send on a closed stream fails, but the server ignores that attempt. var temporaryServer = self.server! var temporaryClient = self.client! - assertConnectionError(type: .streamClosed, temporaryServer.sendWindowUpdate(streamID: streamFour, windowIncrement: 15)) + assertConnectionError( + type: .streamClosed, + temporaryServer.sendWindowUpdate(streamID: streamFour, windowIncrement: 15) + ) assertIgnored(temporaryClient.receiveWindowUpdate(streamID: streamFour, windowIncrement: 15)) temporaryServer = self.server! temporaryClient = self.client! - assertConnectionError(type: .streamClosed, temporaryClient.sendWindowUpdate(streamID: streamFour, windowIncrement: 15)) + assertConnectionError( + type: .streamClosed, + temporaryClient.sendWindowUpdate(streamID: streamFour, windowIncrement: 15) + ) assertIgnored(temporaryServer.receiveWindowUpdate(streamID: streamFour, windowIncrement: 15)) } @@ -665,18 +1414,29 @@ class ConnectionStateMachineTests: XCTestCase { let streamFour = HTTP2StreamID(4) let streamSix = HTTP2StreamID(6) - self.setupClientGoaway(clientStreamID: streamOne, streamsToOpen: [streamTwo, streamFour, streamSix], lastStreamID: streamTwo, expectedToClose: [streamFour, streamSix]) + self.setupClientGoaway( + clientStreamID: streamOne, + streamsToOpen: [streamTwo, streamFour, streamSix], + lastStreamID: streamTwo, + expectedToClose: [streamFour, streamSix] + ) // Server attempts to send on a closed stream fails, but clients ignore that attempt. // Client attempts to send on a closed stream fails, and the server rejects such frames. var temporaryServer = self.server! var temporaryClient = self.client! - assertConnectionError(type: .streamClosed, temporaryServer.sendRstStream(streamID: streamFour, reason: .noError)) + assertConnectionError( + type: .streamClosed, + temporaryServer.sendRstStream(streamID: streamFour, reason: .noError) + ) assertIgnored(temporaryClient.receiveRstStream(streamID: streamFour, reason: .noError)) temporaryServer = self.server! temporaryClient = self.client! - assertConnectionError(type: .streamClosed, temporaryClient.sendRstStream(streamID: streamFour, reason: .noError)) + assertConnectionError( + type: .streamClosed, + temporaryClient.sendRstStream(streamID: streamFour, reason: .noError) + ) // We ignore RST_STREAM in the closed state because the RFC does not explicitly forbid that. assertIgnored(temporaryServer.receiveRstStream(streamID: streamFour, reason: .noError)) } @@ -688,59 +1448,155 @@ class ConnectionStateMachineTests: XCTestCase { let streamSix = HTTP2StreamID(6) let streamEight = HTTP2StreamID(8) - self.setupClientGoaway(clientStreamID: streamOne, streamsToOpen: [streamTwo, streamFour, streamSix], lastStreamID: streamTwo, expectedToClose: [streamFour, streamSix]) + self.setupClientGoaway( + clientStreamID: streamOne, + streamsToOpen: [streamTwo, streamFour, streamSix], + lastStreamID: streamTwo, + expectedToClose: [streamFour, streamSix] + ) // Server has received GOAWAY, cannot initiate new stream. Client ignores this, as it may have been in flight. var temporaryServer = self.server! var temporaryClient = self.client! - assertConnectionError(type: .protocolError, temporaryServer.sendPushPromise(originalStreamID: streamOne, childStreamID: streamEight, headers: ConnectionStateMachineTests.requestHeaders)) - assertIgnored(temporaryClient.receivePushPromise(originalStreamID: streamOne, childStreamID: streamEight, headers: ConnectionStateMachineTests.requestHeaders)) + assertConnectionError( + type: .protocolError, + temporaryServer.sendPushPromise( + originalStreamID: streamOne, + childStreamID: streamEight, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) + assertIgnored( + temporaryClient.receivePushPromise( + originalStreamID: streamOne, + childStreamID: streamEight, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) } func testSendingFramesBeforePrefaceIsIllegal() { let streamOne = HTTP2StreamID(1) // We only need one of the state machines here. - assertConnectionError(type: .protocolError, self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: false)) - assertConnectionError(type: .protocolError, self.client.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false)) + assertConnectionError( + type: .protocolError, + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: false + ) + ) + assertConnectionError( + type: .protocolError, + self.client.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false) + ) assertConnectionError(type: .protocolError, self.client.sendPing()) assertConnectionError(type: .protocolError, self.client.sendPriority()) - assertConnectionError(type: .protocolError, self.client.sendPushPromise(originalStreamID: streamOne, childStreamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders)) + assertConnectionError( + type: .protocolError, + self.client.sendPushPromise( + originalStreamID: streamOne, + childStreamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) assertConnectionError(type: .protocolError, self.client.sendRstStream(streamID: streamOne, reason: .noError)) - assertConnectionError(type: .protocolError, self.client.sendWindowUpdate(streamID: streamOne, windowIncrement: 15)) + assertConnectionError( + type: .protocolError, + self.client.sendWindowUpdate(streamID: streamOne, windowIncrement: 15) + ) assertConnectionError(type: .protocolError, self.client.sendGoaway(lastStreamID: streamOne)) } func testSendingFramesBeforePrefaceAfterReceivedPrefaceIsIllegal() { let streamOne = HTTP2StreamID(1) - assertSucceeds(self.client.receiveSettings(.settings([]), frameEncoder: &self.clientEncoder, frameDecoder: &self.clientDecoder)) + assertSucceeds( + self.client.receiveSettings( + .settings([]), + frameEncoder: &self.clientEncoder, + frameDecoder: &self.clientDecoder + ) + ) // We only need one of the state machines here. - assertConnectionError(type: .protocolError, self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: false)) - assertConnectionError(type: .protocolError, self.client.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false)) + assertConnectionError( + type: .protocolError, + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: false + ) + ) + assertConnectionError( + type: .protocolError, + self.client.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false) + ) assertConnectionError(type: .protocolError, self.client.sendPing()) assertConnectionError(type: .protocolError, self.client.sendPriority()) - assertConnectionError(type: .protocolError, self.client.sendPushPromise(originalStreamID: streamOne, childStreamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders)) + assertConnectionError( + type: .protocolError, + self.client.sendPushPromise( + originalStreamID: streamOne, + childStreamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) assertConnectionError(type: .protocolError, self.client.sendRstStream(streamID: streamOne, reason: .noError)) - assertConnectionError(type: .protocolError, self.client.sendWindowUpdate(streamID: streamOne, windowIncrement: 15)) + assertConnectionError( + type: .protocolError, + self.client.sendWindowUpdate(streamID: streamOne, windowIncrement: 15) + ) assertConnectionError(type: .protocolError, self.client.sendGoaway(lastStreamID: streamOne)) } func testSendingFramesBeforePrefaceAfterReceivedPrefaceAndGoawayIsIllegal() { let streamOne = HTTP2StreamID(1) let streamTwo = HTTP2StreamID(2) - assertSucceeds(self.server.receiveSettings(.settings([]), frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) + assertSucceeds( + self.server.receiveSettings( + .settings([]), + frameEncoder: &self.serverEncoder, + frameDecoder: &self.serverDecoder + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) assertSucceeds(self.server.receiveGoaway(lastStreamID: .rootStream)) // We only need one of the state machines here. - assertConnectionError(type: .protocolError, self.server.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertConnectionError(type: .protocolError, self.server.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false)) + assertConnectionError( + type: .protocolError, + self.server.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertConnectionError( + type: .protocolError, + self.server.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false) + ) assertConnectionError(type: .protocolError, self.server.sendPing()) assertConnectionError(type: .protocolError, self.server.sendPriority()) - assertConnectionError(type: .protocolError, self.server.sendPushPromise(originalStreamID: streamOne, childStreamID: streamTwo, headers: ConnectionStateMachineTests.requestHeaders)) + assertConnectionError( + type: .protocolError, + self.server.sendPushPromise( + originalStreamID: streamOne, + childStreamID: streamTwo, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) assertConnectionError(type: .protocolError, self.server.sendRstStream(streamID: streamOne, reason: .noError)) - assertConnectionError(type: .protocolError, self.server.sendWindowUpdate(streamID: streamOne, windowIncrement: 15)) + assertConnectionError( + type: .protocolError, + self.server.sendWindowUpdate(streamID: streamOne, windowIncrement: 15) + ) assertConnectionError(type: .protocolError, self.server.sendGoaway(lastStreamID: streamOne)) } @@ -749,13 +1605,38 @@ class ConnectionStateMachineTests: XCTestCase { let streamTwo = HTTP2StreamID(2) // We only need one of the state machines here. - assertConnectionError(type: .protocolError, self.client.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertConnectionError(type: .protocolError, self.client.receiveData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false)) + assertConnectionError( + type: .protocolError, + self.client.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertConnectionError( + type: .protocolError, + self.client.receiveData( + streamID: streamOne, + contentLength: 15, + flowControlledBytes: 15, + isEndStreamSet: false + ) + ) assertConnectionError(type: .protocolError, self.client.receivePing(ackFlagSet: false)) assertConnectionError(type: .protocolError, self.client.receivePriority()) - assertConnectionError(type: .protocolError, self.client.receivePushPromise(originalStreamID: streamOne, childStreamID: streamTwo, headers: ConnectionStateMachineTests.requestHeaders)) + assertConnectionError( + type: .protocolError, + self.client.receivePushPromise( + originalStreamID: streamOne, + childStreamID: streamTwo, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) assertConnectionError(type: .protocolError, self.client.receiveRstStream(streamID: streamOne, reason: .noError)) - assertConnectionError(type: .protocolError, self.client.receiveWindowUpdate(streamID: streamOne, windowIncrement: 15)) + assertConnectionError( + type: .protocolError, + self.client.receiveWindowUpdate(streamID: streamOne, windowIncrement: 15) + ) assertConnectionError(type: .protocolError, self.client.receiveGoaway(lastStreamID: streamOne)) } @@ -763,16 +1644,47 @@ class ConnectionStateMachineTests: XCTestCase { let streamOne = HTTP2StreamID(1) let streamTwo = HTTP2StreamID(2) assertSucceeds(self.client.sendSettings([])) - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) // We only need one of the state machines here. - assertConnectionError(type: .protocolError, self.client.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertConnectionError(type: .protocolError, self.client.receiveData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false)) + assertConnectionError( + type: .protocolError, + self.client.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertConnectionError( + type: .protocolError, + self.client.receiveData( + streamID: streamOne, + contentLength: 15, + flowControlledBytes: 15, + isEndStreamSet: false + ) + ) assertConnectionError(type: .protocolError, self.client.receivePing(ackFlagSet: false)) assertConnectionError(type: .protocolError, self.client.receivePriority()) - assertConnectionError(type: .protocolError, self.client.receivePushPromise(originalStreamID: streamOne, childStreamID: streamTwo, headers: ConnectionStateMachineTests.requestHeaders)) + assertConnectionError( + type: .protocolError, + self.client.receivePushPromise( + originalStreamID: streamOne, + childStreamID: streamTwo, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) assertConnectionError(type: .protocolError, self.client.receiveRstStream(streamID: streamOne, reason: .noError)) - assertConnectionError(type: .protocolError, self.client.receiveWindowUpdate(streamID: streamOne, windowIncrement: 15)) + assertConnectionError( + type: .protocolError, + self.client.receiveWindowUpdate(streamID: streamOne, windowIncrement: 15) + ) assertConnectionError(type: .protocolError, self.client.receiveGoaway(lastStreamID: streamOne)) } @@ -780,17 +1692,48 @@ class ConnectionStateMachineTests: XCTestCase { let streamOne = HTTP2StreamID(1) let streamTwo = HTTP2StreamID(2) assertSucceeds(self.client.sendSettings([])) - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) assertSucceeds(self.client.sendGoaway(lastStreamID: .rootStream)) // We only need one of the state machines here. - assertConnectionError(type: .protocolError, self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertConnectionError(type: .protocolError, self.server.receiveData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false)) + assertConnectionError( + type: .protocolError, + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertConnectionError( + type: .protocolError, + self.server.receiveData( + streamID: streamOne, + contentLength: 15, + flowControlledBytes: 15, + isEndStreamSet: false + ) + ) assertConnectionError(type: .protocolError, self.server.receivePing(ackFlagSet: false)) assertConnectionError(type: .protocolError, self.server.receivePriority()) - assertConnectionError(type: .protocolError, self.server.receivePushPromise(originalStreamID: streamOne, childStreamID: streamTwo, headers: ConnectionStateMachineTests.requestHeaders)) + assertConnectionError( + type: .protocolError, + self.server.receivePushPromise( + originalStreamID: streamOne, + childStreamID: streamTwo, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) assertConnectionError(type: .protocolError, self.server.receiveRstStream(streamID: streamOne, reason: .noError)) - assertConnectionError(type: .protocolError, self.server.receiveWindowUpdate(streamID: streamOne, windowIncrement: 15)) + assertConnectionError( + type: .protocolError, + self.server.receiveWindowUpdate(streamID: streamOne, windowIncrement: 15) + ) assertConnectionError(type: .protocolError, self.server.receiveGoaway(lastStreamID: streamOne)) } @@ -800,10 +1743,16 @@ class ConnectionStateMachineTests: XCTestCase { let streamFive = HTTP2StreamID(5) let streamSeven = HTTP2StreamID(7) - self.setupServerGoaway(streamsToOpen: [streamOne, streamThree, streamFive, streamSeven], lastStreamID: streamSeven, expectedToClose: nil) + self.setupServerGoaway( + streamsToOpen: [streamOne, streamThree, streamFive, streamSeven], + lastStreamID: streamSeven, + expectedToClose: nil + ) // Now the server ratchets down slowly. - for (lastStreamID, dropping) in [(streamFive, streamSeven), (streamThree, streamFive), (streamOne, streamThree), (.rootStream, streamOne)] { + for (lastStreamID, dropping) in [ + (streamFive, streamSeven), (streamThree, streamFive), (streamOne, streamThree), (.rootStream, streamOne), + ] { assertGoawaySucceeds(self.server.sendGoaway(lastStreamID: lastStreamID), droppingStreams: [dropping]) assertGoawaySucceeds(self.client.receiveGoaway(lastStreamID: lastStreamID), droppingStreams: [dropping]) } @@ -815,14 +1764,20 @@ class ConnectionStateMachineTests: XCTestCase { let streamFive = HTTP2StreamID(5) let streamSeven = HTTP2StreamID(7) - self.setupServerGoaway(streamsToOpen: [streamOne, streamThree, streamFive, streamSeven], lastStreamID: streamSeven, expectedToClose: nil) + self.setupServerGoaway( + streamsToOpen: [streamOne, streamThree, streamFive, streamSeven], + lastStreamID: streamSeven, + expectedToClose: nil + ) // Now the client quiesces the server. assertSucceeds(self.client.sendGoaway(lastStreamID: .rootStream)) assertSucceeds(self.server.receiveGoaway(lastStreamID: .rootStream)) // Now the server ratchets down slowly. - for (lastStreamID, dropping) in [(streamFive, streamSeven), (streamThree, streamFive), (streamOne, streamThree), (.rootStream, streamOne)] { + for (lastStreamID, dropping) in [ + (streamFive, streamSeven), (streamThree, streamFive), (streamOne, streamThree), (.rootStream, streamOne), + ] { assertGoawaySucceeds(self.server.sendGoaway(lastStreamID: lastStreamID), droppingStreams: [dropping]) assertGoawaySucceeds(self.client.receiveGoaway(lastStreamID: lastStreamID), droppingStreams: [dropping]) } @@ -836,12 +1791,48 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble() // Client opens streams, server opens one back (just to be safe). - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: false)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: false)) - assertSucceeds(self.server.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.client.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.server.sendPushPromise(originalStreamID: streamOne, childStreamID: streamTwo, headers: ConnectionStateMachineTests.requestHeaders)) - assertSucceeds(self.client.receivePushPromise(originalStreamID: streamOne, childStreamID: streamTwo, headers: ConnectionStateMachineTests.requestHeaders)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.server.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.server.sendPushPromise( + originalStreamID: streamOne, + childStreamID: streamTwo, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) + assertSucceeds( + self.client.receivePushPromise( + originalStreamID: streamOne, + childStreamID: streamTwo, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) // The following operations aren't valid transitions from active. assertConnectionError(type: .protocolError, self.server.sendGoaway(lastStreamID: streamTwo)) @@ -863,15 +1854,42 @@ class ConnectionStateMachineTests: XCTestCase { // Client sends preface. assertSucceeds(self.client.sendSettings(HTTP2Settings())) - assertSucceeds(self.server.receiveSettings(.settings(HTTP2Settings()), frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder)) + assertSucceeds( + self.server.receiveSettings( + .settings(HTTP2Settings()), + frameEncoder: &self.serverEncoder, + frameDecoder: &self.serverDecoder + ) + ) // Client opens a stream - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: false)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: false)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: false + ) + ) // We can now do all of the streamy things. - assertSucceeds(self.client.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false)) - assertSucceeds(self.server.receiveData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false)) + assertSucceeds( + self.client.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false) + ) + assertSucceeds( + self.server.receiveData( + streamID: streamOne, + contentLength: 15, + flowControlledBytes: 15, + isEndStreamSet: false + ) + ) assertSucceeds(self.client.sendWindowUpdate(streamID: streamOne, windowIncrement: 1024)) assertSucceeds(self.server.receiveWindowUpdate(streamID: streamOne, windowIncrement: 1024)) assertSucceeds(self.client.sendRstStream(streamID: streamOne, reason: .noError)) @@ -887,9 +1905,19 @@ class ConnectionStateMachineTests: XCTestCase { // Server can bring the connection up by sending its own preface back. assertSucceeds(self.server.sendSettings(HTTP2Settings())) - assertSucceeds(self.client.receiveSettings(.settings(HTTP2Settings()), frameEncoder: &self.clientEncoder, frameDecoder: &self.clientDecoder)) - assertSucceeds(self.client.receiveSettings(.ack, frameEncoder: &self.clientEncoder, frameDecoder: &self.clientDecoder)) - assertSucceeds(self.server.receiveSettings(.ack, frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder)) + assertSucceeds( + self.client.receiveSettings( + .settings(HTTP2Settings()), + frameEncoder: &self.clientEncoder, + frameDecoder: &self.clientDecoder + ) + ) + assertSucceeds( + self.client.receiveSettings(.ack, frameEncoder: &self.clientEncoder, frameDecoder: &self.clientDecoder) + ) + assertSucceeds( + self.server.receiveSettings(.ack, frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder) + ) // Both sides quiesce, which will end the connection. assertSucceeds(self.client.sendGoaway(lastStreamID: .rootStream)) @@ -906,17 +1934,44 @@ class ConnectionStateMachineTests: XCTestCase { // Client sends preface. assertSucceeds(self.client.sendSettings(HTTP2Settings())) - assertSucceeds(self.server.receiveSettings(.settings(HTTP2Settings()), frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder)) + assertSucceeds( + self.server.receiveSettings( + .settings(HTTP2Settings()), + frameEncoder: &self.serverEncoder, + frameDecoder: &self.serverDecoder + ) + ) // Client quiesces, then opens a stream. assertSucceeds(self.client.sendGoaway(lastStreamID: .rootStream)) assertSucceeds(self.server.receiveGoaway(lastStreamID: .rootStream)) - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: false)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: false)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: false + ) + ) // We can now do all of the streamy things. - assertSucceeds(self.client.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false)) - assertSucceeds(self.server.receiveData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false)) + assertSucceeds( + self.client.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false) + ) + assertSucceeds( + self.server.receiveData( + streamID: streamOne, + contentLength: 15, + flowControlledBytes: 15, + isEndStreamSet: false + ) + ) assertSucceeds(self.client.sendWindowUpdate(streamID: streamOne, windowIncrement: 1024)) assertSucceeds(self.server.receiveWindowUpdate(streamID: streamOne, windowIncrement: 1024)) assertSucceeds(self.client.sendRstStream(streamID: streamOne, reason: .noError)) @@ -940,12 +1995,48 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble() // Client opens a stream, so does the server. - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: false)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: false)) - assertSucceeds(self.server.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.client.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.server.sendPushPromise(originalStreamID: streamOne, childStreamID: streamTwo, headers: ConnectionStateMachineTests.requestHeaders)) - assertSucceeds(self.client.receivePushPromise(originalStreamID: streamOne, childStreamID: streamTwo, headers: ConnectionStateMachineTests.requestHeaders)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.server.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.server.sendPushPromise( + originalStreamID: streamOne, + childStreamID: streamTwo, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) + assertSucceeds( + self.client.receivePushPromise( + originalStreamID: streamOne, + childStreamID: streamTwo, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) // Both sides quiesce this. assertSucceeds(self.client.sendGoaway(lastStreamID: streamTwo)) @@ -954,10 +2045,28 @@ class ConnectionStateMachineTests: XCTestCase { assertSucceeds(self.client.receiveGoaway(lastStreamID: streamOne)) // All the streamy operations work on stream one except push promise. - assertSucceeds(self.client.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false)) - assertSucceeds(self.server.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false)) - assertSucceeds(self.server.receiveData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false)) - assertSucceeds(self.client.receiveData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false)) + assertSucceeds( + self.client.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false) + ) + assertSucceeds( + self.server.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false) + ) + assertSucceeds( + self.server.receiveData( + streamID: streamOne, + contentLength: 15, + flowControlledBytes: 15, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.client.receiveData( + streamID: streamOne, + contentLength: 15, + flowControlledBytes: 15, + isEndStreamSet: false + ) + ) assertSucceeds(self.client.sendWindowUpdate(streamID: streamOne, windowIncrement: 1024)) assertSucceeds(self.server.sendWindowUpdate(streamID: streamOne, windowIncrement: 1024)) assertSucceeds(self.server.receiveWindowUpdate(streamID: streamOne, windowIncrement: 1024)) @@ -982,15 +2091,41 @@ class ConnectionStateMachineTests: XCTestCase { var temporaryServer = self.server! var temporaryClient = self.client! - assertConnectionError(type: .protocolError, temporaryServer.sendPushPromise(originalStreamID: streamOne, childStreamID: streamFour, headers: ConnectionStateMachineTests.requestHeaders)) - assertIgnored(temporaryClient.receivePushPromise(originalStreamID: streamOne, childStreamID: streamFour, headers: ConnectionStateMachineTests.requestHeaders)) + assertConnectionError( + type: .protocolError, + temporaryServer.sendPushPromise( + originalStreamID: streamOne, + childStreamID: streamFour, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) + assertIgnored( + temporaryClient.receivePushPromise( + originalStreamID: streamOne, + childStreamID: streamFour, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) // And the client cannot initiate a new stream with headers. temporaryServer = self.server! temporaryClient = self.client! - let error = assertConnectionError(type: .protocolError, temporaryClient.sendHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) + let error = assertConnectionError( + type: .protocolError, + temporaryClient.sendHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) XCTAssertEqual(error as? NIOHTTP2Errors.CreatedStreamAfterGoaway, NIOHTTP2Errors.createdStreamAfterGoaway()) - assertIgnored(temporaryServer.receiveHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) + assertIgnored( + temporaryServer.receiveHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) XCTAssertFalse(self.server.fullyQuiesced) XCTAssertFalse(self.client.fullyQuiesced) @@ -1009,12 +2144,36 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble() // Client sends headers - assertSucceeds(client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: false)) - assertSucceeds(server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: false)) + assertSucceeds( + client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: false + ) + ) // Server responds with headers - assertSucceeds(server.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(client.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) + assertSucceeds( + server.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + client.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) // Client sends a GOAWAY with lastStreamID = 0 assertGoawaySucceeds(client.sendGoaway(lastStreamID: 0), droppingStreams: nil) @@ -1034,8 +2193,20 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble() // Client opens a stream. - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) // The server sends goaway. assertSucceeds(self.server.sendGoaway(lastStreamID: streamOne)) @@ -1046,8 +2217,20 @@ class ConnectionStateMachineTests: XCTestCase { // Ok, there are two ways this stream can be closed: via headers, or via rst_stream. Either of these should cause the connection to be closed. var temporaryServer = self.server! var temporaryClient = self.client! - assertSucceeds(temporaryServer.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: true)) - assertSucceeds(temporaryClient.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: true)) + assertSucceeds( + temporaryServer.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + temporaryClient.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: true + ) + ) XCTAssertTrue(temporaryServer.fullyQuiesced) XCTAssertTrue(temporaryClient.fullyQuiesced) @@ -1070,21 +2253,73 @@ class ConnectionStateMachineTests: XCTestCase { assertSucceeds(self.client.receiveGoaway(lastStreamID: .rootStream)) // Stream specific things don't work. - assertConnectionError(type: .protocolError, self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertStreamError(type: .refusedStream, self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertConnectionError(type: .protocolError, self.client.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false)) - assertConnectionError(type: .protocolError, self.server.receiveData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false)) - assertConnectionError(type: .protocolError, self.client.sendWindowUpdate(streamID: streamOne, windowIncrement: 1024)) - assertConnectionError(type: .protocolError, self.server.receiveWindowUpdate(streamID: streamOne, windowIncrement: 1024)) + assertConnectionError( + type: .protocolError, + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertStreamError( + type: .refusedStream, + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertConnectionError( + type: .protocolError, + self.client.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false) + ) + assertConnectionError( + type: .protocolError, + self.server.receiveData( + streamID: streamOne, + contentLength: 15, + flowControlledBytes: 15, + isEndStreamSet: false + ) + ) + assertConnectionError( + type: .protocolError, + self.client.sendWindowUpdate(streamID: streamOne, windowIncrement: 1024) + ) + assertConnectionError( + type: .protocolError, + self.server.receiveWindowUpdate(streamID: streamOne, windowIncrement: 1024) + ) assertConnectionError(type: .protocolError, self.server.receiveRstStream(streamID: streamOne, reason: .noError)) - assertConnectionError(type: .protocolError, self.server.sendPushPromise(originalStreamID: streamOne, childStreamID: streamTwo, headers: ConnectionStateMachineTests.requestHeaders)) - assertConnectionError(type: .protocolError, self.client.receivePushPromise(originalStreamID: streamOne, childStreamID: streamTwo, headers: ConnectionStateMachineTests.requestHeaders)) + assertConnectionError( + type: .protocolError, + self.server.sendPushPromise( + originalStreamID: streamOne, + childStreamID: streamTwo, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) + assertConnectionError( + type: .protocolError, + self.client.receivePushPromise( + originalStreamID: streamOne, + childStreamID: streamTwo, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) // Connectiony things don't work either. assertConnectionError(type: .protocolError, self.client.sendPriority()) assertConnectionError(type: .protocolError, self.server.receivePriority()) assertConnectionError(type: .protocolError, self.client.sendSettings([])) - assertConnectionError(type: .protocolError, self.server.receiveSettings(.settings([]), frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder)) + assertConnectionError( + type: .protocolError, + self.server.receiveSettings( + .settings([]), + frameEncoder: &self.serverEncoder, + frameDecoder: &self.serverDecoder + ) + ) // Duplicate goaway is cool though. assertSucceeds(self.client.sendGoaway(lastStreamID: .rootStream)) @@ -1105,13 +2340,33 @@ class ConnectionStateMachineTests: XCTestCase { // Server sends its preface. assertSucceeds(self.server.sendSettings(HTTP2Settings())) - assertSucceeds(self.client.receiveSettings(.settings(HTTP2Settings()), frameEncoder: &self.clientEncoder, frameDecoder: &self.clientDecoder)) + assertSucceeds( + self.client.receiveSettings( + .settings(HTTP2Settings()), + frameEncoder: &self.clientEncoder, + frameDecoder: &self.clientDecoder + ) + ) // Pushing in this state fails. var temporaryServer = self.server! var temporaryClient = self.client! - assertConnectionError(type: .protocolError, temporaryServer.sendPushPromise(originalStreamID: streamOne, childStreamID: streamTwo, headers: ConnectionStateMachineTests.requestHeaders)) - assertConnectionError(type: .protocolError, temporaryClient.receivePushPromise(originalStreamID: streamOne, childStreamID: streamTwo, headers: ConnectionStateMachineTests.requestHeaders)) + assertConnectionError( + type: .protocolError, + temporaryServer.sendPushPromise( + originalStreamID: streamOne, + childStreamID: streamTwo, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) + assertConnectionError( + type: .protocolError, + temporaryClient.receivePushPromise( + originalStreamID: streamOne, + childStreamID: streamTwo, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) } func testClientsMayNotPush() { @@ -1120,32 +2375,90 @@ class ConnectionStateMachineTests: XCTestCase { // Client sends its preface. assertSucceeds(self.client.sendSettings([])) - assertSucceeds(self.server.receiveSettings(.settings([]), frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder)) + assertSucceeds( + self.server.receiveSettings( + .settings([]), + frameEncoder: &self.serverEncoder, + frameDecoder: &self.serverDecoder + ) + ) // The client may not push here. var temporaryServer = self.server! var temporaryClient = self.client! - assertConnectionError(type: .protocolError, temporaryClient.sendPushPromise(originalStreamID: streamOne, childStreamID: streamTwo, headers: ConnectionStateMachineTests.requestHeaders)) - assertConnectionError(type: .protocolError, temporaryServer.receivePushPromise(originalStreamID: streamOne, childStreamID: streamTwo, headers: ConnectionStateMachineTests.requestHeaders)) + assertConnectionError( + type: .protocolError, + temporaryClient.sendPushPromise( + originalStreamID: streamOne, + childStreamID: streamTwo, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) + assertConnectionError( + type: .protocolError, + temporaryServer.receivePushPromise( + originalStreamID: streamOne, + childStreamID: streamTwo, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) // What if the client now quiesced? temporaryServer = self.server! temporaryClient = self.client! assertSucceeds(temporaryClient.sendGoaway(lastStreamID: .rootStream)) assertSucceeds(temporaryServer.receiveGoaway(lastStreamID: .rootStream)) - assertConnectionError(type: .protocolError, temporaryClient.sendPushPromise(originalStreamID: streamOne, childStreamID: streamTwo, headers: ConnectionStateMachineTests.requestHeaders)) - assertConnectionError(type: .protocolError, temporaryServer.receivePushPromise(originalStreamID: streamOne, childStreamID: streamTwo, headers: ConnectionStateMachineTests.requestHeaders)) + assertConnectionError( + type: .protocolError, + temporaryClient.sendPushPromise( + originalStreamID: streamOne, + childStreamID: streamTwo, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) + assertConnectionError( + type: .protocolError, + temporaryServer.receivePushPromise( + originalStreamID: streamOne, + childStreamID: streamTwo, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) // What if the client became active? assertSucceeds(self.server.sendSettings([])) - assertSucceeds(self.server.receiveSettings(.ack, frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder)) - assertSucceeds(self.client.receiveSettings(.settings([]), frameEncoder: &self.clientEncoder, frameDecoder: &self.clientDecoder)) - assertSucceeds(self.client.receiveSettings(.ack, frameEncoder: &self.clientEncoder, frameDecoder: &self.clientDecoder)) + assertSucceeds( + self.server.receiveSettings(.ack, frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder) + ) + assertSucceeds( + self.client.receiveSettings( + .settings([]), + frameEncoder: &self.clientEncoder, + frameDecoder: &self.clientDecoder + ) + ) + assertSucceeds( + self.client.receiveSettings(.ack, frameEncoder: &self.clientEncoder, frameDecoder: &self.clientDecoder) + ) temporaryServer = self.server! temporaryClient = self.client! - assertConnectionError(type: .protocolError, temporaryClient.sendPushPromise(originalStreamID: streamOne, childStreamID: streamTwo, headers: ConnectionStateMachineTests.requestHeaders)) - assertConnectionError(type: .protocolError, temporaryServer.receivePushPromise(originalStreamID: streamOne, childStreamID: streamTwo, headers: ConnectionStateMachineTests.requestHeaders)) + assertConnectionError( + type: .protocolError, + temporaryClient.sendPushPromise( + originalStreamID: streamOne, + childStreamID: streamTwo, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) + assertConnectionError( + type: .protocolError, + temporaryServer.receivePushPromise( + originalStreamID: streamOne, + childStreamID: streamTwo, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) } func testMaySendSettingsInAllStates() { @@ -1153,9 +2466,21 @@ class ConnectionStateMachineTests: XCTestCase { // During setup, we can send settings. assertSucceeds(self.client.sendSettings([])) - assertSucceeds(self.server.receiveSettings(.settings([]), frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder)) + assertSucceeds( + self.server.receiveSettings( + .settings([]), + frameEncoder: &self.serverEncoder, + frameDecoder: &self.serverDecoder + ) + ) assertSucceeds(self.client.sendSettings([])) - assertSucceeds(self.server.receiveSettings(.settings([]), frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder)) + assertSucceeds( + self.server.receiveSettings( + .settings([]), + frameEncoder: &self.serverEncoder, + frameDecoder: &self.serverDecoder + ) + ) // If we quiesce during setup we can still send settings. var temporaryServer = self.server! @@ -1163,43 +2488,113 @@ class ConnectionStateMachineTests: XCTestCase { assertSucceeds(temporaryClient.sendGoaway(lastStreamID: .rootStream)) assertSucceeds(temporaryServer.receiveGoaway(lastStreamID: .rootStream)) assertSucceeds(temporaryClient.sendSettings([])) - assertSucceeds(temporaryServer.receiveSettings(.settings([]), frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder)) + assertSucceeds( + temporaryServer.receiveSettings( + .settings([]), + frameEncoder: &self.serverEncoder, + frameDecoder: &self.serverDecoder + ) + ) assertSucceeds(temporaryServer.sendSettings([])) - assertSucceeds(temporaryClient.receiveSettings(.settings([]), frameEncoder: &self.clientEncoder, frameDecoder: &self.clientDecoder)) + assertSucceeds( + temporaryClient.receiveSettings( + .settings([]), + frameEncoder: &self.clientEncoder, + frameDecoder: &self.clientDecoder + ) + ) // We can also activate. assertSucceeds(self.server.sendSettings([])) - assertSucceeds(self.server.receiveSettings(.ack, frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder)) - assertSucceeds(self.client.receiveSettings(.settings([]), frameEncoder: &self.clientEncoder, frameDecoder: &self.clientDecoder)) - assertSucceeds(self.client.receiveSettings(.ack, frameEncoder: &self.clientEncoder, frameDecoder: &self.clientDecoder)) + assertSucceeds( + self.server.receiveSettings(.ack, frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder) + ) + assertSucceeds( + self.client.receiveSettings( + .settings([]), + frameEncoder: &self.clientEncoder, + frameDecoder: &self.clientDecoder + ) + ) + assertSucceeds( + self.client.receiveSettings(.ack, frameEncoder: &self.clientEncoder, frameDecoder: &self.clientDecoder) + ) // When active we can send settings. temporaryServer = self.server! temporaryClient = self.client! assertSucceeds(temporaryClient.sendSettings([])) - assertSucceeds(temporaryServer.receiveSettings(.settings([]), frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder)) + assertSucceeds( + temporaryServer.receiveSettings( + .settings([]), + frameEncoder: &self.serverEncoder, + frameDecoder: &self.serverDecoder + ) + ) assertSucceeds(temporaryServer.sendSettings([])) - assertSucceeds(temporaryClient.receiveSettings(.settings([]), frameEncoder: &self.clientEncoder, frameDecoder: &self.clientDecoder)) + assertSucceeds( + temporaryClient.receiveSettings( + .settings([]), + frameEncoder: &self.clientEncoder, + frameDecoder: &self.clientDecoder + ) + ) // When quiesced by one peer we can send settings. assertSucceeds(self.client.sendGoaway(lastStreamID: .rootStream)) assertSucceeds(self.server.receiveGoaway(lastStreamID: .rootStream)) assertSucceeds(self.client.sendSettings([])) - assertSucceeds(self.server.receiveSettings(.settings([]), frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder)) + assertSucceeds( + self.server.receiveSettings( + .settings([]), + frameEncoder: &self.serverEncoder, + frameDecoder: &self.serverDecoder + ) + ) assertSucceeds(self.server.sendSettings([])) - assertSucceeds(self.client.receiveSettings(.settings([]), frameEncoder: &self.clientEncoder, frameDecoder: &self.clientDecoder)) + assertSucceeds( + self.client.receiveSettings( + .settings([]), + frameEncoder: &self.clientEncoder, + frameDecoder: &self.clientDecoder + ) + ) // Bring up a stream just to keep the system from shutting down. - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) // Now quiesce the other way. We can still send settings. assertSucceeds(self.server.sendGoaway(lastStreamID: streamOne)) assertSucceeds(self.client.receiveGoaway(lastStreamID: streamOne)) assertSucceeds(self.client.sendSettings([])) - assertSucceeds(self.server.receiveSettings(.settings([]), frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder)) + assertSucceeds( + self.server.receiveSettings( + .settings([]), + frameEncoder: &self.serverEncoder, + frameDecoder: &self.serverDecoder + ) + ) assertSucceeds(self.server.sendSettings([])) - assertSucceeds(self.client.receiveSettings(.settings([]), frameEncoder: &self.clientEncoder, frameDecoder: &self.clientDecoder)) + assertSucceeds( + self.client.receiveSettings( + .settings([]), + frameEncoder: &self.clientEncoder, + frameDecoder: &self.clientDecoder + ) + ) } func testValidatingFlowControlOnFullyActiveConnections() { @@ -1207,15 +2602,53 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble() - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: false)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: false)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: false + ) + ) - assertSucceeds(self.server.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.client.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) + assertSucceeds( + self.server.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) // The default value of the flow control window is 65535. So let's see if we can hit it. First, let's send 65535 bytes from client to server. - assertSucceeds(self.client.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 65535, isEndStreamSet: false)) - assertSucceeds(self.server.receiveData(streamID: streamOne, contentLength: 15, flowControlledBytes: 65535, isEndStreamSet: false)) + assertSucceeds( + self.client.sendData( + streamID: streamOne, + contentLength: 15, + flowControlledBytes: 65535, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.server.receiveData( + streamID: streamOne, + contentLength: 15, + flowControlledBytes: 65535, + isEndStreamSet: false + ) + ) // Now the server opens the *stream window only*. assertSucceeds(self.server.sendWindowUpdate(streamID: streamOne, windowIncrement: 1000)) @@ -1224,38 +2657,121 @@ class ConnectionStateMachineTests: XCTestCase { // The client cannot send more than one byte on this stream. var temporaryServer = self.server! var temporaryClient = self.client! - assertConnectionError(type: .flowControlError, temporaryClient.sendData(streamID: streamOne, contentLength: 1, flowControlledBytes: 1, isEndStreamSet: false)) - assertConnectionError(type: .flowControlError, temporaryServer.receiveData(streamID: streamOne, contentLength: 1, flowControlledBytes: 1, isEndStreamSet: false)) + assertConnectionError( + type: .flowControlError, + temporaryClient.sendData( + streamID: streamOne, + contentLength: 1, + flowControlledBytes: 1, + isEndStreamSet: false + ) + ) + assertConnectionError( + type: .flowControlError, + temporaryServer.receiveData( + streamID: streamOne, + contentLength: 1, + flowControlledBytes: 1, + isEndStreamSet: false + ) + ) // Now the server opens the connection flow control window. assertSucceeds(self.server.sendWindowUpdate(streamID: .rootStream, windowIncrement: 65535)) assertSucceeds(self.client.receiveWindowUpdate(streamID: .rootStream, windowIncrement: 65535)) // The client may now send 1000 bytes. - assertSucceeds(self.client.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 1000, isEndStreamSet: false)) - assertSucceeds(self.server.receiveData(streamID: streamOne, contentLength: 15, flowControlledBytes: 1000, isEndStreamSet: false)) + assertSucceeds( + self.client.sendData( + streamID: streamOne, + contentLength: 15, + flowControlledBytes: 1000, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.server.receiveData( + streamID: streamOne, + contentLength: 15, + flowControlledBytes: 1000, + isEndStreamSet: false + ) + ) // But any attempt to send more fails, again. temporaryServer = self.server! temporaryClient = self.client! - assertStreamError(type: .flowControlError, temporaryClient.sendData(streamID: streamOne, contentLength: 1, flowControlledBytes: 1, isEndStreamSet: false)) - assertStreamError(type: .flowControlError, temporaryServer.receiveData(streamID: streamOne, contentLength: 1, flowControlledBytes: 1, isEndStreamSet: false)) + assertStreamError( + type: .flowControlError, + temporaryClient.sendData( + streamID: streamOne, + contentLength: 1, + flowControlledBytes: 1, + isEndStreamSet: false + ) + ) + assertStreamError( + type: .flowControlError, + temporaryServer.receiveData( + streamID: streamOne, + contentLength: 1, + flowControlledBytes: 1, + isEndStreamSet: false + ) + ) // The server can increase the flow control window by sending a SETTINGS frame with the appropriate new setting. // This adds 1000 to the window size. assertSucceeds(self.server.sendSettings([HTTP2Setting(parameter: .initialWindowSize, value: 66535)])) - assertSucceeds(self.client.receiveSettings(.settings([HTTP2Setting(parameter: .initialWindowSize, value: 66535)]), frameEncoder: &self.clientEncoder, frameDecoder: &self.clientDecoder)) + assertSucceeds( + self.client.receiveSettings( + .settings([HTTP2Setting(parameter: .initialWindowSize, value: 66535)]), + frameEncoder: &self.clientEncoder, + frameDecoder: &self.clientDecoder + ) + ) // In this state, the client may send new data, but if the server doesn't receive the ACK first it holds the client to the new value. temporaryServer = self.server! temporaryClient = self.client! - assertSucceeds(temporaryClient.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 1000, isEndStreamSet: false)) - assertStreamError(type: .flowControlError, temporaryServer.receiveData(streamID: streamOne, contentLength: 15, flowControlledBytes: 1000, isEndStreamSet: false)) + assertSucceeds( + temporaryClient.sendData( + streamID: streamOne, + contentLength: 15, + flowControlledBytes: 1000, + isEndStreamSet: false + ) + ) + assertStreamError( + type: .flowControlError, + temporaryServer.receiveData( + streamID: streamOne, + contentLength: 15, + flowControlledBytes: 1000, + isEndStreamSet: false + ) + ) // Once the server receives the ACK, it's fine. - assertSucceeds(self.server.receiveSettings(.ack, frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder)) - assertSucceeds(self.client.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 1000, isEndStreamSet: false)) - assertSucceeds(self.server.receiveData(streamID: streamOne, contentLength: 15, flowControlledBytes: 1000, isEndStreamSet: false)) + assertSucceeds( + self.server.receiveSettings(.ack, frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder) + ) + assertSucceeds( + self.client.sendData( + streamID: streamOne, + contentLength: 15, + flowControlledBytes: 1000, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.server.receiveData( + streamID: streamOne, + contentLength: 15, + flowControlledBytes: 1000, + isEndStreamSet: false + ) + ) // Open the flow control window of the stream. assertSucceeds(self.server.sendWindowUpdate(streamID: streamOne, windowIncrement: 65535)) @@ -1263,10 +2779,35 @@ class ConnectionStateMachineTests: XCTestCase { // At this stage the stream has a window size of 65535, but the connection should not have gained the extra 2000 bytes from the change in // SETTINGS_INITIAL_WINDOW_SIZE, so it should have a size of 63535. Verify this by exceeding it. - assertSucceeds(self.client.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 63535, isEndStreamSet: false)) - assertSucceeds(self.server.receiveData(streamID: streamOne, contentLength: 15, flowControlledBytes: 63535, isEndStreamSet: false)) - assertConnectionError(type: .flowControlError, self.client.sendData(streamID: streamOne, contentLength: 1, flowControlledBytes: 1, isEndStreamSet: false)) - assertConnectionError(type: .flowControlError, self.server.receiveData(streamID: streamOne, contentLength: 1, flowControlledBytes: 1, isEndStreamSet: false)) + assertSucceeds( + self.client.sendData( + streamID: streamOne, + contentLength: 15, + flowControlledBytes: 63535, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.server.receiveData( + streamID: streamOne, + contentLength: 15, + flowControlledBytes: 63535, + isEndStreamSet: false + ) + ) + assertConnectionError( + type: .flowControlError, + self.client.sendData(streamID: streamOne, contentLength: 1, flowControlledBytes: 1, isEndStreamSet: false) + ) + assertConnectionError( + type: .flowControlError, + self.server.receiveData( + streamID: streamOne, + contentLength: 1, + flowControlledBytes: 1, + isEndStreamSet: false + ) + ) } func testTrailersWithoutData() { @@ -1274,17 +2815,65 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble() - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: false)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: false)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: false + ) + ) - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.trailers, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.trailers, isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.trailers, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.trailers, + isEndStreamSet: true + ) + ) - assertSucceeds(self.server.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.client.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) + assertSucceeds( + self.server.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) - assertSucceeds(self.server.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.trailers, isEndStreamSet: true)) - assertSucceeds(self.client.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.trailers, isEndStreamSet: true)) + assertSucceeds( + self.server.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.trailers, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.trailers, + isEndStreamSet: true + ) + ) } func testServerResponseEndsBeforeRequestFinishes() { @@ -1292,14 +2881,52 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble() - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: false)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: false)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: false + ) + ) - assertSucceeds(self.server.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: true)) - assertSucceeds(self.client.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: true)) + assertSucceeds( + self.server.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: true + ) + ) - assertSucceeds(self.client.sendData(streamID: streamOne, contentLength: 1024, flowControlledBytes: 1024, isEndStreamSet: true)) - assertSucceeds(self.server.receiveData(streamID: streamOne, contentLength: 1024, flowControlledBytes: 1024, isEndStreamSet: true)) + assertSucceeds( + self.client.sendData( + streamID: streamOne, + contentLength: 1024, + flowControlledBytes: 1024, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveData( + streamID: streamOne, + contentLength: 1024, + flowControlledBytes: 1024, + isEndStreamSet: true + ) + ) } func testPushedResponsesMayHaveBodies() { @@ -1308,20 +2935,82 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble() - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: false)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: false)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: false + ) + ) - assertSucceeds(self.server.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.client.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) + assertSucceeds( + self.server.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) - assertSucceeds(self.server.sendPushPromise(originalStreamID: streamOne, childStreamID: streamTwo, headers: ConnectionStateMachineTests.requestHeaders)) - assertSucceeds(self.client.receivePushPromise(originalStreamID: streamOne, childStreamID: streamTwo, headers: ConnectionStateMachineTests.requestHeaders)) + assertSucceeds( + self.server.sendPushPromise( + originalStreamID: streamOne, + childStreamID: streamTwo, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) + assertSucceeds( + self.client.receivePushPromise( + originalStreamID: streamOne, + childStreamID: streamTwo, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) - assertSucceeds(self.server.sendHeaders(streamID: streamTwo, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.client.receiveHeaders(streamID: streamTwo, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) + assertSucceeds( + self.server.sendHeaders( + streamID: streamTwo, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamTwo, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) - assertSucceeds(self.server.sendData(streamID: streamTwo, contentLength: 1024, flowControlledBytes: 1024, isEndStreamSet: true)) - assertSucceeds(self.client.receiveData(streamID: streamTwo, contentLength: 1024, flowControlledBytes: 1024, isEndStreamSet: true)) + assertSucceeds( + self.server.sendData( + streamID: streamTwo, + contentLength: 1024, + flowControlledBytes: 1024, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.client.receiveData( + streamID: streamTwo, + contentLength: 1024, + flowControlledBytes: 1024, + isEndStreamSet: true + ) + ) } func testDataFramesWithoutEndStream() { @@ -1330,22 +3019,97 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble() // We can send some DATA frames while only the client has opened. - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: false)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: false)) - assertSucceeds(self.client.sendData(streamID: streamOne, contentLength: 1024, flowControlledBytes: 1024, isEndStreamSet: false)) - assertSucceeds(self.server.receiveData(streamID: streamOne, contentLength: 1024, flowControlledBytes: 1024, isEndStreamSet: false)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.client.sendData( + streamID: streamOne, + contentLength: 1024, + flowControlledBytes: 1024, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.server.receiveData( + streamID: streamOne, + contentLength: 1024, + flowControlledBytes: 1024, + isEndStreamSet: false + ) + ) // We can send some more while the server has opened. - assertSucceeds(self.server.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.client.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.client.sendData(streamID: streamOne, contentLength: 1024, flowControlledBytes: 1024, isEndStreamSet: false)) - assertSucceeds(self.server.receiveData(streamID: streamOne, contentLength: 1024, flowControlledBytes: 1024, isEndStreamSet: false)) + assertSucceeds( + self.server.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.client.sendData( + streamID: streamOne, + contentLength: 1024, + flowControlledBytes: 1024, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.server.receiveData( + streamID: streamOne, + contentLength: 1024, + flowControlledBytes: 1024, + isEndStreamSet: false + ) + ) // And we can send some after the server is done. - assertSucceeds(self.server.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: true)) - assertSucceeds(self.client.receiveData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: true)) - assertSucceeds(self.client.sendData(streamID: streamOne, contentLength: 1024, flowControlledBytes: 1024, isEndStreamSet: false)) - assertSucceeds(self.server.receiveData(streamID: streamOne, contentLength: 1024, flowControlledBytes: 1024, isEndStreamSet: false)) + assertSucceeds( + self.server.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: true) + ) + assertSucceeds( + self.client.receiveData( + streamID: streamOne, + contentLength: 15, + flowControlledBytes: 15, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.client.sendData( + streamID: streamOne, + contentLength: 1024, + flowControlledBytes: 1024, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.server.receiveData( + streamID: streamOne, + contentLength: 1024, + flowControlledBytes: 1024, + isEndStreamSet: false + ) + ) } func testSendingCompleteRequestBeforeResponse() { @@ -1354,16 +3118,63 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble() // We can send a complete request before the remote peer sends us anything. - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: false)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: false)) - assertSucceeds(self.client.sendData(streamID: streamOne, contentLength: 1024, flowControlledBytes: 1024, isEndStreamSet: true)) - assertSucceeds(self.server.receiveData(streamID: streamOne, contentLength: 1024, flowControlledBytes: 1024, isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.client.sendData( + streamID: streamOne, + contentLength: 1024, + flowControlledBytes: 1024, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveData( + streamID: streamOne, + contentLength: 1024, + flowControlledBytes: 1024, + isEndStreamSet: true + ) + ) // The remote peer can then respond. - assertSucceeds(self.server.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.client.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.server.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: true)) - assertSucceeds(self.client.receiveData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: true)) + assertSucceeds( + self.server.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.server.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: true) + ) + assertSucceeds( + self.client.receiveData( + streamID: streamOne, + contentLength: 15, + flowControlledBytes: 15, + isEndStreamSet: true + ) + ) } func testWindowUpdateValidity() { @@ -1373,72 +3184,188 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble() // WindowUpdate frames are valid in a wide range of states. This test validates them in all of them, including proving that errors are correctly reported. - func assertCanWindowUpdate(client: HTTP2ConnectionStateMachine, server: HTTP2ConnectionStateMachine, file: StaticString = #filePath, line: UInt = #line) { + func assertCanWindowUpdate( + client: HTTP2ConnectionStateMachine, + server: HTTP2ConnectionStateMachine, + file: StaticString = #filePath, + line: UInt = #line + ) { var client = client var server = server assertSucceeds(client.sendWindowUpdate(streamID: streamOne, windowIncrement: 10), file: (file), line: line) - assertSucceeds(server.receiveWindowUpdate(streamID: streamOne, windowIncrement: 10), file: (file), line: line) - assertStreamError(type: .flowControlError, client.sendWindowUpdate(streamID: streamOne, windowIncrement: UInt32(Int32.max)), file: (file), line: line) - assertStreamError(type: .flowControlError, server.receiveWindowUpdate(streamID: streamOne, windowIncrement: UInt32(Int32.max)), file: (file), line: line) + assertSucceeds( + server.receiveWindowUpdate(streamID: streamOne, windowIncrement: 10), + file: (file), + line: line + ) + assertStreamError( + type: .flowControlError, + client.sendWindowUpdate(streamID: streamOne, windowIncrement: UInt32(Int32.max)), + file: (file), + line: line + ) + assertStreamError( + type: .flowControlError, + server.receiveWindowUpdate(streamID: streamOne, windowIncrement: UInt32(Int32.max)), + file: (file), + line: line + ) assertSucceeds(server.sendWindowUpdate(streamID: streamOne, windowIncrement: 10), file: (file), line: line) - assertSucceeds(client.receiveWindowUpdate(streamID: streamOne, windowIncrement: 10), file: (file), line: line) - assertStreamError(type: .flowControlError, server.sendWindowUpdate(streamID: streamOne, windowIncrement: UInt32(Int32.max)), file: (file), line: line) - assertStreamError(type: .flowControlError, client.receiveWindowUpdate(streamID: streamOne, windowIncrement: UInt32(Int32.max)), file: (file), line: line) + assertSucceeds( + client.receiveWindowUpdate(streamID: streamOne, windowIncrement: 10), + file: (file), + line: line + ) + assertStreamError( + type: .flowControlError, + server.sendWindowUpdate(streamID: streamOne, windowIncrement: UInt32(Int32.max)), + file: (file), + line: line + ) + assertStreamError( + type: .flowControlError, + client.receiveWindowUpdate(streamID: streamOne, windowIncrement: UInt32(Int32.max)), + file: (file), + line: line + ) } - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: false)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: false)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: false + ) + ) assertCanWindowUpdate(client: self.client, server: self.server) var tempClient = self.client! var tempServer = self.server! // If we close the client side of the stream, it's ok for the client to send. The server may not send, but the client will tolerate it. - assertSucceeds(tempClient.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: true)) - assertSucceeds(tempServer.receiveData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: true)) + assertSucceeds( + tempClient.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: true) + ) + assertSucceeds( + tempServer.receiveData( + streamID: streamOne, + contentLength: 15, + flowControlledBytes: 15, + isEndStreamSet: true + ) + ) assertSucceeds(tempClient.sendWindowUpdate(streamID: streamOne, windowIncrement: 10)) assertSucceeds(tempServer.receiveWindowUpdate(streamID: streamOne, windowIncrement: 10)) - assertStreamError(type: .flowControlError, tempClient.sendWindowUpdate(streamID: streamOne, windowIncrement: UInt32(Int32.max))) - assertStreamError(type: .flowControlError, tempServer.receiveWindowUpdate(streamID: streamOne, windowIncrement: UInt32(Int32.max))) + assertStreamError( + type: .flowControlError, + tempClient.sendWindowUpdate(streamID: streamOne, windowIncrement: UInt32(Int32.max)) + ) + assertStreamError( + type: .flowControlError, + tempServer.receiveWindowUpdate(streamID: streamOne, windowIncrement: UInt32(Int32.max)) + ) assertStreamError(type: .protocolError, tempServer.sendWindowUpdate(streamID: streamOne, windowIncrement: 10)) assertSucceeds(tempClient.receiveWindowUpdate(streamID: streamOne, windowIncrement: 10)) - assertStreamError(type: .protocolError, tempServer.sendWindowUpdate(streamID: streamOne, windowIncrement: UInt32(Int32.max))) - assertSucceeds(tempClient.receiveWindowUpdate(streamID: streamOne, windowIncrement: UInt32(Int32.max))) // Weird, but we don't have the data to enforce this. + assertStreamError( + type: .protocolError, + tempServer.sendWindowUpdate(streamID: streamOne, windowIncrement: UInt32(Int32.max)) + ) + // Weird, but we don't have the data to enforce this. + assertSucceeds(tempClient.receiveWindowUpdate(streamID: streamOne, windowIncrement: UInt32(Int32.max))) // If the server is active, it's fine. - assertSucceeds(self.server.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.client.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) + assertSucceeds( + self.server.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) assertCanWindowUpdate(client: self.client, server: self.server) // If we close now it's ok for the client to send. The server may not send, but the client will tolerate it. - assertSucceeds(self.client.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: true)) - assertSucceeds(self.server.receiveData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: true)) + assertSucceeds( + self.client.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: true) + ) + assertSucceeds( + self.server.receiveData( + streamID: streamOne, + contentLength: 15, + flowControlledBytes: 15, + isEndStreamSet: true + ) + ) tempClient = self.client! tempServer = self.server! assertSucceeds(tempClient.sendWindowUpdate(streamID: streamOne, windowIncrement: 10)) assertSucceeds(tempServer.receiveWindowUpdate(streamID: streamOne, windowIncrement: 10)) - assertStreamError(type: .flowControlError, tempClient.sendWindowUpdate(streamID: streamOne, windowIncrement: UInt32(Int32.max))) - assertStreamError(type: .flowControlError, tempServer.receiveWindowUpdate(streamID: streamOne, windowIncrement: UInt32(Int32.max))) + assertStreamError( + type: .flowControlError, + tempClient.sendWindowUpdate(streamID: streamOne, windowIncrement: UInt32(Int32.max)) + ) + assertStreamError( + type: .flowControlError, + tempServer.receiveWindowUpdate(streamID: streamOne, windowIncrement: UInt32(Int32.max)) + ) assertStreamError(type: .protocolError, server.sendWindowUpdate(streamID: streamOne, windowIncrement: 10)) assertSucceeds(client.receiveWindowUpdate(streamID: streamOne, windowIncrement: 10)) - assertStreamError(type: .protocolError, server.sendWindowUpdate(streamID: streamOne, windowIncrement: UInt32(Int32.max))) - assertSucceeds(client.receiveWindowUpdate(streamID: streamOne, windowIncrement: UInt32(Int32.max))) // Weird, but we don't have the data to enforce this. + assertStreamError( + type: .protocolError, + server.sendWindowUpdate(streamID: streamOne, windowIncrement: UInt32(Int32.max)) + ) + // Weird, but we don't have the data to enforce this. + assertSucceeds(client.receiveWindowUpdate(streamID: streamOne, windowIncrement: UInt32(Int32.max))) // What if the server pushes? This one is actually a bit tricky: the client is allowed to, but the server is not. - assertSucceeds(self.server.sendPushPromise(originalStreamID: streamOne, childStreamID: streamTwo, headers: ConnectionStateMachineTests.requestHeaders)) - assertSucceeds(self.client.receivePushPromise(originalStreamID: streamOne, childStreamID: streamTwo, headers: ConnectionStateMachineTests.requestHeaders)) + assertSucceeds( + self.server.sendPushPromise( + originalStreamID: streamOne, + childStreamID: streamTwo, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) + assertSucceeds( + self.client.receivePushPromise( + originalStreamID: streamOne, + childStreamID: streamTwo, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) tempClient = self.client! tempServer = self.server! assertSucceeds(tempClient.sendWindowUpdate(streamID: streamTwo, windowIncrement: 15)) assertSucceeds(tempServer.receiveWindowUpdate(streamID: streamTwo, windowIncrement: 15)) - assertStreamError(type: .flowControlError, tempClient.sendWindowUpdate(streamID: streamTwo, windowIncrement: UInt32(Int32.max))) - assertStreamError(type: .flowControlError, tempServer.receiveWindowUpdate(streamID: streamTwo, windowIncrement: UInt32(Int32.max))) + assertStreamError( + type: .flowControlError, + tempClient.sendWindowUpdate(streamID: streamTwo, windowIncrement: UInt32(Int32.max)) + ) + assertStreamError( + type: .flowControlError, + tempServer.receiveWindowUpdate(streamID: streamTwo, windowIncrement: UInt32(Int32.max)) + ) assertStreamError(type: .protocolError, tempServer.sendWindowUpdate(streamID: streamTwo, windowIncrement: 15)) - assertStreamError(type: .protocolError, tempClient.receiveWindowUpdate(streamID: streamTwo, windowIncrement: 15)) + assertStreamError( + type: .protocolError, + tempClient.receiveWindowUpdate(streamID: streamTwo, windowIncrement: 15) + ) } func testWindowUpdateOnClosedStream() { @@ -1447,28 +3374,60 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble() // Client sends a request. - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: false)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: false)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: false + ) + ) // Server sends a response. - assertSucceeds(self.server.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.client.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) + assertSucceeds( + self.server.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) // Client sends end stream, server receives end stream. - assertSucceeds(self.client.sendData(streamID: streamOne, contentLength: 0, flowControlledBytes: 0, isEndStreamSet: true)) - assertSucceeds(self.server.receiveData(streamID: streamOne, contentLength: 0, flowControlledBytes: 0, isEndStreamSet: true)) + assertSucceeds( + self.client.sendData(streamID: streamOne, contentLength: 0, flowControlledBytes: 0, isEndStreamSet: true) + ) + assertSucceeds( + self.server.receiveData(streamID: streamOne, contentLength: 0, flowControlledBytes: 0, isEndStreamSet: true) + ) // Client is now half closed (local), server is half closed (remote) // Server sends end stream and is now closed. - assertSucceeds(self.server.sendData(streamID: streamOne, contentLength: 0, flowControlledBytes: 0, isEndStreamSet: true)) + assertSucceeds( + self.server.sendData(streamID: streamOne, contentLength: 0, flowControlledBytes: 0, isEndStreamSet: true) + ) // Client is half closed and sends window update, the server MUST ignore this. assertSucceeds(self.client.sendWindowUpdate(streamID: streamOne, windowIncrement: 10)) assertIgnored(self.server.receiveWindowUpdate(streamID: streamOne, windowIncrement: 10)) // Client receives end stream and closes. - assertSucceeds(self.client.receiveData(streamID: streamOne, contentLength: 0, flowControlledBytes: 0, isEndStreamSet: true)) + assertSucceeds( + self.client.receiveData(streamID: streamOne, contentLength: 0, flowControlledBytes: 0, isEndStreamSet: true) + ) } func testWindowIncrementsOfSizeZeroArentOk() { @@ -1476,8 +3435,20 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble() - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: false)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: false)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: false + ) + ) var tempClient = self.client! var tempServer = self.server! @@ -1486,8 +3457,14 @@ class ConnectionStateMachineTests: XCTestCase { tempClient = self.client! tempServer = self.server! - assertConnectionError(type: .protocolError, tempClient.sendWindowUpdate(streamID: .rootStream, windowIncrement: 0)) - assertConnectionError(type: .protocolError, tempServer.receiveWindowUpdate(streamID: .rootStream, windowIncrement: 0)) + assertConnectionError( + type: .protocolError, + tempClient.sendWindowUpdate(streamID: .rootStream, windowIncrement: 0) + ) + assertConnectionError( + type: .protocolError, + tempServer.receiveWindowUpdate(streamID: .rootStream, windowIncrement: 0) + ) } func testCannotSendDataFrames() { @@ -1501,50 +3478,184 @@ class ConnectionStateMachineTests: XCTestCase { var tempServer = self.server! // We can't do it before we've opened a stream. - assertConnectionError(type: .protocolError, tempClient.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false)) - assertConnectionError(type: .protocolError, tempServer.receiveData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false)) + assertConnectionError( + type: .protocolError, + tempClient.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false) + ) + assertConnectionError( + type: .protocolError, + tempServer.receiveData( + streamID: streamOne, + contentLength: 15, + flowControlledBytes: 15, + isEndStreamSet: false + ) + ) - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) // We can't send it after we have sent end stream, or before we've sent our headers. tempClient = self.client! tempServer = self.server! - assertStreamError(type: .streamClosed, tempClient.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false)) - assertStreamError(type: .streamClosed, tempServer.receiveData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false)) - assertStreamError(type: .streamClosed, tempServer.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false)) - assertStreamError(type: .streamClosed, tempClient.receiveData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false)) + assertStreamError( + type: .streamClosed, + tempClient.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false) + ) + assertStreamError( + type: .streamClosed, + tempServer.receiveData( + streamID: streamOne, + contentLength: 15, + flowControlledBytes: 15, + isEndStreamSet: false + ) + ) + assertStreamError( + type: .streamClosed, + tempServer.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false) + ) + assertStreamError( + type: .streamClosed, + tempClient.receiveData( + streamID: streamOne, + contentLength: 15, + flowControlledBytes: 15, + isEndStreamSet: false + ) + ) - assertSucceeds(self.server.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.client.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) + assertSucceeds( + self.server.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) // The client still can't do it, regardless of what the server just did. tempClient = self.client! tempServer = self.server! - assertStreamError(type: .streamClosed, tempClient.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false)) - assertStreamError(type: .streamClosed, tempServer.receiveData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false)) + assertStreamError( + type: .streamClosed, + tempClient.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false) + ) + assertStreamError( + type: .streamClosed, + tempServer.receiveData( + streamID: streamOne, + contentLength: 15, + flowControlledBytes: 15, + isEndStreamSet: false + ) + ) - assertSucceeds(self.server.sendPushPromise(originalStreamID: streamOne, childStreamID: streamTwo, headers: ConnectionStateMachineTests.requestHeaders)) - assertSucceeds(self.client.receivePushPromise(originalStreamID: streamOne, childStreamID: streamTwo, headers: ConnectionStateMachineTests.requestHeaders)) - assertSucceeds(self.server.sendHeaders(streamID: streamTwo, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.client.receiveHeaders(streamID: streamTwo, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) + assertSucceeds( + self.server.sendPushPromise( + originalStreamID: streamOne, + childStreamID: streamTwo, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) + assertSucceeds( + self.client.receivePushPromise( + originalStreamID: streamOne, + childStreamID: streamTwo, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) + assertSucceeds( + self.server.sendHeaders( + streamID: streamTwo, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamTwo, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) // The client can't send on pushed streams either. tempClient = self.client! tempServer = self.server! - assertStreamError(type: .streamClosed, tempClient.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false)) - assertStreamError(type: .streamClosed, tempServer.receiveData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false)) + assertStreamError( + type: .streamClosed, + tempClient.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false) + ) + assertStreamError( + type: .streamClosed, + tempServer.receiveData( + streamID: streamOne, + contentLength: 15, + flowControlledBytes: 15, + isEndStreamSet: false + ) + ) - assertSucceeds(self.server.sendData(streamID: streamTwo, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: true)) - assertSucceeds(self.client.receiveData(streamID: streamTwo, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: true)) + assertSucceeds( + self.server.sendData(streamID: streamTwo, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: true) + ) + assertSucceeds( + self.client.receiveData( + streamID: streamTwo, + contentLength: 15, + flowControlledBytes: 15, + isEndStreamSet: true + ) + ) // Neither peer can send on closed streams. tempClient = self.client! tempServer = self.server! - assertConnectionError(type: .streamClosed, tempClient.sendData(streamID: streamTwo, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false)) - assertConnectionError(type: .streamClosed, tempServer.receiveData(streamID: streamTwo, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false)) - assertConnectionError(type: .streamClosed, tempServer.sendData(streamID: streamTwo, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false)) - assertConnectionError(type: .streamClosed, tempClient.receiveData(streamID: streamTwo, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false)) + assertConnectionError( + type: .streamClosed, + tempClient.sendData(streamID: streamTwo, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false) + ) + assertConnectionError( + type: .streamClosed, + tempServer.receiveData( + streamID: streamTwo, + contentLength: 15, + flowControlledBytes: 15, + isEndStreamSet: false + ) + ) + assertConnectionError( + type: .streamClosed, + tempServer.sendData(streamID: streamTwo, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false) + ) + assertConnectionError( + type: .streamClosed, + tempClient.receiveData( + streamID: streamTwo, + contentLength: 15, + flowControlledBytes: 15, + isEndStreamSet: false + ) + ) } func testChangingInitialWindowSizeLotsOfStreams() { @@ -1558,38 +3669,162 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble() // We're going to set up several streams in different states, and then mess with the flow control window in all of them at the same time. - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) - assertSucceeds(self.client.sendHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: false)) - assertSucceeds(self.server.receiveHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: false)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: false + ) + ) - assertSucceeds(self.client.sendHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: false)) - assertSucceeds(self.server.receiveHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: false)) - assertSucceeds(self.server.sendHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.client.receiveHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.server.sendHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) - assertSucceeds(self.client.sendHeaders(streamID: streamSeven, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamSeven, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.sendHeaders(streamID: streamSeven, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.client.receiveHeaders(streamID: streamSeven, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamSeven, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamSeven, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.sendHeaders( + streamID: streamSeven, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamSeven, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) - assertSucceeds(self.server.sendPushPromise(originalStreamID: streamFive, childStreamID: streamTwo, headers: ConnectionStateMachineTests.requestHeaders)) - assertSucceeds(self.client.receivePushPromise(originalStreamID: streamFive, childStreamID: streamTwo, headers: ConnectionStateMachineTests.requestHeaders)) + assertSucceeds( + self.server.sendPushPromise( + originalStreamID: streamFive, + childStreamID: streamTwo, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) + assertSucceeds( + self.client.receivePushPromise( + originalStreamID: streamFive, + childStreamID: streamTwo, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) - assertSucceeds(self.server.sendPushPromise(originalStreamID: streamFive, childStreamID: streamFour, headers: ConnectionStateMachineTests.requestHeaders)) - assertSucceeds(self.client.receivePushPromise(originalStreamID: streamFive, childStreamID: streamFour, headers: ConnectionStateMachineTests.requestHeaders)) - assertSucceeds(self.server.sendHeaders(streamID: streamFour, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.client.receiveHeaders(streamID: streamFour, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) + assertSucceeds( + self.server.sendPushPromise( + originalStreamID: streamFive, + childStreamID: streamFour, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) + assertSucceeds( + self.client.receivePushPromise( + originalStreamID: streamFive, + childStreamID: streamFour, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) + assertSucceeds( + self.server.sendHeaders( + streamID: streamFour, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamFour, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) // We're going to update the initial window size, adding 1000 to it. This should update for every stream. We do this both ways. assertSucceeds(self.client.sendSettings([HTTP2Setting(parameter: .initialWindowSize, value: 66535)])) - assertSucceeds(self.server.receiveSettings(.settings([HTTP2Setting(parameter: .initialWindowSize, value: 66535)]), frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder)) - assertSucceeds(self.client.receiveSettings(.ack, frameEncoder: &self.clientEncoder, frameDecoder: &self.clientDecoder)) + assertSucceeds( + self.server.receiveSettings( + .settings([HTTP2Setting(parameter: .initialWindowSize, value: 66535)]), + frameEncoder: &self.serverEncoder, + frameDecoder: &self.serverDecoder + ) + ) + assertSucceeds( + self.client.receiveSettings(.ack, frameEncoder: &self.clientEncoder, frameDecoder: &self.clientDecoder) + ) assertSucceeds(self.server.sendSettings([HTTP2Setting(parameter: .initialWindowSize, value: 66535)])) - assertSucceeds(self.client.receiveSettings(.settings([HTTP2Setting(parameter: .initialWindowSize, value: 66535)]), frameEncoder: &self.clientEncoder, frameDecoder: &self.clientDecoder)) - assertSucceeds(self.server.receiveSettings(.ack, frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder)) + assertSucceeds( + self.client.receiveSettings( + .settings([HTTP2Setting(parameter: .initialWindowSize, value: 66535)]), + frameEncoder: &self.clientEncoder, + frameDecoder: &self.clientDecoder + ) + ) + assertSucceeds( + self.server.receiveSettings(.ack, frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder) + ) // We're also adding 10000 to the connection window to get it out of the way. assertSucceeds(self.client.sendWindowUpdate(streamID: .rootStream, windowIncrement: 10000)) @@ -1599,28 +3834,90 @@ class ConnectionStateMachineTests: XCTestCase { // For streams one, three, and two the server is going to send headers. The goal is to have all streams be active for the server to send a data frame. for streamID in [streamOne, streamThree, streamTwo] { - assertSucceeds(self.server.sendHeaders(streamID: streamID, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.client.receiveHeaders(streamID: streamID, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) + assertSucceeds( + self.server.sendHeaders( + streamID: streamID, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamID, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) } // Now the server is going to send data frames for 66535 bytes, consuming the stream window. It'll then prove it by sending one more byte and failing. for streamID in [streamOne, streamTwo, streamThree, streamFour, streamFive, streamSeven] { var tempClient = self.client! var tempServer = self.server! - assertSucceeds(tempServer.sendData(streamID: streamID, contentLength: 15, flowControlledBytes: 66535, isEndStreamSet: false)) - assertSucceeds(tempClient.receiveData(streamID: streamID, contentLength: 15, flowControlledBytes: 66535, isEndStreamSet: false)) - assertStreamError(type: .flowControlError, tempServer.sendData(streamID: streamID, contentLength: 1, flowControlledBytes: 1, isEndStreamSet: false)) - assertStreamError(type: .flowControlError, tempClient.receiveData(streamID: streamID, contentLength: 1, flowControlledBytes: 1, isEndStreamSet: false)) + assertSucceeds( + tempServer.sendData( + streamID: streamID, + contentLength: 15, + flowControlledBytes: 66535, + isEndStreamSet: false + ) + ) + assertSucceeds( + tempClient.receiveData( + streamID: streamID, + contentLength: 15, + flowControlledBytes: 66535, + isEndStreamSet: false + ) + ) + assertStreamError( + type: .flowControlError, + tempServer.sendData(streamID: streamID, contentLength: 1, flowControlledBytes: 1, isEndStreamSet: false) + ) + assertStreamError( + type: .flowControlError, + tempClient.receiveData( + streamID: streamID, + contentLength: 1, + flowControlledBytes: 1, + isEndStreamSet: false + ) + ) } // The client can only send on streams three and five, but it will. for streamID in [streamThree, streamFive] { var tempClient = self.client! var tempServer = self.server! - assertSucceeds(tempClient.sendData(streamID: streamID, contentLength: 15, flowControlledBytes: 66535, isEndStreamSet: false)) - assertSucceeds(tempServer.receiveData(streamID: streamID, contentLength: 15, flowControlledBytes: 66535, isEndStreamSet: false)) - assertStreamError(type: .flowControlError, tempClient.sendData(streamID: streamID, contentLength: 1, flowControlledBytes: 1, isEndStreamSet: false)) - assertStreamError(type: .flowControlError, tempServer.receiveData(streamID: streamID, contentLength: 1, flowControlledBytes: 1, isEndStreamSet: false)) + assertSucceeds( + tempClient.sendData( + streamID: streamID, + contentLength: 15, + flowControlledBytes: 66535, + isEndStreamSet: false + ) + ) + assertSucceeds( + tempServer.receiveData( + streamID: streamID, + contentLength: 15, + flowControlledBytes: 66535, + isEndStreamSet: false + ) + ) + assertStreamError( + type: .flowControlError, + tempClient.sendData(streamID: streamID, contentLength: 1, flowControlledBytes: 1, isEndStreamSet: false) + ) + assertStreamError( + type: .flowControlError, + tempServer.receiveData( + streamID: streamID, + contentLength: 1, + flowControlledBytes: 1, + isEndStreamSet: false + ) + ) } } @@ -1630,26 +3927,102 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble() - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: false)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: false)) - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.trailers, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.trailers, isEndStreamSet: true)) - assertSucceeds(self.server.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.client.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.server.sendPushPromise(originalStreamID: streamOne, childStreamID: streamTwo, headers: ConnectionStateMachineTests.requestHeaders)) - assertSucceeds(self.client.receivePushPromise(originalStreamID: streamOne, childStreamID: streamTwo, headers: ConnectionStateMachineTests.requestHeaders)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.trailers, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.trailers, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.server.sendPushPromise( + originalStreamID: streamOne, + childStreamID: streamTwo, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) + assertSucceeds( + self.client.receivePushPromise( + originalStreamID: streamOne, + childStreamID: streamTwo, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) // Client cannot send more headers on stream one var tempClient = self.client! var tempServer = self.server! - assertStreamError(type: .protocolError, tempClient.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.trailers, isEndStreamSet: false)) - assertStreamError(type: .protocolError, tempServer.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.trailers, isEndStreamSet: false)) + assertStreamError( + type: .protocolError, + tempClient.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.trailers, + isEndStreamSet: false + ) + ) + assertStreamError( + type: .protocolError, + tempServer.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.trailers, + isEndStreamSet: false + ) + ) // Client could never send headers on stream two tempClient = self.client! tempServer = self.server! - assertStreamError(type: .protocolError, tempClient.sendHeaders(streamID: streamTwo, headers: ConnectionStateMachineTests.trailers, isEndStreamSet: false)) - assertStreamError(type: .protocolError, tempServer.receiveHeaders(streamID: streamTwo, headers: ConnectionStateMachineTests.trailers, isEndStreamSet: false)) + assertStreamError( + type: .protocolError, + tempClient.sendHeaders( + streamID: streamTwo, + headers: ConnectionStateMachineTests.trailers, + isEndStreamSet: false + ) + ) + assertStreamError( + type: .protocolError, + tempServer.receiveHeaders( + streamID: streamTwo, + headers: ConnectionStateMachineTests.trailers, + isEndStreamSet: false + ) + ) } func testInvalidChangesToConnectionFlowControlWindow() { @@ -1657,19 +4030,34 @@ class ConnectionStateMachineTests: XCTestCase { // The client cannot send window updates that take us past Int32.max. The default size is 65535. Let's try to take us one past this. let update = UInt32(Int32.max) - 65535 + 1 - assertConnectionError(type: .flowControlError, self.client.sendWindowUpdate(streamID: .rootStream, windowIncrement: update)) - assertConnectionError(type: .flowControlError, self.server.receiveWindowUpdate(streamID: .rootStream, windowIncrement: update)) + assertConnectionError( + type: .flowControlError, + self.client.sendWindowUpdate(streamID: .rootStream, windowIncrement: update) + ) + assertConnectionError( + type: .flowControlError, + self.server.receiveWindowUpdate(streamID: .rootStream, windowIncrement: update) + ) // It's also forbidden to send window updates of size 0. - assertConnectionError(type: .protocolError, self.client.sendWindowUpdate(streamID: .rootStream, windowIncrement: 0)) - assertConnectionError(type: .protocolError, self.server.receiveWindowUpdate(streamID: .rootStream, windowIncrement: 0)) + assertConnectionError( + type: .protocolError, + self.client.sendWindowUpdate(streamID: .rootStream, windowIncrement: 0) + ) + assertConnectionError( + type: .protocolError, + self.server.receiveWindowUpdate(streamID: .rootStream, windowIncrement: 0) + ) } func testSettingsACKWithoutOutstandingSettingsIsAnError() { self.exchangePreamble() // We don't keep track of un-acked settings on the receive side and don't provide a "sendSettingsAck" function. - assertConnectionError(type: .protocolError, self.server.receiveSettings(.ack, frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder)) + assertConnectionError( + type: .protocolError, + self.server.receiveSettings(.ack, frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder) + ) } func testClientsMustCreateStreamsWithOddStreamIDs() { @@ -1677,8 +4065,22 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble() - assertConnectionError(type: .protocolError, self.client.sendHeaders(streamID: streamTwo, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertConnectionError(type: .protocolError, self.server.receiveHeaders(streamID: streamTwo, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) + assertConnectionError( + type: .protocolError, + self.client.sendHeaders( + streamID: streamTwo, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertConnectionError( + type: .protocolError, + self.server.receiveHeaders( + streamID: streamTwo, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) } func testClientsServersMayNotCreateStreamsBackwards() { @@ -1690,61 +4092,184 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble() // Client opens stream 3, server opens stream four. - assertSucceeds(self.client.sendHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.sendHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.client.receiveHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.server.sendPushPromise(originalStreamID: streamThree, childStreamID: streamFour, headers: ConnectionStateMachineTests.requestHeaders)) - assertSucceeds(self.client.receivePushPromise(originalStreamID: streamThree, childStreamID: streamFour, headers: ConnectionStateMachineTests.requestHeaders)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.sendHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.server.sendPushPromise( + originalStreamID: streamThree, + childStreamID: streamFour, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) + assertSucceeds( + self.client.receivePushPromise( + originalStreamID: streamThree, + childStreamID: streamFour, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) // Client may not open stream one now! var tempClient = self.client! var tempServer = self.server! - assertConnectionError(type: .protocolError, tempClient.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertConnectionError(type: .protocolError, tempServer.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - + assertConnectionError( + type: .protocolError, + tempClient.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertConnectionError( + type: .protocolError, + tempServer.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) // Server may not open stream two now. tempClient = self.client! tempServer = self.server! - assertConnectionError(type: .protocolError, tempServer.sendPushPromise(originalStreamID: streamThree, childStreamID: streamTwo, headers: ConnectionStateMachineTests.requestHeaders)) - assertConnectionError(type: .protocolError, tempClient.receivePushPromise(originalStreamID: streamThree, childStreamID: streamTwo, headers: ConnectionStateMachineTests.requestHeaders)) + assertConnectionError( + type: .protocolError, + tempServer.sendPushPromise( + originalStreamID: streamThree, + childStreamID: streamTwo, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) + assertConnectionError( + type: .protocolError, + tempClient.receivePushPromise( + originalStreamID: streamThree, + childStreamID: streamTwo, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) } func testUnknownSettingsAreIgnored() { self.exchangePreamble() assertSucceeds(self.client.sendSettings([HTTP2Setting(parameter: .init(extensionSetting: 88), value: 65536)])) - assertSucceeds(self.server.receiveSettings(.settings([HTTP2Setting(parameter: .init(extensionSetting: 88), value: 65536)]), frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder)) - assertSucceeds(self.client.receiveSettings(.ack, frameEncoder: &self.clientEncoder, frameDecoder: &self.clientDecoder)) + assertSucceeds( + self.server.receiveSettings( + .settings([HTTP2Setting(parameter: .init(extensionSetting: 88), value: 65536)]), + frameEncoder: &self.serverEncoder, + frameDecoder: &self.serverDecoder + ) + ) + assertSucceeds( + self.client.receiveSettings(.ack, frameEncoder: &self.clientEncoder, frameDecoder: &self.clientDecoder) + ) } func testMaxConcurrentStreamsEnforcement() { // Client is going to set SETTINGS_MAX_CONCURRENT_STREAMS to 5, server will set it to 50. assertSucceeds(self.client.sendSettings([HTTP2Setting(parameter: .maxConcurrentStreams, value: 5)])) - assertSucceeds(self.server.receiveSettings(.settings([HTTP2Setting(parameter: .maxConcurrentStreams, value: 5)]), frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder)) + assertSucceeds( + self.server.receiveSettings( + .settings([HTTP2Setting(parameter: .maxConcurrentStreams, value: 5)]), + frameEncoder: &self.serverEncoder, + frameDecoder: &self.serverDecoder + ) + ) assertSucceeds(self.server.sendSettings([HTTP2Setting(parameter: .maxConcurrentStreams, value: 50)])) - assertSucceeds(self.client.receiveSettings(.settings([HTTP2Setting(parameter: .maxConcurrentStreams, value: 50)]), frameEncoder: &self.clientEncoder, frameDecoder: &self.clientDecoder)) + assertSucceeds( + self.client.receiveSettings( + .settings([HTTP2Setting(parameter: .maxConcurrentStreams, value: 50)]), + frameEncoder: &self.clientEncoder, + frameDecoder: &self.clientDecoder + ) + ) - assertSucceeds(self.client.receiveSettings(.ack, frameEncoder: &self.clientEncoder, frameDecoder: &self.clientDecoder)) - assertSucceeds(self.server.receiveSettings(.ack, frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder)) + assertSucceeds( + self.client.receiveSettings(.ack, frameEncoder: &self.clientEncoder, frameDecoder: &self.clientDecoder) + ) + assertSucceeds( + self.server.receiveSettings(.ack, frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder) + ) // Firstly, the client will create 50 streams. This should work just fine. let clientStreamIDs = stride(from: 1, to: 100, by: 2).map { HTTP2StreamID($0) } let serverStreamIDs = stride(from: 2, to: 11, by: 2).map { HTTP2StreamID($0) } for streamID in clientStreamIDs { - assertSucceeds(self.client.sendHeaders(streamID: streamID, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamID, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.sendHeaders(streamID: streamID, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.client.receiveHeaders(streamID: streamID, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamID, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamID, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.sendHeaders( + streamID: streamID, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamID, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) } // The server will now create its 5. for streamID in serverStreamIDs { - assertSucceeds(self.server.sendPushPromise(originalStreamID: clientStreamIDs.first!, childStreamID: streamID, headers: ConnectionStateMachineTests.requestHeaders)) - assertSucceeds(self.client.receivePushPromise(originalStreamID: clientStreamIDs.first!, childStreamID: streamID, headers: ConnectionStateMachineTests.requestHeaders)) + assertSucceeds( + self.server.sendPushPromise( + originalStreamID: clientStreamIDs.first!, + childStreamID: streamID, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) + assertSucceeds( + self.client.receivePushPromise( + originalStreamID: clientStreamIDs.first!, + childStreamID: streamID, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) } // Neither the client nor the server can create new streams @@ -1753,38 +4278,124 @@ class ConnectionStateMachineTests: XCTestCase { var tempClient = self.client! var tempServer = self.server! - assertConnectionError(type: .protocolError, tempClient.sendHeaders(streamID: stream101, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertConnectionError(type: .protocolError, tempServer.receiveHeaders(streamID: stream101, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) + assertConnectionError( + type: .protocolError, + tempClient.sendHeaders( + streamID: stream101, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertConnectionError( + type: .protocolError, + tempServer.receiveHeaders( + streamID: stream101, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) tempClient = self.client! tempServer = self.server! - assertConnectionError(type: .protocolError, tempServer.sendPushPromise(originalStreamID: clientStreamIDs.first!, childStreamID: stream12, headers: ConnectionStateMachineTests.requestHeaders)) - assertConnectionError(type: .protocolError, tempClient.receivePushPromise(originalStreamID: clientStreamIDs.first!, childStreamID: stream12, headers: ConnectionStateMachineTests.requestHeaders)) + assertConnectionError( + type: .protocolError, + tempServer.sendPushPromise( + originalStreamID: clientStreamIDs.first!, + childStreamID: stream12, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) + assertConnectionError( + type: .protocolError, + tempClient.receivePushPromise( + originalStreamID: clientStreamIDs.first!, + childStreamID: stream12, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) // We can drop the value of SETTINGS_MAX_CONCURRENT_STREAMS without error. assertSucceeds(self.server.sendSettings([HTTP2Setting(parameter: .maxConcurrentStreams, value: 2)])) - assertSucceeds(self.client.receiveSettings(.settings([HTTP2Setting(parameter: .maxConcurrentStreams, value: 2)]), frameEncoder: &self.clientEncoder, frameDecoder: &self.clientDecoder)) - assertSucceeds(self.server.receiveSettings(.ack, frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder)) + assertSucceeds( + self.client.receiveSettings( + .settings([HTTP2Setting(parameter: .maxConcurrentStreams, value: 2)]), + frameEncoder: &self.clientEncoder, + frameDecoder: &self.clientDecoder + ) + ) + assertSucceeds( + self.server.receiveSettings(.ack, frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder) + ) // The server can now cleanly close all but two of the existing streams. for streamID in clientStreamIDs.dropLast(2) { - assertSucceeds(self.server.sendHeaders(streamID: streamID, headers: ConnectionStateMachineTests.trailers, isEndStreamSet: true)) - assertSucceeds(self.client.receiveHeaders(streamID: streamID, headers: ConnectionStateMachineTests.trailers, isEndStreamSet: true)) + assertSucceeds( + self.server.sendHeaders( + streamID: streamID, + headers: ConnectionStateMachineTests.trailers, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamID, + headers: ConnectionStateMachineTests.trailers, + isEndStreamSet: true + ) + ) } // The client still cannot initiate new streams here. tempClient = self.client! tempServer = self.server! - assertConnectionError(type: .protocolError, tempClient.sendHeaders(streamID: stream101, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertConnectionError(type: .protocolError, tempServer.receiveHeaders(streamID: stream101, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) + assertConnectionError( + type: .protocolError, + tempClient.sendHeaders( + streamID: stream101, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertConnectionError( + type: .protocolError, + tempServer.receiveHeaders( + streamID: stream101, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) // The server can now drop one more stream. - assertSucceeds(self.server.sendHeaders(streamID: clientStreamIDs.last!, headers: ConnectionStateMachineTests.trailers, isEndStreamSet: true)) - assertSucceeds(self.client.receiveHeaders(streamID: clientStreamIDs.last!, headers: ConnectionStateMachineTests.trailers, isEndStreamSet: true)) + assertSucceeds( + self.server.sendHeaders( + streamID: clientStreamIDs.last!, + headers: ConnectionStateMachineTests.trailers, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: clientStreamIDs.last!, + headers: ConnectionStateMachineTests.trailers, + isEndStreamSet: true + ) + ) // Now the client can open a new one! - assertSucceeds(self.client.sendHeaders(streamID: stream101, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: stream101, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: stream101, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: stream101, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) } func testDisablingPushPreventsPush() { @@ -1793,39 +4404,122 @@ class ConnectionStateMachineTests: XCTestCase { // Client is going to set SETTINGS_ENABLE_PUSH to false. assertSucceeds(self.client.sendSettings([HTTP2Setting(parameter: .enablePush, value: 0)])) - assertSucceeds(self.server.receiveSettings(.settings([HTTP2Setting(parameter: .enablePush, value: 0)]), frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder)) + assertSucceeds( + self.server.receiveSettings( + .settings([HTTP2Setting(parameter: .enablePush, value: 0)]), + frameEncoder: &self.serverEncoder, + frameDecoder: &self.serverDecoder + ) + ) assertSucceeds(self.server.sendSettings([])) - assertSucceeds(self.client.receiveSettings(.settings([]), frameEncoder: &self.clientEncoder, frameDecoder: &self.clientDecoder)) + assertSucceeds( + self.client.receiveSettings( + .settings([]), + frameEncoder: &self.clientEncoder, + frameDecoder: &self.clientDecoder + ) + ) - assertSucceeds(self.client.receiveSettings(.ack, frameEncoder: &self.clientEncoder, frameDecoder: &self.clientDecoder)) - assertSucceeds(self.server.receiveSettings(.ack, frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder)) + assertSucceeds( + self.client.receiveSettings(.ack, frameEncoder: &self.clientEncoder, frameDecoder: &self.clientDecoder) + ) + assertSucceeds( + self.server.receiveSettings(.ack, frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder) + ) // Client initiates a stream. - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.client.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) // Server may not push. var tempClient = self.client! var tempServer = self.server! - assertConnectionError(type: .protocolError, tempServer.sendPushPromise(originalStreamID: streamOne, childStreamID: streamTwo, headers: ConnectionStateMachineTests.requestHeaders)) - assertConnectionError(type: .protocolError, tempClient.receivePushPromise(originalStreamID: streamOne, childStreamID: streamTwo, headers: ConnectionStateMachineTests.requestHeaders)) + assertConnectionError( + type: .protocolError, + tempServer.sendPushPromise( + originalStreamID: streamOne, + childStreamID: streamTwo, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) + assertConnectionError( + type: .protocolError, + tempClient.receivePushPromise( + originalStreamID: streamOne, + childStreamID: streamTwo, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) // Client can re-enable push. assertSucceeds(self.client.sendSettings([HTTP2Setting(parameter: .enablePush, value: 1)])) - assertSucceeds(self.server.receiveSettings(.settings([HTTP2Setting(parameter: .enablePush, value: 1)]), frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder)) - assertSucceeds(self.client.receiveSettings(.ack, frameEncoder: &self.clientEncoder, frameDecoder: &self.clientDecoder)) + assertSucceeds( + self.server.receiveSettings( + .settings([HTTP2Setting(parameter: .enablePush, value: 1)]), + frameEncoder: &self.serverEncoder, + frameDecoder: &self.serverDecoder + ) + ) + assertSucceeds( + self.client.receiveSettings(.ack, frameEncoder: &self.clientEncoder, frameDecoder: &self.clientDecoder) + ) // Push is now allowed. - assertSucceeds(self.server.sendPushPromise(originalStreamID: streamOne, childStreamID: streamTwo, headers: ConnectionStateMachineTests.requestHeaders)) - assertSucceeds(self.client.receivePushPromise(originalStreamID: streamOne, childStreamID: streamTwo, headers: ConnectionStateMachineTests.requestHeaders)) + assertSucceeds( + self.server.sendPushPromise( + originalStreamID: streamOne, + childStreamID: streamTwo, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) + assertSucceeds( + self.client.receivePushPromise( + originalStreamID: streamOne, + childStreamID: streamTwo, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) // Out-of-bounds push values are forbidden. - assertConnectionError(type: .protocolError, self.client.sendSettings([HTTP2Setting(parameter: .enablePush, value: 2)])) - assertConnectionError(type: .protocolError, - self.server.receiveSettings(.settings([HTTP2Setting(parameter: .enablePush, value: 2)]), frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder)) + assertConnectionError( + type: .protocolError, + self.client.sendSettings([HTTP2Setting(parameter: .enablePush, value: 2)]) + ) + assertConnectionError( + type: .protocolError, + self.server.receiveSettings( + .settings([HTTP2Setting(parameter: .enablePush, value: 2)]), + frameEncoder: &self.serverEncoder, + frameDecoder: &self.serverDecoder + ) + ) } func testClientsCannotPush() { @@ -1834,19 +4528,63 @@ class ConnectionStateMachineTests: XCTestCase { // Default settings. assertSucceeds(self.client.sendSettings([])) - assertSucceeds(self.server.receiveSettings(.settings([]), frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder)) + assertSucceeds( + self.server.receiveSettings( + .settings([]), + frameEncoder: &self.serverEncoder, + frameDecoder: &self.serverDecoder + ) + ) assertSucceeds(self.server.sendSettings([])) - assertSucceeds(self.client.receiveSettings(.settings([]), frameEncoder: &self.clientEncoder, frameDecoder: &self.clientDecoder)) - assertSucceeds(self.client.receiveSettings(.ack, frameEncoder: &self.clientEncoder, frameDecoder: &self.clientDecoder)) - assertSucceeds(self.server.receiveSettings(.ack, frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder)) + assertSucceeds( + self.client.receiveSettings( + .settings([]), + frameEncoder: &self.clientEncoder, + frameDecoder: &self.clientDecoder + ) + ) + assertSucceeds( + self.client.receiveSettings(.ack, frameEncoder: &self.clientEncoder, frameDecoder: &self.clientDecoder) + ) + assertSucceeds( + self.server.receiveSettings(.ack, frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder) + ) // Client attempts to push, using a _server_ stream ID, with stream one not open. This should fail on both server and client. - assertConnectionError(type: .protocolError, self.client.sendPushPromise(originalStreamID: streamOne, childStreamID: streamTwo, headers: ConnectionStateMachineTests.requestHeaders)) - assertConnectionError(type: .protocolError, self.server.receivePushPromise(originalStreamID: streamOne, childStreamID: streamTwo, headers: ConnectionStateMachineTests.requestHeaders)) + assertConnectionError( + type: .protocolError, + self.client.sendPushPromise( + originalStreamID: streamOne, + childStreamID: streamTwo, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) + assertConnectionError( + type: .protocolError, + self.server.receivePushPromise( + originalStreamID: streamOne, + childStreamID: streamTwo, + headers: ConnectionStateMachineTests.requestHeaders + ) + ) // Client then sends a HEADERS frame on the stream it just pushed. This should also fail. - assertConnectionError(type: .protocolError, self.client.sendHeaders(streamID: streamTwo, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: false)) - assertConnectionError(type: .protocolError, self.server.receiveHeaders(streamID: streamTwo, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: false)) + assertConnectionError( + type: .protocolError, + self.client.sendHeaders( + streamID: streamTwo, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: false + ) + ) + assertConnectionError( + type: .protocolError, + self.server.receiveHeaders( + streamID: streamTwo, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: false + ) + ) } func testRatchetingGoawayEvenWhenFullyQueisced() { @@ -1858,9 +4596,17 @@ class ConnectionStateMachineTests: XCTestCase { self.setupServerGoaway(streamsToOpen: [streamSeven], lastStreamID: .maxID, expectedToClose: nil) // Now the server ratchets down slowly. - for (lastStreamID, dropping) in [(streamSeven, nil), (streamFive, streamSeven), (streamThree, nil), (streamOne, nil), (.rootStream, nil)] { - assertGoawaySucceeds(self.server.sendGoaway(lastStreamID: lastStreamID), droppingStreams: dropping.map { [$0] }) - assertGoawaySucceeds(self.client.receiveGoaway(lastStreamID: lastStreamID), droppingStreams: dropping.map { [$0] }) + for (lastStreamID, dropping) in [ + (streamSeven, nil), (streamFive, streamSeven), (streamThree, nil), (streamOne, nil), (.rootStream, nil), + ] { + assertGoawaySucceeds( + self.server.sendGoaway(lastStreamID: lastStreamID), + droppingStreams: dropping.map { [$0] } + ) + assertGoawaySucceeds( + self.client.receiveGoaway(lastStreamID: lastStreamID), + droppingStreams: dropping.map { [$0] } + ) // Duplicate goaways succeed, but change nothing. assertGoawaySucceeds(self.server.sendGoaway(lastStreamID: lastStreamID), droppingStreams: nil) @@ -1881,9 +4627,17 @@ class ConnectionStateMachineTests: XCTestCase { assertSucceeds(self.server.receiveGoaway(lastStreamID: HTTP2StreamID(Int32.max - 1))) // Now the server ratchets down slowly. - for (lastStreamID, dropping) in [(streamSeven, nil), (streamFive, streamSeven), (streamThree, nil), (streamOne, nil), (.rootStream, nil)] { - assertGoawaySucceeds(self.server.sendGoaway(lastStreamID: lastStreamID), droppingStreams: dropping.map { [$0] }) - assertGoawaySucceeds(self.client.receiveGoaway(lastStreamID: lastStreamID), droppingStreams: dropping.map { [$0] }) + for (lastStreamID, dropping) in [ + (streamSeven, nil), (streamFive, streamSeven), (streamThree, nil), (streamOne, nil), (.rootStream, nil), + ] { + assertGoawaySucceeds( + self.server.sendGoaway(lastStreamID: lastStreamID), + droppingStreams: dropping.map { [$0] } + ) + assertGoawaySucceeds( + self.client.receiveGoaway(lastStreamID: lastStreamID), + droppingStreams: dropping.map { [$0] } + ) // Duplicate goaways succeed, but change nothing. assertGoawaySucceeds(self.server.sendGoaway(lastStreamID: lastStreamID), droppingStreams: nil) @@ -1905,12 +4659,38 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble() // Client initiates a stream. - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: false)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: false)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: false + ) + ) // If the client attempts to send trailers without end stream, this fails with a stream error. - assertStreamError(type: .protocolError, self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.trailers, isEndStreamSet: false)) - assertStreamError(type: .protocolError, self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.trailers, isEndStreamSet: false)) + assertStreamError( + type: .protocolError, + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.trailers, + isEndStreamSet: false + ) + ) + assertStreamError( + type: .protocolError, + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.trailers, + isEndStreamSet: false + ) + ) } func testServerTrailersMustHaveEndStreamSet() { @@ -1919,16 +4699,54 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble() // Client initiates a stream. - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) // Server sends back headers. - assertSucceeds(self.server.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.client.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) + assertSucceeds( + self.server.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) // If the server attempts to send trailers without end stream, this fails with a stream error. - assertStreamError(type: .protocolError, self.server.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.trailers, isEndStreamSet: false)) - assertStreamError(type: .protocolError, self.client.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.trailers, isEndStreamSet: false)) + assertStreamError( + type: .protocolError, + self.server.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.trailers, + isEndStreamSet: false + ) + ) + assertStreamError( + type: .protocolError, + self.client.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.trailers, + isEndStreamSet: false + ) + ) } func testRejectHeadersWithUppercaseHeaderFieldName() { @@ -1941,22 +4759,100 @@ class ConnectionStateMachineTests: XCTestCase { let invalidExtraHeaders = [("UppercaseFieldName", "value")] // First, test that client initial headers may not contain uppercase headers. - assertStreamError(type: .protocolError, self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) - assertStreamError(type: .protocolError, self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) + assertStreamError( + type: .protocolError, + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) + assertStreamError( + type: .protocolError, + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) // Next, set up a valid stream for the client and confirm that the server response cannot have uppercase headers. - assertSucceeds(self.client.sendHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertStreamError(type: .protocolError, self.server.sendHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.responseHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) - assertStreamError(type: .protocolError, self.client.receiveHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.responseHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertStreamError( + type: .protocolError, + self.server.sendHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.responseHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) + assertStreamError( + type: .protocolError, + self.client.receiveHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.responseHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) // Next, test this with trailers. - assertSucceeds(self.client.sendHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.sendHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.client.receiveHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertStreamError(type: .protocolError, self.server.sendHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.trailers.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) - assertStreamError(type: .protocolError, self.client.receiveHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.trailers.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.sendHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertStreamError( + type: .protocolError, + self.server.sendHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.trailers.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) + assertStreamError( + type: .protocolError, + self.client.receiveHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.trailers.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) } func testAllowHeadersWithUppercaseHeaderFieldNameWhenValidationDisabled() { @@ -1973,22 +4869,94 @@ class ConnectionStateMachineTests: XCTestCase { let invalidExtraHeaders = [("UppercaseFieldName", "value")] // First, test that client initial headers may not contain uppercase headers. - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) // Next, set up a valid stream for the client and confirm that the server response cannot have uppercase headers. - assertSucceeds(self.client.sendHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.sendHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.responseHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) - assertSucceeds(self.client.receiveHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.responseHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.sendHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.responseHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.responseHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) // Next, test this with trailers. - assertSucceeds(self.client.sendHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.sendHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.client.receiveHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.server.sendHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.trailers.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) - assertSucceeds(self.client.receiveHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.trailers.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.sendHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.server.sendHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.trailers.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.trailers.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) } func testRejectPseudoHeadersAfterRegularHeaders() { @@ -2001,22 +4969,100 @@ class ConnectionStateMachineTests: XCTestCase { let invalidExtraHeaders = [(":pseudo", "value")] // First, test that client initial headers may not contain pseudo-headers after regular ones. - assertStreamError(type: .protocolError, self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) - assertStreamError(type: .protocolError, self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) + assertStreamError( + type: .protocolError, + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) + assertStreamError( + type: .protocolError, + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) // Next, set up a valid stream for the client and confirm that the server response cannot have pseudo-headers after regular ones. - assertSucceeds(self.client.sendHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertStreamError(type: .protocolError, self.server.sendHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.responseHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) - assertStreamError(type: .protocolError, self.client.receiveHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.responseHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertStreamError( + type: .protocolError, + self.server.sendHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.responseHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) + assertStreamError( + type: .protocolError, + self.client.receiveHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.responseHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) // Next, test this with trailers. - assertSucceeds(self.client.sendHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.sendHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.client.receiveHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertStreamError(type: .protocolError, self.server.sendHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.trailers.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) - assertStreamError(type: .protocolError, self.client.receiveHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.trailers.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.sendHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertStreamError( + type: .protocolError, + self.server.sendHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.trailers.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) + assertStreamError( + type: .protocolError, + self.client.receiveHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.trailers.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) } func testAllowPseudoHeadersAfterRegularHeaders() { @@ -2033,22 +5079,94 @@ class ConnectionStateMachineTests: XCTestCase { let invalidExtraHeaders = [(":pseudo", "value")] // First, test that client initial headers may not contain pseudo-headers after regular ones. - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) // Next, set up a valid stream for the client and confirm that the server response cannot have pseudo-headers after regular ones. - assertSucceeds(self.client.sendHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.sendHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.responseHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) - assertSucceeds(self.client.receiveHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.responseHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.sendHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.responseHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.responseHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) // Next, test this with trailers. - assertSucceeds(self.client.sendHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.sendHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.client.receiveHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.server.sendHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.trailers.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) - assertSucceeds(self.client.receiveHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.trailers.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.sendHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.server.sendHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.trailers.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.trailers.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) } func testRejectRequestHeadersWithMissingMethodField() { @@ -2056,11 +5174,19 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble() - let headers = HPACKHeaders([(":authority", "localhost"), (":scheme", "https"), (":path", "/"), ("content-length", "0")]) + let headers = HPACKHeaders([ + (":authority", "localhost"), (":scheme", "https"), (":path", "/"), ("content-length", "0"), + ]) // Request headers must contain :method. - assertStreamError(type: .protocolError, self.client.sendHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true)) - assertStreamError(type: .protocolError, self.server.receiveHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true)) + assertStreamError( + type: .protocolError, + self.client.sendHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true) + ) + assertStreamError( + type: .protocolError, + self.server.receiveHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true) + ) } func testAllowRequestHeadersWithMissingMethodFieldWhenValidationDisabled() { @@ -2072,7 +5198,9 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble() - let headers = HPACKHeaders([(":authority", "localhost"), (":scheme", "https"), (":path", "/"), ("content-length", "0")]) + let headers = HPACKHeaders([ + (":authority", "localhost"), (":scheme", "https"), (":path", "/"), ("content-length", "0"), + ]) // Request headers must contain :method. assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true)) @@ -2084,11 +5212,19 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble() - let headers = HPACKHeaders([(":authority", "localhost"), (":scheme", "https"), (":method", "GET"), ("content-length", "0")]) + let headers = HPACKHeaders([ + (":authority", "localhost"), (":scheme", "https"), (":method", "GET"), ("content-length", "0"), + ]) // Request headers must contain :path. - assertStreamError(type: .protocolError, self.client.sendHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true)) - assertStreamError(type: .protocolError, self.server.receiveHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true)) + assertStreamError( + type: .protocolError, + self.client.sendHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true) + ) + assertStreamError( + type: .protocolError, + self.server.receiveHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true) + ) } func testAllowRequestHeadersWithMissingPathFieldWhenValidationDisabled() { @@ -2100,7 +5236,9 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble() - let headers = HPACKHeaders([(":authority", "localhost"), (":scheme", "https"), (":method", "GET"), ("content-length", "0")]) + let headers = HPACKHeaders([ + (":authority", "localhost"), (":scheme", "https"), (":method", "GET"), ("content-length", "0"), + ]) // Request headers must contain :path. assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true)) @@ -2112,11 +5250,20 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble() - let headers = HPACKHeaders([(":authority", "localhost"), (":scheme", "https"), (":method", "GET"), (":path", ""), ("content-length", "0")]) + let headers = HPACKHeaders([ + (":authority", "localhost"), (":scheme", "https"), (":method", "GET"), (":path", ""), + ("content-length", "0"), + ]) // Request headers must contain non-empty :path. - assertStreamError(type: .protocolError, self.client.sendHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true)) - assertStreamError(type: .protocolError, self.server.receiveHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true)) + assertStreamError( + type: .protocolError, + self.client.sendHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true) + ) + assertStreamError( + type: .protocolError, + self.server.receiveHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true) + ) } func testAllowRequestHeadersWithEmptyPathFieldWhenValidationDisabled() { @@ -2128,7 +5275,10 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble() - let headers = HPACKHeaders([(":authority", "localhost"), (":scheme", "https"), (":method", "GET"), (":path", ""), ("content-length", "0")]) + let headers = HPACKHeaders([ + (":authority", "localhost"), (":scheme", "https"), (":method", "GET"), (":path", ""), + ("content-length", "0"), + ]) // Request headers must contain non-empty :path. assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true)) @@ -2140,11 +5290,19 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble() - let headers = HPACKHeaders([(":authority", "localhost"), (":method", "GET"), (":path", "/"), ("content-length", "0")]) + let headers = HPACKHeaders([ + (":authority", "localhost"), (":method", "GET"), (":path", "/"), ("content-length", "0"), + ]) // Request headers must contain :scheme. - assertStreamError(type: .protocolError, self.client.sendHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true)) - assertStreamError(type: .protocolError, self.server.receiveHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true)) + assertStreamError( + type: .protocolError, + self.client.sendHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true) + ) + assertStreamError( + type: .protocolError, + self.server.receiveHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true) + ) } func testAllowRequestHeadersWithMissingSchemeFieldWhenValidationDisabled() { @@ -2156,7 +5314,9 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble() - let headers = HPACKHeaders([(":authority", "localhost"), (":method", "GET"), (":path", "/"), ("content-length", "0")]) + let headers = HPACKHeaders([ + (":authority", "localhost"), (":method", "GET"), (":path", "/"), ("content-length", "0"), + ]) // Request headers must contain :scheme. assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true)) @@ -2168,11 +5328,20 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble() - let headers = HPACKHeaders([(":method", "GET"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https"), (":path", "/"), ("content-length", "0")]) + let headers = HPACKHeaders([ + (":method", "GET"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https"), (":path", "/"), + ("content-length", "0"), + ]) // Request headers must contain only one :method. - assertStreamError(type: .protocolError, self.client.sendHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true)) - assertStreamError(type: .protocolError, self.server.receiveHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true)) + assertStreamError( + type: .protocolError, + self.client.sendHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true) + ) + assertStreamError( + type: .protocolError, + self.server.receiveHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true) + ) } func testAllowRequestHeadersWithDuplicateMethodFieldWhenValidationDisabled() { @@ -2184,7 +5353,10 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble() - let headers = HPACKHeaders([(":method", "GET"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https"), (":path", "/"), ("content-length", "0")]) + let headers = HPACKHeaders([ + (":method", "GET"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https"), (":path", "/"), + ("content-length", "0"), + ]) // Request headers must contain only one :method. assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true)) @@ -2196,11 +5368,20 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble() - let headers = HPACKHeaders([(":path", "/"), (":path", "/"), (":authority", "localhost"), (":scheme", "https"), (":method", "GET"), ("content-length", "0")]) + let headers = HPACKHeaders([ + (":path", "/"), (":path", "/"), (":authority", "localhost"), (":scheme", "https"), (":method", "GET"), + ("content-length", "0"), + ]) // Request headers must contain only one :path. - assertStreamError(type: .protocolError, self.client.sendHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true)) - assertStreamError(type: .protocolError, self.server.receiveHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true)) + assertStreamError( + type: .protocolError, + self.client.sendHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true) + ) + assertStreamError( + type: .protocolError, + self.server.receiveHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true) + ) } func testAllowRequestHeadersWithDuplicatePathFieldWhenValidationDisabled() { @@ -2212,7 +5393,10 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble() - let headers = HPACKHeaders([(":path", "/"), (":path", "/"), (":authority", "localhost"), (":scheme", "https"), (":method", "GET"), ("content-length", "0")]) + let headers = HPACKHeaders([ + (":path", "/"), (":path", "/"), (":authority", "localhost"), (":scheme", "https"), (":method", "GET"), + ("content-length", "0"), + ]) // Request headers must contain only one :path. assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true)) @@ -2224,11 +5408,20 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble() - let headers = HPACKHeaders([(":scheme", "https"), (":scheme", "https"), (":authority", "localhost"), (":method", "GET"), (":path", "/"), ("content-length", "0")]) + let headers = HPACKHeaders([ + (":scheme", "https"), (":scheme", "https"), (":authority", "localhost"), (":method", "GET"), (":path", "/"), + ("content-length", "0"), + ]) // Request headers must contain only one :scheme. - assertStreamError(type: .protocolError, self.client.sendHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true)) - assertStreamError(type: .protocolError, self.server.receiveHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true)) + assertStreamError( + type: .protocolError, + self.client.sendHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true) + ) + assertStreamError( + type: .protocolError, + self.server.receiveHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true) + ) } func testAllowRequestHeadersWithDuplicateSchemeFieldWhenValidationDisabled() { @@ -2240,7 +5433,10 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble() - let headers = HPACKHeaders([(":scheme", "https"), (":scheme", "https"), (":authority", "localhost"), (":method", "GET"), (":path", "/"), ("content-length", "0")]) + let headers = HPACKHeaders([ + (":scheme", "https"), (":scheme", "https"), (":authority", "localhost"), (":method", "GET"), (":path", "/"), + ("content-length", "0"), + ]) // Request headers must contain only one :scheme. assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true)) @@ -2254,12 +5450,30 @@ class ConnectionStateMachineTests: XCTestCase { let headers = HPACKHeaders([("content-length", "0")]) - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) // Response headers must contain :status. - assertStreamError(type: .protocolError, self.server.sendHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true)) - assertStreamError(type: .protocolError, self.client.receiveHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true)) + assertStreamError( + type: .protocolError, + self.server.sendHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true) + ) + assertStreamError( + type: .protocolError, + self.client.receiveHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true) + ) } func testAllowResponseHeadersWithMissingStatusFieldWhenValidationDisabled() { @@ -2273,8 +5487,20 @@ class ConnectionStateMachineTests: XCTestCase { let headers = HPACKHeaders([("content-length", "0")]) - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) // Response headers must contain :status. assertSucceeds(self.server.sendHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true)) @@ -2288,12 +5514,30 @@ class ConnectionStateMachineTests: XCTestCase { let headers = HPACKHeaders([(":status", "200"), (":status", "200"), ("content-length", "0")]) - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) // Response headers must contain only one :status. - assertStreamError(type: .protocolError, self.server.sendHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true)) - assertStreamError(type: .protocolError, self.client.receiveHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true)) + assertStreamError( + type: .protocolError, + self.server.sendHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true) + ) + assertStreamError( + type: .protocolError, + self.client.receiveHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true) + ) } func testAllowResponseHeadersWithDuplicateStatusFieldWhenValidationDisabled() { @@ -2307,8 +5551,20 @@ class ConnectionStateMachineTests: XCTestCase { let headers = HPACKHeaders([(":status", "200"), (":status", "200"), ("content-length", "0")]) - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) // Response headers must contain only one :status. assertSucceeds(self.server.sendHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true)) @@ -2322,12 +5578,30 @@ class ConnectionStateMachineTests: XCTestCase { let trailers = HPACKHeaders([(":method", "GET")]) - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) // Trailers must not contain pseudo-headers. - assertStreamError(type: .protocolError, self.client.sendHeaders(streamID: streamOne, headers: trailers, isEndStreamSet: true)) - assertStreamError(type: .protocolError, self.server.receiveHeaders(streamID: streamOne, headers: trailers, isEndStreamSet: true)) + assertStreamError( + type: .protocolError, + self.client.sendHeaders(streamID: streamOne, headers: trailers, isEndStreamSet: true) + ) + assertStreamError( + type: .protocolError, + self.server.receiveHeaders(streamID: streamOne, headers: trailers, isEndStreamSet: true) + ) } func testRejectRequestHeadersWithSchemeFieldOnCONNECT() { @@ -2338,8 +5612,14 @@ class ConnectionStateMachineTests: XCTestCase { let headers = HPACKHeaders([(":authority", "localhost:443"), (":method", "CONNECT"), (":scheme", "https")]) // Request headers for a CONNECT request must not contain :scheme. - assertStreamError(type: .protocolError, self.client.sendHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true)) - assertStreamError(type: .protocolError, self.server.receiveHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true)) + assertStreamError( + type: .protocolError, + self.client.sendHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true) + ) + assertStreamError( + type: .protocolError, + self.server.receiveHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true) + ) } func testAllowRequestHeadersWithSchemeFieldOnCONNECTValidationDisabled() { @@ -2366,8 +5646,14 @@ class ConnectionStateMachineTests: XCTestCase { let headers = HPACKHeaders([(":authority", "localhost:443"), (":method", "CONNECT"), (":path", "/")]) // Request headers for a CONNECT request must not contain :scheme. - assertStreamError(type: .protocolError, self.client.sendHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true)) - assertStreamError(type: .protocolError, self.server.receiveHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true)) + assertStreamError( + type: .protocolError, + self.client.sendHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true) + ) + assertStreamError( + type: .protocolError, + self.server.receiveHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true) + ) } func testAllowRequestHeadersWithPathFieldOnCONNECTValidationDisabled() { @@ -2404,8 +5690,14 @@ class ConnectionStateMachineTests: XCTestCase { let headers = HPACKHeaders([(":method", "CONNECT")]) // Request headers for a CONNECT request must contain :authority. - assertStreamError(type: .protocolError, self.client.sendHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true)) - assertStreamError(type: .protocolError, self.server.receiveHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true)) + assertStreamError( + type: .protocolError, + self.client.sendHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true) + ) + assertStreamError( + type: .protocolError, + self.server.receiveHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true) + ) } func testAllowRequestHeadersWithoutAuthorityFieldOnCONNECTValidationDisabled() { @@ -2429,10 +5721,18 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble() - let headers = HPACKHeaders([(":method", "CONNECT"), (":protocol", "websocket"), (":scheme", "https"), (":path", "/chat") ]) + let headers = HPACKHeaders([ + (":method", "CONNECT"), (":protocol", "websocket"), (":scheme", "https"), (":path", "/chat"), + ]) - assertStreamError(type: .protocolError, self.client.sendHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true)) - assertStreamError(type: .protocolError, self.server.receiveHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true)) + assertStreamError( + type: .protocolError, + self.client.sendHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true) + ) + assertStreamError( + type: .protocolError, + self.server.receiveHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true) + ) } func testProtocolPseudoheaderWithEnableConnectProtocolSetting() { @@ -2440,7 +5740,9 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble(server: [HTTP2Setting(parameter: .enableConnectProtocol, value: 1)]) - let headers = HPACKHeaders([(":method", "CONNECT"), (":protocol", "websocket"), (":scheme", "https"), (":path", "/chat") ]) + let headers = HPACKHeaders([ + (":method", "CONNECT"), (":protocol", "websocket"), (":scheme", "https"), (":path", "/chat"), + ]) assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true)) assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true)) @@ -2451,9 +5753,17 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble(server: [HTTP2Setting(parameter: .enableConnectProtocol, value: 1)]) - let headers = HPACKHeaders([(":method", "GET"), (":protocol", "websocket"), (":scheme", "https"), (":path", "/chat") ]) - assertStreamError(type: .protocolError, self.client.sendHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true)) - assertStreamError(type: .protocolError, self.server.receiveHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true)) + let headers = HPACKHeaders([ + (":method", "GET"), (":protocol", "websocket"), (":scheme", "https"), (":path", "/chat"), + ]) + assertStreamError( + type: .protocolError, + self.client.sendHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true) + ) + assertStreamError( + type: .protocolError, + self.server.receiveHeaders(streamID: streamOne, headers: headers, isEndStreamSet: true) + ) } func testRejectHeadersWithConnectionHeader() { @@ -2466,22 +5776,100 @@ class ConnectionStateMachineTests: XCTestCase { let invalidExtraHeaders = [("connection", "close")] // First, test that client initial headers may not contain the connection header. - assertStreamError(type: .protocolError, self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) - assertStreamError(type: .protocolError, self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) + assertStreamError( + type: .protocolError, + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) + assertStreamError( + type: .protocolError, + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) // Next, set up a valid stream for the client and confirm that the server response cannot have the connection header. - assertSucceeds(self.client.sendHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertStreamError(type: .protocolError, self.server.sendHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.responseHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) - assertStreamError(type: .protocolError, self.client.receiveHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.responseHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertStreamError( + type: .protocolError, + self.server.sendHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.responseHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) + assertStreamError( + type: .protocolError, + self.client.receiveHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.responseHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) // Next, test this with trailers. - assertSucceeds(self.client.sendHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.sendHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.client.receiveHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertStreamError(type: .protocolError, self.server.sendHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.trailers.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) - assertStreamError(type: .protocolError, self.client.receiveHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.trailers.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.sendHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertStreamError( + type: .protocolError, + self.server.sendHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.trailers.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) + assertStreamError( + type: .protocolError, + self.client.receiveHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.trailers.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) } func testAllowHeadersWithConnectionHeaderWhenValidationDisabled() { @@ -2498,22 +5886,94 @@ class ConnectionStateMachineTests: XCTestCase { let invalidExtraHeaders = [("connection", "close")] // First, test that client initial headers may not contain the connection header. - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) // Next, set up a valid stream for the client and confirm that the server response cannot have the connection header. - assertSucceeds(self.client.sendHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.sendHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.responseHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) - assertSucceeds(self.client.receiveHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.responseHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.sendHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.responseHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.responseHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) // Next, test this with trailers. - assertSucceeds(self.client.sendHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.sendHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.client.receiveHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.server.sendHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.trailers.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) - assertSucceeds(self.client.receiveHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.trailers.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.sendHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.server.sendHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.trailers.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.trailers.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) } func testRejectHeadersWithTransferEncodingHeader() { @@ -2526,22 +5986,100 @@ class ConnectionStateMachineTests: XCTestCase { let invalidExtraHeaders = [("transfer-encoding", "chunked")] // First, test that client initial headers may not contain the transfer-encoding header. - assertStreamError(type: .protocolError, self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) - assertStreamError(type: .protocolError, self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) + assertStreamError( + type: .protocolError, + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) + assertStreamError( + type: .protocolError, + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) // Next, set up a valid stream for the client and confirm that the server response cannot have the transfer-encoding header. - assertSucceeds(self.client.sendHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertStreamError(type: .protocolError, self.server.sendHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.responseHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) - assertStreamError(type: .protocolError, self.client.receiveHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.responseHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertStreamError( + type: .protocolError, + self.server.sendHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.responseHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) + assertStreamError( + type: .protocolError, + self.client.receiveHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.responseHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) // Next, test this with trailers. - assertSucceeds(self.client.sendHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.sendHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.client.receiveHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertStreamError(type: .protocolError, self.server.sendHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.trailers.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) - assertStreamError(type: .protocolError, self.client.receiveHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.trailers.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.sendHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertStreamError( + type: .protocolError, + self.server.sendHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.trailers.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) + assertStreamError( + type: .protocolError, + self.client.receiveHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.trailers.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) } func testAllowHeadersWithTransferEncodingHeaderWhenValidationDisabled() { @@ -2558,22 +6096,94 @@ class ConnectionStateMachineTests: XCTestCase { let invalidExtraHeaders = [("transfer-encoding", "chunked")] // First, test that client initial headers may not contain the transfer-encoding header. - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) // Next, set up a valid stream for the client and confirm that the server response cannot have the transfer-encoding header. - assertSucceeds(self.client.sendHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.sendHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.responseHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) - assertSucceeds(self.client.receiveHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.responseHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.sendHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.responseHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.responseHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) // Next, test this with trailers. - assertSucceeds(self.client.sendHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.sendHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.client.receiveHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.server.sendHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.trailers.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) - assertSucceeds(self.client.receiveHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.trailers.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.sendHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.server.sendHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.trailers.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.trailers.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) } func testRejectHeadersWithProxyConnectionHeader() { @@ -2586,22 +6196,100 @@ class ConnectionStateMachineTests: XCTestCase { let invalidExtraHeaders = [("proxy-connection", "close")] // First, test that client initial headers may not contain the proxy=connection header. - assertStreamError(type: .protocolError, self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) - assertStreamError(type: .protocolError, self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) + assertStreamError( + type: .protocolError, + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) + assertStreamError( + type: .protocolError, + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) // Next, set up a valid stream for the client and confirm that the server response cannot have the proxy-connection header. - assertSucceeds(self.client.sendHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertStreamError(type: .protocolError, self.server.sendHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.responseHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) - assertStreamError(type: .protocolError, self.client.receiveHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.responseHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertStreamError( + type: .protocolError, + self.server.sendHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.responseHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) + assertStreamError( + type: .protocolError, + self.client.receiveHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.responseHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) // Next, test this with trailers. - assertSucceeds(self.client.sendHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.sendHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.client.receiveHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertStreamError(type: .protocolError, self.server.sendHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.trailers.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) - assertStreamError(type: .protocolError, self.client.receiveHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.trailers.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.sendHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertStreamError( + type: .protocolError, + self.server.sendHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.trailers.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) + assertStreamError( + type: .protocolError, + self.client.receiveHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.trailers.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) } func testAllowHeadersWithProxyConnectionHeaderWhenValidationDisabled() { @@ -2618,22 +6306,94 @@ class ConnectionStateMachineTests: XCTestCase { let invalidExtraHeaders = [("proxy-connection", "close")] // First, test that client initial headers may not contain the proxy-connection header. - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) // Next, set up a valid stream for the client and confirm that the server response cannot have the proxy-connection header. - assertSucceeds(self.client.sendHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.sendHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.responseHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) - assertSucceeds(self.client.receiveHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.responseHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.sendHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.responseHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.responseHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) // Next, test this with trailers. - assertSucceeds(self.client.sendHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.sendHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.client.receiveHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.server.sendHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.trailers.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) - assertSucceeds(self.client.receiveHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.trailers.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.sendHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.server.sendHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.trailers.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.trailers.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) } func testRejectHeadersWithTEHeaderNotTrailers() { @@ -2646,22 +6406,96 @@ class ConnectionStateMachineTests: XCTestCase { let invalidExtraHeaders = [("te", "deflate")] // First, test that client initial headers may not contain the TE header. - assertStreamError(type: .protocolError, self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) - assertStreamError(type: .protocolError, self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) + assertStreamError( + type: .protocolError, + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) + assertStreamError( + type: .protocolError, + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) // Next, set up a valid stream for the client and confirm that the server response *may* have the TE header. This is allowed as TE is only defined on requests. - assertSucceeds(self.client.sendHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.sendHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.responseHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) - assertSucceeds(self.client.receiveHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.responseHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.sendHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.responseHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.responseHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) // Next, test this with trailers. Again, this is allowed. - assertSucceeds(self.client.sendHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.sendHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.client.receiveHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.server.sendHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.trailers.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) - assertSucceeds(self.client.receiveHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.trailers.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.sendHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.server.sendHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.trailers.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.trailers.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) } func testAllowHeadersWithTEHeaderNotTrailersWhenValidationDisabled() { @@ -2678,22 +6512,94 @@ class ConnectionStateMachineTests: XCTestCase { let invalidExtraHeaders = [("te", "deflate")] // First, test that client initial headers may not contain the TE header. - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) // Next, set up a valid stream for the client and confirm that the server response *may* have the TE header. This is allowed as TE is only defined on requests. - assertSucceeds(self.client.sendHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.sendHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.responseHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) - assertSucceeds(self.client.receiveHeaders(streamID: streamThree, headers: ConnectionStateMachineTests.responseHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.sendHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.responseHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamThree, + headers: ConnectionStateMachineTests.responseHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) // Next, test this with trailers. Again, this is allowed. - assertSucceeds(self.client.sendHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.sendHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.client.receiveHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.responseHeaders, isEndStreamSet: false)) - assertSucceeds(self.server.sendHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.trailers.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) - assertSucceeds(self.client.receiveHeaders(streamID: streamFive, headers: ConnectionStateMachineTests.trailers.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.sendHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.responseHeaders, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.server.sendHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.trailers.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) + assertSucceeds( + self.client.receiveHeaders( + streamID: streamFive, + headers: ConnectionStateMachineTests.trailers.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) } func testAllowHeadersWithTEHeaderSetToTrailers() { @@ -2704,28 +6610,56 @@ class ConnectionStateMachineTests: XCTestCase { let invalidExtraHeaders = [("te", "trailers")] // Client headers may contain TE: trailers. - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders.withExtraHeaders(invalidExtraHeaders), + isEndStreamSet: true + ) + ) } func testSettingActualMaxFrameSize() { self.exchangePreamble() // It must be possible to set SETTINGS_MAX_FRAME_SIZE to (2**24)-1. - let trickySettings: HTTP2Settings = [HTTP2Setting(parameter: .maxFrameSize, value: (1<<24) - 1)] + let trickySettings: HTTP2Settings = [HTTP2Setting(parameter: .maxFrameSize, value: (1 << 24) - 1)] assertSucceeds(self.client.sendSettings(trickySettings)) - assertSucceeds(self.server.receiveSettings(.settings(trickySettings), frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder)) - assertSucceeds(self.client.receiveSettings(.ack, frameEncoder: &self.clientEncoder, frameDecoder: &self.clientDecoder)) + assertSucceeds( + self.server.receiveSettings( + .settings(trickySettings), + frameEncoder: &self.serverEncoder, + frameDecoder: &self.serverDecoder + ) + ) + assertSucceeds( + self.client.receiveSettings(.ack, frameEncoder: &self.clientEncoder, frameDecoder: &self.clientDecoder) + ) } func testSettingActualInitialWindowSize() { self.exchangePreamble() // It must be possible to set SETTINGS_INITIAL_WINDOW_SIZE to (2**31)-1. - let trickySettings: HTTP2Settings = [HTTP2Setting(parameter: .initialWindowSize, value: (1<<31) - 1)] + let trickySettings: HTTP2Settings = [HTTP2Setting(parameter: .initialWindowSize, value: (1 << 31) - 1)] assertSucceeds(self.client.sendSettings(trickySettings)) - assertSucceeds(self.server.receiveSettings(.settings(trickySettings), frameEncoder: &self.serverEncoder, frameDecoder: &self.serverDecoder)) - assertSucceeds(self.client.receiveSettings(.ack, frameEncoder: &self.clientEncoder, frameDecoder: &self.clientDecoder)) + assertSucceeds( + self.server.receiveSettings( + .settings(trickySettings), + frameEncoder: &self.serverEncoder, + frameDecoder: &self.serverDecoder + ) + ) + assertSucceeds( + self.client.receiveSettings(.ack, frameEncoder: &self.clientEncoder, frameDecoder: &self.clientDecoder) + ) } func testPolicingExceedingContentLengthForRequests() { @@ -2733,28 +6667,59 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble() - let requestHeaders = HPACKHeaders([(":method", "POST"), (":authority", "localhost"), (":scheme", "https"), (":path", "/"), ("content-length", "25")]) + let requestHeaders = HPACKHeaders([ + (":method", "POST"), (":authority", "localhost"), (":scheme", "https"), (":path", "/"), + ("content-length", "25"), + ]) // Set up the connection assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: requestHeaders, isEndStreamSet: false)) assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: requestHeaders, isEndStreamSet: false)) // Send in 25 bytes over two frames, messing with the flow controlled length to just be a bit tricky. - assertSucceeds(self.client.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false)) - assertSucceeds(self.server.receiveData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false)) - assertSucceeds(self.client.sendData(streamID: streamOne, contentLength: 10, flowControlledBytes: 15, isEndStreamSet: false)) - assertSucceeds(self.server.receiveData(streamID: streamOne, contentLength: 10, flowControlledBytes: 15, isEndStreamSet: false)) + assertSucceeds( + self.client.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false) + ) + assertSucceeds( + self.server.receiveData( + streamID: streamOne, + contentLength: 15, + flowControlledBytes: 15, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.client.sendData(streamID: streamOne, contentLength: 10, flowControlledBytes: 15, isEndStreamSet: false) + ) + assertSucceeds( + self.server.receiveData( + streamID: streamOne, + contentLength: 10, + flowControlledBytes: 15, + isEndStreamSet: false + ) + ) var tempClient = self.client! var tempServer = self.server! // Sending any more data fails. - assertStreamError(type: .protocolError, tempClient.sendData(streamID: streamOne, contentLength: 1, flowControlledBytes: 1, isEndStreamSet: true)) - assertStreamError(type: .protocolError, tempServer.receiveData(streamID: streamOne, contentLength: 1, flowControlledBytes: 1, isEndStreamSet: true)) + assertStreamError( + type: .protocolError, + tempClient.sendData(streamID: streamOne, contentLength: 1, flowControlledBytes: 1, isEndStreamSet: true) + ) + assertStreamError( + type: .protocolError, + tempServer.receiveData(streamID: streamOne, contentLength: 1, flowControlledBytes: 1, isEndStreamSet: true) + ) // But if we send a zero length frame that works fine. - assertSucceeds(self.client.sendData(streamID: streamOne, contentLength: 0, flowControlledBytes: 1, isEndStreamSet: true)) - assertSucceeds(self.server.receiveData(streamID: streamOne, contentLength: 0, flowControlledBytes: 1, isEndStreamSet: true)) + assertSucceeds( + self.client.sendData(streamID: streamOne, contentLength: 0, flowControlledBytes: 1, isEndStreamSet: true) + ) + assertSucceeds( + self.server.receiveData(streamID: streamOne, contentLength: 0, flowControlledBytes: 1, isEndStreamSet: true) + ) } func testPolicingExceedingContentLengthForResponses() { @@ -2765,29 +6730,69 @@ class ConnectionStateMachineTests: XCTestCase { let responseHeaders = HPACKHeaders([(":status", "200"), ("content-length", "25")]) // Set up the connection - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) // The server responds assertSucceeds(self.server.sendHeaders(streamID: streamOne, headers: responseHeaders, isEndStreamSet: false)) assertSucceeds(self.client.receiveHeaders(streamID: streamOne, headers: responseHeaders, isEndStreamSet: false)) // Send in 25 bytes over two frames, messing with the flow controlled length to just be a bit tricky. - assertSucceeds(self.server.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false)) - assertSucceeds(self.client.receiveData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false)) - assertSucceeds(self.server.sendData(streamID: streamOne, contentLength: 10, flowControlledBytes: 15, isEndStreamSet: false)) - assertSucceeds(self.client.receiveData(streamID: streamOne, contentLength: 10, flowControlledBytes: 15, isEndStreamSet: false)) + assertSucceeds( + self.server.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false) + ) + assertSucceeds( + self.client.receiveData( + streamID: streamOne, + contentLength: 15, + flowControlledBytes: 15, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.server.sendData(streamID: streamOne, contentLength: 10, flowControlledBytes: 15, isEndStreamSet: false) + ) + assertSucceeds( + self.client.receiveData( + streamID: streamOne, + contentLength: 10, + flowControlledBytes: 15, + isEndStreamSet: false + ) + ) var tempClient = self.client! var tempServer = self.server! // Sending any more data fails. - assertStreamError(type: .protocolError, tempServer.sendData(streamID: streamOne, contentLength: 1, flowControlledBytes: 1, isEndStreamSet: true)) - assertStreamError(type: .protocolError, tempClient.receiveData(streamID: streamOne, contentLength: 1, flowControlledBytes: 1, isEndStreamSet: true)) + assertStreamError( + type: .protocolError, + tempServer.sendData(streamID: streamOne, contentLength: 1, flowControlledBytes: 1, isEndStreamSet: true) + ) + assertStreamError( + type: .protocolError, + tempClient.receiveData(streamID: streamOne, contentLength: 1, flowControlledBytes: 1, isEndStreamSet: true) + ) // But if we send a zero length frame that works fine. - assertSucceeds(self.server.sendData(streamID: streamOne, contentLength: 0, flowControlledBytes: 1, isEndStreamSet: true)) - assertSucceeds(self.client.receiveData(streamID: streamOne, contentLength: 0, flowControlledBytes: 1, isEndStreamSet: true)) + assertSucceeds( + self.server.sendData(streamID: streamOne, contentLength: 0, flowControlledBytes: 1, isEndStreamSet: true) + ) + assertSucceeds( + self.client.receiveData(streamID: streamOne, contentLength: 0, flowControlledBytes: 1, isEndStreamSet: true) + ) } func testPolicingMissingContentLengthForRequests() { @@ -2795,21 +6800,48 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble() - let requestHeaders = HPACKHeaders([(":method", "POST"), (":authority", "localhost"), (":scheme", "https"), (":path", "/"), ("content-length", "25")]) + let requestHeaders = HPACKHeaders([ + (":method", "POST"), (":authority", "localhost"), (":scheme", "https"), (":path", "/"), + ("content-length", "25"), + ]) // Set up the connection assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: requestHeaders, isEndStreamSet: false)) assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: requestHeaders, isEndStreamSet: false)) // Send in 20 bytes over two frames, messing with the flow controlled length to just be a bit tricky. - assertSucceeds(self.client.sendData(streamID: streamOne, contentLength: 10, flowControlledBytes: 15, isEndStreamSet: false)) - assertSucceeds(self.server.receiveData(streamID: streamOne, contentLength: 10, flowControlledBytes: 15, isEndStreamSet: false)) - assertSucceeds(self.client.sendData(streamID: streamOne, contentLength: 10, flowControlledBytes: 15, isEndStreamSet: false)) - assertSucceeds(self.server.receiveData(streamID: streamOne, contentLength: 10, flowControlledBytes: 15, isEndStreamSet: false)) + assertSucceeds( + self.client.sendData(streamID: streamOne, contentLength: 10, flowControlledBytes: 15, isEndStreamSet: false) + ) + assertSucceeds( + self.server.receiveData( + streamID: streamOne, + contentLength: 10, + flowControlledBytes: 15, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.client.sendData(streamID: streamOne, contentLength: 10, flowControlledBytes: 15, isEndStreamSet: false) + ) + assertSucceeds( + self.server.receiveData( + streamID: streamOne, + contentLength: 10, + flowControlledBytes: 15, + isEndStreamSet: false + ) + ) // Closing the stream fails. - assertStreamError(type: .protocolError, self.client.sendData(streamID: streamOne, contentLength: 0, flowControlledBytes: 1, isEndStreamSet: true)) - assertStreamError(type: .protocolError, self.server.receiveData(streamID: streamOne, contentLength: 0, flowControlledBytes: 1, isEndStreamSet: true)) + assertStreamError( + type: .protocolError, + self.client.sendData(streamID: streamOne, contentLength: 0, flowControlledBytes: 1, isEndStreamSet: true) + ) + assertStreamError( + type: .protocolError, + self.server.receiveData(streamID: streamOne, contentLength: 0, flowControlledBytes: 1, isEndStreamSet: true) + ) } func testPolicingMissingContentLengthForResponses() { @@ -2820,22 +6852,58 @@ class ConnectionStateMachineTests: XCTestCase { let responseHeaders = HPACKHeaders([(":status", "200"), ("content-length", "25")]) // Set up the connection - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) // The server responds assertSucceeds(self.server.sendHeaders(streamID: streamOne, headers: responseHeaders, isEndStreamSet: false)) assertSucceeds(self.client.receiveHeaders(streamID: streamOne, headers: responseHeaders, isEndStreamSet: false)) // Send in 20 bytes over two frames, messing with the flow controlled length to just be a bit tricky. - assertSucceeds(self.server.sendData(streamID: streamOne, contentLength: 10, flowControlledBytes: 15, isEndStreamSet: false)) - assertSucceeds(self.client.receiveData(streamID: streamOne, contentLength: 10, flowControlledBytes: 15, isEndStreamSet: false)) - assertSucceeds(self.server.sendData(streamID: streamOne, contentLength: 10, flowControlledBytes: 15, isEndStreamSet: false)) - assertSucceeds(self.client.receiveData(streamID: streamOne, contentLength: 10, flowControlledBytes: 15, isEndStreamSet: false)) + assertSucceeds( + self.server.sendData(streamID: streamOne, contentLength: 10, flowControlledBytes: 15, isEndStreamSet: false) + ) + assertSucceeds( + self.client.receiveData( + streamID: streamOne, + contentLength: 10, + flowControlledBytes: 15, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.server.sendData(streamID: streamOne, contentLength: 10, flowControlledBytes: 15, isEndStreamSet: false) + ) + assertSucceeds( + self.client.receiveData( + streamID: streamOne, + contentLength: 10, + flowControlledBytes: 15, + isEndStreamSet: false + ) + ) // Closing the stream fails. - assertStreamError(type: .protocolError, self.server.sendData(streamID: streamOne, contentLength: 0, flowControlledBytes: 1, isEndStreamSet: true)) - assertStreamError(type: .protocolError, self.client.receiveData(streamID: streamOne, contentLength: 0, flowControlledBytes: 1, isEndStreamSet: true)) + assertStreamError( + type: .protocolError, + self.server.sendData(streamID: streamOne, contentLength: 0, flowControlledBytes: 1, isEndStreamSet: true) + ) + assertStreamError( + type: .protocolError, + self.client.receiveData(streamID: streamOne, contentLength: 0, flowControlledBytes: 1, isEndStreamSet: true) + ) } func testPolicingInvalidContentLengthForRequestsWithEndStream() { @@ -2843,11 +6911,20 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble() - let requestHeaders = HPACKHeaders([(":method", "POST"), (":authority", "localhost"), (":scheme", "https"), (":path", "/"), ("content-length", "25")]) + let requestHeaders = HPACKHeaders([ + (":method", "POST"), (":authority", "localhost"), (":scheme", "https"), (":path", "/"), + ("content-length", "25"), + ]) // Set up the connection - assertStreamError(type: .protocolError, self.client.sendHeaders(streamID: streamOne, headers: requestHeaders, isEndStreamSet: true)) - assertStreamError(type: .protocolError, self.server.receiveHeaders(streamID: streamOne, headers: requestHeaders, isEndStreamSet: true)) + assertStreamError( + type: .protocolError, + self.client.sendHeaders(streamID: streamOne, headers: requestHeaders, isEndStreamSet: true) + ) + assertStreamError( + type: .protocolError, + self.server.receiveHeaders(streamID: streamOne, headers: requestHeaders, isEndStreamSet: true) + ) } func testPolicingInvalidContentLengthForResponsesWithEndStream() { @@ -2858,12 +6935,30 @@ class ConnectionStateMachineTests: XCTestCase { let responseHeaders = HPACKHeaders([(":status", "200"), ("content-length", "25")]) // Set up the connection - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) // The server responds - assertStreamError(type: .protocolError, self.server.sendHeaders(streamID: streamOne, headers: responseHeaders, isEndStreamSet: true)) - assertStreamError(type: .protocolError, self.client.receiveHeaders(streamID: streamOne, headers: responseHeaders, isEndStreamSet: true)) + assertStreamError( + type: .protocolError, + self.server.sendHeaders(streamID: streamOne, headers: responseHeaders, isEndStreamSet: true) + ) + assertStreamError( + type: .protocolError, + self.client.receiveHeaders(streamID: streamOne, headers: responseHeaders, isEndStreamSet: true) + ) } func testValidContentLengthForRequestsWithEndStream() { @@ -2871,7 +6966,10 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble() - let requestHeaders = HPACKHeaders([(":method", "POST"), (":authority", "localhost"), (":scheme", "https"), (":path", "/"), ("content-length", "0")]) + let requestHeaders = HPACKHeaders([ + (":method", "POST"), (":authority", "localhost"), (":scheme", "https"), (":path", "/"), + ("content-length", "0"), + ]) // Set up the connection assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: requestHeaders, isEndStreamSet: true)) @@ -2886,8 +6984,20 @@ class ConnectionStateMachineTests: XCTestCase { let responseHeaders = HPACKHeaders([(":status", "200"), ("content-length", "0")]) // Set up the connection - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) // The server responds assertSucceeds(self.server.sendHeaders(streamID: streamOne, headers: responseHeaders, isEndStreamSet: true)) @@ -2903,28 +7013,57 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble() - let requestHeaders = HPACKHeaders([(":method", "POST"), (":authority", "localhost"), (":scheme", "https"), (":path", "/"), ("content-length", "25")]) + let requestHeaders = HPACKHeaders([ + (":method", "POST"), (":authority", "localhost"), (":scheme", "https"), (":path", "/"), + ("content-length", "25"), + ]) // Set up the connection assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: requestHeaders, isEndStreamSet: false)) assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: requestHeaders, isEndStreamSet: false)) // Send in 25 bytes over two frames, messing with the flow controlled length to just be a bit tricky. - assertSucceeds(self.client.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false)) - assertSucceeds(self.server.receiveData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false)) - assertSucceeds(self.client.sendData(streamID: streamOne, contentLength: 10, flowControlledBytes: 15, isEndStreamSet: false)) - assertSucceeds(self.server.receiveData(streamID: streamOne, contentLength: 10, flowControlledBytes: 15, isEndStreamSet: false)) + assertSucceeds( + self.client.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false) + ) + assertSucceeds( + self.server.receiveData( + streamID: streamOne, + contentLength: 15, + flowControlledBytes: 15, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.client.sendData(streamID: streamOne, contentLength: 10, flowControlledBytes: 15, isEndStreamSet: false) + ) + assertSucceeds( + self.server.receiveData( + streamID: streamOne, + contentLength: 10, + flowControlledBytes: 15, + isEndStreamSet: false + ) + ) var tempClient = self.client! var tempServer = self.server! // Sending any more data succeeds. - assertSucceeds(tempClient.sendData(streamID: streamOne, contentLength: 1, flowControlledBytes: 1, isEndStreamSet: true)) - assertSucceeds(tempServer.receiveData(streamID: streamOne, contentLength: 1, flowControlledBytes: 1, isEndStreamSet: true)) + assertSucceeds( + tempClient.sendData(streamID: streamOne, contentLength: 1, flowControlledBytes: 1, isEndStreamSet: true) + ) + assertSucceeds( + tempServer.receiveData(streamID: streamOne, contentLength: 1, flowControlledBytes: 1, isEndStreamSet: true) + ) // But if we send a zero length frame that works fine. - assertSucceeds(self.client.sendData(streamID: streamOne, contentLength: 0, flowControlledBytes: 1, isEndStreamSet: true)) - assertSucceeds(self.server.receiveData(streamID: streamOne, contentLength: 0, flowControlledBytes: 1, isEndStreamSet: true)) + assertSucceeds( + self.client.sendData(streamID: streamOne, contentLength: 0, flowControlledBytes: 1, isEndStreamSet: true) + ) + assertSucceeds( + self.server.receiveData(streamID: streamOne, contentLength: 0, flowControlledBytes: 1, isEndStreamSet: true) + ) } func testNoPolicingExceedingContentLengthForResponsesWhenValidationDisabled() { @@ -2939,29 +7078,67 @@ class ConnectionStateMachineTests: XCTestCase { let responseHeaders = HPACKHeaders([(":status", "200"), ("content-length", "25")]) // Set up the connection - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) // The server responds assertSucceeds(self.server.sendHeaders(streamID: streamOne, headers: responseHeaders, isEndStreamSet: false)) assertSucceeds(self.client.receiveHeaders(streamID: streamOne, headers: responseHeaders, isEndStreamSet: false)) // Send in 25 bytes over two frames, messing with the flow controlled length to just be a bit tricky. - assertSucceeds(self.server.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false)) - assertSucceeds(self.client.receiveData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false)) - assertSucceeds(self.server.sendData(streamID: streamOne, contentLength: 10, flowControlledBytes: 15, isEndStreamSet: false)) - assertSucceeds(self.client.receiveData(streamID: streamOne, contentLength: 10, flowControlledBytes: 15, isEndStreamSet: false)) + assertSucceeds( + self.server.sendData(streamID: streamOne, contentLength: 15, flowControlledBytes: 15, isEndStreamSet: false) + ) + assertSucceeds( + self.client.receiveData( + streamID: streamOne, + contentLength: 15, + flowControlledBytes: 15, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.server.sendData(streamID: streamOne, contentLength: 10, flowControlledBytes: 15, isEndStreamSet: false) + ) + assertSucceeds( + self.client.receiveData( + streamID: streamOne, + contentLength: 10, + flowControlledBytes: 15, + isEndStreamSet: false + ) + ) var tempClient = self.client! var tempServer = self.server! // Sending any more data succeeds. - assertSucceeds(tempServer.sendData(streamID: streamOne, contentLength: 1, flowControlledBytes: 1, isEndStreamSet: true)) - assertSucceeds(tempClient.receiveData(streamID: streamOne, contentLength: 1, flowControlledBytes: 1, isEndStreamSet: true)) + assertSucceeds( + tempServer.sendData(streamID: streamOne, contentLength: 1, flowControlledBytes: 1, isEndStreamSet: true) + ) + assertSucceeds( + tempClient.receiveData(streamID: streamOne, contentLength: 1, flowControlledBytes: 1, isEndStreamSet: true) + ) // But if we send a zero length frame that works fine. - assertSucceeds(self.server.sendData(streamID: streamOne, contentLength: 0, flowControlledBytes: 1, isEndStreamSet: true)) - assertSucceeds(self.client.receiveData(streamID: streamOne, contentLength: 0, flowControlledBytes: 1, isEndStreamSet: true)) + assertSucceeds( + self.server.sendData(streamID: streamOne, contentLength: 0, flowControlledBytes: 1, isEndStreamSet: true) + ) + assertSucceeds( + self.client.receiveData(streamID: streamOne, contentLength: 0, flowControlledBytes: 1, isEndStreamSet: true) + ) } func testNoPolicingMissingContentLengthForRequestsWhenValidationDisabled() { @@ -2973,21 +7150,46 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble() - let requestHeaders = HPACKHeaders([(":method", "POST"), (":authority", "localhost"), (":scheme", "https"), (":path", "/"), ("content-length", "25")]) + let requestHeaders = HPACKHeaders([ + (":method", "POST"), (":authority", "localhost"), (":scheme", "https"), (":path", "/"), + ("content-length", "25"), + ]) // Set up the connection assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: requestHeaders, isEndStreamSet: false)) assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: requestHeaders, isEndStreamSet: false)) // Send in 20 bytes over two frames, messing with the flow controlled length to just be a bit tricky. - assertSucceeds(self.client.sendData(streamID: streamOne, contentLength: 10, flowControlledBytes: 15, isEndStreamSet: false)) - assertSucceeds(self.server.receiveData(streamID: streamOne, contentLength: 10, flowControlledBytes: 15, isEndStreamSet: false)) - assertSucceeds(self.client.sendData(streamID: streamOne, contentLength: 10, flowControlledBytes: 15, isEndStreamSet: false)) - assertSucceeds(self.server.receiveData(streamID: streamOne, contentLength: 10, flowControlledBytes: 15, isEndStreamSet: false)) + assertSucceeds( + self.client.sendData(streamID: streamOne, contentLength: 10, flowControlledBytes: 15, isEndStreamSet: false) + ) + assertSucceeds( + self.server.receiveData( + streamID: streamOne, + contentLength: 10, + flowControlledBytes: 15, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.client.sendData(streamID: streamOne, contentLength: 10, flowControlledBytes: 15, isEndStreamSet: false) + ) + assertSucceeds( + self.server.receiveData( + streamID: streamOne, + contentLength: 10, + flowControlledBytes: 15, + isEndStreamSet: false + ) + ) // Closing the stream succeeds. - assertSucceeds(self.client.sendData(streamID: streamOne, contentLength: 0, flowControlledBytes: 1, isEndStreamSet: true)) - assertSucceeds(self.server.receiveData(streamID: streamOne, contentLength: 0, flowControlledBytes: 1, isEndStreamSet: true)) + assertSucceeds( + self.client.sendData(streamID: streamOne, contentLength: 0, flowControlledBytes: 1, isEndStreamSet: true) + ) + assertSucceeds( + self.server.receiveData(streamID: streamOne, contentLength: 0, flowControlledBytes: 1, isEndStreamSet: true) + ) } func testNoPolicingMissingContentLengthForResponsesWhenValidationDisabled() { @@ -3002,22 +7204,56 @@ class ConnectionStateMachineTests: XCTestCase { let responseHeaders = HPACKHeaders([(":status", "200"), ("content-length", "25")]) // Set up the connection - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) // The server responds assertSucceeds(self.server.sendHeaders(streamID: streamOne, headers: responseHeaders, isEndStreamSet: false)) assertSucceeds(self.client.receiveHeaders(streamID: streamOne, headers: responseHeaders, isEndStreamSet: false)) // Send in 20 bytes over two frames, messing with the flow controlled length to just be a bit tricky. - assertSucceeds(self.server.sendData(streamID: streamOne, contentLength: 10, flowControlledBytes: 15, isEndStreamSet: false)) - assertSucceeds(self.client.receiveData(streamID: streamOne, contentLength: 10, flowControlledBytes: 15, isEndStreamSet: false)) - assertSucceeds(self.server.sendData(streamID: streamOne, contentLength: 10, flowControlledBytes: 15, isEndStreamSet: false)) - assertSucceeds(self.client.receiveData(streamID: streamOne, contentLength: 10, flowControlledBytes: 15, isEndStreamSet: false)) + assertSucceeds( + self.server.sendData(streamID: streamOne, contentLength: 10, flowControlledBytes: 15, isEndStreamSet: false) + ) + assertSucceeds( + self.client.receiveData( + streamID: streamOne, + contentLength: 10, + flowControlledBytes: 15, + isEndStreamSet: false + ) + ) + assertSucceeds( + self.server.sendData(streamID: streamOne, contentLength: 10, flowControlledBytes: 15, isEndStreamSet: false) + ) + assertSucceeds( + self.client.receiveData( + streamID: streamOne, + contentLength: 10, + flowControlledBytes: 15, + isEndStreamSet: false + ) + ) // Closing the stream succeeds. - assertSucceeds(self.server.sendData(streamID: streamOne, contentLength: 0, flowControlledBytes: 1, isEndStreamSet: true)) - assertSucceeds(self.client.receiveData(streamID: streamOne, contentLength: 0, flowControlledBytes: 1, isEndStreamSet: true)) + assertSucceeds( + self.server.sendData(streamID: streamOne, contentLength: 0, flowControlledBytes: 1, isEndStreamSet: true) + ) + assertSucceeds( + self.client.receiveData(streamID: streamOne, contentLength: 0, flowControlledBytes: 1, isEndStreamSet: true) + ) } func testNoPolicingInvalidContentLengthForRequestsWithEndStreamWhenValidationDisabled() { @@ -3029,7 +7265,10 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble() - let requestHeaders = HPACKHeaders([(":method", "POST"), (":authority", "localhost"), (":scheme", "https"), (":path", "/"), ("content-length", "25")]) + let requestHeaders = HPACKHeaders([ + (":method", "POST"), (":authority", "localhost"), (":scheme", "https"), (":path", "/"), + ("content-length", "25"), + ]) // Set up the succeeds assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: requestHeaders, isEndStreamSet: true)) @@ -3048,8 +7287,20 @@ class ConnectionStateMachineTests: XCTestCase { let responseHeaders = HPACKHeaders([(":status", "200"), ("content-length", "25")]) // Set up the connection - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) // The server succeeds assertSucceeds(self.server.sendHeaders(streamID: streamOne, headers: responseHeaders, isEndStreamSet: true)) @@ -3061,8 +7312,20 @@ class ConnectionStateMachineTests: XCTestCase { let streamOne = HTTP2StreamID(1) // Set up the connection - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) // The server succeeds let responseHeaders = HPACKHeaders([(":status", "200"), ("content-length", "25")]) @@ -3071,7 +7334,10 @@ class ConnectionStateMachineTests: XCTestCase { // Let's test that we cannot emit two RST_STREAMs for the same stream. assertSucceeds(self.client.sendRstStream(streamID: streamOne, reason: .cancel)) - assertConnectionError(type: .streamClosed, self.client.sendRstStream(streamID: streamOne, reason: .streamClosed)) + assertConnectionError( + type: .streamClosed, + self.client.sendRstStream(streamID: streamOne, reason: .streamClosed) + ) // But let's also verify that we're happily ignoring this should the other peer do so. assertSucceeds(self.server.receiveRstStream(streamID: streamOne, reason: .cancel)) @@ -3095,22 +7361,38 @@ class ConnectionStateMachineTests: XCTestCase { self.server = .init(role: .server) self.client = .init(role: .client) - + self.exchangePreamble() - + let responseHeaders = HPACKHeaders([(":status", "304"), ("content-length", "25")]) - + // Set up the connection - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + // The server responds assertSucceeds(self.server.sendHeaders(streamID: streamOne, headers: responseHeaders, isEndStreamSet: false)) assertSucceeds(self.client.receiveHeaders(streamID: streamOne, headers: responseHeaders, isEndStreamSet: false)) - + // Send in 0 bytes over two sets - assertSucceeds(self.server.sendData(streamID: streamOne, contentLength: 0, flowControlledBytes: 0, isEndStreamSet: true)) - assertSucceeds(self.client.receiveData(streamID: streamOne, contentLength: 0, flowControlledBytes: 0, isEndStreamSet: true)) + assertSucceeds( + self.server.sendData(streamID: streamOne, contentLength: 0, flowControlledBytes: 0, isEndStreamSet: true) + ) + assertSucceeds( + self.client.receiveData(streamID: streamOne, contentLength: 0, flowControlledBytes: 0, isEndStreamSet: true) + ) } func testContentLengthForStatus304Failure() { @@ -3124,16 +7406,34 @@ class ConnectionStateMachineTests: XCTestCase { let responseHeaders = HPACKHeaders([(":status", "304"), ("content-length", "25")]) // Set up the connection - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) // The server responds assertSucceeds(self.server.sendHeaders(streamID: streamOne, headers: responseHeaders, isEndStreamSet: false)) assertSucceeds(self.client.receiveHeaders(streamID: streamOne, headers: responseHeaders, isEndStreamSet: false)) // Send in 1 byte over one frame - assertStreamError(type: HTTP2ErrorCode.protocolError, self.server.sendData(streamID: streamOne, contentLength: 1, flowControlledBytes: 1, isEndStreamSet: true)) - assertStreamError(type: HTTP2ErrorCode.protocolError, self.client.receiveData(streamID: streamOne, contentLength: 1, flowControlledBytes: 1, isEndStreamSet: true)) + assertStreamError( + type: HTTP2ErrorCode.protocolError, + self.server.sendData(streamID: streamOne, contentLength: 1, flowControlledBytes: 1, isEndStreamSet: true) + ) + assertStreamError( + type: HTTP2ErrorCode.protocolError, + self.client.receiveData(streamID: streamOne, contentLength: 1, flowControlledBytes: 1, isEndStreamSet: true) + ) } func testContentLengthForMethodHead() { @@ -3144,7 +7444,10 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble() - let requestHeaders = HPACKHeaders([(":method", "HEAD"), (":authority", "localhost"), (":scheme", "https"), (":path", "/"), ("user-agent", "test")]) + let requestHeaders = HPACKHeaders([ + (":method", "HEAD"), (":authority", "localhost"), (":scheme", "https"), (":path", "/"), + ("user-agent", "test"), + ]) let responseHeaders = HPACKHeaders([(":status", "200"), ("content-length", "25")]) // Set up the connection @@ -3156,8 +7459,12 @@ class ConnectionStateMachineTests: XCTestCase { assertSucceeds(self.client.receiveHeaders(streamID: streamOne, headers: responseHeaders, isEndStreamSet: false)) // Send in 0 bytes over one frame - assertSucceeds(self.server.sendData(streamID: streamOne, contentLength: 0, flowControlledBytes: 0, isEndStreamSet: true)) - assertSucceeds(self.client.receiveData(streamID: streamOne, contentLength: 0, flowControlledBytes: 0, isEndStreamSet: true)) + assertSucceeds( + self.server.sendData(streamID: streamOne, contentLength: 0, flowControlledBytes: 0, isEndStreamSet: true) + ) + assertSucceeds( + self.client.receiveData(streamID: streamOne, contentLength: 0, flowControlledBytes: 0, isEndStreamSet: true) + ) } func testContentLengthForHeadFailure() { @@ -3168,7 +7475,10 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble() - let requestHeaders = HPACKHeaders([(":method", "HEAD"), (":authority", "localhost"), (":scheme", "https"), (":path", "/"), ("user-agent", "test")]) + let requestHeaders = HPACKHeaders([ + (":method", "HEAD"), (":authority", "localhost"), (":scheme", "https"), (":path", "/"), + ("user-agent", "test"), + ]) let responseHeaders = HPACKHeaders([(":status", "200"), ("content-length", "25")]) // Set up the connection @@ -3180,33 +7490,68 @@ class ConnectionStateMachineTests: XCTestCase { assertSucceeds(self.client.receiveHeaders(streamID: streamOne, headers: responseHeaders, isEndStreamSet: false)) // Send in 1 byte over 1 frame - assertStreamError(type: HTTP2ErrorCode.protocolError, self.server.sendData(streamID: streamOne, contentLength: 1, flowControlledBytes: 1, isEndStreamSet: true)) - assertStreamError(type: HTTP2ErrorCode.protocolError, self.client.receiveData(streamID: streamOne, contentLength: 1, flowControlledBytes: 1, isEndStreamSet: true)) + assertStreamError( + type: HTTP2ErrorCode.protocolError, + self.server.sendData(streamID: streamOne, contentLength: 1, flowControlledBytes: 1, isEndStreamSet: true) + ) + assertStreamError( + type: HTTP2ErrorCode.protocolError, + self.client.receiveData(streamID: streamOne, contentLength: 1, flowControlledBytes: 1, isEndStreamSet: true) + ) } func testPushHeadRequestFailure() { let streamOne = HTTP2StreamID(1) let streamTwo = HTTP2StreamID(2) - + self.exchangePreamble() - - let requestHeaders = HPACKHeaders([(":method", "HEAD"), (":authority", "localhost"), (":scheme", "https"), (":path", "/"), ("user-agent", "test")]) + + let requestHeaders = HPACKHeaders([ + (":method", "HEAD"), (":authority", "localhost"), (":scheme", "https"), (":path", "/"), + ("user-agent", "test"), + ]) let responseHeaders = HPACKHeaders([(":status", "200"), ("content-length", "25")]) - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + // Server can push right away - assertSucceeds(self.server.sendPushPromise(originalStreamID: streamOne, childStreamID: streamTwo, headers: requestHeaders)) - assertSucceeds(self.client.receivePushPromise(originalStreamID: streamOne, childStreamID: streamTwo, headers: requestHeaders)) + assertSucceeds( + self.server.sendPushPromise(originalStreamID: streamOne, childStreamID: streamTwo, headers: requestHeaders) + ) + assertSucceeds( + self.client.receivePushPromise( + originalStreamID: streamOne, + childStreamID: streamTwo, + headers: requestHeaders + ) + ) // The server responds assertSucceeds(self.server.sendHeaders(streamID: streamTwo, headers: responseHeaders, isEndStreamSet: false)) assertSucceeds(self.client.receiveHeaders(streamID: streamTwo, headers: responseHeaders, isEndStreamSet: false)) // Send in 1 byte over one frame - assertStreamError(type: HTTP2ErrorCode.protocolError, self.server.sendData(streamID: streamTwo, contentLength: 1, flowControlledBytes: 1, isEndStreamSet: true)) - assertStreamError(type: HTTP2ErrorCode.protocolError, self.client.receiveData(streamID: streamTwo, contentLength: 1, flowControlledBytes: 1, isEndStreamSet: true)) + assertStreamError( + type: HTTP2ErrorCode.protocolError, + self.server.sendData(streamID: streamTwo, contentLength: 1, flowControlledBytes: 1, isEndStreamSet: true) + ) + assertStreamError( + type: HTTP2ErrorCode.protocolError, + self.client.receiveData(streamID: streamTwo, contentLength: 1, flowControlledBytes: 1, isEndStreamSet: true) + ) } func testPushHeadRequest() { @@ -3215,22 +7560,47 @@ class ConnectionStateMachineTests: XCTestCase { self.exchangePreamble() - let requestHeaders = HPACKHeaders([(":method", "HEAD"), (":authority", "localhost"), (":scheme", "https"), (":path", "/"), ("user-agent", "test")]) + let requestHeaders = HPACKHeaders([ + (":method", "HEAD"), (":authority", "localhost"), (":scheme", "https"), (":path", "/"), + ("user-agent", "test"), + ]) let responseHeaders = HPACKHeaders([(":status", "200"), ("content-length", "25")]) - assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: ConnectionStateMachineTests.requestHeaders, isEndStreamSet: true)) + assertSucceeds( + self.client.sendHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) + assertSucceeds( + self.server.receiveHeaders( + streamID: streamOne, + headers: ConnectionStateMachineTests.requestHeaders, + isEndStreamSet: true + ) + ) // Server can push right away - assertSucceeds(self.server.sendPushPromise(originalStreamID: streamOne, childStreamID: streamTwo, headers: requestHeaders)) - assertSucceeds(self.client.receivePushPromise(originalStreamID: streamOne, childStreamID: streamTwo, headers: requestHeaders)) + assertSucceeds( + self.server.sendPushPromise(originalStreamID: streamOne, childStreamID: streamTwo, headers: requestHeaders) + ) + assertSucceeds( + self.client.receivePushPromise( + originalStreamID: streamOne, + childStreamID: streamTwo, + headers: requestHeaders + ) + ) // The server responds assertSucceeds(self.server.sendHeaders(streamID: streamTwo, headers: responseHeaders, isEndStreamSet: false)) assertSucceeds(self.client.receiveHeaders(streamID: streamTwo, headers: responseHeaders, isEndStreamSet: false)) // Send in 0 bytes over one frame - assertSucceeds(self.client.receiveData(streamID: streamTwo, contentLength: 0, flowControlledBytes: 0, isEndStreamSet: true)) + assertSucceeds( + self.client.receiveData(streamID: streamTwo, contentLength: 0, flowControlledBytes: 0, isEndStreamSet: true) + ) } func testNegativeContentLengthHeader() { @@ -3242,10 +7612,18 @@ class ConnectionStateMachineTests: XCTestCase { // Set up the connection assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: Self.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: Self.requestHeaders, isEndStreamSet: true)) + assertSucceeds( + self.server.receiveHeaders(streamID: streamOne, headers: Self.requestHeaders, isEndStreamSet: true) + ) - assertStreamError(type: .protocolError, self.server.sendHeaders(streamID: streamOne, headers: responseHeaders, isEndStreamSet: false)) - assertStreamError(type: .protocolError, self.client.receiveHeaders(streamID: streamOne, headers: responseHeaders, isEndStreamSet: false)) + assertStreamError( + type: .protocolError, + self.server.sendHeaders(streamID: streamOne, headers: responseHeaders, isEndStreamSet: false) + ) + assertStreamError( + type: .protocolError, + self.client.receiveHeaders(streamID: streamOne, headers: responseHeaders, isEndStreamSet: false) + ) } func testInvalidContentLengthHeader() { @@ -3257,10 +7635,18 @@ class ConnectionStateMachineTests: XCTestCase { // Set up the connection assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: Self.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: Self.requestHeaders, isEndStreamSet: true)) + assertSucceeds( + self.server.receiveHeaders(streamID: streamOne, headers: Self.requestHeaders, isEndStreamSet: true) + ) - assertStreamError(type: .protocolError, self.server.sendHeaders(streamID: streamOne, headers: responseHeaders, isEndStreamSet: false)) - assertStreamError(type: .protocolError, self.client.receiveHeaders(streamID: streamOne, headers: responseHeaders, isEndStreamSet: false)) + assertStreamError( + type: .protocolError, + self.server.sendHeaders(streamID: streamOne, headers: responseHeaders, isEndStreamSet: false) + ) + assertStreamError( + type: .protocolError, + self.client.receiveHeaders(streamID: streamOne, headers: responseHeaders, isEndStreamSet: false) + ) } func testContentLengthHeadersMismatch() { @@ -3272,14 +7658,21 @@ class ConnectionStateMachineTests: XCTestCase { // Set up the connection assertSucceeds(self.client.sendHeaders(streamID: streamOne, headers: Self.requestHeaders, isEndStreamSet: true)) - assertSucceeds(self.server.receiveHeaders(streamID: streamOne, headers: Self.requestHeaders, isEndStreamSet: true)) + assertSucceeds( + self.server.receiveHeaders(streamID: streamOne, headers: Self.requestHeaders, isEndStreamSet: true) + ) - assertStreamError(type: .protocolError, self.server.sendHeaders(streamID: streamOne, headers: responseHeaders, isEndStreamSet: false)) - assertStreamError(type: .protocolError, self.client.receiveHeaders(streamID: streamOne, headers: responseHeaders, isEndStreamSet: false)) + assertStreamError( + type: .protocolError, + self.server.sendHeaders(streamID: streamOne, headers: responseHeaders, isEndStreamSet: false) + ) + assertStreamError( + type: .protocolError, + self.client.receiveHeaders(streamID: streamOne, headers: responseHeaders, isEndStreamSet: false) + ) } } - extension HPACKHeaders { /// Take the header block and add some more. internal func withExtraHeaders(_ headers: [(String, String)]) -> HPACKHeaders { @@ -3290,4 +7683,3 @@ extension HPACKHeaders { return newHeaders } } - diff --git a/Tests/NIOHTTP2Tests/ContentLengthVerifierTests.swift b/Tests/NIOHTTP2Tests/ContentLengthVerifierTests.swift index 3566538..3a7070e 100644 --- a/Tests/NIOHTTP2Tests/ContentLengthVerifierTests.swift +++ b/Tests/NIOHTTP2Tests/ContentLengthVerifierTests.swift @@ -12,13 +12,16 @@ // //===----------------------------------------------------------------------===// -import XCTest import NIOHPACK +import XCTest + @testable import NIOHTTP2 class ContentLengthVerifierTests: XCTestCase { func testDuplicatedLengthHeadersPermitted() throws { - var headers = HPACKHeaders([("Host", "apple.com"), ("content-length", "1834"), ("User-Agent", "myCoolClient/1.0")]) + var headers = HPACKHeaders([ + ("Host", "apple.com"), ("content-length", "1834"), ("User-Agent", "myCoolClient/1.0"), + ]) XCTAssertNoThrow(try ContentLengthVerifier(headers, requestMethod: nil)) var verifier = try assertNoThrowWithValue(try ContentLengthVerifier(headers, requestMethod: nil)) XCTAssertEqual(1834, verifier.expectedContentLength) @@ -39,7 +42,9 @@ class ContentLengthVerifierTests: XCTestCase { } func testDuplicatedConflictingLengthHeadersThrow() throws { - var headers = HPACKHeaders([("Host", "apple.com"), ("content-length", "1834"), ("User-Agent", "myCoolClient/1.0")]) + var headers = HPACKHeaders([ + ("Host", "apple.com"), ("content-length", "1834"), ("User-Agent", "myCoolClient/1.0"), + ]) let verifier = try assertNoThrowWithValue(try ContentLengthVerifier(headers, requestMethod: nil)) XCTAssertEqual(1834, verifier.expectedContentLength) @@ -50,7 +55,9 @@ class ContentLengthVerifierTests: XCTestCase { } func testNumericallyEquivalentButConflictingLengthHeadersThrow() throws { - var headers = HPACKHeaders([("Host", "apple.com"), ("content-length", "1834"), ("User-Agent", "myCoolClient/1.0")]) + var headers = HPACKHeaders([ + ("Host", "apple.com"), ("content-length", "1834"), ("User-Agent", "myCoolClient/1.0"), + ]) let verifier = try assertNoThrowWithValue(try ContentLengthVerifier(headers, requestMethod: nil)) XCTAssertEqual(1834, verifier.expectedContentLength) @@ -61,53 +68,68 @@ class ContentLengthVerifierTests: XCTestCase { } func testNegativeLengthHeaderThrows() throws { - let headers = HPACKHeaders([("Host", "apple.com"), ("content-length", "-1"), ("User-Agent", "myCoolClient/1.0")]) + let headers = HPACKHeaders([ + ("Host", "apple.com"), ("content-length", "-1"), ("User-Agent", "myCoolClient/1.0"), + ]) XCTAssertThrowsError(try ContentLengthVerifier(headers, requestMethod: nil)) { error in XCTAssertTrue(error is NIOHTTP2Errors.ContentLengthHeaderNegative) } } func testMinIntLengthHeaderDoesntPanic() throws { - let headers = HPACKHeaders([("Host", "apple.com"), ("content-length", String(Int.min)), ("User-Agent", "myCoolClient/1.0")]) + let headers = HPACKHeaders([ + ("Host", "apple.com"), ("content-length", String(Int.min)), ("User-Agent", "myCoolClient/1.0"), + ]) XCTAssertThrowsError(try ContentLengthVerifier(headers, requestMethod: nil)) { error in XCTAssertTrue(error is NIOHTTP2Errors.ContentLengthHeaderNegative) } } func testMaxIntLengthHeaderDoesntPanic() throws { - let headers = HPACKHeaders([("Host", "apple.com"), ("content-length", String(Int.max)), ("User-Agent", "myCoolClient/1.0")]) + let headers = HPACKHeaders([ + ("Host", "apple.com"), ("content-length", String(Int.max)), ("User-Agent", "myCoolClient/1.0"), + ]) let verifier = try assertNoThrowWithValue(try ContentLengthVerifier(headers, requestMethod: nil)) XCTAssertEqual(Int.max, verifier.expectedContentLength) } func testInvalidLengthHeaderValuesThrow() throws { - var headers = HPACKHeaders([("Host", "apple.com"), ("content-length", "0xFF"), ("User-Agent", "myCoolClient/1.0")]) + var headers = HPACKHeaders([ + ("Host", "apple.com"), ("content-length", "0xFF"), ("User-Agent", "myCoolClient/1.0"), + ]) XCTAssertThrowsError(try ContentLengthVerifier(headers, requestMethod: nil)) { error in XCTAssertTrue(error is NIOHTTP2Errors.ContentLengthHeaderMalformedValue) } // Int.min - 1 - headers = HPACKHeaders([("Host", "apple.com"), ("content-length", "-9223372036854775809"), ("User-Agent", "myCoolClient/1.0")]) + headers = HPACKHeaders([ + ("Host", "apple.com"), ("content-length", "-9223372036854775809"), ("User-Agent", "myCoolClient/1.0"), + ]) XCTAssertThrowsError(try ContentLengthVerifier(headers, requestMethod: nil)) { error in XCTAssertTrue(error is NIOHTTP2Errors.ContentLengthHeaderMalformedValue) } // Int.max + 1 - headers = HPACKHeaders([("Host", "apple.com"), ("content-length", "9223372036854775809"), ("User-Agent", "myCoolClient/1.0")]) + headers = HPACKHeaders([ + ("Host", "apple.com"), ("content-length", "9223372036854775809"), ("User-Agent", "myCoolClient/1.0"), + ]) XCTAssertThrowsError(try ContentLengthVerifier(headers, requestMethod: nil)) { error in XCTAssertTrue(error is NIOHTTP2Errors.ContentLengthHeaderMalformedValue) } } func testContentLengthVerifier_whenResponseStatusIs304() throws { - let headers = HPACKHeaders([(":status", "304"), ("Host", "apple.com"), ("content-length", "1834"), ("User-Agent", "myCoolClient/1.0")]) + let headers = HPACKHeaders([ + (":status", "304"), ("Host", "apple.com"), ("content-length", "1834"), ("User-Agent", "myCoolClient/1.0"), + ]) let verifier = try assertNoThrowWithValue(try ContentLengthVerifier(headers, requestMethod: "GET")) XCTAssertEqual(0, verifier.expectedContentLength) } - func testContentLengthVerifier_whenRequestMethodIsHead() throws { - let headers = HPACKHeaders([("Host", "apple.com"), ("content-length", "1834"), ("User-Agent", "myCoolClient/1.0")]) + let headers = HPACKHeaders([ + ("Host", "apple.com"), ("content-length", "1834"), ("User-Agent", "myCoolClient/1.0"), + ]) let verifier = try assertNoThrowWithValue(try ContentLengthVerifier(headers, requestMethod: "HEAD")) XCTAssertEqual(0, verifier.expectedContentLength) } diff --git a/Tests/NIOHTTP2Tests/ControlFrameBufferTests.swift b/Tests/NIOHTTP2Tests/ControlFrameBufferTests.swift index f75165c..e0b54f9 100644 --- a/Tests/NIOHTTP2Tests/ControlFrameBufferTests.swift +++ b/Tests/NIOHTTP2Tests/ControlFrameBufferTests.swift @@ -12,11 +12,11 @@ // //===----------------------------------------------------------------------===// -import XCTest import NIOCore import NIOHPACK -@testable import NIOHTTP2 +import XCTest +@testable import NIOHTTP2 final class ControlFrameBufferTests: XCTestCase { func testByDefaultAllFramesPassThroughWhenChannelIsWritable() throws { @@ -24,13 +24,23 @@ final class ControlFrameBufferTests: XCTestCase { XCTAssertNoThrow(try buffer.processOutboundFrame(.data, promise: nil, channelWritable: true).assertForward()) XCTAssertNoThrow(try buffer.processOutboundFrame(.headers, promise: nil, channelWritable: true).assertForward()) - XCTAssertNoThrow(try buffer.processOutboundFrame(.priority, promise: nil, channelWritable: true).assertForward()) - XCTAssertNoThrow(try buffer.processOutboundFrame(.rstStream, promise: nil, channelWritable: true).assertForward()) - XCTAssertNoThrow(try buffer.processOutboundFrame(.settings, promise: nil, channelWritable: true).assertForward()) - XCTAssertNoThrow(try buffer.processOutboundFrame(.pushPromise, promise: nil, channelWritable: true).assertForward()) + XCTAssertNoThrow( + try buffer.processOutboundFrame(.priority, promise: nil, channelWritable: true).assertForward() + ) + XCTAssertNoThrow( + try buffer.processOutboundFrame(.rstStream, promise: nil, channelWritable: true).assertForward() + ) + XCTAssertNoThrow( + try buffer.processOutboundFrame(.settings, promise: nil, channelWritable: true).assertForward() + ) + XCTAssertNoThrow( + try buffer.processOutboundFrame(.pushPromise, promise: nil, channelWritable: true).assertForward() + ) XCTAssertNoThrow(try buffer.processOutboundFrame(.ping, promise: nil, channelWritable: true).assertForward()) XCTAssertNoThrow(try buffer.processOutboundFrame(.goAway, promise: nil, channelWritable: true).assertForward()) - XCTAssertNoThrow(try buffer.processOutboundFrame(.windowUpdate, promise: nil, channelWritable: true).assertForward()) + XCTAssertNoThrow( + try buffer.processOutboundFrame(.windowUpdate, promise: nil, channelWritable: true).assertForward() + ) XCTAssertNoThrow(try buffer.processOutboundFrame(.altSvc, promise: nil, channelWritable: true).assertForward()) XCTAssertNoThrow(try buffer.processOutboundFrame(.origin, promise: nil, channelWritable: true).assertForward()) @@ -44,14 +54,26 @@ final class ControlFrameBufferTests: XCTestCase { // we'll trip an assert. var buffer = ControlFrameBuffer(maximumBufferSize: 1024) - XCTAssertNoThrow(try buffer.processOutboundFrame(.headers, promise: nil, channelWritable: false).assertNothing()) - XCTAssertNoThrow(try buffer.processOutboundFrame(.priority, promise: nil, channelWritable: false).assertNothing()) - XCTAssertNoThrow(try buffer.processOutboundFrame(.rstStream, promise: nil, channelWritable: false).assertNothing()) - XCTAssertNoThrow(try buffer.processOutboundFrame(.settings, promise: nil, channelWritable: false).assertNothing()) - XCTAssertNoThrow(try buffer.processOutboundFrame(.pushPromise, promise: nil, channelWritable: false).assertNothing()) + XCTAssertNoThrow( + try buffer.processOutboundFrame(.headers, promise: nil, channelWritable: false).assertNothing() + ) + XCTAssertNoThrow( + try buffer.processOutboundFrame(.priority, promise: nil, channelWritable: false).assertNothing() + ) + XCTAssertNoThrow( + try buffer.processOutboundFrame(.rstStream, promise: nil, channelWritable: false).assertNothing() + ) + XCTAssertNoThrow( + try buffer.processOutboundFrame(.settings, promise: nil, channelWritable: false).assertNothing() + ) + XCTAssertNoThrow( + try buffer.processOutboundFrame(.pushPromise, promise: nil, channelWritable: false).assertNothing() + ) XCTAssertNoThrow(try buffer.processOutboundFrame(.ping, promise: nil, channelWritable: false).assertNothing()) XCTAssertNoThrow(try buffer.processOutboundFrame(.goAway, promise: nil, channelWritable: false).assertNothing()) - XCTAssertNoThrow(try buffer.processOutboundFrame(.windowUpdate, promise: nil, channelWritable: false).assertNothing()) + XCTAssertNoThrow( + try buffer.processOutboundFrame(.windowUpdate, promise: nil, channelWritable: false).assertNothing() + ) XCTAssertNoThrow(try buffer.processOutboundFrame(.altSvc, promise: nil, channelWritable: false).assertNothing()) XCTAssertNoThrow(try buffer.processOutboundFrame(.origin, promise: nil, channelWritable: false).assertNothing()) @@ -65,23 +87,37 @@ final class ControlFrameBufferTests: XCTestCase { while let flushedFrame = buffer.nextFlushedWritableFrame() { flushedFrames.append(flushedFrame.frame) } - flushedFrames.assertFramesMatch([.headers, .priority, .rstStream, .settings, .pushPromise, .ping, .goAway, .windowUpdate, .altSvc, .origin]) + flushedFrames.assertFramesMatch([ + .headers, .priority, .rstStream, .settings, .pushPromise, .ping, .goAway, .windowUpdate, .altSvc, .origin, + ]) } func testControlFramesWillQueueEvenIfWritable() throws { // We'll queue a HEADERS frame. var buffer = ControlFrameBuffer(maximumBufferSize: 1024) - XCTAssertNoThrow(try buffer.processOutboundFrame(.headers, promise: nil, channelWritable: false).assertNothing()) + XCTAssertNoThrow( + try buffer.processOutboundFrame(.headers, promise: nil, channelWritable: false).assertNothing() + ) // Now, further control frames will buffer, even if writable. XCTAssertNoThrow(try buffer.processOutboundFrame(.headers, promise: nil, channelWritable: true).assertNothing()) - XCTAssertNoThrow(try buffer.processOutboundFrame(.priority, promise: nil, channelWritable: true).assertNothing()) - XCTAssertNoThrow(try buffer.processOutboundFrame(.rstStream, promise: nil, channelWritable: true).assertNothing()) - XCTAssertNoThrow(try buffer.processOutboundFrame(.settings, promise: nil, channelWritable: true).assertNothing()) - XCTAssertNoThrow(try buffer.processOutboundFrame(.pushPromise, promise: nil, channelWritable: true).assertNothing()) + XCTAssertNoThrow( + try buffer.processOutboundFrame(.priority, promise: nil, channelWritable: true).assertNothing() + ) + XCTAssertNoThrow( + try buffer.processOutboundFrame(.rstStream, promise: nil, channelWritable: true).assertNothing() + ) + XCTAssertNoThrow( + try buffer.processOutboundFrame(.settings, promise: nil, channelWritable: true).assertNothing() + ) + XCTAssertNoThrow( + try buffer.processOutboundFrame(.pushPromise, promise: nil, channelWritable: true).assertNothing() + ) XCTAssertNoThrow(try buffer.processOutboundFrame(.ping, promise: nil, channelWritable: true).assertNothing()) XCTAssertNoThrow(try buffer.processOutboundFrame(.goAway, promise: nil, channelWritable: true).assertNothing()) - XCTAssertNoThrow(try buffer.processOutboundFrame(.windowUpdate, promise: nil, channelWritable: true).assertNothing()) + XCTAssertNoThrow( + try buffer.processOutboundFrame(.windowUpdate, promise: nil, channelWritable: true).assertNothing() + ) XCTAssertNoThrow(try buffer.processOutboundFrame(.altSvc, promise: nil, channelWritable: true).assertNothing()) XCTAssertNoThrow(try buffer.processOutboundFrame(.origin, promise: nil, channelWritable: true).assertNothing()) @@ -91,71 +127,80 @@ final class ControlFrameBufferTests: XCTestCase { while let flushedFrame = buffer.nextFlushedWritableFrame() { flushedFrames.append(flushedFrame.frame) } - flushedFrames.assertFramesMatch([.headers, .headers, .priority, .rstStream, .settings, .pushPromise, .ping, .goAway, .windowUpdate, .altSvc, .origin]) + flushedFrames.assertFramesMatch([ + .headers, .headers, .priority, .rstStream, .settings, .pushPromise, .ping, .goAway, .windowUpdate, .altSvc, + .origin, + ]) } func testExcessiveBufferingLeadsToErrors() throws { var buffer = ControlFrameBuffer(maximumBufferSize: 1024) for _ in 0..<1024 { - XCTAssertNoThrow(try buffer.processOutboundFrame(.headers, promise: nil, channelWritable: false).assertNothing()) + XCTAssertNoThrow( + try buffer.processOutboundFrame(.headers, promise: nil, channelWritable: false).assertNothing() + ) } XCTAssertThrowsError(try buffer.processOutboundFrame(.headers, promise: nil, channelWritable: false)) { error in - XCTAssertEqual(error as? NIOHTTP2Errors.ExcessiveOutboundFrameBuffering, NIOHTTP2Errors.excessiveOutboundFrameBuffering()) + XCTAssertEqual( + error as? NIOHTTP2Errors.ExcessiveOutboundFrameBuffering, + NIOHTTP2Errors.excessiveOutboundFrameBuffering() + ) } } } - extension HTTP2Frame { fileprivate static var data: HTTP2Frame { - return HTTP2Frame(streamID: 1, payload: .data(.init(data: .byteBuffer(.empty)))) + HTTP2Frame(streamID: 1, payload: .data(.init(data: .byteBuffer(.empty)))) } fileprivate static var headers: HTTP2Frame { - return HTTP2Frame(streamID: 1, payload: .headers(.init(headers: HPACKHeaders()))) + HTTP2Frame(streamID: 1, payload: .headers(.init(headers: HPACKHeaders()))) } fileprivate static var priority: HTTP2Frame { - return HTTP2Frame(streamID: 1, payload: .priority(.init(exclusive: true, dependency: 0, weight: 32))) + HTTP2Frame(streamID: 1, payload: .priority(.init(exclusive: true, dependency: 0, weight: 32))) } fileprivate static var rstStream: HTTP2Frame { - return HTTP2Frame(streamID: 1, payload: .rstStream(.protocolError)) + HTTP2Frame(streamID: 1, payload: .rstStream(.protocolError)) } fileprivate static var settings: HTTP2Frame { - return HTTP2Frame(streamID: .rootStream, payload: .settings(.ack)) + HTTP2Frame(streamID: .rootStream, payload: .settings(.ack)) } fileprivate static var pushPromise: HTTP2Frame { - return HTTP2Frame(streamID: 1, payload: .pushPromise(.init(pushedStreamID: 2, headers: HPACKHeaders()))) + HTTP2Frame(streamID: 1, payload: .pushPromise(.init(pushedStreamID: 2, headers: HPACKHeaders()))) } fileprivate static var ping: HTTP2Frame { - return HTTP2Frame(streamID: .rootStream, payload: .ping(HTTP2PingData(), ack: false)) + HTTP2Frame(streamID: .rootStream, payload: .ping(HTTP2PingData(), ack: false)) } fileprivate static var goAway: HTTP2Frame { - return HTTP2Frame(streamID: .rootStream, payload: .goAway(lastStreamID: .maxID, errorCode: .protocolError, opaqueData: nil)) + HTTP2Frame( + streamID: .rootStream, + payload: .goAway(lastStreamID: .maxID, errorCode: .protocolError, opaqueData: nil) + ) } fileprivate static var windowUpdate: HTTP2Frame { - return HTTP2Frame(streamID: 1, payload: .windowUpdate(windowSizeIncrement: 1)) + HTTP2Frame(streamID: 1, payload: .windowUpdate(windowSizeIncrement: 1)) } fileprivate static var altSvc: HTTP2Frame { - return HTTP2Frame(streamID: .rootStream, payload: .alternativeService(origin: nil, field: nil)) + HTTP2Frame(streamID: .rootStream, payload: .alternativeService(origin: nil, field: nil)) } fileprivate static var origin: HTTP2Frame { - return HTTP2Frame(streamID: .rootStream, payload: .origin([])) + HTTP2Frame(streamID: .rootStream, payload: .origin([])) } } - extension ByteBuffer { fileprivate static var empty: ByteBuffer { - return ByteBufferAllocator().buffer(capacity: 0) + ByteBufferAllocator().buffer(capacity: 0) } } diff --git a/Tests/NIOHTTP2Tests/DOSHeuristicsTests.swift b/Tests/NIOHTTP2Tests/DOSHeuristicsTests.swift index c98ff1d..c28a4fd 100644 --- a/Tests/NIOHTTP2Tests/DOSHeuristicsTests.swift +++ b/Tests/NIOHTTP2Tests/DOSHeuristicsTests.swift @@ -12,14 +12,20 @@ // //===----------------------------------------------------------------------===// -import XCTest import NIOCore +import XCTest + @testable import NIOHTTP2 final class DOSHeuristicsTests: XCTestCase { func testRSTFramePermittedRate() throws { let testClock = TestClock() - var dosHeuristics = DOSHeuristics(maximumSequentialEmptyDataFrames: 100, maximumResetFrameCount: 200, resetFrameCounterWindow: .seconds(30), clock: testClock) + var dosHeuristics = DOSHeuristics( + maximumSequentialEmptyDataFrames: 100, + maximumResetFrameCount: 200, + resetFrameCounterWindow: .seconds(30), + clock: testClock + ) // more resets than allowed, but slow enough to be okay for i in 0..<300 { @@ -30,7 +36,12 @@ final class DOSHeuristicsTests: XCTestCase { func testRSTFrameExcessiveRate() throws { let testClock = TestClock() - var dosHeuristics = DOSHeuristics(maximumSequentialEmptyDataFrames: 100, maximumResetFrameCount: 200, resetFrameCounterWindow: .seconds(30), clock: testClock) + var dosHeuristics = DOSHeuristics( + maximumSequentialEmptyDataFrames: 100, + maximumResetFrameCount: 200, + resetFrameCounterWindow: .seconds(30), + clock: testClock + ) // up to the limit for i in 0..<200 { @@ -39,12 +50,19 @@ final class DOSHeuristicsTests: XCTestCase { } // over the limit - XCTAssertThrowsError(try dosHeuristics.process(.init(streamID: HTTP2StreamID(201), payload: .rstStream(.cancel)))) + XCTAssertThrowsError( + try dosHeuristics.process(.init(streamID: HTTP2StreamID(201), payload: .rstStream(.cancel))) + ) } func testRSTFrameGarbageCollects() throws { let testClock = TestClock() - var dosHeuristics = DOSHeuristics(maximumSequentialEmptyDataFrames: 100, maximumResetFrameCount: 200, resetFrameCounterWindow: .seconds(30), clock: testClock) + var dosHeuristics = DOSHeuristics( + maximumSequentialEmptyDataFrames: 100, + maximumResetFrameCount: 200, + resetFrameCounterWindow: .seconds(30), + clock: testClock + ) // up to the limit for i in 0..<200 { @@ -62,12 +80,19 @@ final class DOSHeuristicsTests: XCTestCase { } // over the limit - XCTAssertThrowsError(try dosHeuristics.process(.init(streamID: HTTP2StreamID(401), payload: .rstStream(.cancel)))) + XCTAssertThrowsError( + try dosHeuristics.process(.init(streamID: HTTP2StreamID(401), payload: .rstStream(.cancel))) + ) } func testRSTFrameExcessiveRateConfigurableCount() throws { let testClock = TestClock() - var dosHeuristics = DOSHeuristics(maximumSequentialEmptyDataFrames: 100, maximumResetFrameCount: 400, resetFrameCounterWindow: .seconds(30), clock: testClock) + var dosHeuristics = DOSHeuristics( + maximumSequentialEmptyDataFrames: 100, + maximumResetFrameCount: 400, + resetFrameCounterWindow: .seconds(30), + clock: testClock + ) // up to the limit for i in 0..<400 { @@ -76,12 +101,19 @@ final class DOSHeuristicsTests: XCTestCase { } // over the limit - XCTAssertThrowsError(try dosHeuristics.process(.init(streamID: HTTP2StreamID(401), payload: .rstStream(.cancel)))) + XCTAssertThrowsError( + try dosHeuristics.process(.init(streamID: HTTP2StreamID(401), payload: .rstStream(.cancel))) + ) } func testRSTFrameExcessiveRateConfigurableWindow() throws { let testClock = TestClock() - var dosHeuristics = DOSHeuristics(maximumSequentialEmptyDataFrames: 100, maximumResetFrameCount: 200, resetFrameCounterWindow: .seconds(3600), clock: testClock) + var dosHeuristics = DOSHeuristics( + maximumSequentialEmptyDataFrames: 100, + maximumResetFrameCount: 200, + resetFrameCounterWindow: .seconds(3600), + clock: testClock + ) // up to the limit, previously slow enough to be okay but not with this window for i in 0..<200 { @@ -90,7 +122,9 @@ final class DOSHeuristicsTests: XCTestCase { } // over the limit - XCTAssertThrowsError(try dosHeuristics.process(.init(streamID: HTTP2StreamID(201), payload: .rstStream(.cancel)))) + XCTAssertThrowsError( + try dosHeuristics.process(.init(streamID: HTTP2StreamID(201), payload: .rstStream(.cancel))) + ) } } @@ -98,7 +132,7 @@ class TestClock: NIODeadlineClock { private var time: NIODeadline func now() -> NIODeadline { - return self.time + self.time } func advance(by delta: TimeAmount) { diff --git a/Tests/NIOHTTP2Tests/HTTP2ErrorTests.swift b/Tests/NIOHTTP2Tests/HTTP2ErrorTests.swift index b9d5170..f65260a 100644 --- a/Tests/NIOHTTP2Tests/HTTP2ErrorTests.swift +++ b/Tests/NIOHTTP2Tests/HTTP2ErrorTests.swift @@ -12,184 +12,300 @@ // //===----------------------------------------------------------------------===// -import XCTest import NIOHTTP2 +import XCTest class HTTP2ErrorTests: XCTestCase { func testEquatableExcludesFileAndLine() throws { - XCTAssertEqual(NIOHTTP2Errors.excessiveOutboundFrameBuffering(), - NIOHTTP2Errors.excessiveOutboundFrameBuffering(file: "", line: 0)) + XCTAssertEqual( + NIOHTTP2Errors.excessiveOutboundFrameBuffering(), + NIOHTTP2Errors.excessiveOutboundFrameBuffering(file: "", line: 0) + ) - XCTAssertEqual(NIOHTTP2Errors.invalidALPNToken(), - NIOHTTP2Errors.invalidALPNToken(file: "", line: 0)) + XCTAssertEqual( + NIOHTTP2Errors.invalidALPNToken(), + NIOHTTP2Errors.invalidALPNToken(file: "", line: 0) + ) - XCTAssertEqual(NIOHTTP2Errors.noSuchStream(streamID: .rootStream), - NIOHTTP2Errors.noSuchStream(streamID: .rootStream, file: "", line: 0)) + XCTAssertEqual( + NIOHTTP2Errors.noSuchStream(streamID: .rootStream), + NIOHTTP2Errors.noSuchStream(streamID: .rootStream, file: "", line: 0) + ) - XCTAssertNotEqual(NIOHTTP2Errors.noSuchStream(streamID: 1), - NIOHTTP2Errors.noSuchStream(streamID: 2)) + XCTAssertNotEqual( + NIOHTTP2Errors.noSuchStream(streamID: 1), + NIOHTTP2Errors.noSuchStream(streamID: 2) + ) - XCTAssertEqual(NIOHTTP2Errors.streamClosed(streamID: .rootStream, errorCode: .cancel), - NIOHTTP2Errors.streamClosed(streamID: .rootStream, errorCode: .cancel, file: "", line: 0)) + XCTAssertEqual( + NIOHTTP2Errors.streamClosed(streamID: .rootStream, errorCode: .cancel), + NIOHTTP2Errors.streamClosed(streamID: .rootStream, errorCode: .cancel, file: "", line: 0) + ) - XCTAssertNotEqual(NIOHTTP2Errors.streamClosed(streamID: 1, errorCode: .cancel), - NIOHTTP2Errors.streamClosed(streamID: 1, errorCode: .compressionError)) + XCTAssertNotEqual( + NIOHTTP2Errors.streamClosed(streamID: 1, errorCode: .cancel), + NIOHTTP2Errors.streamClosed(streamID: 1, errorCode: .compressionError) + ) - XCTAssertNotEqual(NIOHTTP2Errors.streamClosed(streamID: 1, errorCode: .cancel), - NIOHTTP2Errors.streamClosed(streamID: 2, errorCode: .cancel)) + XCTAssertNotEqual( + NIOHTTP2Errors.streamClosed(streamID: 1, errorCode: .cancel), + NIOHTTP2Errors.streamClosed(streamID: 2, errorCode: .cancel) + ) - XCTAssertEqual(NIOHTTP2Errors.badClientMagic(), - NIOHTTP2Errors.badClientMagic(file: "", line: 0)) + XCTAssertEqual( + NIOHTTP2Errors.badClientMagic(), + NIOHTTP2Errors.badClientMagic(file: "", line: 0) + ) - XCTAssertEqual(NIOHTTP2Errors.badStreamStateTransition(), - NIOHTTP2Errors.badStreamStateTransition(file: "", line: 0)) + XCTAssertEqual( + NIOHTTP2Errors.badStreamStateTransition(), + NIOHTTP2Errors.badStreamStateTransition(file: "", line: 0) + ) - XCTAssertNotEqual(NIOHTTP2Errors.badStreamStateTransition(from: .closed), - NIOHTTP2Errors.badStreamStateTransition()) + XCTAssertNotEqual( + NIOHTTP2Errors.badStreamStateTransition(from: .closed), + NIOHTTP2Errors.badStreamStateTransition() + ) - XCTAssertEqual(NIOHTTP2Errors.invalidFlowControlWindowSize(delta: 1, currentWindowSize: 2), - NIOHTTP2Errors.invalidFlowControlWindowSize(delta: 1, currentWindowSize: 2, file: "", line: 0)) + XCTAssertEqual( + NIOHTTP2Errors.invalidFlowControlWindowSize(delta: 1, currentWindowSize: 2), + NIOHTTP2Errors.invalidFlowControlWindowSize(delta: 1, currentWindowSize: 2, file: "", line: 0) + ) - XCTAssertNotEqual(NIOHTTP2Errors.invalidFlowControlWindowSize(delta: 1, currentWindowSize: 2), - NIOHTTP2Errors.invalidFlowControlWindowSize(delta: 2, currentWindowSize: 2)) + XCTAssertNotEqual( + NIOHTTP2Errors.invalidFlowControlWindowSize(delta: 1, currentWindowSize: 2), + NIOHTTP2Errors.invalidFlowControlWindowSize(delta: 2, currentWindowSize: 2) + ) - XCTAssertNotEqual(NIOHTTP2Errors.invalidFlowControlWindowSize(delta: 1, currentWindowSize: 3), - NIOHTTP2Errors.invalidFlowControlWindowSize(delta: 1, currentWindowSize: 2)) + XCTAssertNotEqual( + NIOHTTP2Errors.invalidFlowControlWindowSize(delta: 1, currentWindowSize: 3), + NIOHTTP2Errors.invalidFlowControlWindowSize(delta: 1, currentWindowSize: 2) + ) - XCTAssertEqual(NIOHTTP2Errors.flowControlViolation(), - NIOHTTP2Errors.flowControlViolation(file: "", line: 0)) + XCTAssertEqual( + NIOHTTP2Errors.flowControlViolation(), + NIOHTTP2Errors.flowControlViolation(file: "", line: 0) + ) - XCTAssertEqual(NIOHTTP2Errors.invalidSetting(setting: .init(parameter: .maxConcurrentStreams, value: 1)), - NIOHTTP2Errors.invalidSetting(setting: .init(parameter: .maxConcurrentStreams, value: 1), file: "", line: 0)) + XCTAssertEqual( + NIOHTTP2Errors.invalidSetting(setting: .init(parameter: .maxConcurrentStreams, value: 1)), + NIOHTTP2Errors.invalidSetting(setting: .init(parameter: .maxConcurrentStreams, value: 1), file: "", line: 0) + ) - XCTAssertNotEqual(NIOHTTP2Errors.invalidSetting(setting: .init(parameter: .maxConcurrentStreams, value: 1)), - NIOHTTP2Errors.invalidSetting(setting: .init(parameter: .maxConcurrentStreams, value: 2))) + XCTAssertNotEqual( + NIOHTTP2Errors.invalidSetting(setting: .init(parameter: .maxConcurrentStreams, value: 1)), + NIOHTTP2Errors.invalidSetting(setting: .init(parameter: .maxConcurrentStreams, value: 2)) + ) - XCTAssertEqual(NIOHTTP2Errors.ioOnClosedConnection(), - NIOHTTP2Errors.ioOnClosedConnection(file: "", line: 0)) + XCTAssertEqual( + NIOHTTP2Errors.ioOnClosedConnection(), + NIOHTTP2Errors.ioOnClosedConnection(file: "", line: 0) + ) - XCTAssertEqual(NIOHTTP2Errors.receivedBadSettings(), - NIOHTTP2Errors.receivedBadSettings(file: "", line: 0)) + XCTAssertEqual( + NIOHTTP2Errors.receivedBadSettings(), + NIOHTTP2Errors.receivedBadSettings(file: "", line: 0) + ) - XCTAssertEqual(NIOHTTP2Errors.maxStreamsViolation(), - NIOHTTP2Errors.maxStreamsViolation(file: "", line: 0)) + XCTAssertEqual( + NIOHTTP2Errors.maxStreamsViolation(), + NIOHTTP2Errors.maxStreamsViolation(file: "", line: 0) + ) - XCTAssertEqual(NIOHTTP2Errors.streamIDTooSmall(), - NIOHTTP2Errors.streamIDTooSmall(file: "", line: 0)) + XCTAssertEqual( + NIOHTTP2Errors.streamIDTooSmall(), + NIOHTTP2Errors.streamIDTooSmall(file: "", line: 0) + ) - XCTAssertEqual(NIOHTTP2Errors.missingPreface(), - NIOHTTP2Errors.missingPreface(file: "", line: 0)) + XCTAssertEqual( + NIOHTTP2Errors.missingPreface(), + NIOHTTP2Errors.missingPreface(file: "", line: 0) + ) - XCTAssertEqual(NIOHTTP2Errors.createdStreamAfterGoaway(), - NIOHTTP2Errors.createdStreamAfterGoaway(file: "", line: 0)) + XCTAssertEqual( + NIOHTTP2Errors.createdStreamAfterGoaway(), + NIOHTTP2Errors.createdStreamAfterGoaway(file: "", line: 0) + ) - XCTAssertEqual(NIOHTTP2Errors.invalidStreamIDForPeer(), - NIOHTTP2Errors.invalidStreamIDForPeer(file: "", line: 0)) + XCTAssertEqual( + NIOHTTP2Errors.invalidStreamIDForPeer(), + NIOHTTP2Errors.invalidStreamIDForPeer(file: "", line: 0) + ) - XCTAssertEqual(NIOHTTP2Errors.raisedGoawayLastStreamID(), - NIOHTTP2Errors.raisedGoawayLastStreamID(file: "", line: 0)) + XCTAssertEqual( + NIOHTTP2Errors.raisedGoawayLastStreamID(), + NIOHTTP2Errors.raisedGoawayLastStreamID(file: "", line: 0) + ) - XCTAssertEqual(NIOHTTP2Errors.invalidWindowIncrementSize(), - NIOHTTP2Errors.invalidWindowIncrementSize(file: "", line: 0)) + XCTAssertEqual( + NIOHTTP2Errors.invalidWindowIncrementSize(), + NIOHTTP2Errors.invalidWindowIncrementSize(file: "", line: 0) + ) - XCTAssertEqual(NIOHTTP2Errors.pushInViolationOfSetting(), - NIOHTTP2Errors.pushInViolationOfSetting(file: "", line: 0)) + XCTAssertEqual( + NIOHTTP2Errors.pushInViolationOfSetting(), + NIOHTTP2Errors.pushInViolationOfSetting(file: "", line: 0) + ) - XCTAssertEqual(NIOHTTP2Errors.unsupported(info: "info"), - NIOHTTP2Errors.unsupported(info: "info", file: "", line: 0)) + XCTAssertEqual( + NIOHTTP2Errors.unsupported(info: "info"), + NIOHTTP2Errors.unsupported(info: "info", file: "", line: 0) + ) - XCTAssertNotEqual(NIOHTTP2Errors.unsupported(info: "info"), - NIOHTTP2Errors.unsupported(info: "notinfo")) + XCTAssertNotEqual( + NIOHTTP2Errors.unsupported(info: "info"), + NIOHTTP2Errors.unsupported(info: "notinfo") + ) - XCTAssertEqual(NIOHTTP2Errors.unableToSerializeFrame(), - NIOHTTP2Errors.unableToSerializeFrame(file: "", line: 0)) + XCTAssertEqual( + NIOHTTP2Errors.unableToSerializeFrame(), + NIOHTTP2Errors.unableToSerializeFrame(file: "", line: 0) + ) - XCTAssertEqual(NIOHTTP2Errors.unableToParseFrame(), - NIOHTTP2Errors.unableToParseFrame(file: "", line: 0)) + XCTAssertEqual( + NIOHTTP2Errors.unableToParseFrame(), + NIOHTTP2Errors.unableToParseFrame(file: "", line: 0) + ) - XCTAssertEqual(NIOHTTP2Errors.missingPseudoHeader("missing"), - NIOHTTP2Errors.missingPseudoHeader("missing", file: "", line: 0)) + XCTAssertEqual( + NIOHTTP2Errors.missingPseudoHeader("missing"), + NIOHTTP2Errors.missingPseudoHeader("missing", file: "", line: 0) + ) - XCTAssertNotEqual(NIOHTTP2Errors.missingPseudoHeader("missing"), - NIOHTTP2Errors.missingPseudoHeader("notmissing")) + XCTAssertNotEqual( + NIOHTTP2Errors.missingPseudoHeader("missing"), + NIOHTTP2Errors.missingPseudoHeader("notmissing") + ) - XCTAssertEqual(NIOHTTP2Errors.duplicatePseudoHeader("duplicate"), - NIOHTTP2Errors.duplicatePseudoHeader("duplicate", file: "", line: 0)) + XCTAssertEqual( + NIOHTTP2Errors.duplicatePseudoHeader("duplicate"), + NIOHTTP2Errors.duplicatePseudoHeader("duplicate", file: "", line: 0) + ) - XCTAssertNotEqual(NIOHTTP2Errors.duplicatePseudoHeader("duplicate"), - NIOHTTP2Errors.duplicatePseudoHeader("notduplicate")) + XCTAssertNotEqual( + NIOHTTP2Errors.duplicatePseudoHeader("duplicate"), + NIOHTTP2Errors.duplicatePseudoHeader("notduplicate") + ) - XCTAssertEqual(NIOHTTP2Errors.pseudoHeaderAfterRegularHeader("after"), - NIOHTTP2Errors.pseudoHeaderAfterRegularHeader("after", file: "", line: 0)) + XCTAssertEqual( + NIOHTTP2Errors.pseudoHeaderAfterRegularHeader("after"), + NIOHTTP2Errors.pseudoHeaderAfterRegularHeader("after", file: "", line: 0) + ) - XCTAssertNotEqual(NIOHTTP2Errors.pseudoHeaderAfterRegularHeader("after"), - NIOHTTP2Errors.pseudoHeaderAfterRegularHeader("notafter")) + XCTAssertNotEqual( + NIOHTTP2Errors.pseudoHeaderAfterRegularHeader("after"), + NIOHTTP2Errors.pseudoHeaderAfterRegularHeader("notafter") + ) - XCTAssertEqual(NIOHTTP2Errors.unknownPseudoHeader("unknown"), - NIOHTTP2Errors.unknownPseudoHeader("unknown", file: "", line: 0)) + XCTAssertEqual( + NIOHTTP2Errors.unknownPseudoHeader("unknown"), + NIOHTTP2Errors.unknownPseudoHeader("unknown", file: "", line: 0) + ) - XCTAssertNotEqual(NIOHTTP2Errors.unknownPseudoHeader("unknown"), - NIOHTTP2Errors.unknownPseudoHeader("notunknown")) + XCTAssertNotEqual( + NIOHTTP2Errors.unknownPseudoHeader("unknown"), + NIOHTTP2Errors.unknownPseudoHeader("notunknown") + ) - XCTAssertEqual(NIOHTTP2Errors.invalidPseudoHeaders([:]), - NIOHTTP2Errors.invalidPseudoHeaders([:], file: "", line: 0)) + XCTAssertEqual( + NIOHTTP2Errors.invalidPseudoHeaders([:]), + NIOHTTP2Errors.invalidPseudoHeaders([:], file: "", line: 0) + ) - XCTAssertNotEqual(NIOHTTP2Errors.invalidPseudoHeaders([:]), - NIOHTTP2Errors.invalidPseudoHeaders(["not": "empty"])) + XCTAssertNotEqual( + NIOHTTP2Errors.invalidPseudoHeaders([:]), + NIOHTTP2Errors.invalidPseudoHeaders(["not": "empty"]) + ) - XCTAssertEqual(NIOHTTP2Errors.missingHostHeader(), - NIOHTTP2Errors.missingHostHeader(file: "", line: 0)) + XCTAssertEqual( + NIOHTTP2Errors.missingHostHeader(), + NIOHTTP2Errors.missingHostHeader(file: "", line: 0) + ) - XCTAssertEqual(NIOHTTP2Errors.duplicateHostHeader(), - NIOHTTP2Errors.duplicateHostHeader(file: "", line: 0)) + XCTAssertEqual( + NIOHTTP2Errors.duplicateHostHeader(), + NIOHTTP2Errors.duplicateHostHeader(file: "", line: 0) + ) - XCTAssertEqual(NIOHTTP2Errors.emptyPathHeader(), - NIOHTTP2Errors.emptyPathHeader(file: "", line: 0)) + XCTAssertEqual( + NIOHTTP2Errors.emptyPathHeader(), + NIOHTTP2Errors.emptyPathHeader(file: "", line: 0) + ) - XCTAssertEqual(NIOHTTP2Errors.invalidStatusValue("invalid"), - NIOHTTP2Errors.invalidStatusValue("invalid", file: "", line: 0)) + XCTAssertEqual( + NIOHTTP2Errors.invalidStatusValue("invalid"), + NIOHTTP2Errors.invalidStatusValue("invalid", file: "", line: 0) + ) - XCTAssertNotEqual(NIOHTTP2Errors.invalidStatusValue("invalid"), - NIOHTTP2Errors.invalidStatusValue("notinvalid")) + XCTAssertNotEqual( + NIOHTTP2Errors.invalidStatusValue("invalid"), + NIOHTTP2Errors.invalidStatusValue("notinvalid") + ) - XCTAssertEqual(NIOHTTP2Errors.priorityCycle(streamID: .rootStream), - NIOHTTP2Errors.priorityCycle(streamID: .rootStream, file: "", line: 0)) + XCTAssertEqual( + NIOHTTP2Errors.priorityCycle(streamID: .rootStream), + NIOHTTP2Errors.priorityCycle(streamID: .rootStream, file: "", line: 0) + ) - XCTAssertNotEqual(NIOHTTP2Errors.priorityCycle(streamID: .rootStream), - NIOHTTP2Errors.priorityCycle(streamID: 1)) + XCTAssertNotEqual( + NIOHTTP2Errors.priorityCycle(streamID: .rootStream), + NIOHTTP2Errors.priorityCycle(streamID: 1) + ) - XCTAssertEqual(NIOHTTP2Errors.trailersWithoutEndStream(streamID: .rootStream), - NIOHTTP2Errors.trailersWithoutEndStream(streamID: .rootStream, file: "", line: 0)) + XCTAssertEqual( + NIOHTTP2Errors.trailersWithoutEndStream(streamID: .rootStream), + NIOHTTP2Errors.trailersWithoutEndStream(streamID: .rootStream, file: "", line: 0) + ) - XCTAssertNotEqual(NIOHTTP2Errors.trailersWithoutEndStream(streamID: .rootStream), - NIOHTTP2Errors.trailersWithoutEndStream(streamID: 1)) + XCTAssertNotEqual( + NIOHTTP2Errors.trailersWithoutEndStream(streamID: .rootStream), + NIOHTTP2Errors.trailersWithoutEndStream(streamID: 1) + ) - XCTAssertEqual(NIOHTTP2Errors.invalidHTTP2HeaderFieldName("fieldName"), - NIOHTTP2Errors.invalidHTTP2HeaderFieldName("fieldName", file: "", line: 0)) + XCTAssertEqual( + NIOHTTP2Errors.invalidHTTP2HeaderFieldName("fieldName"), + NIOHTTP2Errors.invalidHTTP2HeaderFieldName("fieldName", file: "", line: 0) + ) - XCTAssertNotEqual(NIOHTTP2Errors.invalidHTTP2HeaderFieldName("fieldName"), - NIOHTTP2Errors.invalidHTTP2HeaderFieldName("notFieldName")) + XCTAssertNotEqual( + NIOHTTP2Errors.invalidHTTP2HeaderFieldName("fieldName"), + NIOHTTP2Errors.invalidHTTP2HeaderFieldName("notFieldName") + ) - XCTAssertEqual(NIOHTTP2Errors.forbiddenHeaderField(name: "name", value: "value"), - NIOHTTP2Errors.forbiddenHeaderField(name: "name", value: "value", file: "", line: 0)) + XCTAssertEqual( + NIOHTTP2Errors.forbiddenHeaderField(name: "name", value: "value"), + NIOHTTP2Errors.forbiddenHeaderField(name: "name", value: "value", file: "", line: 0) + ) - XCTAssertNotEqual(NIOHTTP2Errors.forbiddenHeaderField(name: "name", value: "value"), - NIOHTTP2Errors.forbiddenHeaderField(name: "notname", value: "value")) + XCTAssertNotEqual( + NIOHTTP2Errors.forbiddenHeaderField(name: "name", value: "value"), + NIOHTTP2Errors.forbiddenHeaderField(name: "notname", value: "value") + ) - XCTAssertNotEqual(NIOHTTP2Errors.forbiddenHeaderField(name: "name", value: "value"), - NIOHTTP2Errors.forbiddenHeaderField(name: "name", value: "notvalue")) + XCTAssertNotEqual( + NIOHTTP2Errors.forbiddenHeaderField(name: "name", value: "value"), + NIOHTTP2Errors.forbiddenHeaderField(name: "name", value: "notvalue") + ) - XCTAssertEqual(NIOHTTP2Errors.contentLengthViolated(), - NIOHTTP2Errors.contentLengthViolated(file: "", line: 0)) + XCTAssertEqual( + NIOHTTP2Errors.contentLengthViolated(), + NIOHTTP2Errors.contentLengthViolated(file: "", line: 0) + ) - XCTAssertEqual(NIOHTTP2Errors.excessiveEmptyDataFrames(), - NIOHTTP2Errors.excessiveEmptyDataFrames(file: "", line: 0)) + XCTAssertEqual( + NIOHTTP2Errors.excessiveEmptyDataFrames(), + NIOHTTP2Errors.excessiveEmptyDataFrames(file: "", line: 0) + ) - XCTAssertEqual(NIOHTTP2Errors.excessivelyLargeHeaderBlock(), - NIOHTTP2Errors.excessivelyLargeHeaderBlock(file: "", line: 0)) + XCTAssertEqual( + NIOHTTP2Errors.excessivelyLargeHeaderBlock(), + NIOHTTP2Errors.excessivelyLargeHeaderBlock(file: "", line: 0) + ) - XCTAssertEqual(NIOHTTP2Errors.noStreamIDAvailable(), - NIOHTTP2Errors.noStreamIDAvailable(file: "", line: 0)) + XCTAssertEqual( + NIOHTTP2Errors.noStreamIDAvailable(), + NIOHTTP2Errors.noStreamIDAvailable(file: "", line: 0) + ) } func testFitsInAnExistentialContainer() { diff --git a/Tests/NIOHTTP2Tests/HTTP2FrameParserTests.swift b/Tests/NIOHTTP2Tests/HTTP2FrameParserTests.swift index 1c8677c..c4036a3 100644 --- a/Tests/NIOHTTP2Tests/HTTP2FrameParserTests.swift +++ b/Tests/NIOHTTP2Tests/HTTP2FrameParserTests.swift @@ -12,44 +12,57 @@ // //===----------------------------------------------------------------------===// -import XCTest import NIOCore import NIOHPACK +import XCTest + @testable import NIOHTTP2 class HTTP2FrameParserTests: XCTestCase { - + let allocator = ByteBufferAllocator() - + let simpleHeaders = HPACKHeaders([ (":method", "GET"), (":scheme", "http"), (":path", "/"), - (":authority", "www.example.com") + (":authority", "www.example.com"), ]) - let simpleHeadersEncoded: [UInt8] = [0x82, 0x86, 0x84, 0x41, 0x8c, 0xf1, 0xe3, 0xc2, 0xe5, 0xf2, 0x3a, 0x6b, 0xa0, 0xab, 0x90, 0xf4, 0xff] + let simpleHeadersEncoded: [UInt8] = [ + 0x82, 0x86, 0x84, 0x41, 0x8c, 0xf1, 0xe3, 0xc2, 0xe5, 0xf2, 0x3a, 0x6b, 0xa0, 0xab, 0x90, 0xf4, 0xff, + ] let maximumSequentialContinuationFrames = 5 // MARK: - Utilities - - private func byteBuffer(withBytes bytes: C, extraCapacity: Int = 0) -> ByteBuffer where C.Element == UInt8 { + + private func byteBuffer(withBytes bytes: C, extraCapacity: Int = 0) -> ByteBuffer + where C.Element == UInt8 { var buf = allocator.buffer(capacity: bytes.count + extraCapacity) buf.writeBytes(bytes) return buf } - + private func byteBuffer(withStaticString string: StaticString) -> ByteBuffer { var buf = allocator.buffer(capacity: string.utf8CodeUnitCount) buf.writeStaticString(string) return buf } - - private func assertEqualFrames(_ frame1: HTTP2Frame, _ frame2: HTTP2Frame, - file: StaticString = #filePath, line: UInt = #line) { - XCTAssertEqual(frame1.streamID, frame2.streamID, "StreamID mismatch: \(frame1.streamID) != \(frame2.streamID)", - file: (file), line: line) - + + private func assertEqualFrames( + _ frame1: HTTP2Frame, + _ frame2: HTTP2Frame, + file: StaticString = #filePath, + line: UInt = #line + ) { + XCTAssertEqual( + frame1.streamID, + frame2.streamID, + "StreamID mismatch: \(frame1.streamID) != \(frame2.streamID)", + file: (file), + line: line + ) + switch (frame1.payload, frame2.payload) { case let (.data(l), .data(r)): switch (l.data, r.data) { @@ -58,66 +71,138 @@ class HTTP2FrameParserTests: XCTestCase { default: XCTFail("We're not testing with file regions!", file: (file), line: line) } - XCTAssertEqual(l.endStream, r.endStream, "endStream mismatch: \(l.endStream) != \(r.endStream)", file: (file), line: line) - XCTAssertEqual(l.paddingBytes, r.paddingBytes, "paddingBytes mismatch: \(String(describing: l.paddingBytes)) != \(String(describing: r.paddingBytes))", file: (file), line: line) - + XCTAssertEqual( + l.endStream, + r.endStream, + "endStream mismatch: \(l.endStream) != \(r.endStream)", + file: (file), + line: line + ) + XCTAssertEqual( + l.paddingBytes, + r.paddingBytes, + "paddingBytes mismatch: \(String(describing: l.paddingBytes)) != \(String(describing: r.paddingBytes))", + file: (file), + line: line + ) + case let (.headers(l), .headers(r)): - XCTAssertEqual(l.headers, r.headers, "Headers mismatch: \(l.headers) != \(r.headers)", file: (file), line: line) - XCTAssertEqual(l.priorityData, r.priorityData, "Priority mismatch: \(String(describing: l.priorityData)) != \(String(describing: r.priorityData))", - file: (file), line: line) - XCTAssertEqual(l.endStream, r.endStream, "endStream mismatch: \(l.endStream) != \(r.endStream)", file: (file), line: line) - XCTAssertEqual(l.paddingBytes, r.paddingBytes, "paddingBytes mismatch: \(String(describing: l.paddingBytes)) != \(String(describing: r.paddingBytes))", file: (file), line: line) - + XCTAssertEqual( + l.headers, + r.headers, + "Headers mismatch: \(l.headers) != \(r.headers)", + file: (file), + line: line + ) + XCTAssertEqual( + l.priorityData, + r.priorityData, + "Priority mismatch: \(String(describing: l.priorityData)) != \(String(describing: r.priorityData))", + file: (file), + line: line + ) + XCTAssertEqual( + l.endStream, + r.endStream, + "endStream mismatch: \(l.endStream) != \(r.endStream)", + file: (file), + line: line + ) + XCTAssertEqual( + l.paddingBytes, + r.paddingBytes, + "paddingBytes mismatch: \(String(describing: l.paddingBytes)) != \(String(describing: r.paddingBytes))", + file: (file), + line: line + ) + case let (.priority(lp), .priority(rp)): XCTAssertEqual(lp, rp, "Priority mismatch: \(lp) != \(rp)", file: (file), line: line) - + case let (.rstStream(le), .rstStream(re)): XCTAssertEqual(le, re, "Error mismatch: \(le) != \(re)", file: (file), line: line) - + case let (.settings(.settings(ls)), .settings(.settings(rs))): XCTAssertEqual(ls, rs, "Settings mismatch: \(ls) != \(rs)", file: (file), line: line) case (.settings(.ack), .settings(.ack)): // Nothing specific to compare here. break - + case let (.pushPromise(l), .pushPromise(r)): - XCTAssertEqual(l.pushedStreamID, r.pushedStreamID, "Stream ID mismatch: \(l.pushedStreamID) != \(r.pushedStreamID)", file: (file), line: line) - XCTAssertEqual(l.headers, r.headers, "Headers mismatch: \(l.headers) != \(r.headers)", file: (file), line: line) - XCTAssertEqual(l.paddingBytes, r.paddingBytes, "paddingBytes mismatch: \(String(describing: l.paddingBytes)) != \(String(describing: r.paddingBytes))", file: (file), line: line) - + XCTAssertEqual( + l.pushedStreamID, + r.pushedStreamID, + "Stream ID mismatch: \(l.pushedStreamID) != \(r.pushedStreamID)", + file: (file), + line: line + ) + XCTAssertEqual( + l.headers, + r.headers, + "Headers mismatch: \(l.headers) != \(r.headers)", + file: (file), + line: line + ) + XCTAssertEqual( + l.paddingBytes, + r.paddingBytes, + "paddingBytes mismatch: \(String(describing: l.paddingBytes)) != \(String(describing: r.paddingBytes))", + file: (file), + line: line + ) + case let (.ping(lp, la), .ping(rp, ra)): XCTAssertEqual(lp, rp, "Ping data mismatch: \(lp) != \(rp)", file: (file), line: line) XCTAssertEqual(la, ra, "Ping ack flag mismatch: \(la) != \(ra)", file: (file), line: line) - + case let (.goAway(ls, le, lo), .goAway(rs, re, ro)): XCTAssertEqual(ls, rs, "Stream ID mismatch: \(ls) != \(rs)", file: (file), line: line) XCTAssertEqual(le, re, "Error mismatch: \(le) != \(re)", file: (file), line: line) - XCTAssertEqual(lo, ro, "Opaque data mismatch: \(String(describing: lo)) != \(String(describing: ro))", - file: (file), line: line) - + XCTAssertEqual( + lo, + ro, + "Opaque data mismatch: \(String(describing: lo)) != \(String(describing: ro))", + file: (file), + line: line + ) + case let (.windowUpdate(ls), .windowUpdate(rs)): XCTAssertEqual(ls, rs, "Window size mismatch: \(ls) != \(rs)", file: (file), line: line) - + case let (.alternativeService(lo, lf), .alternativeService(ro, rf)): - XCTAssertEqual(lo, ro, "Origin mismatch: \(String(describing: lo)), \(String(describing: ro))", - file: (file), line: line) - XCTAssertEqual(lf, rf, "ALTSVC field mismatch: \(String(describing: lf)), \(String(describing: rf))", - file: (file), line: line) - + XCTAssertEqual( + lo, + ro, + "Origin mismatch: \(String(describing: lo)), \(String(describing: ro))", + file: (file), + line: line + ) + XCTAssertEqual( + lf, + rf, + "ALTSVC field mismatch: \(String(describing: lf)), \(String(describing: rf))", + file: (file), + line: line + ) + case let (.origin(lo), .origin(ro)): XCTAssertEqual(lo, ro, "Origins mismatch: \(lo) != \(ro)", file: (file), line: line) - + default: XCTFail("Payload mismatch: \(frame1.payload) / \(frame2.payload)", file: (file), line: line) } } - - private func assertReadsFrame(from bytes: ByteBuffer, matching expectedFrame: HTTP2Frame, - expectedFlowControlledLength: Int = 0, - file: StaticString = #filePath, line: UInt = #line) throws { + + private func assertReadsFrame( + from bytes: ByteBuffer, + matching expectedFrame: HTTP2Frame, + expectedFlowControlledLength: Int = 0, + file: StaticString = #filePath, + line: UInt = #line + ) throws { let totalFrameSize = bytes.readableBytes - + var decoder = HTTP2FrameDecoder( allocator: self.allocator, expectClientMagic: false, @@ -128,14 +213,20 @@ class HTTP2FrameParserTests: XCTestCase { let (frame, actualLength) = try decoder.nextFrame()! self.assertEqualFrames(frame, expectedFrame, file: (file), line: line) - XCTAssertEqual(actualLength, expectedFlowControlledLength, "Non-matching flow controlled length", file: (file), line: line) + XCTAssertEqual( + actualLength, + expectedFlowControlledLength, + "Non-matching flow controlled length", + file: (file), + line: line + ) if totalFrameSize > 9 { // Now try again with the frame arriving in two separate chunks. var bytes = bytes let first = bytes.readSlice(length: 9)! let second = bytes - + decoder.append(bytes: first) XCTAssertNil(try decoder.nextFrame()) @@ -144,81 +235,99 @@ class HTTP2FrameParserTests: XCTestCase { XCTAssertNotNil(realFrame) self.assertEqualFrames(realFrame, expectedFrame, file: (file), line: line) - XCTAssertEqual(length, expectedFlowControlledLength, "Non-matching flow controlled length in parts", - file: (file), line: line) + XCTAssertEqual( + length, + expectedFlowControlledLength, + "Non-matching flow controlled length in parts", + file: (file), + line: line + ) } } - + // MARK: - General functionality - + func testPaddingIsNotAllowedByEncoder() { let bytes = self.byteBuffer(withBytes: [0x00, 0x01, 0x02, 0x03]) - let frame = HTTP2Frame(streamID: HTTP2StreamID(1), payload: .data(.init(data: .byteBuffer(bytes), paddingBytes: 0))) + let frame = HTTP2Frame( + streamID: HTTP2StreamID(1), + payload: .data(.init(data: .byteBuffer(bytes), paddingBytes: 0)) + ) var encoder = HTTP2FrameEncoder(allocator: self.allocator) var target = self.allocator.buffer(capacity: 48) - - XCTAssertThrowsError(try encoder.encode(frame: frame, to: &target), "Should throw an Unsupported error", { err in - guard let unsupported = err as? NIOHTTP2Errors.Unsupported, unsupported.info.contains("Padding") else { - XCTFail("Should have thrown an error due to unsupported PADDING flag") - return + + XCTAssertThrowsError( + try encoder.encode(frame: frame, to: &target), + "Should throw an Unsupported error", + { err in + guard let unsupported = err as? NIOHTTP2Errors.Unsupported, unsupported.info.contains("Padding") else { + XCTFail("Should have thrown an error due to unsupported PADDING flag") + return + } } - }) + ) } - + // MARK: - DATA frames func testDataFrameDecodingNoPadding() throws { let payload = byteBuffer(withStaticString: "Hello, World!") - let expectedFrame = HTTP2Frame(streamID: HTTP2StreamID(1), - payload: .data(.init(data: .byteBuffer(payload), endStream: true))) - + let expectedFrame = HTTP2Frame( + streamID: HTTP2StreamID(1), + payload: .data(.init(data: .byteBuffer(payload), endStream: true)) + ) + let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x0d, // 3-byte payload length (13 bytes) - 0x00, // 1-byte frame type (DATA) - 0x01, // 1-byte flags (END_STREAM) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x00, 0x00, 0x0d, // 3-byte payload length (13 bytes) + 0x00, // 1-byte frame type (DATA) + 0x01, // 1-byte flags (END_STREAM) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier ] var buf = byteBuffer(withBytes: frameBytes, extraCapacity: payload.readableBytes) buf.writeBytes(payload.readableBytesView) - + try assertReadsFrame(from: buf, matching: expectedFrame, expectedFlowControlledLength: 13) } - + func testDataFrameDecodingWithPadding() throws { let payload = byteBuffer(withStaticString: "Hello, World!") // We remove the PADDED flag when eliding padding bytes. - let expectedFrame = HTTP2Frame(streamID: HTTP2StreamID(1), - payload: .data(.init(data: .byteBuffer(payload), endStream: true, paddingBytes: 1))) - + let expectedFrame = HTTP2Frame( + streamID: HTTP2StreamID(1), + payload: .data(.init(data: .byteBuffer(payload), endStream: true, paddingBytes: 1)) + ) + // Unpadded frame is 22 bytes. When we add padding, we get +1 byte for pad length, +1 byte of padding, for 24 bytes total let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x0f, // 3-byte payload length (15 bytes) - 0x00, // 1-byte frame type (DATA) - 0x09, // 1-byte flags (PADDED, END_STREAM) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier - 0x01, // 1-byte padding length + 0x00, 0x00, 0x0f, // 3-byte payload length (15 bytes) + 0x00, // 1-byte frame type (DATA) + 0x09, // 1-byte flags (PADDED, END_STREAM) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x01, // 1-byte padding length ] var buf = byteBuffer(withBytes: frameBytes, extraCapacity: payload.readableBytes + 1) buf.writeBytes(payload.readableBytesView) buf.writeInteger(UInt8(0)) - + try assertReadsFrame(from: buf, matching: expectedFrame, expectedFlowControlledLength: 15) } func testDataFrameDecodingWithPaddingSplitOverBuffers() throws { // Unpadded frame is 22 bytes. When we add padding, we get +1 byte for pad length, +2 byte of padding, for 25 bytes total. let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x10, // 3-byte payload length (16 bytes) - 0x00, // 1-byte frame type (DATA) - 0x09, // 1-byte flags (PADDED, END_STREAM) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier - 0x02, // 1-byte padding length (2 bytes) + 0x00, 0x00, 0x10, // 3-byte payload length (16 bytes) + 0x00, // 1-byte frame type (DATA) + 0x09, // 1-byte flags (PADDED, END_STREAM) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x02, // 1-byte padding length (2 bytes) ] let expectedPayload = byteBuffer(withStaticString: "Hello, World!") // We remove the PADDED flag when eliding padding bytes. - let expectedFrame = HTTP2Frame(streamID: HTTP2StreamID(1), - payload: .data(.init(data: .byteBuffer(expectedPayload), endStream: true, paddingBytes: 2))) + let expectedFrame = HTTP2Frame( + streamID: HTTP2StreamID(1), + payload: .data(.init(data: .byteBuffer(expectedPayload), endStream: true, paddingBytes: 2)) + ) var frameBuffer = byteBuffer(withBytes: frameBytes, extraCapacity: expectedPayload.readableBytes) frameBuffer.writeBytes(expectedPayload.readableBytesView) @@ -243,26 +352,30 @@ class HTTP2FrameParserTests: XCTestCase { decoder.append(bytes: secondPaddingBuffer) XCTAssertNil(try decoder.nextFrame()) } - + func testSyntheticMultipleDataFrames() throws { let payload = byteBuffer(withStaticString: "Hello, World!Hello, World!") let payloadHalf = byteBuffer(withStaticString: "Hello, World!") - + let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x01a, // 3-byte payload length (26 bytes) - 0x00, // 1-byte frame type (DATA) - 0x01, // 1-byte flags (END_STREAM) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x00, 0x00, 0x01a, // 3-byte payload length (26 bytes) + 0x00, // 1-byte frame type (DATA) + 0x01, // 1-byte flags (END_STREAM) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier ] var buf = byteBuffer(withBytes: frameBytes, extraCapacity: payload.readableBytes) buf.writeBytes(payload.readableBytesView) - + // two separate pieces - let expectedFrame1 = HTTP2Frame(streamID: HTTP2StreamID(1), - payload: .data(.init(data: .byteBuffer(payloadHalf)))) - let expectedFrame2 = HTTP2Frame(streamID: HTTP2StreamID(1), - payload: .data(.init(data: .byteBuffer(payloadHalf), endStream: true))) - + let expectedFrame1 = HTTP2Frame( + streamID: HTTP2StreamID(1), + payload: .data(.init(data: .byteBuffer(payloadHalf))) + ) + let expectedFrame2 = HTTP2Frame( + streamID: HTTP2StreamID(1), + payload: .data(.init(data: .byteBuffer(payloadHalf), endStream: true)) + ) + var decoder = HTTP2FrameDecoder( allocator: self.allocator, expectClientMagic: false, @@ -274,35 +387,39 @@ class HTTP2FrameParserTests: XCTestCase { let frame: HTTP2Frame! = try decoder.nextFrame()?.0 XCTAssertNotNil(frame) self.assertEqualFrames(frame, expectedFrame1) - + decoder.append(bytes: buf) let frame2: HTTP2Frame! = try decoder.nextFrame()?.0 XCTAssertNotNil(frame) self.assertEqualFrames(frame2, expectedFrame2) } - + func testComplexPaddedSyntheticMultiDataFrames() throws { let payload = byteBuffer(withStaticString: "Hello, World!Hello, World!") let payloadHalf = byteBuffer(withStaticString: "Hello, World!") - + let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x1f, // 3-byte payload length (31 bytes) - 0x00, // 1-byte frame type (DATA) - 0x09, // 1-byte flags (END_STREAM, PADDED) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier - 0x04, // 1-byte padding length + 0x00, 0x00, 0x1f, // 3-byte payload length (31 bytes) + 0x00, // 1-byte frame type (DATA) + 0x09, // 1-byte flags (END_STREAM, PADDED) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x04, // 1-byte padding length ] var buf = byteBuffer(withBytes: frameBytes, extraCapacity: payload.readableBytes) buf.writeBytes(payload.readableBytesView) buf.writeBytes(Array(repeating: UInt8(0), count: 4)) XCTAssertEqual(buf.readableBytes, 40) - + // two separate pieces, padded flag removed along with padding bytes - let expectedFrame1 = HTTP2Frame(streamID: HTTP2StreamID(1), - payload: .data(.init(data: .byteBuffer(payloadHalf)))) - let expectedFrame2 = HTTP2Frame(streamID: HTTP2StreamID(1), - payload: .data(.init(data: .byteBuffer(payloadHalf), endStream: true, paddingBytes: 4))) - + let expectedFrame1 = HTTP2Frame( + streamID: HTTP2StreamID(1), + payload: .data(.init(data: .byteBuffer(payloadHalf))) + ) + let expectedFrame2 = HTTP2Frame( + streamID: HTTP2StreamID(1), + payload: .data(.init(data: .byteBuffer(payloadHalf), endStream: true, paddingBytes: 4)) + ) + var decoder = HTTP2FrameDecoder( allocator: self.allocator, expectClientMagic: false, @@ -312,32 +429,34 @@ class HTTP2FrameParserTests: XCTestCase { let slice = buf.readSlice(length: 9)! decoder.append(bytes: slice) let noFrame: HTTP2Frame! = try decoder.nextFrame()?.0 - XCTAssertNil(noFrame) // no frame produced - + XCTAssertNil(noFrame) // no frame produced + // append the next slice to the remaining bytes let next = buf.readSlice(length: payloadHalf.readableBytes + 1)! decoder.append(bytes: next) let frame: HTTP2Frame! = try decoder.nextFrame()?.0 XCTAssertNotNil(frame) // produces a frame self.assertEqualFrames(frame, expectedFrame1) - + decoder.append(bytes: buf) let frame2: HTTP2Frame! = try decoder.nextFrame()?.0 - XCTAssertNotNil(frame) // produces frame + XCTAssertNotNil(frame) // produces frame self.assertEqualFrames(frame2, expectedFrame2) } func testDataFrameDecodingMultibyteLength() throws { var payload = allocator.buffer(capacity: 16384) payload.writeBytes(repeatElement(0, count: 16384)) - let expectedFrame = HTTP2Frame(streamID: HTTP2StreamID(1), - payload: .data(.init(data: .byteBuffer(payload), endStream: true))) + let expectedFrame = HTTP2Frame( + streamID: HTTP2StreamID(1), + payload: .data(.init(data: .byteBuffer(payload), endStream: true)) + ) let frameBytes: [UInt8] = [ - 0x00, 0x40, 0x00, // 3-byte payload length (16384 bytes) - 0x00, // 1-byte frame type (DATA) - 0x01, // 1-byte flags (END_STREAM) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x00, 0x40, 0x00, // 3-byte payload length (16384 bytes) + 0x00, // 1-byte frame type (DATA) + 0x01, // 1-byte flags (END_STREAM) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier ] var buf = byteBuffer(withBytes: frameBytes, extraCapacity: payload.readableBytes) buf.writeBytes(payload.readableBytesView) @@ -347,15 +466,17 @@ class HTTP2FrameParserTests: XCTestCase { func testDataFrameDecodingZeroLengthPayload() throws { let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x00, // 3-byte payload length (0 bytes) - 0x00, // 1-byte frame type (DATA) - 0x01, // 1-byte flags (END_STREAM) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x00, 0x00, 0x00, // 3-byte payload length (0 bytes) + 0x00, // 1-byte frame type (DATA) + 0x01, // 1-byte flags (END_STREAM) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier ] let payload = allocator.buffer(capacity: 0) - let expectedFrame = HTTP2Frame(streamID: HTTP2StreamID(1), - payload: .data(.init(data: .byteBuffer(payload), endStream: true))) + let expectedFrame = HTTP2Frame( + streamID: HTTP2StreamID(1), + payload: .data(.init(data: .byteBuffer(payload), endStream: true)) + ) let buf = byteBuffer(withBytes: frameBytes) try assertReadsFrame(from: buf, matching: expectedFrame, expectedFlowControlledLength: 0) @@ -363,16 +484,18 @@ class HTTP2FrameParserTests: XCTestCase { func testDataFrameDecodingZeroLengthPaddingOnlyPayload() throws { let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x01, // 3-byte payload length (1 bytes) - 0x00, // 1-byte frame type (DATA) - 0x09, // 1-byte flags (PADDED, END_STREAM) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier - 0x00 // 1-byte padding length (0) + 0x00, 0x00, 0x01, // 3-byte payload length (1 bytes) + 0x00, // 1-byte frame type (DATA) + 0x09, // 1-byte flags (PADDED, END_STREAM) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x00, // 1-byte padding length (0) ] let expectedPayload = self.allocator.buffer(capacity: 0) - let expectedFrame = HTTP2Frame(streamID: HTTP2StreamID(1), - payload: .data(.init(data: .byteBuffer(expectedPayload), endStream: true, paddingBytes: 0))) + let expectedFrame = HTTP2Frame( + streamID: HTTP2StreamID(1), + payload: .data(.init(data: .byteBuffer(expectedPayload), endStream: true, paddingBytes: 0)) + ) let buffer = self.allocator.buffer(bytes: frameBytes) try assertReadsFrame(from: buffer, matching: expectedFrame, expectedFlowControlledLength: 1) @@ -381,17 +504,19 @@ class HTTP2FrameParserTests: XCTestCase { func testDataFrameDecodingPaddingOnlyPayload() throws { // Unpadded frame is 9 bytes. When we add padding, we get +1 byte for pad length, +1 byte of padding, for 11 bytes total. let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x02, // 3-byte payload length (2 bytes) - 0x00, // 1-byte frame type (DATA) - 0x09, // 1-byte flags (PADDED, END_STREAM) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier - 0x01, // 1-byte padding length + 0x00, 0x00, 0x02, // 3-byte payload length (2 bytes) + 0x00, // 1-byte frame type (DATA) + 0x09, // 1-byte flags (PADDED, END_STREAM) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x01, // 1-byte padding length ] let expectedPayload = allocator.buffer(capacity: 0) // We remove the PADDED flag when eliding padding bytes. - let expectedFrame = HTTP2Frame(streamID: HTTP2StreamID(1), - payload: .data(.init(data: .byteBuffer(expectedPayload), endStream: true, paddingBytes: 1))) + let expectedFrame = HTTP2Frame( + streamID: HTTP2StreamID(1), + payload: .data(.init(data: .byteBuffer(expectedPayload), endStream: true, paddingBytes: 1)) + ) var buf = byteBuffer(withBytes: frameBytes, extraCapacity: 1) buf.writeInteger(UInt8(0)) @@ -402,17 +527,19 @@ class HTTP2FrameParserTests: XCTestCase { func testDataFrameDecodingWithOnlyPaddingSplitOverBuffers() throws { // Unpadded frame is 9 bytes. When we add padding, we get +1 byte for pad length, +2 byte of padding, for 12 bytes total. let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x03, // 3-byte payload length (3 bytes) - 0x00, // 1-byte frame type (DATA) - 0x09, // 1-byte flags (PADDED, END_STREAM) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier - 0x02, // 1-byte padding length + 0x00, 0x00, 0x03, // 3-byte payload length (3 bytes) + 0x00, // 1-byte frame type (DATA) + 0x09, // 1-byte flags (PADDED, END_STREAM) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x02, // 1-byte padding length ] let expectedPayload = allocator.buffer(capacity: 0) // We remove the PADDED flag when eliding padding bytes. - let expectedFrame = HTTP2Frame(streamID: HTTP2StreamID(1), - payload: .data(.init(data: .byteBuffer(expectedPayload), endStream: true, paddingBytes: 2))) + let expectedFrame = HTTP2Frame( + streamID: HTTP2StreamID(1), + payload: .data(.init(data: .byteBuffer(expectedPayload), endStream: true, paddingBytes: 2)) + ) let frameBuffer = byteBuffer(withBytes: frameBytes) let firstPaddingBuffer = byteBuffer(withBytes: [UInt8(0)]) @@ -442,14 +569,17 @@ class HTTP2FrameParserTests: XCTestCase { var payloadBytes = allocator.buffer(capacity: payload.count) payloadBytes.writeString(payload) - let frame = HTTP2Frame(streamID: streamID, payload: .data(.init(data: .byteBuffer(payloadBytes), endStream: true))) + let frame = HTTP2Frame( + streamID: streamID, + payload: .data(.init(data: .byteBuffer(payloadBytes), endStream: true)) + ) var encoder = HTTP2FrameEncoder(allocator: self.allocator) let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x0d, // 3-byte payload length (13 bytes) - 0x00, // 1-byte frame type (DATA) - 0x01, // 1-byte flags (END_STREAM) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x00, 0x00, 0x0d, // 3-byte payload length (13 bytes) + 0x00, // 1-byte frame type (DATA) + 0x01, // 1-byte flags (END_STREAM) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier ] let expectedBufContent = byteBuffer(withBytes: frameBytes) var buf = self.allocator.buffer(capacity: expectedBufContent.readableBytes) @@ -464,14 +594,17 @@ class HTTP2FrameParserTests: XCTestCase { var payloadBytes = allocator.buffer(capacity: 16384) payloadBytes.writeBytes(repeatElement(0, count: 16384)) - let frame = HTTP2Frame(streamID: streamID, payload: .data(.init(data: .byteBuffer(payloadBytes), endStream: true))) + let frame = HTTP2Frame( + streamID: streamID, + payload: .data(.init(data: .byteBuffer(payloadBytes), endStream: true)) + ) var encoder = HTTP2FrameEncoder(allocator: self.allocator) let frameBytes: [UInt8] = [ - 0x00, 0x40, 0x00, // 3-byte payload length (16384 bytes) - 0x00, // 1-byte frame type (DATA) - 0x01, // 1-byte flags (END_STREAM) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x00, 0x40, 0x00, // 3-byte payload length (16384 bytes) + 0x00, // 1-byte frame type (DATA) + 0x01, // 1-byte flags (END_STREAM) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier ] let expectedBufContent = byteBuffer(withBytes: frameBytes) var buf = self.allocator.buffer(capacity: expectedBufContent.readableBytes) @@ -498,11 +631,11 @@ class HTTP2FrameParserTests: XCTestCase { func testDataFrameDecodeFailureRootStream() { let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x01, // 3-byte payload length (1 byte) - 0x00, // 1-byte frame type (DATA) - 0x01, // 1-byte flags (END_STREAM) - 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier (INVALID) - 0x00, // payload + 0x00, 0x00, 0x01, // 3-byte payload length (1 byte) + 0x00, // 1-byte frame type (DATA) + 0x01, // 1-byte flags (END_STREAM) + 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier (INVALID) + 0x00, // payload ] let badFrameBuf = byteBuffer(withBytes: frameBytes) var decoder = HTTP2FrameDecoder( @@ -512,22 +645,26 @@ class HTTP2FrameParserTests: XCTestCase { ) decoder.append(bytes: badFrameBuf) - XCTAssertThrowsError(try decoder.nextFrame(), "Should throw a protocol error", { err in - guard let connErr = err as? InternalError, case .codecError(code: .protocolError) = connErr else { - XCTFail("Should have thrown a codec error of type PROTOCOL_ERROR") - return + XCTAssertThrowsError( + try decoder.nextFrame(), + "Should throw a protocol error", + { err in + guard let connErr = err as? InternalError, case .codecError(code: .protocolError) = connErr else { + XCTFail("Should have thrown a codec error of type PROTOCOL_ERROR") + return + } } - }) + ) } - + func testDataFrameDecodeFailureExcessPadding() { let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x01, // 3-byte payload length (1 byte) - 0x00, // 1-byte frame type (DATA) - 0x09, // 1-byte flags (PADDED, END_STREAM) - 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier (INVALID) - 0x01, // 1-byte padding - // no payload! + 0x00, 0x00, 0x01, // 3-byte payload length (1 byte) + 0x00, // 1-byte frame type (DATA) + 0x09, // 1-byte flags (PADDED, END_STREAM) + 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier (INVALID) + 0x01, // 1-byte padding + // no payload! ] let buf = self.byteBuffer(withBytes: frameBytes) var decoder = HTTP2FrameDecoder( @@ -537,20 +674,24 @@ class HTTP2FrameParserTests: XCTestCase { ) decoder.append(bytes: buf) - XCTAssertThrowsError(try decoder.nextFrame(), "Should throw a protocol error", { err in - guard let connErr = err as? InternalError, case .codecError(code: .protocolError) = connErr else { - XCTFail("Should have thrown a codec error of type PROTOCOL_ERROR") - return + XCTAssertThrowsError( + try decoder.nextFrame(), + "Should throw a protocol error", + { err in + guard let connErr = err as? InternalError, case .codecError(code: .protocolError) = connErr else { + XCTFail("Should have thrown a codec error of type PROTOCOL_ERROR") + return + } } - }) + ) } func testDataFrameDecodeFailureZeroLengthPayloadAndPaddedFlag() throws { let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x00, // 3-byte payload length (0 bytes) - 0x00, // 1-byte frame type (DATA) - 0x09, // 1-byte flags (PADDED, END_STREAM) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x00, 0x00, 0x00, // 3-byte payload length (0 bytes) + 0x00, // 1-byte frame type (DATA) + 0x09, // 1-byte flags (PADDED, END_STREAM) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier ] let buffer = self.allocator.buffer(bytes: frameBytes) @@ -561,20 +702,24 @@ class HTTP2FrameParserTests: XCTestCase { ) decoder.append(bytes: buffer) - XCTAssertThrowsError(try decoder.nextFrame(), "Should throw a protocol error", { err in - guard let connErr = err as? InternalError, case .codecError(code: .protocolError) = connErr else { - XCTFail("Should have thrown a codec error of type PROTOCOL_ERROR") - return + XCTAssertThrowsError( + try decoder.nextFrame(), + "Should throw a protocol error", + { err in + guard let connErr = err as? InternalError, case .codecError(code: .protocolError) = connErr else { + XCTFail("Should have thrown a codec error of type PROTOCOL_ERROR") + return + } } - }) + ) } func testDataFrameDecodingViolatingMaxFrameSize() throws { let frameBytes: [UInt8] = [ - 0x00, 0x40, 0x01, // 3-byte payload length (16385 bytes) - 0x00, // 1-byte frame type (DATA) - 0x01, // 1-byte flags (END_STREAM) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x00, 0x40, 0x01, // 3-byte payload length (16385 bytes) + 0x00, // 1-byte frame type (DATA) + 0x01, // 1-byte flags (END_STREAM) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier ] let badFrameBuf = byteBuffer(withBytes: frameBytes) var decoder = HTTP2FrameDecoder( @@ -593,17 +738,19 @@ class HTTP2FrameParserTests: XCTestCase { func testDataFrameDecodingWithOnlyPaddingSplitOverBuffersFollowedByAnotherFrame() throws { // Unpadded frame is 9 bytes. When we add padding, we get +1 byte for pad length, +2 byte of padding, for 12 bytes total. let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x03, // 3-byte payload length (3 bytes) - 0x00, // 1-byte frame type (DATA) - 0x09, // 1-byte flags (PADDED, END_STREAM) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier - 0x02, // 1-byte padding length + 0x00, 0x00, 0x03, // 3-byte payload length (3 bytes) + 0x00, // 1-byte frame type (DATA) + 0x09, // 1-byte flags (PADDED, END_STREAM) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x02, // 1-byte padding length ] let expectedPayload = allocator.buffer(capacity: 0) // We remove the PADDED flag when eliding padding bytes. - let expectedFrame = HTTP2Frame(streamID: HTTP2StreamID(1), - payload: .data(.init(data: .byteBuffer(expectedPayload), endStream: true, paddingBytes: 2))) + let expectedFrame = HTTP2Frame( + streamID: HTTP2StreamID(1), + payload: .data(.init(data: .byteBuffer(expectedPayload), endStream: true, paddingBytes: 2)) + ) let frameBuffer = byteBuffer(withBytes: frameBytes) let firstPaddingBuffer = byteBuffer(withBytes: [UInt8(0)]) @@ -632,95 +779,103 @@ class HTTP2FrameParserTests: XCTestCase { self.assertEqualFrames(frame, expectedFrame) XCTAssertEqual(actualLength, 3) } - + // MARK: - HEADERS frames - + func testHeadersFrameDecodingNoPriorityNoPadding() throws { - let expectedFrame = HTTP2Frame(streamID: HTTP2StreamID(1), - payload: .headers(.init(headers: self.simpleHeaders))) - + let expectedFrame = HTTP2Frame( + streamID: HTTP2StreamID(1), + payload: .headers(.init(headers: self.simpleHeaders)) + ) + let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x11, // 3-byte payload length (17 bytes) - 0x01, // 1-byte frame type (HEADERS) - 0x04, // 1-byte flags (END_HEADERS) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x00, 0x00, 0x11, // 3-byte payload length (17 bytes) + 0x01, // 1-byte frame type (HEADERS) + 0x04, // 1-byte flags (END_HEADERS) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier ] var buf = byteBuffer(withBytes: frameBytes, extraCapacity: self.simpleHeadersEncoded.count) buf.writeBytes(self.simpleHeadersEncoded) - + try assertReadsFrame(from: buf, matching: expectedFrame) } - + func testHeadersFrameDecodingNoPriorityWithPadding() throws { - let expectedFrame = HTTP2Frame(streamID: HTTP2StreamID(1), - payload: .headers(.init(headers: self.simpleHeaders, paddingBytes: 3))) - + let expectedFrame = HTTP2Frame( + streamID: HTTP2StreamID(1), + payload: .headers(.init(headers: self.simpleHeaders, paddingBytes: 3)) + ) + let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x15, // 3-byte payload length (21 bytes) - 0x01, // 1-byte frame type (HEADERS) - 0x0c, // 1-byte flags (PADDED, END_HEADERS) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier - 0x03, // 1-byte pad length + 0x00, 0x00, 0x15, // 3-byte payload length (21 bytes) + 0x01, // 1-byte frame type (HEADERS) + 0x0c, // 1-byte flags (PADDED, END_HEADERS) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x03, // 1-byte pad length ] var buf = byteBuffer(withBytes: frameBytes, extraCapacity: self.simpleHeadersEncoded.count + 4) buf.writeBytes(self.simpleHeadersEncoded) buf.writeBytes([UInt8](repeating: 0, count: 3)) - + try assertReadsFrame(from: buf, matching: expectedFrame) } - + func testHeadersFrameDecodingWithPriorityNoPadding() throws { let priority = HTTP2Frame.StreamPriorityData(exclusive: true, dependency: HTTP2StreamID(1), weight: 139) - let expectedFrame = HTTP2Frame(streamID: HTTP2StreamID(3), - payload: .headers(.init(headers: self.simpleHeaders, priorityData: priority))) - + let expectedFrame = HTTP2Frame( + streamID: HTTP2StreamID(3), + payload: .headers(.init(headers: self.simpleHeaders, priorityData: priority)) + ) + let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x16, // 3-byte payload length (22 bytes) - 0x01, // 1-byte frame type (HEADERS) - 0x24, // 1-byte flags (END_HEADERS, PRIORITY) - 0x00, 0x00, 0x00, 0x03, // 4-byte stream identifier - 0x80, 0x00, 0x00, 0x01, // 4-byte stream dependency (top bit = exclusive) - 0x8b, // 1-byte weight (139) + 0x00, 0x00, 0x16, // 3-byte payload length (22 bytes) + 0x01, // 1-byte frame type (HEADERS) + 0x24, // 1-byte flags (END_HEADERS, PRIORITY) + 0x00, 0x00, 0x00, 0x03, // 4-byte stream identifier + 0x80, 0x00, 0x00, 0x01, // 4-byte stream dependency (top bit = exclusive) + 0x8b, // 1-byte weight (139) ] var buf = byteBuffer(withBytes: frameBytes, extraCapacity: self.simpleHeadersEncoded.count) buf.writeBytes(self.simpleHeadersEncoded) - + try assertReadsFrame(from: buf, matching: expectedFrame) } - + func testHeadersFrameDecodingWithPriorityWithPadding() throws { let priority = HTTP2Frame.StreamPriorityData(exclusive: true, dependency: HTTP2StreamID(1), weight: 139) - let expectedFrame = HTTP2Frame(streamID: HTTP2StreamID(3), - payload: .headers(.init(headers: self.simpleHeaders, priorityData: priority, paddingBytes: 8))) - + let expectedFrame = HTTP2Frame( + streamID: HTTP2StreamID(3), + payload: .headers(.init(headers: self.simpleHeaders, priorityData: priority, paddingBytes: 8)) + ) + let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x1F, // 3-byte payload length (31 bytes) - 0x01, // 1-byte frame type (HEADERS) - 0x2c, // 1-byte flags (PADDED, END_HEADERS, PRIORITY) - 0x00, 0x00, 0x00, 0x03, // 4-byte stream identifier - 0x08, // 1-byte pad length - 0x80, 0x00, 0x00, 0x01, // 4-byte stream dependency (top bit = exclusive) - 0x8b, // 1-byte weight (139) + 0x00, 0x00, 0x1F, // 3-byte payload length (31 bytes) + 0x01, // 1-byte frame type (HEADERS) + 0x2c, // 1-byte flags (PADDED, END_HEADERS, PRIORITY) + 0x00, 0x00, 0x00, 0x03, // 4-byte stream identifier + 0x08, // 1-byte pad length + 0x80, 0x00, 0x00, 0x01, // 4-byte stream dependency (top bit = exclusive) + 0x8b, // 1-byte weight (139) ] var buf = byteBuffer(withBytes: frameBytes, extraCapacity: self.simpleHeadersEncoded.count + 8) buf.writeBytes(self.simpleHeadersEncoded) buf.writeBytes([UInt8](repeating: 0, count: 8)) - + try assertReadsFrame(from: buf, matching: expectedFrame) } - + func testHeadersFrameDecodeFailures() { let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x15, // 3-byte payload length (21 bytes) - 0x01, // 1-byte frame type (HEADERS) - 0x0c, // 1-byte flags (PADDED, END_HEADERS) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier - 0x03, // 1-byte pad length + 0x00, 0x00, 0x15, // 3-byte payload length (21 bytes) + 0x01, // 1-byte frame type (HEADERS) + 0x0c, // 1-byte flags (PADDED, END_HEADERS) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x03, // 1-byte pad length ] var buf = byteBuffer(withBytes: frameBytes, extraCapacity: self.simpleHeadersEncoded.count) buf.writeBytes(self.simpleHeadersEncoded) buf.writeBytes([UInt8](repeating: 0, count: 3)) - + var decoder = HTTP2FrameDecoder( allocator: self.allocator, expectClientMagic: false, @@ -730,36 +885,44 @@ class HTTP2FrameParserTests: XCTestCase { // should fail if the stream is zero buf.setInteger(UInt8(0), at: 8) decoder.append(bytes: buf) - XCTAssertThrowsError(try decoder.nextFrame(), "Should throw a protocol error", { err in - guard let connErr = err as? InternalError, case .codecError(code: .protocolError) = connErr else { - XCTFail("Should have thrown a codec error of type PROTOCOL_ERROR") - return + XCTAssertThrowsError( + try decoder.nextFrame(), + "Should throw a protocol error", + { err in + guard let connErr = err as? InternalError, case .codecError(code: .protocolError) = connErr else { + XCTFail("Should have thrown a codec error of type PROTOCOL_ERROR") + return + } } - }) - + ) + buf.moveReaderIndex(to: 0) buf.setInteger(UInt8(1), at: 8) - + // pad size that exceeds payload size is illegal buf.setInteger(UInt8(200), at: 9) decoder.append(bytes: buf) - XCTAssertThrowsError(try decoder.nextFrame(), "Should throw a protocol error", { err in - guard let connErr = err as? InternalError, case .codecError(code: .protocolError) = connErr else { - XCTFail("Should have thrown a codec error of type PROTOCOL_ERROR") - return + XCTAssertThrowsError( + try decoder.nextFrame(), + "Should throw a protocol error", + { err in + guard let connErr = err as? InternalError, case .codecError(code: .protocolError) = connErr else { + XCTFail("Should have thrown a codec error of type PROTOCOL_ERROR") + return + } } - }) + ) } func testHeadersFrameDecodingWithPriorityAndIncorrectLength() throws { - for invalidLength in UInt8(0) ... UInt8(4) { + for invalidLength in UInt8(0)...UInt8(4) { let frameBytes: [UInt8] = [ 0x00, 0x00, invalidLength, // 3-byte payload length ('invalidLength' bytes) - 0x01, // 1-byte frame type (HEADERS) - 0x24, // 1-byte flags (END_HEADERS, PRIORITY) - 0x00, 0x00, 0x00, 0x03, // 4-byte stream identifier - 0x80, 0x00, 0x00, 0x01, // 4-byte stream dependency (top bit = exclusive) - 0x01, // 1-byte weight (1) + 0x01, // 1-byte frame type (HEADERS) + 0x24, // 1-byte flags (END_HEADERS, PRIORITY) + 0x00, 0x00, 0x00, 0x03, // 4-byte stream identifier + 0x80, 0x00, 0x00, 0x01, // 4-byte stream dependency (top bit = exclusive) + 0x01, // 1-byte weight (1) ] let buf = self.byteBuffer(withBytes: frameBytes) @@ -770,28 +933,34 @@ class HTTP2FrameParserTests: XCTestCase { ) decoder.append(bytes: buf) - XCTAssertThrowsError(try decoder.nextFrame(), "Should throw a protocol error", { err in - guard let connErr = err as? InternalError, case .codecError(code: .protocolError) = connErr else { - XCTFail("Should have thrown a codec error of type PROTOCOL_ERROR") - return + XCTAssertThrowsError( + try decoder.nextFrame(), + "Should throw a protocol error", + { err in + guard let connErr = err as? InternalError, case .codecError(code: .protocolError) = connErr else { + XCTFail("Should have thrown a codec error of type PROTOCOL_ERROR") + return + } } - }) + ) } } func testHeadersFrameDecodingWithPriorityAndCorrectLength() throws { let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x05, // 3-byte payload length (5 bytes) - 0x01, // 1-byte frame type (HEADERS) - 0x24, // 1-byte flags (END_HEADERS, PRIORITY) - 0x00, 0x00, 0x00, 0x03, // 4-byte stream identifier - 0x80, 0x00, 0x00, 0x01, // 4-byte stream dependency (top bit = exclusive) - 0x01, // 1-byte weight (1) + 0x00, 0x00, 0x05, // 3-byte payload length (5 bytes) + 0x01, // 1-byte frame type (HEADERS) + 0x24, // 1-byte flags (END_HEADERS, PRIORITY) + 0x00, 0x00, 0x00, 0x03, // 4-byte stream identifier + 0x80, 0x00, 0x00, 0x01, // 4-byte stream dependency (top bit = exclusive) + 0x01, // 1-byte weight (1) ] let priorityData = HTTP2Frame.StreamPriorityData(exclusive: true, dependency: HTTP2StreamID(1), weight: 1) - let expectedFrame = HTTP2Frame(streamID: HTTP2StreamID(3), - payload: .headers(.init(headers: [:], priorityData: priorityData, endStream: false))) + let expectedFrame = HTTP2Frame( + streamID: HTTP2StreamID(3), + payload: .headers(.init(headers: [:], priorityData: priorityData, endStream: false)) + ) let buf = byteBuffer(withBytes: frameBytes) try assertReadsFrame(from: buf, matching: expectedFrame) @@ -799,15 +968,17 @@ class HTTP2FrameParserTests: XCTestCase { func testHeadersFrameDecodingWithZeroLengthPaddingOnly() throws { let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x01, // 3-byte payload length (1 byte) - 0x01, // 1-byte frame type (HEADERS) - 0x0c, // 1-byte flags (PADDED, END_HEADERS) - 0x00, 0x00, 0x00, 0x03, // 4-byte stream identifier - 0x00 // 1-byte padding length (0) + 0x00, 0x00, 0x01, // 3-byte payload length (1 byte) + 0x01, // 1-byte frame type (HEADERS) + 0x0c, // 1-byte flags (PADDED, END_HEADERS) + 0x00, 0x00, 0x00, 0x03, // 4-byte stream identifier + 0x00, // 1-byte padding length (0) ] - let expectedFrame = HTTP2Frame(streamID: HTTP2StreamID(3), - payload: .headers(.init(headers: [:], endStream: false, paddingBytes: 0))) + let expectedFrame = HTTP2Frame( + streamID: HTTP2StreamID(3), + payload: .headers(.init(headers: [:], endStream: false, paddingBytes: 0)) + ) let buf = byteBuffer(withBytes: frameBytes) try assertReadsFrame(from: buf, matching: expectedFrame) @@ -816,20 +987,22 @@ class HTTP2FrameParserTests: XCTestCase { func testHeadersAndContinuationFrameDecodingWithZeroLengthPaddingOnly() throws { let frameBytes: [UInt8] = [ // HEADERS - 0x00, 0x00, 0x01, // 3-byte payload length (1 byte) - 0x01, // 1-byte frame type (HEADERS) - 0x08, // 1-byte flags (PADDED) - 0x00, 0x00, 0x00, 0x03, // 4-byte stream identifier - 0x00, // 1-byte padding length (0) + 0x00, 0x00, 0x01, // 3-byte payload length (1 byte) + 0x01, // 1-byte frame type (HEADERS) + 0x08, // 1-byte flags (PADDED) + 0x00, 0x00, 0x00, 0x03, // 4-byte stream identifier + 0x00, // 1-byte padding length (0) // CONTINUATION - 0x00, 0x00, 0x00, // 3-byte payload length (0 bytes) - 0x09, // 1-byte frame type (CONTINUATION) - 0x04, // 1-byte flags (END_HEADERS) - 0x00, 0x00, 0x00, 0x03 // 4-byte stream identifier + 0x00, 0x00, 0x00, // 3-byte payload length (0 bytes) + 0x09, // 1-byte frame type (CONTINUATION) + 0x04, // 1-byte flags (END_HEADERS) + 0x00, 0x00, 0x00, 0x03, // 4-byte stream identifier ] - let expectedFrame = HTTP2Frame(streamID: HTTP2StreamID(3), - payload: .headers(.init(headers: [:], endStream: false, paddingBytes: 0))) + let expectedFrame = HTTP2Frame( + streamID: HTTP2StreamID(3), + payload: .headers(.init(headers: [:], endStream: false, paddingBytes: 0)) + ) let buf = byteBuffer(withBytes: frameBytes) try assertReadsFrame(from: buf, matching: expectedFrame) @@ -837,10 +1010,10 @@ class HTTP2FrameParserTests: XCTestCase { func testHeadersFrameDecodingWithZeroLengthAndPaddingFlagSet() throws { let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x00, // 3-byte payload length (0 bytes) - 0x01, // 1-byte frame type (HEADERS) - 0x08, // 1-byte flags (PADDED) - 0x00, 0x00, 0x00, 0x03, // 4-byte stream identifier + 0x00, 0x00, 0x00, // 3-byte payload length (0 bytes) + 0x01, // 1-byte frame type (HEADERS) + 0x08, // 1-byte flags (PADDED) + 0x00, 0x00, 0x00, 0x03, // 4-byte stream identifier ] let buffer = self.allocator.buffer(bytes: frameBytes) @@ -851,21 +1024,25 @@ class HTTP2FrameParserTests: XCTestCase { ) decoder.append(bytes: buffer) - XCTAssertThrowsError(try decoder.nextFrame(), "Should throw a protocol error", { err in - guard let connErr = err as? InternalError, case .codecError(code: .protocolError) = connErr else { - XCTFail("Should have thrown a codec error of type PROTOCOL_ERROR") - return + XCTAssertThrowsError( + try decoder.nextFrame(), + "Should throw a protocol error", + { err in + guard let connErr = err as? InternalError, case .codecError(code: .protocolError) = connErr else { + XCTFail("Should have thrown a codec error of type PROTOCOL_ERROR") + return + } } - }) + ) } func testHeadersFrameDecodingWithNotEnoughPaddingBytes() throws { let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x01, // 3-byte payload length (1 bytes) - 0x01, // 1-byte frame type (HEADERS) - 0x08, // 1-byte flags (PADDED) - 0x00, 0x00, 0x00, 0x03, // 4-byte stream identifier - 0x01 // 1-byte padding length (1) + 0x00, 0x00, 0x01, // 3-byte payload length (1 bytes) + 0x01, // 1-byte frame type (HEADERS) + 0x08, // 1-byte flags (PADDED) + 0x00, 0x00, 0x00, 0x03, // 4-byte stream identifier + 0x01, // 1-byte padding length (1) ] let buffer = self.allocator.buffer(bytes: frameBytes) @@ -876,12 +1053,16 @@ class HTTP2FrameParserTests: XCTestCase { ) decoder.append(bytes: buffer) - XCTAssertThrowsError(try decoder.nextFrame(), "Should throw a protocol error", { err in - guard let connErr = err as? InternalError, case .codecError(code: .protocolError) = connErr else { - XCTFail("Should have thrown a codec error of type PROTOCOL_ERROR") - return + XCTAssertThrowsError( + try decoder.nextFrame(), + "Should throw a protocol error", + { err in + guard let connErr = err as? InternalError, case .codecError(code: .protocolError) = connErr else { + XCTFail("Should have thrown a codec error of type PROTOCOL_ERROR") + return + } } - }) + ) } func testHeadersFrameEncodingNoPriority() throws { @@ -890,74 +1071,77 @@ class HTTP2FrameParserTests: XCTestCase { var encoder = HTTP2FrameEncoder(allocator: self.allocator) let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x11, // 3-byte payload length (17 bytes) - 0x01, // 1-byte frame type (HEADERS) - 0x04, // 1-byte flags (END_HEADERS) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x00, 0x00, 0x11, // 3-byte payload length (17 bytes) + 0x01, // 1-byte frame type (HEADERS) + 0x04, // 1-byte flags (END_HEADERS) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier ] var expectedBufContent = byteBuffer(withBytes: frameBytes) expectedBufContent.writeBytes(self.simpleHeadersEncoded) var buf = self.allocator.buffer(capacity: expectedBufContent.readableBytes) - + let extraBuf = try encoder.encode(frame: frame, to: &buf) XCTAssertNil(extraBuf, "Should not return an extra buf") XCTAssertEqual(buf, expectedBufContent) } - + func testHeadersFrameEncodingWithPriority() throws { let priorityData = HTTP2Frame.StreamPriorityData(exclusive: true, dependency: HTTP2StreamID(1), weight: 139) let streamID = HTTP2StreamID(3) - - let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: self.simpleHeaders, priorityData: priorityData))) + + let frame = HTTP2Frame( + streamID: streamID, + payload: .headers(.init(headers: self.simpleHeaders, priorityData: priorityData)) + ) var encoder = HTTP2FrameEncoder(allocator: self.allocator) - + let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x16, // 3-byte payload length (22 bytes) - 0x01, // 1-byte frame type (HEADERS) - 0x24, // 1-byte flags (END_HEADERS, PRIORITY) - 0x00, 0x00, 0x00, 0x03, // 4-byte stream identifier - 0x80, 0x00, 0x00, 0x01, // 4-byte stream dependency (top bit = exclusive) - 0x8b, // 1-byte weight (139) + 0x00, 0x00, 0x16, // 3-byte payload length (22 bytes) + 0x01, // 1-byte frame type (HEADERS) + 0x24, // 1-byte flags (END_HEADERS, PRIORITY) + 0x00, 0x00, 0x00, 0x03, // 4-byte stream identifier + 0x80, 0x00, 0x00, 0x01, // 4-byte stream dependency (top bit = exclusive) + 0x8b, // 1-byte weight (139) ] var expectedBufContent = byteBuffer(withBytes: frameBytes) expectedBufContent.writeBytes(self.simpleHeadersEncoded) var buf = self.allocator.buffer(capacity: expectedBufContent.readableBytes) - + let extraBuf = try encoder.encode(frame: frame, to: &buf) XCTAssertNil(extraBuf, "Should not return an extra buf") XCTAssertEqual(buf, expectedBufContent) } - + // MARK: - PRIORITY frames - + func testPriorityFrameDecoding() throws { let priorityData = HTTP2Frame.StreamPriorityData(exclusive: true, dependency: HTTP2StreamID(1), weight: 139) let expectedFrame = HTTP2Frame(streamID: 3, payload: .priority(priorityData)) - + let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x05, // 3-byte payload length (5 bytes) - 0x02, // 1-byte frame type (PRIORITY) - 0x00, // 1-byte flags (none) - 0x00, 0x00, 0x00, 0x03, // 4-byte stream identifier - 0x80, 0x00, 0x00, 0x01, // 4-byte stream dependency (top bit = exclusive) - 0x8b, // 1-byte weight (139) + 0x00, 0x00, 0x05, // 3-byte payload length (5 bytes) + 0x02, // 1-byte frame type (PRIORITY) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x03, // 4-byte stream identifier + 0x80, 0x00, 0x00, 0x01, // 4-byte stream dependency (top bit = exclusive) + 0x8b, // 1-byte weight (139) ] let buf = byteBuffer(withBytes: frameBytes) - + try assertReadsFrame(from: buf, matching: expectedFrame) } - + func testPriorityFrameDecodingFailure() { let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x05, // 3-byte payload length (5 bytes) - 0x02, // 1-byte frame type (PRIORITY) - 0x00, // 1-byte flags (none) - 0x00, 0x00, 0x00, 0x03, // 4-byte stream identifier - 0x80, 0x00, 0x00, 0x01, // 4-byte stream dependency (top bit = exclusive) - 0x8b, // 1-byte weight (139) + 0x00, 0x00, 0x05, // 3-byte payload length (5 bytes) + 0x02, // 1-byte frame type (PRIORITY) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x03, // 4-byte stream identifier + 0x80, 0x00, 0x00, 0x01, // 4-byte stream dependency (top bit = exclusive) + 0x8b, // 1-byte weight (139) ] var buf = byteBuffer(withBytes: frameBytes) - + var decoder = HTTP2FrameDecoder( allocator: self.allocator, expectClientMagic: false, @@ -967,76 +1151,84 @@ class HTTP2FrameParserTests: XCTestCase { // cannot be on root stream buf.setInteger(UInt8(0), at: 8) decoder.append(bytes: buf) - XCTAssertThrowsError(try decoder.nextFrame(), "Should throw a protocol error", { err in - guard let connErr = err as? InternalError, case .codecError(code: .protocolError) = connErr else { - XCTFail("Should have thrown a codec error of type PROTOCOL_ERROR") - return + XCTAssertThrowsError( + try decoder.nextFrame(), + "Should throw a protocol error", + { err in + guard let connErr = err as? InternalError, case .codecError(code: .protocolError) = connErr else { + XCTFail("Should have thrown a codec error of type PROTOCOL_ERROR") + return + } } - }) + ) buf.setInteger(UInt8(3), at: 8) buf.moveReaderIndex(to: 0) - + // must have a size of 5 octets buf.setInteger(UInt8(6), at: 2) - buf.writeInteger(UInt8(0)) // append an extra byte so we read it all + buf.writeInteger(UInt8(0)) // append an extra byte so we read it all decoder.append(bytes: buf) - XCTAssertThrowsError(try decoder.nextFrame(), "Should throw a frame size error", { err in - guard let connErr = err as? InternalError, case .codecError(code: .frameSizeError) = connErr else { - XCTFail("Should have thrown a codec error of type FRAME_SIZE_ERROR") - return + XCTAssertThrowsError( + try decoder.nextFrame(), + "Should throw a frame size error", + { err in + guard let connErr = err as? InternalError, case .codecError(code: .frameSizeError) = connErr else { + XCTFail("Should have thrown a codec error of type FRAME_SIZE_ERROR") + return + } } - }) + ) } - + func testPriorityFrameEncoding() throws { let streamID = HTTP2StreamID(3) let priorityData = HTTP2Frame.StreamPriorityData(exclusive: true, dependency: HTTP2StreamID(1), weight: 139) let frame = HTTP2Frame(streamID: streamID, payload: .priority(priorityData)) var encoder = HTTP2FrameEncoder(allocator: self.allocator) - + let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x05, // 3-byte payload length (5 bytes) - 0x02, // 1-byte frame type (PRIORITY) - 0x00, // 1-byte flags (none) - 0x00, 0x00, 0x00, 0x03, // 4-byte stream identifier - 0x80, 0x00, 0x00, 0x01, // 4-byte stream dependency (top bit = exclusive) - 0x8b, // 1-byte weight (139) + 0x00, 0x00, 0x05, // 3-byte payload length (5 bytes) + 0x02, // 1-byte frame type (PRIORITY) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x03, // 4-byte stream identifier + 0x80, 0x00, 0x00, 0x01, // 4-byte stream dependency (top bit = exclusive) + 0x8b, // 1-byte weight (139) ] let expectedBufContent = byteBuffer(withBytes: frameBytes) var buf = self.allocator.buffer(capacity: expectedBufContent.readableBytes) - + let extraBuf = try encoder.encode(frame: frame, to: &buf) XCTAssertNil(extraBuf, "Should not have returned extra buf") XCTAssertEqual(buf, expectedBufContent) } - + // MARK: - RST_STREAM frames - + func testResetStreamFrameDecoding() throws { let expectedFrame = HTTP2Frame(streamID: 1, payload: .rstStream(.protocolError)) - + let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x04, // 3-byte payload length (4 bytes) - 0x03, // 1-byte frame type (RST_STREAM) - 0x00, // 1-byte flags (none) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier - 0x00, 0x00, 0x00, 0x01, // 4-byte error (PROTOCOL_ERROR = 0x1) + 0x00, 0x00, 0x04, // 3-byte payload length (4 bytes) + 0x03, // 1-byte frame type (RST_STREAM) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x00, 0x00, 0x00, 0x01, // 4-byte error (PROTOCOL_ERROR = 0x1) ] let buf = byteBuffer(withBytes: frameBytes) - + try assertReadsFrame(from: buf, matching: expectedFrame) } - + func testResetStreamFrameDecodingFailure() { let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x04, // 3-byte payload length (4 bytes) - 0x03, // 1-byte frame type (RST_STREAM) - 0x00, // 1-byte flags (none) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier - 0x00, 0x00, 0x00, 0x01, // 4-byte error (PROTOCOL_ERROR = 0x1) + 0x00, 0x00, 0x04, // 3-byte payload length (4 bytes) + 0x03, // 1-byte frame type (RST_STREAM) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x00, 0x00, 0x00, 0x01, // 4-byte error (PROTOCOL_ERROR = 0x1) ] var buf = byteBuffer(withBytes: frameBytes) - + var decoder = HTTP2FrameDecoder( allocator: self.allocator, expectClientMagic: false, @@ -1046,132 +1238,140 @@ class HTTP2FrameParserTests: XCTestCase { // cannot be on root stream buf.setInteger(UInt8(0), at: 8) decoder.append(bytes: buf) - XCTAssertThrowsError(try decoder.nextFrame(), "Should throw a protocol error", { err in - guard let connErr = err as? InternalError, case .codecError(code: .protocolError) = connErr else { - XCTFail("Should have thrown a codec error of type PROTOCOL_ERROR") - return + XCTAssertThrowsError( + try decoder.nextFrame(), + "Should throw a protocol error", + { err in + guard let connErr = err as? InternalError, case .codecError(code: .protocolError) = connErr else { + XCTFail("Should have thrown a codec error of type PROTOCOL_ERROR") + return + } } - }) + ) buf.setInteger(UInt8(1), at: 8) buf.moveReaderIndex(to: 0) - + // must have a size of 4 octets buf.setInteger(UInt8(5), at: 2) - buf.writeInteger(UInt8(0)) // append an extra byte so we read it all + buf.writeInteger(UInt8(0)) // append an extra byte so we read it all decoder.append(bytes: buf) - XCTAssertThrowsError(try decoder.nextFrame(), "Should throw a frame size error", { err in - guard let connErr = err as? InternalError, case .codecError(code: .frameSizeError) = connErr else { - XCTFail("Should have thrown a codec error of type FRAME_SIZE_ERROR") - return + XCTAssertThrowsError( + try decoder.nextFrame(), + "Should throw a frame size error", + { err in + guard let connErr = err as? InternalError, case .codecError(code: .frameSizeError) = connErr else { + XCTFail("Should have thrown a codec error of type FRAME_SIZE_ERROR") + return + } } - }) + ) } - + func testResetStreamFrameEncoding() throws { let streamID = HTTP2StreamID(1) let frame = HTTP2Frame(streamID: streamID, payload: .rstStream(.protocolError)) var encoder = HTTP2FrameEncoder(allocator: self.allocator) - + let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x04, // 3-byte payload length (4 bytes) - 0x03, // 1-byte frame type (RST_STREAM) - 0x00, // 1-byte flags (none) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier - 0x00, 0x00, 0x00, 0x01, // 4-byte error (PROTOCOL_ERROR = 0x1) + 0x00, 0x00, 0x04, // 3-byte payload length (4 bytes) + 0x03, // 1-byte frame type (RST_STREAM) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x00, 0x00, 0x00, 0x01, // 4-byte error (PROTOCOL_ERROR = 0x1) ] let expectedBufContent = byteBuffer(withBytes: frameBytes) var buf = self.allocator.buffer(capacity: expectedBufContent.readableBytes) - + let extraBuf = try encoder.encode(frame: frame, to: &buf) XCTAssertNil(extraBuf, "Should not have returned extra buf") XCTAssertEqual(buf, expectedBufContent) } - + // MARK: - SETTINGS frames - + func testSettingsFrameDecoding() throws { let settings: [HTTP2Setting] = [ HTTP2Setting(parameter: .headerTableSize, value: 256), HTTP2Setting(parameter: .initialWindowSize, value: 32_768), - HTTP2Setting(parameter: .maxHeaderListSize, value: 2_048) + HTTP2Setting(parameter: .maxHeaderListSize, value: 2_048), ] let expectedFrame = HTTP2Frame(streamID: .rootStream, payload: .settings(.settings(settings))) - + let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x12, // 3-byte payload length (18 bytes) - 0x04, // 1-byte frame type (SETTINGS) - 0x00, // 1-byte flags (none) - 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier - 0x00, 0x01, // SETTINGS_HEADER_TABLE_SIZE - 0x00, 0x00, 0x01, 0x00, // = 256 bytes - 0x00, 0x04, // SETTINGS_INITIAL_WINDOW_SIZE - 0x00, 0x00, 0x80, 0x00, // = 32 KiB - 0x00, 0x06, // SETTINGS_MAX_HEADER_LIST_SIZE - 0x00, 0x00, 0x08, 0x00, // = 2 KiB + 0x00, 0x00, 0x12, // 3-byte payload length (18 bytes) + 0x04, // 1-byte frame type (SETTINGS) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier + 0x00, 0x01, // SETTINGS_HEADER_TABLE_SIZE + 0x00, 0x00, 0x01, 0x00, // = 256 bytes + 0x00, 0x04, // SETTINGS_INITIAL_WINDOW_SIZE + 0x00, 0x00, 0x80, 0x00, // = 32 KiB + 0x00, 0x06, // SETTINGS_MAX_HEADER_LIST_SIZE + 0x00, 0x00, 0x08, 0x00, // = 2 KiB ] let buf = byteBuffer(withBytes: frameBytes) - + try assertReadsFrame(from: buf, matching: expectedFrame) } - func testSettingsFrameDecodingWithNoSettings() throws { - let settings: [HTTP2Setting] = [] - let expectedFrame = HTTP2Frame(streamID: .rootStream, payload: .settings(.settings(settings))) + func testSettingsFrameDecodingWithNoSettings() throws { + let settings: [HTTP2Setting] = [] + let expectedFrame = HTTP2Frame(streamID: .rootStream, payload: .settings(.settings(settings))) - let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x00, // 3-byte payload length (0 bytes) - 0x04, // 1-byte frame type (SETTINGS) - 0x00, // 1-byte flags (none) - 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier - ] - let buf = byteBuffer(withBytes: frameBytes) + let frameBytes: [UInt8] = [ + 0x00, 0x00, 0x00, // 3-byte payload length (0 bytes) + 0x04, // 1-byte frame type (SETTINGS) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier + ] + let buf = byteBuffer(withBytes: frameBytes) + + try assertReadsFrame(from: buf, matching: expectedFrame) + } - try assertReadsFrame(from: buf, matching: expectedFrame) - } - func testSettingsFrameDecodingWithUnknownItems() throws { let settings: [HTTP2Setting] = [ HTTP2Setting(parameter: .headerTableSize, value: 256), HTTP2Setting(parameter: .initialWindowSize, value: 32_768), HTTP2Setting(parameter: HTTP2SettingsParameter(fromNetwork: 0x99), value: 32_768), - HTTP2Setting(parameter: .maxHeaderListSize, value: 2_048) + HTTP2Setting(parameter: .maxHeaderListSize, value: 2_048), ] let expectedFrame = HTTP2Frame(streamID: .rootStream, payload: .settings(.settings(settings))) - + let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x18, // 3-byte payload length (18 bytes) - 0x04, // 1-byte frame type (SETTINGS) - 0x00, // 1-byte flags (none) - 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier - 0x00, 0x01, // SETTINGS_HEADER_TABLE_SIZE - 0x00, 0x00, 0x01, 0x00, // = 256 bytes - 0x00, 0x04, // SETTINGS_INITIAL_WINDOW_SIZE - 0x00, 0x00, 0x80, 0x00, // = 32 KiB - 0x00, 0x99, // <> - 0x00, 0x00, 0x80, 0x00, // = 32768 somethings - 0x00, 0x06, // SETTINGS_MAX_HEADER_LIST_SIZE - 0x00, 0x00, 0x08, 0x00, // = 2 KiB + 0x00, 0x00, 0x18, // 3-byte payload length (18 bytes) + 0x04, // 1-byte frame type (SETTINGS) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier + 0x00, 0x01, // SETTINGS_HEADER_TABLE_SIZE + 0x00, 0x00, 0x01, 0x00, // = 256 bytes + 0x00, 0x04, // SETTINGS_INITIAL_WINDOW_SIZE + 0x00, 0x00, 0x80, 0x00, // = 32 KiB + 0x00, 0x99, // <> + 0x00, 0x00, 0x80, 0x00, // = 32768 somethings + 0x00, 0x06, // SETTINGS_MAX_HEADER_LIST_SIZE + 0x00, 0x00, 0x08, 0x00, // = 2 KiB ] let buf = byteBuffer(withBytes: frameBytes) - + try assertReadsFrame(from: buf, matching: expectedFrame) } - + func testSettingsFrameDecodingFailure() { let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x12, // 3-byte payload length (18 bytes) - 0x04, // 1-byte frame type (SETTINGS) - 0x00, // 1-byte flags (none) - 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier - 0x00, 0x01, // SETTINGS_HEADER_TABLE_SIZE - 0x00, 0x00, 0x01, 0x00, // = 256 bytes - 0x00, 0x04, // SETTINGS_INITIAL_WINDOW_SIZE - 0x00, 0x00, 0x80, 0x00, // = 32 KiB - 0x00, 0x06, // SETTINGS_MAX_HEADER_LIST_SIZE - 0x00, 0x00, 0x08, 0x00, // = 2 KiB + 0x00, 0x00, 0x12, // 3-byte payload length (18 bytes) + 0x04, // 1-byte frame type (SETTINGS) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier + 0x00, 0x01, // SETTINGS_HEADER_TABLE_SIZE + 0x00, 0x00, 0x01, 0x00, // = 256 bytes + 0x00, 0x04, // SETTINGS_INITIAL_WINDOW_SIZE + 0x00, 0x00, 0x80, 0x00, // = 32 KiB + 0x00, 0x06, // SETTINGS_MAX_HEADER_LIST_SIZE + 0x00, 0x00, 0x08, 0x00, // = 2 KiB ] var buf = byteBuffer(withBytes: frameBytes) - + var decoder = HTTP2FrameDecoder( allocator: self.allocator, expectClientMagic: false, @@ -1181,78 +1381,86 @@ class HTTP2FrameParserTests: XCTestCase { // MUST be sent on the root stream buf.setInteger(UInt8(1), at: 8) decoder.append(bytes: buf) - XCTAssertThrowsError(try decoder.nextFrame(), "Should throw a protocol error", { err in - guard let connErr = err as? InternalError, case .codecError(code: .protocolError) = connErr else { - XCTFail("Should have thrown a codec error of type PROTOCOL_ERROR") - return + XCTAssertThrowsError( + try decoder.nextFrame(), + "Should throw a protocol error", + { err in + guard let connErr = err as? InternalError, case .codecError(code: .protocolError) = connErr else { + XCTFail("Should have thrown a codec error of type PROTOCOL_ERROR") + return + } } - }) + ) buf.setInteger(UInt8(0), at: 8) buf.moveReaderIndex(to: 0) - + // size must be a multiple of 6 octets buf.setInteger(UInt8(19), at: 2) - buf.writeInteger(UInt8(0)) // append an extra byte so we read it all + buf.writeInteger(UInt8(0)) // append an extra byte so we read it all decoder.append(bytes: buf) - XCTAssertThrowsError(try decoder.nextFrame(), "Should throw a frame size error", { err in - guard let connErr = err as? InternalError, case .codecError(code: .frameSizeError) = connErr else { - XCTFail("Should have thrown a codec error of type FRAME_SIZE_ERROR") - return + XCTAssertThrowsError( + try decoder.nextFrame(), + "Should throw a frame size error", + { err in + guard let connErr = err as? InternalError, case .codecError(code: .frameSizeError) = connErr else { + XCTFail("Should have thrown a codec error of type FRAME_SIZE_ERROR") + return + } } - }) + ) } - + func testSettingsFrameEncoding() throws { let settings: [HTTP2Setting] = [ HTTP2Setting(parameter: .headerTableSize, value: 256), HTTP2Setting(parameter: .initialWindowSize, value: 32_768), - HTTP2Setting(parameter: .maxHeaderListSize, value: 2_048) + HTTP2Setting(parameter: .maxHeaderListSize, value: 2_048), ] let frame = HTTP2Frame(streamID: .rootStream, payload: .settings(.settings(settings))) var encoder = HTTP2FrameEncoder(allocator: self.allocator) - + let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x12, // 3-byte payload length (18 bytes) - 0x04, // 1-byte frame type (SETTINGS) - 0x00, // 1-byte flags (none) - 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier - 0x00, 0x01, // SETTINGS_HEADER_TABLE_SIZE - 0x00, 0x00, 0x01, 0x00, // = 256 bytes - 0x00, 0x04, // SETTINGS_INITIAL_WINDOW_SIZE - 0x00, 0x00, 0x80, 0x00, // = 32 KiB - 0x00, 0x06, // SETTINGS_MAX_HEADER_LIST_SIZE - 0x00, 0x00, 0x08, 0x00, // = 2 KiB + 0x00, 0x00, 0x12, // 3-byte payload length (18 bytes) + 0x04, // 1-byte frame type (SETTINGS) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier + 0x00, 0x01, // SETTINGS_HEADER_TABLE_SIZE + 0x00, 0x00, 0x01, 0x00, // = 256 bytes + 0x00, 0x04, // SETTINGS_INITIAL_WINDOW_SIZE + 0x00, 0x00, 0x80, 0x00, // = 32 KiB + 0x00, 0x06, // SETTINGS_MAX_HEADER_LIST_SIZE + 0x00, 0x00, 0x08, 0x00, // = 2 KiB ] let expectedBufContent = byteBuffer(withBytes: frameBytes) var buf = self.allocator.buffer(capacity: expectedBufContent.readableBytes) - + let extraBuf = try encoder.encode(frame: frame, to: &buf) XCTAssertNil(extraBuf, "Should not have returned extra buf") XCTAssertEqual(buf, expectedBufContent) } - + func testSettingsAckFrameDecoding() throws { let expectedFrame = HTTP2Frame(streamID: .rootStream, payload: .settings(.ack)) let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x00, // 3-byte payload length (0 bytes) - 0x04, // 1-byte frame type (SETTINGS) - 0x01, // 1-byte flags (ACK) - 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier + 0x00, 0x00, 0x00, // 3-byte payload length (0 bytes) + 0x04, // 1-byte frame type (SETTINGS) + 0x01, // 1-byte flags (ACK) + 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier ] let buf = byteBuffer(withBytes: frameBytes) - + try self.assertReadsFrame(from: buf, matching: expectedFrame) } - + func testSettingsAckFrameDecodingFailure() { let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x00, // 3-byte payload length (0 bytes) - 0x04, // 1-byte frame type (SETTINGS) - 0x01, // 1-byte flags (ACK) - 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier + 0x00, 0x00, 0x00, // 3-byte payload length (0 bytes) + 0x04, // 1-byte frame type (SETTINGS) + 0x01, // 1-byte flags (ACK) + 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier ] var buf = byteBuffer(withBytes: frameBytes) - + var decoder = HTTP2FrameDecoder( allocator: self.allocator, expectClientMagic: false, @@ -1262,96 +1470,108 @@ class HTTP2FrameParserTests: XCTestCase { // MUST be sent on the root stream buf.setInteger(UInt8(1), at: 8) decoder.append(bytes: buf) - XCTAssertThrowsError(try decoder.nextFrame(), "Should throw a protocol error", { err in - guard let connErr = err as? InternalError, case .codecError(code: .protocolError) = connErr else { - XCTFail("Should have thrown a codec error of type PROTOCOL_ERROR") - return + XCTAssertThrowsError( + try decoder.nextFrame(), + "Should throw a protocol error", + { err in + guard let connErr = err as? InternalError, case .codecError(code: .protocolError) = connErr else { + XCTFail("Should have thrown a codec error of type PROTOCOL_ERROR") + return + } } - }) + ) buf.setInteger(UInt8(0), at: 8) buf.moveReaderIndex(to: 0) - + // size must be 0 for ACKs buf.setInteger(UInt8(1), at: 2) - buf.writeInteger(UInt8(0)) // append an extra byte so we read it all + buf.writeInteger(UInt8(0)) // append an extra byte so we read it all decoder.append(bytes: buf) - XCTAssertThrowsError(try decoder.nextFrame(), "Should throw a frame size error", { err in - guard let connErr = err as? InternalError, case .codecError(code: .frameSizeError) = connErr else { - XCTFail("Should have thrown a codec error of type FRAME_SIZE_ERROR") - return + XCTAssertThrowsError( + try decoder.nextFrame(), + "Should throw a frame size error", + { err in + guard let connErr = err as? InternalError, case .codecError(code: .frameSizeError) = connErr else { + XCTFail("Should have thrown a codec error of type FRAME_SIZE_ERROR") + return + } } - }) + ) } - + func testSettingsAckFrameEncoding() throws { let frame = HTTP2Frame(streamID: .rootStream, payload: .settings(.ack)) var encoder = HTTP2FrameEncoder(allocator: self.allocator) - + let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x00, // 3-byte payload length (0 bytes) - 0x04, // 1-byte frame type (SETTINGS) - 0x01, // 1-byte flags (ACK) - 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier + 0x00, 0x00, 0x00, // 3-byte payload length (0 bytes) + 0x04, // 1-byte frame type (SETTINGS) + 0x01, // 1-byte flags (ACK) + 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier ] let expectedBufContent = byteBuffer(withBytes: frameBytes) var buf = self.allocator.buffer(capacity: expectedBufContent.readableBytes) - + let extraBuf = try encoder.encode(frame: frame, to: &buf) XCTAssertNil(extraBuf, "Should not have returned extra buf") XCTAssertEqual(buf, expectedBufContent) } - + // MARK: - PUSH_PROMISE frames - + func testPushPromiseFrameDecodingNoPadding() throws { let streamID = HTTP2StreamID(3) - let expectedFrame = HTTP2Frame(streamID: HTTP2StreamID(1), - payload: .pushPromise(.init(pushedStreamID: streamID, headers: self.simpleHeaders))) - + let expectedFrame = HTTP2Frame( + streamID: HTTP2StreamID(1), + payload: .pushPromise(.init(pushedStreamID: streamID, headers: self.simpleHeaders)) + ) + let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x15, // 3-byte payload length (21 bytes) - 0x05, // 1-byte frame type (PUSH_PROMISE) - 0x04, // 1-byte flags (END_HEADERS) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier - 0x00, 0x00, 0x00, 0x03, // 4-byte promised stream identifier + 0x00, 0x00, 0x15, // 3-byte payload length (21 bytes) + 0x05, // 1-byte frame type (PUSH_PROMISE) + 0x04, // 1-byte flags (END_HEADERS) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x00, 0x00, 0x00, 0x03, // 4-byte promised stream identifier ] var buf = byteBuffer(withBytes: frameBytes, extraCapacity: self.simpleHeadersEncoded.count) buf.writeBytes(self.simpleHeadersEncoded) - + try self.assertReadsFrame(from: buf, matching: expectedFrame) } - + func testPushPromiseFrameDecodingWithPadding() throws { let streamID = HTTP2StreamID(3) - let expectedFrame = HTTP2Frame(streamID: HTTP2StreamID(1), - payload: .pushPromise(.init(pushedStreamID: streamID, headers: self.simpleHeaders, paddingBytes: 1))) - + let expectedFrame = HTTP2Frame( + streamID: HTTP2StreamID(1), + payload: .pushPromise(.init(pushedStreamID: streamID, headers: self.simpleHeaders, paddingBytes: 1)) + ) + let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x17, // 3-byte payload length (23 bytes) (32 total) - 0x05, // 1-byte frame type (PUSH_PROMISE) - 0x0c, // 1-byte flags (END_HEADERS, PADDED) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier - 0x01, // 1-byte pad size - 0x00, 0x00, 0x00, 0x03, // 4-byte promised stream identifier + 0x00, 0x00, 0x17, // 3-byte payload length (23 bytes) (32 total) + 0x05, // 1-byte frame type (PUSH_PROMISE) + 0x0c, // 1-byte flags (END_HEADERS, PADDED) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x01, // 1-byte pad size + 0x00, 0x00, 0x00, 0x03, // 4-byte promised stream identifier ] var buf = byteBuffer(withBytes: frameBytes, extraCapacity: self.simpleHeadersEncoded.count) buf.writeBytes(self.simpleHeadersEncoded) buf.writeInteger(UInt8(0)) - + try self.assertReadsFrame(from: buf, matching: expectedFrame) } - + func testPushPromiseFrameDecodingFailure() { let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x15, // 3-byte payload length (21 bytes) - 0x05, // 1-byte frame type (PUSH_PROMISE) - 0x04, // 1-byte flags (END_HEADERS) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier - 0x00, 0x00, 0x00, 0x03, // 4-byte promised stream identifier + 0x00, 0x00, 0x15, // 3-byte payload length (21 bytes) + 0x05, // 1-byte frame type (PUSH_PROMISE) + 0x04, // 1-byte flags (END_HEADERS) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x00, 0x00, 0x00, 0x03, // 4-byte promised stream identifier ] var buf = byteBuffer(withBytes: frameBytes) buf.writeBytes(self.simpleHeadersEncoded) - + var decoder = HTTP2FrameDecoder( allocator: self.allocator, expectClientMagic: false, @@ -1361,28 +1581,34 @@ class HTTP2FrameParserTests: XCTestCase { // MUST NOT be sent on the root stream buf.setInteger(UInt8(0), at: 8) decoder.append(bytes: buf) - XCTAssertThrowsError(try decoder.nextFrame(), "Should throw a protocol error", { err in - guard let connErr = err as? InternalError, case .codecError(code: .protocolError) = connErr else { - XCTFail("Should have thrown a codec error of type PROTOCOL_ERROR") - return + XCTAssertThrowsError( + try decoder.nextFrame(), + "Should throw a protocol error", + { err in + guard let connErr = err as? InternalError, case .codecError(code: .protocolError) = connErr else { + XCTFail("Should have thrown a codec error of type PROTOCOL_ERROR") + return + } } - }) + ) buf.setInteger(UInt8(0), at: 8) buf.moveReaderIndex(to: 0) } - + func testPushPromiseFrameEncoding() throws { let streamID = HTTP2StreamID(3) - let frame = HTTP2Frame(streamID: HTTP2StreamID(1), - payload: .pushPromise(.init(pushedStreamID: streamID, headers: self.simpleHeaders))) + let frame = HTTP2Frame( + streamID: HTTP2StreamID(1), + payload: .pushPromise(.init(pushedStreamID: streamID, headers: self.simpleHeaders)) + ) var encoder = HTTP2FrameEncoder(allocator: self.allocator) - + let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x15, // 3-byte payload length (21 bytes) - 0x05, // 1-byte frame type (PUSH_PROMISE) - 0x04, // 1-byte flags (END_HEADERS) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier - 0x00, 0x00, 0x00, 0x03, // 4-byte promised stream identifier + 0x00, 0x00, 0x15, // 3-byte payload length (21 bytes) + 0x05, // 1-byte frame type (PUSH_PROMISE) + 0x04, // 1-byte flags (END_HEADERS) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x00, 0x00, 0x00, 0x03, // 4-byte promised stream identifier ] var expectedBufContent = self.byteBuffer(withBytes: frameBytes) expectedBufContent.writeBytes(self.simpleHeadersEncoded) @@ -1395,16 +1621,18 @@ class HTTP2FrameParserTests: XCTestCase { func testPushPromiseFrameDecodingWithZeroLengthPadding() throws { let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x05, // 3-byte payload length (5 bytes) - 0x05, // 1-byte frame type (PUSH_PROMISE) - 0x0c, // 1-byte flags (PADDED, END_HEADERS) - 0x00, 0x00, 0x00, 0x03, // 4-byte stream identifier - 0x00, // 1-byte padding length (0) - 0x00, 0x00, 0x00, 0x04 // 4-byte promised stream identifier + 0x00, 0x00, 0x05, // 3-byte payload length (5 bytes) + 0x05, // 1-byte frame type (PUSH_PROMISE) + 0x0c, // 1-byte flags (PADDED, END_HEADERS) + 0x00, 0x00, 0x00, 0x03, // 4-byte stream identifier + 0x00, // 1-byte padding length (0) + 0x00, 0x00, 0x00, 0x04, // 4-byte promised stream identifier ] - let expectedFrame = HTTP2Frame(streamID: HTTP2StreamID(3), - payload: .pushPromise(.init(pushedStreamID: 4, headers: [:], paddingBytes: 0))) + let expectedFrame = HTTP2Frame( + streamID: HTTP2StreamID(3), + payload: .pushPromise(.init(pushedStreamID: 4, headers: [:], paddingBytes: 0)) + ) let buf = self.allocator.buffer(bytes: frameBytes) try assertReadsFrame(from: buf, matching: expectedFrame) @@ -1413,21 +1641,23 @@ class HTTP2FrameParserTests: XCTestCase { func testPushPromiseAndContinuationFrameDecodingWithZeroLengthPaddingOnly() throws { let frameBytes: [UInt8] = [ // PUSH_PROMISE - 0x00, 0x00, 0x05, // 3-byte payload length (5 bytes) - 0x05, // 1-byte frame type (PUSH_PROMISE) - 0x08, // 1-byte flags (PADDED) - 0x00, 0x00, 0x00, 0x03, // 4-byte stream identifier (3) - 0x00, // 1-byte padding length (0) - 0x00, 0x00, 0x00, 0x04, // 4-byte promised stream identifier (4) + 0x00, 0x00, 0x05, // 3-byte payload length (5 bytes) + 0x05, // 1-byte frame type (PUSH_PROMISE) + 0x08, // 1-byte flags (PADDED) + 0x00, 0x00, 0x00, 0x03, // 4-byte stream identifier (3) + 0x00, // 1-byte padding length (0) + 0x00, 0x00, 0x00, 0x04, // 4-byte promised stream identifier (4) // CONTINUATION - 0x00, 0x00, 0x00, // 3-byte payload length (0 bytes) - 0x09, // 1-byte frame type (CONTINUATION) - 0x04, // 1-byte flags (END_HEADERS) - 0x00, 0x00, 0x00, 0x03 // 4-byte stream identifier (3) + 0x00, 0x00, 0x00, // 3-byte payload length (0 bytes) + 0x09, // 1-byte frame type (CONTINUATION) + 0x04, // 1-byte flags (END_HEADERS) + 0x00, 0x00, 0x00, 0x03, // 4-byte stream identifier (3) ] - let expectedFrame = HTTP2Frame(streamID: HTTP2StreamID(3), - payload: .pushPromise(.init(pushedStreamID: 4, headers: [:], paddingBytes: 0))) + let expectedFrame = HTTP2Frame( + streamID: HTTP2StreamID(3), + payload: .pushPromise(.init(pushedStreamID: 4, headers: [:], paddingBytes: 0)) + ) let buf = byteBuffer(withBytes: frameBytes) try assertReadsFrame(from: buf, matching: expectedFrame) @@ -1435,10 +1665,10 @@ class HTTP2FrameParserTests: XCTestCase { func testPushPromiseFrameDecodingWithZeroLengthAndPaddingFlagSet() throws { let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x00, // 3-byte payload length (0 bytes) - 0x05, // 1-byte frame type (PUSH_PROMISE) - 0x08, // 1-byte flags (PADDED) - 0x00, 0x00, 0x00, 0x03, // 4-byte stream identifier + 0x00, 0x00, 0x00, // 3-byte payload length (0 bytes) + 0x05, // 1-byte frame type (PUSH_PROMISE) + 0x08, // 1-byte flags (PADDED) + 0x00, 0x00, 0x00, 0x03, // 4-byte stream identifier ] let buffer = self.allocator.buffer(bytes: frameBytes) @@ -1449,22 +1679,26 @@ class HTTP2FrameParserTests: XCTestCase { ) decoder.append(bytes: buffer) - XCTAssertThrowsError(try decoder.nextFrame(), "Should throw a protocol error", { err in - guard let connErr = err as? InternalError, case .codecError(code: .protocolError) = connErr else { - XCTFail("Should have thrown a codec error of type PROTOCOL_ERROR") - return + XCTAssertThrowsError( + try decoder.nextFrame(), + "Should throw a protocol error", + { err in + guard let connErr = err as? InternalError, case .codecError(code: .protocolError) = connErr else { + XCTFail("Should have thrown a codec error of type PROTOCOL_ERROR") + return + } } - }) + ) } func testPushPromiseFrameDecodingWithNotEnoughPaddingBytes() throws { let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x05, // 3-byte payload length (5 bytes) - 0x05, // 1-byte frame type (PUSH_PROMISE) - 0x0c, // 1-byte flags (PADDED, END_HEADERS) - 0x00, 0x00, 0x00, 0x03, // 4-byte stream identifier - 0x01, // 1-byte padding length (1) - 0x00, 0x00, 0x00, 0x04, // 4-byte promised stream identifier + 0x00, 0x00, 0x05, // 3-byte payload length (5 bytes) + 0x05, // 1-byte frame type (PUSH_PROMISE) + 0x0c, // 1-byte flags (PADDED, END_HEADERS) + 0x00, 0x00, 0x00, 0x03, // 4-byte stream identifier + 0x01, // 1-byte padding length (1) + 0x00, 0x00, 0x00, 0x04, // 4-byte promised stream identifier ] let buffer = self.allocator.buffer(bytes: frameBytes) @@ -1475,59 +1709,63 @@ class HTTP2FrameParserTests: XCTestCase { ) decoder.append(bytes: buffer) - XCTAssertThrowsError(try decoder.nextFrame(), "Should throw a frame size error", { err in - guard let connErr = err as? InternalError, case .codecError(code: .frameSizeError) = connErr else { - XCTFail("Should have thrown a codec error of type FRAME_SIZE_ERROR") - return + XCTAssertThrowsError( + try decoder.nextFrame(), + "Should throw a frame size error", + { err in + guard let connErr = err as? InternalError, case .codecError(code: .frameSizeError) = connErr else { + XCTFail("Should have thrown a codec error of type FRAME_SIZE_ERROR") + return + } } - }) + ) } // MARK: - PING frames func testPingFrameDecoding() throws { - let pingData = HTTP2PingData(withTuple: (0,1,2,3,4,5,6,7)) + let pingData = HTTP2PingData(withTuple: (0, 1, 2, 3, 4, 5, 6, 7)) let expectedFrame = HTTP2Frame(streamID: .rootStream, payload: .ping(pingData, ack: false)) let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x08, // 3-byte payload length (8 bytes) - 0x06, // 1-byte frame type (PING) - 0x00, // 1-byte flags (none) - 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier, - + 0x00, 0x00, 0x08, // 3-byte payload length (8 bytes) + 0x06, // 1-byte frame type (PING) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier, + // PING payload, 8 bytes 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, ] let buf = byteBuffer(withBytes: frameBytes) - + try self.assertReadsFrame(from: buf, matching: expectedFrame) } - + func testPingAckFrameDecoding() throws { - let pingData = HTTP2PingData(withTuple: (0,1,2,3,4,5,6,7)) + let pingData = HTTP2PingData(withTuple: (0, 1, 2, 3, 4, 5, 6, 7)) let expectedFrame = HTTP2Frame(streamID: .rootStream, payload: .ping(pingData, ack: true)) let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x08, // 3-byte payload length (8 bytes) - 0x06, // 1-byte frame type (PING) - 0x01, // 1-byte flags (ACK) - 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier, - + 0x00, 0x00, 0x08, // 3-byte payload length (8 bytes) + 0x06, // 1-byte frame type (PING) + 0x01, // 1-byte flags (ACK) + 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier, + // PING payload, 8 bytes 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, - ] + ] let buf = byteBuffer(withBytes: frameBytes) - + try self.assertReadsFrame(from: buf, matching: expectedFrame) } - + func testPingFrameDecodingFailure() { let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x08, // 3-byte payload length (8 bytes) - 0x06, // 1-byte frame type (PING) - 0x01, // 1-byte flags (ACK) - 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier, - + 0x00, 0x00, 0x08, // 3-byte payload length (8 bytes) + 0x06, // 1-byte frame type (PING) + 0x01, // 1-byte flags (ACK) + 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier, + // PING payload, 8 bytes 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, @@ -1542,112 +1780,122 @@ class HTTP2FrameParserTests: XCTestCase { // MUST NOT be associated with a stream. buf.setInteger(UInt8(1), at: 8) decoder.append(bytes: buf) - XCTAssertThrowsError(try decoder.nextFrame(), "Should throw a protocol error", { err in - guard let connErr = err as? InternalError, case .codecError(code: .protocolError) = connErr else { - XCTFail("Should have thrown a codec error of type PROTOCOL_ERROR") - return + XCTAssertThrowsError( + try decoder.nextFrame(), + "Should throw a protocol error", + { err in + guard let connErr = err as? InternalError, case .codecError(code: .protocolError) = connErr else { + XCTFail("Should have thrown a codec error of type PROTOCOL_ERROR") + return + } } - }) + ) buf.setInteger(UInt8(0), at: 8) buf.moveReaderIndex(to: 0) - + // length MUST be 8 octets buf.setInteger(UInt8(7), at: 2) decoder.append(bytes: buf) - XCTAssertThrowsError(try decoder.nextFrame(), "Should throw a frame size error", { err in - guard let connErr = err as? InternalError, case .codecError(code: .frameSizeError) = connErr else { - XCTFail("Should have thrown a codec error of type FRAME_SIZE_ERROR") - return + XCTAssertThrowsError( + try decoder.nextFrame(), + "Should throw a frame size error", + { err in + guard let connErr = err as? InternalError, case .codecError(code: .frameSizeError) = connErr else { + XCTFail("Should have thrown a codec error of type FRAME_SIZE_ERROR") + return + } } - }) + ) } - + func testPingFrameEncoding() throws { - let pingData = HTTP2PingData(withTuple: (0,1,2,3,4,5,6,7)) + let pingData = HTTP2PingData(withTuple: (0, 1, 2, 3, 4, 5, 6, 7)) let frame = HTTP2Frame(streamID: .rootStream, payload: .ping(pingData, ack: false)) var encoder = HTTP2FrameEncoder(allocator: self.allocator) - + let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x08, // 3-byte payload length (8 bytes) - 0x06, // 1-byte frame type (PING) - 0x00, // 1-byte flags (none) - 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier, - + 0x00, 0x00, 0x08, // 3-byte payload length (8 bytes) + 0x06, // 1-byte frame type (PING) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier, + // PING payload, 8 bytes 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, ] let expectedBufContent = self.byteBuffer(withBytes: frameBytes) var buf = self.allocator.buffer(capacity: expectedBufContent.readableBytes) - + let extraBuf = try encoder.encode(frame: frame, to: &buf) XCTAssertNil(extraBuf, "Should not return an extra buf") XCTAssertEqual(buf, expectedBufContent) } - + func testPingAckFrameEncoding() throws { - let pingData = HTTP2PingData(withTuple: (0,1,2,3,4,5,6,7)) + let pingData = HTTP2PingData(withTuple: (0, 1, 2, 3, 4, 5, 6, 7)) let frame = HTTP2Frame(streamID: .rootStream, payload: .ping(pingData, ack: true)) var encoder = HTTP2FrameEncoder(allocator: self.allocator) - + let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x08, // 3-byte payload length (8 bytes) - 0x06, // 1-byte frame type (PING) - 0x01, // 1-byte flags (ACK) - 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier, - + 0x00, 0x00, 0x08, // 3-byte payload length (8 bytes) + 0x06, // 1-byte frame type (PING) + 0x01, // 1-byte flags (ACK) + 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier, + // PING payload, 8 bytes 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, ] let expectedBufContent = self.byteBuffer(withBytes: frameBytes) var buf = self.allocator.buffer(capacity: expectedBufContent.readableBytes) - + let extraBuf = try encoder.encode(frame: frame, to: &buf) XCTAssertNil(extraBuf, "Should not return an extra buf") XCTAssertEqual(buf, expectedBufContent) } - + // MARK: - GOAWAY frame - + func testGoAwayFrameDecoding() throws { let dataBytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7] let lastStreamID = HTTP2StreamID(1) let opaqueData = self.byteBuffer(withBytes: dataBytes) - let expectedFrame = HTTP2Frame(streamID: .rootStream, - payload: .goAway(lastStreamID: lastStreamID, errorCode: .frameSizeError, opaqueData: opaqueData)) + let expectedFrame = HTTP2Frame( + streamID: .rootStream, + payload: .goAway(lastStreamID: lastStreamID, errorCode: .frameSizeError, opaqueData: opaqueData) + ) let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x10, // 3-byte payload length (16 bytes) - 0x07, // 1-byte frame type (GOAWAY) - 0x00, // 1-byte flags (none) - 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier, - 0x00, 0x00, 0x00, 0x01, // 4-byte last stream identifier, - 0x00, 0x00, 0x00, 0x06, // 4-byte error code - + 0x00, 0x00, 0x10, // 3-byte payload length (16 bytes) + 0x07, // 1-byte frame type (GOAWAY) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier, + 0x00, 0x00, 0x00, 0x01, // 4-byte last stream identifier, + 0x00, 0x00, 0x00, 0x06, // 4-byte error code + // opaque data (8 bytes) 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, ] let buf = byteBuffer(withBytes: frameBytes) - + try self.assertReadsFrame(from: buf, matching: expectedFrame) } - + func testGoAwayFrameDecodingFailure() { let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x10, // 3-byte payload length (16 bytes) - 0x07, // 1-byte frame type (GOAWAY) - 0x00, // 1-byte flags (none) - 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier, - 0x00, 0x00, 0x00, 0x01, // 4-byte last stream identifier, - 0x00, 0x00, 0x00, 0x06, // 4-byte error code - + 0x00, 0x00, 0x10, // 3-byte payload length (16 bytes) + 0x07, // 1-byte frame type (GOAWAY) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier, + 0x00, 0x00, 0x00, 0x01, // 4-byte last stream identifier, + 0x00, 0x00, 0x00, 0x06, // 4-byte error code + // opaque data (8 bytes) 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, ] var buf = byteBuffer(withBytes: frameBytes) - + var decoder = HTTP2FrameDecoder( allocator: self.allocator, expectClientMagic: false, @@ -1657,88 +1905,96 @@ class HTTP2FrameParserTests: XCTestCase { // MUST NOT be associated with a stream. buf.setInteger(UInt8(1), at: 8) decoder.append(bytes: buf) - XCTAssertThrowsError(try decoder.nextFrame(), "Should throw a protocol error", { err in - guard let connErr = err as? InternalError, case .codecError(code: .protocolError) = connErr else { - XCTFail("Should have thrown a codec error of type PROTOCOL_ERROR") - return + XCTAssertThrowsError( + try decoder.nextFrame(), + "Should throw a protocol error", + { err in + guard let connErr = err as? InternalError, case .codecError(code: .protocolError) = connErr else { + XCTFail("Should have thrown a codec error of type PROTOCOL_ERROR") + return + } } - }) + ) } - + func testGoAwayFrameEncodingWithOpaqueData() throws { let dataBytes: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7] let lastStreamID = HTTP2StreamID(1) let opaqueData = self.byteBuffer(withBytes: dataBytes) - let frame = HTTP2Frame(streamID: .rootStream, - payload: .goAway(lastStreamID: lastStreamID, errorCode: .frameSizeError, opaqueData: opaqueData)) + let frame = HTTP2Frame( + streamID: .rootStream, + payload: .goAway(lastStreamID: lastStreamID, errorCode: .frameSizeError, opaqueData: opaqueData) + ) var encoder = HTTP2FrameEncoder(allocator: self.allocator) - + let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x10, // 3-byte payload length (16 bytes) - 0x07, // 1-byte frame type (GOAWAY) - 0x00, // 1-byte flags (none) - 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier, - 0x00, 0x00, 0x00, 0x01, // 4-byte last stream identifier, - 0x00, 0x00, 0x00, 0x06, // 4-byte error code + 0x00, 0x00, 0x10, // 3-byte payload length (16 bytes) + 0x07, // 1-byte frame type (GOAWAY) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier, + 0x00, 0x00, 0x00, 0x01, // 4-byte last stream identifier, + 0x00, 0x00, 0x00, 0x06, // 4-byte error code ] let expectedBufContent = self.byteBuffer(withBytes: frameBytes) var buf = self.allocator.buffer(capacity: expectedBufContent.readableBytes) - + let extraBuf = try encoder.encode(frame: frame, to: &buf) XCTAssertNotNil(extraBuf, "Should return an extra buf") XCTAssertEqual(buf, expectedBufContent) XCTAssertEqual(extraBuf!, .byteBuffer(opaqueData)) } - + func testGoAwayFrameEncodingWithNoOpaqueData() throws { let lastStreamID = HTTP2StreamID(1) - let frame = HTTP2Frame(streamID: .rootStream, - payload: .goAway(lastStreamID: lastStreamID, errorCode: .frameSizeError, opaqueData: nil)) + let frame = HTTP2Frame( + streamID: .rootStream, + payload: .goAway(lastStreamID: lastStreamID, errorCode: .frameSizeError, opaqueData: nil) + ) var encoder = HTTP2FrameEncoder(allocator: self.allocator) - + let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x08, // 3-byte payload length (8 bytes) - 0x07, // 1-byte frame type (GOAWAY) - 0x00, // 1-byte flags (none) - 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier, - 0x00, 0x00, 0x00, 0x01, // 4-byte last stream identifier, - 0x00, 0x00, 0x00, 0x06, // 4-byte error code + 0x00, 0x00, 0x08, // 3-byte payload length (8 bytes) + 0x07, // 1-byte frame type (GOAWAY) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier, + 0x00, 0x00, 0x00, 0x01, // 4-byte last stream identifier, + 0x00, 0x00, 0x00, 0x06, // 4-byte error code ] let expectedBufContent = self.byteBuffer(withBytes: frameBytes) var buf = self.allocator.buffer(capacity: expectedBufContent.readableBytes) - + let extraBuf = try encoder.encode(frame: frame, to: &buf) XCTAssertNil(extraBuf, "Should not return an extra buf") XCTAssertEqual(buf, expectedBufContent) } - + // MARK: - WINDOW_UPDATE frame - + func testWindowUpdateFrameDecoding() throws { let expectedFrame = HTTP2Frame(streamID: 1, payload: .windowUpdate(windowSizeIncrement: 5)) - + let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x04, // 3-byte payload length (4 bytes) - 0x08, // 1-byte frame type (WINDOW_UPDATE) - 0x00, // 1-byte flags (none) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier - 0x00, 0x00, 0x00, 0x05, // window size adjustment + 0x00, 0x00, 0x04, // 3-byte payload length (4 bytes) + 0x08, // 1-byte frame type (WINDOW_UPDATE) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x00, 0x00, 0x00, 0x05, // window size adjustment ] let buf = byteBuffer(withBytes: frameBytes) - + try assertReadsFrame(from: buf, matching: expectedFrame) } - + func testWindowUpdateFrameDecodingFailure() { let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x04, // 3-byte payload length (4 bytes) - 0x08, // 1-byte frame type (WINDOW_UPDATE) - 0x00, // 1-byte flags (none) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier - 0x00, 0x00, 0x00, 0x05, // window size adjustment + 0x00, 0x00, 0x04, // 3-byte payload length (4 bytes) + 0x08, // 1-byte frame type (WINDOW_UPDATE) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x00, 0x00, 0x00, 0x05, // window size adjustment ] var buf = byteBuffer(withBytes: frameBytes) - + var decoder = HTTP2FrameDecoder( allocator: self.allocator, expectClientMagic: false, @@ -1747,54 +2003,60 @@ class HTTP2FrameParserTests: XCTestCase { // must have a size of 4 octets buf.setInteger(UInt8(5), at: 2) - buf.writeInteger(UInt8(0)) // append an extra byte so we read it all + buf.writeInteger(UInt8(0)) // append an extra byte so we read it all decoder.append(bytes: buf) - XCTAssertThrowsError(try decoder.nextFrame(), "Should throw a frame size error", { err in - guard let connErr = err as? InternalError, case .codecError(code: .frameSizeError) = connErr else { - XCTFail("Should have thrown a codec error of type FRAME_SIZE_ERROR") - return + XCTAssertThrowsError( + try decoder.nextFrame(), + "Should throw a frame size error", + { err in + guard let connErr = err as? InternalError, case .codecError(code: .frameSizeError) = connErr else { + XCTFail("Should have thrown a codec error of type FRAME_SIZE_ERROR") + return + } } - }) + ) } - + func testWindowUpdateFrameEncoding() throws { let streamID = HTTP2StreamID(1) let frame = HTTP2Frame(streamID: streamID, payload: .windowUpdate(windowSizeIncrement: 5)) var encoder = HTTP2FrameEncoder(allocator: self.allocator) - + let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x04, // 3-byte payload length (4 bytes) - 0x08, // 1-byte frame type (WINDOW_UPDATE) - 0x00, // 1-byte flags (none) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier - 0x00, 0x00, 0x00, 0x05, // window size adjustment + 0x00, 0x00, 0x04, // 3-byte payload length (4 bytes) + 0x08, // 1-byte frame type (WINDOW_UPDATE) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x00, 0x00, 0x00, 0x05, // window size adjustment ] let expectedBufContent = byteBuffer(withBytes: frameBytes) var buf = self.allocator.buffer(capacity: expectedBufContent.readableBytes) - + let extraBuf = try encoder.encode(frame: frame, to: &buf) XCTAssertNil(extraBuf, "Should not have returned extra buf") XCTAssertEqual(buf, expectedBufContent) } - + // MARK: - CONTINUATION frames - + func testHeadersContinuationFrameDecoding() throws { - let expectedFrame = HTTP2Frame(streamID: HTTP2StreamID(1), - payload: .headers(.init(headers: self.simpleHeaders))) - + let expectedFrame = HTTP2Frame( + streamID: HTTP2StreamID(1), + payload: .headers(.init(headers: self.simpleHeaders)) + ) + var headers2 = self.byteBuffer(withBytes: self.simpleHeadersEncoded) var headers1 = headers2.readSlice(length: 10)! - + let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x0a, // 3-byte payload length (10 bytes) - 0x01, // 1-byte frame type (HEADERS) - 0x00, // 1-byte flags (none) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x00, 0x00, 0x0a, // 3-byte payload length (10 bytes) + 0x01, // 1-byte frame type (HEADERS) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier ] var buf = byteBuffer(withBytes: frameBytes, extraCapacity: 10) buf.writeBuffer(&headers1) - + var decoder = HTTP2FrameDecoder( allocator: self.allocator, expectClientMagic: false, @@ -1804,44 +2066,46 @@ class HTTP2FrameParserTests: XCTestCase { // should return nothing thus far and wait for CONTINUATION frames and an END_HEADERS flag decoder.append(bytes: buf) XCTAssertNil(try decoder.nextFrame()) - + buf.clear() - + let continuationFrameBytes: [UInt8] = [ - 0x00, 0x00, 0x07, // 3-byte payload length (7 bytes) - 0x09, // 1-byte frame type (CONTINUATION) - 0x04, // 1-byte flags (END_HEADERS) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x00, 0x00, 0x07, // 3-byte payload length (7 bytes) + 0x09, // 1-byte frame type (CONTINUATION) + 0x04, // 1-byte flags (END_HEADERS) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier ] buf.writeBytes(continuationFrameBytes) buf.writeBuffer(&headers2) - + // This should now yield a HEADERS frame containing the complete set of headers decoder.append(bytes: buf) let frame: HTTP2Frame! = try decoder.nextFrame()?.0 XCTAssertNotNil(frame) - + self.assertEqualFrames(frame, expectedFrame) } - + func testPushPromiseContinuationFrameDecoding() throws { let streamID = HTTP2StreamID(3) - let expectedFrame = HTTP2Frame(streamID: HTTP2StreamID(1), - payload: .pushPromise(.init(pushedStreamID: streamID, headers: self.simpleHeaders))) - + let expectedFrame = HTTP2Frame( + streamID: HTTP2StreamID(1), + payload: .pushPromise(.init(pushedStreamID: streamID, headers: self.simpleHeaders)) + ) + var headers2 = self.byteBuffer(withBytes: self.simpleHeadersEncoded) var headers1 = headers2.readSlice(length: 10)! - + let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x0e, // 3-byte payload length (14 bytes) - 0x05, // 1-byte frame type (PUSH_PROMISE) - 0x00, // 1-byte flags (none) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier - 0x00, 0x00, 0x00, 0x03, // 4-byte promised stream id + 0x00, 0x00, 0x0e, // 3-byte payload length (14 bytes) + 0x05, // 1-byte frame type (PUSH_PROMISE) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x00, 0x00, 0x00, 0x03, // 4-byte promised stream id ] var buf = byteBuffer(withBytes: frameBytes, extraCapacity: 10) buf.writeBuffer(&headers1) - + var decoder = HTTP2FrameDecoder( allocator: self.allocator, expectClientMagic: false, @@ -1851,23 +2115,23 @@ class HTTP2FrameParserTests: XCTestCase { // should return nothing thus far and wait for CONTINUATION frames and an END_HEADERS flag decoder.append(bytes: buf) XCTAssertNil(try decoder.nextFrame()) - + buf.clear() - + let continuationFrameBytes: [UInt8] = [ - 0x00, 0x00, 0x07, // 3-byte payload length (7 bytes) - 0x09, // 1-byte frame type (CONTINUATION) - 0x04, // 1-byte flags (END_HEADERS) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x00, 0x00, 0x07, // 3-byte payload length (7 bytes) + 0x09, // 1-byte frame type (CONTINUATION) + 0x04, // 1-byte flags (END_HEADERS) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier ] buf.writeBytes(continuationFrameBytes) buf.writeBuffer(&headers2) - + // This should now yield a HEADERS frame containing the complete set of headers decoder.append(bytes: buf) let frame: HTTP2Frame! = try decoder.nextFrame()?.0 XCTAssertNotNil(frame) - + self.assertEqualFrames(frame, expectedFrame) } @@ -1875,10 +2139,10 @@ class HTTP2FrameParserTests: XCTestCase { var headers = self.byteBuffer(withBytes: self.simpleHeadersEncoded) let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x0a, // 3-byte payload length (17 bytes) - 0x09, // 1-byte frame type (CONTINUATION) - 0x00, // 1-byte flags (none) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x00, 0x00, 0x0a, // 3-byte payload length (17 bytes) + 0x09, // 1-byte frame type (CONTINUATION) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier ] var buf = byteBuffer(withBytes: frameBytes, extraCapacity: 10) buf.writeBuffer(&headers) @@ -1901,10 +2165,10 @@ class HTTP2FrameParserTests: XCTestCase { var headers1 = headers2.readSlice(length: 10)! let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x0a, // 3-byte payload length (10 bytes) - 0x01, // 1-byte frame type (HEADERS) - 0x00, // 1-byte flags (none) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x00, 0x00, 0x0a, // 3-byte payload length (10 bytes) + 0x01, // 1-byte frame type (HEADERS) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier ] var buf = byteBuffer(withBytes: frameBytes, extraCapacity: 10) buf.writeBuffer(&headers1) @@ -1922,10 +2186,10 @@ class HTTP2FrameParserTests: XCTestCase { buf.clear() let continuationFrameBytes: [UInt8] = [ - 0x00, 0x00, 0x07, // 3-byte payload length (7 bytes) - 0x09, // 1-byte frame type (CONTINUATION) - 0x04, // 1-byte flags (END_HEADERS) - 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier, stream 0 + 0x00, 0x00, 0x07, // 3-byte payload length (7 bytes) + 0x09, // 1-byte frame type (CONTINUATION) + 0x04, // 1-byte flags (END_HEADERS) + 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier, stream 0 ] buf.writeBytes(continuationFrameBytes) buf.writeBuffer(&headers2) @@ -1942,10 +2206,10 @@ class HTTP2FrameParserTests: XCTestCase { var headers1 = headers2.readSlice(length: 10)! let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x0a, // 3-byte payload length (10 bytes) - 0x01, // 1-byte frame type (HEADERS) - 0x00, // 1-byte flags (none) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x00, 0x00, 0x0a, // 3-byte payload length (10 bytes) + 0x01, // 1-byte frame type (HEADERS) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier ] var buf = byteBuffer(withBytes: frameBytes, extraCapacity: 10) buf.writeBuffer(&headers1) @@ -1963,10 +2227,10 @@ class HTTP2FrameParserTests: XCTestCase { buf.clear() let continuationFrameBytes: [UInt8] = [ - 0x00, 0x00, 0x07, // 3-byte payload length (7 bytes) - 0x09, // 1-byte frame type (CONTINUATION) - 0x04, // 1-byte flags (END_HEADERS) - 0x00, 0x00, 0x00, 0x03, // 4-byte stream identifier, stream 3 + 0x00, 0x00, 0x07, // 3-byte payload length (7 bytes) + 0x09, // 1-byte frame type (CONTINUATION) + 0x04, // 1-byte flags (END_HEADERS) + 0x00, 0x00, 0x00, 0x03, // 4-byte stream identifier, stream 3 ] buf.writeBytes(continuationFrameBytes) buf.writeBuffer(&headers2) @@ -1979,18 +2243,20 @@ class HTTP2FrameParserTests: XCTestCase { } func testHeadersContinuationFrameDecodingWithPadding() throws { - let expectedFrame = HTTP2Frame(streamID: HTTP2StreamID(1), - payload: .headers(.init(headers: self.simpleHeaders, paddingBytes: 2))) + let expectedFrame = HTTP2Frame( + streamID: HTTP2StreamID(1), + payload: .headers(.init(headers: self.simpleHeaders, paddingBytes: 2)) + ) var headers2 = self.byteBuffer(withBytes: self.simpleHeadersEncoded) var headers1 = headers2.readSlice(length: 10)! let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x0d, // 3-byte payload length (13 bytes) - 0x01, // 1-byte frame type (HEADERS) - 0x08, // 1-byte flags (PADDED) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier - 0x02 // Pad length (2 bytes) + 0x00, 0x00, 0x0d, // 3-byte payload length (13 bytes) + 0x01, // 1-byte frame type (HEADERS) + 0x08, // 1-byte flags (PADDED) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x02, // Pad length (2 bytes) ] var buf = byteBuffer(withBytes: frameBytes, extraCapacity: 12) buf.writeBuffer(&headers1) @@ -2009,10 +2275,10 @@ class HTTP2FrameParserTests: XCTestCase { buf.clear() let continuationFrameBytes: [UInt8] = [ - 0x00, 0x00, 0x07, // 3-byte payload length (7 bytes) - 0x09, // 1-byte frame type (CONTINUATION) - 0x04, // 1-byte flags (END_HEADERS) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x00, 0x00, 0x07, // 3-byte payload length (7 bytes) + 0x09, // 1-byte frame type (CONTINUATION) + 0x04, // 1-byte flags (END_HEADERS) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier ] buf.writeBytes(continuationFrameBytes) buf.writeBuffer(&headers2) @@ -2027,19 +2293,21 @@ class HTTP2FrameParserTests: XCTestCase { func testPushPromiseContinuationFrameDecodingWithPadding() throws { let streamID = HTTP2StreamID(3) - let expectedFrame = HTTP2Frame(streamID: HTTP2StreamID(1), - payload: .pushPromise(.init(pushedStreamID: streamID, headers: self.simpleHeaders, paddingBytes: 5))) + let expectedFrame = HTTP2Frame( + streamID: HTTP2StreamID(1), + payload: .pushPromise(.init(pushedStreamID: streamID, headers: self.simpleHeaders, paddingBytes: 5)) + ) var headers2 = self.byteBuffer(withBytes: self.simpleHeadersEncoded) var headers1 = headers2.readSlice(length: 10)! let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x14, // 3-byte payload length (20 bytes) - 0x05, // 1-byte frame type (PUSH_PROMISE) - 0x08, // 1-byte flags (PADDED) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier - 0x05, // Pad length (5 bytes) - 0x00, 0x00, 0x00, 0x03, // 4-byte promised stream id + 0x00, 0x00, 0x14, // 3-byte payload length (20 bytes) + 0x05, // 1-byte frame type (PUSH_PROMISE) + 0x08, // 1-byte flags (PADDED) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x05, // Pad length (5 bytes) + 0x00, 0x00, 0x00, 0x03, // 4-byte promised stream id ] var buf = byteBuffer(withBytes: frameBytes, extraCapacity: 15) buf.writeBuffer(&headers1) @@ -2058,10 +2326,10 @@ class HTTP2FrameParserTests: XCTestCase { buf.clear() let continuationFrameBytes: [UInt8] = [ - 0x00, 0x00, 0x07, // 3-byte payload length (7 bytes) - 0x09, // 1-byte frame type (CONTINUATION) - 0x04, // 1-byte flags (END_HEADERS) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x00, 0x00, 0x07, // 3-byte payload length (7 bytes) + 0x09, // 1-byte frame type (CONTINUATION) + 0x04, // 1-byte flags (END_HEADERS) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier ] buf.writeBytes(continuationFrameBytes) buf.writeBuffer(&headers2) @@ -2077,31 +2345,31 @@ class HTTP2FrameParserTests: XCTestCase { func testMaximumSequentialContinuationFrames() throws { let continuationBytes: [UInt8] = [ // CONTINUATION frame with the END_HEADERS flag not set - 0x00, 0x00, 0x00, // 3-byte payload length (0 bytes) - 0x09, // 1-byte frame type (CONTINUATION) - 0x00, // 1-byte flags (none) - 0x00, 0x00, 0x00, 0x03, // 4-byte stream identifier + 0x00, 0x00, 0x00, // 3-byte payload length (0 bytes) + 0x09, // 1-byte frame type (CONTINUATION) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x03, // 4-byte stream identifier ] var frameBytes: [UInt8] = [ // HEADERS - 0x00, 0x00, 0x01, // 3-byte payload length (1 byte) - 0x01, // 1-byte frame type (HEADERS) - 0x08, // 1-byte flags (PADDED) - 0x00, 0x00, 0x00, 0x03, // 4-byte stream identifier - 0x00, // 1-byte padding length (0) + 0x00, 0x00, 0x01, // 3-byte payload length (1 byte) + 0x01, // 1-byte frame type (HEADERS) + 0x08, // 1-byte flags (PADDED) + 0x00, 0x00, 0x00, 0x03, // 4-byte stream identifier + 0x00, // 1-byte padding length (0) // CONTINUATION frame with the END_HEADERS flag set - 0x00, 0x00, 0x00, // 3-byte payload length (0 bytes) - 0x09, // 1-byte frame type (CONTINUATION) - 0x04, // 1-byte flags (END_HEADERS) - 0x00, 0x00, 0x00, 0x03 // 4-byte stream identifier + 0x00, 0x00, 0x00, // 3-byte payload length (0 bytes) + 0x09, // 1-byte frame type (CONTINUATION) + 0x04, // 1-byte flags (END_HEADERS) + 0x00, 0x00, 0x00, 0x03, // 4-byte stream identifier ] let excessContinuationFrames = 1 // Iteratively test that sequential CONTINUATION frames are received up to the configured // limit, after which an error should be thrown. - for numberOfContinuationFrames in 1 ... self.maximumSequentialContinuationFrames + excessContinuationFrames { + for numberOfContinuationFrames in 1...self.maximumSequentialContinuationFrames + excessContinuationFrames { let buf = byteBuffer(withBytes: frameBytes) var decoder = HTTP2FrameDecoder( @@ -2118,7 +2386,8 @@ class HTTP2FrameParserTests: XCTestCase { ) try assertReadsFrame(from: buf, matching: expectedFrame) } else { - XCTAssertThrowsError(try decoder.nextFrame(), "Should throw an 'Excessive CONTINUATION frames' error") { err in + XCTAssertThrowsError(try decoder.nextFrame(), "Should throw an 'Excessive CONTINUATION frames' error") { + err in XCTAssert(err is NIOHTTP2Errors.ExcessiveContinuationFrames) } } @@ -2130,46 +2399,48 @@ class HTTP2FrameParserTests: XCTestCase { } // MARK: - ALTSVC frames - + func testAltServiceFrameDecoding() throws { let origin = "apple.com" var field = self.allocator.buffer(capacity: 10) field.writeStaticString("h2=\":8000\"") - let expectedFrame = HTTP2Frame(streamID: .rootStream, - payload: .alternativeService(origin: origin, field: field)) - + let expectedFrame = HTTP2Frame( + streamID: .rootStream, + payload: .alternativeService(origin: origin, field: field) + ) + let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x15, // 3-byte payload length (21 bytes) - 0x0a, // 1-byte frame type (ALTSVC) - 0x00, // 1-byte flags (none) - 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier - 0x00, 0x09, // 2-byte origin size + 0x00, 0x00, 0x15, // 3-byte payload length (21 bytes) + 0x0a, // 1-byte frame type (ALTSVC) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier + 0x00, 0x09, // 2-byte origin size ] var buf = byteBuffer(withBytes: frameBytes) buf.writeString(origin) buf.writeBytes(field.readableBytesView) XCTAssertEqual(buf.readableBytes, 30) - + try assertReadsFrame(from: buf, matching: expectedFrame) } - + func testAltServiceFrameDecodingFailure() { let origin = "apple.com" var field = self.allocator.buffer(capacity: 10) field.writeStaticString("h2=\":8000\"") - + let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x15, // 3-byte payload length (21 bytes) - 0x0a, // 1-byte frame type (ALTSVC) - 0x00, // 1-byte flags (none) - 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier - 0x00, 0x09, // 2-byte origin size + 0x00, 0x00, 0x15, // 3-byte payload length (21 bytes) + 0x0a, // 1-byte frame type (ALTSVC) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier + 0x00, 0x09, // 2-byte origin size ] var buf = byteBuffer(withBytes: frameBytes) buf.writeString(origin) buf.writeBytes(field.readableBytesView) XCTAssertEqual(buf.readableBytes, 30) - + var decoder = HTTP2FrameDecoder( allocator: self.allocator, expectClientMagic: false, @@ -2180,38 +2451,38 @@ class HTTP2FrameParserTests: XCTestCase { buf.setInteger(UInt8(1), at: 8) decoder.append(bytes: buf) XCTAssertNil(try decoder.nextFrame()) - + buf.moveReaderIndex(to: 0) buf.setInteger(UInt8(0), at: 8) - + // must have origin on non-root stream buf.moveWriterIndex(to: 9) buf.writeInteger(UInt16(0)) buf.writeBytes(field.readableBytesView) - + decoder.append(bytes: buf) XCTAssertNil(try decoder.nextFrame()) } - + func testAltServiceFrameEncoding() throws { let origin = "apple.com" var field = self.allocator.buffer(capacity: 10) field.writeStaticString("h2=\":8000\"") let frame = HTTP2Frame(streamID: .rootStream, payload: .alternativeService(origin: origin, field: field)) var encoder = HTTP2FrameEncoder(allocator: self.allocator) - + let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x15, // 3-byte payload length (21 bytes) - 0x0a, // 1-byte frame type (ALTSVC) - 0x00, // 1-byte flags (none) - 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier, - 0x00, 0x09, // 2-byte origin length + 0x00, 0x00, 0x15, // 3-byte payload length (21 bytes) + 0x0a, // 1-byte frame type (ALTSVC) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier, + 0x00, 0x09, // 2-byte origin length ] var expectedBufContent = self.byteBuffer(withBytes: frameBytes) expectedBufContent.writeString(origin) - + var buf = self.allocator.buffer(capacity: expectedBufContent.readableBytes) - + let extraBuf = try encoder.encode(frame: frame, to: &buf) XCTAssertNotNil(extraBuf, "Should return encoded field as separate buffer") XCTAssertEqual(buf, expectedBufContent) @@ -2220,11 +2491,11 @@ class HTTP2FrameParserTests: XCTestCase { func testAltServiceFrameDecodingLengthTooShort() throws { let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x02, // 3-byte payload length (2 bytes) - 0x0a, // 1-byte frame type (ALTSVC) - 0x00, // 1-byte flags (none) - 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier - 0x00, 0x09, // 2-byte origin length + 0x00, 0x00, 0x02, // 3-byte payload length (2 bytes) + 0x0a, // 1-byte frame type (ALTSVC) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier + 0x00, 0x09, // 2-byte origin length ] let buffer = self.allocator.buffer(bytes: frameBytes) var decoder = HTTP2FrameDecoder( @@ -2241,18 +2512,18 @@ class HTTP2FrameParserTests: XCTestCase { } } } - + // MARK: - ORIGIN frame - + func testOriginFrameDecoding() throws { let origins = ["apple.com", "www.apple.com", "www2.apple.com"] let expectedFrame = HTTP2Frame(streamID: .rootStream, payload: .origin(origins)) - + let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x2a, // 3-byte payload length (42 bytes) - 0x0c, // 1-byte frame type (ORIGIN) - 0x00, // 1-byte flags (none) - 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier + 0x00, 0x00, 0x2a, // 3-byte payload length (42 bytes) + 0x0c, // 1-byte frame type (ORIGIN) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier ] var buf = byteBuffer(withBytes: frameBytes) for origin in origins { @@ -2261,18 +2532,18 @@ class HTTP2FrameParserTests: XCTestCase { buf.writeBytes(u) } XCTAssertEqual(buf.readableBytes, 51) - + try assertReadsFrame(from: buf, matching: expectedFrame) } - + func testOriginFrameDecodingFailure() { let origins = ["apple.com", "www.apple.com", "www2.apple.com"] - + let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x2a, // 3-byte payload length (42 bytes) - 0x0c, // 1-byte frame type (ORIGIN) - 0x00, // 1-byte flags (none) - 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier + 0x00, 0x00, 0x2a, // 3-byte payload length (42 bytes) + 0x0c, // 1-byte frame type (ORIGIN) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier ] var buf = byteBuffer(withBytes: frameBytes) for origin in origins { @@ -2281,7 +2552,7 @@ class HTTP2FrameParserTests: XCTestCase { buf.writeBytes(u) } XCTAssertEqual(buf.readableBytes, 51) - + var decoder = HTTP2FrameDecoder( allocator: self.allocator, expectClientMagic: false, @@ -2292,31 +2563,35 @@ class HTTP2FrameParserTests: XCTestCase { buf.setInteger(UInt8(1), at: 8) decoder.append(bytes: buf) XCTAssertNil(try decoder.nextFrame()) - + buf.moveReaderIndex(to: 0) buf.setInteger(UInt8(0), at: 8) - + // should throw frame size error if string length exceeds payload size - buf.setInteger(UInt8(255), at: 9) // really big string length! + buf.setInteger(UInt8(255), at: 9) // really big string length! decoder.append(bytes: buf) - XCTAssertThrowsError(try decoder.nextFrame(), "Should throw a frame size error", { err in - guard let connErr = err as? InternalError, case .codecError(code: .frameSizeError) = connErr else { - XCTFail("Should have thrown a codec error of type FRAME_SIZE_ERROR") - return + XCTAssertThrowsError( + try decoder.nextFrame(), + "Should throw a frame size error", + { err in + guard let connErr = err as? InternalError, case .codecError(code: .frameSizeError) = connErr else { + XCTFail("Should have thrown a codec error of type FRAME_SIZE_ERROR") + return + } } - }) + ) } - + func testOriginFrameEncoding() throws { let origins = ["apple.com", "www.apple.com", "www2.apple.com"] let frame = HTTP2Frame(streamID: .rootStream, payload: .origin(origins)) var encoder = HTTP2FrameEncoder(allocator: self.allocator) - + let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x2a, // 3-byte payload length (42 bytes) - 0x0c, // 1-byte frame type (ORIGIN) - 0x00, // 1-byte flags (none) - 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier, + 0x00, 0x00, 0x2a, // 3-byte payload length (42 bytes) + 0x0c, // 1-byte frame type (ORIGIN) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier, ] var expectedBufContent = self.byteBuffer(withBytes: frameBytes) for origin in origins { @@ -2324,53 +2599,55 @@ class HTTP2FrameParserTests: XCTestCase { expectedBufContent.writeInteger(UInt16(u.count)) expectedBufContent.writeBytes(u) } - + var buf = self.allocator.buffer(capacity: expectedBufContent.readableBytes) - + let extraBuf = try encoder.encode(frame: frame, to: &buf) XCTAssertNil(extraBuf, "Should return no extra buffer") XCTAssertEqual(buf, expectedBufContent) } - + // MARK: - Multi-Frame Buffers - + func testHeaderAndContinuationsInOneBuffer() throws { - let expectedFrame = HTTP2Frame(streamID: HTTP2StreamID(1), - payload: .headers(.init(headers: self.simpleHeaders))) - + let expectedFrame = HTTP2Frame( + streamID: HTTP2StreamID(1), + payload: .headers(.init(headers: self.simpleHeaders)) + ) + // Break into four chunks var allHeaderBytes = self.byteBuffer(withBytes: self.simpleHeadersEncoded) var headers1 = allHeaderBytes.readSlice(length: 4)! var headers2 = allHeaderBytes.readSlice(length: 4)! var headers3 = allHeaderBytes.readSlice(length: 4)! - var headers4 = allHeaderBytes // any remaining bytes - + var headers4 = allHeaderBytes // any remaining bytes + let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x04, // 3-byte payload length (4 bytes) - 0x01, // 1-byte frame type (HEADERS) - 0x00, // 1-byte flags (none) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x00, 0x00, 0x04, // 3-byte payload length (4 bytes) + 0x01, // 1-byte frame type (HEADERS) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier ] var buf = byteBuffer(withBytes: frameBytes, extraCapacity: 10) buf.writeBuffer(&headers1) - + var continuationFrameBytes: [UInt8] = [ - 0x00, 0x00, 0x04, // 3-byte payload length (7 bytes) - 0x09, // 1-byte frame type (CONTINUATION) - 0x00, // 1-byte flags (none) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x00, 0x00, 0x04, // 3-byte payload length (7 bytes) + 0x09, // 1-byte frame type (CONTINUATION) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier ] buf.writeBytes(continuationFrameBytes) buf.writeBuffer(&headers2) - + buf.writeBytes(continuationFrameBytes) buf.writeBuffer(&headers3) - + continuationFrameBytes[2] = UInt8(headers4.readableBytes) continuationFrameBytes[4] = 0x04 // END_HEADERS buf.writeBytes(continuationFrameBytes) buf.writeBuffer(&headers4) - + // This should now yield a HEADERS frame containing the complete set of headers var decoder = HTTP2FrameDecoder( allocator: self.allocator, @@ -2380,48 +2657,50 @@ class HTTP2FrameParserTests: XCTestCase { decoder.append(bytes: buf) let frame: HTTP2Frame! = try decoder.nextFrame()?.0 XCTAssertNotNil(frame) - + self.assertEqualFrames(frame, expectedFrame) } - + func testPushPromiseAndContinuationsInOneBuffer() throws { - let expectedFrame = HTTP2Frame(streamID: HTTP2StreamID(1), - payload: .pushPromise(.init(pushedStreamID: HTTP2StreamID(3), headers: self.simpleHeaders))) - + let expectedFrame = HTTP2Frame( + streamID: HTTP2StreamID(1), + payload: .pushPromise(.init(pushedStreamID: HTTP2StreamID(3), headers: self.simpleHeaders)) + ) + // Break into four chunks var allHeaderBytes = self.byteBuffer(withBytes: self.simpleHeadersEncoded) var headers1 = allHeaderBytes.readSlice(length: 4)! var headers2 = allHeaderBytes.readSlice(length: 4)! var headers3 = allHeaderBytes.readSlice(length: 4)! - var headers4 = allHeaderBytes // any remaining bytes - + var headers4 = allHeaderBytes // any remaining bytes + let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x08, // 3-byte payload length (4 bytes) - 0x05, // 1-byte frame type (PUSH_PROMISE) - 0x00, // 1-byte flags (none) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier - 0x00, 0x00, 0x00, 0x03, // 4-byte promised stream identifier + 0x00, 0x00, 0x08, // 3-byte payload length (4 bytes) + 0x05, // 1-byte frame type (PUSH_PROMISE) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x00, 0x00, 0x00, 0x03, // 4-byte promised stream identifier ] - var buf = byteBuffer(withBytes: frameBytes, extraCapacity: 17 + 9*3) + var buf = byteBuffer(withBytes: frameBytes, extraCapacity: 17 + 9 * 3) buf.writeBuffer(&headers1) - + var continuationFrameBytes: [UInt8] = [ - 0x00, 0x00, 0x04, // 3-byte payload length (7 bytes) - 0x09, // 1-byte frame type (CONTINUATION) - 0x00, // 1-byte flags (none) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x00, 0x00, 0x04, // 3-byte payload length (7 bytes) + 0x09, // 1-byte frame type (CONTINUATION) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier ] buf.writeBytes(continuationFrameBytes) buf.writeBuffer(&headers2) - + buf.writeBytes(continuationFrameBytes) buf.writeBuffer(&headers3) - + continuationFrameBytes[2] = UInt8(headers4.readableBytes) continuationFrameBytes[4] = 0x04 // END_HEADERS buf.writeBytes(continuationFrameBytes) buf.writeBuffer(&headers4) - + // This should now yield a HEADERS frame containing the complete set of headers var decoder = HTTP2FrameDecoder( allocator: self.allocator, @@ -2431,94 +2710,102 @@ class HTTP2FrameParserTests: XCTestCase { decoder.append(bytes: buf) let frame: HTTP2Frame! = try decoder.nextFrame()?.0 XCTAssertNotNil(frame) - + self.assertEqualFrames(frame, expectedFrame) } - + func testMultipleFramesInOneBuffer() throws { // We are going to encode a single buffer containing a bunch of different frames. // We'll pretend to be the result of a server with a bad temper responding to a request. // It will send out a SETTINGS ACK, then HEADERS, CONTINUATION, DATA, and finally // (because it has a bad temper) GOAWAY. let settingsAckBytes: [UInt8] = [ - 0x00, 0x00, 0x00, // 3-byte payload length (0 bytes) - 0x04, // 1-byte frame type (SETTINGS) - 0x01, // 1-byte flags (ACK) - 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier + 0x00, 0x00, 0x00, // 3-byte payload length (0 bytes) + 0x04, // 1-byte frame type (SETTINGS) + 0x01, // 1-byte flags (ACK) + 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier ] - let headerFrameBytes: [UInt8] = [ - 0x00, 0x00, 0x0a, // 3-byte payload length (10 bytes) - 0x01, // 1-byte frame type (HEADERS) - 0x00, // 1-byte flags (none) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier - ] + self.simpleHeadersEncoded[0..<10] - let continuationFrameBytes: [UInt8] = [ - 0x00, 0x00, 0x07, // 3-byte payload length (7 bytes) - 0x09, // 1-byte frame type (CONTINUATION) - 0x04, // 1-byte flags (END_HEADERS) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier - ] + self.simpleHeadersEncoded[10...] + let headerFrameBytes: [UInt8] = + [ + 0x00, 0x00, 0x0a, // 3-byte payload length (10 bytes) + 0x01, // 1-byte frame type (HEADERS) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + ] + self.simpleHeadersEncoded[0..<10] + let continuationFrameBytes: [UInt8] = + [ + 0x00, 0x00, 0x07, // 3-byte payload length (7 bytes) + 0x09, // 1-byte frame type (CONTINUATION) + 0x04, // 1-byte flags (END_HEADERS) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + ] + self.simpleHeadersEncoded[10...] let dataFrameBytes: [UInt8] = [ - 0x00, 0x00, 0x08, // 3-byte payload length (8 bytes) - 0x00, // 1-byte frame type (DATA) - 0x01, // 1-byte flags (END_STREAM) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x00, 0x00, 0x08, // 3-byte payload length (8 bytes) + 0x00, // 1-byte frame type (DATA) + 0x01, // 1-byte flags (END_STREAM) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier // DATA payload 0x00, 0x01, 0x02, 0x03, - 0x04, 0x05, 0x06, 0x07 + 0x04, 0x05, 0x06, 0x07, ] let goawayFrameBytes: [UInt8] = [ - 0x00, 0x00, 0x10, // 3-byte payload length (16 bytes) - 0x07, // 1-byte frame type (GOAWAY) - 0x00, // 1-byte flags (none) - 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier, - 0x00, 0x00, 0x00, 0x01, // 4-byte last stream identifier, - 0x00, 0x00, 0x00, 0x00, // 4-byte error code (NO_ERROR) - + 0x00, 0x00, 0x10, // 3-byte payload length (16 bytes) + 0x07, // 1-byte frame type (GOAWAY) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier, + 0x00, 0x00, 0x00, 0x01, // 4-byte last stream identifier, + 0x00, 0x00, 0x00, 0x00, // 4-byte error code (NO_ERROR) + // opaque data (8 bytes) 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, ] - + var buf = self.allocator.buffer(capacity: 128) buf.writeBytes(settingsAckBytes) buf.writeBytes(headerFrameBytes) buf.writeBytes(continuationFrameBytes) buf.writeBytes(dataFrameBytes) buf.writeBytes(goawayFrameBytes) - + var dataBuf = self.allocator.buffer(capacity: 8) dataBuf.writeBytes(dataFrameBytes[9...]) - + let streamID = HTTP2StreamID(1) let settingsAckFrame = HTTP2Frame(streamID: .rootStream, payload: .settings(.ack)) let headersFrame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: self.simpleHeaders))) - let dataFrame = HTTP2Frame(streamID: streamID, payload: .data(.init(data: .byteBuffer(dataBuf), endStream: true))) - let goawayFrame = HTTP2Frame(streamID: .rootStream, payload: .goAway(lastStreamID: streamID, errorCode: .noError, opaqueData: dataBuf)) - + let dataFrame = HTTP2Frame( + streamID: streamID, + payload: .data(.init(data: .byteBuffer(dataBuf), endStream: true)) + ) + let goawayFrame = HTTP2Frame( + streamID: .rootStream, + payload: .goAway(lastStreamID: streamID, errorCode: .noError, opaqueData: dataBuf) + ) + var decoder = HTTP2FrameDecoder( allocator: self.allocator, expectClientMagic: false, maximumSequentialContinuationFrames: self.maximumSequentialContinuationFrames ) decoder.append(bytes: buf) - + let frame1 = try decoder.nextFrame()?.0 XCTAssertNotNil(frame1) self.assertEqualFrames(frame1!, settingsAckFrame) - + let frame2 = try decoder.nextFrame()?.0 XCTAssertNotNil(frame2) self.assertEqualFrames(frame2!, headersFrame) - + let frame3 = try decoder.nextFrame()?.0 XCTAssertNotNil(frame3) self.assertEqualFrames(frame3!, dataFrame) - + let frame4 = try decoder.nextFrame()?.0 XCTAssertNotNil(frame4) self.assertEqualFrames(frame4!, goawayFrame) - + let noFrame = try decoder.nextFrame()?.0 XCTAssertNil(noFrame) } @@ -2528,10 +2815,10 @@ class HTTP2FrameParserTests: XCTestCase { payload.writeBytes(repeatElement(UInt8(0), count: 2)) let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x02, // 3-byte payload length (2 bytes) - 0x00, // 1-byte frame type (DATA) - 0x00, // 0-byte flags - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x00, 0x00, 0x02, // 3-byte payload length (2 bytes) + 0x00, // 1-byte frame type (DATA) + 0x00, // 0-byte flags + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier ] var buf = byteBuffer(withBytes: frameBytes, extraCapacity: payload.readableBytes) buf.writeBytes(payload.readableBytesView) @@ -2562,17 +2849,17 @@ class HTTP2FrameParserTests: XCTestCase { // We're going to start by sending a grease frame, with a different frame right behind it. The // decoder should act as though the grease frame simply is not there. let greaseFrameBytes: [UInt8] = [ - 0x00, 0x00, 0x04, // 3-byte payload length (4 bytes) - 0x68, // 1-byte frame type (0x0b + 0x1f * 3) - 0x2B, // 1-byte flags (random byte) - 0x7D, 0x3F, 0x9F, 0x49, // 4-byte stream identifier (random bytes) - 0x97, 0xF2, 0x1D, 0x77 // 4-byte payload (random bytes) + 0x00, 0x00, 0x04, // 3-byte payload length (4 bytes) + 0x68, // 1-byte frame type (0x0b + 0x1f * 3) + 0x2B, // 1-byte flags (random byte) + 0x7D, 0x3F, 0x9F, 0x49, // 4-byte stream identifier (random bytes) + 0x97, 0xF2, 0x1D, 0x77, // 4-byte payload (random bytes) ] let frameBytes: [UInt8] = [ - 0x00, 0x00, 0x0d, // 3-byte payload length (13 bytes) - 0x00, // 1-byte frame type (DATA) - 0x01, // 1-byte flags (END_STREAM) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x00, 0x00, 0x0d, // 3-byte payload length (13 bytes) + 0x00, // 1-byte frame type (DATA) + 0x01, // 1-byte flags (END_STREAM) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier ] let payload = byteBuffer(withStaticString: "Hello, World!") @@ -2580,8 +2867,10 @@ class HTTP2FrameParserTests: XCTestCase { greaseBuf.writeBytes(frameBytes) greaseBuf.writeBytes(payload.readableBytesView) - let expectedFrame = HTTP2Frame(streamID: HTTP2StreamID(1), - payload: .data(.init(data: .byteBuffer(payload), endStream: true))) + let expectedFrame = HTTP2Frame( + streamID: HTTP2StreamID(1), + payload: .data(.init(data: .byteBuffer(payload), endStream: true)) + ) try assertReadsFrame(from: greaseBuf, matching: expectedFrame, expectedFlowControlledLength: 13) } diff --git a/Tests/NIOHTTP2Tests/HTTP2FramePayloadStreamMultiplexerTests.swift b/Tests/NIOHTTP2Tests/HTTP2FramePayloadStreamMultiplexerTests.swift index 802ada2..672b583 100644 --- a/Tests/NIOHTTP2Tests/HTTP2FramePayloadStreamMultiplexerTests.swift +++ b/Tests/NIOHTTP2Tests/HTTP2FramePayloadStreamMultiplexerTests.swift @@ -12,25 +12,30 @@ // //===----------------------------------------------------------------------===// -import XCTest import Atomics import NIOConcurrencyHelpers import NIOCore import NIOEmbedded import NIOHTTP1 -@testable import NIOHPACK // for HPACKHeaders initializers +import XCTest + +@testable import NIOHPACK // for HPACKHeaders initializers @testable import NIOHTTP2 -private extension Channel { +extension Channel { /// Adds a simple no-op `HTTP2StreamMultiplexer` to the pipeline. - func addNoOpMultiplexer(mode: NIOHTTP2Handler.ParserMode) { - XCTAssertNoThrow(try self.pipeline.addHandler(HTTP2StreamMultiplexer(mode: mode, channel: self) { channel in - self.eventLoop.makeSucceededFuture(()) - }).wait()) + fileprivate func addNoOpMultiplexer(mode: NIOHTTP2Handler.ParserMode) { + XCTAssertNoThrow( + try self.pipeline.addHandler( + HTTP2StreamMultiplexer(mode: mode, channel: self) { channel in + self.eventLoop.makeSucceededFuture(()) + } + ).wait() + ) } } -private struct MyError: Error { } +private struct MyError: Error {} /// A handler that asserts the frames received match the expected set. internal final class FramePayloadExpecter: ChannelInboundHandler { @@ -76,14 +81,21 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { } private func activateStream(_ streamID: HTTP2StreamID) { - let activated = NIOHTTP2StreamCreatedEvent(streamID: streamID, localInitialWindowSize: 16384, remoteInitialWindowSize: 16384) + let activated = NIOHTTP2StreamCreatedEvent( + streamID: streamID, + localInitialWindowSize: 16384, + remoteInitialWindowSize: 16384 + ) self.channel.pipeline.fireUserInboundEventTriggered(activated) } func testMultiplexerIgnoresFramesOnStream0() throws { self.channel.addNoOpMultiplexer(mode: .server) - let simplePingFrame = HTTP2Frame(streamID: .rootStream, payload: .ping(HTTP2PingData(withInteger: 5), ack: false)) + let simplePingFrame = HTTP2Frame( + streamID: .rootStream, + payload: .ping(HTTP2PingData(withInteger: 5), ack: false) + ) XCTAssertNoThrow(try self.channel.writeInbound(simplePingFrame)) XCTAssertNoThrow(try self.channel.assertReceivedFrame().assertFrameMatches(this: simplePingFrame)) @@ -111,7 +123,9 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { func testChannelsCloseThemselvesWhenToldTo() throws { let completedChannelCount = ManagedAtomic(0) let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel in - channel.closeFuture.whenSuccess { completedChannelCount.wrappingIncrement(ordering: .sequentiallyConsistent) } + channel.closeFuture.whenSuccess { + completedChannelCount.wrappingIncrement(ordering: .sequentiallyConsistent) + } return channel.eventLoop.makeSucceededFuture(()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) @@ -119,7 +133,10 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { // Let's send a bunch of headers frames with endStream on them. This should open some streams. let streamIDs = stride(from: 1, to: 100, by: 2).map { HTTP2StreamID($0) } for streamID in streamIDs { - let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders(), endStream: true))) + let frame = HTTP2Frame( + streamID: streamID, + payload: .headers(.init(headers: HPACKHeaders(), endStream: true)) + ) XCTAssertNoThrow(try self.channel.writeInbound(frame)) } XCTAssertEqual(completedChannelCount.load(ordering: .sequentiallyConsistent), 0) @@ -155,7 +172,9 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { closeError = error } } - return channel.pipeline.addHandler(FramePayloadExpecter(expectedPayload: [frame.payload, rstStreamFrame.payload])) + return channel.pipeline.addHandler( + FramePayloadExpecter(expectedPayload: [frame.payload, rstStreamFrame.payload]) + ) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) @@ -176,8 +195,10 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { // At this stage the stream should be closed with the appropriate error code. closeError.withLockedValue { closeError in - XCTAssertEqual(closeError as? NIOHTTP2Errors.StreamClosed, - NIOHTTP2Errors.streamClosed(streamID: streamID, errorCode: .cancel)) + XCTAssertEqual( + closeError as? NIOHTTP2Errors.StreamClosed, + NIOHTTP2Errors.streamClosed(streamID: streamID, errorCode: .cancel) + ) } XCTAssertNoThrow(try self.channel.finish()) } @@ -190,7 +211,10 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { // First, set up the frames we want to send/receive. let streamID = HTTP2StreamID(1) let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders(), endStream: true))) - let goAwayFrame = HTTP2Frame(streamID: .rootStream, payload: .goAway(lastStreamID: .rootStream, errorCode: .http11Required, opaqueData: nil)) + let goAwayFrame = HTTP2Frame( + streamID: .rootStream, + payload: .goAway(lastStreamID: .rootStream, errorCode: .http11Required, opaqueData: nil) + ) let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel in closeError.withLockedValue { closeError in @@ -223,8 +247,10 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { // At this stage the stream should be closed with the appropriate manufactured error code. closeError.withLockedValue { closeError in - XCTAssertEqual(closeError as? NIOHTTP2Errors.StreamClosed, - NIOHTTP2Errors.streamClosed(streamID: streamID, errorCode: .refusedStream)) + XCTAssertEqual( + closeError as? NIOHTTP2Errors.StreamClosed, + NIOHTTP2Errors.streamClosed(streamID: streamID, errorCode: .refusedStream) + ) } XCTAssertNoThrow(try self.channel.finish()) } @@ -274,7 +300,7 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { func testClosingIdleChannels() throws { let frameReceiver = FrameWriteRecorder() let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel in - return channel.close() + channel.close() } XCTAssertNoThrow(try self.channel.pipeline.addHandler(frameReceiver).wait()) XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) @@ -306,7 +332,6 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { XCTAssertNoThrow(try self.channel.pipeline.addHandler(frameReceiver).wait()) XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) - XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) // Let's send a headers frame to open the stream. @@ -337,7 +362,6 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { XCTAssertNoThrow(try self.channel.pipeline.addHandler(frameReceiver).wait()) XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) - XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) // Let's send a headers frame to open the stream. @@ -377,7 +401,6 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { XCTAssertNoThrow(try self.channel.pipeline.addHandler(frameReceiver).wait()) XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) - XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) // Let's send a headers frame to open the stream. @@ -463,7 +486,10 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { let userEvent = StreamClosedEvent(streamID: streamID, reason: .cancel) self.channel.pipeline.fireUserInboundEventTriggered(userEvent) closeError.withLockedValue { closeError in - XCTAssertEqual(closeError as? NIOHTTP2Errors.StreamClosed, NIOHTTP2Errors.streamClosed(streamID: streamID, errorCode: .cancel)) + XCTAssertEqual( + closeError as? NIOHTTP2Errors.StreamClosed, + NIOHTTP2Errors.streamClosed(streamID: streamID, errorCode: .cancel) + ) } XCTAssertNoThrow(try self.channel.finish()) @@ -480,7 +506,6 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) - XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) // Let's send a headers frame to open the stream. @@ -606,7 +631,10 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { let firstStreamID = HTTP2StreamID(1) let secondStreamID = HTTP2StreamID(3) for streamID in [firstStreamID, secondStreamID] { - let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders(), endStream: true))) + let frame = HTTP2Frame( + streamID: streamID, + payload: .headers(.init(headers: HPACKHeaders(), endStream: true)) + ) XCTAssertNoThrow(try self.channel.writeInbound(frame)) self.activateStream(streamID) } @@ -705,7 +733,10 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { self.channel.pipeline.fireUserInboundEventTriggered(userEvent) writeError.withLockedValue { writeError in - XCTAssertEqual(writeError as? NIOHTTP2Errors.StreamClosed, NIOHTTP2Errors.streamClosed(streamID: streamID, errorCode: .cancel)) + XCTAssertEqual( + writeError as? NIOHTTP2Errors.StreamClosed, + NIOHTTP2Errors.streamClosed(streamID: streamID, errorCode: .cancel) + ) } XCTAssertNoThrow(try self.channel.finish()) @@ -749,7 +780,8 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { func testReadPullsInAllFrames() throws { let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) let frameRecorder = InboundFramePayloadRecorder() - let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel -> EventLoopFuture in + let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { + channel -> EventLoopFuture in childChannelPromise.succeed(channel) // We're going to disable autoRead on this channel. @@ -767,7 +799,6 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) - XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) // Let's open a stream. @@ -812,7 +843,8 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { let autoRead = ManagedAtomic(false) let (channelsStream, channelsContinuation) = AsyncStream.makeStream(of: Channel.self) - let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel -> EventLoopFuture in + let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { + channel -> EventLoopFuture in channelsContinuation.yield(channel) // We'll disable auto read on the first channel only. let autoReadValue = autoRead.exchange(true, ordering: .sequentiallyConsistent) @@ -865,12 +897,13 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { func testReadWillCauseAutomaticFrameDelivery() throws { let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) let frameRecorder = InboundFramePayloadRecorder() - let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel -> EventLoopFuture in + let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { + channel -> EventLoopFuture in childChannelPromise.succeed(channel) // We're going to disable autoRead on this channel. return channel.setOption(ChannelOptions.autoRead, value: false).flatMap { - return channel.pipeline.addHandler(frameRecorder) + channel.pipeline.addHandler(frameRecorder) } } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) @@ -919,7 +952,8 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) let readCounter = ReadCounter() let frameRecorder = InboundFramePayloadRecorder() - let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel -> EventLoopFuture in + let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { + channel -> EventLoopFuture in childChannelPromise.succeed(channel) // We're going to disable autoRead on this channel. @@ -1004,10 +1038,12 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { func testHandlersAreRemovedOnClosure() throws { let handlerRemoved = ManagedAtomic(false) let handlerRemovedPromise: EventLoopPromise = self.channel.eventLoop.makePromise() - handlerRemovedPromise.futureResult.whenComplete { _ in handlerRemoved.store(true, ordering: .sequentiallyConsistent) } + handlerRemovedPromise.futureResult.whenComplete { _ in + handlerRemoved.store(true, ordering: .sequentiallyConsistent) + } let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel in - return channel.pipeline.addHandler(HandlerRemovedHandler(removedPromise: handlerRemovedPromise)) + channel.pipeline.addHandler(HandlerRemovedHandler(removedPromise: handlerRemovedPromise)) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) @@ -1034,10 +1070,12 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { func testHandlersAreRemovedOnClosureWithError() throws { let handlerRemoved = ManagedAtomic(false) let handlerRemovedPromise: EventLoopPromise = self.channel.eventLoop.makePromise() - handlerRemovedPromise.futureResult.whenComplete { _ in handlerRemoved.store(true, ordering: .sequentiallyConsistent) } + handlerRemovedPromise.futureResult.whenComplete { _ in + handlerRemoved.store(true, ordering: .sequentiallyConsistent) + } let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel in - return channel.pipeline.addHandler(HandlerRemovedHandler(removedPromise: handlerRemovedPromise)) + channel.pipeline.addHandler(HandlerRemovedHandler(removedPromise: handlerRemovedPromise)) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) @@ -1065,7 +1103,7 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { let configurePromise: EventLoopPromise = self.channel.eventLoop.makePromise() let createdChannelCount = ManagedAtomic(0) let configuredChannelCount = ManagedAtomic(0) - let streamIDs = NIOLockedValueBox(Array()) + let streamIDs = NIOLockedValueBox([HTTP2StreamID]()) let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel in XCTFail("Must not be called") return channel.eventLoop.makeFailedFuture(MyError()) @@ -1115,7 +1153,7 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { let configurePromise: EventLoopPromise = self.channel.eventLoop.makePromise() let createdChannelCount = ManagedAtomic(0) let configuredChannelCount = ManagedAtomic(0) - let streamIDs = NIOLockedValueBox(Array()) + let streamIDs = NIOLockedValueBox([HTTP2StreamID]()) let multiplexer = HTTP2StreamMultiplexer(mode: .client, channel: self.channel) { channel in XCTFail("Must not be called") return channel.eventLoop.makeFailedFuture(MyError()) @@ -1180,7 +1218,6 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { } (self.channel.eventLoop as! EmbeddedEventLoop).run() - let childChannel = try childChannelPromise.futureResult.wait() childChannel.writeAndFlush(HTTP2Frame.FramePayload.headers(.init(headers: HPACKHeaders())), promise: nil) @@ -1211,18 +1248,19 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { let childChannel = try childChannelPromise.futureResult.wait() let writeError = NIOLockedValueBox(nil) - childChannel.writeAndFlush(HTTP2Frame.FramePayload.headers(.init(headers: HPACKHeaders()))).whenFailure { error in - writeError.withLockedValue{ writeError in + childChannel.writeAndFlush(HTTP2Frame.FramePayload.headers(.init(headers: HPACKHeaders()))).whenFailure { + error in + writeError.withLockedValue { writeError in writeError = error } } - writeError.withLockedValue{ writeError in + writeError.withLockedValue { writeError in XCTAssertNil(writeError) } configurePromise.fail(MyError()) - writeError.withLockedValue{ writeError in + writeError.withLockedValue { writeError in XCTAssertNotNil(writeError) XCTAssertTrue(writeError is MyError) } @@ -1241,7 +1279,7 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { XCTAssertNoThrow(try self.channel.pipeline.addHandler(writeRecorder).wait()) XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) multiplexer.createStreamChannel(promise: nil) { channel in - return configurePromise.futureResult + configurePromise.futureResult } (self.channel.eventLoop as! EmbeddedEventLoop).run() @@ -1341,7 +1379,10 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { func testMultiplexerIgnoresPriorityFrames() throws { self.channel.addNoOpMultiplexer(mode: .server) - let simplePingFrame = HTTP2Frame(streamID: 106, payload: .priority(.init(exclusive: true, dependency: .rootStream, weight: 15))) + let simplePingFrame = HTTP2Frame( + streamID: 106, + payload: .priority(.init(exclusive: true, dependency: .rootStream, weight: 15)) + ) XCTAssertNoThrow(try self.channel.writeInbound(simplePingFrame)) XCTAssertNoThrow(try self.channel.assertReceivedFrame().assertFrameMatches(this: simplePingFrame)) @@ -1396,7 +1437,7 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { let channelPromise = self.channel.eventLoop.makePromise(of: Channel.self) multiplexer.createStreamChannel(promise: channelPromise) { channel in - return channel.eventLoop.makeSucceededFuture(()) + channel.eventLoop.makeSucceededFuture(()) } self.channel.embeddedEventLoop.run() @@ -1450,7 +1491,7 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { let channelPromise = self.channel.eventLoop.makePromise(of: Channel.self) multiplexer.createStreamChannel(promise: channelPromise) { channel in - return channel.eventLoop.makeSucceededFuture(()) + channel.eventLoop.makeSucceededFuture(()) } self.channel.embeddedEventLoop.run() @@ -1481,10 +1522,14 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) // We're going to send in 10 request frames. - let requestHeaders = HPACKHeaders([(":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https")]) + let requestHeaders = HPACKHeaders([ + (":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https"), + ]) XCTAssertEqual(flushCounter.flushCount, 0) - let framesToSend = stride(from: 1, through: 19, by: 2).map { HTTP2Frame(streamID: HTTP2StreamID($0), payload: .headers(.init(headers: requestHeaders, endStream: true))) } - for frame in framesToSend { + let framesToSend = stride(from: 1, through: 19, by: 2).map { + HTTP2Frame(streamID: HTTP2StreamID($0), payload: .headers(.init(headers: requestHeaders, endStream: true))) + } + for frame in framesToSend { self.channel.pipeline.fireChannelRead(NIOAny(frame)) } self.channel.embeddedEventLoop.run() @@ -1507,7 +1552,7 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { let readCompleteCounter = ReadCompleteCounter() let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { childChannel in - return childChannel.pipeline.addHandler(frameRecorder).flatMap { + childChannel.pipeline.addHandler(frameRecorder).flatMap { childChannel.pipeline.addHandler(readCompleteCounter) } } @@ -1519,7 +1564,9 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { } // Wake up and activate the stream. - let requestHeaders = HPACKHeaders([(":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https")]) + let requestHeaders = HPACKHeaders([ + (":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https"), + ]) let requestFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: requestHeaders, endStream: false))) self.channel.pipeline.fireChannelRead(NIOAny(requestFrame)) self.activateStream(1) @@ -1533,7 +1580,10 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { // Now we're going to send 9 data frames. var requestData = self.channel.allocator.buffer(capacity: 1024) requestData.writeBytes("Hello world!".utf8) - let dataFrames = repeatElement(HTTP2Frame(streamID: 1, payload: .data(.init(data: .byteBuffer(requestData), endStream: false))), count: 9) + let dataFrames = repeatElement( + HTTP2Frame(streamID: 1, payload: .data(.init(data: .byteBuffer(requestData), endStream: false))), + count: 9 + ) for frame in dataFrames { self.channel.pipeline.fireChannelRead(NIOAny(frame)) @@ -1572,7 +1622,7 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { let readCompleteCounter = ReadCompleteCounter() let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { childChannel in - return childChannel.pipeline.addHandler(frameRecorder).flatMap { + childChannel.pipeline.addHandler(frameRecorder).flatMap { childChannel.pipeline.addHandler(readCompleteCounter) } } @@ -1584,10 +1634,15 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { } // Wake up and activate the streams. - let requestHeaders = HPACKHeaders([(":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https")]) + let requestHeaders = HPACKHeaders([ + (":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https"), + ]) for streamID in [HTTP2StreamID(1), HTTP2StreamID(3), HTTP2StreamID(5)] { - let requestFrame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: requestHeaders, endStream: false))) + let requestFrame = HTTP2Frame( + streamID: streamID, + payload: .headers(.init(headers: requestHeaders, endStream: false)) + ) self.channel.pipeline.fireChannelRead(NIOAny(requestFrame)) self.activateStream(streamID) } @@ -1636,10 +1691,12 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { } func testMultiplexerModifiesStreamChannelWritabilityBasedOnFixedSizeTokens() throws { - let multiplexer = HTTP2StreamMultiplexer(mode: .client, - channel: self.channel, - outboundBufferSizeHighWatermark: 100, - outboundBufferSizeLowWatermark: 50) { channel in + let multiplexer = HTTP2StreamMultiplexer( + mode: .client, + channel: self.channel, + outboundBufferSizeHighWatermark: 100, + outboundBufferSizeLowWatermark: 50 + ) { channel in XCTFail("Must not be called") return channel.eventLoop.makeFailedFuture(MyError()) } @@ -1651,7 +1708,7 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { // Now we want to create a new child stream. let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) multiplexer.createStreamChannel(promise: childChannelPromise) { childChannel in - return childChannel.eventLoop.makeSucceededFuture(()) + childChannel.eventLoop.makeSucceededFuture(()) } self.channel.embeddedEventLoop.run() @@ -1660,7 +1717,9 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { // We're going to write a HEADERS frame (not counted towards flow control calculations) and a 90 byte DATA frame (90 bytes). This will not flip the // writability state. - let headers = HPACKHeaders([(":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https")]) + let headers = HPACKHeaders([ + (":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https"), + ]) let headersPayload = HTTP2Frame.FramePayload.headers(.init(headers: headers, endStream: false)) var dataBuffer = childChannel.allocator.buffer(capacity: 90) @@ -1704,7 +1763,7 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { let promises = (0..<5).map { _ in self.channel.eventLoop.makePromise(of: Channel.self) } for promise in promises { multiplexer.createStreamChannel(promise: promise) { childChannel in - return childChannel.eventLoop.makeSucceededFuture(()) + childChannel.eventLoop.makeSucceededFuture(()) } } self.channel.embeddedEventLoop.run() @@ -1716,7 +1775,9 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { // We need to write (and flush) some data so that the streams get stream IDs. for childChannel in channels { - XCTAssertNoThrow(try childChannel.writeAndFlush(HTTP2Frame.FramePayload.headers(.init(headers: [:]))).wait()) + XCTAssertNoThrow( + try childChannel.writeAndFlush(HTTP2Frame.FramePayload.headers(.init(headers: [:]))).wait() + ) } // Mark the parent channel not writable. This currently changes nothing. @@ -1741,10 +1802,12 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { } func testMultiplexerModifiesStreamChannelWritabilityBasedOnFixedSizeTokensAndChannelWritability() throws { - let multiplexer = HTTP2StreamMultiplexer(mode: .client, - channel: self.channel, - outboundBufferSizeHighWatermark: 100, - outboundBufferSizeLowWatermark: 50) { channel in + let multiplexer = HTTP2StreamMultiplexer( + mode: .client, + channel: self.channel, + outboundBufferSizeHighWatermark: 100, + outboundBufferSizeLowWatermark: 50 + ) { channel in XCTFail("Must not be called") return channel.eventLoop.makeFailedFuture(MyError()) } @@ -1756,7 +1819,7 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { // Now we want to create a new child stream. let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) multiplexer.createStreamChannel(promise: childChannelPromise) { childChannel in - return childChannel.eventLoop.makeSucceededFuture(()) + childChannel.eventLoop.makeSucceededFuture(()) } self.channel.embeddedEventLoop.run() @@ -1769,7 +1832,9 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { // We're going to write a HEADERS frame (not counted towards flow control calculations) and a 90 byte DATA frame (90 bytes). This will not flip the // writability state. - let headers = HPACKHeaders([(":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https")]) + let headers = HPACKHeaders([ + (":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https"), + ]) let headersPayload = HTTP2Frame.FramePayload.headers(.init(headers: headers, endStream: false)) var dataBuffer = childChannel.allocator.buffer(capacity: 90) @@ -1810,10 +1875,12 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { func testStreamChannelToleratesFailingInitializer() { struct DummyError: Error {} - let multiplexer = HTTP2StreamMultiplexer(mode: .client, - channel: self.channel, - outboundBufferSizeHighWatermark: 100, - outboundBufferSizeLowWatermark: 50) { channel in + let multiplexer = HTTP2StreamMultiplexer( + mode: .client, + channel: self.channel, + outboundBufferSizeHighWatermark: 100, + outboundBufferSizeLowWatermark: 50 + ) { channel in XCTFail("Must not be called") return channel.eventLoop.makeFailedFuture(MyError()) } @@ -1835,10 +1902,12 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { func testInboundChannelWindowSizeIsCustomisable() throws { let targetWindowSize = 1 << 18 - let multiplexer = HTTP2StreamMultiplexer(mode: .client, - channel: self.channel, - targetWindowSize: targetWindowSize) { channel in - return channel.eventLoop.makeSucceededFuture(()) + let multiplexer = HTTP2StreamMultiplexer( + mode: .client, + channel: self.channel, + targetWindowSize: targetWindowSize + ) { channel in + channel.eventLoop.makeSucceededFuture(()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) @@ -1850,12 +1919,20 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { // Now claim that the window got consumed. Nothing happens. XCTAssertNoThrow(try XCTAssertNil(self.channel.readOutbound(as: HTTP2Frame.self))) - var windowEvent = NIOHTTP2WindowUpdatedEvent(streamID: 1, inboundWindowSize: (targetWindowSize / 2) + 1, outboundWindowSize: nil) + var windowEvent = NIOHTTP2WindowUpdatedEvent( + streamID: 1, + inboundWindowSize: (targetWindowSize / 2) + 1, + outboundWindowSize: nil + ) channel.pipeline.fireUserInboundEventTriggered(windowEvent) XCTAssertNoThrow(try XCTAssertNil(self.channel.readOutbound(as: HTTP2Frame.self))) // Consume the last byte. - windowEvent = NIOHTTP2WindowUpdatedEvent(streamID: 1, inboundWindowSize: (targetWindowSize / 2), outboundWindowSize: nil) + windowEvent = NIOHTTP2WindowUpdatedEvent( + streamID: 1, + inboundWindowSize: (targetWindowSize / 2), + outboundWindowSize: nil + ) channel.pipeline.fireUserInboundEventTriggered(windowEvent) guard let receivedFrame = try assertNoThrowWithValue(self.channel.readOutbound(as: HTTP2Frame.self)) else { XCTFail("No frame received") @@ -1878,7 +1955,7 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { // Create a payload based stream. let streamAPromise = self.channel.eventLoop.makePromise(of: Channel.self) multiplexer.createStreamChannel(promise: streamAPromise) { channel in - return channel.eventLoop.makeSucceededFuture(()) + channel.eventLoop.makeSucceededFuture(()) } self.channel.embeddedEventLoop.run() let streamA = try assertNoThrowWithValue(try streamAPromise.futureResult.wait()) @@ -1898,7 +1975,9 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { let streamB = try assertNoThrowWithValue(try streamBPromise.futureResult.wait()) // Do some writes on A and B. - let headers = HPACKHeaders([(":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https")]) + let headers = HPACKHeaders([ + (":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https"), + ]) let headersPayload = HTTP2Frame.FramePayload.headers(.init(headers: headers, endStream: false)) // (We checked the streamID above.) @@ -1909,14 +1988,17 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { // Stream A must have an ID now. XCTAssertEqual(try streamA.getOption(HTTP2StreamChannelOptions.streamID).wait(), HTTP2StreamID(3)) - frameRecorder.flushedWrites.assertFramesMatch([HTTP2Frame(streamID: 1, payload: headersPayload), - HTTP2Frame(streamID: 3, payload: headersPayload)]) + frameRecorder.flushedWrites.assertFramesMatch([ + HTTP2Frame(streamID: 1, payload: headersPayload), + HTTP2Frame(streamID: 3, payload: headersPayload), + ]) } func testReadWhenUsingAutoreadOnChildChannel() throws { let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) let readCounter = ReadCounter() - let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel -> EventLoopFuture in + let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { + channel -> EventLoopFuture in childChannelPromise.succeed(channel) // We're going to _enable_ autoRead on this channel. @@ -1934,7 +2016,6 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { XCTAssertNoThrow(try self.channel.writeInbound(frame)) self.activateStream(streamID) - _ = try childChannelPromise.futureResult.wait() // There should be two calls to read: the first, when the stream was activated, the second after the HEADERS @@ -1966,10 +2047,12 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { func testWindowUpdateIsNotEmittedAfterStreamIsClosed() throws { let targetWindowSize = 1024 - let multiplexer = HTTP2StreamMultiplexer(mode: .client, - channel: self.channel, - targetWindowSize: targetWindowSize) { channel in - return channel.eventLoop.makeSucceededFuture(()) + let multiplexer = HTTP2StreamMultiplexer( + mode: .client, + channel: self.channel, + targetWindowSize: targetWindowSize + ) { channel in + channel.eventLoop.makeSucceededFuture(()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) @@ -1977,7 +2060,9 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(ipAddress: "127.0.0.1", port: 80)).wait()) // Write a headers frame. - let headers = HPACKHeaders([(":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https")]) + let headers = HPACKHeaders([ + (":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https"), + ]) let headersFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: headers))) self.channel.pipeline.fireChannelRead(NIOAny(headersFrame)) @@ -1995,7 +2080,9 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { // The inbound window size should now be our target: 1024. Write enough bytes to consume the // inbound window. - let data = HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(.init(repeating: 0, count: targetWindowSize + 1)))) + let data = HTTP2Frame.FramePayload.data( + .init(data: .byteBuffer(.init(repeating: 0, count: targetWindowSize + 1))) + ) let dataFrame = HTTP2Frame(streamID: 1, payload: data) self.channel.pipeline.fireChannelRead(NIOAny(dataFrame)) @@ -2009,10 +2096,12 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { func testWindowUpdateIsNotEmittedAfterStreamIsClosedEvenOnLaterFrame() throws { let targetWindowSize = 128 - let multiplexer = HTTP2StreamMultiplexer(mode: .client, - channel: self.channel, - targetWindowSize: targetWindowSize) { channel in - return channel.eventLoop.makeSucceededFuture(()) + let multiplexer = HTTP2StreamMultiplexer( + mode: .client, + channel: self.channel, + targetWindowSize: targetWindowSize + ) { channel in + channel.eventLoop.makeSucceededFuture(()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) @@ -2020,7 +2109,9 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(ipAddress: "127.0.0.1", port: 80)).wait()) // Write a headers frame. - let headers = HPACKHeaders([(":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https")]) + let headers = HPACKHeaders([ + (":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https"), + ]) let headersFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: headers))) self.channel.pipeline.fireChannelRead(NIOAny(headersFrame)) @@ -2035,8 +2126,12 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { // The inbound window size should now be our target: 128. Write enough bytes to consume the // inbound window as two frames: a 127-byte frame, followed by a 1-byte with END_STREAM set. let bytes = ByteBuffer(repeating: 0, count: targetWindowSize) - let firstData = HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(bytes.getSlice(at: bytes.readerIndex, length: targetWindowSize - 1)!))) - let secondData = HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(bytes.getSlice(at: bytes.readerIndex, length: 1)!), endStream: true)) + let firstData = HTTP2Frame.FramePayload.data( + .init(data: .byteBuffer(bytes.getSlice(at: bytes.readerIndex, length: targetWindowSize - 1)!)) + ) + let secondData = HTTP2Frame.FramePayload.data( + .init(data: .byteBuffer(bytes.getSlice(at: bytes.readerIndex, length: 1)!), endStream: true) + ) let firstDataFrame = HTTP2Frame(streamID: 1, payload: firstData) let secondDataFrame = HTTP2Frame(streamID: 1, payload: secondData) @@ -2085,15 +2180,16 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { func testStreamErrorIsDeliveredToChannel() throws { let goodHeaders = HPACKHeaders([ - (":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost") + (":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost"), ]) var badHeaders = goodHeaders badHeaders.add(name: "transfer-encoding", value: "chunked") - - let multiplexer = HTTP2StreamMultiplexer(mode: .client, - channel: self.channel) { channel in - return channel.eventLoop.makeSucceededFuture(()) + let multiplexer = HTTP2StreamMultiplexer( + mode: .client, + channel: self.channel + ) { channel in + channel.eventLoop.makeSucceededFuture(()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) @@ -2166,12 +2262,18 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { XCTAssertEqual(frames.count, 2) frames[0].assertHeadersFrame(endStream: false, streamID: 1, headers: goodHeaders, priority: nil, type: .request) - frames[1].assertHeadersFrame(endStream: false, streamID: 3, headers: badHeaders, priority: nil, type: .doNotValidate) + frames[1].assertHeadersFrame( + endStream: false, + streamID: 3, + headers: badHeaders, + priority: nil, + type: .doNotValidate + ) } func testPendingReadsAreFlushedEvenWithoutUnsatisfiedReadOnChannelInactive() throws { let goodHeaders = HPACKHeaders([ - (":path", "/"), (":method", "GET"), (":scheme", "https"), (":authority", "localhost") + (":path", "/"), (":method", "GET"), (":scheme", "https"), (":authority", "localhost"), ]) let multiplexer = HTTP2StreamMultiplexer(mode: .client, channel: self.channel) { channel in @@ -2230,7 +2332,9 @@ final class HTTP2FramePayloadStreamMultiplexerTests: XCTestCase { // 3. pass on more body - should not change a thing, since read is pending in consumer - let responseBody2 = HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(.init(string: "bar")), endStream: true)) + let responseBody2 = HTTP2Frame.FramePayload.data( + .init(data: .byteBuffer(.init(string: "bar")), endStream: true) + ) XCTAssertNoThrow(try self.channel.writeInbound(HTTP2Frame(streamID: streamID, payload: responseBody2))) try childChannel.pipeline.handler(type: ReadAndFrameConsumer.self).flatMapThrowing { consumer in diff --git a/Tests/NIOHTTP2Tests/HTTP2FramePayloadToHTTP1CodecTests.swift b/Tests/NIOHTTP2Tests/HTTP2FramePayloadToHTTP1CodecTests.swift index 0864854..960d9aa 100644 --- a/Tests/NIOHTTP2Tests/HTTP2FramePayloadToHTTP1CodecTests.swift +++ b/Tests/NIOHTTP2Tests/HTTP2FramePayloadToHTTP1CodecTests.swift @@ -12,11 +12,12 @@ // //===----------------------------------------------------------------------===// -import XCTest import NIOCore import NIOEmbedded -import NIOHTTP1 import NIOHPACK +import NIOHTTP1 +import XCTest + @testable import NIOHTTP2 final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { @@ -34,7 +35,10 @@ final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ServerCodec()).wait()) // A basic request. - let requestHeaders = HPACKHeaders([(":path", "/post"), (":method", "POST"), (":scheme", "https"), (":authority", "example.org"), ("other", "header")]) + let requestHeaders = HPACKHeaders([ + (":path", "/post"), (":method", "POST"), (":scheme", "https"), (":authority", "example.org"), + ("other", "header"), + ]) XCTAssertNoThrow(try self.channel.writeInbound(HTTP2Frame.FramePayload.headers(.init(headers: requestHeaders)))) var expectedRequestHead = HTTPRequestHead(version: HTTPVersion(major: 2, minor: 0), method: .POST, uri: "/post") @@ -57,7 +61,10 @@ final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ServerCodec()).wait()) // A basic request. - let requestHeaders = HPACKHeaders([(":path", "/get"), (":method", "GET"), (":scheme", "https"), (":authority", "example.org"), ("other", "header")]) + let requestHeaders = HPACKHeaders([ + (":path", "/get"), (":method", "GET"), (":scheme", "https"), (":authority", "example.org"), + ("other", "header"), + ]) let headersPayload = HTTP2Frame.FramePayload.headers(.init(headers: requestHeaders, endStream: true)) XCTAssertNoThrow(try self.channel.writeInbound(headersPayload)) @@ -74,7 +81,10 @@ final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ServerCodec()).wait()) // A basic request. - let requestHeaders = HPACKHeaders([(":path", "/get"), (":method", "GET"), (":scheme", "https"), (":authority", "example.org"), ("other", "header")]) + let requestHeaders = HPACKHeaders([ + (":path", "/get"), (":method", "GET"), (":scheme", "https"), (":authority", "example.org"), + ("other", "header"), + ]) let headersPayload = HTTP2Frame.FramePayload.headers(.init(headers: requestHeaders)) XCTAssertNoThrow(try self.channel.writeInbound(headersPayload)) @@ -100,7 +110,11 @@ final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { // A basic response. let responseHeaders = HPACKHeaders([("server", "swift-nio"), ("other", "header")]) - let responseHead = HTTPResponseHead(version: .init(major: 2, minor: 0), status: .ok, headers: HTTPHeaders(regularHeadersFrom: responseHeaders)) + let responseHead = HTTPResponseHead( + version: .init(major: 2, minor: 0), + status: .ok, + headers: HTTPHeaders(regularHeadersFrom: responseHeaders) + ) self.channel.writeAndFlush(HTTPServerResponsePart.head(responseHead), promise: nil) let expectedResponseHeaders = HPACKHeaders([(":status", "200")]) + responseHeaders @@ -130,7 +144,11 @@ final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { // A basic response. let responseHeaders = HPACKHeaders([("server", "swift-nio"), ("other", "header")]) - let responseHead = HTTPResponseHead(version: .init(major: 2, minor: 0), status: .ok, headers: HTTPHeaders(regularHeadersFrom: responseHeaders)) + let responseHead = HTTPResponseHead( + version: .init(major: 2, minor: 0), + status: .ok, + headers: HTTPHeaders(regularHeadersFrom: responseHeaders) + ) self.channel.writeAndFlush(HTTPServerResponsePart.head(responseHead), promise: nil) let expectedResponseHeaders = HPACKHeaders([(":status", "200")]) + responseHeaders @@ -153,7 +171,11 @@ final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { // First, we're going to send a few 103 blocks. let informationalResponseHeaders = HPACKHeaders([("link", "no link really")]) - let informationalResponseHead = HTTPResponseHead(version: .init(major: 2, minor: 0), status: .custom(code: 103, reasonPhrase: "Early Hints"), headers: HTTPHeaders(regularHeadersFrom: informationalResponseHeaders)) + let informationalResponseHead = HTTPResponseHead( + version: .init(major: 2, minor: 0), + status: .custom(code: 103, reasonPhrase: "Early Hints"), + headers: HTTPHeaders(regularHeadersFrom: informationalResponseHeaders) + ) for _ in 0..<3 { self.channel.write(HTTPServerResponsePart.head(informationalResponseHead), promise: nil) } @@ -162,12 +184,19 @@ final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { let expectedInformationalResponseHeaders = HPACKHeaders([(":status", "103")]) + informationalResponseHeaders XCTAssertEqual(writeRecorder.flushedWrites.count, 3) for idx in 0..<3 { - writeRecorder.flushedWrites[idx].assertHeadersFramePayload(endStream: false, headers: expectedInformationalResponseHeaders) + writeRecorder.flushedWrites[idx].assertHeadersFramePayload( + endStream: false, + headers: expectedInformationalResponseHeaders + ) } // Now we finish up with a basic response. let responseHeaders = HPACKHeaders([("server", "swift-nio"), ("other", "header")]) - let responseHead = HTTPResponseHead(version: .init(major: 2, minor: 0), status: .ok, headers: HTTPHeaders(regularHeadersFrom: responseHeaders)) + let responseHead = HTTPResponseHead( + version: .init(major: 2, minor: 0), + status: .ok, + headers: HTTPHeaders(regularHeadersFrom: responseHeaders) + ) self.channel.writeAndFlush(HTTPServerResponsePart.head(responseHead), promise: nil) self.channel.writeAndFlush(HTTPServerResponsePart.end(nil), promise: nil) @@ -212,17 +241,28 @@ final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { func testBasicResponseClientSide() throws { let writeRecorder = FramePayloadWriteRecorder() XCTAssertNoThrow(try self.channel.pipeline.addHandler(writeRecorder).wait()) - XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ClientCodec(httpProtocol: .https)).wait()) + XCTAssertNoThrow( + try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ClientCodec(httpProtocol: .https)).wait() + ) // A basic request let http1Head = HTTPRequestHead(version: .http1_1, method: .GET, uri: "/", headers: ["host": "example.org"]) XCTAssertNoThrow(try self.channel.writeOutbound(HTTPClientRequestPart.head(http1Head))) - let expectedRequestHeaders = HPACKHeaders([(":method", "GET"), (":path", "/"), (":authority", "example.org"), (":scheme", "https")]) - writeRecorder.flushedWrites.popLast()?.assertHeadersFramePayload(endStream: false, headers: expectedRequestHeaders) - + let expectedRequestHeaders = HPACKHeaders([ + (":method", "GET"), (":path", "/"), (":authority", "example.org"), (":scheme", "https"), + ]) + writeRecorder.flushedWrites.popLast()?.assertHeadersFramePayload( + endStream: false, + headers: expectedRequestHeaders + ) + // A basic response. let responseHeaders = HTTPHeaders([(":status", "200"), ("other", "header")]) - XCTAssertNoThrow(try self.channel.writeInbound(HTTP2Frame.FramePayload.headers(.init(headers: HPACKHeaders(httpHeaders: responseHeaders))))) + XCTAssertNoThrow( + try self.channel.writeInbound( + HTTP2Frame.FramePayload.headers(.init(headers: HPACKHeaders(httpHeaders: responseHeaders))) + ) + ) var expectedResponseHead = HTTPResponseHead(version: .init(major: 2, minor: 0), status: .ok) expectedResponseHead.headers.add(name: "other", value: "header") @@ -242,17 +282,26 @@ final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { func testResponseWithOnlyHeadClientSide() throws { let writeRecorder = FramePayloadWriteRecorder() XCTAssertNoThrow(try self.channel.pipeline.addHandler(writeRecorder).wait()) - XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ClientCodec(httpProtocol: .https)).wait()) + XCTAssertNoThrow( + try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ClientCodec(httpProtocol: .https)).wait() + ) // A basic request let http1Head = HTTPRequestHead(version: .http1_1, method: .GET, uri: "/", headers: ["host": "example.org"]) XCTAssertNoThrow(try self.channel.writeOutbound(HTTPClientRequestPart.head(http1Head))) - let expectedRequestHeaders = HPACKHeaders([(":method", "GET"), (":path", "/"), (":authority", "example.org"), (":scheme", "https")]) - writeRecorder.flushedWrites.popLast()?.assertHeadersFramePayload(endStream: false, headers: expectedRequestHeaders) - + let expectedRequestHeaders = HPACKHeaders([ + (":method", "GET"), (":path", "/"), (":authority", "example.org"), (":scheme", "https"), + ]) + writeRecorder.flushedWrites.popLast()?.assertHeadersFramePayload( + endStream: false, + headers: expectedRequestHeaders + ) + // A basic response. let responseHeaders = HTTPHeaders([(":status", "200"), ("other", "header")]) - let headersPayload = HTTP2Frame.FramePayload.headers(.init(headers: HPACKHeaders(httpHeaders: responseHeaders), endStream: true)) + let headersPayload = HTTP2Frame.FramePayload.headers( + .init(headers: HPACKHeaders(httpHeaders: responseHeaders), endStream: true) + ) XCTAssertNoThrow(try self.channel.writeInbound(headersPayload)) var expectedResponseHead = HTTPResponseHead(version: .init(major: 2, minor: 0), status: .ok) @@ -267,13 +316,20 @@ final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { func testResponseWithTrailers() throws { let writeRecorder = FramePayloadWriteRecorder() XCTAssertNoThrow(try self.channel.pipeline.addHandler(writeRecorder).wait()) - XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ClientCodec(httpProtocol: .https)).wait()) + XCTAssertNoThrow( + try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ClientCodec(httpProtocol: .https)).wait() + ) // A basic request let http1Head = HTTPRequestHead(version: .http1_1, method: .GET, uri: "/", headers: ["host": "example.org"]) XCTAssertNoThrow(try self.channel.writeOutbound(HTTPClientRequestPart.head(http1Head))) - let expectedRequestHeaders = HPACKHeaders([(":method", "GET"), (":path", "/"), (":authority", "example.org"), (":scheme", "https")]) - writeRecorder.flushedWrites.popLast()?.assertHeadersFramePayload(endStream: false, headers: expectedRequestHeaders) + let expectedRequestHeaders = HPACKHeaders([ + (":method", "GET"), (":path", "/"), (":authority", "example.org"), (":scheme", "https"), + ]) + writeRecorder.flushedWrites.popLast()?.assertHeadersFramePayload( + endStream: false, + headers: expectedRequestHeaders + ) // A basic response. let responseHeaders = HTTPHeaders([(":status", "200"), ("other", "header")]) @@ -287,7 +343,9 @@ final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { // Ok, we're going to send trailers. let trailers = HTTPHeaders([("a trailer", "yes"), ("another trailer", "also yes")]) - let trailersPayload = HTTP2Frame.FramePayload.headers(.init(headers: HPACKHeaders(httpHeaders: trailers), endStream: true)) + let trailersPayload = HTTP2Frame.FramePayload.headers( + .init(headers: HPACKHeaders(httpHeaders: trailers), endStream: true) + ) XCTAssertNoThrow(try self.channel.writeInbound(trailersPayload)) self.channel.assertReceivedClientResponsePart(.end(trailers)) @@ -298,7 +356,9 @@ final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { func testSendingSimpleRequest() throws { let writeRecorder = FramePayloadWriteRecorder() XCTAssertNoThrow(try self.channel.pipeline.addHandler(writeRecorder).wait()) - XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ClientCodec(httpProtocol: .https)).wait()) + XCTAssertNoThrow( + try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ClientCodec(httpProtocol: .https)).wait() + ) // A basic request. let requestHeaders = HPACKHeaders([("host", "example.org"), ("other", "header")]) @@ -306,7 +366,10 @@ final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { requestHead.headers = HTTPHeaders(regularHeadersFrom: requestHeaders) self.channel.writeAndFlush(HTTPClientRequestPart.head(requestHead), promise: nil) - let expectedRequestHeaders = HPACKHeaders([(":path", "/post"), (":method", "POST"), (":scheme", "https"), (":authority", "example.org"), ("other", "header")]) + let expectedRequestHeaders = HPACKHeaders([ + (":path", "/post"), (":method", "POST"), (":scheme", "https"), (":authority", "example.org"), + ("other", "header"), + ]) XCTAssertEqual(writeRecorder.flushedWrites.count, 1) writeRecorder.flushedWrites[0].assertHeadersFramePayload(endStream: false, headers: expectedRequestHeaders) @@ -329,7 +392,9 @@ final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { func testRequestWithoutTrailers() throws { let writeRecorder = FramePayloadWriteRecorder() XCTAssertNoThrow(try self.channel.pipeline.addHandler(writeRecorder).wait()) - XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ClientCodec(httpProtocol: .http)).wait()) + XCTAssertNoThrow( + try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ClientCodec(httpProtocol: .http)).wait() + ) // A basic request. let requestHeaders = HTTPHeaders([("host", "example.org"), ("other", "header")]) @@ -337,7 +402,10 @@ final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { requestHead.headers = requestHeaders self.channel.writeAndFlush(HTTPClientRequestPart.head(requestHead), promise: nil) - let expectedRequestHeaders = HPACKHeaders([(":path", "/post"), (":method", "POST"), (":scheme", "http"), (":authority", "example.org"), ("other", "header")]) + let expectedRequestHeaders = HPACKHeaders([ + (":path", "/post"), (":method", "POST"), (":scheme", "http"), (":authority", "example.org"), + ("other", "header"), + ]) XCTAssertEqual(writeRecorder.flushedWrites.count, 1) writeRecorder.flushedWrites[0].assertHeadersFramePayload(endStream: false, headers: expectedRequestHeaders) @@ -353,8 +421,10 @@ final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { func testResponseWith100BlocksClientSide() throws { let writeRecorder = FramePayloadWriteRecorder() XCTAssertNoThrow(try self.channel.pipeline.addHandler(writeRecorder).wait()) - XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ClientCodec(httpProtocol: .https)).wait()) - + XCTAssertNoThrow( + try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ClientCodec(httpProtocol: .https)).wait() + ) + // A basic request. let requestHeaders = HPACKHeaders([("host", "example.org"), ("other", "header")]) var requestHead = HTTPRequestHead(version: .init(major: 2, minor: 0), method: .GET, uri: "/get") @@ -364,10 +434,19 @@ final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { // Start with a few 100 blocks. let informationalResponseHeaders = HTTPHeaders([(":status", "103"), ("link", "example")]) for _ in 0..<3 { - XCTAssertNoThrow(try self.channel.writeInbound(HTTP2Frame.FramePayload.headers(.init(headers: HPACKHeaders(httpHeaders: informationalResponseHeaders))))) + XCTAssertNoThrow( + try self.channel.writeInbound( + HTTP2Frame.FramePayload.headers( + .init(headers: HPACKHeaders(httpHeaders: informationalResponseHeaders)) + ) + ) + ) } - var expectedInformationalResponseHead = HTTPResponseHead(version: .init(major: 2, minor: 0), status: .custom(code: 103, reasonPhrase: "")) + var expectedInformationalResponseHead = HTTPResponseHead( + version: .init(major: 2, minor: 0), + status: .custom(code: 103, reasonPhrase: "") + ) expectedInformationalResponseHead.headers.add(name: "link", value: "example") for _ in 0..<3 { self.channel.assertReceivedClientResponsePart(.head(expectedInformationalResponseHead)) @@ -375,7 +454,9 @@ final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { // Now a response. let responseHeaders = HTTPHeaders([(":status", "200"), ("other", "header")]) - let responsePayload = HTTP2Frame.FramePayload.headers(.init(headers: HPACKHeaders(httpHeaders: responseHeaders), endStream: true)) + let responsePayload = HTTP2Frame.FramePayload.headers( + .init(headers: HPACKHeaders(httpHeaders: responseHeaders), endStream: true) + ) XCTAssertNoThrow(try self.channel.writeInbound(responsePayload)) var expectedResponseHead = HTTPResponseHead(version: .init(major: 2, minor: 0), status: .ok) @@ -392,7 +473,9 @@ final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { let promises: [EventLoopPromise] = (0..<3).map { _ in self.channel.eventLoop.makePromise() } XCTAssertNoThrow(try self.channel.pipeline.addHandler(promiseRecorder).wait()) - XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ClientCodec(httpProtocol: .https)).wait()) + XCTAssertNoThrow( + try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ClientCodec(httpProtocol: .https)).wait() + ) // A basic response. let requestHeaders = HTTPHeaders([("host", "example.org"), ("other", "header")]) @@ -421,8 +504,12 @@ final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ServerCodec()).wait()) // A basic request. - let requestHeaders = HPACKHeaders([(":path", "/post"), (":scheme", "https"), (":authority", "example.org"), ("other", "header")]) - XCTAssertThrowsError(try self.channel.writeInbound(HTTP2Frame.FramePayload.headers(.init(headers: requestHeaders)))) { error in + let requestHeaders = HPACKHeaders([ + (":path", "/post"), (":scheme", "https"), (":authority", "example.org"), ("other", "header"), + ]) + XCTAssertThrowsError( + try self.channel.writeInbound(HTTP2Frame.FramePayload.headers(.init(headers: requestHeaders))) + ) { error in XCTAssertEqual(error as? NIOHTTP2Errors.MissingPseudoHeader, NIOHTTP2Errors.missingPseudoHeader(":method")) } @@ -434,9 +521,17 @@ final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ServerCodec()).wait()) // A basic request. - let requestHeaders = HPACKHeaders([(":path", "/post"), (":method", "GET"), (":method", "GET"), (":scheme", "https"), (":authority", "example.org"), ("other", "header")]) - XCTAssertThrowsError(try self.channel.writeInbound(HTTP2Frame.FramePayload.headers(.init(headers: requestHeaders)))) { error in - XCTAssertEqual(error as? NIOHTTP2Errors.DuplicatePseudoHeader, NIOHTTP2Errors.duplicatePseudoHeader(":method")) + let requestHeaders = HPACKHeaders([ + (":path", "/post"), (":method", "GET"), (":method", "GET"), (":scheme", "https"), + (":authority", "example.org"), ("other", "header"), + ]) + XCTAssertThrowsError( + try self.channel.writeInbound(HTTP2Frame.FramePayload.headers(.init(headers: requestHeaders))) + ) { error in + XCTAssertEqual( + error as? NIOHTTP2Errors.DuplicatePseudoHeader, + NIOHTTP2Errors.duplicatePseudoHeader(":method") + ) } // We already know there's an error here. @@ -447,8 +542,12 @@ final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ServerCodec()).wait()) // A basic request. - let requestHeaders = HPACKHeaders([(":method", "GET"), (":scheme", "https"), (":authority", "example.org"), ("other", "header")]) - XCTAssertThrowsError(try self.channel.writeInbound(HTTP2Frame.FramePayload.headers(.init(headers: requestHeaders)))) { error in + let requestHeaders = HPACKHeaders([ + (":method", "GET"), (":scheme", "https"), (":authority", "example.org"), ("other", "header"), + ]) + XCTAssertThrowsError( + try self.channel.writeInbound(HTTP2Frame.FramePayload.headers(.init(headers: requestHeaders))) + ) { error in XCTAssertEqual(error as? NIOHTTP2Errors.MissingPseudoHeader, NIOHTTP2Errors.missingPseudoHeader(":path")) } @@ -460,9 +559,17 @@ final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ServerCodec()).wait()) // A basic request. - let requestHeaders = HPACKHeaders([(":path", "/post"), (":path", "/post"), (":method", "GET"), (":scheme", "https"), (":authority", "example.org"), ("other", "header")]) - XCTAssertThrowsError(try self.channel.writeInbound(HTTP2Frame.FramePayload.headers(.init(headers: requestHeaders)))) { error in - XCTAssertEqual(error as? NIOHTTP2Errors.DuplicatePseudoHeader, NIOHTTP2Errors.duplicatePseudoHeader(":path")) + let requestHeaders = HPACKHeaders([ + (":path", "/post"), (":path", "/post"), (":method", "GET"), (":scheme", "https"), + (":authority", "example.org"), ("other", "header"), + ]) + XCTAssertThrowsError( + try self.channel.writeInbound(HTTP2Frame.FramePayload.headers(.init(headers: requestHeaders))) + ) { error in + XCTAssertEqual( + error as? NIOHTTP2Errors.DuplicatePseudoHeader, + NIOHTTP2Errors.duplicatePseudoHeader(":path") + ) } // We already know there's an error here. @@ -473,9 +580,16 @@ final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ServerCodec()).wait()) // A basic request. - let requestHeaders = HPACKHeaders([(":method", "GET"), (":scheme", "https"), (":path", "/post"), ("other", "header")]) - XCTAssertThrowsError(try self.channel.writeInbound(HTTP2Frame.FramePayload.headers(.init(headers: requestHeaders)))) { error in - XCTAssertEqual(error as? NIOHTTP2Errors.MissingPseudoHeader, NIOHTTP2Errors.missingPseudoHeader(":authority")) + let requestHeaders = HPACKHeaders([ + (":method", "GET"), (":scheme", "https"), (":path", "/post"), ("other", "header"), + ]) + XCTAssertThrowsError( + try self.channel.writeInbound(HTTP2Frame.FramePayload.headers(.init(headers: requestHeaders))) + ) { error in + XCTAssertEqual( + error as? NIOHTTP2Errors.MissingPseudoHeader, + NIOHTTP2Errors.missingPseudoHeader(":authority") + ) } // We already know there's an error here. @@ -486,9 +600,17 @@ final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ServerCodec()).wait()) // A basic request. - let requestHeaders = HPACKHeaders([(":path", "/post"), (":method", "GET"), (":scheme", "https"), (":authority", "example.org"), (":authority", "example.org"), ("other", "header")]) - XCTAssertThrowsError(try self.channel.writeInbound(HTTP2Frame.FramePayload.headers(.init(headers: requestHeaders)))) { error in - XCTAssertEqual(error as? NIOHTTP2Errors.DuplicatePseudoHeader, NIOHTTP2Errors.duplicatePseudoHeader(":authority")) + let requestHeaders = HPACKHeaders([ + (":path", "/post"), (":method", "GET"), (":scheme", "https"), (":authority", "example.org"), + (":authority", "example.org"), ("other", "header"), + ]) + XCTAssertThrowsError( + try self.channel.writeInbound(HTTP2Frame.FramePayload.headers(.init(headers: requestHeaders))) + ) { error in + XCTAssertEqual( + error as? NIOHTTP2Errors.DuplicatePseudoHeader, + NIOHTTP2Errors.duplicatePseudoHeader(":authority") + ) } // We already know there's an error here. @@ -499,8 +621,12 @@ final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ServerCodec()).wait()) // A basic request. - let requestHeaders = HPACKHeaders([(":method", "GET"), (":authority", "example.org"), (":path", "/post"), ("other", "header")]) - XCTAssertThrowsError(try self.channel.writeInbound(HTTP2Frame.FramePayload.headers(.init(headers: requestHeaders)))) { error in + let requestHeaders = HPACKHeaders([ + (":method", "GET"), (":authority", "example.org"), (":path", "/post"), ("other", "header"), + ]) + XCTAssertThrowsError( + try self.channel.writeInbound(HTTP2Frame.FramePayload.headers(.init(headers: requestHeaders))) + ) { error in XCTAssertEqual(error as? NIOHTTP2Errors.MissingPseudoHeader, NIOHTTP2Errors.missingPseudoHeader(":scheme")) } @@ -512,9 +638,17 @@ final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ServerCodec()).wait()) // A basic request. - let requestHeaders = HPACKHeaders([(":path", "/post"), (":method", "GET"), (":scheme", "https"), (":scheme", "https"), (":authority", "example.org"), ("other", "header")]) - XCTAssertThrowsError(try self.channel.writeInbound(HTTP2Frame.FramePayload.headers(.init(headers: requestHeaders)))) { error in - XCTAssertEqual(error as? NIOHTTP2Errors.DuplicatePseudoHeader, NIOHTTP2Errors.duplicatePseudoHeader(":scheme")) + let requestHeaders = HPACKHeaders([ + (":path", "/post"), (":method", "GET"), (":scheme", "https"), (":scheme", "https"), + (":authority", "example.org"), ("other", "header"), + ]) + XCTAssertThrowsError( + try self.channel.writeInbound(HTTP2Frame.FramePayload.headers(.init(headers: requestHeaders))) + ) { error in + XCTAssertEqual( + error as? NIOHTTP2Errors.DuplicatePseudoHeader, + NIOHTTP2Errors.duplicatePseudoHeader(":scheme") + ) } // We already know there's an error here. @@ -522,11 +656,15 @@ final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { } func testReceiveResponseWithoutStatus() throws { - XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ClientCodec(httpProtocol: .https)).wait()) + XCTAssertNoThrow( + try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ClientCodec(httpProtocol: .https)).wait() + ) // A basic response. let requestHeaders = HPACKHeaders([("other", "header")]) - XCTAssertThrowsError(try self.channel.writeInbound(HTTP2Frame.FramePayload.headers(.init(headers: requestHeaders)))) { error in + XCTAssertThrowsError( + try self.channel.writeInbound(HTTP2Frame.FramePayload.headers(.init(headers: requestHeaders))) + ) { error in XCTAssertEqual(error as? NIOHTTP2Errors.MissingPseudoHeader, NIOHTTP2Errors.missingPseudoHeader(":status")) } @@ -535,12 +673,19 @@ final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { } func testReceiveResponseWithDuplicateStatus() throws { - XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ClientCodec(httpProtocol: .https)).wait()) + XCTAssertNoThrow( + try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ClientCodec(httpProtocol: .https)).wait() + ) // A basic request. let requestHeaders = HPACKHeaders([(":status", "200"), (":status", "404"), ("other", "header")]) - XCTAssertThrowsError(try self.channel.writeInbound(HTTP2Frame.FramePayload.headers(.init(headers: requestHeaders)))) { error in - XCTAssertEqual(error as? NIOHTTP2Errors.DuplicatePseudoHeader, NIOHTTP2Errors.duplicatePseudoHeader(":status")) + XCTAssertThrowsError( + try self.channel.writeInbound(HTTP2Frame.FramePayload.headers(.init(headers: requestHeaders))) + ) { error in + XCTAssertEqual( + error as? NIOHTTP2Errors.DuplicatePseudoHeader, + NIOHTTP2Errors.duplicatePseudoHeader(":status") + ) } // We already know there's an error here. @@ -548,7 +693,9 @@ final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { } func testReceiveResponseWithNonNumericalStatus() throws { - XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ClientCodec(httpProtocol: .https)).wait()) + XCTAssertNoThrow( + try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ClientCodec(httpProtocol: .https)).wait() + ) // A basis request let requestHeaders = HTTPHeaders([("host", "example.org"), ("other", "header")]) @@ -558,8 +705,13 @@ final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { // A basic response. let responseHeaders = HPACKHeaders([(":status", "captivating")]) - XCTAssertThrowsError(try self.channel.writeInbound(HTTP2Frame.FramePayload.headers(.init(headers: responseHeaders)))) { error in - XCTAssertEqual(error as? NIOHTTP2Errors.InvalidStatusValue, NIOHTTP2Errors.invalidStatusValue("captivating")) + XCTAssertThrowsError( + try self.channel.writeInbound(HTTP2Frame.FramePayload.headers(.init(headers: responseHeaders))) + ) { error in + XCTAssertEqual( + error as? NIOHTTP2Errors.InvalidStatusValue, + NIOHTTP2Errors.invalidStatusValue("captivating") + ) } // We already know there's an error here. @@ -567,7 +719,9 @@ final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { } func testSendRequestWithoutHost() throws { - XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ClientCodec(httpProtocol: .https)).wait()) + XCTAssertNoThrow( + try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ClientCodec(httpProtocol: .https)).wait() + ) // A basic request without Host. let request = HTTPClientRequestPart.head(.init(version: .init(major: 1, minor: 1), method: .GET, uri: "/")) @@ -582,7 +736,9 @@ final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { } func testSendRequestWithDuplicateHost() throws { - XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ClientCodec(httpProtocol: .https)).wait()) + XCTAssertNoThrow( + try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ClientCodec(httpProtocol: .https)).wait() + ) // A basic request with too many host headers. var requestHead = HTTPRequestHead(version: .init(major: 1, minor: 1), method: .GET, uri: "/") @@ -601,18 +757,22 @@ final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { func testFramesWithoutHTTP1EquivalentAreIgnored() throws { let streamID = HTTP2StreamID(1) - XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ClientCodec(httpProtocol: .https)).wait()) + XCTAssertNoThrow( + try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ClientCodec(httpProtocol: .https)).wait() + ) let headers = HPACKHeaders([(":method", "GET"), (":scheme", "https"), (":path", "/x")]) - let payloads: [HTTP2Frame.FramePayload] = [.alternativeService(origin: nil, field: nil), - .rstStream(.init(networkCode: 1)), - .priority(.init(exclusive: true, dependency: streamID, weight: 1)), - .windowUpdate(windowSizeIncrement: 1), - .settings(.ack), - .pushPromise(.init(pushedStreamID: HTTP2StreamID(2), headers: headers)), - .ping(.init(withInteger: 123), ack: true), - .goAway(lastStreamID: streamID, errorCode: .init(networkCode: 1), opaqueData: nil), - .origin([])] + let payloads: [HTTP2Frame.FramePayload] = [ + .alternativeService(origin: nil, field: nil), + .rstStream(.init(networkCode: 1)), + .priority(.init(exclusive: true, dependency: streamID, weight: 1)), + .windowUpdate(windowSizeIncrement: 1), + .settings(.ack), + .pushPromise(.init(pushedStreamID: HTTP2StreamID(2), headers: headers)), + .ping(.init(withInteger: 123), ack: true), + .goAway(lastStreamID: streamID, errorCode: .init(networkCode: 1), opaqueData: nil), + .origin([]), + ] for payload in payloads { XCTAssertNoThrow(try self.channel.writeInbound(payload), "error on \(payload)") } @@ -622,18 +782,25 @@ final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { func testWeTolerateUpperCasedHTTP1HeadersForRequests() throws { let writeRecorder = FramePayloadWriteRecorder() XCTAssertNoThrow(try self.channel.pipeline.addHandler(writeRecorder).wait()) - XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ClientCodec(httpProtocol: .https)).wait()) + XCTAssertNoThrow( + try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ClientCodec(httpProtocol: .https)).wait() + ) // A basic request. var requestHead = HTTPRequestHead(version: .init(major: 2, minor: 0), method: .POST, uri: "/post") requestHead.headers = HTTPHeaders([("host", "example.org"), ("UpperCased", "Header")]) self.channel.writeAndFlush(HTTPClientRequestPart.head(requestHead), promise: nil) - let expectedRequestHeaders = HPACKHeaders([(":path", "/post"), (":method", "POST"), (":scheme", "https"), (":authority", "example.org"), ("uppercased", "Header")]) + let expectedRequestHeaders = HPACKHeaders([ + (":path", "/post"), (":method", "POST"), (":scheme", "https"), (":authority", "example.org"), + ("uppercased", "Header"), + ]) XCTAssertEqual(writeRecorder.flushedWrites.count, 1) - writeRecorder.flushedWrites[0].assertHeadersFramePayload(endStream: false, - headers: expectedRequestHeaders, - type: .request) + writeRecorder.flushedWrites[0].assertHeadersFramePayload( + endStream: false, + headers: expectedRequestHeaders, + type: .request + ) } func testWeTolerateUpperCasedHTTP1HeadersForResponses() throws { @@ -647,34 +814,49 @@ final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { let expectedRequestHeaders = HPACKHeaders([(":status", "200"), ("uppercased", "Header")]) XCTAssertEqual(writeRecorder.flushedWrites.count, 1) - writeRecorder.flushedWrites[0].assertHeadersFramePayload(endStream: false, - headers: expectedRequestHeaders, - type: .response) + writeRecorder.flushedWrites[0].assertHeadersFramePayload( + endStream: false, + headers: expectedRequestHeaders, + type: .response + ) } func testWeDoNotNormalizeHeadersIfUserAskedUsNotToForRequests() throws { let writeRecorder = FramePayloadWriteRecorder() XCTAssertNoThrow(try self.channel.pipeline.addHandler(writeRecorder).wait()) - XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ClientCodec(httpProtocol: .https, - normalizeHTTPHeaders: false)).wait()) + XCTAssertNoThrow( + try self.channel.pipeline.addHandler( + HTTP2FramePayloadToHTTP1ClientCodec( + httpProtocol: .https, + normalizeHTTPHeaders: false + ) + ).wait() + ) // A basic request. var requestHead = HTTPRequestHead(version: .init(major: 2, minor: 0), method: .POST, uri: "/post") requestHead.headers = HTTPHeaders([("host", "example.org"), ("UpperCased", "Header")]) self.channel.writeAndFlush(HTTPClientRequestPart.head(requestHead), promise: nil) - let expectedRequestHeaders = HPACKHeaders([(":path", "/post"), (":method", "POST"), (":scheme", "https"), - (":authority", "example.org"), ("UpperCased", "Header")]) + let expectedRequestHeaders = HPACKHeaders([ + (":path", "/post"), (":method", "POST"), (":scheme", "https"), + (":authority", "example.org"), ("UpperCased", "Header"), + ]) XCTAssertEqual(writeRecorder.flushedWrites.count, 1) - writeRecorder.flushedWrites[0].assertHeadersFramePayload(endStream: false, - headers: expectedRequestHeaders, - type: .doNotValidate) + writeRecorder.flushedWrites[0].assertHeadersFramePayload( + endStream: false, + headers: expectedRequestHeaders, + type: .doNotValidate + ) } func testWeDoNotNormalizeHeadersIfUserAskedUsNotToForResponses() throws { let writeRecorder = FramePayloadWriteRecorder() XCTAssertNoThrow(try self.channel.pipeline.addHandler(writeRecorder).wait()) - XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ServerCodec(normalizeHTTPHeaders: false)).wait()) + XCTAssertNoThrow( + try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ServerCodec(normalizeHTTPHeaders: false)) + .wait() + ) var responseHead = HTTPResponseHead(version: .init(major: 2, minor: 0), status: .ok) responseHead.headers = HTTPHeaders([("UpperCased", "Header")]) @@ -682,35 +864,47 @@ final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { let expectedRequestHeaders = HPACKHeaders([(":status", "200"), ("UpperCased", "Header")]) XCTAssertEqual(writeRecorder.flushedWrites.count, 1) - writeRecorder.flushedWrites[0].assertHeadersFramePayload(endStream: false, - headers: expectedRequestHeaders, - type: .doNotValidate) + writeRecorder.flushedWrites[0].assertHeadersFramePayload( + endStream: false, + headers: expectedRequestHeaders, + type: .doNotValidate + ) } func testWeStripIllegalHeadersAsWellAsTheHeadersNominatedByTheConnectionHeaderForRequests() throws { let writeRecorder = FramePayloadWriteRecorder() XCTAssertNoThrow(try self.channel.pipeline.addHandler(writeRecorder).wait()) - XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ClientCodec(httpProtocol: .https)).wait()) + XCTAssertNoThrow( + try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ClientCodec(httpProtocol: .https)).wait() + ) // A basic request. var requestHead = HTTPRequestHead(version: .init(major: 2, minor: 0), method: .POST, uri: "/post") - requestHead.headers = HTTPHeaders([("host", "example.org"), ("connection", "keep-alive, also-to-be-removed"), - ("keep-alive", "foo"), ("also-to-be-removed", "yes"), ("should", "stay"), - ("Proxy-Connection", "bad"), ("Transfer-Encoding", "also bad")]) + requestHead.headers = HTTPHeaders([ + ("host", "example.org"), ("connection", "keep-alive, also-to-be-removed"), + ("keep-alive", "foo"), ("also-to-be-removed", "yes"), ("should", "stay"), + ("Proxy-Connection", "bad"), ("Transfer-Encoding", "also bad"), + ]) self.channel.writeAndFlush(HTTPClientRequestPart.head(requestHead), promise: nil) - let expectedRequestHeaders = HPACKHeaders([(":path", "/post"), (":method", "POST"), (":scheme", "https"), - (":authority", "example.org"), ("should", "stay")]) + let expectedRequestHeaders = HPACKHeaders([ + (":path", "/post"), (":method", "POST"), (":scheme", "https"), + (":authority", "example.org"), ("should", "stay"), + ]) XCTAssertEqual(writeRecorder.flushedWrites.count, 1) - writeRecorder.flushedWrites[0].assertHeadersFramePayload(endStream: false, - headers: expectedRequestHeaders, - type: .request) + writeRecorder.flushedWrites[0].assertHeadersFramePayload( + endStream: false, + headers: expectedRequestHeaders, + type: .request + ) } - + func testWeStripTransferEncodingChunkedHeader() { let writeRecorder = FramePayloadWriteRecorder() XCTAssertNoThrow(try self.channel.pipeline.addHandler(writeRecorder).wait()) - XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ClientCodec(httpProtocol: .https)).wait()) + XCTAssertNoThrow( + try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ClientCodec(httpProtocol: .https)).wait() + ) // A basic request. var requestHead = HTTPRequestHead(version: .init(major: 1, minor: 1), method: .POST, uri: "/post") @@ -720,12 +914,16 @@ final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { ]) self.channel.writeAndFlush(HTTPClientRequestPart.head(requestHead), promise: nil) - let expectedRequestHeaders = HPACKHeaders([(":path", "/post"), (":method", "POST"), (":scheme", "https"), - (":authority", "example.org")]) + let expectedRequestHeaders = HPACKHeaders([ + (":path", "/post"), (":method", "POST"), (":scheme", "https"), + (":authority", "example.org"), + ]) XCTAssertEqual(writeRecorder.flushedWrites.count, 1) - writeRecorder.flushedWrites[0].assertHeadersFramePayload(endStream: false, - headers: expectedRequestHeaders, - type: .request) + writeRecorder.flushedWrites[0].assertHeadersFramePayload( + endStream: false, + headers: expectedRequestHeaders, + type: .request + ) } func testWeStripIllegalHeadersAsWellAsTheHeadersNominatedByTheConnectionHeaderForResponses() throws { @@ -734,23 +932,29 @@ final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ServerCodec()).wait()) var responseHead = HTTPResponseHead(version: .init(major: 2, minor: 0), status: .ok) - responseHead.headers = HTTPHeaders([("connection", "keep-alive, also-to-be-removed"), - ("keep-alive", "foo"), ("also-to-be-removed", "yes"), ("should", "stay"), - ("Proxy-Connection", "bad"), ("Transfer-Encoding", "also bad")]) + responseHead.headers = HTTPHeaders([ + ("connection", "keep-alive, also-to-be-removed"), + ("keep-alive", "foo"), ("also-to-be-removed", "yes"), ("should", "stay"), + ("Proxy-Connection", "bad"), ("Transfer-Encoding", "also bad"), + ]) self.channel.writeAndFlush(HTTPServerResponsePart.head(responseHead), promise: nil) let expectedRequestHeaders = HPACKHeaders([(":status", "200"), ("should", "stay")]) XCTAssertEqual(writeRecorder.flushedWrites.count, 1) - writeRecorder.flushedWrites[0].assertHeadersFramePayload(endStream: false, - headers: expectedRequestHeaders, - type: .response) + writeRecorder.flushedWrites[0].assertHeadersFramePayload( + endStream: false, + headers: expectedRequestHeaders, + type: .response + ) } - + func testServerSideWithEmptyFinalPackage() throws { XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ServerCodec()).wait()) // A basic request. - let requestHeaders = HPACKHeaders([(":path", "/post"), (":method", "POST"), (":scheme", "https"), (":authority", "example.org")]) + let requestHeaders = HPACKHeaders([ + (":path", "/post"), (":method", "POST"), (":scheme", "https"), (":authority", "example.org"), + ]) XCTAssertNoThrow(try self.channel.writeInbound(HTTP2Frame.FramePayload.headers(.init(headers: requestHeaders)))) var expectedRequestHead = HTTPRequestHead(version: HTTPVersion(major: 2, minor: 0), method: .POST, uri: "/post") @@ -763,17 +967,21 @@ final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { let dataPayload = HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(bodyData), endStream: false)) XCTAssertNoThrow(try self.channel.writeInbound(dataPayload)) self.channel.assertReceivedServerRequestPart(.body(bodyData)) - - let endPayload = HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(self.channel.allocator.buffer(capacity: 0)), endStream: true)) + + let endPayload = HTTP2Frame.FramePayload.data( + .init(data: .byteBuffer(self.channel.allocator.buffer(capacity: 0)), endStream: true) + ) XCTAssertNoThrow(try self.channel.writeInbound(endPayload)) self.channel.assertReceivedServerRequestPart(.end(nil)) XCTAssertNoThrow(try self.channel.finish()) } - + func testClientSideWithEmptyFinalPackage() throws { - XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ClientCodec(httpProtocol: .https)).wait()) - + XCTAssertNoThrow( + try self.channel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ClientCodec(httpProtocol: .https)).wait() + ) + // A basic request. let requestHeaders = HPACKHeaders([("host", "example.org"), ("other", "header")]) var requestHead = HTTPRequestHead(version: .init(major: 1, minor: 1), method: .GET, uri: "/get") @@ -782,9 +990,17 @@ final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { // A basic response. let responseHeaders = HTTPHeaders([(":status", "200")]) - XCTAssertNoThrow(try self.channel.writeInbound(HTTP2Frame.FramePayload.headers(.init(headers: HPACKHeaders(httpHeaders: responseHeaders))))) + XCTAssertNoThrow( + try self.channel.writeInbound( + HTTP2Frame.FramePayload.headers(.init(headers: HPACKHeaders(httpHeaders: responseHeaders))) + ) + ) - let expectedResponseHead = HTTPResponseHead(version: .init(major: 2, minor: 0), status: .ok, headers: ["transfer-encoding": "chunked"]) + let expectedResponseHead = HTTPResponseHead( + version: .init(major: 2, minor: 0), + status: .ok, + headers: ["transfer-encoding": "chunked"] + ) self.channel.assertReceivedClientResponsePart(.head(expectedResponseHead)) var bodyData = self.channel.allocator.buffer(capacity: 12) @@ -792,27 +1008,44 @@ final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { let dataPayload = HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(bodyData), endStream: true)) XCTAssertNoThrow(try self.channel.writeInbound(dataPayload)) self.channel.assertReceivedClientResponsePart(.body(bodyData)) - - let endPayload = HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(self.channel.allocator.buffer(capacity: 0)), endStream: true)) + + let endPayload = HTTP2Frame.FramePayload.data( + .init(data: .byteBuffer(self.channel.allocator.buffer(capacity: 0)), endStream: true) + ) XCTAssertNoThrow(try self.channel.writeInbound(endPayload)) self.channel.assertReceivedClientResponsePart(.end(nil)) XCTAssertNoThrow(try self.channel.finish()) } - + func testRequestMethodsWithoutDefinedSemanticsForAPayloadDontGetTransferEncodingAdded() { let methods: [HTTPMethod] = [.GET, .HEAD, .DELETE, .CONNECT, .TRACE] for method in methods { let embedded = EmbeddedChannel() - + XCTAssertNoThrow(try embedded.pipeline.addHandler(HTTP2FramePayloadToHTTP1ServerCodec()).wait()) // A basic request. - let requestHeaders = HPACKHeaders([(":path", "/"), (":method", "\(method)"), (":scheme", "https"), (":authority", "example.org"), ("other", "header")]) - XCTAssertNoThrow(try embedded.writeInbound(HTTP2Frame.FramePayload.headers(.init(headers: requestHeaders, endStream: false)))) - XCTAssertNoThrow(try embedded.writeInbound(HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(.init()), endStream: true)))) + let requestHeaders = HPACKHeaders([ + (":path", "/"), (":method", "\(method)"), (":scheme", "https"), (":authority", "example.org"), + ("other", "header"), + ]) + XCTAssertNoThrow( + try embedded.writeInbound( + HTTP2Frame.FramePayload.headers(.init(headers: requestHeaders, endStream: false)) + ) + ) + XCTAssertNoThrow( + try embedded.writeInbound( + HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(.init()), endStream: true)) + ) + ) - var expectedRequestHead = HTTPRequestHead(version: HTTPVersion(major: 2, minor: 0), method: method, uri: "/") + var expectedRequestHead = HTTPRequestHead( + version: HTTPVersion(major: 2, minor: 0), + method: method, + uri: "/" + ) expectedRequestHead.headers.add(name: "host", value: "example.org") expectedRequestHead.headers.add(name: "other", value: "header") embedded.assertReceivedServerRequestPart(.head(expectedRequestHead)) @@ -821,24 +1054,39 @@ final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { XCTAssertNoThrow(try embedded.finish()) } } - + func testRequestMethodsWithoutDefinedSemanticsForAPayloadDontRemoveContentLengthIfSet() { let methods: [HTTPMethod] = [.GET, .HEAD, .DELETE, .CONNECT, .TRACE] for method in methods { let embedded = EmbeddedChannel() - + XCTAssertNoThrow(try embedded.pipeline.addHandler(HTTP2FramePayloadToHTTP1ServerCodec()).wait()) // A basic request. - let requestHeaders = HPACKHeaders([(":path", "/"), (":method", "\(method)"), (":scheme", "https"), (":authority", "example.org"), ("content-length", "13")]) - XCTAssertNoThrow(try embedded.writeInbound(HTTP2Frame.FramePayload.headers(.init(headers: requestHeaders, endStream: false)))) - + let requestHeaders = HPACKHeaders([ + (":path", "/"), (":method", "\(method)"), (":scheme", "https"), (":authority", "example.org"), + ("content-length", "13"), + ]) + XCTAssertNoThrow( + try embedded.writeInbound( + HTTP2Frame.FramePayload.headers(.init(headers: requestHeaders, endStream: false)) + ) + ) + let bodyData = embedded.allocator.buffer(string: "hello, world!") let dataPayload = HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(bodyData), endStream: true)) XCTAssertNoThrow(try embedded.writeInbound(dataPayload)) - XCTAssertNoThrow(try embedded.writeInbound(HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(.init()), endStream: true)))) + XCTAssertNoThrow( + try embedded.writeInbound( + HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(.init()), endStream: true)) + ) + ) - var expectedRequestHead = HTTPRequestHead(version: HTTPVersion(major: 2, minor: 0), method: method, uri: "/") + var expectedRequestHead = HTTPRequestHead( + version: HTTPVersion(major: 2, minor: 0), + method: method, + uri: "/" + ) expectedRequestHead.headers.add(name: "host", value: "example.org") expectedRequestHead.headers.add(name: "content-length", value: "13") embedded.assertReceivedServerRequestPart(.head(expectedRequestHead)) @@ -848,25 +1096,35 @@ final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { XCTAssertNoThrow(try embedded.finish()) } } - + func testRequestMethodsWithDefinedSemanticsForAPayloadAddContentLengthHeaderIfEmpty() { let methods: [HTTPMethod] = [ .PUT, .ACL, .POST, .COPY, .LOCK, .MOVE, .BIND, .LINK, .PATCH, .MKCOL, .MERGE, .PURGE, .NOTIFY, .SEARCH, .UNLOCK, .REBIND, .UNBIND, .REPORT, .UNLINK, .MSEARCH, .OPTIONS, .PROPFIND, .CHECKOUT, .PROPPATCH, .SUBSCRIBE, .MKCALENDAR, .MKACTIVITY, .UNSUBSCRIBE, - .SOURCE + .SOURCE, ] for method in methods { let embedded = EmbeddedChannel() - + XCTAssertNoThrow(try embedded.pipeline.addHandler(HTTP2FramePayloadToHTTP1ServerCodec()).wait()) // A basic request. - let requestHeaders = HPACKHeaders([(":path", "/"), (":method", "\(method)"), (":scheme", "https"), (":authority", "example.org")]) - XCTAssertNoThrow(try embedded.writeInbound(HTTP2Frame.FramePayload.headers(.init(headers: requestHeaders, endStream: true)))) + let requestHeaders = HPACKHeaders([ + (":path", "/"), (":method", "\(method)"), (":scheme", "https"), (":authority", "example.org"), + ]) + XCTAssertNoThrow( + try embedded.writeInbound( + HTTP2Frame.FramePayload.headers(.init(headers: requestHeaders, endStream: true)) + ) + ) - var expectedRequestHead = HTTPRequestHead(version: HTTPVersion(major: 2, minor: 0), method: method, uri: "/") + var expectedRequestHead = HTTPRequestHead( + version: HTTPVersion(major: 2, minor: 0), + method: method, + uri: "/" + ) expectedRequestHead.headers.add(name: "host", value: "example.org") expectedRequestHead.headers.add(name: "content-length", value: "0") embedded.assertReceivedServerRequestPart(.head(expectedRequestHead)) @@ -875,26 +1133,40 @@ final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { XCTAssertNoThrow(try embedded.finish()) } } - + func testRequestMethodsWithDefinedSemanticsForAPayloadAddTransferEncodingIfNotEmpty() { let methods: [HTTPMethod] = [ .PUT, .ACL, .POST, .COPY, .LOCK, .MOVE, .BIND, .LINK, .PATCH, .MKCOL, .MERGE, .PURGE, .NOTIFY, .SEARCH, .UNLOCK, .REBIND, .UNBIND, .REPORT, .UNLINK, .MSEARCH, .OPTIONS, .PROPFIND, .CHECKOUT, .PROPPATCH, .SUBSCRIBE, .MKCALENDAR, .MKACTIVITY, .UNSUBSCRIBE, - .SOURCE + .SOURCE, ] for method in methods { let embedded = EmbeddedChannel() - + XCTAssertNoThrow(try embedded.pipeline.addHandler(HTTP2FramePayloadToHTTP1ServerCodec()).wait()) // A basic request. - let requestHeaders = HPACKHeaders([(":path", "/"), (":method", "\(method)"), (":scheme", "https"), (":authority", "example.org")]) - XCTAssertNoThrow(try embedded.writeInbound(HTTP2Frame.FramePayload.headers(.init(headers: requestHeaders, endStream: false)))) - XCTAssertNoThrow(try embedded.writeInbound(HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(.init()), endStream: true)))) + let requestHeaders = HPACKHeaders([ + (":path", "/"), (":method", "\(method)"), (":scheme", "https"), (":authority", "example.org"), + ]) + XCTAssertNoThrow( + try embedded.writeInbound( + HTTP2Frame.FramePayload.headers(.init(headers: requestHeaders, endStream: false)) + ) + ) + XCTAssertNoThrow( + try embedded.writeInbound( + HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(.init()), endStream: true)) + ) + ) - var expectedRequestHead = HTTPRequestHead(version: HTTPVersion(major: 2, minor: 0), method: method, uri: "/") + var expectedRequestHead = HTTPRequestHead( + version: HTTPVersion(major: 2, minor: 0), + method: method, + uri: "/" + ) expectedRequestHead.headers.add(name: "host", value: "example.org") expectedRequestHead.headers.add(name: "transfer-encoding", value: "chunked") embedded.assertReceivedServerRequestPart(.head(expectedRequestHead)) @@ -903,34 +1175,49 @@ final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { XCTAssertNoThrow(try embedded.finish()) } } - + func testRequestContentLengthIsAlwaysPreserved() { let methods: [HTTPMethod] = [ // methods in which a body has no defined meaning .GET, .HEAD, .DELETE, .CONNECT, .TRACE, - + // methods in which a body has a defined meaning .PUT, .ACL, .POST, .COPY, .LOCK, .MOVE, .BIND, .LINK, .PATCH, .MKCOL, .MERGE, .PURGE, .NOTIFY, .SEARCH, .UNLOCK, .REBIND, .UNBIND, .REPORT, .UNLINK, .MSEARCH, .OPTIONS, .PROPFIND, .CHECKOUT, .PROPPATCH, .SUBSCRIBE, .MKCALENDAR, .MKACTIVITY, .UNSUBSCRIBE, - .SOURCE + .SOURCE, ] for method in methods { let embedded = EmbeddedChannel() - + XCTAssertNoThrow(try embedded.pipeline.addHandler(HTTP2FramePayloadToHTTP1ServerCodec()).wait()) // A basic request. - let requestHeaders = HPACKHeaders([(":path", "/"), (":method", "\(method)"), (":scheme", "https"), (":authority", "example.org"), ("content-length", "13")]) - XCTAssertNoThrow(try embedded.writeInbound(HTTP2Frame.FramePayload.headers(.init(headers: requestHeaders, endStream: false)))) - + let requestHeaders = HPACKHeaders([ + (":path", "/"), (":method", "\(method)"), (":scheme", "https"), (":authority", "example.org"), + ("content-length", "13"), + ]) + XCTAssertNoThrow( + try embedded.writeInbound( + HTTP2Frame.FramePayload.headers(.init(headers: requestHeaders, endStream: false)) + ) + ) + let bodyData = embedded.allocator.buffer(string: "hello, world!") let dataPayload = HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(bodyData), endStream: true)) XCTAssertNoThrow(try embedded.writeInbound(dataPayload)) - XCTAssertNoThrow(try embedded.writeInbound(HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(.init()), endStream: true)))) + XCTAssertNoThrow( + try embedded.writeInbound( + HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(.init()), endStream: true)) + ) + ) - var expectedRequestHead = HTTPRequestHead(version: HTTPVersion(major: 2, minor: 0), method: method, uri: "/") + var expectedRequestHead = HTTPRequestHead( + version: HTTPVersion(major: 2, minor: 0), + method: method, + uri: "/" + ) expectedRequestHead.headers.add(name: "host", value: "example.org") expectedRequestHead.headers.add(name: "content-length", value: "13") embedded.assertReceivedServerRequestPart(.head(expectedRequestHead)) @@ -940,33 +1227,50 @@ final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { XCTAssertNoThrow(try embedded.finish()) } } - + func testResponseTransferEncodingIsNotAddedInReponseToHEADorCONNECT() { let methods: [HTTPMethod] = [ // methods in which a body has no defined meaning - .HEAD, .CONNECT + .HEAD, .CONNECT, ] for method in methods { let embedded = EmbeddedChannel() - + let writeRecorder = FramePayloadWriteRecorder() XCTAssertNoThrow(try embedded.pipeline.addHandler(writeRecorder).wait()) - XCTAssertNoThrow(try embedded.pipeline.addHandler(HTTP2FramePayloadToHTTP1ClientCodec(httpProtocol: .https, normalizeHTTPHeaders: true)).wait()) + XCTAssertNoThrow( + try embedded.pipeline.addHandler( + HTTP2FramePayloadToHTTP1ClientCodec(httpProtocol: .https, normalizeHTTPHeaders: true) + ).wait() + ) - let requestHead = HTTPRequestHead(version: .http1_1, method: method, uri: "/", headers: ["Host": "example.org"]) + let requestHead = HTTPRequestHead( + version: .http1_1, + method: method, + uri: "/", + headers: ["Host": "example.org"] + ) XCTAssertNoThrow(try embedded.writeOutbound(HTTPClientRequestPart.head(requestHead))) XCTAssertNoThrow(try embedded.writeOutbound(HTTPClientRequestPart.end(nil))) - - let expectedRequestHeaders = HPACKHeaders([(":path", "/"), (":method", "\(method)"), (":scheme", "https"), (":authority", "example.org")]) - writeRecorder.flushedWrites[0].assertHeadersFramePayload(endStream: false, - headers: expectedRequestHeaders, - type: .doNotValidate) + + let expectedRequestHeaders = HPACKHeaders([ + (":path", "/"), (":method", "\(method)"), (":scheme", "https"), (":authority", "example.org"), + ]) + writeRecorder.flushedWrites[0].assertHeadersFramePayload( + endStream: false, + headers: expectedRequestHeaders, + type: .doNotValidate + ) writeRecorder.flushedWrites[1].assertDataFramePayload(endStream: true, payload: ByteBuffer()) - + let responseHeaders = HPACKHeaders(httpHeaders: [":status": "200"]) - XCTAssertNoThrow(try embedded.writeInbound(HTTP2Frame.FramePayload.headers(.init(headers: responseHeaders, endStream: true)))) - + XCTAssertNoThrow( + try embedded.writeInbound( + HTTP2Frame.FramePayload.headers(.init(headers: responseHeaders, endStream: true)) + ) + ) + let expectedResponseHead = HTTPResponseHead(version: .http2, status: .ok) embedded.assertReceivedClientResponsePart(.head(expectedResponseHead)) embedded.assertReceivedClientResponsePart(.end(nil)) @@ -977,29 +1281,46 @@ final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { let responseStatus: [HTTPResponseStatus] = [ // methods in which a body has no defined meaning .continue, .switchingProtocols, .processing, .init(statusCode: 103, reasonPhrase: ""), - .noContent, .notModified + .noContent, .notModified, ] for status in responseStatus { let embedded = EmbeddedChannel() - + let writeRecorder = FramePayloadWriteRecorder() XCTAssertNoThrow(try embedded.pipeline.addHandler(writeRecorder).wait()) - XCTAssertNoThrow(try embedded.pipeline.addHandler(HTTP2FramePayloadToHTTP1ClientCodec(httpProtocol: .https, normalizeHTTPHeaders: true)).wait()) + XCTAssertNoThrow( + try embedded.pipeline.addHandler( + HTTP2FramePayloadToHTTP1ClientCodec(httpProtocol: .https, normalizeHTTPHeaders: true) + ).wait() + ) - let requestHead = HTTPRequestHead(version: .http1_1, method: .GET, uri: "/", headers: ["Host": "example.org"]) + let requestHead = HTTPRequestHead( + version: .http1_1, + method: .GET, + uri: "/", + headers: ["Host": "example.org"] + ) XCTAssertNoThrow(try embedded.writeOutbound(HTTPClientRequestPart.head(requestHead))) XCTAssertNoThrow(try embedded.writeOutbound(HTTPClientRequestPart.end(nil))) - - let expectedRequestHeaders = HPACKHeaders([(":path", "/"), (":method", "GET"), (":scheme", "https"), (":authority", "example.org")]) - writeRecorder.flushedWrites[0].assertHeadersFramePayload(endStream: false, - headers: expectedRequestHeaders, - type: .doNotValidate) + + let expectedRequestHeaders = HPACKHeaders([ + (":path", "/"), (":method", "GET"), (":scheme", "https"), (":authority", "example.org"), + ]) + writeRecorder.flushedWrites[0].assertHeadersFramePayload( + endStream: false, + headers: expectedRequestHeaders, + type: .doNotValidate + ) writeRecorder.flushedWrites[1].assertDataFramePayload(endStream: true, payload: ByteBuffer()) - + let responseHeaders = HPACKHeaders(httpHeaders: [":status": "\(status.code)"]) - XCTAssertNoThrow(try embedded.writeInbound(HTTP2Frame.FramePayload.headers(.init(headers: responseHeaders, endStream: true)))) - + XCTAssertNoThrow( + try embedded.writeInbound( + HTTP2Frame.FramePayload.headers(.init(headers: responseHeaders, endStream: true)) + ) + ) + let expectedResponseHead = HTTPResponseHead(version: .http2, status: status) embedded.assertReceivedClientResponsePart(.head(expectedResponseHead)) if status.code >= 200 { @@ -1008,5 +1329,4 @@ final class HTTP2FramePayloadToHTTP1CodecTests: XCTestCase { } } - } diff --git a/Tests/NIOHTTP2Tests/HTTP2InlineStreamMultiplexerTests.swift b/Tests/NIOHTTP2Tests/HTTP2InlineStreamMultiplexerTests.swift index 68b1f3e..77eb5ed 100644 --- a/Tests/NIOHTTP2Tests/HTTP2InlineStreamMultiplexerTests.swift +++ b/Tests/NIOHTTP2Tests/HTTP2InlineStreamMultiplexerTests.swift @@ -12,25 +12,34 @@ // //===----------------------------------------------------------------------===// -import XCTest import Atomics import NIOConcurrencyHelpers import NIOCore import NIOEmbedded import NIOHTTP1 -@testable import NIOHPACK // for HPACKHeaders initializers +import XCTest + +@testable import NIOHPACK // for HPACKHeaders initializers @testable import NIOHTTP2 -private extension Channel { +extension Channel { /// Adds a simple no-op ``HTTP2StreamMultiplexer`` to the pipeline. - func addNoOpInlineMultiplexer(mode: NIOHTTP2Handler.ParserMode, eventLoop: EventLoop) { - XCTAssertNoThrow(try self.pipeline.addHandler(NIOHTTP2Handler(mode: mode, eventLoop: eventLoop, inboundStreamInitializer: { channel in - self.eventLoop.makeSucceededFuture(()) - })).wait()) + fileprivate func addNoOpInlineMultiplexer(mode: NIOHTTP2Handler.ParserMode, eventLoop: EventLoop) { + XCTAssertNoThrow( + try self.pipeline.addHandler( + NIOHTTP2Handler( + mode: mode, + eventLoop: eventLoop, + inboundStreamInitializer: { channel in + self.eventLoop.makeSucceededFuture(()) + } + ) + ).wait() + ) } } -private struct MyError: Error { } +private struct MyError: Error {} typealias IODataWriteRecorder = WriteRecorder @@ -67,8 +76,11 @@ extension IODataWriteRecorder { } extension HPACKHeaders { - static let basicRequestHeaders = HPACKHeaders(headers: [.init(name: ":path", value: "/"), .init(name: ":method", value: "GET"), .init(name: ":scheme", value: "HTTP/2.0")]) - static let basicResponseHeaders = HPACKHeaders(headers: [.init(name: ":status", value: "200")]) + static let basicRequestValues = HPACKHeaders(headers: [ + .init(name: ":path", value: "/"), .init(name: ":method", value: "GET"), + .init(name: ":scheme", value: "HTTP/2.0"), + ]) + static let basicResponseValues = HPACKHeaders(headers: [.init(name: ":status", value: "200")]) } final class HTTP2InlineStreamMultiplexerTests: XCTestCase { @@ -115,7 +127,7 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { typealias InboundIn = HTTP2Frame.FramePayload typealias OutboundOut = HTTP2Frame.FramePayload - let channelReadHook: (ChannelHandlerContext, HTTP2Frame.FramePayload) -> () + let channelReadHook: (ChannelHandlerContext, HTTP2Frame.FramePayload) -> Void init(channelReadHook: @escaping (ChannelHandlerContext, HTTP2Frame.FramePayload) -> Void) { self.channelReadHook = channelReadHook @@ -131,7 +143,10 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { self.channel.addNoOpInlineMultiplexer(mode: .server, eventLoop: self.channel.eventLoop) XCTAssertNoThrow(try connectionSetup()) - let simplePingFrame = HTTP2Frame(streamID: .rootStream, payload: .ping(HTTP2PingData(withInteger: 5), ack: false)) + let simplePingFrame = HTTP2Frame( + streamID: .rootStream, + payload: .ping(HTTP2PingData(withInteger: 5), ack: false) + ) XCTAssertNoThrow(try self.channel.writeInbound(simplePingFrame.encode())) XCTAssertNoThrow(try self.channel.assertReceivedFrame().assertFrameMatches(this: simplePingFrame)) @@ -140,17 +155,24 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { func testHeadersFramesCreateNewChannels() throws { let channelCount = ManagedAtomic(0) - let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop, inboundStreamInitializer: { channel in - channelCount.wrappingIncrement(ordering: .sequentiallyConsistent) - return channel.close() - }) + let http2Handler = NIOHTTP2Handler( + mode: .server, + eventLoop: self.channel.eventLoop, + inboundStreamInitializer: { channel in + channelCount.wrappingIncrement(ordering: .sequentiallyConsistent) + return channel.close() + } + ) XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) XCTAssertNoThrow(try connectionSetup()) // Let's send a bunch of headers frames. for streamID in stride(from: 1, to: 100, by: 2) { - let frame = HTTP2Frame(streamID: HTTP2StreamID(streamID), payload: HTTP2Frame.FramePayload.headers(.init(headers: .basicRequestHeaders))) + let frame = HTTP2Frame( + streamID: HTTP2StreamID(streamID), + payload: HTTP2Frame.FramePayload.headers(.init(headers: .basicRequestValues)) + ) XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) } @@ -160,23 +182,33 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { func testChannelsCloseThemselvesWhenToldTo() throws { let completedChannelCount = ManagedAtomic(0) - let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop, inboundStreamInitializer: { channel in - channel.closeFuture.whenSuccess { completedChannelCount.wrappingIncrement(ordering: .sequentiallyConsistent) } - return channel.pipeline.addHandler(TestHookHandler { context, payload in - guard case .headers(let requestHeaders) = payload else { - preconditionFailure("Expected request headers.") + let http2Handler = NIOHTTP2Handler( + mode: .server, + eventLoop: self.channel.eventLoop, + inboundStreamInitializer: { channel in + channel.closeFuture.whenSuccess { + completedChannelCount.wrappingIncrement(ordering: .sequentiallyConsistent) } - XCTAssertEqual(requestHeaders.headers, .basicRequestHeaders) + return channel.pipeline.addHandler( + TestHookHandler { context, payload in + guard case .headers(let requestHeaders) = payload else { + preconditionFailure("Expected request headers.") + } + XCTAssertEqual(requestHeaders.headers, .basicRequestValues) - let headers = HTTP2Frame.FramePayload.headers(.init(headers: .basicResponseHeaders, endStream: true)) - context.writeAndFlush(NIOAny(headers), promise: nil) - }) - }) + let headers = HTTP2Frame.FramePayload.headers( + .init(headers: .basicResponseValues, endStream: true) + ) + context.writeAndFlush(NIOAny(headers), promise: nil) + } + ) + } + ) XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) XCTAssertNoThrow(try connectionSetup()) // Let's send a bunch of headers frames with endStream on them. This should open some streams. - let headers = HTTP2Frame.FramePayload.headers(.init(headers: .basicRequestHeaders, endStream: true)) + let headers = HTTP2Frame.FramePayload.headers(.init(headers: .basicRequestValues, endStream: true)) let streamIDs = stride(from: 1, to: 100, by: 2).map { HTTP2StreamID($0) } for streamID in streamIDs { XCTAssertNoThrow(try self.channel.writeInbound(HTTP2Frame(streamID: streamID, payload: headers).encode())) @@ -197,20 +229,29 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { // First, set up the frames we want to send/receive. let streamID = HTTP2StreamID(1) - let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestHeaders, endStream: true))) + let frame = HTTP2Frame( + streamID: streamID, + payload: .headers(.init(headers: .basicRequestValues, endStream: true)) + ) let rstStreamFrame = HTTP2Frame(streamID: streamID, payload: .rstStream(.cancel)) - let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop, inboundStreamInitializer: { channel in - closeError.withLockedValue { closeError in - XCTAssertNil(closeError) - } - channel.closeFuture.whenFailure { failureError in + let http2Handler = NIOHTTP2Handler( + mode: .server, + eventLoop: self.channel.eventLoop, + inboundStreamInitializer: { channel in closeError.withLockedValue { closeError in - closeError = failureError + XCTAssertNil(closeError) } + channel.closeFuture.whenFailure { failureError in + closeError.withLockedValue { closeError in + closeError = failureError + } + } + return channel.pipeline.addHandler( + FramePayloadExpecter(expectedPayload: [frame.payload, rstStreamFrame.payload]) + ) } - return channel.pipeline.addHandler(FramePayloadExpecter(expectedPayload: [frame.payload, rstStreamFrame.payload])) - }) + ) XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) XCTAssertNoThrow(try connectionSetup()) @@ -227,8 +268,10 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { // At this stage the stream should be closed with the appropriate error code. closeError.withLockedValue { error in - XCTAssertEqual(error as? NIOHTTP2Errors.StreamClosed, - NIOHTTP2Errors.streamClosed(streamID: streamID, errorCode: .cancel)) + XCTAssertEqual( + error as? NIOHTTP2Errors.StreamClosed, + NIOHTTP2Errors.streamClosed(streamID: streamID, errorCode: .cancel) + ) } XCTAssertNoThrow(try self.channel.finish()) } @@ -236,20 +279,30 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { func testChannelsCloseAfterGoawayFrameFirstThenEvent() throws { // First, set up the frames we want to send/receive. let streamID = HTTP2StreamID(1) - let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestHeaders, endStream: true))) - let goAwayFrame = HTTP2Frame(streamID: .rootStream, payload: .goAway(lastStreamID: .rootStream, errorCode: .http11Required, opaqueData: nil)) + let frame = HTTP2Frame( + streamID: streamID, + payload: .headers(.init(headers: .basicRequestValues, endStream: true)) + ) + let goAwayFrame = HTTP2Frame( + streamID: .rootStream, + payload: .goAway(lastStreamID: .rootStream, errorCode: .http11Required, opaqueData: nil) + ) - let http2Handler = NIOHTTP2Handler(mode: .client, eventLoop: self.channel.eventLoop, inboundStreamInitializer: { channel in - XCTFail() - return channel.eventLoop.makeSucceededVoidFuture() - }) + let http2Handler = NIOHTTP2Handler( + mode: .client, + eventLoop: self.channel.eventLoop, + inboundStreamInitializer: { channel in + XCTFail() + return channel.eventLoop.makeSucceededVoidFuture() + } + ) XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) XCTAssertNoThrow(try connectionSetup(mode: .client)) // Let's open the stream up. let multiplexer = try http2Handler.multiplexer.wait() let streamFuture = multiplexer.createStreamChannel { channel in - return channel.eventLoop.makeSucceededVoidFuture() + channel.eventLoop.makeSucceededVoidFuture() } (self.channel.eventLoop as! EmbeddedEventLoop).run() @@ -264,8 +317,10 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { (self.channel.eventLoop as! EmbeddedEventLoop).run() XCTAssertThrowsError(try stream.closeFuture.wait()) { closeError in - XCTAssertEqual(closeError as? NIOHTTP2Errors.StreamClosed, - NIOHTTP2Errors.streamClosed(streamID: streamID, errorCode: .cancel)) + XCTAssertEqual( + closeError as? NIOHTTP2Errors.StreamClosed, + NIOHTTP2Errors.streamClosed(streamID: streamID, errorCode: .cancel) + ) } // At this stage the stream should be closed with the appropriate manufactured error code. XCTAssertNoThrow(try self.channel.finish()) @@ -273,9 +328,13 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { func testClosingIdleChannels() throws { let frameReceiver = IODataWriteRecorder() - let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop, inboundStreamInitializer: { channel in - return channel.close() - }) + let http2Handler = NIOHTTP2Handler( + mode: .server, + eventLoop: self.channel.eventLoop, + inboundStreamInitializer: { channel in + channel.close() + } + ) XCTAssertNoThrow(try self.channel.pipeline.addHandler(frameReceiver).wait()) XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) XCTAssertNoThrow(try connectionSetup()) @@ -284,7 +343,7 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { // Let's send a bunch of headers frames. These will all be answered by RST_STREAM frames. let streamIDs = stride(from: 1, to: 100, by: 2).map { HTTP2StreamID($0) } for streamID in streamIDs { - let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestHeaders))) + let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestValues))) XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) } @@ -310,7 +369,7 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { let frameReceiver = IODataWriteRecorder() let channelPromise: EventLoopPromise = self.channel.eventLoop.makePromise() let http2Handler = NIOHTTP2Handler( - mode: .server, + mode: .server, eventLoop: self.channel.eventLoop, inboundStreamInitializer: { channel in channelPromise.succeed(channel) @@ -326,7 +385,7 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { // Let's send a headers frame to open the stream. let streamID = HTTP2StreamID(1) - let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestHeaders))) + let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestValues))) XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) // The channel should now be active. @@ -354,7 +413,7 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { let frameReceiver = IODataWriteRecorder() let channelPromise: EventLoopPromise = self.channel.eventLoop.makePromise() let http2Handler = NIOHTTP2Handler( - mode: .server, + mode: .server, eventLoop: self.channel.eventLoop, inboundStreamInitializer: { channel in channelPromise.succeed(channel) @@ -370,7 +429,7 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { // Let's send a headers frame to open the stream. let streamID = HTTP2StreamID(1) - let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestHeaders))) + let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestValues))) XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) // The channel should now be active. @@ -398,7 +457,7 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { let frameReceiver = IODataWriteRecorder() let channelPromise: EventLoopPromise = self.channel.eventLoop.makePromise() let http2Handler = NIOHTTP2Handler( - mode: .server, + mode: .server, eventLoop: self.channel.eventLoop, inboundStreamInitializer: { channel in channelPromise.succeed(channel) @@ -412,7 +471,7 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { // Let's send a headers frame to open the stream. let streamID = HTTP2StreamID(1) - let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestHeaders))) + let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestValues))) XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) // The channel should now be active. @@ -461,7 +520,7 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { let frameReceiver = IODataWriteRecorder() let channelPromise: EventLoopPromise = self.channel.eventLoop.makePromise() let http2Handler = NIOHTTP2Handler( - mode: .server, + mode: .server, eventLoop: self.channel.eventLoop, inboundStreamInitializer: { channel in channelPromise.succeed(channel) @@ -475,7 +534,7 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { // Let's send a headers frame to open the stream. let streamID = HTTP2StreamID(1) - let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestHeaders))) + let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestValues))) XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) // The channel should now be active. @@ -501,7 +560,10 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { let (flushedFrame, _) = try frameDecoder.nextFrame()! flushedFrame.assertRstStreamFrame(streamID: streamID, errorCode: .cancel) closeError.withLockedValue { closeError in - XCTAssertEqual(closeError as? NIOHTTP2Errors.StreamClosed, NIOHTTP2Errors.streamClosed(streamID: streamID, errorCode: .cancel)) + XCTAssertEqual( + closeError as? NIOHTTP2Errors.StreamClosed, + NIOHTTP2Errors.streamClosed(streamID: streamID, errorCode: .cancel) + ) } XCTAssertNoThrow(try self.channel.finish()) @@ -510,18 +572,22 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { func testFramesAreNotDeliveredUntilStreamIsSetUp() throws { let channelPromise: EventLoopPromise = self.channel.eventLoop.makePromise() let setupCompletePromise: EventLoopPromise = self.channel.eventLoop.makePromise() - let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop, inboundStreamInitializer: { channel in - channelPromise.succeed(channel) - return channel.pipeline.addHandler(InboundFramePayloadRecorder()).flatMap { - setupCompletePromise.futureResult + let http2Handler = NIOHTTP2Handler( + mode: .server, + eventLoop: self.channel.eventLoop, + inboundStreamInitializer: { channel in + channelPromise.succeed(channel) + return channel.pipeline.addHandler(InboundFramePayloadRecorder()).flatMap { + setupCompletePromise.futureResult + } } - }) + ) XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) XCTAssertNoThrow(try connectionSetup()) // Let's send a headers frame to open the stream. let streamID = HTTP2StreamID(1) - let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestHeaders))) + let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestValues))) XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) // The channel should now be available, but no frames should have been received on either the parent or child channel. @@ -531,7 +597,10 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { XCTAssertEqual(frameRecorder.receivedFrames.count, 0) // Send a few data frames for this stream, which should also not go through. - let dataFrame = HTTP2Frame(streamID: streamID, payload: .data(.init(data: .byteBuffer(ByteBuffer(string: "Hello, world!"))))) + let dataFrame = HTTP2Frame( + streamID: streamID, + payload: .data(.init(data: .byteBuffer(ByteBuffer(string: "Hello, world!")))) + ) for _ in 0..<5 { XCTAssertNoThrow(try self.channel.writeInbound(dataFrame.encode())) } @@ -561,12 +630,16 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { let writeRecorder = IODataWriteRecorder() let channelPromise: EventLoopPromise = self.channel.eventLoop.makePromise() let setupCompletePromise: EventLoopPromise = self.channel.eventLoop.makePromise() - let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop, inboundStreamInitializer: { channel in - channelPromise.succeed(channel) - return channel.pipeline.addHandler(InboundFramePayloadRecorder()).flatMap { - setupCompletePromise.futureResult + let http2Handler = NIOHTTP2Handler( + mode: .server, + eventLoop: self.channel.eventLoop, + inboundStreamInitializer: { channel in + channelPromise.succeed(channel) + return channel.pipeline.addHandler(InboundFramePayloadRecorder()).flatMap { + setupCompletePromise.futureResult + } } - }) + ) XCTAssertNoThrow(try self.channel.pipeline.addHandler(writeRecorder).wait()) XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) XCTAssertNoThrow(try connectionSetup()) @@ -574,10 +647,13 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { // Let's send a headers frame to open the stream, along with some DATA frames. let streamID = HTTP2StreamID(1) - let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestHeaders))) + let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestValues))) XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) - let dataFrame = try HTTP2Frame(streamID: streamID, payload: .data(.init(data: .byteBuffer(ByteBuffer(string: "Hello, world!"))))).encode() + let dataFrame = try HTTP2Frame( + streamID: streamID, + payload: .data(.init(data: .byteBuffer(ByteBuffer(string: "Hello, world!")))) + ).encode() for _ in 0..<5 { XCTAssertNoThrow(try self.channel.writeInbound(dataFrame)) } @@ -630,10 +706,14 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { func testFlushingOneChannelDoesntFlushThemAll() async throws { let writeTracker = IODataWriteRecorder() let (channelsStream, channelsContinuation) = AsyncStream.makeStream(of: Channel.self) - let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop, inboundStreamInitializer: { channel in - channelsContinuation.yield(channel) - return channel.eventLoop.makeSucceededFuture(()) - }) + let http2Handler = NIOHTTP2Handler( + mode: .server, + eventLoop: self.channel.eventLoop, + inboundStreamInitializer: { channel in + channelsContinuation.yield(channel) + return channel.eventLoop.makeSucceededFuture(()) + } + ) XCTAssertNoThrow(try self.channel.pipeline.addHandler(writeTracker).wait()) XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) XCTAssertNoThrow(try connectionSetup()) @@ -643,7 +723,10 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { let firstStreamID = HTTP2StreamID(1) let secondStreamID = HTTP2StreamID(3) for streamID in [firstStreamID, secondStreamID] { - let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestHeaders, endStream: true))) + let frame = HTTP2Frame( + streamID: streamID, + payload: .headers(.init(headers: .basicRequestValues, endStream: true)) + ) XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) } @@ -654,7 +737,7 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { // We will now write a headers frame to each channel. Neither frame should be written to the connection. To verify this // we will flush the parent channel. for channel in [firstStreamChannel, secondStreamChannel] { - let frame = HTTP2Frame.FramePayload.headers(.init(headers: .basicResponseHeaders)) + let frame = HTTP2Frame.FramePayload.headers(.init(headers: .basicResponseValues)) channel.write(frame, promise: nil) } self.channel.flush() @@ -673,23 +756,30 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { func testUnflushedWritesFailOnError() throws { let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) - let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop, inboundStreamInitializer: { channel in - childChannelPromise.succeed(channel) - return channel.eventLoop.makeSucceededVoidFuture() - }) + let http2Handler = NIOHTTP2Handler( + mode: .server, + eventLoop: self.channel.eventLoop, + inboundStreamInitializer: { channel in + childChannelPromise.succeed(channel) + return channel.eventLoop.makeSucceededVoidFuture() + } + ) XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) XCTAssertNoThrow(try connectionSetup()) // Let's open a stream. let streamID = HTTP2StreamID(1) - let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestHeaders, endStream: true))) + let frame = HTTP2Frame( + streamID: streamID, + payload: .headers(.init(headers: .basicRequestValues, endStream: true)) + ) XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) XCTAssertNotNil(channel) let childChannel = try childChannelPromise.futureResult.wait() // We will now write a headers frame to the channel, but don't flush it. let writeError = NIOLockedValueBox(nil) - let responseFrame = HTTP2Frame.FramePayload.headers(.init(headers: .basicResponseHeaders)) + let responseFrame = HTTP2Frame.FramePayload.headers(.init(headers: .basicResponseValues)) childChannel.write(responseFrame).whenFailure { error in writeError.withLockedValue { writeError in writeError = error @@ -712,24 +802,35 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { func testWritesFailOnClosedStreamChannels() throws { let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) - let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop, inboundStreamInitializer: { channel in - childChannelPromise.succeed(channel) - return channel.pipeline.addHandler(TestHookHandler { context, payload in - guard case .headers(let requestHeaders) = payload else { - preconditionFailure("Expected request headers.") - } - XCTAssertEqual(requestHeaders.headers, .basicRequestHeaders) + let http2Handler = NIOHTTP2Handler( + mode: .server, + eventLoop: self.channel.eventLoop, + inboundStreamInitializer: { channel in + childChannelPromise.succeed(channel) + return channel.pipeline.addHandler( + TestHookHandler { context, payload in + guard case .headers(let requestHeaders) = payload else { + preconditionFailure("Expected request headers.") + } + XCTAssertEqual(requestHeaders.headers, .basicRequestValues) - let headers = HTTP2Frame.FramePayload.headers(.init(headers: .basicResponseHeaders, endStream: true)) - context.writeAndFlush(NIOAny(headers), promise: nil) - }) - }) + let headers = HTTP2Frame.FramePayload.headers( + .init(headers: .basicResponseValues, endStream: true) + ) + context.writeAndFlush(NIOAny(headers), promise: nil) + } + ) + } + ) XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) XCTAssertNoThrow(try connectionSetup()) // Let's open a stream. let streamID = HTTP2StreamID(1) - let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestHeaders, endStream: true))) + let frame = HTTP2Frame( + streamID: streamID, + payload: .headers(.init(headers: .basicRequestValues, endStream: true)) + ) XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) XCTAssertNotNil(channel) @@ -737,7 +838,7 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { // We will now write a headers frame to the channel. This should fail immediately. let writeError = NIOLockedValueBox(nil) - let responseFrame = HTTP2Frame.FramePayload.headers(.init(headers: .basicRequestHeaders)) + let responseFrame = HTTP2Frame.FramePayload.headers(.init(headers: .basicRequestValues)) childChannel.write(responseFrame).whenFailure { error in writeError.withLockedValue { writeError in writeError = error @@ -753,36 +854,40 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { func testReadPullsInAllFrames() throws { let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) let frameRecorder = InboundFramePayloadRecorder() - let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop, inboundStreamInitializer: { channel -> EventLoopFuture in - childChannelPromise.succeed(channel) + let http2Handler = NIOHTTP2Handler( + mode: .server, + eventLoop: self.channel.eventLoop, + inboundStreamInitializer: { channel -> EventLoopFuture in + childChannelPromise.succeed(channel) - // We're going to disable autoRead on this channel. - return channel.getOption(ChannelOptions.autoRead).map { - XCTAssertTrue($0) - }.flatMap { - channel.setOption(ChannelOptions.autoRead, value: false) - }.flatMap { - channel.getOption(ChannelOptions.autoRead) - }.map { - XCTAssertFalse($0) - }.flatMap { - channel.pipeline.addHandler(frameRecorder) + // We're going to disable autoRead on this channel. + return channel.getOption(ChannelOptions.autoRead).map { + XCTAssertTrue($0) + }.flatMap { + channel.setOption(ChannelOptions.autoRead, value: false) + }.flatMap { + channel.getOption(ChannelOptions.autoRead) + }.map { + XCTAssertFalse($0) + }.flatMap { + channel.pipeline.addHandler(frameRecorder) + } } - }) + ) XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) XCTAssertNoThrow(try connectionSetup()) // Let's open a stream. let streamID = HTTP2StreamID(1) - let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestHeaders))) + let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestValues))) XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) - let childChannel = try childChannelPromise.futureResult.wait() // Now we're going to deliver 5 data frames for this stream. let payloadBuffer = ByteBuffer(string: "Hello, world!") - let dataFrame = try HTTP2Frame(streamID: streamID, payload: .data(.init(data: .byteBuffer(payloadBuffer)))).encode() + let dataFrame = try HTTP2Frame(streamID: streamID, payload: .data(.init(data: .byteBuffer(payloadBuffer)))) + .encode() for _ in 0..<5 { XCTAssertNoThrow(try self.channel.writeInbound(dataFrame)) } @@ -812,7 +917,8 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { let autoRead = ManagedAtomic(false) let frameRecorders = NIOLockedValueBox<[HTTP2StreamID: InboundFramePayloadRecorder]>([:]) - let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop) { channel -> EventLoopFuture in + let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop) { + channel -> EventLoopFuture in let recorder = InboundFramePayloadRecorder() frameRecorders.withLockedValue { frameRecorders in let expectedStreamID = frameRecorders.count * 2 + 1 @@ -832,7 +938,7 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { // Let's open two streams. for streamID in [firstStreamID, secondStreamID] { - let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestHeaders))) + let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestValues))) XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) } @@ -862,7 +968,8 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { func testReadWillCauseAutomaticFrameDelivery() throws { let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) let frameRecorder = InboundFramePayloadRecorder() - let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop) { channel -> EventLoopFuture in + let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop) { + channel -> EventLoopFuture in childChannelPromise.succeed(channel) // We're going to disable autoRead on this channel. @@ -875,10 +982,9 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { // Let's open a stream. let streamID = HTTP2StreamID(1) - let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestHeaders))) + let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestValues))) XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) - let childChannel = try childChannelPromise.futureResult.wait() // This stream should have seen no frames. @@ -893,7 +999,10 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { XCTAssertEqual(frameRecorder.receivedFrames.count, 1) // Now deliver a data frame. - let dataFrame = try HTTP2Frame(streamID: streamID, payload: .data(.init(data: .byteBuffer(ByteBuffer(string: "Hello, world!"))))).encode() + let dataFrame = try HTTP2Frame( + streamID: streamID, + payload: .data(.init(data: .byteBuffer(ByteBuffer(string: "Hello, world!")))) + ).encode() XCTAssertNoThrow(try self.channel.writeInbound(dataFrame)) // This frame should have been immediately delivered. @@ -910,7 +1019,8 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) let readCounter = ReadCounter() let frameRecorder = InboundFramePayloadRecorder() - let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop) { channel -> EventLoopFuture in + let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop) { + channel -> EventLoopFuture in childChannelPromise.succeed(channel) // We're going to disable autoRead on this channel. @@ -924,10 +1034,9 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { // Let's open a stream. let streamID = HTTP2StreamID(1) - let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestHeaders))) + let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestValues))) XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) - let childChannel = try childChannelPromise.futureResult.wait() // This stream should have seen no frames. @@ -953,7 +1062,10 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { } // Now deliver a data frame. - let dataFrame = try HTTP2Frame(streamID: streamID, payload: .data(.init(data: .byteBuffer(ByteBuffer(string: "Hello, world!"))))).encode() + let dataFrame = try HTTP2Frame( + streamID: streamID, + payload: .data(.init(data: .byteBuffer(ByteBuffer(string: "Hello, world!")))) + ).encode() XCTAssertNoThrow(try self.channel.writeInbound(dataFrame)) // This frame should have been immediately delivered. No extra call to read. @@ -991,27 +1103,39 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { func testHandlersAreRemovedOnClosure() throws { let handlerRemoved = ManagedAtomic(false) let handlerRemovedPromise: EventLoopPromise = self.channel.eventLoop.makePromise() - handlerRemovedPromise.futureResult.whenComplete { _ in handlerRemoved.store(true, ordering: .sequentiallyConsistent) } + handlerRemovedPromise.futureResult.whenComplete { _ in + handlerRemoved.store(true, ordering: .sequentiallyConsistent) + } - let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop, inboundStreamInitializer: { channel in - return channel.pipeline.addHandlers([ - HandlerRemovedHandler(removedPromise: handlerRemovedPromise), - TestHookHandler { context, payload in - guard case .headers(let requestHeaders) = payload else { - preconditionFailure("Expected request headers.") - } - XCTAssertEqual(requestHeaders.headers, .basicRequestHeaders) + let http2Handler = NIOHTTP2Handler( + mode: .server, + eventLoop: self.channel.eventLoop, + inboundStreamInitializer: { channel in + channel.pipeline.addHandlers([ + HandlerRemovedHandler(removedPromise: handlerRemovedPromise), + TestHookHandler { context, payload in + guard case .headers(let requestHeaders) = payload else { + preconditionFailure("Expected request headers.") + } + XCTAssertEqual(requestHeaders.headers, .basicRequestValues) - let headers = HTTP2Frame.FramePayload.headers(.init(headers: .basicResponseHeaders, endStream: true)) - context.writeAndFlush(NIOAny(headers), promise: nil) - }]) - }) + let headers = HTTP2Frame.FramePayload.headers( + .init(headers: .basicResponseValues, endStream: true) + ) + context.writeAndFlush(NIOAny(headers), promise: nil) + }, + ]) + } + ) XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) XCTAssertNoThrow(try connectionSetup()) // Let's open a stream. let streamID = HTTP2StreamID(1) - let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestHeaders, endStream: true))) + let frame = HTTP2Frame( + streamID: streamID, + payload: .headers(.init(headers: .basicRequestValues, endStream: true)) + ) XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) // No handlerRemoved so far. @@ -1027,27 +1151,35 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { func testHandlersAreRemovedOnClosureWithError() throws { let handlerRemoved = ManagedAtomic(false) let handlerRemovedPromise: EventLoopPromise = self.channel.eventLoop.makePromise() - handlerRemovedPromise.futureResult.whenComplete { _ in handlerRemoved.store(true, ordering: .sequentiallyConsistent) } + handlerRemovedPromise.futureResult.whenComplete { _ in + handlerRemoved.store(true, ordering: .sequentiallyConsistent) + } - let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop) { channel in - return channel.pipeline.addHandlers([ + let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop) { channel in + channel.pipeline.addHandlers([ HandlerRemovedHandler(removedPromise: handlerRemovedPromise), TestHookHandler { context, payload in guard case .headers(let requestHeaders) = payload else { preconditionFailure("Expected request headers.") } - XCTAssertEqual(requestHeaders.headers, .basicRequestHeaders) + XCTAssertEqual(requestHeaders.headers, .basicRequestValues) - let headers = HTTP2Frame.FramePayload.headers(.init(headers: .basicResponseHeaders, endStream: true)) + let headers = HTTP2Frame.FramePayload.headers( + .init(headers: .basicResponseValues, endStream: true) + ) context.writeAndFlush(NIOAny(headers), promise: nil) - }]) + }, + ]) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) XCTAssertNoThrow(try connectionSetup()) // Let's open a stream. let streamID = HTTP2StreamID(1) - let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestHeaders, endStream: true))) + let frame = HTTP2Frame( + streamID: streamID, + payload: .headers(.init(headers: .basicRequestValues, endStream: true)) + ) XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) // No handlerRemoved so far. @@ -1064,13 +1196,18 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { let configurePromise: EventLoopPromise = self.channel.eventLoop.makePromise() let createdChannelCount = ManagedAtomic(0) let configuredChannelCount = ManagedAtomic(0) - let streamIDs = NIOLockedValueBox(Array()) - let http2Handler = NIOHTTP2Handler(mode: .client, eventLoop: self.channel.eventLoop, inboundStreamInitializer: { channel in - XCTFail("Must not be called") - return channel.eventLoop.makeFailedFuture(MyError()) - }) + let streamIDs = NIOLockedValueBox([HTTP2StreamID]()) + let http2Handler = NIOHTTP2Handler( + mode: .client, + eventLoop: self.channel.eventLoop, + inboundStreamInitializer: { channel in + XCTFail("Must not be called") + return channel.eventLoop.makeFailedFuture(MyError()) + } + ) XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) - XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) // to make the channel active + // to make the channel active + XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) let multiplexer = try http2Handler.multiplexer.wait() for _ in 0..<3 { @@ -1082,7 +1219,8 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { channelPromise.futureResult.whenSuccess { channel in configuredChannelCount.wrappingIncrement(ordering: .sequentiallyConsistent) // Write some headers: the flush will trigger a stream ID to be assigned to the channel. - channel.writeAndFlush(HTTP2Frame.FramePayload.headers(.init(headers: .basicRequestHeaders))).whenSuccess { + channel.writeAndFlush(HTTP2Frame.FramePayload.headers(.init(headers: .basicRequestValues))).whenSuccess + { channel.getOption(HTTP2StreamChannelOptions.streamID).whenSuccess { streamID in streamIDs.withLockedValue { streamIDs in streamIDs.append(streamID) @@ -1118,10 +1256,14 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) - let http2Handler = NIOHTTP2Handler(mode: .client, eventLoop: self.channel.eventLoop, inboundStreamInitializer: { channel in - XCTFail("Must not be called") - return channel.eventLoop.makeFailedFuture(MyError()) - }) + let http2Handler = NIOHTTP2Handler( + mode: .client, + eventLoop: self.channel.eventLoop, + inboundStreamInitializer: { channel in + XCTFail("Must not be called") + return channel.eventLoop.makeFailedFuture(MyError()) + } + ) XCTAssertNoThrow(try self.channel.pipeline.addHandler(writeRecorder).wait()) XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) (self.channel.eventLoop as! EmbeddedEventLoop).run() @@ -1134,10 +1276,9 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { } (self.channel.eventLoop as! EmbeddedEventLoop).run() - let childChannel = try childChannelPromise.futureResult.wait() - childChannel.writeAndFlush(HTTP2Frame.FramePayload.headers(.init(headers: .basicRequestHeaders)), promise: nil) + childChannel.writeAndFlush(HTTP2Frame.FramePayload.headers(.init(headers: .basicRequestValues)), promise: nil) XCTAssertEqual(writeRecorder.flushedWrites.count, 0) @@ -1152,10 +1293,14 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { let configurePromise: EventLoopPromise = self.channel.eventLoop.makePromise() let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) - let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop, inboundStreamInitializer: { channel in - XCTFail("Must not be called") - return channel.eventLoop.makeFailedFuture(MyError()) - }) + let http2Handler = NIOHTTP2Handler( + mode: .server, + eventLoop: self.channel.eventLoop, + inboundStreamInitializer: { channel in + XCTFail("Must not be called") + return channel.eventLoop.makeFailedFuture(MyError()) + } + ) XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) let multiplexer = try http2Handler.multiplexer.wait() multiplexer.createStreamChannel(promise: nil) { channel in @@ -1167,7 +1312,8 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { let childChannel = try childChannelPromise.futureResult.wait() let writeError = NIOLockedValueBox(nil) - childChannel.writeAndFlush(HTTP2Frame.FramePayload.headers(.init(headers: .basicRequestHeaders))).whenFailure { error in + childChannel.writeAndFlush(HTTP2Frame.FramePayload.headers(.init(headers: .basicRequestValues))).whenFailure { + error in writeError.withLockedValue { writeError in writeError = error } @@ -1189,15 +1335,19 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { let configurePromise: EventLoopPromise = self.channel.eventLoop.makePromise() let writeRecorder = FrameWriteRecorder() - let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop, inboundStreamInitializer: { channel in - XCTFail("Must not be called") - return channel.eventLoop.makeFailedFuture(MyError()) - }) + let http2Handler = NIOHTTP2Handler( + mode: .server, + eventLoop: self.channel.eventLoop, + inboundStreamInitializer: { channel in + XCTFail("Must not be called") + return channel.eventLoop.makeFailedFuture(MyError()) + } + ) XCTAssertNoThrow(try self.channel.pipeline.addHandler(writeRecorder).wait()) XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) let multiplexer = try http2Handler.multiplexer.wait() multiplexer.createStreamChannel(promise: nil) { channel in - return configurePromise.futureResult + configurePromise.futureResult } (self.channel.eventLoop as! EmbeddedEventLoop).run() @@ -1217,10 +1367,14 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { XCTFail("Activation promise must not fail") } - let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop, inboundStreamInitializer: { channel in - XCTFail("Must not be called") - return channel.eventLoop.makeFailedFuture(MyError()) - }) + let http2Handler = NIOHTTP2Handler( + mode: .server, + eventLoop: self.channel.eventLoop, + inboundStreamInitializer: { channel in + XCTFail("Must not be called") + return channel.eventLoop.makeFailedFuture(MyError()) + } + ) XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) let multiplexer = try http2Handler.multiplexer.wait() multiplexer.createStreamChannel(promise: nil) { channel in @@ -1247,10 +1401,14 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { XCTFail("Activation promise must not fail") } - let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop, inboundStreamInitializer: { channel in - XCTFail("Must not be called") - return channel.eventLoop.makeFailedFuture(MyError()) - }) + let http2Handler = NIOHTTP2Handler( + mode: .server, + eventLoop: self.channel.eventLoop, + inboundStreamInitializer: { channel in + XCTFail("Must not be called") + return channel.eventLoop.makeFailedFuture(MyError()) + } + ) XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(ipAddress: "127.0.0.1", port: 8765)).wait()) @@ -1279,10 +1437,14 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { XCTFail("Activation promise must not fail") } - let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop, inboundStreamInitializer: { channel in - let activeRecorder = ActiveHandler(activatedPromise: activePromise) - return channel.pipeline.addHandler(activeRecorder) - }) + let http2Handler = NIOHTTP2Handler( + mode: .server, + eventLoop: self.channel.eventLoop, + inboundStreamInitializer: { channel in + let activeRecorder = ActiveHandler(activatedPromise: activePromise) + return channel.pipeline.addHandler(activeRecorder) + } + ) XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) XCTAssertNoThrow(try connectionSetup()) self.channel.pipeline.fireChannelActive() @@ -1290,7 +1452,7 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { // Open a new stream. XCTAssertFalse(activated.load(ordering: .sequentiallyConsistent)) let streamID = HTTP2StreamID(1) - let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestHeaders))) + let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestValues))) XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) XCTAssertTrue(activated.load(ordering: .sequentiallyConsistent)) @@ -1301,7 +1463,10 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { self.channel.addNoOpInlineMultiplexer(mode: .server, eventLoop: self.channel.eventLoop) XCTAssertNoThrow(try connectionSetup()) - let simplePingFrame = HTTP2Frame(streamID: 106, payload: .priority(.init(exclusive: true, dependency: .rootStream, weight: 15))) + let simplePingFrame = HTTP2Frame( + streamID: 106, + payload: .priority(.init(exclusive: true, dependency: .rootStream, weight: 15)) + ) XCTAssertNoThrow(try self.channel.writeInbound(simplePingFrame.encode())) XCTAssertNoThrow(try self.channel.assertReceivedFrame().assertFrameMatches(this: simplePingFrame)) @@ -1327,10 +1492,14 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { func testCreatedChildChannelCanBeClosedImmediately() throws { let closed = ManagedAtomic(false) - let http2Handler = NIOHTTP2Handler(mode: .client, eventLoop: self.channel.eventLoop, inboundStreamInitializer: { channel in - XCTFail("Must not be called") - return channel.eventLoop.makeFailedFuture(MyError()) - }) + let http2Handler = NIOHTTP2Handler( + mode: .client, + eventLoop: self.channel.eventLoop, + inboundStreamInitializer: { channel in + XCTFail("Must not be called") + return channel.eventLoop.makeFailedFuture(MyError()) + } + ) XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) XCTAssertFalse(closed.load(ordering: .sequentiallyConsistent)) @@ -1347,16 +1516,20 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { func testCreatedChildChannelCanBeClosedBeforeWritingHeaders() throws { let closed = ManagedAtomic(false) - let http2Handler = NIOHTTP2Handler(mode: .client, eventLoop: self.channel.eventLoop, inboundStreamInitializer: { channel in - XCTFail("Must not be called") - return channel.eventLoop.makeFailedFuture(MyError()) - }) + let http2Handler = NIOHTTP2Handler( + mode: .client, + eventLoop: self.channel.eventLoop, + inboundStreamInitializer: { channel in + XCTFail("Must not be called") + return channel.eventLoop.makeFailedFuture(MyError()) + } + ) XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) let channelPromise = self.channel.eventLoop.makePromise(of: Channel.self) let multiplexer = try http2Handler.multiplexer.wait() multiplexer.createStreamChannel(promise: channelPromise) { channel in - return channel.eventLoop.makeSucceededFuture(()) + channel.eventLoop.makeSucceededFuture(()) } self.channel.embeddedEventLoop.run() @@ -1378,12 +1551,16 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { // We need to activate the underlying channel here. XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(ipAddress: "127.0.0.1", port: 80)).wait()) - let http2Handler = NIOHTTP2Handler(mode: .client, eventLoop: self.channel.eventLoop, inboundStreamInitializer: { channel in - XCTFail("Must not be called") - return channel.eventLoop.makeFailedFuture(MyError()) - }) + let http2Handler = NIOHTTP2Handler( + mode: .client, + eventLoop: self.channel.eventLoop, + inboundStreamInitializer: { channel in + XCTFail("Must not be called") + return channel.eventLoop.makeFailedFuture(MyError()) + } + ) XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) - XCTAssertEqual(try self.channel.readAllBuffers().count, 2) // magic & settings + XCTAssertEqual(try self.channel.readAllBuffers().count, 2) // magic & settings XCTAssertFalse(closed.load(ordering: .sequentiallyConsistent)) let multiplexer = try http2Handler.multiplexer.wait() @@ -1403,17 +1580,21 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { // We need to activate the underlying channel here. XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(ipAddress: "127.0.0.1", port: 80)).wait()) - let http2Handler = NIOHTTP2Handler(mode: .client, eventLoop: self.channel.eventLoop, inboundStreamInitializer: { channel in - XCTFail("Must not be called") - return channel.eventLoop.makeFailedFuture(MyError()) - }) + let http2Handler = NIOHTTP2Handler( + mode: .client, + eventLoop: self.channel.eventLoop, + inboundStreamInitializer: { channel in + XCTFail("Must not be called") + return channel.eventLoop.makeFailedFuture(MyError()) + } + ) XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) - XCTAssertEqual(try self.channel.readAllBuffers().count, 2) // magic & settings + XCTAssertEqual(try self.channel.readAllBuffers().count, 2) // magic & settings let channelPromise = self.channel.eventLoop.makePromise(of: Channel.self) let multiplexer = try http2Handler.multiplexer.wait() multiplexer.createStreamChannel(promise: channelPromise) { channel in - return channel.eventLoop.makeSucceededFuture(()) + channel.eventLoop.makeSucceededFuture(()) } self.channel.embeddedEventLoop.run() @@ -1436,25 +1617,33 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { XCTAssertNoThrow(try self.channel.pipeline.addHandler(flushCounter).wait()) // Add a server-mode multiplexer that will add an auto-response handler. - let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop, inboundStreamInitializer: { channel in - channel.pipeline.addHandler(QuickFramePayloadResponseHandler()) - }) + let http2Handler = NIOHTTP2Handler( + mode: .server, + eventLoop: self.channel.eventLoop, + inboundStreamInitializer: { channel in + channel.pipeline.addHandler(QuickFramePayloadResponseHandler()) + } + ) XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) XCTAssertNoThrow(try connectionSetup()) // We're going to send in 10 request frames. - let requestHeaders = HPACKHeaders([(":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https")]) - XCTAssertEqual(flushCounter.flushCount, 2) // two flushes in connection setup + let requestHeaders = HPACKHeaders([ + (":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https"), + ]) + XCTAssertEqual(flushCounter.flushCount, 2) // two flushes in connection setup - let framesToSend = stride(from: 1, through: 19, by: 2).map { HTTP2Frame(streamID: HTTP2StreamID($0), payload: .headers(.init(headers: requestHeaders, endStream: true))) } + let framesToSend = stride(from: 1, through: 19, by: 2).map { + HTTP2Frame(streamID: HTTP2StreamID($0), payload: .headers(.init(headers: requestHeaders, endStream: true))) + } for frame in framesToSend { self.channel.pipeline.fireChannelRead(NIOAny(try frame.encode())) } self.channel.embeddedEventLoop.run() // Response frames should have been written, but no flushes, so they aren't visible. - XCTAssertEqual(try self.channel.decodedSentFrames().count, 2) // 2 for handler setup - XCTAssertEqual(flushCounter.flushCount, 2) // 2 for handler setup + XCTAssertEqual(try self.channel.decodedSentFrames().count, 2) // 2 for handler setup + XCTAssertEqual(flushCounter.flushCount, 2) // 2 for handler setup // Now send channel read complete. The frames should be flushed through. self.channel.pipeline.fireChannelReadComplete() @@ -1467,7 +1656,7 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { let readCompleteCounter = ReadCompleteCounter() let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop) { childChannel in - return childChannel.pipeline.addHandler(frameRecorder).flatMap { + childChannel.pipeline.addHandler(frameRecorder).flatMap { childChannel.pipeline.addHandler(readCompleteCounter) } } @@ -1480,7 +1669,9 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { } // Wake up and activate the stream. - let requestHeaders = HPACKHeaders([(":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https")]) + let requestHeaders = HPACKHeaders([ + (":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https"), + ]) let requestFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: requestHeaders, endStream: false))) XCTAssertNoThrow(self.channel.pipeline.fireChannelRead(NIOAny(try requestFrame.encode()))) self.channel.embeddedEventLoop.run() @@ -1491,7 +1682,10 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { } // Now we're going to send 9 data frames. - let dataFrame = try HTTP2Frame(streamID: 1, payload: .data(.init(data: .byteBuffer(ByteBuffer(string: "Hello, world!"))))).encode() + let dataFrame = try HTTP2Frame( + streamID: 1, + payload: .data(.init(data: .byteBuffer(ByteBuffer(string: "Hello, world!")))) + ).encode() for _ in 0..<9 { self.channel.pipeline.fireChannelRead(NIOAny(dataFrame)) } @@ -1526,7 +1720,7 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { let readCompleteCounter = ReadCompleteCounter() let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop) { childChannel in - return childChannel.pipeline.addHandler(frameRecorder).flatMap { + childChannel.pipeline.addHandler(frameRecorder).flatMap { childChannel.pipeline.addHandler(readCompleteCounter) } } @@ -1539,9 +1733,14 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { } // Wake up and activate the streams. - let requestHeaders = HPACKHeaders([(":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https")]) + let requestHeaders = HPACKHeaders([ + (":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https"), + ]) for streamID in [HTTP2StreamID(1), HTTP2StreamID(3), HTTP2StreamID(5)] { - let requestFrame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: requestHeaders, endStream: false))) + let requestFrame = HTTP2Frame( + streamID: streamID, + payload: .headers(.init(headers: requestHeaders, endStream: false)) + ) try self.channel.pipeline.fireChannelRead(NIOAny(requestFrame.encode())) } self.channel.embeddedEventLoop.run() @@ -1559,7 +1758,10 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { } // Now we're going to send a data frame on stream 1. - let dataFrame = HTTP2Frame(streamID: 1, payload: .data(.init(data: .byteBuffer(ByteBuffer(string: "Hello, world!"))))) + let dataFrame = HTTP2Frame( + streamID: 1, + payload: .data(.init(data: .byteBuffer(ByteBuffer(string: "Hello, world!")))) + ) self.channel.pipeline.fireChannelRead(NIOAny(try dataFrame.encode())) // We should have 3 reads, and 3 read completes. The frame is not delivered as we have no frame fast-path. @@ -1590,10 +1792,15 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { var streamConfiguration = NIOHTTP2Handler.StreamConfiguration() streamConfiguration.outboundBufferSizeHighWatermark = 100 streamConfiguration.outboundBufferSizeLowWatermark = 50 - let http2Handler = NIOHTTP2Handler(mode: .client, eventLoop: self.channel.eventLoop, streamConfiguration: streamConfiguration, inboundStreamInitializer: { channel in - XCTFail("Must not be called") - return channel.eventLoop.makeFailedFuture(MyError()) - }) + let http2Handler = NIOHTTP2Handler( + mode: .client, + eventLoop: self.channel.eventLoop, + streamConfiguration: streamConfiguration, + inboundStreamInitializer: { channel in + XCTFail("Must not be called") + return channel.eventLoop.makeFailedFuture(MyError()) + } + ) XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) // We need to activate the underlying channel here. @@ -1603,7 +1810,7 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) let multiplexer = try http2Handler.multiplexer.wait() multiplexer.createStreamChannel(promise: childChannelPromise) { childChannel in - return childChannel.eventLoop.makeSucceededFuture(()) + childChannel.eventLoop.makeSucceededFuture(()) } self.channel.embeddedEventLoop.run() @@ -1612,7 +1819,9 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { // We're going to write a HEADERS frame (not counted towards flow control calculations) and a 90 byte DATA frame (90 bytes). This will not flip the // writability state. - let headers = HPACKHeaders([(":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https")]) + let headers = HPACKHeaders([ + (":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https"), + ]) let headersPayload = HTTP2Frame.FramePayload.headers(.init(headers: headers, endStream: false)) var dataBuffer = childChannel.allocator.buffer(capacity: 90) @@ -1644,10 +1853,14 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { func testMultiplexerModifiesStreamChannelWritabilityBasedOnParentChannelWritability() throws { - let http2Handler = NIOHTTP2Handler(mode: .client, eventLoop: self.channel.eventLoop, inboundStreamInitializer: { channel in - XCTFail("Must not be called") - return channel.eventLoop.makeFailedFuture(MyError()) - }) + let http2Handler = NIOHTTP2Handler( + mode: .client, + eventLoop: self.channel.eventLoop, + inboundStreamInitializer: { channel in + XCTFail("Must not be called") + return channel.eventLoop.makeFailedFuture(MyError()) + } + ) XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) // We need to activate the underlying channel here. @@ -1658,7 +1871,7 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { for promise in promises { let multiplexer = try http2Handler.multiplexer.wait() multiplexer.createStreamChannel(promise: promise) { childChannel in - return childChannel.eventLoop.makeSucceededFuture(()) + childChannel.eventLoop.makeSucceededFuture(()) } } self.channel.embeddedEventLoop.run() @@ -1670,7 +1883,10 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { // We need to write (and flush) some data so that the streams get stream IDs. for childChannel in channels { - XCTAssertNoThrow(try childChannel.writeAndFlush(HTTP2Frame.FramePayload.headers(.init(headers: .basicRequestHeaders))).wait()) + XCTAssertNoThrow( + try childChannel.writeAndFlush(HTTP2Frame.FramePayload.headers(.init(headers: .basicRequestValues))) + .wait() + ) } // Mark the parent channel not writable. This currently changes nothing. @@ -1690,10 +1906,15 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { var streamConfiguration = NIOHTTP2Handler.StreamConfiguration() streamConfiguration.outboundBufferSizeHighWatermark = 100 streamConfiguration.outboundBufferSizeLowWatermark = 50 - let http2Handler = NIOHTTP2Handler(mode: .client, eventLoop: self.channel.eventLoop, streamConfiguration: streamConfiguration, inboundStreamInitializer: { channel in - XCTFail("Must not be called") - return channel.eventLoop.makeFailedFuture(MyError()) - }) + let http2Handler = NIOHTTP2Handler( + mode: .client, + eventLoop: self.channel.eventLoop, + streamConfiguration: streamConfiguration, + inboundStreamInitializer: { channel in + XCTFail("Must not be called") + return channel.eventLoop.makeFailedFuture(MyError()) + } + ) XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) // We need to activate the underlying channel here. @@ -1703,19 +1924,23 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) let multiplexer = try http2Handler.multiplexer.wait() multiplexer.createStreamChannel(promise: childChannelPromise) { childChannel in - return childChannel.eventLoop.makeSucceededFuture(()) + childChannel.eventLoop.makeSucceededFuture(()) } self.channel.embeddedEventLoop.run() let childChannel = try assertNoThrowWithValue(childChannelPromise.futureResult.wait()) // We need to write (and flush) some data so that the streams get stream IDs. - XCTAssertNoThrow(try childChannel.writeAndFlush(HTTP2Frame.FramePayload.headers(.init(headers: .basicRequestHeaders))).wait()) + XCTAssertNoThrow( + try childChannel.writeAndFlush(HTTP2Frame.FramePayload.headers(.init(headers: .basicRequestValues))).wait() + ) XCTAssertTrue(childChannel.isWritable) // We're going to write a HEADERS frame (not counted towards flow control calculations) and a 90 byte DATA frame (90 bytes). This will not flip the // writability state. - let headers = HPACKHeaders([(":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https")]) + let headers = HPACKHeaders([ + (":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https"), + ]) let headersPayload = HTTP2Frame.FramePayload.headers(.init(headers: headers, endStream: false)) var dataBuffer = childChannel.allocator.buffer(capacity: 90) @@ -1759,10 +1984,15 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { var streamConfiguration = NIOHTTP2Handler.StreamConfiguration() streamConfiguration.outboundBufferSizeHighWatermark = 100 streamConfiguration.outboundBufferSizeLowWatermark = 50 - let http2Handler = NIOHTTP2Handler(mode: .client, eventLoop: self.channel.eventLoop, streamConfiguration: streamConfiguration, inboundStreamInitializer: { channel in - XCTFail("Must not be called") - return channel.eventLoop.makeFailedFuture(MyError()) - }) + let http2Handler = NIOHTTP2Handler( + mode: .client, + eventLoop: self.channel.eventLoop, + streamConfiguration: streamConfiguration, + inboundStreamInitializer: { channel in + XCTFail("Must not be called") + return channel.eventLoop.makeFailedFuture(MyError()) + } + ) XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) // We need to activate the underlying channel here. @@ -1782,7 +2012,8 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { func testReadWhenUsingAutoreadOnChildChannel() throws { let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) let readCounter = ReadCounter() - let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop) { channel -> EventLoopFuture in + let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop) { + channel -> EventLoopFuture in childChannelPromise.succeed(channel) // We're going to _enable_ autoRead on this channel. @@ -1793,12 +2024,11 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) XCTAssertNoThrow(try connectionSetup()) - // Let's open a stream. let streamID = HTTP2StreamID(1) - let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestHeaders))) + let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: .basicRequestValues))) XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) - let _ = try childChannelPromise.futureResult.wait() // just ensure that the initializer ran + let _ = try childChannelPromise.futureResult.wait() // just ensure that the initializer ran // There should be two calls to read: the first, when the stream was activated, the second after the HEADERS // frame was delivered. @@ -1807,7 +2037,10 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { } // Now deliver a data frame. - let dataFrame = try HTTP2Frame(streamID: streamID, payload: .data(.init(data: .byteBuffer(ByteBuffer(string: "Hello, world!"))))).encode() + let dataFrame = try HTTP2Frame( + streamID: streamID, + payload: .data(.init(data: .byteBuffer(ByteBuffer(string: "Hello, world!")))) + ).encode() XCTAssertNoThrow(try self.channel.writeInbound(dataFrame)) // This frame should have been immediately delivered, _and_ a call to read should have happened. @@ -1826,45 +2059,53 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { } func testStreamChannelSupportsSyncOptions() throws { - let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop, inboundStreamInitializer: { channel in - XCTAssert(channel is HTTP2StreamChannel) - if let sync = channel.syncOptions { - do { - let streamID = try sync.getOption(HTTP2StreamChannelOptions.streamID) - XCTAssertEqual(streamID, HTTP2StreamID(1)) + let http2Handler = NIOHTTP2Handler( + mode: .server, + eventLoop: self.channel.eventLoop, + inboundStreamInitializer: { channel in + XCTAssert(channel is HTTP2StreamChannel) + if let sync = channel.syncOptions { + do { + let streamID = try sync.getOption(HTTP2StreamChannelOptions.streamID) + XCTAssertEqual(streamID, HTTP2StreamID(1)) - let autoRead = try sync.getOption(ChannelOptions.autoRead) - try sync.setOption(ChannelOptions.autoRead, value: !autoRead) - XCTAssertNotEqual(autoRead, try sync.getOption(ChannelOptions.autoRead)) - } catch { - XCTFail("Missing StreamID") + let autoRead = try sync.getOption(ChannelOptions.autoRead) + try sync.setOption(ChannelOptions.autoRead, value: !autoRead) + XCTAssertNotEqual(autoRead, try sync.getOption(ChannelOptions.autoRead)) + } catch { + XCTFail("Missing StreamID") + } + } else { + XCTFail("syncOptions was nil but should be supported for HTTP2StreamChannel") } - } else { - XCTFail("syncOptions was nil but should be supported for HTTP2StreamChannel") - } - return channel.close() - }) + return channel.close() + } + ) XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) XCTAssertNoThrow(try connectionSetup()) - let frame = HTTP2Frame(streamID: HTTP2StreamID(1), payload: .headers(.init(headers: .basicRequestHeaders))) + let frame = HTTP2Frame(streamID: HTTP2StreamID(1), payload: .headers(.init(headers: .basicRequestValues))) XCTAssertNoThrow(try self.channel.writeInbound(frame.encode())) } func testStreamErrorIsDeliveredToChannel() throws { let goodHeaders = HPACKHeaders([ - (":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost") + (":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost"), ]) var badHeaders = goodHeaders badHeaders.add(name: "transfer-encoding", value: "chunked") - let http2Handler = NIOHTTP2Handler(mode: .client, eventLoop: self.channel.eventLoop, inboundStreamInitializer: { channel in - return channel.eventLoop.makeSucceededFuture(()) - }) + let http2Handler = NIOHTTP2Handler( + mode: .client, + eventLoop: self.channel.eventLoop, + inboundStreamInitializer: { channel in + channel.eventLoop.makeSucceededFuture(()) + } + ) XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) XCTAssertNoThrow(try connectionSetup(mode: .client)) - XCTAssertEqual(try self.channel.readAllBuffers().count, 3) // drain outbound magic, settings & ACK + XCTAssertEqual(try self.channel.readAllBuffers().count, 3) // drain outbound magic, settings & ACK // We need to activate the underlying channel here. XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(ipAddress: "127.0.0.1", port: 80)).wait()) @@ -1933,7 +2174,7 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { func testPendingReadsAreFlushedEvenWithoutUnsatisfiedReadOnChannelInactive() throws { let goodHeaders = HPACKHeaders([ - (":path", "/"), (":method", "GET"), (":scheme", "https"), (":authority", "localhost") + (":path", "/"), (":method", "GET"), (":scheme", "https"), (":authority", "localhost"), ]) let http2Handler = NIOHTTP2Handler( @@ -1946,7 +2187,7 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { ) XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) XCTAssertNoThrow(try connectionSetup(mode: .client)) - XCTAssertEqual(try self.channel.readAllBuffers().count, 3) // drain outbound magic, settings & ACK + XCTAssertEqual(try self.channel.readAllBuffers().count, 3) // drain outbound magic, settings & ACK // Now create and save a child channel with an error recording handler in it.x let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) @@ -1987,7 +2228,10 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { // 2. pass body onwards - let responseFrame1 = HTTP2Frame(streamID: streamID, payload: .data(.init(data: .byteBuffer(.init(string: "foo"))))) + let responseFrame1 = HTTP2Frame( + streamID: streamID, + payload: .data(.init(data: .byteBuffer(.init(string: "foo")))) + ) XCTAssertNoThrow(try self.channel.writeInbound(responseFrame1.encode())) try childChannel.pipeline.handler(type: ReadAndFrameConsumer.self).map { consumer in @@ -1999,7 +2243,10 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { // 3. pass on more body - should not change a thing, since read is pending in consumer - let responseFrame2 = HTTP2Frame(streamID: streamID, payload: .data(.init(data: .byteBuffer(.init(string: "bar")), endStream: false))) + let responseFrame2 = HTTP2Frame( + streamID: streamID, + payload: .data(.init(data: .byteBuffer(.init(string: "bar")), endStream: false)) + ) XCTAssertNoThrow(try self.channel.writeInbound(responseFrame2.encode())) try childChannel.pipeline.handler(type: ReadAndFrameConsumer.self).map { consumer in @@ -2011,7 +2258,10 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { // 4. signal stream is closed โ€“ this should force forward all pending frames - let responseFrame3 = HTTP2Frame(streamID: streamID, payload: .data(.init(data: .byteBuffer(.init(string: "bar")), endStream: true))) + let responseFrame3 = HTTP2Frame( + streamID: streamID, + payload: .data(.init(data: .byteBuffer(.init(string: "bar")), endStream: true)) + ) XCTAssertNoThrow(try self.channel.writeInbound(responseFrame3.encode())) try childChannel.pipeline.handler(type: ReadAndFrameConsumer.self).map { consumer in @@ -2028,15 +2278,15 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { func streamCreated(_ id: NIOHTTP2.HTTP2StreamID, channel: NIOCore.Channel) { self.store.withLockedValue { store in - store.created+=1 - store.open+=1 + store.created += 1 + store.open += 1 } } func streamClosed(_ id: NIOHTTP2.HTTP2StreamID, channel: NIOCore.Channel) { self.store.withLockedValue { store in - store.closed+=1 - store.open-=1 + store.closed += 1 + store.open -= 1 } } @@ -2068,22 +2318,33 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { func testDelegateReceivesCreationAndCloseNotifications() throws { let streamDelegate = CountingStreamDelegate() let completedChannelCount = ManagedAtomic(0) - let http2Handler = NIOHTTP2Handler(mode: .server, eventLoop: self.channel.eventLoop, streamDelegate: streamDelegate, inboundStreamInitializer: { channel in - channel.closeFuture.whenSuccess { completedChannelCount.wrappingIncrement(ordering: .sequentiallyConsistent) } - return channel.pipeline.addHandler(TestHookHandler { context, payload in - if case .headers(let requestHeaders) = payload { - XCTAssertEqual(requestHeaders.headers, .basicRequestHeaders) - - let headers = HTTP2Frame.FramePayload.headers(.init(headers: .basicResponseHeaders, endStream: true)) - context.writeAndFlush(NIOAny(headers), promise: nil) + let http2Handler = NIOHTTP2Handler( + mode: .server, + eventLoop: self.channel.eventLoop, + streamDelegate: streamDelegate, + inboundStreamInitializer: { channel in + channel.closeFuture.whenSuccess { + completedChannelCount.wrappingIncrement(ordering: .sequentiallyConsistent) } - }) - }) + return channel.pipeline.addHandler( + TestHookHandler { context, payload in + if case .headers(let requestHeaders) = payload { + XCTAssertEqual(requestHeaders.headers, .basicRequestValues) + + let headers = HTTP2Frame.FramePayload.headers( + .init(headers: .basicResponseValues, endStream: true) + ) + context.writeAndFlush(NIOAny(headers), promise: nil) + } + } + ) + } + ) XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) XCTAssertNoThrow(try connectionSetup()) // Let's send a bunch of headers frames. This should open some streams. - let headers = HTTP2Frame.FramePayload.headers(.init(headers: .basicRequestHeaders, endStream: false)) + let headers = HTTP2Frame.FramePayload.headers(.init(headers: .basicRequestValues, endStream: false)) let streamIDs = stride(from: 1, to: 100, by: 2).map { HTTP2StreamID($0) } for streamID in streamIDs { XCTAssertNoThrow(try self.channel.writeInbound(HTTP2Frame(streamID: streamID, payload: headers).encode())) @@ -2095,7 +2356,10 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { // Let's some data with endStream to close the streams. for streamID in streamIDs { - let dataFrame = HTTP2Frame(streamID: streamID, payload: .data(.init(data: .byteBuffer(ByteBuffer(string: "Hello, world!")), endStream: true))) + let dataFrame = HTTP2Frame( + streamID: streamID, + payload: .data(.init(data: .byteBuffer(ByteBuffer(string: "Hello, world!")), endStream: true)) + ) XCTAssertNoThrow(try self.channel.writeInbound(dataFrame.encode())) } XCTAssertEqual(completedChannelCount.load(ordering: .sequentiallyConsistent), 0) @@ -2118,11 +2382,16 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { let configurePromise: EventLoopPromise = self.channel.eventLoop.makePromise() let createdChannelCount = ManagedAtomic(0) let configuredChannelCount = ManagedAtomic(0) - let streamIDs = NIOLockedValueBox(Array()) - let http2Handler = NIOHTTP2Handler(mode: .client, eventLoop: self.channel.eventLoop, streamDelegate: streamDelegate, inboundStreamInitializer: { channel in - XCTFail("Must not be called") - return channel.eventLoop.makeFailedFuture(MyError()) - }) + let streamIDs = NIOLockedValueBox([HTTP2StreamID]()) + let http2Handler = NIOHTTP2Handler( + mode: .client, + eventLoop: self.channel.eventLoop, + streamDelegate: streamDelegate, + inboundStreamInitializer: { channel in + XCTFail("Must not be called") + return channel.eventLoop.makeFailedFuture(MyError()) + } + ) XCTAssertNoThrow(try self.channel.pipeline.addHandler(http2Handler).wait()) try connectionSetup(mode: .client) @@ -2136,7 +2405,9 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { channelPromise.futureResult.whenSuccess { channel in configuredChannelCount.wrappingIncrement(ordering: .sequentiallyConsistent) // Write some headers: the flush will trigger a stream ID to be assigned to the channel. - channel.writeAndFlush(HTTP2Frame.FramePayload.headers(.init(headers: .basicRequestHeaders, endStream: true))).whenSuccess { + channel.writeAndFlush( + HTTP2Frame.FramePayload.headers(.init(headers: .basicRequestValues, endStream: true)) + ).whenSuccess { channel.getOption(HTTP2StreamChannelOptions.streamID).whenSuccess { streamID in streamIDs.withLockedValue { streamIDs in streamIDs.append(streamID) @@ -2165,20 +2436,23 @@ final class HTTP2InlineStreamMultiplexerTests: XCTestCase { XCTAssertEqual(streamIDs, [1, 3, 5].map { HTTP2StreamID($0) }) } XCTAssertEqual(streamDelegate.created, 3) - XCTAssertEqual(streamDelegate.closed,0) + XCTAssertEqual(streamDelegate.closed, 0) XCTAssertEqual(streamDelegate.open, 3) // write a response to allow the streams to fully closes try streamIDs.withLockedValue { streamIDs in for id in streamIDs { - let headers = HTTP2Frame(streamID: id, payload: .headers(.init(headers: .basicResponseHeaders, endStream: true))) + let headers = HTTP2Frame( + streamID: id, + payload: .headers(.init(headers: .basicResponseValues, endStream: true)) + ) XCTAssertNoThrow(try self.channel.writeInbound(headers.encode())) } } (self.channel.eventLoop as! EmbeddedEventLoop).run() XCTAssertEqual(streamDelegate.created, 3) - XCTAssertEqual(streamDelegate.closed,3) + XCTAssertEqual(streamDelegate.closed, 3) XCTAssertEqual(streamDelegate.open, 0) XCTAssertNoThrow(try self.channel.finish()) diff --git a/Tests/NIOHTTP2Tests/HTTP2StreamMultiplexerTests.swift b/Tests/NIOHTTP2Tests/HTTP2StreamMultiplexerTests.swift index fee5ee4..929e4e6 100644 --- a/Tests/NIOHTTP2Tests/HTTP2StreamMultiplexerTests.swift +++ b/Tests/NIOHTTP2Tests/HTTP2StreamMultiplexerTests.swift @@ -12,27 +12,31 @@ // //===----------------------------------------------------------------------===// -import XCTest import Atomics import NIOConcurrencyHelpers import NIOCore import NIOEmbedded import NIOHTTP1 -@testable import NIOHPACK // for HPACKHeaders initializers +import XCTest + +@testable import NIOHPACK // for HPACKHeaders initializers @testable import NIOHTTP2 -private extension Channel { +extension Channel { /// Adds a simple no-op `HTTP2StreamMultiplexer` to the pipeline. @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") - func addNoOpMultiplexer(mode: NIOHTTP2Handler.ParserMode) { - XCTAssertNoThrow(try self.pipeline.addHandler(HTTP2StreamMultiplexer(mode: mode, channel: self) { (channel, streamID) in - self.eventLoop.makeSucceededFuture(()) - }).wait()) + fileprivate func addNoOpMultiplexer(mode: NIOHTTP2Handler.ParserMode) { + XCTAssertNoThrow( + try self.pipeline.addHandler( + HTTP2StreamMultiplexer(mode: mode, channel: self) { (channel, streamID) in + self.eventLoop.makeSucceededFuture(()) + } + ).wait() + ) } } -private struct MyError: Error { } - +private struct MyError: Error {} /// A handler that asserts the frames received match the expected set. private final class FrameExpecter: ChannelInboundHandler { @@ -66,7 +70,6 @@ private final class FrameExpecter: ChannelInboundHandler { } } - // A handler that keeps track of the writes made on a channel. Used to work around the limitations // in `EmbeddedChannel`. final class WriteRecorder: ChannelOutboundHandler { @@ -91,7 +94,6 @@ final class WriteRecorder: ChannelOutboundHandler { typealias FrameWriteRecorder = WriteRecorder typealias FramePayloadWriteRecorder = WriteRecorder - /// A handler that keeps track of all reads made on a channel. final class InboundRecorder: ChannelInboundHandler, @unchecked Sendable { typealias InboundIn = Frame @@ -134,7 +136,6 @@ final class ReadCounter: ChannelOutboundHandler, Sendable { } } - /// A handler that tracks the number of times flush() was called on the channel. final class FlushCounter: ChannelOutboundHandler { typealias OutboundIn = Any @@ -148,7 +149,6 @@ final class FlushCounter: ChannelOutboundHandler { } } - final class ReadCompleteCounter: ChannelInboundHandler, Sendable { typealias InboundIn = Any typealias InboundOut = Any @@ -163,7 +163,6 @@ final class ReadCompleteCounter: ChannelInboundHandler, Sendable { } } - /// A channel handler that sends a response in response to a HEADERS frame. final class QuickResponseHandler: ChannelInboundHandler { typealias InboundIn = HTTP2Frame @@ -178,7 +177,10 @@ final class QuickResponseHandler: ChannelInboundHandler { } let responseHeaders = HPACKHeaders([(":status", "200"), ("content-length", "0")]) - let responseFrame = HTTP2Frame(streamID: frame.streamID, payload: .headers(.init(headers: responseHeaders, endStream: true))) + let responseFrame = HTTP2Frame( + streamID: frame.streamID, + payload: .headers(.init(headers: responseHeaders, endStream: true)) + ) context.writeAndFlush(self.wrapOutboundOut(responseFrame), promise: nil) context.fireChannelRead(data) } @@ -219,7 +221,6 @@ final class HandlerRemovedHandler: ChannelInboundHandler { } } - /// A channel handler that succeeds a promise when its channel becomes active. final class ActiveHandler: ChannelInboundHandler { typealias InboundIn = Any @@ -241,7 +242,6 @@ final class ActiveHandler: ChannelInboundHandler { } } - final class HTTP2StreamMultiplexerTests: XCTestCase { var channel: EmbeddedChannel! @@ -254,7 +254,11 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { } private func activateStream(_ streamID: HTTP2StreamID) { - let activated = NIOHTTP2StreamCreatedEvent(streamID: streamID, localInitialWindowSize: 16384, remoteInitialWindowSize: 16384) + let activated = NIOHTTP2StreamCreatedEvent( + streamID: streamID, + localInitialWindowSize: 16384, + remoteInitialWindowSize: 16384 + ) self.channel.pipeline.fireUserInboundEventTriggered(activated) } @@ -262,7 +266,10 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { func testMultiplexerIgnoresFramesOnStream0() throws { self.channel.addNoOpMultiplexer(mode: .server) - let simplePingFrame = HTTP2Frame(streamID: .rootStream, payload: .ping(HTTP2PingData(withInteger: 5), ack: false)) + let simplePingFrame = HTTP2Frame( + streamID: .rootStream, + payload: .ping(HTTP2PingData(withInteger: 5), ack: false) + ) XCTAssertNoThrow(try self.channel.writeInbound(simplePingFrame)) XCTAssertNoThrow(try self.channel.assertReceivedFrame().assertFrameMatches(this: simplePingFrame)) @@ -292,7 +299,9 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { func testChannelsCloseThemselvesWhenToldTo() throws { let completedChannelCount = ManagedAtomic(0) let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { (channel, _) in - channel.closeFuture.whenSuccess { completedChannelCount.wrappingIncrement(ordering: .sequentiallyConsistent) } + channel.closeFuture.whenSuccess { + completedChannelCount.wrappingIncrement(ordering: .sequentiallyConsistent) + } return channel.eventLoop.makeSucceededFuture(()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) @@ -300,7 +309,10 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { // Let's send a bunch of headers frames with endStream on them. This should open some streams. let streamIDs = stride(from: 1, to: 100, by: 2).map { HTTP2StreamID($0) } for streamID in streamIDs { - let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders(), endStream: true))) + let frame = HTTP2Frame( + streamID: streamID, + payload: .headers(.init(headers: HPACKHeaders(), endStream: true)) + ) XCTAssertNoThrow(try self.channel.writeInbound(frame)) } XCTAssertEqual(completedChannelCount.load(ordering: .sequentiallyConsistent), 0) @@ -358,8 +370,10 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { // At this stage the stream should be closed with the appropriate error code. closeError.withLockedValue { closeError in - XCTAssertEqual(closeError as? NIOHTTP2Errors.StreamClosed, - NIOHTTP2Errors.StreamClosed(streamID: streamID, errorCode: .cancel)) + XCTAssertEqual( + closeError as? NIOHTTP2Errors.StreamClosed, + NIOHTTP2Errors.StreamClosed(streamID: streamID, errorCode: .cancel) + ) } XCTAssertNoThrow(try self.channel.finish()) } @@ -373,7 +387,10 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { // First, set up the frames we want to send/receive. let streamID = HTTP2StreamID(1) let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders(), endStream: true))) - let goAwayFrame = HTTP2Frame(streamID: .rootStream, payload: .goAway(lastStreamID: .rootStream, errorCode: .http11Required, opaqueData: nil)) + let goAwayFrame = HTTP2Frame( + streamID: .rootStream, + payload: .goAway(lastStreamID: .rootStream, errorCode: .http11Required, opaqueData: nil) + ) let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { (channel, _) in closeError.withLockedValue { closeError in @@ -406,8 +423,10 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { // At this stage the stream should be closed with the appropriate manufactured error code. closeError.withLockedValue { closeError in - XCTAssertEqual(closeError as? NIOHTTP2Errors.StreamClosed, - NIOHTTP2Errors.StreamClosed(streamID: streamID, errorCode: .refusedStream)) + XCTAssertEqual( + closeError as? NIOHTTP2Errors.StreamClosed, + NIOHTTP2Errors.StreamClosed(streamID: streamID, errorCode: .refusedStream) + ) } XCTAssertNoThrow(try self.channel.finish()) } @@ -460,7 +479,7 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { func testClosingIdleChannels() throws { let frameReceiver = FrameWriteRecorder() let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { (channel, _) in - return channel.close() + channel.close() } XCTAssertNoThrow(try self.channel.pipeline.addHandler(frameReceiver).wait()) XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) @@ -493,7 +512,6 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { XCTAssertNoThrow(try self.channel.pipeline.addHandler(frameReceiver).wait()) XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) - XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) // Let's send a headers frame to open the stream. @@ -525,7 +543,6 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { XCTAssertNoThrow(try self.channel.pipeline.addHandler(frameReceiver).wait()) XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) - XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) // Let's send a headers frame to open the stream. @@ -566,7 +583,6 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { XCTAssertNoThrow(try self.channel.pipeline.addHandler(frameReceiver).wait()) XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) - XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) // Let's send a headers frame to open the stream. @@ -653,7 +669,10 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { let userEvent = StreamClosedEvent(streamID: streamID, reason: .cancel) self.channel.pipeline.fireUserInboundEventTriggered(userEvent) closeError.withLockedValue { closeError in - XCTAssertEqual(closeError as? NIOHTTP2Errors.StreamClosed, NIOHTTP2Errors.StreamClosed(streamID: streamID, errorCode: .cancel)) + XCTAssertEqual( + closeError as? NIOHTTP2Errors.StreamClosed, + NIOHTTP2Errors.StreamClosed(streamID: streamID, errorCode: .cancel) + ) } XCTAssertNoThrow(try self.channel.finish()) @@ -671,7 +690,6 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) - XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) // Let's send a headers frame to open the stream. @@ -682,7 +700,9 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { // The channel should now be available, but no frames should have been received on either the parent or child channel. let childChannel = try channelPromise.futureResult.wait() - let frameRecorder = try childChannel.pipeline.context(handlerType: InboundFrameRecorder.self).wait().handler as! InboundFrameRecorder + let frameRecorder = + try childChannel.pipeline.context(handlerType: InboundFrameRecorder.self).wait().handler + as! InboundFrameRecorder self.channel.assertNoFramesReceived() XCTAssertEqual(frameRecorder.receivedFrames.count, 0) @@ -744,7 +764,9 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { // The channel should now be available, but no frames should have been received on either the parent or child channel. let childChannel = try channelPromise.futureResult.wait() - let frameRecorder = try childChannel.pipeline.context(handlerType: InboundFrameRecorder.self).wait().handler as! InboundFrameRecorder + let frameRecorder = + try childChannel.pipeline.context(handlerType: InboundFrameRecorder.self).wait().handler + as! InboundFrameRecorder self.channel.assertNoFramesReceived() XCTAssertEqual(frameRecorder.receivedFrames.count, 0) @@ -800,7 +822,10 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { let firstStreamID = HTTP2StreamID(1) let secondStreamID = HTTP2StreamID(3) for streamID in [firstStreamID, secondStreamID] { - let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders(), endStream: true))) + let frame = HTTP2Frame( + streamID: streamID, + payload: .headers(.init(headers: HPACKHeaders(), endStream: true)) + ) XCTAssertNoThrow(try self.channel.writeInbound(frame)) self.activateStream(streamID) } @@ -812,8 +837,14 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { // We will now write a headers frame to each channel. Neither frame should be written to the connection. To verify this // we will flush the parent channel. - firstStreamChannel.write(HTTP2Frame(streamID: firstStreamID, payload: .headers(.init(headers: HPACKHeaders()))), promise: nil) - secondStreamChannel.write(HTTP2Frame(streamID: secondStreamID, payload: .headers(.init(headers: HPACKHeaders()))), promise: nil) + firstStreamChannel.write( + HTTP2Frame(streamID: firstStreamID, payload: .headers(.init(headers: HPACKHeaders()))), + promise: nil + ) + secondStreamChannel.write( + HTTP2Frame(streamID: secondStreamID, payload: .headers(.init(headers: HPACKHeaders()))), + promise: nil + ) self.channel.flush() XCTAssertEqual(writeTracker.flushedWrites.count, 0) @@ -899,7 +930,10 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { self.channel.pipeline.fireUserInboundEventTriggered(userEvent) writeError.withLockedValue { writeError in - XCTAssertEqual(writeError as? NIOHTTP2Errors.StreamClosed, NIOHTTP2Errors.StreamClosed(streamID: streamID, errorCode: .cancel)) + XCTAssertEqual( + writeError as? NIOHTTP2Errors.StreamClosed, + NIOHTTP2Errors.StreamClosed(streamID: streamID, errorCode: .cancel) + ) } XCTAssertNoThrow(try self.channel.finish()) @@ -945,7 +979,8 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { func testReadPullsInAllFrames() throws { let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) let frameRecorder = InboundFrameRecorder() - let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { (channel, _) -> EventLoopFuture in + let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { + (channel, _) -> EventLoopFuture in childChannelPromise.succeed(channel) // We're going to disable autoRead on this channel. @@ -963,10 +998,8 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) - XCTAssertNoThrow(try self.channel.connect(to: SocketAddress(unixDomainSocketPath: "/whatever"), promise: nil)) - // Let's open a stream. let streamID = HTTP2StreamID(1) let frame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders()))) @@ -1004,13 +1037,14 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { let firstStreamID = HTTP2StreamID(1) let secondStreamID = HTTP2StreamID(3) let (channelsStream, channelsContinuation) = AsyncStream.makeStream(of: Channel.self) - let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { (channel, streamID) -> EventLoopFuture in + let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { + (channel, streamID) -> EventLoopFuture in let recorder = InboundFrameRecorder() channelsContinuation.yield(channel) // Disable autoRead on the first channel. return channel.setOption(ChannelOptions.autoRead, value: streamID != firstStreamID).flatMap { - return channel.pipeline.addHandler(recorder) + channel.pipeline.addHandler(recorder) } } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) @@ -1060,7 +1094,8 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { func testReadWillCauseAutomaticFrameDelivery() throws { let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) let frameRecorder = InboundFrameRecorder() - let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { (channel, _) -> EventLoopFuture in + let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { + (channel, _) -> EventLoopFuture in childChannelPromise.succeed(channel) // We're going to disable autoRead on this channel. @@ -1078,7 +1113,6 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { XCTAssertNoThrow(try self.channel.writeInbound(frame)) self.activateStream(streamID) - let childChannel = try childChannelPromise.futureResult.wait() // This stream should have seen no frames. @@ -1113,7 +1147,8 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) let readCounter = ReadCounter() let frameRecorder = InboundFrameRecorder() - let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { (channel, _) -> EventLoopFuture in + let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { + (channel, _) -> EventLoopFuture in childChannelPromise.succeed(channel) // We're going to disable autoRead on this channel. @@ -1132,7 +1167,6 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { XCTAssertNoThrow(try self.channel.writeInbound(frame)) self.activateStream(streamID) - let childChannel = try childChannelPromise.futureResult.wait() // This stream should have seen no frames. @@ -1199,10 +1233,12 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { func testHandlersAreRemovedOnClosure() throws { let handlerRemoved = ManagedAtomic(false) let handlerRemovedPromise: EventLoopPromise = self.channel.eventLoop.makePromise() - handlerRemovedPromise.futureResult.whenComplete { _ in handlerRemoved.store(true, ordering: .sequentiallyConsistent) } + handlerRemovedPromise.futureResult.whenComplete { _ in + handlerRemoved.store(true, ordering: .sequentiallyConsistent) + } let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { (channel, _) in - return channel.pipeline.addHandler(HandlerRemovedHandler(removedPromise: handlerRemovedPromise)) + channel.pipeline.addHandler(HandlerRemovedHandler(removedPromise: handlerRemovedPromise)) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) @@ -1230,10 +1266,12 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { func testHandlersAreRemovedOnClosureWithError() throws { let handlerRemoved = ManagedAtomic(false) let handlerRemovedPromise: EventLoopPromise = self.channel.eventLoop.makePromise() - handlerRemovedPromise.futureResult.whenComplete { _ in handlerRemoved.store(true, ordering: .sequentiallyConsistent) } + handlerRemovedPromise.futureResult.whenComplete { _ in + handlerRemoved.store(true, ordering: .sequentiallyConsistent) + } let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { (channel, _) in - return channel.pipeline.addHandler(HandlerRemovedHandler(removedPromise: handlerRemovedPromise)) + channel.pipeline.addHandler(HandlerRemovedHandler(removedPromise: handlerRemovedPromise)) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) @@ -1262,7 +1300,7 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { let configurePromise: EventLoopPromise = self.channel.eventLoop.makePromise() let createdChannelCount = ManagedAtomic(0) let configuredChannelCount = ManagedAtomic(0) - let streamIDs = NIOLockedValueBox(Array()) + let streamIDs = NIOLockedValueBox([HTTP2StreamID]()) let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { (channel, _) in XCTFail("Must not be called") return channel.eventLoop.makeFailedFuture(MyError()) @@ -1307,7 +1345,7 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { let configurePromise: EventLoopPromise = self.channel.eventLoop.makePromise() let createdChannelCount = ManagedAtomic(0) let configuredChannelCount = ManagedAtomic(0) - let streamIDs = NIOLockedValueBox(Array()) + let streamIDs = NIOLockedValueBox([HTTP2StreamID]()) let multiplexer = HTTP2StreamMultiplexer(mode: .client, channel: self.channel) { (channel, _) in XCTFail("Must not be called") return channel.eventLoop.makeFailedFuture(MyError()) @@ -1367,11 +1405,13 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { } (self.channel.eventLoop as! EmbeddedEventLoop).run() - let childChannel = try childChannelPromise.futureResult.wait() let childStreamID = try childStreamIDPromise.futureResult.wait() - childChannel.writeAndFlush(HTTP2Frame(streamID: childStreamID, payload: .headers(.init(headers: HPACKHeaders()))), promise: nil) + childChannel.writeAndFlush( + HTTP2Frame(streamID: childStreamID, payload: .headers(.init(headers: HPACKHeaders()))), + promise: nil + ) XCTAssertEqual(writeRecorder.flushedWrites.count, 0) @@ -1405,7 +1445,9 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { let writeError = NIOLockedValueBox(nil) - childChannel.writeAndFlush(HTTP2Frame(streamID: childStreamID, payload: .headers(.init(headers: HPACKHeaders())))).whenFailure { error in + childChannel.writeAndFlush( + HTTP2Frame(streamID: childStreamID, payload: .headers(.init(headers: HPACKHeaders()))) + ).whenFailure { error in writeError.withLockedValue { writeError in writeError = error } @@ -1436,7 +1478,7 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { XCTAssertNoThrow(try self.channel.pipeline.addHandler(writeRecorder).wait()) XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) multiplexer.createStreamChannel(promise: nil) { (channel, streamID) in - return configurePromise.futureResult + configurePromise.futureResult } (self.channel.eventLoop as! EmbeddedEventLoop).run() @@ -1540,7 +1582,10 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { func testMultiplexerIgnoresPriorityFrames() throws { self.channel.addNoOpMultiplexer(mode: .server) - let simplePingFrame = HTTP2Frame(streamID: 106, payload: .priority(.init(exclusive: true, dependency: .rootStream, weight: 15))) + let simplePingFrame = HTTP2Frame( + streamID: 106, + payload: .priority(.init(exclusive: true, dependency: .rootStream, weight: 15)) + ) XCTAssertNoThrow(try self.channel.writeInbound(simplePingFrame)) XCTAssertNoThrow(try self.channel.assertReceivedFrame().assertFrameMatches(this: simplePingFrame)) @@ -1598,7 +1643,7 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { let channelPromise = self.channel.eventLoop.makePromise(of: Channel.self) multiplexer.createStreamChannel(promise: channelPromise) { (channel, streamID) in - return channel.eventLoop.makeSucceededFuture(()) + channel.eventLoop.makeSucceededFuture(()) } self.channel.embeddedEventLoop.run() @@ -1654,7 +1699,7 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { let channelPromise = self.channel.eventLoop.makePromise(of: Channel.self) multiplexer.createStreamChannel(promise: channelPromise) { (channel, streamID) in - return channel.eventLoop.makeSucceededFuture(()) + channel.eventLoop.makeSucceededFuture(()) } self.channel.embeddedEventLoop.run() @@ -1686,11 +1731,15 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) // We're going to send in 10 request frames. - let requestHeaders = HPACKHeaders([(":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https")]) + let requestHeaders = HPACKHeaders([ + (":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https"), + ]) XCTAssertEqual(flushCounter.flushCount, 0) - let framesToSend = stride(from: 1, through: 19, by: 2).map { HTTP2Frame(streamID: HTTP2StreamID($0), payload: .headers(.init(headers: requestHeaders, endStream: true))) } - for frame in framesToSend { + let framesToSend = stride(from: 1, through: 19, by: 2).map { + HTTP2Frame(streamID: HTTP2StreamID($0), payload: .headers(.init(headers: requestHeaders, endStream: true))) + } + for frame in framesToSend { self.channel.pipeline.fireChannelRead(NIOAny(frame)) } self.channel.embeddedEventLoop.run() @@ -1714,7 +1763,7 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { let readCompleteCounter = ReadCompleteCounter() let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { (childChannel, _) in - return childChannel.pipeline.addHandler(frameRecorder).flatMap { + childChannel.pipeline.addHandler(frameRecorder).flatMap { childChannel.pipeline.addHandler(readCompleteCounter) } } @@ -1726,7 +1775,9 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { } // Wake up and activate the stream. - let requestHeaders = HPACKHeaders([(":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https")]) + let requestHeaders = HPACKHeaders([ + (":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https"), + ]) let requestFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: requestHeaders, endStream: false))) self.channel.pipeline.fireChannelRead(NIOAny(requestFrame)) self.activateStream(1) @@ -1740,7 +1791,10 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { // Now we're going to send 9 data frames. var requestData = self.channel.allocator.buffer(capacity: 1024) requestData.writeBytes("Hello world!".utf8) - let dataFrames = repeatElement(HTTP2Frame(streamID: 1, payload: .data(.init(data: .byteBuffer(requestData), endStream: false))), count: 9) + let dataFrames = repeatElement( + HTTP2Frame(streamID: 1, payload: .data(.init(data: .byteBuffer(requestData), endStream: false))), + count: 9 + ) for frame in dataFrames { self.channel.pipeline.fireChannelRead(NIOAny(frame)) @@ -1780,7 +1834,7 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { let readCompleteCounter = ReadCompleteCounter() let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { (childChannel, _) in - return childChannel.pipeline.addHandler(frameRecorder).flatMap { + childChannel.pipeline.addHandler(frameRecorder).flatMap { childChannel.pipeline.addHandler(readCompleteCounter) } } @@ -1792,10 +1846,15 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { } // Wake up and activate the streams. - let requestHeaders = HPACKHeaders([(":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https")]) + let requestHeaders = HPACKHeaders([ + (":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https"), + ]) for streamID in [HTTP2StreamID(1), HTTP2StreamID(3), HTTP2StreamID(5)] { - let requestFrame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: requestHeaders, endStream: false))) + let requestFrame = HTTP2Frame( + streamID: streamID, + payload: .headers(.init(headers: requestHeaders, endStream: false)) + ) self.channel.pipeline.fireChannelRead(NIOAny(requestFrame)) self.activateStream(streamID) } @@ -1846,10 +1905,12 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") func testMultiplexerModifiesStreamChannelWritabilityBasedOnFixedSizeTokens() throws { - let multiplexer = HTTP2StreamMultiplexer(mode: .client, - channel: self.channel, - outboundBufferSizeHighWatermark: 100, - outboundBufferSizeLowWatermark: 50) { (channel, _) in + let multiplexer = HTTP2StreamMultiplexer( + mode: .client, + channel: self.channel, + outboundBufferSizeHighWatermark: 100, + outboundBufferSizeLowWatermark: 50 + ) { (channel, _) in XCTFail("Must not be called") return channel.eventLoop.makeFailedFuture(MyError()) } @@ -1861,7 +1922,7 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { // Now we want to create a new child stream. let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) multiplexer.createStreamChannel(promise: childChannelPromise) { childChannel, _ in - return childChannel.eventLoop.makeSucceededFuture(()) + childChannel.eventLoop.makeSucceededFuture(()) } self.channel.embeddedEventLoop.run() @@ -1870,7 +1931,9 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { // We're going to write a HEADERS frame (not counted towards flow control calculations) and a 90 byte DATA frame (90 bytes). This will not flip the // writability state. - let headers = HPACKHeaders([(":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https")]) + let headers = HPACKHeaders([ + (":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https"), + ]) let headersFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: headers, endStream: false))) var dataBuffer = childChannel.allocator.buffer(capacity: 90) @@ -1884,7 +1947,10 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { // We're going to write another 20 byte DATA frame (20 bytes). This should flip the channel writability. dataBuffer = childChannel.allocator.buffer(capacity: 20) dataBuffer.writeBytes(repeatElement(0, count: 20)) - let secondDataFrame = HTTP2Frame(streamID: 1, payload: .data(.init(data: .byteBuffer(dataBuffer), endStream: false))) + let secondDataFrame = HTTP2Frame( + streamID: 1, + payload: .data(.init(data: .byteBuffer(dataBuffer), endStream: false)) + ) childChannel.write(secondDataFrame, promise: nil) // Now we're going to send another HEADERS frame (for trailers). This should not affect the channel writability. @@ -1913,7 +1979,7 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { let promises = (0..<5).map { _ in self.channel.eventLoop.makePromise(of: Channel.self) } for promise in promises { multiplexer.createStreamChannel(promise: promise) { childChannel, _ in - return childChannel.eventLoop.makeSucceededFuture(()) + childChannel.eventLoop.makeSucceededFuture(()) } } self.channel.embeddedEventLoop.run() @@ -1946,10 +2012,12 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") func testMultiplexerModifiesStreamChannelWritabilityBasedOnFixedSizeTokensAndChannelWritability() throws { - let multiplexer = HTTP2StreamMultiplexer(mode: .client, - channel: self.channel, - outboundBufferSizeHighWatermark: 100, - outboundBufferSizeLowWatermark: 50) { (channel, _) in + let multiplexer = HTTP2StreamMultiplexer( + mode: .client, + channel: self.channel, + outboundBufferSizeHighWatermark: 100, + outboundBufferSizeLowWatermark: 50 + ) { (channel, _) in XCTFail("Must not be called") return channel.eventLoop.makeFailedFuture(MyError()) } @@ -1961,7 +2029,7 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { // Now we want to create a new child stream. let childChannelPromise = self.channel.eventLoop.makePromise(of: Channel.self) multiplexer.createStreamChannel(promise: childChannelPromise) { childChannel, _ in - return childChannel.eventLoop.makeSucceededFuture(()) + childChannel.eventLoop.makeSucceededFuture(()) } self.channel.embeddedEventLoop.run() self.activateStream(1) @@ -1971,7 +2039,9 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { // We're going to write a HEADERS frame (not counted towards flow control calculations) and a 90 byte DATA frame (90 bytes). This will not flip the // writability state. - let headers = HPACKHeaders([(":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https")]) + let headers = HPACKHeaders([ + (":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https"), + ]) let headersFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: headers, endStream: false))) var dataBuffer = childChannel.allocator.buffer(capacity: 90) @@ -1985,7 +2055,10 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { // We're going to write another 20 byte DATA frame (20 bytes). This should flip the channel writability. dataBuffer = childChannel.allocator.buffer(capacity: 20) dataBuffer.writeBytes(repeatElement(0, count: 20)) - let secondDataFrame = HTTP2Frame(streamID: 1, payload: .data(.init(data: .byteBuffer(dataBuffer), endStream: false))) + let secondDataFrame = HTTP2Frame( + streamID: 1, + payload: .data(.init(data: .byteBuffer(dataBuffer), endStream: false)) + ) childChannel.write(secondDataFrame, promise: nil) // Now we're going to send another HEADERS frame (for trailers). This should not affect the channel writability. @@ -2011,10 +2084,12 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") func testStreamChannelToleratesFailingInitializer() { struct DummyError: Error {} - let multiplexer = HTTP2StreamMultiplexer(mode: .client, - channel: self.channel, - outboundBufferSizeHighWatermark: 100, - outboundBufferSizeLowWatermark: 50) { (channel, _) in + let multiplexer = HTTP2StreamMultiplexer( + mode: .client, + channel: self.channel, + outboundBufferSizeHighWatermark: 100, + outboundBufferSizeLowWatermark: 50 + ) { (channel, _) in XCTFail("Must not be called") return channel.eventLoop.makeFailedFuture(MyError()) } @@ -2037,10 +2112,12 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { func testInboundChannelWindowSizeIsCustomisable() throws { let targetWindowSize = 1 << 18 - let multiplexer = HTTP2StreamMultiplexer(mode: .client, - channel: self.channel, - targetWindowSize: targetWindowSize) { (channel, streamID) in - return channel.eventLoop.makeSucceededFuture(()) + let multiplexer = HTTP2StreamMultiplexer( + mode: .client, + channel: self.channel, + targetWindowSize: targetWindowSize + ) { (channel, streamID) in + channel.eventLoop.makeSucceededFuture(()) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(multiplexer).wait()) @@ -2052,12 +2129,20 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { // Now claim that the window got consumed. Nothing happens. XCTAssertNoThrow(try XCTAssertNil(self.channel.readOutbound(as: HTTP2Frame.self))) - var windowEvent = NIOHTTP2WindowUpdatedEvent(streamID: 1, inboundWindowSize: (targetWindowSize / 2) + 1, outboundWindowSize: nil) + var windowEvent = NIOHTTP2WindowUpdatedEvent( + streamID: 1, + inboundWindowSize: (targetWindowSize / 2) + 1, + outboundWindowSize: nil + ) channel.pipeline.fireUserInboundEventTriggered(windowEvent) XCTAssertNoThrow(try XCTAssertNil(self.channel.readOutbound(as: HTTP2Frame.self))) // Consume the last byte. - windowEvent = NIOHTTP2WindowUpdatedEvent(streamID: 1, inboundWindowSize: (targetWindowSize / 2), outboundWindowSize: nil) + windowEvent = NIOHTTP2WindowUpdatedEvent( + streamID: 1, + inboundWindowSize: (targetWindowSize / 2), + outboundWindowSize: nil + ) channel.pipeline.fireUserInboundEventTriggered(windowEvent) guard let receivedFrame = try assertNoThrowWithValue(self.channel.readOutbound(as: HTTP2Frame.self)) else { XCTFail("No frame received") @@ -2102,7 +2187,9 @@ final class HTTP2StreamMultiplexerTests: XCTestCase { let dataFrame = HTTP2Frame(streamID: streamID, payload: .data(.init(data: .byteBuffer(payloadBuffer)))) let multiplexer = HTTP2StreamMultiplexer(mode: .server, channel: self.channel) { channel in - channel.pipeline.addHandler(FramePayloadExpecter(expectedPayload: [headerFrame.payload, dataFrame.payload])) + channel.pipeline.addHandler( + FramePayloadExpecter(expectedPayload: [headerFrame.payload, dataFrame.payload]) + ) } XCTAssertNoThrow(try self.channel.pipeline.addHandler(BufferingChannelHandler()).wait()) diff --git a/Tests/NIOHTTP2Tests/HTTP2ToHTTP1CodecTests.swift b/Tests/NIOHTTP2Tests/HTTP2ToHTTP1CodecTests.swift index 75e6f65..6a7a6d1 100644 --- a/Tests/NIOHTTP2Tests/HTTP2ToHTTP1CodecTests.swift +++ b/Tests/NIOHTTP2Tests/HTTP2ToHTTP1CodecTests.swift @@ -12,17 +12,21 @@ // //===----------------------------------------------------------------------===// -import XCTest import NIOCore import NIOEmbedded import NIOHTTP1 -@testable import NIOHPACK // For HPACKHeaders initializer access -@testable import NIOHTTP2 +import XCTest +@testable import NIOHPACK // For HPACKHeaders initializer access +@testable import NIOHTTP2 extension EmbeddedChannel { /// Assert that we received a request head. - func assertReceivedServerRequestPart(_ part: HTTPServerRequestPart, file: StaticString = #filePath, line: UInt = #line) { + func assertReceivedServerRequestPart( + _ part: HTTPServerRequestPart, + file: StaticString = #filePath, + line: UInt = #line + ) { guard let actualPart: HTTPServerRequestPart = try? assertNoThrowWithValue(self.readInbound()) else { XCTFail("No data received", file: (file), line: line) return @@ -31,7 +35,11 @@ extension EmbeddedChannel { XCTAssertEqual(actualPart, part, file: (file), line: line) } - func assertReceivedClientResponsePart(_ part: HTTPClientResponsePart, file: StaticString = #filePath, line: UInt = #line) { + func assertReceivedClientResponsePart( + _ part: HTTPClientResponsePart, + file: StaticString = #filePath, + line: UInt = #line + ) { guard let actualPart: HTTPClientResponsePart = try? assertNoThrowWithValue(self.readInbound()) else { XCTFail("No data received", file: (file), line: line) return @@ -41,9 +49,8 @@ extension EmbeddedChannel { } } - extension HTTPHeaders { - static func +(lhs: HTTPHeaders, rhs: HTTPHeaders) -> HTTPHeaders { + static func + (lhs: HTTPHeaders, rhs: HTTPHeaders) -> HTTPHeaders { var new = lhs for (name, value) in rhs { new.add(name: name, value: value) @@ -54,7 +61,7 @@ extension HTTPHeaders { } extension HPACKHeaders { - static func +(lhs: HPACKHeaders, rhs: HPACKHeaders) -> HPACKHeaders { + static func + (lhs: HPACKHeaders, rhs: HPACKHeaders) -> HPACKHeaders { var new = lhs for (name, value, index) in rhs { new.add(name: name, value: value, indexing: index) @@ -63,7 +70,6 @@ extension HPACKHeaders { } } - /// A simple channel handler that records the promises sent through it. final class PromiseRecorder: ChannelOutboundHandler { typealias OutboundIn = Any @@ -77,7 +83,6 @@ final class PromiseRecorder: ChannelOutboundHandler { } } - final class HTTP2ToHTTP1CodecTests: XCTestCase { var channel: EmbeddedChannel! @@ -95,8 +100,15 @@ final class HTTP2ToHTTP1CodecTests: XCTestCase { XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2ToHTTP1ServerCodec(streamID: streamID)).wait()) // A basic request. - let requestHeaders = HPACKHeaders([(":path", "/post"), (":method", "POST"), (":scheme", "https"), (":authority", "example.org"), ("other", "header")]) - XCTAssertNoThrow(try self.channel.writeInbound(HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: requestHeaders))))) + let requestHeaders = HPACKHeaders([ + (":path", "/post"), (":method", "POST"), (":scheme", "https"), (":authority", "example.org"), + ("other", "header"), + ]) + XCTAssertNoThrow( + try self.channel.writeInbound( + HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: requestHeaders))) + ) + ) var expectedRequestHead = HTTPRequestHead(version: HTTPVersion(major: 2, minor: 0), method: .POST, uri: "/post") expectedRequestHead.headers.add(name: "host", value: "example.org") @@ -106,7 +118,10 @@ final class HTTP2ToHTTP1CodecTests: XCTestCase { var bodyData = self.channel.allocator.buffer(capacity: 12) bodyData.writeStaticString("hello, world!") - let dataFrame = HTTP2Frame(streamID: streamID, payload: .data(.init(data: .byteBuffer(bodyData), endStream: true))) + let dataFrame = HTTP2Frame( + streamID: streamID, + payload: .data(.init(data: .byteBuffer(bodyData), endStream: true)) + ) XCTAssertNoThrow(try self.channel.writeInbound(dataFrame)) self.channel.assertReceivedServerRequestPart(.body(bodyData)) self.channel.assertReceivedServerRequestPart(.end(nil)) @@ -120,8 +135,14 @@ final class HTTP2ToHTTP1CodecTests: XCTestCase { XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2ToHTTP1ServerCodec(streamID: streamID)).wait()) // A basic request. - let requestHeaders = HPACKHeaders([(":path", "/get"), (":method", "GET"), (":scheme", "https"), (":authority", "example.org"), ("other", "header")]) - let headersFrame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: requestHeaders, endStream: true))) + let requestHeaders = HPACKHeaders([ + (":path", "/get"), (":method", "GET"), (":scheme", "https"), (":authority", "example.org"), + ("other", "header"), + ]) + let headersFrame = HTTP2Frame( + streamID: streamID, + payload: .headers(.init(headers: requestHeaders, endStream: true)) + ) XCTAssertNoThrow(try self.channel.writeInbound(headersFrame)) var expectedRequestHead = HTTPRequestHead(version: HTTPVersion(major: 2, minor: 0), method: .GET, uri: "/get") @@ -139,7 +160,10 @@ final class HTTP2ToHTTP1CodecTests: XCTestCase { XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2ToHTTP1ServerCodec(streamID: streamID)).wait()) // A basic request. - let requestHeaders = HPACKHeaders([(":path", "/get"), (":method", "GET"), (":scheme", "https"), (":authority", "example.org"), ("other", "header")]) + let requestHeaders = HPACKHeaders([ + (":path", "/get"), (":method", "GET"), (":scheme", "https"), (":authority", "example.org"), + ("other", "header"), + ]) let headersFrame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: requestHeaders))) XCTAssertNoThrow(try self.channel.writeInbound(headersFrame)) @@ -167,12 +191,20 @@ final class HTTP2ToHTTP1CodecTests: XCTestCase { // A basic response. let responseHeaders = HPACKHeaders([("server", "swift-nio"), ("other", "header")]) - let responseHead = HTTPResponseHead(version: .init(major: 2, minor: 0), status: .ok, headers: HTTPHeaders(regularHeadersFrom: responseHeaders)) + let responseHead = HTTPResponseHead( + version: .init(major: 2, minor: 0), + status: .ok, + headers: HTTPHeaders(regularHeadersFrom: responseHeaders) + ) self.channel.writeAndFlush(HTTPServerResponsePart.head(responseHead), promise: nil) let expectedResponseHeaders = HPACKHeaders([(":status", "200")]) + responseHeaders XCTAssertEqual(writeRecorder.flushedWrites.count, 1) - writeRecorder.flushedWrites[0].assertHeadersFrame(endStream: false, streamID: 1, headers: expectedResponseHeaders) + writeRecorder.flushedWrites[0].assertHeadersFrame( + endStream: false, + streamID: 1, + headers: expectedResponseHeaders + ) // Now body. var bodyData = self.channel.allocator.buffer(capacity: 12) @@ -199,12 +231,20 @@ final class HTTP2ToHTTP1CodecTests: XCTestCase { // A basic response. let responseHeaders = HPACKHeaders([("server", "swift-nio"), ("other", "header")]) - let responseHead = HTTPResponseHead(version: .init(major: 2, minor: 0), status: .ok, headers: HTTPHeaders(regularHeadersFrom: responseHeaders)) + let responseHead = HTTPResponseHead( + version: .init(major: 2, minor: 0), + status: .ok, + headers: HTTPHeaders(regularHeadersFrom: responseHeaders) + ) self.channel.writeAndFlush(HTTPServerResponsePart.head(responseHead), promise: nil) let expectedResponseHeaders = HPACKHeaders([(":status", "200")]) + responseHeaders XCTAssertEqual(writeRecorder.flushedWrites.count, 1) - writeRecorder.flushedWrites[0].assertHeadersFrame(endStream: false, streamID: 1, headers: expectedResponseHeaders) + writeRecorder.flushedWrites[0].assertHeadersFrame( + endStream: false, + streamID: 1, + headers: expectedResponseHeaders + ) // No trailers, just end. let emptyBuffer = self.channel.allocator.buffer(capacity: 0) @@ -224,7 +264,11 @@ final class HTTP2ToHTTP1CodecTests: XCTestCase { // First, we're going to send a few 103 blocks. let informationalResponseHeaders = HPACKHeaders([("link", "no link really")]) - let informationalResponseHead = HTTPResponseHead(version: .init(major: 2, minor: 0), status: .custom(code: 103, reasonPhrase: "Early Hints"), headers: HTTPHeaders(regularHeadersFrom: informationalResponseHeaders)) + let informationalResponseHead = HTTPResponseHead( + version: .init(major: 2, minor: 0), + status: .custom(code: 103, reasonPhrase: "Early Hints"), + headers: HTTPHeaders(regularHeadersFrom: informationalResponseHeaders) + ) for _ in 0..<3 { self.channel.write(HTTPServerResponsePart.head(informationalResponseHead), promise: nil) } @@ -233,19 +277,31 @@ final class HTTP2ToHTTP1CodecTests: XCTestCase { let expectedInformationalResponseHeaders = HPACKHeaders([(":status", "103")]) + informationalResponseHeaders XCTAssertEqual(writeRecorder.flushedWrites.count, 3) for idx in 0..<3 { - writeRecorder.flushedWrites[idx].assertHeadersFrame(endStream: false, streamID: 1, headers: expectedInformationalResponseHeaders) + writeRecorder.flushedWrites[idx].assertHeadersFrame( + endStream: false, + streamID: 1, + headers: expectedInformationalResponseHeaders + ) } // Now we finish up with a basic response. let responseHeaders = HPACKHeaders([("server", "swift-nio"), ("other", "header")]) - let responseHead = HTTPResponseHead(version: .init(major: 2, minor: 0), status: .ok, headers: HTTPHeaders(regularHeadersFrom: responseHeaders)) + let responseHead = HTTPResponseHead( + version: .init(major: 2, minor: 0), + status: .ok, + headers: HTTPHeaders(regularHeadersFrom: responseHeaders) + ) self.channel.writeAndFlush(HTTPServerResponsePart.head(responseHead), promise: nil) self.channel.writeAndFlush(HTTPServerResponsePart.end(nil), promise: nil) let expectedResponseHeaders = HPACKHeaders([(":status", "200")]) + responseHeaders let emptyBuffer = self.channel.allocator.buffer(capacity: 0) XCTAssertEqual(writeRecorder.flushedWrites.count, 5) - writeRecorder.flushedWrites[3].assertHeadersFrame(endStream: false, streamID: 1, headers: expectedResponseHeaders) + writeRecorder.flushedWrites[3].assertHeadersFrame( + endStream: false, + streamID: 1, + headers: expectedResponseHeaders + ) writeRecorder.flushedWrites[4].assertDataFrame(endStream: true, streamID: 1, payload: emptyBuffer) XCTAssertNoThrow(try self.channel.finish()) @@ -285,15 +341,25 @@ final class HTTP2ToHTTP1CodecTests: XCTestCase { @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") func testBasicResponseClientSide() throws { let streamID = HTTP2StreamID(1) - XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2ToHTTP1ClientCodec(streamID: streamID, httpProtocol: .https)).wait()) + XCTAssertNoThrow( + try self.channel.pipeline.addHandler(HTTP2ToHTTP1ClientCodec(streamID: streamID, httpProtocol: .https)) + .wait() + ) // A basic request. let http1Head = HTTPRequestHead(version: .http1_1, method: .GET, uri: "/", headers: ["host": "example.org"]) XCTAssertNoThrow(try self.channel.writeOutbound(HTTPClientRequestPart.head(http1Head))) - + // A basic response. let responseHeaders = HTTPHeaders([(":status", "200"), ("other", "header")]) - XCTAssertNoThrow(try self.channel.writeInbound(HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders(httpHeaders: responseHeaders)))))) + XCTAssertNoThrow( + try self.channel.writeInbound( + HTTP2Frame( + streamID: streamID, + payload: .headers(.init(headers: HPACKHeaders(httpHeaders: responseHeaders))) + ) + ) + ) var expectedResponseHead = HTTPResponseHead(version: .init(major: 2, minor: 0), status: .ok) expectedResponseHead.headers.add(name: "other", value: "header") @@ -302,7 +368,10 @@ final class HTTP2ToHTTP1CodecTests: XCTestCase { var bodyData = self.channel.allocator.buffer(capacity: 12) bodyData.writeStaticString("hello, world!") - let dataFrame = HTTP2Frame(streamID: streamID, payload: .data(.init(data: .byteBuffer(bodyData), endStream: true))) + let dataFrame = HTTP2Frame( + streamID: streamID, + payload: .data(.init(data: .byteBuffer(bodyData), endStream: true)) + ) XCTAssertNoThrow(try self.channel.writeInbound(dataFrame)) self.channel.assertReceivedClientResponsePart(.body(bodyData)) self.channel.assertReceivedClientResponsePart(.end(nil)) @@ -313,15 +382,21 @@ final class HTTP2ToHTTP1CodecTests: XCTestCase { @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") func testResponseWithOnlyHeadClientSide() throws { let streamID = HTTP2StreamID(1) - XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2ToHTTP1ClientCodec(streamID: streamID, httpProtocol: .https)).wait()) - + XCTAssertNoThrow( + try self.channel.pipeline.addHandler(HTTP2ToHTTP1ClientCodec(streamID: streamID, httpProtocol: .https)) + .wait() + ) + // A basic request. let http1Head = HTTPRequestHead(version: .http1_1, method: .GET, uri: "/", headers: ["host": "example.org"]) XCTAssertNoThrow(try self.channel.writeOutbound(HTTPClientRequestPart.head(http1Head))) // A basic response. let responseHeaders = HTTPHeaders([(":status", "200"), ("other", "header")]) - let headersFrame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders(httpHeaders: responseHeaders), endStream: true))) + let headersFrame = HTTP2Frame( + streamID: streamID, + payload: .headers(.init(headers: HPACKHeaders(httpHeaders: responseHeaders), endStream: true)) + ) XCTAssertNoThrow(try self.channel.writeInbound(headersFrame)) var expectedResponseHead = HTTPResponseHead(version: .init(major: 2, minor: 0), status: .ok) @@ -336,15 +411,21 @@ final class HTTP2ToHTTP1CodecTests: XCTestCase { @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") func testResponseWithTrailers() throws { let streamID = HTTP2StreamID(1) - XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2ToHTTP1ClientCodec(streamID: streamID, httpProtocol: .https)).wait()) + XCTAssertNoThrow( + try self.channel.pipeline.addHandler(HTTP2ToHTTP1ClientCodec(streamID: streamID, httpProtocol: .https)) + .wait() + ) // A basic request. let http1Head = HTTPRequestHead(version: .http1_1, method: .GET, uri: "/", headers: ["host": "example.org"]) XCTAssertNoThrow(try self.channel.writeOutbound(HTTPClientRequestPart.head(http1Head))) - + // A basic response. let responseHeaders = HTTPHeaders([(":status", "200"), ("other", "header")]) - let headersFrame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders(httpHeaders: responseHeaders)))) + let headersFrame = HTTP2Frame( + streamID: streamID, + payload: .headers(.init(headers: HPACKHeaders(httpHeaders: responseHeaders))) + ) XCTAssertNoThrow(try self.channel.writeInbound(headersFrame)) var expectedResponseHead = HTTPResponseHead(version: .init(major: 2, minor: 0), status: .ok) @@ -354,7 +435,10 @@ final class HTTP2ToHTTP1CodecTests: XCTestCase { // Ok, we're going to send trailers. let trailers = HTTPHeaders([("a trailer", "yes"), ("another trailer", "also yes")]) - let trailersFrame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders(httpHeaders: trailers), endStream: true))) + let trailersFrame = HTTP2Frame( + streamID: streamID, + payload: .headers(.init(headers: HPACKHeaders(httpHeaders: trailers), endStream: true)) + ) XCTAssertNoThrow(try self.channel.writeInbound(trailersFrame)) self.channel.assertReceivedClientResponsePart(.end(trailers)) @@ -367,7 +451,10 @@ final class HTTP2ToHTTP1CodecTests: XCTestCase { let streamID = HTTP2StreamID(1) let writeRecorder = FrameWriteRecorder() XCTAssertNoThrow(try self.channel.pipeline.addHandler(writeRecorder).wait()) - XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2ToHTTP1ClientCodec(streamID: streamID, httpProtocol: .https)).wait()) + XCTAssertNoThrow( + try self.channel.pipeline.addHandler(HTTP2ToHTTP1ClientCodec(streamID: streamID, httpProtocol: .https)) + .wait() + ) // A basic request. let requestHeaders = HPACKHeaders([("host", "example.org"), ("other", "header")]) @@ -375,9 +462,16 @@ final class HTTP2ToHTTP1CodecTests: XCTestCase { requestHead.headers = HTTPHeaders(regularHeadersFrom: requestHeaders) self.channel.writeAndFlush(HTTPClientRequestPart.head(requestHead), promise: nil) - let expectedRequestHeaders = HPACKHeaders([(":path", "/post"), (":method", "POST"), (":scheme", "https"), (":authority", "example.org"), ("other", "header")]) + let expectedRequestHeaders = HPACKHeaders([ + (":path", "/post"), (":method", "POST"), (":scheme", "https"), (":authority", "example.org"), + ("other", "header"), + ]) XCTAssertEqual(writeRecorder.flushedWrites.count, 1) - writeRecorder.flushedWrites[0].assertHeadersFrame(endStream: false, streamID: 1, headers: expectedRequestHeaders) + writeRecorder.flushedWrites[0].assertHeadersFrame( + endStream: false, + streamID: 1, + headers: expectedRequestHeaders + ) // Now body. var bodyData = self.channel.allocator.buffer(capacity: 12) @@ -400,7 +494,10 @@ final class HTTP2ToHTTP1CodecTests: XCTestCase { let streamID = HTTP2StreamID(1) let writeRecorder = FrameWriteRecorder() XCTAssertNoThrow(try self.channel.pipeline.addHandler(writeRecorder).wait()) - XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2ToHTTP1ClientCodec(streamID: streamID, httpProtocol: .http)).wait()) + XCTAssertNoThrow( + try self.channel.pipeline.addHandler(HTTP2ToHTTP1ClientCodec(streamID: streamID, httpProtocol: .http)) + .wait() + ) // A basic request. let requestHeaders = HTTPHeaders([("host", "example.org"), ("other", "header")]) @@ -408,9 +505,16 @@ final class HTTP2ToHTTP1CodecTests: XCTestCase { requestHead.headers = requestHeaders self.channel.writeAndFlush(HTTPClientRequestPart.head(requestHead), promise: nil) - let expectedRequestHeaders = HPACKHeaders([(":path", "/post"), (":method", "POST"), (":scheme", "http"), (":authority", "example.org"), ("other", "header")]) + let expectedRequestHeaders = HPACKHeaders([ + (":path", "/post"), (":method", "POST"), (":scheme", "http"), (":authority", "example.org"), + ("other", "header"), + ]) XCTAssertEqual(writeRecorder.flushedWrites.count, 1) - writeRecorder.flushedWrites[0].assertHeadersFrame(endStream: false, streamID: 1, headers: expectedRequestHeaders) + writeRecorder.flushedWrites[0].assertHeadersFrame( + endStream: false, + streamID: 1, + headers: expectedRequestHeaders + ) // No trailers, just end. let emptyBuffer = self.channel.allocator.buffer(capacity: 0) @@ -424,8 +528,11 @@ final class HTTP2ToHTTP1CodecTests: XCTestCase { @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") func testResponseWith100BlocksClientSide() throws { let streamID = HTTP2StreamID(1) - XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2ToHTTP1ClientCodec(streamID: streamID, httpProtocol: .https)).wait()) - + XCTAssertNoThrow( + try self.channel.pipeline.addHandler(HTTP2ToHTTP1ClientCodec(streamID: streamID, httpProtocol: .https)) + .wait() + ) + // A basic request. let http1Head = HTTPRequestHead(version: .http1_1, method: .GET, uri: "/", headers: ["host": "example.org"]) XCTAssertNoThrow(try self.channel.writeOutbound(HTTPClientRequestPart.head(http1Head))) @@ -433,10 +540,20 @@ final class HTTP2ToHTTP1CodecTests: XCTestCase { // Start with a few 100 blocks. let informationalResponseHeaders = HTTPHeaders([(":status", "103"), ("link", "example")]) for _ in 0..<3 { - XCTAssertNoThrow(try self.channel.writeInbound(HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders(httpHeaders: informationalResponseHeaders)))))) + XCTAssertNoThrow( + try self.channel.writeInbound( + HTTP2Frame( + streamID: streamID, + payload: .headers(.init(headers: HPACKHeaders(httpHeaders: informationalResponseHeaders))) + ) + ) + ) } - var expectedInformationalResponseHead = HTTPResponseHead(version: .init(major: 2, minor: 0), status: .custom(code: 103, reasonPhrase: "")) + var expectedInformationalResponseHead = HTTPResponseHead( + version: .init(major: 2, minor: 0), + status: .custom(code: 103, reasonPhrase: "") + ) expectedInformationalResponseHead.headers.add(name: "link", value: "example") for _ in 0..<3 { self.channel.assertReceivedClientResponsePart(.head(expectedInformationalResponseHead)) @@ -444,7 +561,10 @@ final class HTTP2ToHTTP1CodecTests: XCTestCase { // Now a response. let responseHeaders = HTTPHeaders([(":status", "200"), ("other", "header")]) - let responseFrame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: HPACKHeaders(httpHeaders: responseHeaders), endStream: true))) + let responseFrame = HTTP2Frame( + streamID: streamID, + payload: .headers(.init(headers: HPACKHeaders(httpHeaders: responseHeaders), endStream: true)) + ) XCTAssertNoThrow(try self.channel.writeInbound(responseFrame)) var expectedResponseHead = HTTPResponseHead(version: .init(major: 2, minor: 0), status: .ok) @@ -463,7 +583,10 @@ final class HTTP2ToHTTP1CodecTests: XCTestCase { let promises: [EventLoopPromise] = (0..<3).map { _ in self.channel.eventLoop.makePromise() } XCTAssertNoThrow(try self.channel.pipeline.addHandler(promiseRecorder).wait()) - XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2ToHTTP1ClientCodec(streamID: streamID, httpProtocol: .https)).wait()) + XCTAssertNoThrow( + try self.channel.pipeline.addHandler(HTTP2ToHTTP1ClientCodec(streamID: streamID, httpProtocol: .https)) + .wait() + ) // A basic response. let requestHeaders = HTTPHeaders([("host", "example.org"), ("other", "header")]) @@ -494,8 +617,14 @@ final class HTTP2ToHTTP1CodecTests: XCTestCase { XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2ToHTTP1ServerCodec(streamID: streamID)).wait()) // A basic request. - let requestHeaders = HPACKHeaders([(":path", "/post"), (":scheme", "https"), (":authority", "example.org"), ("other", "header")]) - XCTAssertThrowsError(try self.channel.writeInbound(HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: requestHeaders))))) { error in + let requestHeaders = HPACKHeaders([ + (":path", "/post"), (":scheme", "https"), (":authority", "example.org"), ("other", "header"), + ]) + XCTAssertThrowsError( + try self.channel.writeInbound( + HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: requestHeaders))) + ) + ) { error in XCTAssertEqual(error as? NIOHTTP2Errors.MissingPseudoHeader, NIOHTTP2Errors.MissingPseudoHeader(":method")) } @@ -509,9 +638,19 @@ final class HTTP2ToHTTP1CodecTests: XCTestCase { XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2ToHTTP1ServerCodec(streamID: streamID)).wait()) // A basic request. - let requestHeaders = HPACKHeaders([(":path", "/post"), (":method", "GET"), (":method", "GET"), (":scheme", "https"), (":authority", "example.org"), ("other", "header")]) - XCTAssertThrowsError(try self.channel.writeInbound(HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: requestHeaders))))) { error in - XCTAssertEqual(error as? NIOHTTP2Errors.DuplicatePseudoHeader, NIOHTTP2Errors.DuplicatePseudoHeader(":method")) + let requestHeaders = HPACKHeaders([ + (":path", "/post"), (":method", "GET"), (":method", "GET"), (":scheme", "https"), + (":authority", "example.org"), ("other", "header"), + ]) + XCTAssertThrowsError( + try self.channel.writeInbound( + HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: requestHeaders))) + ) + ) { error in + XCTAssertEqual( + error as? NIOHTTP2Errors.DuplicatePseudoHeader, + NIOHTTP2Errors.DuplicatePseudoHeader(":method") + ) } // We already know there's an error here. @@ -524,8 +663,14 @@ final class HTTP2ToHTTP1CodecTests: XCTestCase { XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2ToHTTP1ServerCodec(streamID: streamID)).wait()) // A basic request. - let requestHeaders = HPACKHeaders([(":method", "GET"), (":scheme", "https"), (":authority", "example.org"), ("other", "header")]) - XCTAssertThrowsError(try self.channel.writeInbound(HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: requestHeaders))))) { error in + let requestHeaders = HPACKHeaders([ + (":method", "GET"), (":scheme", "https"), (":authority", "example.org"), ("other", "header"), + ]) + XCTAssertThrowsError( + try self.channel.writeInbound( + HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: requestHeaders))) + ) + ) { error in XCTAssertEqual(error as? NIOHTTP2Errors.MissingPseudoHeader, NIOHTTP2Errors.MissingPseudoHeader(":path")) } @@ -539,9 +684,19 @@ final class HTTP2ToHTTP1CodecTests: XCTestCase { XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2ToHTTP1ServerCodec(streamID: streamID)).wait()) // A basic request. - let requestHeaders = HPACKHeaders([(":path", "/post"), (":path", "/post"), (":method", "GET"), (":scheme", "https"), (":authority", "example.org"), ("other", "header")]) - XCTAssertThrowsError(try self.channel.writeInbound(HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: requestHeaders))))) { error in - XCTAssertEqual(error as? NIOHTTP2Errors.DuplicatePseudoHeader, NIOHTTP2Errors.DuplicatePseudoHeader(":path")) + let requestHeaders = HPACKHeaders([ + (":path", "/post"), (":path", "/post"), (":method", "GET"), (":scheme", "https"), + (":authority", "example.org"), ("other", "header"), + ]) + XCTAssertThrowsError( + try self.channel.writeInbound( + HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: requestHeaders))) + ) + ) { error in + XCTAssertEqual( + error as? NIOHTTP2Errors.DuplicatePseudoHeader, + NIOHTTP2Errors.DuplicatePseudoHeader(":path") + ) } // We already know there's an error here. @@ -554,9 +709,18 @@ final class HTTP2ToHTTP1CodecTests: XCTestCase { XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2ToHTTP1ServerCodec(streamID: streamID)).wait()) // A basic request. - let requestHeaders = HPACKHeaders([(":method", "GET"), (":scheme", "https"), (":path", "/post"), ("other", "header")]) - XCTAssertThrowsError(try self.channel.writeInbound(HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: requestHeaders))))) { error in - XCTAssertEqual(error as? NIOHTTP2Errors.MissingPseudoHeader, NIOHTTP2Errors.MissingPseudoHeader(":authority")) + let requestHeaders = HPACKHeaders([ + (":method", "GET"), (":scheme", "https"), (":path", "/post"), ("other", "header"), + ]) + XCTAssertThrowsError( + try self.channel.writeInbound( + HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: requestHeaders))) + ) + ) { error in + XCTAssertEqual( + error as? NIOHTTP2Errors.MissingPseudoHeader, + NIOHTTP2Errors.MissingPseudoHeader(":authority") + ) } // We already know there's an error here. @@ -569,9 +733,19 @@ final class HTTP2ToHTTP1CodecTests: XCTestCase { XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2ToHTTP1ServerCodec(streamID: streamID)).wait()) // A basic request. - let requestHeaders = HPACKHeaders([(":path", "/post"), (":method", "GET"), (":scheme", "https"), (":authority", "example.org"), (":authority", "example.org"), ("other", "header")]) - XCTAssertThrowsError(try self.channel.writeInbound(HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: requestHeaders))))) { error in - XCTAssertEqual(error as? NIOHTTP2Errors.DuplicatePseudoHeader, NIOHTTP2Errors.DuplicatePseudoHeader(":authority")) + let requestHeaders = HPACKHeaders([ + (":path", "/post"), (":method", "GET"), (":scheme", "https"), (":authority", "example.org"), + (":authority", "example.org"), ("other", "header"), + ]) + XCTAssertThrowsError( + try self.channel.writeInbound( + HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: requestHeaders))) + ) + ) { error in + XCTAssertEqual( + error as? NIOHTTP2Errors.DuplicatePseudoHeader, + NIOHTTP2Errors.DuplicatePseudoHeader(":authority") + ) } // We already know there's an error here. @@ -584,8 +758,14 @@ final class HTTP2ToHTTP1CodecTests: XCTestCase { XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2ToHTTP1ServerCodec(streamID: streamID)).wait()) // A basic request. - let requestHeaders = HPACKHeaders([(":method", "GET"), (":authority", "example.org"), (":path", "/post"), ("other", "header")]) - XCTAssertThrowsError(try self.channel.writeInbound(HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: requestHeaders))))) { error in + let requestHeaders = HPACKHeaders([ + (":method", "GET"), (":authority", "example.org"), (":path", "/post"), ("other", "header"), + ]) + XCTAssertThrowsError( + try self.channel.writeInbound( + HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: requestHeaders))) + ) + ) { error in XCTAssertEqual(error as? NIOHTTP2Errors.MissingPseudoHeader, NIOHTTP2Errors.MissingPseudoHeader(":scheme")) } @@ -599,9 +779,19 @@ final class HTTP2ToHTTP1CodecTests: XCTestCase { XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2ToHTTP1ServerCodec(streamID: streamID)).wait()) // A basic request. - let requestHeaders = HPACKHeaders([(":path", "/post"), (":method", "GET"), (":scheme", "https"), (":scheme", "https"), (":authority", "example.org"), ("other", "header")]) - XCTAssertThrowsError(try self.channel.writeInbound(HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: requestHeaders))))) { error in - XCTAssertEqual(error as? NIOHTTP2Errors.DuplicatePseudoHeader, NIOHTTP2Errors.DuplicatePseudoHeader(":scheme")) + let requestHeaders = HPACKHeaders([ + (":path", "/post"), (":method", "GET"), (":scheme", "https"), (":scheme", "https"), + (":authority", "example.org"), ("other", "header"), + ]) + XCTAssertThrowsError( + try self.channel.writeInbound( + HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: requestHeaders))) + ) + ) { error in + XCTAssertEqual( + error as? NIOHTTP2Errors.DuplicatePseudoHeader, + NIOHTTP2Errors.DuplicatePseudoHeader(":scheme") + ) } // We already know there's an error here. @@ -611,11 +801,18 @@ final class HTTP2ToHTTP1CodecTests: XCTestCase { @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") func testReceiveResponseWithoutStatus() throws { let streamID = HTTP2StreamID(1) - XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2ToHTTP1ClientCodec(streamID: streamID, httpProtocol: .https)).wait()) + XCTAssertNoThrow( + try self.channel.pipeline.addHandler(HTTP2ToHTTP1ClientCodec(streamID: streamID, httpProtocol: .https)) + .wait() + ) // A basic response. let requestHeaders = HPACKHeaders([("other", "header")]) - XCTAssertThrowsError(try self.channel.writeInbound(HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: requestHeaders))))) { error in + XCTAssertThrowsError( + try self.channel.writeInbound( + HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: requestHeaders))) + ) + ) { error in XCTAssertEqual(error as? NIOHTTP2Errors.MissingPseudoHeader, NIOHTTP2Errors.MissingPseudoHeader(":status")) } @@ -626,12 +823,22 @@ final class HTTP2ToHTTP1CodecTests: XCTestCase { @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") func testReceiveResponseWithDuplicateStatus() throws { let streamID = HTTP2StreamID(1) - XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2ToHTTP1ClientCodec(streamID: streamID, httpProtocol: .https)).wait()) + XCTAssertNoThrow( + try self.channel.pipeline.addHandler(HTTP2ToHTTP1ClientCodec(streamID: streamID, httpProtocol: .https)) + .wait() + ) // A basic request. let requestHeaders = HPACKHeaders([(":status", "200"), (":status", "404"), ("other", "header")]) - XCTAssertThrowsError(try self.channel.writeInbound(HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: requestHeaders))))) { error in - XCTAssertEqual(error as? NIOHTTP2Errors.DuplicatePseudoHeader, NIOHTTP2Errors.DuplicatePseudoHeader(":status")) + XCTAssertThrowsError( + try self.channel.writeInbound( + HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: requestHeaders))) + ) + ) { error in + XCTAssertEqual( + error as? NIOHTTP2Errors.DuplicatePseudoHeader, + NIOHTTP2Errors.DuplicatePseudoHeader(":status") + ) } // We already know there's an error here. @@ -641,16 +848,26 @@ final class HTTP2ToHTTP1CodecTests: XCTestCase { @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") func testReceiveResponseWithNonNumericalStatus() throws { let streamID = HTTP2StreamID(1) - XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2ToHTTP1ClientCodec(streamID: streamID, httpProtocol: .https)).wait()) - + XCTAssertNoThrow( + try self.channel.pipeline.addHandler(HTTP2ToHTTP1ClientCodec(streamID: streamID, httpProtocol: .https)) + .wait() + ) + // A basic request. let http1Head = HTTPRequestHead(version: .http1_1, method: .GET, uri: "/", headers: ["host": "example.org"]) XCTAssertNoThrow(try self.channel.writeOutbound(HTTPClientRequestPart.head(http1Head))) // A basic response. let requestHeaders = HPACKHeaders([(":status", "captivating")]) - XCTAssertThrowsError(try self.channel.writeInbound(HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: requestHeaders))))) { error in - XCTAssertEqual(error as? NIOHTTP2Errors.InvalidStatusValue, NIOHTTP2Errors.InvalidStatusValue("captivating")) + XCTAssertThrowsError( + try self.channel.writeInbound( + HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: requestHeaders))) + ) + ) { error in + XCTAssertEqual( + error as? NIOHTTP2Errors.InvalidStatusValue, + NIOHTTP2Errors.InvalidStatusValue("captivating") + ) } // We already know there's an error here. @@ -660,7 +877,10 @@ final class HTTP2ToHTTP1CodecTests: XCTestCase { @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") func testSendRequestWithoutHost() throws { let streamID = HTTP2StreamID(1) - XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2ToHTTP1ClientCodec(streamID: streamID, httpProtocol: .https)).wait()) + XCTAssertNoThrow( + try self.channel.pipeline.addHandler(HTTP2ToHTTP1ClientCodec(streamID: streamID, httpProtocol: .https)) + .wait() + ) // A basic request without Host. let request = HTTPClientRequestPart.head(.init(version: .init(major: 1, minor: 1), method: .GET, uri: "/")) @@ -677,7 +897,10 @@ final class HTTP2ToHTTP1CodecTests: XCTestCase { @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") func testSendRequestWithDuplicateHost() throws { let streamID = HTTP2StreamID(1) - XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2ToHTTP1ClientCodec(streamID: streamID, httpProtocol: .https)).wait()) + XCTAssertNoThrow( + try self.channel.pipeline.addHandler(HTTP2ToHTTP1ClientCodec(streamID: streamID, httpProtocol: .https)) + .wait() + ) // A basic request with too many host headers. var requestHead = HTTPRequestHead(version: .init(major: 1, minor: 1), method: .GET, uri: "/") @@ -697,19 +920,27 @@ final class HTTP2ToHTTP1CodecTests: XCTestCase { @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") func testFramesWithoutHTTP1EquivalentAreIgnored() throws { let streamID = HTTP2StreamID(1) - XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2ToHTTP1ClientCodec(streamID: streamID, - httpProtocol: .https)).wait()) + XCTAssertNoThrow( + try self.channel.pipeline.addHandler( + HTTP2ToHTTP1ClientCodec( + streamID: streamID, + httpProtocol: .https + ) + ).wait() + ) let headers = HPACKHeaders([(":method", "GET"), (":scheme", "https"), (":path", "/x")]) - let frames: [HTTP2Frame.FramePayload] = [.alternativeService(origin: nil, field: nil), - .rstStream(.init(networkCode: 1)), - .priority(.init(exclusive: true, dependency: streamID, weight: 1)), - .windowUpdate(windowSizeIncrement: 1), - .settings(.ack), - .pushPromise(.init(pushedStreamID: HTTP2StreamID(2), headers: headers)), - .ping(.init(withInteger: 123), ack: true), - .goAway(lastStreamID: streamID, errorCode: .init(networkCode: 1), opaqueData: nil), - .origin([])] + let frames: [HTTP2Frame.FramePayload] = [ + .alternativeService(origin: nil, field: nil), + .rstStream(.init(networkCode: 1)), + .priority(.init(exclusive: true, dependency: streamID, weight: 1)), + .windowUpdate(windowSizeIncrement: 1), + .settings(.ack), + .pushPromise(.init(pushedStreamID: HTTP2StreamID(2), headers: headers)), + .ping(.init(withInteger: 123), ack: true), + .goAway(lastStreamID: streamID, errorCode: .init(networkCode: 1), opaqueData: nil), + .origin([]), + ] for payload in frames { let frame = HTTP2Frame(streamID: streamID, payload: payload) XCTAssertNoThrow(try self.channel.writeInbound(frame), "error on \(frame)") @@ -722,19 +953,27 @@ final class HTTP2ToHTTP1CodecTests: XCTestCase { let streamID = HTTP2StreamID(1) let writeRecorder = FrameWriteRecorder() XCTAssertNoThrow(try self.channel.pipeline.addHandler(writeRecorder).wait()) - XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2ToHTTP1ClientCodec(streamID: streamID, httpProtocol: .https)).wait()) + XCTAssertNoThrow( + try self.channel.pipeline.addHandler(HTTP2ToHTTP1ClientCodec(streamID: streamID, httpProtocol: .https)) + .wait() + ) // A basic request. var requestHead = HTTPRequestHead(version: .init(major: 2, minor: 0), method: .POST, uri: "/post") requestHead.headers = HTTPHeaders([("host", "example.org"), ("UpperCased", "Header")]) self.channel.writeAndFlush(HTTPClientRequestPart.head(requestHead), promise: nil) - let expectedRequestHeaders = HPACKHeaders([(":path", "/post"), (":method", "POST"), (":scheme", "https"), (":authority", "example.org"), ("uppercased", "Header")]) + let expectedRequestHeaders = HPACKHeaders([ + (":path", "/post"), (":method", "POST"), (":scheme", "https"), (":authority", "example.org"), + ("uppercased", "Header"), + ]) XCTAssertEqual(writeRecorder.flushedWrites.count, 1) - writeRecorder.flushedWrites[0].assertHeadersFrame(endStream: false, - streamID: 1, - headers: expectedRequestHeaders, - type: .request) + writeRecorder.flushedWrites[0].assertHeadersFrame( + endStream: false, + streamID: 1, + headers: expectedRequestHeaders, + type: .request + ) } @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") @@ -750,10 +989,12 @@ final class HTTP2ToHTTP1CodecTests: XCTestCase { let expectedRequestHeaders = HPACKHeaders([(":status", "200"), ("uppercased", "Header")]) XCTAssertEqual(writeRecorder.flushedWrites.count, 1) - writeRecorder.flushedWrites[0].assertHeadersFrame(endStream: false, - streamID: 1, - headers: expectedRequestHeaders, - type: .response) + writeRecorder.flushedWrites[0].assertHeadersFrame( + endStream: false, + streamID: 1, + headers: expectedRequestHeaders, + type: .response + ) } @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") @@ -761,22 +1002,32 @@ final class HTTP2ToHTTP1CodecTests: XCTestCase { let streamID = HTTP2StreamID(1) let writeRecorder = FrameWriteRecorder() XCTAssertNoThrow(try self.channel.pipeline.addHandler(writeRecorder).wait()) - XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2ToHTTP1ClientCodec(streamID: streamID, - httpProtocol: .https, - normalizeHTTPHeaders: false)).wait()) + XCTAssertNoThrow( + try self.channel.pipeline.addHandler( + HTTP2ToHTTP1ClientCodec( + streamID: streamID, + httpProtocol: .https, + normalizeHTTPHeaders: false + ) + ).wait() + ) // A basic request. var requestHead = HTTPRequestHead(version: .init(major: 2, minor: 0), method: .POST, uri: "/post") requestHead.headers = HTTPHeaders([("host", "example.org"), ("UpperCased", "Header")]) self.channel.writeAndFlush(HTTPClientRequestPart.head(requestHead), promise: nil) - let expectedRequestHeaders = HPACKHeaders([(":path", "/post"), (":method", "POST"), (":scheme", "https"), - (":authority", "example.org"), ("UpperCased", "Header")]) + let expectedRequestHeaders = HPACKHeaders([ + (":path", "/post"), (":method", "POST"), (":scheme", "https"), + (":authority", "example.org"), ("UpperCased", "Header"), + ]) XCTAssertEqual(writeRecorder.flushedWrites.count, 1) - writeRecorder.flushedWrites[0].assertHeadersFrame(endStream: false, - streamID: 1, - headers: expectedRequestHeaders, - type: .doNotValidate) + writeRecorder.flushedWrites[0].assertHeadersFrame( + endStream: false, + streamID: 1, + headers: expectedRequestHeaders, + type: .doNotValidate + ) } @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") @@ -784,8 +1035,14 @@ final class HTTP2ToHTTP1CodecTests: XCTestCase { let streamID = HTTP2StreamID(1) let writeRecorder = FrameWriteRecorder() XCTAssertNoThrow(try self.channel.pipeline.addHandler(writeRecorder).wait()) - XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2ToHTTP1ServerCodec(streamID: streamID, - normalizeHTTPHeaders: false)).wait()) + XCTAssertNoThrow( + try self.channel.pipeline.addHandler( + HTTP2ToHTTP1ServerCodec( + streamID: streamID, + normalizeHTTPHeaders: false + ) + ).wait() + ) var responseHead = HTTPResponseHead(version: .init(major: 2, minor: 0), status: .ok) responseHead.headers = HTTPHeaders([("UpperCased", "Header")]) @@ -793,10 +1050,12 @@ final class HTTP2ToHTTP1CodecTests: XCTestCase { let expectedRequestHeaders = HPACKHeaders([(":status", "200"), ("UpperCased", "Header")]) XCTAssertEqual(writeRecorder.flushedWrites.count, 1) - writeRecorder.flushedWrites[0].assertHeadersFrame(endStream: false, - streamID: 1, - headers: expectedRequestHeaders, - type: .doNotValidate) + writeRecorder.flushedWrites[0].assertHeadersFrame( + endStream: false, + streamID: 1, + headers: expectedRequestHeaders, + type: .doNotValidate + ) } @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") @@ -804,22 +1063,31 @@ final class HTTP2ToHTTP1CodecTests: XCTestCase { let streamID = HTTP2StreamID(1) let writeRecorder = FrameWriteRecorder() XCTAssertNoThrow(try self.channel.pipeline.addHandler(writeRecorder).wait()) - XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2ToHTTP1ClientCodec(streamID: streamID, httpProtocol: .https)).wait()) + XCTAssertNoThrow( + try self.channel.pipeline.addHandler(HTTP2ToHTTP1ClientCodec(streamID: streamID, httpProtocol: .https)) + .wait() + ) // A basic request. var requestHead = HTTPRequestHead(version: .init(major: 2, minor: 0), method: .POST, uri: "/post") - requestHead.headers = HTTPHeaders([("host", "example.org"), ("connection", "keep-alive, also-to-be-removed"), - ("keep-alive", "foo"), ("also-to-be-removed", "yes"), ("should", "stay"), - ("Proxy-Connection", "bad"), ("Transfer-Encoding", "also bad")]) + requestHead.headers = HTTPHeaders([ + ("host", "example.org"), ("connection", "keep-alive, also-to-be-removed"), + ("keep-alive", "foo"), ("also-to-be-removed", "yes"), ("should", "stay"), + ("Proxy-Connection", "bad"), ("Transfer-Encoding", "also bad"), + ]) self.channel.writeAndFlush(HTTPClientRequestPart.head(requestHead), promise: nil) - let expectedRequestHeaders = HPACKHeaders([(":path", "/post"), (":method", "POST"), (":scheme", "https"), - (":authority", "example.org"), ("should", "stay")]) + let expectedRequestHeaders = HPACKHeaders([ + (":path", "/post"), (":method", "POST"), (":scheme", "https"), + (":authority", "example.org"), ("should", "stay"), + ]) XCTAssertEqual(writeRecorder.flushedWrites.count, 1) - writeRecorder.flushedWrites[0].assertHeadersFrame(endStream: false, - streamID: 1, - headers: expectedRequestHeaders, - type: .request) + writeRecorder.flushedWrites[0].assertHeadersFrame( + endStream: false, + streamID: 1, + headers: expectedRequestHeaders, + type: .request + ) } @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") @@ -830,16 +1098,20 @@ final class HTTP2ToHTTP1CodecTests: XCTestCase { XCTAssertNoThrow(try self.channel.pipeline.addHandler(HTTP2ToHTTP1ServerCodec(streamID: streamID)).wait()) var responseHead = HTTPResponseHead(version: .init(major: 2, minor: 0), status: .ok) - responseHead.headers = HTTPHeaders([("connection", "keep-alive, also-to-be-removed"), - ("keep-alive", "foo"), ("also-to-be-removed", "yes"), ("should", "stay"), - ("Proxy-Connection", "bad"), ("Transfer-Encoding", "also bad")]) + responseHead.headers = HTTPHeaders([ + ("connection", "keep-alive, also-to-be-removed"), + ("keep-alive", "foo"), ("also-to-be-removed", "yes"), ("should", "stay"), + ("Proxy-Connection", "bad"), ("Transfer-Encoding", "also bad"), + ]) self.channel.writeAndFlush(HTTPServerResponsePart.head(responseHead), promise: nil) let expectedRequestHeaders = HPACKHeaders([(":status", "200"), ("should", "stay")]) XCTAssertEqual(writeRecorder.flushedWrites.count, 1) - writeRecorder.flushedWrites[0].assertHeadersFrame(endStream: false, - streamID: 1, - headers: expectedRequestHeaders, - type: .response) + writeRecorder.flushedWrites[0].assertHeadersFrame( + endStream: false, + streamID: 1, + headers: expectedRequestHeaders, + type: .response + ) } } diff --git a/Tests/NIOHTTP2Tests/InboundWindowManagerTests.swift b/Tests/NIOHTTP2Tests/InboundWindowManagerTests.swift index 7fb1ee3..5179c7f 100644 --- a/Tests/NIOHTTP2Tests/InboundWindowManagerTests.swift +++ b/Tests/NIOHTTP2Tests/InboundWindowManagerTests.swift @@ -12,9 +12,10 @@ // //===----------------------------------------------------------------------===// -@testable import NIOHTTP2 import XCTest +@testable import NIOHTTP2 + class InboundWindowManagerTests: XCTestCase { func testNewWindowSizeWhenNewSizeIsAtOrAboveTarget() { diff --git a/Tests/NIOHTTP2Tests/OutboundFlowControlBufferTests.swift b/Tests/NIOHTTP2Tests/OutboundFlowControlBufferTests.swift index 82ad6ed..55af3b7 100644 --- a/Tests/NIOHTTP2Tests/OutboundFlowControlBufferTests.swift +++ b/Tests/NIOHTTP2Tests/OutboundFlowControlBufferTests.swift @@ -12,14 +12,14 @@ // //===----------------------------------------------------------------------===// -import XCTest import Atomics import NIOCore import NIOEmbedded -import NIOHTTP1 -@testable import NIOHTTP2 import NIOHPACK +import NIOHTTP1 +import XCTest +@testable import NIOHTTP2 class OutboundFlowControlBufferTests: XCTestCase { var loop: EmbeddedEventLoop! @@ -37,7 +37,7 @@ class OutboundFlowControlBufferTests: XCTestCase { } private func makeWritePromise() -> EventLoopPromise { - return self.loop.makePromise() + self.loop.makePromise() } private func receivedFrames(file: StaticString = #filePath, line: UInt = #line) -> [HTTP2Frame] { @@ -137,7 +137,10 @@ class OutboundFlowControlBufferTests: XCTestCase { // We also send a WindowUpdate frame, a RST_STREAM frame, and a PRIORITY frame. let windowUpdateFrame = HTTP2Frame(streamID: streamOne, payload: .windowUpdate(windowSizeIncrement: 500)) - let priorityFrame = HTTP2Frame(streamID: streamOne, payload: .priority(.init(exclusive: false, dependency: 0, weight: 50))) + let priorityFrame = HTTP2Frame( + streamID: streamOne, + payload: .priority(.init(exclusive: false, dependency: 0, weight: 50)) + ) let rstStreamFrame = HTTP2Frame(streamID: streamOne, payload: .rstStream(.protocolError)) // All of these frames are written. @@ -196,7 +199,10 @@ class OutboundFlowControlBufferTests: XCTestCase { let streamOne = HTTP2StreamID(1) // Start by sending a headers frame through, even before createStream is fired. This should pass unmolested. - let headers = HTTP2Frame(streamID: streamOne, payload: .headers(.init(headers: HPACKHeaders([("name", "value")])))) + let headers = HTTP2Frame( + streamID: streamOne, + payload: .headers(.init(headers: HPACKHeaders([("name", "value")]))) + ) XCTAssertNoThrow(try self.buffer.processOutboundFrame(headers, promise: nil).assertForward()) // Now send createStream, and another headers frame. This is also fine. @@ -204,7 +210,10 @@ class OutboundFlowControlBufferTests: XCTestCase { XCTAssertNoThrow(try self.buffer.processOutboundFrame(headers, promise: nil).assertForward()) // Now send a large DATA frame that is going to be buffered, followed by a HEADERS frame. - let endHeaders = HTTP2Frame(streamID: streamOne, payload: .headers(.init(headers: HPACKHeaders([("name", "value")]), endStream: true))) + let endHeaders = HTTP2Frame( + streamID: streamOne, + payload: .headers(.init(headers: HPACKHeaders([("name", "value")]), endStream: true)) + ) var frame = self.createDataFrame(streamOne, byteBufferSize: 50) XCTAssertNoThrow(try self.buffer.processOutboundFrame(frame, promise: nil).assertNothing()) XCTAssertNoThrow(try self.buffer.processOutboundFrame(endHeaders, promise: nil).assertNothing()) @@ -232,7 +241,10 @@ class OutboundFlowControlBufferTests: XCTestCase { let headersPromise = self.loop.makePromise(of: Void.self) var dataFrame = self.createDataFrame(streamOne, byteBufferSize: 50) - let headersFrame = HTTP2Frame(streamID: streamOne, payload: .headers(.init(headers: HPACKHeaders([("key", "value")])))) + let headersFrame = HTTP2Frame( + streamID: streamOne, + payload: .headers(.init(headers: HPACKHeaders([("key", "value")]))) + ) XCTAssertNoThrow(try self.buffer.processOutboundFrame(dataFrame, promise: dataPromise).assertNothing()) XCTAssertNoThrow(try self.buffer.processOutboundFrame(headersFrame, promise: headersPromise).assertNothing()) self.buffer.flushReceived() @@ -281,16 +293,18 @@ class OutboundFlowControlBufferTests: XCTestCase { func testOverlargeFramesAreSplitOnMaxFrameSizeByteBuffer() { let streamOne = HTTP2StreamID(1) - self.buffer.streamCreated(streamOne, initialWindowSize: 1<<16) - self.buffer.connectionWindowSize = 1<<24 + self.buffer.streamCreated(streamOne, initialWindowSize: 1 << 16) + self.buffer.connectionWindowSize = 1 << 24 var dataFrame = self.createDataFrame(streamOne, byteBufferSize: (1 << 16) + 1) XCTAssertNoThrow(try self.buffer.processOutboundFrame(dataFrame, promise: nil).assertNothing()) XCTAssertEqual(0, self.receivedFrames().count) - self.buffer.maxFrameSize = 1<<15 + self.buffer.maxFrameSize = 1 << 15 self.buffer.flushReceived() - self.receivedFrames().assertFramesMatch([dataFrame.sliceDataFrame(length: 1<<15), dataFrame.sliceDataFrame(length: 1<<15)]) + self.receivedFrames().assertFramesMatch([ + dataFrame.sliceDataFrame(length: 1 << 15), dataFrame.sliceDataFrame(length: 1 << 15), + ]) // Update the window. self.buffer.updateWindowOfStream(streamOne, newSize: 20) @@ -299,16 +313,19 @@ class OutboundFlowControlBufferTests: XCTestCase { func testOverlargeFramesAreSplitOnMaxFrameSizeFileRegion() { let streamOne = HTTP2StreamID(1) - self.buffer.streamCreated(streamOne, initialWindowSize: 1<<16) - self.buffer.connectionWindowSize = 1<<24 + self.buffer.streamCreated(streamOne, initialWindowSize: 1 << 16) + self.buffer.connectionWindowSize = 1 << 24 var dataFrame = self.createDataFrame(streamOne, fileRegionSize: (1 << 16) + 1) XCTAssertNoThrow(try self.buffer.processOutboundFrame(dataFrame, promise: nil).assertNothing()) XCTAssertEqual(0, self.receivedFrames().count) - self.buffer.maxFrameSize = 1<<15 + self.buffer.maxFrameSize = 1 << 15 self.buffer.flushReceived() - self.receivedFrames().assertFramesMatch([dataFrame.sliceDataFrame(length: 1<<15), dataFrame.sliceDataFrame(length: 1<<15)], dataFileRegionToByteBuffer: false) + self.receivedFrames().assertFramesMatch( + [dataFrame.sliceDataFrame(length: 1 << 15), dataFrame.sliceDataFrame(length: 1 << 15)], + dataFileRegionToByteBuffer: false + ) // Update the window. self.buffer.updateWindowOfStream(streamOne, newSize: 20) @@ -354,7 +371,9 @@ class OutboundFlowControlBufferTests: XCTestCase { // Let the window be consumed. self.buffer.flushReceived() - self.receivedFrames().sorted(by: { $0.streamID < $1.streamID }).assertFramesMatch([oneFrame.sliceDataFrame(length: 15), threeFrame]) + self.receivedFrames().sorted(by: { $0.streamID < $1.streamID }).assertFramesMatch([ + oneFrame.sliceDataFrame(length: 15), threeFrame, + ]) // Ok, now we can increase the window size for all streams. This makes more data available. self.buffer.initialWindowSizeChanged(10) @@ -375,10 +394,17 @@ class OutboundFlowControlBufferTests: XCTestCase { } func testRejectsPrioritySelfDependency() { - XCTAssertThrowsError(try self.buffer.priorityUpdate(streamID: 1, priorityData: .init(exclusive: false, dependency: 1, weight: 36))) { error in + XCTAssertThrowsError( + try self.buffer.priorityUpdate( + streamID: 1, + priorityData: .init(exclusive: false, dependency: 1, weight: 36) + ) + ) { error in XCTAssertEqual(error as? NIOHTTP2Errors.PriorityCycle, NIOHTTP2Errors.priorityCycle(streamID: 1)) } - XCTAssertThrowsError(try self.buffer.priorityUpdate(streamID: 1, priorityData: .init(exclusive: true, dependency: 1, weight: 36))) { error in + XCTAssertThrowsError( + try self.buffer.priorityUpdate(streamID: 1, priorityData: .init(exclusive: true, dependency: 1, weight: 36)) + ) { error in XCTAssertEqual(error as? NIOHTTP2Errors.PriorityCycle, NIOHTTP2Errors.priorityCycle(streamID: 1)) } } @@ -471,7 +497,6 @@ class OutboundFlowControlBufferTests: XCTestCase { } } - /// Various helpers that make tests easier to understand. extension OutboundFlowControlBufferTests { func createDataFrame(_ streamID: HTTP2StreamID, byteBufferSize: Int, endStream: Bool = false) -> HTTP2Frame { @@ -489,7 +514,6 @@ extension OutboundFlowControlBufferTests { } } - extension IOData { mutating func readSlice(length: Int) -> IOData { switch self { @@ -498,7 +522,11 @@ extension IOData { self = .byteBuffer(buf) return .byteBuffer(slice) case .fileRegion(var region): - let slice = FileRegion(fileHandle: region.fileHandle, readerIndex: region.readerIndex, endIndex: region.readerIndex + length) + let slice = FileRegion( + fileHandle: region.fileHandle, + readerIndex: region.readerIndex, + endIndex: region.readerIndex + length + ) region.moveReaderIndex(forwardBy: length) self = .fileRegion(region) return .fileRegion(slice) @@ -506,7 +534,6 @@ extension IOData { } } - extension HTTP2Frame { mutating func sliceDataFrame(length: Int) -> HTTP2Frame { guard case .data(var dataPayload) = self.payload else { diff --git a/Tests/NIOHTTP2Tests/ReentrancyTests.swift b/Tests/NIOHTTP2Tests/ReentrancyTests.swift index e1e7246..bc96eef 100644 --- a/Tests/NIOHTTP2Tests/ReentrancyTests.swift +++ b/Tests/NIOHTTP2Tests/ReentrancyTests.swift @@ -12,12 +12,12 @@ // //===----------------------------------------------------------------------===// -import XCTest import NIOCore import NIOEmbedded +import NIOHPACK import NIOHTTP1 import NIOHTTP2 -import NIOHPACK +import XCTest /// A `ChannelInboundHandler` that re-entrantly calls into a handler that just passed /// it `channelRead`. @@ -51,7 +51,7 @@ final class WindowUpdatedEventHandler: ChannelInboundHandler { init() { } - + func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) { guard event is NIOHTTP2WindowUpdatedEvent else { return } @@ -90,7 +90,9 @@ final class ReentrancyTests: XCTestCase { // Here we're going to prepare some frames: specifically, we're going to send a SETTINGS frame and a PING frame at the same time. // We need to send two frames to try to catch any ordering problems we might hit. - let settings: [HTTP2Setting] = [HTTP2Setting(parameter: .enablePush, value: 0), HTTP2Setting(parameter: .maxConcurrentStreams, value: 5)] + let settings: [HTTP2Setting] = [ + HTTP2Setting(parameter: .enablePush, value: 0), HTTP2Setting(parameter: .maxConcurrentStreams, value: 5), + ] let settingsFrame = HTTP2Frame(streamID: .rootStream, payload: .settings(.settings(settings))) let pingFrame = HTTP2Frame(streamID: .rootStream, payload: .ping(HTTP2PingData(withInteger: 5), ack: false)) self.clientChannel.write(settingsFrame, promise: nil) @@ -99,7 +101,9 @@ final class ReentrancyTests: XCTestCase { // Collect the serialized frames. var frameBuffer = self.clientChannel.allocator.buffer(capacity: 1024) - while case .some(.byteBuffer(var buf)) = try assertNoThrowWithValue(self.clientChannel.readOutbound(as: IOData.self)) { + while case .some(.byteBuffer(var buf)) = try assertNoThrowWithValue( + self.clientChannel.readOutbound(as: IOData.self) + ) { frameBuffer.writeBuffer(&buf) } @@ -128,7 +132,9 @@ final class ReentrancyTests: XCTestCase { // Here we're going to prepare some frames: specifically, we're going to send a SETTINGS frame and a PING frame at the same time. // We need to send two frames to try to catch any ordering problems we might hit. - let settings: [HTTP2Setting] = [HTTP2Setting(parameter: .enablePush, value: 0), HTTP2Setting(parameter: .maxConcurrentStreams, value: 5)] + let settings: [HTTP2Setting] = [ + HTTP2Setting(parameter: .enablePush, value: 0), HTTP2Setting(parameter: .maxConcurrentStreams, value: 5), + ] let settingsFrame = HTTP2Frame(streamID: .rootStream, payload: .settings(.settings(settings))) let pingFrame = HTTP2Frame(streamID: .rootStream, payload: .ping(HTTP2PingData(withInteger: 5), ack: false)) self.clientChannel.write(settingsFrame, promise: nil) @@ -157,7 +163,9 @@ final class ReentrancyTests: XCTestCase { // Here we're going to prepare some frames: specifically, we're going to send a SETTINGS frame and a PING frame at the same time. // We need to send two frames to try to catch any ordering problems we might hit. - let settings: [HTTP2Setting] = [HTTP2Setting(parameter: .enablePush, value: 0), HTTP2Setting(parameter: .maxConcurrentStreams, value: 5)] + let settings: [HTTP2Setting] = [ + HTTP2Setting(parameter: .enablePush, value: 0), HTTP2Setting(parameter: .maxConcurrentStreams, value: 5), + ] let settingsFrame = HTTP2Frame(streamID: .rootStream, payload: .settings(.settings(settings))) let pingFrame = HTTP2Frame(streamID: .rootStream, payload: .ping(HTTP2PingData(withInteger: 5), ack: false)) self.clientChannel.write(settingsFrame, promise: nil) @@ -180,24 +188,26 @@ final class ReentrancyTests: XCTestCase { XCTAssertNoThrow(try self.clientChannel.finish()) XCTAssertNoThrow(try self.serverChannel.finish()) } - + func testReenterAutomaticFrames() throws { // Start by setting up the connection. try self.basicHTTP2Connection() let windowUpdateFrameHandler = WindowUpdatedEventHandler() XCTAssertNoThrow(try self.serverChannel.pipeline.addHandler(windowUpdateFrameHandler).wait()) - + // Write and flush the header from the client to open a stream - let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")]) + let headers = HPACKHeaders([ + (":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost"), + ]) let reqFramePayload = HTTP2Frame.FramePayload.headers(.init(headers: headers)) self.clientChannel.writeAndFlush(HTTP2Frame(streamID: 1, payload: reqFramePayload), promise: nil) self.interactInMemory(clientChannel, serverChannel) - + // Write and flush the header from the server let resHeaders = HPACKHeaders([(":status", "200")]) let resFramePayload = HTTP2Frame.FramePayload.headers(.init(headers: resHeaders)) self.serverChannel.writeAndFlush(HTTP2Frame(streamID: 1, payload: resFramePayload), promise: nil) - + // Write lots of small data frames and flush them all at once var requestBody = self.serverChannel.allocator.buffer(capacity: 1) requestBody.writeBytes(Array(repeating: UInt8(0x04), count: 1)) diff --git a/Tests/NIOHTTP2Tests/SimpleClientServerFramePayloadStreamTests.swift b/Tests/NIOHTTP2Tests/SimpleClientServerFramePayloadStreamTests.swift index 9746eb5..61a8405 100644 --- a/Tests/NIOHTTP2Tests/SimpleClientServerFramePayloadStreamTests.swift +++ b/Tests/NIOHTTP2Tests/SimpleClientServerFramePayloadStreamTests.swift @@ -12,11 +12,12 @@ // //===----------------------------------------------------------------------===// -import XCTest import NIOConcurrencyHelpers import NIOCore import NIOEmbedded import NIOHPACK +import XCTest + @testable import NIOHTTP2 /// A channel handler that passes writes through but fires EOF once the first one hits. @@ -115,7 +116,10 @@ final class InstaGoawayHandler: ChannelInboundHandler { func channelRead(context: ChannelHandlerContext, data: NIOAny) { let frame = self.unwrapInboundIn(data) if case .headers = frame.payload { - let kaboomFrame = HTTP2Frame(streamID: .rootStream, payload: .goAway(lastStreamID: .rootStream, errorCode: .inadequateSecurity, opaqueData: nil)) + let kaboomFrame = HTTP2Frame( + streamID: .rootStream, + payload: .goAway(lastStreamID: .rootStream, errorCode: .inadequateSecurity, opaqueData: nil) + ) context.writeAndFlush(self.wrapOutboundOut(kaboomFrame), promise: nil) } } @@ -176,8 +180,11 @@ class HTTP2ParserProxyHandler: ChannelInboundHandler, RemovableChannelHandler { typealias InboundIn = ByteBuffer func channelRead(context: ChannelHandlerContext, data: NIOAny) { - XCTAssertNoThrow(try context.pipeline.addHandler( - NIOHTTP2Handler(mode: .server)).wait()) + XCTAssertNoThrow( + try context.pipeline.addHandler( + NIOHTTP2Handler(mode: .server) + ).wait() + ) context.fireChannelRead(data) _ = context.pipeline.removeHandler(context: context) } @@ -198,31 +205,61 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { } /// Establish a basic HTTP/2 connection. - func basicHTTP2Connection(clientSettings: HTTP2Settings = nioDefaultSettings, - serverSettings: HTTP2Settings = nioDefaultSettings, - maximumBufferedControlFrames: Int = 10000, - maximumSequentialContinuationFrames: Int = 5, - withMultiplexerCallback multiplexerCallback: NIOChannelInitializer? = nil) throws { - XCTAssertNoThrow(try self.clientChannel.pipeline.addHandler(NIOHTTP2Handler(mode: .client, - initialSettings: clientSettings, - maximumBufferedControlFrames: maximumBufferedControlFrames, - maximumSequentialContinuationFrames: maximumSequentialContinuationFrames)).wait()) - XCTAssertNoThrow(try self.serverChannel.pipeline.addHandler(NIOHTTP2Handler(mode: .server, - initialSettings: serverSettings, - maximumBufferedControlFrames: maximumBufferedControlFrames, - maximumSequentialContinuationFrames: maximumSequentialContinuationFrames)).wait()) + func basicHTTP2Connection( + clientSettings: HTTP2Settings = nioDefaultSettings, + serverSettings: HTTP2Settings = nioDefaultSettings, + maximumBufferedControlFrames: Int = 10000, + maximumSequentialContinuationFrames: Int = 5, + withMultiplexerCallback multiplexerCallback: NIOChannelInitializer? = nil + ) throws { + XCTAssertNoThrow( + try self.clientChannel.pipeline.addHandler( + NIOHTTP2Handler( + mode: .client, + initialSettings: clientSettings, + maximumBufferedControlFrames: maximumBufferedControlFrames, + maximumSequentialContinuationFrames: maximumSequentialContinuationFrames + ) + ).wait() + ) + XCTAssertNoThrow( + try self.serverChannel.pipeline.addHandler( + NIOHTTP2Handler( + mode: .server, + initialSettings: serverSettings, + maximumBufferedControlFrames: maximumBufferedControlFrames, + maximumSequentialContinuationFrames: maximumSequentialContinuationFrames + ) + ).wait() + ) if let multiplexerCallback = multiplexerCallback { - XCTAssertNoThrow(try self.clientChannel.pipeline.addHandler(HTTP2StreamMultiplexer(mode: .client, - channel: self.clientChannel, - inboundStreamInitializer: multiplexerCallback)).wait()) - XCTAssertNoThrow(try self.serverChannel.pipeline.addHandler(HTTP2StreamMultiplexer(mode: .server, - channel: self.serverChannel, - inboundStreamInitializer: multiplexerCallback)).wait()) + XCTAssertNoThrow( + try self.clientChannel.pipeline.addHandler( + HTTP2StreamMultiplexer( + mode: .client, + channel: self.clientChannel, + inboundStreamInitializer: multiplexerCallback + ) + ).wait() + ) + XCTAssertNoThrow( + try self.serverChannel.pipeline.addHandler( + HTTP2StreamMultiplexer( + mode: .server, + channel: self.serverChannel, + inboundStreamInitializer: multiplexerCallback + ) + ).wait() + ) } - try self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel, - clientSettings: clientSettings, serverSettings: serverSettings) + try self.assertDoHandshake( + client: self.clientChannel, + server: self.serverChannel, + clientSettings: clientSettings, + serverSettings: serverSettings + ) } /// Establish a basic HTTP/2 connection where the HTTP2Parser handler is added after the channel has been activated. @@ -237,19 +274,31 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { try self.basicHTTP2Connection() // We're now going to try to send a request from the client to the server. - let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")]) + let headers = HPACKHeaders([ + (":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost"), + ]) var requestBody = self.clientChannel.allocator.buffer(capacity: 128) requestBody.writeStaticString("A simple HTTP/2 request.") let clientStreamID = HTTP2StreamID(1) let reqFrame = HTTP2Frame(streamID: clientStreamID, payload: .headers(.init(headers: headers))) - let reqBodyFrame = HTTP2Frame(streamID: clientStreamID, payload: .data(.init(data: .byteBuffer(requestBody), endStream: true))) + let reqBodyFrame = HTTP2Frame( + streamID: clientStreamID, + payload: .data(.init(data: .byteBuffer(requestBody), endStream: true)) + ) - let serverStreamID = try self.assertFramesRoundTrip(frames: [reqFrame, reqBodyFrame], sender: self.clientChannel, receiver: self.serverChannel).first!.streamID + let serverStreamID = try self.assertFramesRoundTrip( + frames: [reqFrame, reqBodyFrame], + sender: self.clientChannel, + receiver: self.serverChannel + ).first!.streamID // Let's send a quick response back. let responseHeaders = HPACKHeaders([(":status", "200"), ("content-length", "0")]) - let respFrame = HTTP2Frame(streamID: serverStreamID, payload: .headers(.init(headers: responseHeaders, endStream: true))) + let respFrame = HTTP2Frame( + streamID: serverStreamID, + payload: .headers(.init(headers: responseHeaders, endStream: true)) + ) try self.assertFramesRoundTrip(frames: [respFrame], sender: self.serverChannel, receiver: self.clientChannel) XCTAssertNoThrow(try self.clientChannel.finish()) @@ -261,19 +310,31 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { try self.basicHTTP2DynamicPipelineConnection() // We're now going to try to send a request from the client to the server. - let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")]) + let headers = HPACKHeaders([ + (":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost"), + ]) var requestBody = self.clientChannel.allocator.buffer(capacity: 128) requestBody.writeStaticString("A simple HTTP/2 request.") let clientStreamID = HTTP2StreamID(1) let reqFrame = HTTP2Frame(streamID: clientStreamID, payload: .headers(.init(headers: headers))) - let reqBodyFrame = HTTP2Frame(streamID: clientStreamID, payload: .data(.init(data: .byteBuffer(requestBody), endStream: true))) + let reqBodyFrame = HTTP2Frame( + streamID: clientStreamID, + payload: .data(.init(data: .byteBuffer(requestBody), endStream: true)) + ) - let serverStreamID = try self.assertFramesRoundTrip(frames: [reqFrame, reqBodyFrame], sender: self.clientChannel, receiver: self.serverChannel).first!.streamID + let serverStreamID = try self.assertFramesRoundTrip( + frames: [reqFrame, reqBodyFrame], + sender: self.clientChannel, + receiver: self.serverChannel + ).first!.streamID // Let's send a quick response back. let responseHeaders = HPACKHeaders([(":status", "200"), ("content-length", "0")]) - let respFrame = HTTP2Frame(streamID: serverStreamID, payload: .headers(.init(headers: responseHeaders, endStream: true))) + let respFrame = HTTP2Frame( + streamID: serverStreamID, + payload: .headers(.init(headers: responseHeaders, endStream: true)) + ) try self.assertFramesRoundTrip(frames: [respFrame], sender: self.serverChannel, receiver: self.clientChannel) XCTAssertNoThrow(try self.clientChannel.finish()) @@ -284,7 +345,9 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { // Begin by getting the connection up. try self.basicHTTP2Connection() - let requestHeaders = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")]) + let requestHeaders = HPACKHeaders([ + (":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost"), + ]) var requestBody = self.clientChannel.allocator.buffer(capacity: 128) requestBody.writeStaticString("A simple HTTP/2 request.") @@ -296,7 +359,10 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { for id in [1, 3, 5] { let streamID = HTTP2StreamID(id) let reqFrame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: requestHeaders))) - let reqBodyFrame = HTTP2Frame(streamID: streamID, payload: .data(.init(data: .byteBuffer(requestBody), endStream: true))) + let reqBodyFrame = HTTP2Frame( + streamID: streamID, + payload: .data(.init(data: .byteBuffer(requestBody), endStream: true)) + ) self.clientChannel.write(reqFrame, promise: nil) self.clientChannel.write(reqBodyFrame, promise: nil) @@ -314,7 +380,9 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { let receivedFrame = try self.serverChannel.assertReceivedFrame() receivedFrame.assertFrameMatches(this: frame) } - var receivedBodyFrames: [HTTP2Frame] = try assertNoThrowWithValue((0...size)) { + var bodyData = self.clientChannel.allocator.buffer(capacity: 1 << 14) + for val in (0..<((1 << 14) / MemoryLayout.size)) { bodyData.writeInteger(val) } @@ -489,14 +618,18 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { let clientHandler = InboundFramePayloadRecorder() let childChannelPromise = self.clientChannel.eventLoop.makePromise(of: Channel.self) - try (self.clientChannel.pipeline.context(handlerType: HTTP2StreamMultiplexer.self).wait().handler as! HTTP2StreamMultiplexer).createStreamChannel(promise: childChannelPromise) { channel in - return channel.pipeline.addHandler(clientHandler) - } + try + (self.clientChannel.pipeline.context(handlerType: HTTP2StreamMultiplexer.self).wait().handler + as! HTTP2StreamMultiplexer).createStreamChannel(promise: childChannelPromise) { channel in + channel.pipeline.addHandler(clientHandler) + } (self.clientChannel.eventLoop as! EmbeddedEventLoop).run() let childChannel = try childChannelPromise.futureResult.wait() // Start by sending the headers. - let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")]) + let headers = HPACKHeaders([ + (":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost"), + ]) let reqFrame = HTTP2Frame.FramePayload.headers(.init(headers: headers)) childChannel.writeAndFlush(reqFrame, promise: nil) self.interactInMemory(self.clientChannel, self.serverChannel) @@ -511,12 +644,16 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { self.interactInMemory(self.clientChannel, self.serverChannel) // We now expect 3 frames. - let dataFrames = (0..<3).map { idx in HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(bodyData), endStream: idx == 2)) } + let dataFrames = (0..<3).map { idx in + HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(bodyData), endStream: idx == 2)) + } serverHandler.receivedFrames.assertFramePayloadsMatch([reqFrame] + dataFrames) // The client will have seen a pair of window updates: one on the connection, one on the stream. try self.clientChannel.assertReceivedFrame().assertWindowUpdateFrame(streamID: 0, windowIncrement: 32768) - clientHandler.receivedFrames.assertFramePayloadsMatch([HTTP2Frame.FramePayload.windowUpdate(windowSizeIncrement: 32768)]) + clientHandler.receivedFrames.assertFramePayloadsMatch([ + HTTP2Frame.FramePayload.windowUpdate(windowSizeIncrement: 32768) + ]) // No frames left. self.clientChannel.assertNoFramesReceived() @@ -531,7 +668,9 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { // Begin by getting the connection up. try self.basicHTTP2Connection() - let requestHeaders = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")]) + let requestHeaders = HPACKHeaders([ + (":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost"), + ]) var requestBody = self.clientChannel.allocator.buffer(capacity: 128) requestBody.writeStaticString("A simple HTTP/2 request.") @@ -565,11 +704,17 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { self.serverChannel.assertNoFramesReceived() // Let's complete one of the streams by sending data for the first stream on the client, and responding on the server. - let dataFrame = HTTP2Frame(streamID: clientStreamIDs.first!, payload: .data(.init(data: .byteBuffer(requestBody), endStream: true))) + let dataFrame = HTTP2Frame( + streamID: clientStreamIDs.first!, + payload: .data(.init(data: .byteBuffer(requestBody), endStream: true)) + ) self.clientChannel.writeAndFlush(dataFrame, promise: nil) let responseHeaders = HPACKHeaders([(":status", "200"), ("content-length", "0")]) - let respFrame = HTTP2Frame(streamID: serverStreamIDs.first!, payload: .headers(.init(headers :responseHeaders, endStream: true))) + let respFrame = HTTP2Frame( + streamID: serverStreamIDs.first!, + payload: .headers(.init(headers: responseHeaders, endStream: true)) + ) self.serverChannel.writeAndFlush(respFrame, promise: nil) // Now we expect the following things to have happened: 1) the client will have seen the server's response, @@ -593,11 +738,18 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { let initialSettings = [ HTTP2Setting(parameter: .maxHeaderListSize, value: 1000), HTTP2Setting(parameter: .initialWindowSize, value: 100), - HTTP2Setting(parameter: .enablePush, value: 0) + HTTP2Setting(parameter: .enablePush, value: 0), ] - XCTAssertNoThrow(try self.clientChannel.pipeline.addHandler(NIOHTTP2Handler(mode: .client, initialSettings: initialSettings)).wait()) + XCTAssertNoThrow( + try self.clientChannel.pipeline.addHandler(NIOHTTP2Handler(mode: .client, initialSettings: initialSettings)) + .wait() + ) XCTAssertNoThrow(try self.serverChannel.pipeline.addHandler(NIOHTTP2Handler(mode: .server)).wait()) - try self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel, clientSettings: initialSettings) + try self.assertDoHandshake( + client: self.clientChannel, + server: self.serverChannel, + clientSettings: initialSettings + ) // There should be no frames here. self.clientChannel.assertNoFramesReceived() @@ -635,19 +787,23 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { func testAutomaticFlowControl() throws { // Begin by getting the connection up. // We add the stream multiplexer here because it manages automatic flow control. - try self.basicHTTP2Connection() { channel in - return channel.eventLoop.makeSucceededFuture(()) + try self.basicHTTP2Connection { channel in + channel.eventLoop.makeSucceededFuture(()) } // Now we're going to send a request, including a very large body: 65536 bytes in size. To avoid spending too much // time initializing buffers, we're going to send the same 1kB data frame 64 times. - let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")]) + let headers = HPACKHeaders([ + (":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost"), + ]) var _requestBody = self.clientChannel.allocator.buffer(capacity: 1024) _requestBody.writeBytes(Array(repeating: UInt8(0x04), count: 1024)) let requestBody = _requestBody // We're going to open a stream and queue up the frames for that stream. - let handler = try self.clientChannel.pipeline.context(handlerType: HTTP2StreamMultiplexer.self).wait().handler as! HTTP2StreamMultiplexer + let handler = + try self.clientChannel.pipeline.context(handlerType: HTTP2StreamMultiplexer.self).wait().handler + as! HTTP2StreamMultiplexer let childHandler = InboundFramePayloadRecorder() handler.createStreamChannel(promise: nil) { channel in let reqFramePayload = HTTP2Frame.FramePayload.headers(.init(headers: headers)) @@ -694,13 +850,23 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { pingBuffer.writeInteger(UInt32(0)) pingBuffer.writeInteger(UInt64(0)) - XCTAssertNoThrow(try self.serverChannel.writeInbound(pingBuffer.getSlice(at: pingBuffer.readerIndex, length: 8))) - XCTAssertNoThrow(try self.serverChannel.writeInbound(pingBuffer.getSlice(at: pingBuffer.readerIndex + 8, length: 9))) - try self.serverChannel.assertReceivedFrame().assertPingFrame(ack: false, opaqueData: HTTP2PingData(withInteger: 0)) + XCTAssertNoThrow( + try self.serverChannel.writeInbound(pingBuffer.getSlice(at: pingBuffer.readerIndex, length: 8)) + ) + XCTAssertNoThrow( + try self.serverChannel.writeInbound(pingBuffer.getSlice(at: pingBuffer.readerIndex + 8, length: 9)) + ) + try self.serverChannel.assertReceivedFrame().assertPingFrame( + ack: false, + opaqueData: HTTP2PingData(withInteger: 0) + ) // We should have a PING response. Let's check it. self.interactInMemory(self.serverChannel, self.clientChannel) - try self.clientChannel.assertReceivedFrame().assertPingFrame(ack: true, opaqueData: HTTP2PingData(withInteger: 0)) + try self.clientChannel.assertReceivedFrame().assertPingFrame( + ack: true, + opaqueData: HTTP2PingData(withInteger: 0) + ) // No other frames should be emitted. self.clientChannel.assertNoFramesReceived() @@ -715,7 +881,9 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { // We're now going to try to send a request from the client to the server. This request will be one headers frame, one // data frame, and then another headers frame for trailers. - let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")]) + let headers = HPACKHeaders([ + (":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost"), + ]) let trailers = HPACKHeaders([("x-trailers-field", "true")]) var requestBody = self.clientChannel.allocator.buffer(capacity: 128) requestBody.writeStaticString("A simple HTTP/2 request.") @@ -723,14 +891,24 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { let clientStreamID = HTTP2StreamID(1) let reqFrame = HTTP2Frame(streamID: clientStreamID, payload: .headers(.init(headers: headers))) let reqBodyFrame = HTTP2Frame(streamID: clientStreamID, payload: .data(.init(data: .byteBuffer(requestBody)))) - let trailerFrame = HTTP2Frame(streamID: clientStreamID, payload: .headers(.init(headers: trailers, endStream: true))) + let trailerFrame = HTTP2Frame( + streamID: clientStreamID, + payload: .headers(.init(headers: trailers, endStream: true)) + ) - let serverStreamID = try self.assertFramesRoundTrip(frames: [reqFrame, reqBodyFrame, trailerFrame], sender: self.clientChannel, receiver: self.serverChannel).first!.streamID + let serverStreamID = try self.assertFramesRoundTrip( + frames: [reqFrame, reqBodyFrame, trailerFrame], + sender: self.clientChannel, + receiver: self.serverChannel + ).first!.streamID // Let's send a quick response back. This response should also contain trailers. let responseHeaders = HPACKHeaders([(":status", "200"), ("content-length", "0")]) let respFrame = HTTP2Frame(streamID: serverStreamID, payload: .headers(.init(headers: responseHeaders))) - let respTrailersFrame = HTTP2Frame(streamID: serverStreamID, payload: .headers(.init(headers: trailers, endStream: true))) + let respTrailersFrame = HTTP2Frame( + streamID: serverStreamID, + payload: .headers(.init(headers: trailers, endStream: true)) + ) let expectedFrames = [respFrame, respTrailersFrame] @@ -745,20 +923,33 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { try self.basicHTTP2Connection() // We're now going to try to send a simple request from the client. - let headers = HPACKHeaders([(":path", "/"), (":method", "GET"), (":scheme", "https"), (":authority", "localhost")]) + let headers = HPACKHeaders([ + (":path", "/"), (":method", "GET"), (":scheme", "https"), (":authority", "localhost"), + ]) let clientStreamID = HTTP2StreamID(1) let reqFrame = HTTP2Frame(streamID: clientStreamID, payload: .headers(.init(headers: headers, endStream: true))) - let serverStreamID = try self.assertFramesRoundTrip(frames: [reqFrame], sender: self.clientChannel, receiver: self.serverChannel).first!.streamID + let serverStreamID = try self.assertFramesRoundTrip( + frames: [reqFrame], + sender: self.clientChannel, + receiver: self.serverChannel + ).first!.streamID // We're going to send 3 150 responses back. let earlyHeaders = HPACKHeaders([(":status", "150"), ("x-some-data", "is here")]) let earlyFrame = HTTP2Frame(streamID: serverStreamID, payload: .headers(.init(headers: earlyHeaders))) - try self.assertFramesRoundTrip(frames: [earlyFrame, earlyFrame, earlyFrame], sender: self.serverChannel, receiver: self.clientChannel) + try self.assertFramesRoundTrip( + frames: [earlyFrame, earlyFrame, earlyFrame], + sender: self.serverChannel, + receiver: self.clientChannel + ) // Now we send the final response back. let responseHeaders = HPACKHeaders([(":status", "200"), ("content-length", "0")]) - let respFrame = HTTP2Frame(streamID: serverStreamID, payload: .headers(.init(headers: responseHeaders, endStream: true))) + let respFrame = HTTP2Frame( + streamID: serverStreamID, + payload: .headers(.init(headers: responseHeaders, endStream: true)) + ) try self.assertFramesRoundTrip(frames: [respFrame], sender: self.serverChannel, receiver: self.clientChannel) XCTAssertNoThrow(try self.clientChannel.finish()) @@ -770,7 +961,9 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { try self.basicHTTP2Connection() let frame = HTTP2Frame(streamID: 1, payload: .priority(.init(exclusive: false, dependency: 0, weight: 30))) - XCTAssertNoThrow(try self.assertFramesRoundTrip(frames: [frame], sender: self.clientChannel, receiver: self.serverChannel)) + XCTAssertNoThrow( + try self.assertFramesRoundTrip(frames: [frame], sender: self.clientChannel, receiver: self.serverChannel) + ) XCTAssertNoThrow(try self.clientChannel.finish()) XCTAssertNoThrow(try self.serverChannel.finish()) @@ -788,32 +981,64 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { // We're now going to try to send a request from the client to the server and send a server response back. This // stream will terminate cleanly. - let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")]) + let headers = HPACKHeaders([ + (":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost"), + ]) var requestBody = self.clientChannel.allocator.buffer(capacity: 128) requestBody.writeStaticString("A simple HTTP/2 request.") let clientStreamID = HTTP2StreamID(1) let reqFrame = HTTP2Frame(streamID: clientStreamID, payload: .headers(.init(headers: headers))) - let reqBodyFrame = HTTP2Frame(streamID: clientStreamID, payload: .data(.init(data: .byteBuffer(requestBody), endStream: true))) + let reqBodyFrame = HTTP2Frame( + streamID: clientStreamID, + payload: .data(.init(data: .byteBuffer(requestBody), endStream: true)) + ) - let serverStreamID = try self.assertFramesRoundTrip(frames: [reqFrame, reqBodyFrame], sender: self.clientChannel, receiver: self.serverChannel).first!.streamID + let serverStreamID = try self.assertFramesRoundTrip( + frames: [reqFrame, reqBodyFrame], + sender: self.clientChannel, + receiver: self.serverChannel + ).first!.streamID // At this stage the stream is still open, both handlers should have seen stream creation events. XCTAssertEqual(clientHandler.events.count, 3) XCTAssertEqual(serverHandler.events.count, 3) - XCTAssertEqual(clientHandler.events[0] as? NIOHTTP2StreamCreatedEvent, NIOHTTP2StreamCreatedEvent(streamID: clientStreamID, localInitialWindowSize: 65535, remoteInitialWindowSize: 65535)) - XCTAssertEqual(serverHandler.events[0] as? NIOHTTP2StreamCreatedEvent, NIOHTTP2StreamCreatedEvent(streamID: serverStreamID, localInitialWindowSize: 65535, remoteInitialWindowSize: 65535)) + XCTAssertEqual( + clientHandler.events[0] as? NIOHTTP2StreamCreatedEvent, + NIOHTTP2StreamCreatedEvent( + streamID: clientStreamID, + localInitialWindowSize: 65535, + remoteInitialWindowSize: 65535 + ) + ) + XCTAssertEqual( + serverHandler.events[0] as? NIOHTTP2StreamCreatedEvent, + NIOHTTP2StreamCreatedEvent( + streamID: serverStreamID, + localInitialWindowSize: 65535, + remoteInitialWindowSize: 65535 + ) + ) // Let's send a quick response back. let responseHeaders = HPACKHeaders([(":status", "200"), ("content-length", "0")]) - let respFrame = HTTP2Frame(streamID: serverStreamID, payload: .headers(.init(headers: responseHeaders, endStream: true))) + let respFrame = HTTP2Frame( + streamID: serverStreamID, + payload: .headers(.init(headers: responseHeaders, endStream: true)) + ) try self.assertFramesRoundTrip(frames: [respFrame], sender: self.serverChannel, receiver: self.clientChannel) // Now the streams are closed, they should have seen user events. XCTAssertEqual(clientHandler.events.count, 5) XCTAssertEqual(serverHandler.events.count, 5) - XCTAssertEqual(clientHandler.events[3] as? StreamClosedEvent, StreamClosedEvent(streamID: clientStreamID, reason: nil)) - XCTAssertEqual(serverHandler.events[3] as? StreamClosedEvent, StreamClosedEvent(streamID: serverStreamID, reason: nil)) + XCTAssertEqual( + clientHandler.events[3] as? StreamClosedEvent, + StreamClosedEvent(streamID: clientStreamID, reason: nil) + ) + XCTAssertEqual( + serverHandler.events[3] as? StreamClosedEvent, + StreamClosedEvent(streamID: serverStreamID, reason: nil) + ) XCTAssertNoThrow(try self.clientChannel.finish()) XCTAssertNoThrow(try self.serverChannel.finish()) @@ -830,27 +1055,57 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { try self.serverChannel.pipeline.addHandler(serverHandler).wait() // Initiate a stream from the client. No need to send body data, we don't need it. - let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")]) + let headers = HPACKHeaders([ + (":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost"), + ]) let clientStreamID = HTTP2StreamID(1) let reqFrame = HTTP2Frame(streamID: clientStreamID, payload: .headers(.init(headers: headers))) - let serverStreamID = try self.assertFramesRoundTrip(frames: [reqFrame], sender: self.clientChannel, receiver: self.serverChannel).first!.streamID + let serverStreamID = try self.assertFramesRoundTrip( + frames: [reqFrame], + sender: self.clientChannel, + receiver: self.serverChannel + ).first!.streamID // At this stage the stream is still open, both handlers should have seen stream creation events. XCTAssertEqual(clientHandler.events.count, 1) XCTAssertEqual(serverHandler.events.count, 1) - XCTAssertEqual(clientHandler.events[0] as? NIOHTTP2StreamCreatedEvent, NIOHTTP2StreamCreatedEvent(streamID: clientStreamID, localInitialWindowSize: 65535, remoteInitialWindowSize: 65535)) - XCTAssertEqual(serverHandler.events[0] as? NIOHTTP2StreamCreatedEvent, NIOHTTP2StreamCreatedEvent(streamID: serverStreamID, localInitialWindowSize: 65535, remoteInitialWindowSize: 65535)) + XCTAssertEqual( + clientHandler.events[0] as? NIOHTTP2StreamCreatedEvent, + NIOHTTP2StreamCreatedEvent( + streamID: clientStreamID, + localInitialWindowSize: 65535, + remoteInitialWindowSize: 65535 + ) + ) + XCTAssertEqual( + serverHandler.events[0] as? NIOHTTP2StreamCreatedEvent, + NIOHTTP2StreamCreatedEvent( + streamID: serverStreamID, + localInitialWindowSize: 65535, + remoteInitialWindowSize: 65535 + ) + ) // The server will reset the stream. let rstStreamFrame = HTTP2Frame(streamID: serverStreamID, payload: .rstStream(.cancel)) - try self.assertFramesRoundTrip(frames: [rstStreamFrame], sender: self.serverChannel, receiver: self.clientChannel) + try self.assertFramesRoundTrip( + frames: [rstStreamFrame], + sender: self.serverChannel, + receiver: self.clientChannel + ) // Now the streams are closed, they should have seen user events. XCTAssertEqual(clientHandler.events.count, 3) XCTAssertEqual(serverHandler.events.count, 3) - XCTAssertEqual(clientHandler.events[1] as? StreamClosedEvent, StreamClosedEvent(streamID: clientStreamID, reason: .cancel)) - XCTAssertEqual(serverHandler.events[1] as? StreamClosedEvent, StreamClosedEvent(streamID: serverStreamID, reason: .cancel)) + XCTAssertEqual( + clientHandler.events[1] as? StreamClosedEvent, + StreamClosedEvent(streamID: clientStreamID, reason: .cancel) + ) + XCTAssertEqual( + serverHandler.events[1] as? StreamClosedEvent, + StreamClosedEvent(streamID: serverStreamID, reason: .cancel) + ) XCTAssertNoThrow(try self.clientChannel.finish()) XCTAssertNoThrow(try self.serverChannel.finish()) @@ -867,20 +1122,43 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { try self.serverChannel.pipeline.addHandler(serverHandler).wait() // Initiate a stream from the client. No need to send body data, we don't need it. - let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")]) + let headers = HPACKHeaders([ + (":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost"), + ]) let clientStreamID = HTTP2StreamID(1) let reqFrame = HTTP2Frame(streamID: clientStreamID, payload: .headers(.init(headers: headers))) - let serverStreamID = try self.assertFramesRoundTrip(frames: [reqFrame], sender: self.clientChannel, receiver: self.serverChannel).first!.streamID + let serverStreamID = try self.assertFramesRoundTrip( + frames: [reqFrame], + sender: self.clientChannel, + receiver: self.serverChannel + ).first!.streamID // At this stage the stream is still open, both handlers should have seen stream creation events. XCTAssertEqual(clientHandler.events.count, 1) XCTAssertEqual(serverHandler.events.count, 1) - XCTAssertEqual(clientHandler.events[0] as? NIOHTTP2StreamCreatedEvent, NIOHTTP2StreamCreatedEvent(streamID: clientStreamID, localInitialWindowSize: 65535, remoteInitialWindowSize: 65535)) - XCTAssertEqual(serverHandler.events[0] as? NIOHTTP2StreamCreatedEvent, NIOHTTP2StreamCreatedEvent(streamID: serverStreamID, localInitialWindowSize: 65535, remoteInitialWindowSize: 65535)) + XCTAssertEqual( + clientHandler.events[0] as? NIOHTTP2StreamCreatedEvent, + NIOHTTP2StreamCreatedEvent( + streamID: clientStreamID, + localInitialWindowSize: 65535, + remoteInitialWindowSize: 65535 + ) + ) + XCTAssertEqual( + serverHandler.events[0] as? NIOHTTP2StreamCreatedEvent, + NIOHTTP2StreamCreatedEvent( + streamID: serverStreamID, + localInitialWindowSize: 65535, + remoteInitialWindowSize: 65535 + ) + ) // The server will send a GOAWAY. - let goawayFrame = HTTP2Frame(streamID: .rootStream, payload: .goAway(lastStreamID: .rootStream, errorCode: .http11Required, opaqueData: nil)) + let goawayFrame = HTTP2Frame( + streamID: .rootStream, + payload: .goAway(lastStreamID: .rootStream, errorCode: .http11Required, opaqueData: nil) + ) try self.assertFramesRoundTrip(frames: [goawayFrame], sender: self.serverChannel, receiver: self.clientChannel) // Now the streams are closed, they should have seen user events. @@ -899,10 +1177,16 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { // Initiate a stream from the client. No need to send body data, we don't need it. let clientStreamID = HTTP2StreamID(1) - let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")]) + let headers = HPACKHeaders([ + (":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost"), + ]) let reqFrame = HTTP2Frame(streamID: clientStreamID, payload: .headers(.init(headers: headers))) - let serverStreamID = try self.assertFramesRoundTrip(frames: [reqFrame], sender: self.clientChannel, receiver: self.serverChannel).first!.streamID + let serverStreamID = try self.assertFramesRoundTrip( + frames: [reqFrame], + sender: self.clientChannel, + receiver: self.serverChannel + ).first!.streamID // Add handler to record stream closed event. let handler = ClosedEventVsFrameOrderingHandler(targetStreamID: serverStreamID) @@ -910,7 +1194,11 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { // The client will reset the stream. let rstStreamFrame = HTTP2Frame(streamID: serverStreamID, payload: .rstStream(.cancel)) - try self.assertFramesRoundTrip(frames: [rstStreamFrame], sender: self.clientChannel, receiver: self.serverChannel) + try self.assertFramesRoundTrip( + frames: [rstStreamFrame], + sender: self.clientChannel, + receiver: self.serverChannel + ) // Check we saw the frame and the event. XCTAssertTrue(handler.seenEvent) @@ -926,7 +1214,9 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { // Initiate a stream from the client. No need to send body data, we don't need it. let clientStreamID = HTTP2StreamID(1) - let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")]) + let headers = HPACKHeaders([ + (":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost"), + ]) let reqFrame = HTTP2Frame(streamID: clientStreamID, payload: .headers(.init(headers: headers))) try self.assertFramesRoundTrip(frames: [reqFrame], sender: self.clientChannel, receiver: self.serverChannel) @@ -936,7 +1226,10 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { try self.clientChannel.pipeline.addHandler(handler).wait() // The server will send GOAWAY. - let goawayFrame = HTTP2Frame(streamID: .rootStream, payload: .goAway(lastStreamID: .rootStream, errorCode: .http11Required, opaqueData: nil)) + let goawayFrame = HTTP2Frame( + streamID: .rootStream, + payload: .goAway(lastStreamID: .rootStream, errorCode: .http11Required, opaqueData: nil) + ) try self.assertFramesRoundTrip(frames: [goawayFrame], sender: self.serverChannel, receiver: self.clientChannel) // Check we saw the frame and the event. @@ -952,7 +1245,9 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { try self.basicHTTP2Connection() // Obtain some request data. - let requestHeaders = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")]) + let requestHeaders = HPACKHeaders([ + (":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost"), + ]) var requestBody = self.clientChannel.allocator.buffer(capacity: 128) requestBody.writeStaticString("A simple HTTP/2 request.") let responseHeaders = HPACKHeaders([(":status", "200"), ("content-length", "0")]) @@ -963,13 +1258,27 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { // We're now going to try to send a request from the client to the server. let clientStreamID = HTTP2StreamID(id) let reqFrame = HTTP2Frame(streamID: clientStreamID, payload: .headers(.init(headers: requestHeaders))) - let reqBodyFrame = HTTP2Frame(streamID: clientStreamID, payload: .data(.init(data: .byteBuffer(requestBody), endStream: true))) + let reqBodyFrame = HTTP2Frame( + streamID: clientStreamID, + payload: .data(.init(data: .byteBuffer(requestBody), endStream: true)) + ) - let serverStreamID = try self.assertFramesRoundTrip(frames: [reqFrame, reqBodyFrame], sender: self.clientChannel, receiver: self.serverChannel).first!.streamID + let serverStreamID = try self.assertFramesRoundTrip( + frames: [reqFrame, reqBodyFrame], + sender: self.clientChannel, + receiver: self.serverChannel + ).first!.streamID // Let's send a quick response back. - let respFrame = HTTP2Frame(streamID: serverStreamID, payload: .headers(.init(headers: responseHeaders, endStream: true))) - try self.assertFramesRoundTrip(frames: [respFrame], sender: self.serverChannel, receiver: self.clientChannel) + let respFrame = HTTP2Frame( + streamID: serverStreamID, + payload: .headers(.init(headers: responseHeaders, endStream: true)) + ) + try self.assertFramesRoundTrip( + frames: [respFrame], + sender: self.serverChannel, + receiver: self.clientChannel + ) } XCTAssertNoThrow(try self.clientChannel.finish()) @@ -1001,7 +1310,9 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { let errorSeenPromise: EventLoopPromise = self.clientChannel.eventLoop.makePromise() XCTAssertNoThrow(try self.serverChannel.pipeline.addHandler(NIOHTTP2Handler(mode: .server)).wait()) - XCTAssertNoThrow(try self.serverChannel.pipeline.addHandler(WaitForErrorHandler(errorSeenPromise: errorSeenPromise)).wait()) + XCTAssertNoThrow( + try self.serverChannel.pipeline.addHandler(WaitForErrorHandler(errorSeenPromise: errorSeenPromise)).wait() + ) XCTAssertNoThrow(try self.clientChannel?.connect(to: SocketAddress(unixDomainSocketPath: "ignored")).wait()) XCTAssertNoThrow(try self.serverChannel?.connect(to: SocketAddress(unixDomainSocketPath: "ignored")).wait()) @@ -1012,8 +1323,12 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { self.interactInMemory(self.clientChannel, self.serverChannel) - XCTAssertNoThrow(try XCTAssertEqual(NIOHTTP2Errors.badClientMagic(), - errorSeenPromise.futureResult.wait() as? NIOHTTP2Errors.BadClientMagic)) + XCTAssertNoThrow( + try XCTAssertEqual( + NIOHTTP2Errors.badClientMagic(), + errorSeenPromise.futureResult.wait() as? NIOHTTP2Errors.BadClientMagic + ) + ) // The client will get two frames: a SETTINGS frame, and a GOAWAY frame. We don't want to decode these, so we // just check their bytes match the expected payloads. @@ -1039,12 +1354,18 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { try self.basicHTTP2Connection() // Start by having the client shrink the server's initial window size to 0. We should get an ACK as well. - try self.assertSettingsUpdateWithAck([HTTP2Setting(parameter: .initialWindowSize, value: 0)], sender: self.clientChannel, receiver: self.serverChannel) + try self.assertSettingsUpdateWithAck( + [HTTP2Setting(parameter: .initialWindowSize, value: 0)], + sender: self.clientChannel, + receiver: self.serverChannel + ) self.clientChannel.assertNoFramesReceived() self.serverChannel.assertNoFramesReceived() // Now open a stream. - let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")]) + let headers = HPACKHeaders([ + (":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost"), + ]) let clientStreamID = HTTP2StreamID(1) let reqFrame = HTTP2Frame(streamID: clientStreamID, payload: .headers(.init(headers: headers, endStream: true))) try self.assertFramesRoundTrip(frames: [reqFrame], sender: self.clientChannel, receiver: self.serverChannel) @@ -1065,7 +1386,10 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { // Now we're going to send in a DATA frame. This will not be sent, as the window size is 0. var buffer = self.clientChannel.allocator.buffer(capacity: 5) buffer.writeStaticString("hello") - let dataFrame = HTTP2Frame(streamID: clientStreamID, payload: .data(.init(data: .byteBuffer(buffer), endStream: true))) + let dataFrame = HTTP2Frame( + streamID: clientStreamID, + payload: .data(.init(data: .byteBuffer(buffer), endStream: true)) + ) self.serverChannel.writeAndFlush(dataFrame, promise: nil) self.interactInMemory(self.clientChannel, self.serverChannel) @@ -1076,19 +1400,44 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { // Now the client will send a new SETTINGS frame. This will produce a SETTINGS ACK, and widen the flow control window a bit. // We make this one a bit tricky to confirm that we do the math properly: we set the window size to 5, then to 3. The new value // should be 3. - try self.assertSettingsUpdateWithAck([HTTP2Setting(parameter: .initialWindowSize, value: 5), HTTP2Setting(parameter: .initialWindowSize, value: 3)], sender: self.clientChannel, receiver: self.serverChannel) - try self.clientChannel.assertReceivedFrame().assertFrameMatches(this: HTTP2Frame(streamID: clientStreamID, payload: .data(.init(data: .byteBuffer(buffer.readSlice(length: 3)!))))) + try self.assertSettingsUpdateWithAck( + [ + HTTP2Setting(parameter: .initialWindowSize, value: 5), + HTTP2Setting(parameter: .initialWindowSize, value: 3), + ], + sender: self.clientChannel, + receiver: self.serverChannel + ) + try self.clientChannel.assertReceivedFrame().assertFrameMatches( + this: HTTP2Frame( + streamID: clientStreamID, + payload: .data(.init(data: .byteBuffer(buffer.readSlice(length: 3)!))) + ) + ) self.clientChannel.assertNoFramesReceived() self.serverChannel.assertNoFramesReceived() // Sending the same SETTINGS frame again does not produce more data. - try self.assertSettingsUpdateWithAck([HTTP2Setting(parameter: .initialWindowSize, value: 3)], sender: self.clientChannel, receiver: self.serverChannel) + try self.assertSettingsUpdateWithAck( + [HTTP2Setting(parameter: .initialWindowSize, value: 3)], + sender: self.clientChannel, + receiver: self.serverChannel + ) self.clientChannel.assertNoFramesReceived() self.serverChannel.assertNoFramesReceived() // Now we can widen the window again, and get the rest of the frame. - try self.assertSettingsUpdateWithAck([HTTP2Setting(parameter: .initialWindowSize, value: 6)], sender: self.clientChannel, receiver: self.serverChannel) - try self.clientChannel.assertReceivedFrame().assertFrameMatches(this: HTTP2Frame(streamID: clientStreamID, payload: .data(.init(data: .byteBuffer(buffer.readSlice(length: 2)!), endStream: true)))) + try self.assertSettingsUpdateWithAck( + [HTTP2Setting(parameter: .initialWindowSize, value: 6)], + sender: self.clientChannel, + receiver: self.serverChannel + ) + try self.clientChannel.assertReceivedFrame().assertFrameMatches( + this: HTTP2Frame( + streamID: clientStreamID, + payload: .data(.init(data: .byteBuffer(buffer.readSlice(length: 2)!), endStream: true)) + ) + ) self.clientChannel.assertNoFramesReceived() self.serverChannel.assertNoFramesReceived() @@ -1103,8 +1452,12 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { 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))) } + 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. @@ -1112,14 +1465,28 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { // 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) + 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) + 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)]) + XCTAssertEqual( + newEvents, + [NIOHTTP2BulkStreamWindowChangeEvent(delta: -15535), NIOHTTP2BulkStreamWindowChangeEvent(delta: 15535)] + ) XCTAssertNoThrow(try self.clientChannel.finish()) XCTAssertNoThrow(try self.serverChannel.finish()) @@ -1132,13 +1499,19 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { // 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, inboundStreamInitializer: nil)).wait()) + XCTAssertNoThrow( + try self.serverChannel.pipeline.addHandler( + HTTP2StreamMultiplexer(mode: .server, channel: self.serverChannel, inboundStreamInitializer: nil) + ).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 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)))) @@ -1154,18 +1527,30 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { // 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.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) + 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) + try self.assertSettingsUpdateWithAck( + [(HTTP2Setting(parameter: .initialWindowSize, value: 65535))], + sender: self.serverChannel, + receiver: self.clientChannel + ) self.clientChannel.assertNoFramesReceived() self.serverChannel.assertNoFramesReceived() @@ -1178,13 +1563,22 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { try self.basicHTTP2Connection() // We're now going to try to send a request from the client to the server. - let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")]) + let headers = HPACKHeaders([ + (":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost"), + ]) let clientStreamID = HTTP2StreamID(1) let reqFrame = HTTP2Frame(streamID: clientStreamID, payload: .headers(.init(headers: headers))) try self.assertFramesRoundTrip(frames: [reqFrame], sender: self.clientChannel, receiver: self.serverChannel) // Now the server is going to change SETTINGS_MAX_FRAME_SIZE. We set this twice to confirm we do this properly. - try self.assertSettingsUpdateWithAck([HTTP2Setting(parameter: .maxFrameSize, value: 1<<15), HTTP2Setting(parameter: .maxFrameSize, value: 1<<16)], sender: self.serverChannel, receiver: self.clientChannel) + try self.assertSettingsUpdateWithAck( + [ + HTTP2Setting(parameter: .maxFrameSize, value: 1 << 15), + HTTP2Setting(parameter: .maxFrameSize, value: 1 << 16), + ], + sender: self.serverChannel, + receiver: self.clientChannel + ) // Now the client will send a very large DATA frame. It must be passed through as a single entity, and accepted by the remote peer. var buffer = self.clientChannel.allocator.buffer(capacity: 65535) @@ -1215,13 +1609,18 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { XCTAssertEqual(error as? NIOHTTP2Errors.PriorityCycle, NIOHTTP2Errors.priorityCycle(streamID: 1)) } - guard let responseFrame = try assertNoThrowWithValue(self.serverChannel.readOutbound(as: ByteBuffer.self)) else { + guard let responseFrame = try assertNoThrowWithValue(self.serverChannel.readOutbound(as: ByteBuffer.self)) + else { XCTFail("Did not receive response frame") return } XCTAssertNoThrow(try self.clientChannel.writeInbound(responseFrame)) - try self.clientChannel.assertReceivedFrame().assertGoAwayFrame(lastStreamID: .maxID, errorCode: UInt32(http2ErrorCode: .protocolError), opaqueData: nil) + try self.clientChannel.assertReceivedFrame().assertGoAwayFrame( + lastStreamID: .maxID, + errorCode: UInt32(http2ErrorCode: .protocolError), + opaqueData: nil + ) XCTAssertNoThrow(XCTAssertTrue(try self.clientChannel.finish().isClean)) _ = try? self.serverChannel.finish() @@ -1234,8 +1633,13 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { // Send a HEADERS frame that has a self-dependency. Note that we aren't policing these outbound: // as we can't detect cycles generally without maintaining a bunch of state, we simply don't. That // allows us to emit this. - let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")]) - let frame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: headers, priorityData: .init(exclusive: true, dependency: 1, weight: 64)))) + let headers = HPACKHeaders([ + (":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost"), + ]) + let frame = HTTP2Frame( + streamID: 1, + payload: .headers(.init(headers: headers, priorityData: .init(exclusive: true, dependency: 1, weight: 64))) + ) self.clientChannel.writeAndFlush(frame, promise: nil) // We treat this as a connection error. @@ -1247,25 +1651,36 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { XCTAssertEqual(error as? NIOHTTP2Errors.PriorityCycle, NIOHTTP2Errors.priorityCycle(streamID: 1)) } - guard let responseFrame = try assertNoThrowWithValue(self.serverChannel.readOutbound(as: ByteBuffer.self)) else { + guard let responseFrame = try assertNoThrowWithValue(self.serverChannel.readOutbound(as: ByteBuffer.self)) + else { XCTFail("Did not receive response frame") return } XCTAssertNoThrow(try self.clientChannel.writeInbound(responseFrame)) - try self.clientChannel.assertReceivedFrame().assertGoAwayFrame(lastStreamID: .maxID, errorCode: UInt32(http2ErrorCode: .protocolError), opaqueData: nil) + try self.clientChannel.assertReceivedFrame().assertGoAwayFrame( + lastStreamID: .maxID, + errorCode: UInt32(http2ErrorCode: .protocolError), + opaqueData: nil + ) XCTAssertNoThrow(XCTAssertTrue(try self.clientChannel.finish().isClean)) _ = try? self.serverChannel.finish() } func testInvalidRequestHeaderBlockAllowsRstStream() throws { - XCTAssertNoThrow(try self.clientChannel.pipeline.addHandler(NIOHTTP2Handler(mode: .client, headerBlockValidation: .disabled)).wait()) + XCTAssertNoThrow( + try self.clientChannel.pipeline.addHandler(NIOHTTP2Handler(mode: .client, headerBlockValidation: .disabled)) + .wait() + ) XCTAssertNoThrow(try self.serverChannel.pipeline.addHandler(NIOHTTP2Handler(mode: .server)).wait()) try self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel) // We're going to send some invalid HTTP/2 request headers. The client has validation disabled, and will allow it, but the server will not. - let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost"), ("UPPERCASE", "not allowed")]) + let headers = HPACKHeaders([ + (":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost"), + ("UPPERCASE", "not allowed"), + ]) let frame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: headers))) self.clientChannel.writeAndFlush(frame, promise: nil) @@ -1275,10 +1690,14 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { return } XCTAssertThrowsError(try self.serverChannel.writeInbound(frameData)) { error in - XCTAssertEqual(error as? NIOHTTP2Errors.InvalidHTTP2HeaderFieldName, NIOHTTP2Errors.invalidHTTP2HeaderFieldName("UPPERCASE")) + XCTAssertEqual( + error as? NIOHTTP2Errors.InvalidHTTP2HeaderFieldName, + NIOHTTP2Errors.invalidHTTP2HeaderFieldName("UPPERCASE") + ) } - guard let responseFrame = try assertNoThrowWithValue(self.serverChannel.readOutbound(as: ByteBuffer.self)) else { + guard let responseFrame = try assertNoThrowWithValue(self.serverChannel.readOutbound(as: ByteBuffer.self)) + else { XCTFail("Did not receive response frame") return } @@ -1296,18 +1715,21 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { // Now we're going to try to trigger a connection error in the client. We'll do it by sending a weird SETTINGS frame that isn't valid. let weirdSettingsFrame: [UInt8] = [ - 0x00, 0x00, 0x06, // 3-byte payload length (6 bytes) - 0x04, // 1-byte frame type (SETTINGS) - 0x00, // 1-byte flags (none) - 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier - 0x00, 0x02, // SETTINGS_ENABLE_PUSH - 0x00, 0x00, 0x00, 0x03, // = 3, an invalid value + 0x00, 0x00, 0x06, // 3-byte payload length (6 bytes) + 0x04, // 1-byte frame type (SETTINGS) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier + 0x00, 0x02, // SETTINGS_ENABLE_PUSH + 0x00, 0x00, 0x00, 0x03, // = 3, an invalid value ] var settingsBuffer = self.clientChannel.allocator.buffer(capacity: 128) settingsBuffer.writeBytes(weirdSettingsFrame) XCTAssertThrowsError(try self.clientChannel.writeInbound(settingsBuffer)) { error in - XCTAssertEqual(error as? NIOHTTP2Errors.InvalidSetting, NIOHTTP2Errors.invalidSetting(setting: HTTP2Setting(parameter: .enablePush, value: 3))) + XCTAssertEqual( + error as? NIOHTTP2Errors.InvalidSetting, + NIOHTTP2Errors.invalidSetting(setting: HTTP2Setting(parameter: .enablePush, value: 3)) + ) } guard let goAwayFrame = try assertNoThrowWithValue(self.clientChannel.readOutbound(as: ByteBuffer.self)) else { @@ -1315,7 +1737,11 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { return } XCTAssertNoThrow(try self.serverChannel.writeInbound(goAwayFrame)) - try self.serverChannel.assertReceivedFrame().assertGoAwayFrame(lastStreamID: .maxID, errorCode: 0x01, opaqueData: nil) + try self.serverChannel.assertReceivedFrame().assertGoAwayFrame( + lastStreamID: .maxID, + errorCode: 0x01, + opaqueData: nil + ) XCTAssertNoThrow(XCTAssertTrue(try self.serverChannel.finish().isClean)) _ = try? self.clientChannel.finish() @@ -1326,13 +1752,22 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { try self.basicHTTP2Connection() // We're now going to try to send a request from the client to the server. - let headers = HPACKHeaders([(":path", "/"), (":method", "GET"), (":scheme", "https"), (":authority", "localhost")]) + let headers = HPACKHeaders([ + (":path", "/"), (":method", "GET"), (":scheme", "https"), (":authority", "localhost"), + ]) let clientStreamID = HTTP2StreamID(1) let reqFrame = HTTP2Frame(streamID: clientStreamID, payload: .headers(.init(headers: headers, endStream: true))) try self.assertFramesRoundTrip(frames: [reqFrame], sender: self.clientChannel, receiver: self.serverChannel) // Now the server is going to change SETTINGS_MAX_CONCURRENT_STREAMS. We set this twice to confirm we do this properly. - try self.assertSettingsUpdateWithAck([HTTP2Setting(parameter: .maxConcurrentStreams, value: 50), HTTP2Setting(parameter: .maxConcurrentStreams, value: 1)], sender: self.serverChannel, receiver: self.clientChannel) + try self.assertSettingsUpdateWithAck( + [ + HTTP2Setting(parameter: .maxConcurrentStreams, value: 50), + HTTP2Setting(parameter: .maxConcurrentStreams, value: 1), + ], + sender: self.serverChannel, + receiver: self.clientChannel + ) // Now the client will attempt to open another stream. This should buffer. let reqFrame2 = HTTP2Frame(streamID: 3, payload: .headers(.init(headers: headers, endStream: true))) @@ -1341,7 +1776,10 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { // The server will now complete the first stream, which should lead to the second stream being emitted. let responseHeaders = HPACKHeaders([(":status", "200")]) - let respFrame = HTTP2Frame(streamID: clientStreamID, payload: .headers(.init(headers: responseHeaders, endStream: true))) + let respFrame = HTTP2Frame( + streamID: clientStreamID, + payload: .headers(.init(headers: responseHeaders, endStream: true)) + ) self.serverChannel.writeAndFlush(respFrame, promise: nil) self.interactInMemory(self.serverChannel, self.clientChannel) @@ -1369,16 +1807,24 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { // We're going to queue some frames in the client, but not flush them. The HEADERS frame will pass // right through, but the DATA ones won't. - let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")]) + let headers = HPACKHeaders([ + (":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost"), + ]) let clientStreamID = HTTP2StreamID(1) - let reqFrame = HTTP2Frame(streamID: clientStreamID, payload: .headers(.init(headers: headers, endStream: false))) + let reqFrame = HTTP2Frame( + streamID: clientStreamID, + payload: .headers(.init(headers: headers, endStream: false)) + ) let writeCount = 5 self.clientChannel.write(reqFrame, promise: nil) - let bodyFrame = HTTP2Frame(streamID: clientStreamID, payload: .data(.init(data: .byteBuffer(ByteBufferAllocator().buffer(capacity: 0))))) + let bodyFrame = HTTP2Frame( + streamID: clientStreamID, + payload: .data(.init(data: .byteBuffer(ByteBufferAllocator().buffer(capacity: 0)))) + ) - let futures = (0 ..< writeCount).map { _ in + let futures = (0..() + var receivedFrames = [HTTP2Frame]() while let frame = try assertNoThrowWithValue(self.serverChannel.readInbound(as: HTTP2Frame.self)) { receivedFrames.append(frame) } @@ -1668,21 +2211,25 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { // Ok, first let's send something safe. This size is calculated as 32 bytes per entry, plus the octet length // of the name and value. The below block is 225 bytes, as shown below. let goodHeaders = HPACKHeaders([ - (":path", "/"), // 32 byte overhead + 5 byte name + one byte value == 38 bytes, total is 38 - (":method", "GET"), // 32 byte overhead + 7 byte name + 3 byte value == 42 bytes, total is 80 + (":path", "/"), // 32 byte overhead + 5 byte name + one byte value == 38 bytes, total is 38 + (":method", "GET"), // 32 byte overhead + 7 byte name + 3 byte value == 42 bytes, total is 80 (":authority", "localhost"), // 32 byte overhead + 10 byte name + 9 byte value == 51 bytes, total is 131 - (":scheme", "https"), // 32 byte overhead + 7 byte name + 5 byte value == 44 bytes, total is 175 - ("user-agent", "swiftnio"), // 32 byte overhead + 10 byte name + 8 byte value == 50 bytes, total is 225 + (":scheme", "https"), // 32 byte overhead + 7 byte name + 5 byte value == 44 bytes, total is 175 + ("user-agent", "swiftnio"), // 32 byte overhead + 10 byte name + 8 byte value == 50 bytes, total is 225 ]) let firstRequestFrame = HTTP2Frame(streamID: 1, payload: .headers(.init(headers: goodHeaders))) - try self.assertFramesRoundTrip(frames: [firstRequestFrame], sender: self.clientChannel, receiver: self.serverChannel) + try self.assertFramesRoundTrip( + frames: [firstRequestFrame], + sender: self.clientChannel, + receiver: self.serverChannel + ) // Ok, we'll create some new headers that are bad by adding one byte to the last header field. let badHeaders = HPACKHeaders([ - (":path", "/"), // 32 byte overhead + 5 byte name + one byte value == 38 bytes, total is 38 - (":method", "GET"), // 32 byte overhead + 7 byte name + 3 byte value == 42 bytes, total is 80 + (":path", "/"), // 32 byte overhead + 5 byte name + one byte value == 38 bytes, total is 38 + (":method", "GET"), // 32 byte overhead + 7 byte name + 3 byte value == 42 bytes, total is 80 (":authority", "localhost"), // 32 byte overhead + 10 byte name + 9 byte value == 51 bytes, total is 131 - (":scheme", "https"), // 32 byte overhead + 7 byte name + 5 byte value == 44 bytes, total is 175 + (":scheme", "https"), // 32 byte overhead + 7 byte name + 5 byte value == 44 bytes, total is 175 ("user-agent", "swiftnio2"), // 32 byte overhead + 10 byte name + 9 byte value == 51 bytes, total is 226 ]) @@ -1698,13 +2245,18 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { XCTAssertEqual(error as? NIOHTTP2Errors.UnableToParseFrame, NIOHTTP2Errors.unableToParseFrame()) } - guard let responseFrame = try assertNoThrowWithValue(self.serverChannel.readOutbound(as: ByteBuffer.self)) else { + guard let responseFrame = try assertNoThrowWithValue(self.serverChannel.readOutbound(as: ByteBuffer.self)) + else { XCTFail("Did not receive response frame") return } XCTAssertNoThrow(try self.clientChannel.writeInbound(responseFrame)) - try self.clientChannel.assertReceivedFrame().assertGoAwayFrame(lastStreamID: .maxID, errorCode: UInt32(HTTP2ErrorCode.compressionError.networkCode), opaqueData: nil) + try self.clientChannel.assertReceivedFrame().assertGoAwayFrame( + lastStreamID: .maxID, + errorCode: UInt32(HTTP2ErrorCode.compressionError.networkCode), + opaqueData: nil + ) } func testForbidsExceedingMaxHeaderListSizeBeforeDecoding() throws { @@ -1721,18 +2273,18 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { // even before the header block is complete. To do that, we're going to send a HEADERS frame and then a sequence of // CONTINUATION frames. These will never decompress to a valid block, but we don't expect them to get that far. let weirdHeadersFrame: [UInt8] = [ - 0x00, 0x00, 0x01, // 3-byte payload length (1 bytes) - 0x01, // 1-byte frame type (HEADERS) - 0x00, // 1-byte flags (none) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier - 0x82, // payload + 0x00, 0x00, 0x01, // 3-byte payload length (1 bytes) + 0x01, // 1-byte frame type (HEADERS) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x82, // payload ] let weirdContinuationFrame: [UInt8] = [ - 0x00, 0x00, 0x01, // 3-byte payload length (1 bytes) - 0x09, // 1-byte frame type (CONTINUATION) - 0x00, // 1-byte flags (none) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier - 0x82, // payload + 0x00, 0x00, 0x01, // 3-byte payload length (1 bytes) + 0x09, // 1-byte frame type (CONTINUATION) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x82, // payload ] // Each byte of payload is accompanied by 9 bytes of overhead, so we need to allocate enough space to send 255 bytes of payload. @@ -1747,16 +2299,26 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { XCTAssertNoThrow(XCTAssertNil(try self.serverChannel.readOutbound(as: ByteBuffer.self))) // But if we send one more frame, that will be treated as a violation of SETTINGS_MAX_HEADER_LIST_SIZE. - XCTAssertThrowsError(try self.serverChannel.writeInbound(firstBuffer.getSlice(at: firstBuffer.writerIndex - 10, length: 10)!)) { error in - XCTAssertEqual(error as? NIOHTTP2Errors.ExcessivelyLargeHeaderBlock, NIOHTTP2Errors.excessivelyLargeHeaderBlock()) + XCTAssertThrowsError( + try self.serverChannel.writeInbound(firstBuffer.getSlice(at: firstBuffer.writerIndex - 10, length: 10)!) + ) { error in + XCTAssertEqual( + error as? NIOHTTP2Errors.ExcessivelyLargeHeaderBlock, + NIOHTTP2Errors.excessivelyLargeHeaderBlock() + ) } - guard let responseFrame = try assertNoThrowWithValue(self.serverChannel.readOutbound(as: ByteBuffer.self)) else { + guard let responseFrame = try assertNoThrowWithValue(self.serverChannel.readOutbound(as: ByteBuffer.self)) + else { XCTFail("Did not receive response frame") return } XCTAssertNoThrow(try self.clientChannel.writeInbound(responseFrame)) - try self.clientChannel.assertReceivedFrame().assertGoAwayFrame(lastStreamID: .maxID, errorCode: UInt32(HTTP2ErrorCode.protocolError.networkCode), opaqueData: nil) + try self.clientChannel.assertReceivedFrame().assertGoAwayFrame( + lastStreamID: .maxID, + errorCode: UInt32(HTTP2ErrorCode.protocolError.networkCode), + opaqueData: nil + ) } func testForbidsExceedingMaxHeaderListSizeBeforeDecodingSingleFrame() throws { @@ -1771,10 +2333,10 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { // even before the header block is complete. To do that, we're going to send a HEADERS frame that is itself too long to expect // to decode. let weirdHeadersFrame: [UInt8] = [ - 0x00, 0x00, 0xE2, // 3-byte payload length (226 bytes) - 0x01, // 1-byte frame type (HEADERS) - 0x00, // 1-byte flags (none) - 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier + 0x00, 0x00, 0xE2, // 3-byte payload length (226 bytes) + 0x01, // 1-byte frame type (HEADERS) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x01, // 4-byte stream identifier ] // We don't even need the body, we shouldn't get that far. @@ -1783,15 +2345,23 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { // This frame will be treated as a violation of SETTINGS_MAX_HEADER_LIST_SIZE. XCTAssertThrowsError(try self.serverChannel.writeInbound(buffer)) { error in - XCTAssertEqual(error as? NIOHTTP2Errors.ExcessivelyLargeHeaderBlock, NIOHTTP2Errors.excessivelyLargeHeaderBlock()) + XCTAssertEqual( + error as? NIOHTTP2Errors.ExcessivelyLargeHeaderBlock, + NIOHTTP2Errors.excessivelyLargeHeaderBlock() + ) } - guard let responseFrame = try assertNoThrowWithValue(self.serverChannel.readOutbound(as: ByteBuffer.self)) else { + guard let responseFrame = try assertNoThrowWithValue(self.serverChannel.readOutbound(as: ByteBuffer.self)) + else { XCTFail("Did not receive response frame") return } XCTAssertNoThrow(try self.clientChannel.writeInbound(responseFrame)) - try self.clientChannel.assertReceivedFrame().assertGoAwayFrame(lastStreamID: .maxID, errorCode: UInt32(HTTP2ErrorCode.protocolError.networkCode), opaqueData: nil) + try self.clientChannel.assertReceivedFrame().assertGoAwayFrame( + lastStreamID: .maxID, + errorCode: UInt32(HTTP2ErrorCode.protocolError.networkCode), + opaqueData: nil + ) } func testForbidsExceedingMaximumSequentialContinuationFrames() throws { @@ -1803,16 +2373,16 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { ) let headersFrame: [UInt8] = [ - 0x00, 0x00, 0x00, // 3-byte payload length (0 bytes) - 0x01, // 1-byte frame type (HEADERS) - 0x00, // 1-byte flags (none) - 0x00, 0x00, 0x00, 0x03, // 4-byte stream identifier + 0x00, 0x00, 0x00, // 3-byte payload length (0 bytes) + 0x01, // 1-byte frame type (HEADERS) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x03, // 4-byte stream identifier ] let continuationFrame: [UInt8] = [ - 0x00, 0x00, 0x00, // 3-byte payload length (0 bytes) - 0x09, // 1-byte frame type (CONTINUATION) - 0x00, // 1-byte flags (none) - 0x00, 0x00, 0x00, 0x03 // 4-byte stream identifier + 0x00, 0x00, 0x00, // 3-byte payload length (0 bytes) + 0x09, // 1-byte frame type (CONTINUATION) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x03, // 4-byte stream identifier ] var firstBuffer = self.serverChannel.allocator.buffer(capacity: 128) @@ -1836,9 +2406,11 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { NIOHTTP2Errors.excessiveContinuationFrames() ) } - guard let responseFrame = try assertNoThrowWithValue( - self.serverChannel.readOutbound(as: ByteBuffer.self) - ) else { + guard + let responseFrame = try assertNoThrowWithValue( + self.serverChannel.readOutbound(as: ByteBuffer.self) + ) + else { XCTFail("Did not receive response frame") return } @@ -1870,14 +2442,18 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { channel.write(respFramePayload, promise: nil) // Now prepare the large body. - let respBodyFramePayload = HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(responseBody), endStream: true)) + let respBodyFramePayload = HTTP2Frame.FramePayload.data( + .init(data: .byteBuffer(responseBody), endStream: true) + ) channel.writeAndFlush(respBodyFramePayload, promise: nil) return channel.pipeline.addHandler(childHandler) } // Now we're going to send a small request. - let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")]) + let headers = HPACKHeaders([ + (":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost"), + ]) // We're going to open a stream and queue up the frames for that stream. let handler = try self.clientChannel.pipeline.handler(type: HTTP2StreamMultiplexer.self).wait() @@ -1915,11 +2491,13 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { // to correctly confirm we don't receive a frame for the child stream. let childHandler = FrameRecorderHandler() try self.basicHTTP2Connection(serverSettings: serverSettings) { channel in - return channel.eventLoop.makeSucceededFuture(()) + channel.eventLoop.makeSucceededFuture(()) } // Now we're going to send a large request: 65535 bytes in size - let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")]) + let headers = HPACKHeaders([ + (":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost"), + ]) // We're going to open a stream and queue up the frames for that stream. let handler = try self.clientChannel.pipeline.handler(type: HTTP2StreamMultiplexer.self).wait() @@ -1961,24 +2539,30 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { func testStreamCreationOrder() throws { try self.basicHTTP2Connection() - let multiplexer = HTTP2StreamMultiplexer(mode: .client, channel: self.clientChannel, inboundStreamInitializer: nil) + let multiplexer = HTTP2StreamMultiplexer( + mode: .client, + channel: self.clientChannel, + inboundStreamInitializer: nil + ) XCTAssertNoThrow(try self.clientChannel.pipeline.addHandler(multiplexer).wait()) let streamAPromise = self.clientChannel.eventLoop.makePromise(of: Channel.self) multiplexer.createStreamChannel(promise: streamAPromise) { channel in - return channel.eventLoop.makeSucceededFuture(()) + channel.eventLoop.makeSucceededFuture(()) } self.clientChannel.embeddedEventLoop.run() let streamA = try assertNoThrowWithValue(try streamAPromise.futureResult.wait()) let streamBPromise = self.clientChannel.eventLoop.makePromise(of: Channel.self) multiplexer.createStreamChannel(promise: streamBPromise) { channel in - return channel.eventLoop.makeSucceededFuture(()) + channel.eventLoop.makeSucceededFuture(()) } self.clientChannel.embeddedEventLoop.run() let streamB = try assertNoThrowWithValue(try streamBPromise.futureResult.wait()) - let headers = HPACKHeaders([(":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https")]) + let headers = HPACKHeaders([ + (":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https"), + ]) let headersFramePayload = HTTP2Frame.FramePayload.headers(.init(headers: headers, endStream: false)) // Write on 'B' first. @@ -1998,7 +2582,8 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { // contains an invalid header ("transfer-encoding", "chunked"), which will trigger an error. // We'll confirm that the error notifies that this stream was created and then closed. let headers = HPACKHeaders([ - (":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost"), ("transfer-encoding", "chunked") + (":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost"), + ("transfer-encoding", "chunked"), ]) let clientStreamID = HTTP2StreamID(1) @@ -2058,17 +2643,17 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { try self.clientChannel.pipeline.syncOperations.addHandler(h2FrameRecorder, position: .after(h2ClientHandler)) let altServiceFrameBytes: [UInt8] = [ - 0x00, 0x00, 0x15, // 3-byte payload length (21 bytes) - 0x0a, // 1-byte frame type (ALTSVC) - 0x00, // 1-byte flags (none) - 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier - 0x00, 0x09, // 2-byte origin size ("apple.com"; 9 bytes) + 0x00, 0x00, 0x15, // 3-byte payload length (21 bytes) + 0x0a, // 1-byte frame type (ALTSVC) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier + 0x00, 0x09, // 2-byte origin size ("apple.com"; 9 bytes) ] var buffer = self.clientChannel.allocator.buffer(bytes: altServiceFrameBytes) buffer.writeString("apple.com") buffer.writeString("h2=\":8000\"") - XCTAssertEqual(buffer.readableBytes, 30) // 9 (header) + 21 (origin, field) + XCTAssertEqual(buffer.readableBytes, 30) // 9 (header) + 21 (origin, field) XCTAssertNoThrow(try self.clientChannel.writeInbound(buffer)) // Frame should be dropped. @@ -2083,10 +2668,10 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { try self.clientChannel.pipeline.syncOperations.addHandler(h2FrameRecorder, position: .after(h2ClientHandler)) let originFrameBytes: [UInt8] = [ - 0x00, 0x00, 0x2a, // 3-byte payload length (42 bytes) - 0x0c, // 1-byte frame type (ORIGIN) - 0x00, // 1-byte flags (none) - 0x00, 0x00, 0x00, 0x00 // 4-byte stream identifier, + 0x00, 0x00, 0x2a, // 3-byte payload length (42 bytes) + 0x0c, // 1-byte frame type (ORIGIN) + 0x00, // 1-byte flags (none) + 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier, ] var buffer = self.clientChannel.allocator.buffer(bytes: originFrameBytes) @@ -2110,18 +2695,24 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { func testWriteWithAlreadyCompletedPromise() throws { try self.basicHTTP2Connection() - let multiplexer = HTTP2StreamMultiplexer(mode: .client, channel: self.clientChannel, inboundStreamInitializer: nil) + let multiplexer = HTTP2StreamMultiplexer( + mode: .client, + channel: self.clientChannel, + inboundStreamInitializer: nil + ) XCTAssertNoThrow(try self.clientChannel.pipeline.addHandler(multiplexer).wait()) let streamPromise = self.clientChannel.eventLoop.makePromise(of: Channel.self) multiplexer.createStreamChannel(promise: streamPromise) { channel in - return channel.eventLoop.makeSucceededFuture(()) + channel.eventLoop.makeSucceededFuture(()) } self.clientChannel.embeddedEventLoop.run() let stream = try assertNoThrowWithValue(try streamPromise.futureResult.wait()) - let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")]) + let headers = HPACKHeaders([ + (":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost"), + ]) let headerPayload = HTTP2Frame.FramePayload.headers(.init(headers: headers)) let promise = self.clientChannel.eventLoop.makePromise(of: Void.self) promise.succeed(()) @@ -2132,7 +2723,9 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { // Begin by getting the connection up. try self.basicHTTP2Connection() - let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")]) + let headers = HPACKHeaders([ + (":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost"), + ]) // We're now going to try to send lots of resets from the client to the server. for i in stride(from: 1, to: 402, by: 2) { @@ -2142,7 +2735,11 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { try self.assertFramesRoundTrip(frames: [reqFrame], sender: self.clientChannel, receiver: self.serverChannel) if i < 401 { - try self.assertFramesRoundTrip(frames: [reqBodyFrame], sender: self.clientChannel, receiver: self.serverChannel) + try self.assertFramesRoundTrip( + frames: [reqBodyFrame], + sender: self.clientChannel, + receiver: self.serverChannel + ) } else { // this one should trip the DoS threshold and cause EmbeddedChannel to throw, we have to do more manually self.clientChannel.write(reqBodyFrame, promise: nil) @@ -2167,19 +2764,32 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { try self.basicHTTP2Connection(serverSettings: [HTTP2Setting(parameter: .enableConnectProtocol, value: 1)]) // We're now going to try to send a request from the client to the server with the protocol pseudoheader present - let headers = HPACKHeaders([(":path", "/"), (":method", "CONNECT"), (":scheme", "https"), (":authority", "localhost"), (":protocol", "foo")]) + let headers = HPACKHeaders([ + (":path", "/"), (":method", "CONNECT"), (":scheme", "https"), (":authority", "localhost"), + (":protocol", "foo"), + ]) var requestBody = self.clientChannel.allocator.buffer(capacity: 128) requestBody.writeStaticString("A simple HTTP/2 request.") let clientStreamID = HTTP2StreamID(1) let reqFrame = HTTP2Frame(streamID: clientStreamID, payload: .headers(.init(headers: headers))) - let reqBodyFrame = HTTP2Frame(streamID: clientStreamID, payload: .data(.init(data: .byteBuffer(requestBody), endStream: true))) + let reqBodyFrame = HTTP2Frame( + streamID: clientStreamID, + payload: .data(.init(data: .byteBuffer(requestBody), endStream: true)) + ) - let serverStreamID = try self.assertFramesRoundTrip(frames: [reqFrame, reqBodyFrame], sender: self.clientChannel, receiver: self.serverChannel).first!.streamID + let serverStreamID = try self.assertFramesRoundTrip( + frames: [reqFrame, reqBodyFrame], + sender: self.clientChannel, + receiver: self.serverChannel + ).first!.streamID // Let's send a quick response back. let responseHeaders = HPACKHeaders([(":status", "200"), ("content-length", "0")]) - let respFrame = HTTP2Frame(streamID: serverStreamID, payload: .headers(.init(headers: responseHeaders, endStream: true))) + let respFrame = HTTP2Frame( + streamID: serverStreamID, + payload: .headers(.init(headers: responseHeaders, endStream: true)) + ) try self.assertFramesRoundTrip(frames: [respFrame], sender: self.serverChannel, receiver: self.clientChannel) XCTAssertNoThrow(try self.clientChannel.finish()) @@ -2194,7 +2804,9 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { } let connectionReceivedShouldQuiesceEvent = self.clientChannel.eventLoop.makePromise(of: Void.self) - try self.serverChannel.pipeline.addHandler(ShouldQuiesceEventWaiter(promise: connectionReceivedShouldQuiesceEvent)).wait() + try self.serverChannel.pipeline.addHandler( + ShouldQuiesceEventWaiter(promise: connectionReceivedShouldQuiesceEvent) + ).wait() // Create the stream channel. let multiplexer = try self.clientChannel.pipeline.handler(type: HTTP2StreamMultiplexer.self).wait() @@ -2222,7 +2834,6 @@ class SimpleClientServerFramePayloadStreamTests: XCTestCase { } } - final class ShouldQuiesceEventWaiter: ChannelInboundHandler { typealias InboundIn = Never diff --git a/Tests/NIOHTTP2Tests/SimpleClientServerInlineStreamMultiplexerTests.swift b/Tests/NIOHTTP2Tests/SimpleClientServerInlineStreamMultiplexerTests.swift index 32dce36..5d63722 100644 --- a/Tests/NIOHTTP2Tests/SimpleClientServerInlineStreamMultiplexerTests.swift +++ b/Tests/NIOHTTP2Tests/SimpleClientServerInlineStreamMultiplexerTests.swift @@ -12,12 +12,12 @@ // //===----------------------------------------------------------------------===// -import XCTest import NIOCore import NIOEmbedded import NIOHPACK -@testable import NIOHTTP2 +import XCTest +@testable import NIOHTTP2 class SimpleClientServerInlineStreamMultiplexerTests: XCTestCase { var clientChannel: EmbeddedChannel! @@ -38,41 +38,60 @@ class SimpleClientServerInlineStreamMultiplexerTests: XCTestCase { } /// Establish a basic HTTP/2 connection. - func basicHTTP2Connection(clientSettings: HTTP2Settings = nioDefaultSettings, - serverSettings: HTTP2Settings = nioDefaultSettings, - maximumBufferedControlFrames: Int = 10000, - withMultiplexerCallback multiplexerCallback: @escaping (@Sendable (Channel) -> EventLoopFuture) = defaultMultiplexerCallback) throws { + func basicHTTP2Connection( + clientSettings: HTTP2Settings = nioDefaultSettings, + serverSettings: HTTP2Settings = nioDefaultSettings, + maximumBufferedControlFrames: Int = 10000, + withMultiplexerCallback multiplexerCallback: @escaping (@Sendable (Channel) -> EventLoopFuture) = + defaultMultiplexerCallback + ) throws { var clientConnectionConfiguration = NIOHTTP2Handler.ConnectionConfiguration() clientConnectionConfiguration.initialSettings = clientSettings clientConnectionConfiguration.maximumBufferedControlFrames = maximumBufferedControlFrames - XCTAssertNoThrow(try self.clientChannel.pipeline.addHandler(NIOHTTP2Handler(mode: .client, - eventLoop: self.clientChannel.eventLoop, - connectionConfiguration: clientConnectionConfiguration, - inboundStreamInitializer: multiplexerCallback)).wait()) + XCTAssertNoThrow( + try self.clientChannel.pipeline.addHandler( + NIOHTTP2Handler( + mode: .client, + eventLoop: self.clientChannel.eventLoop, + connectionConfiguration: clientConnectionConfiguration, + inboundStreamInitializer: multiplexerCallback + ) + ).wait() + ) var serverConnectionConfiguration = NIOHTTP2Handler.ConnectionConfiguration() serverConnectionConfiguration.initialSettings = serverSettings serverConnectionConfiguration.maximumBufferedControlFrames = maximumBufferedControlFrames - XCTAssertNoThrow(try self.serverChannel.pipeline.addHandler(NIOHTTP2Handler(mode: .server, - eventLoop: self.serverChannel.eventLoop, - connectionConfiguration: serverConnectionConfiguration, - inboundStreamInitializer: multiplexerCallback)).wait()) + XCTAssertNoThrow( + try self.serverChannel.pipeline.addHandler( + NIOHTTP2Handler( + mode: .server, + eventLoop: self.serverChannel.eventLoop, + connectionConfiguration: serverConnectionConfiguration, + inboundStreamInitializer: multiplexerCallback + ) + ).wait() + ) - try self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel, - clientSettings: clientSettings, serverSettings: serverSettings) + try self.assertDoHandshake( + client: self.clientChannel, + server: self.serverChannel, + clientSettings: clientSettings, + serverSettings: serverSettings + ) } func testSendingDataFrameWithLargeFile() throws { // Begin by getting the connection up. // We add the stream multiplexer because it'll emit WINDOW_UPDATE frames, which we need. let serverHandler = InboundFramePayloadRecorder() - try self.basicHTTP2Connection() { channel in - return channel.pipeline.addHandler(serverHandler) + try self.basicHTTP2Connection { channel in + channel.pipeline.addHandler(serverHandler) } // We're going to create a largish temp file: 3 data frames in size. - var bodyData = self.clientChannel.allocator.buffer(capacity: 1<<14) - for val in (0..<((1<<14) / MemoryLayout.size)) { + var bodyData = self.clientChannel.allocator.buffer(capacity: 1 << 14) + for val in (0..<((1 << 14) / MemoryLayout.size)) { bodyData.writeInteger(val) } @@ -85,17 +104,21 @@ class SimpleClientServerInlineStreamMultiplexerTests: XCTestCase { let clientHandler = InboundFramePayloadRecorder() let childChannelPromise = self.clientChannel.eventLoop.makePromise(of: Channel.self) - let multiplexer = try (self.clientChannel.pipeline.context(handlerType: NIOHTTP2Handler.self).wait().handler as! NIOHTTP2Handler).multiplexer.wait() + let multiplexer = try + (self.clientChannel.pipeline.context(handlerType: NIOHTTP2Handler.self).wait().handler + as! NIOHTTP2Handler).multiplexer.wait() multiplexer.createStreamChannel(promise: childChannelPromise) { channel in - return channel.pipeline.addHandler(clientHandler) + channel.pipeline.addHandler(clientHandler) } (self.clientChannel.eventLoop as! EmbeddedEventLoop).run() let childChannel = try childChannelPromise.futureResult.wait() // Start by sending the headers. - let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")]) + let headers = HPACKHeaders([ + (":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost"), + ]) let reqFrame = HTTP2Frame.FramePayload.headers(.init(headers: headers)) - childChannel.writeAndFlush(reqFrame) .whenComplete { + childChannel.writeAndFlush(reqFrame).whenComplete { print("Headers: \($0)") } self.interactInMemory(self.clientChannel, self.serverChannel) @@ -106,18 +129,22 @@ class SimpleClientServerInlineStreamMultiplexerTests: XCTestCase { // Ok, we're gonna send the body here. let reqBodyFrame = HTTP2Frame.FramePayload.data(.init(data: .fileRegion(region), endStream: true)) - childChannel.writeAndFlush(reqBodyFrame) .whenComplete { + childChannel.writeAndFlush(reqBodyFrame).whenComplete { print("Data: \($0)") } self.interactInMemory(self.clientChannel, self.serverChannel) // We now expect 3 frames. - let dataFrames = (0..<3).map { idx in HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(bodyData), endStream: idx == 2)) } + let dataFrames = (0..<3).map { idx in + HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(bodyData), endStream: idx == 2)) + } serverHandler.receivedFrames.assertFramePayloadsMatch([reqFrame] + dataFrames) // The client will have seen a pair of window updates: one on the connection, one on the stream. try self.clientChannel.assertReceivedFrame().assertWindowUpdateFrame(streamID: 0, windowIncrement: 32768) - clientHandler.receivedFrames.assertFramePayloadsMatch([HTTP2Frame.FramePayload.windowUpdate(windowSizeIncrement: 32768)]) + clientHandler.receivedFrames.assertFramePayloadsMatch([ + HTTP2Frame.FramePayload.windowUpdate(windowSizeIncrement: 32768) + ]) // No frames left. self.clientChannel.assertNoFramesReceived() @@ -131,17 +158,21 @@ class SimpleClientServerInlineStreamMultiplexerTests: XCTestCase { func testAutomaticFlowControl() throws { // Begin by getting the connection up. // We add the stream multiplexer here because it manages automatic flow control. - try self.basicHTTP2Connection() { channel in - return channel.eventLoop.makeSucceededFuture(()) + try self.basicHTTP2Connection { channel in + channel.eventLoop.makeSucceededFuture(()) } // Now we're going to send a request, including a very large body: 65536 bytes in size. To avoid spending too much // time initializing buffers, we're going to send the same 1kB data frame 64 times. - let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")]) + let headers = HPACKHeaders([ + (":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost"), + ]) let requestBody = ByteBuffer(repeating: 0x04, count: 1024) // We're going to open a stream and queue up the frames for that stream. - let handler = try self.clientChannel.pipeline.context(handlerType: NIOHTTP2Handler.self).wait().handler as! NIOHTTP2Handler + let handler = + try self.clientChannel.pipeline.context(handlerType: NIOHTTP2Handler.self).wait().handler + as! NIOHTTP2Handler let childHandler = InboundFramePayloadRecorder() let multiplexer = try handler.multiplexer.wait() multiplexer.createStreamChannel(promise: nil) { channel in @@ -196,13 +227,17 @@ class SimpleClientServerInlineStreamMultiplexerTests: XCTestCase { channel.write(respFramePayload, promise: nil) // Now prepare the large body. - let respBodyFramePayload = HTTP2Frame.FramePayload.data(.init(data: .byteBuffer(responseBody), endStream: true)) + let respBodyFramePayload = HTTP2Frame.FramePayload.data( + .init(data: .byteBuffer(responseBody), endStream: true) + ) channel.writeAndFlush(respBodyFramePayload, promise: nil) return channel.pipeline.addHandler(childHandler) } // Now we're going to send a small request. - let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")]) + let headers = HPACKHeaders([ + (":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost"), + ]) // We're going to open a stream and queue up the frames for that stream. let handler = try self.clientChannel.pipeline.handler(type: NIOHTTP2Handler.self).wait() @@ -239,11 +274,13 @@ class SimpleClientServerInlineStreamMultiplexerTests: XCTestCase { // to correctly confirm we don't receive a frame for the child stream. let childHandler = FrameRecorderHandler() try self.basicHTTP2Connection(serverSettings: serverSettings) { channel in - return channel.eventLoop.makeSucceededFuture(()) + channel.eventLoop.makeSucceededFuture(()) } // Now we're going to send a large request: 65535 bytes in size - let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")]) + let headers = HPACKHeaders([ + (":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost"), + ]) // We're going to open a stream and queue up the frames for that stream. let handler = try self.clientChannel.pipeline.handler(type: NIOHTTP2Handler.self).wait() @@ -285,19 +322,21 @@ class SimpleClientServerInlineStreamMultiplexerTests: XCTestCase { let streamAPromise = self.clientChannel.eventLoop.makePromise(of: Channel.self) multiplexer.createStreamChannel(promise: streamAPromise) { channel in - return channel.eventLoop.makeSucceededFuture(()) + channel.eventLoop.makeSucceededFuture(()) } self.clientChannel.embeddedEventLoop.run() let streamA = try assertNoThrowWithValue(try streamAPromise.futureResult.wait()) let streamBPromise = self.clientChannel.eventLoop.makePromise(of: Channel.self) multiplexer.createStreamChannel(promise: streamBPromise) { channel in - return channel.eventLoop.makeSucceededFuture(()) + channel.eventLoop.makeSucceededFuture(()) } self.clientChannel.embeddedEventLoop.run() let streamB = try assertNoThrowWithValue(try streamBPromise.futureResult.wait()) - let headers = HPACKHeaders([(":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https")]) + let headers = HPACKHeaders([ + (":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https"), + ]) let headersFramePayload = HTTP2Frame.FramePayload.headers(.init(headers: headers, endStream: false)) // Write on 'B' first. @@ -316,13 +355,15 @@ class SimpleClientServerInlineStreamMultiplexerTests: XCTestCase { let streamPromise = self.clientChannel.eventLoop.makePromise(of: Channel.self) multiplexer.createStreamChannel(promise: streamPromise) { channel in - return channel.eventLoop.makeSucceededFuture(()) + channel.eventLoop.makeSucceededFuture(()) } self.clientChannel.embeddedEventLoop.run() let stream = try assertNoThrowWithValue(try streamPromise.futureResult.wait()) - let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")]) + let headers = HPACKHeaders([ + (":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost"), + ]) let headerPayload = HTTP2Frame.FramePayload.headers(.init(headers: headers)) let promise = self.clientChannel.eventLoop.makePromise(of: Void.self) promise.succeed(()) @@ -331,25 +372,30 @@ class SimpleClientServerInlineStreamMultiplexerTests: XCTestCase { func testOpenStreamBeforeReceivingAlreadySentGoAway() throws { let serverHandler = InboundFramePayloadRecorder() - try self.basicHTTP2Connection() { channel in - return channel.pipeline.addHandler(serverHandler) + try self.basicHTTP2Connection { channel in + channel.pipeline.addHandler(serverHandler) } let clientHandler = InboundFramePayloadRecorder() let childChannelPromise = self.clientChannel.eventLoop.makePromise(of: Channel.self) let multiplexer = try self.clientChannel.pipeline.handler(type: NIOHTTP2Handler.self).wait().multiplexer.wait() multiplexer.createStreamChannel(promise: childChannelPromise) { channel in - return channel.pipeline.addHandler(clientHandler) + channel.pipeline.addHandler(clientHandler) } self.clientChannel.embeddedEventLoop.run() let childChannel = try childChannelPromise.futureResult.wait() // Server sends GOAWAY frame. - let goAwayFrame = HTTP2Frame(streamID: .rootStream, payload: .goAway(lastStreamID: .maxID, errorCode: .noError, opaqueData: nil)) + let goAwayFrame = HTTP2Frame( + streamID: .rootStream, + payload: .goAway(lastStreamID: .maxID, errorCode: .noError, opaqueData: nil) + ) serverChannel.writeAndFlush(goAwayFrame, promise: nil) // Client sends headers. - let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")]) + let headers = HPACKHeaders([ + (":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost"), + ]) let reqFramePayload = HTTP2Frame.FramePayload.headers(.init(headers: headers)) childChannel.writeAndFlush(reqFramePayload, promise: nil) @@ -362,7 +408,11 @@ class SimpleClientServerInlineStreamMultiplexerTests: XCTestCase { } // Client receives GOAWAY and RST_STREAM frames. - try self.clientChannel.assertReceivedFrame().assertGoAwayFrame(lastStreamID: .maxID, errorCode: 0, opaqueData: nil) + try self.clientChannel.assertReceivedFrame().assertGoAwayFrame( + lastStreamID: .maxID, + errorCode: 0, + opaqueData: nil + ) clientHandler.receivedFrames.assertFramePayloadsMatch([HTTP2Frame.FramePayload.rstStream(.refusedStream)]) // No frames left. @@ -379,11 +429,14 @@ class SimpleClientServerInlineStreamMultiplexerTests: XCTestCase { func testSuccessfullyReceiveAndSendPingEvenWhenConnectionIsFullyQuiesced() throws { let serverHandler = InboundFramePayloadRecorder() - try self.basicHTTP2Connection() { channel in - return channel.pipeline.addHandler(serverHandler) + try self.basicHTTP2Connection { channel in + channel.pipeline.addHandler(serverHandler) } // Fully quiesce the connection on the server. - let goAwayFrame = HTTP2Frame(streamID: .rootStream, payload: .goAway(lastStreamID: .rootStream, errorCode: .noError, opaqueData: nil)) + let goAwayFrame = HTTP2Frame( + streamID: .rootStream, + payload: .goAway(lastStreamID: .rootStream, errorCode: .noError, opaqueData: nil) + ) serverChannel.writeAndFlush(goAwayFrame, promise: nil) // Send PING frame to the server. @@ -393,7 +446,11 @@ class SimpleClientServerInlineStreamMultiplexerTests: XCTestCase { self.interactInMemory(self.clientChannel, self.serverChannel) // The client receives the GOAWAY frame and fully quiesces the connection. - try self.clientChannel.assertReceivedFrame().assertGoAwayFrame(lastStreamID: .rootStream, errorCode: 0, opaqueData: nil) + try self.clientChannel.assertReceivedFrame().assertGoAwayFrame( + lastStreamID: .rootStream, + errorCode: 0, + opaqueData: nil + ) // The server receives and responds to the PING. try self.serverChannel.assertReceivedFrame().assertPingFrame(ack: false, opaqueData: HTTP2PingData()) @@ -417,10 +474,13 @@ class SimpleClientServerInlineStreamMultiplexerTests: XCTestCase { } let connectionReceivedShouldQuiesceEvent = self.clientChannel.eventLoop.makePromise(of: Void.self) - try self.serverChannel.pipeline.addHandler(ShouldQuiesceEventWaiter(promise: connectionReceivedShouldQuiesceEvent)).wait() + try self.serverChannel.pipeline.addHandler( + ShouldQuiesceEventWaiter(promise: connectionReceivedShouldQuiesceEvent) + ).wait() // Create the stream channel. - let multiplexer = try self.clientChannel.pipeline.handler(type: NIOHTTP2Handler.self).flatMap { $0.multiplexer }.wait() + let multiplexer = try self.clientChannel.pipeline.handler(type: NIOHTTP2Handler.self).flatMap { $0.multiplexer } + .wait() let streamPromise = self.clientChannel.eventLoop.makePromise(of: Channel.self) multiplexer.createStreamChannel(promise: streamPromise) { $0.eventLoop.makeSucceededVoidFuture() diff --git a/Tests/NIOHTTP2Tests/SimpleClientServerTests.swift b/Tests/NIOHTTP2Tests/SimpleClientServerTests.swift index ac25d25..9d88477 100644 --- a/Tests/NIOHTTP2Tests/SimpleClientServerTests.swift +++ b/Tests/NIOHTTP2Tests/SimpleClientServerTests.swift @@ -12,11 +12,12 @@ // //===----------------------------------------------------------------------===// -import XCTest import NIOConcurrencyHelpers import NIOCore import NIOEmbedded import NIOHPACK +import XCTest + @testable import NIOHTTP2 typealias FrameRecorderHandler = InboundFrameRecorder @@ -37,23 +38,47 @@ class SimpleClientServerTests: XCTestCase { /// Establish a basic HTTP/2 connection. @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") - func basicHTTP2Connection(clientSettings: HTTP2Settings = nioDefaultSettings, - serverSettings: HTTP2Settings = nioDefaultSettings, - withMultiplexerCallback multiplexerCallback: NIOChannelInitializerWithStreamID? = nil) throws { - XCTAssertNoThrow(try self.clientChannel.pipeline.addHandler(NIOHTTP2Handler(mode: .client, initialSettings: clientSettings)).wait()) - XCTAssertNoThrow(try self.serverChannel.pipeline.addHandler(NIOHTTP2Handler(mode: .server, initialSettings: serverSettings)).wait()) + func basicHTTP2Connection( + clientSettings: HTTP2Settings = nioDefaultSettings, + serverSettings: HTTP2Settings = nioDefaultSettings, + withMultiplexerCallback multiplexerCallback: NIOChannelInitializerWithStreamID? = nil + ) throws { + XCTAssertNoThrow( + try self.clientChannel.pipeline.addHandler(NIOHTTP2Handler(mode: .client, initialSettings: clientSettings)) + .wait() + ) + XCTAssertNoThrow( + try self.serverChannel.pipeline.addHandler(NIOHTTP2Handler(mode: .server, initialSettings: serverSettings)) + .wait() + ) if let multiplexerCallback = multiplexerCallback { - XCTAssertNoThrow(try self.clientChannel.pipeline.addHandler(HTTP2StreamMultiplexer(mode: .client, - channel: self.clientChannel, - inboundStreamStateInitializer: multiplexerCallback)).wait()) - XCTAssertNoThrow(try self.serverChannel.pipeline.addHandler(HTTP2StreamMultiplexer(mode: .server, - channel: self.serverChannel, - inboundStreamStateInitializer: multiplexerCallback)).wait()) + XCTAssertNoThrow( + try self.clientChannel.pipeline.addHandler( + HTTP2StreamMultiplexer( + mode: .client, + channel: self.clientChannel, + inboundStreamStateInitializer: multiplexerCallback + ) + ).wait() + ) + XCTAssertNoThrow( + try self.serverChannel.pipeline.addHandler( + HTTP2StreamMultiplexer( + mode: .server, + channel: self.serverChannel, + inboundStreamStateInitializer: multiplexerCallback + ) + ).wait() + ) } - try self.assertDoHandshake(client: self.clientChannel, server: self.serverChannel, - clientSettings: clientSettings, serverSettings: serverSettings) + try self.assertDoHandshake( + client: self.clientChannel, + server: self.serverChannel, + clientSettings: clientSettings, + serverSettings: serverSettings + ) } @available(*, deprecated, message: "Deprecated so deprecated functionality can be tested without warnings") @@ -61,13 +86,13 @@ class SimpleClientServerTests: XCTestCase { // Begin by getting the connection up. // We add the stream multiplexer because it'll emit WINDOW_UPDATE frames, which we need. let serverHandler = FrameRecorderHandler() - try self.basicHTTP2Connection() { channel, streamID in - return channel.pipeline.addHandler(serverHandler) + try self.basicHTTP2Connection { channel, streamID in + channel.pipeline.addHandler(serverHandler) } // We're going to create a largish temp file: 3 data frames in size. - var bodyData = self.clientChannel.allocator.buffer(capacity: 1<<14) - for val in (0..<((1<<14) / MemoryLayout.size)) { + var bodyData = self.clientChannel.allocator.buffer(capacity: 1 << 14) + for val in (0..<((1 << 14) / MemoryLayout.size)) { bodyData.writeInteger(val) } @@ -80,14 +105,18 @@ class SimpleClientServerTests: XCTestCase { let clientHandler = FrameRecorderHandler() let childChannelPromise = self.clientChannel.eventLoop.makePromise(of: Channel.self) - try (self.clientChannel.pipeline.context(handlerType: HTTP2StreamMultiplexer.self).wait().handler as! HTTP2StreamMultiplexer).createStreamChannel(promise: childChannelPromise) { channel, streamID in - return channel.pipeline.addHandler(clientHandler) - } + try + (self.clientChannel.pipeline.context(handlerType: HTTP2StreamMultiplexer.self).wait().handler + as! HTTP2StreamMultiplexer).createStreamChannel(promise: childChannelPromise) { channel, streamID in + channel.pipeline.addHandler(clientHandler) + } (self.clientChannel.eventLoop as! EmbeddedEventLoop).run() let childChannel = try childChannelPromise.futureResult.wait() // Start by sending the headers. - let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")]) + let headers = HPACKHeaders([ + (":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost"), + ]) let clientStreamID = HTTP2StreamID(1) let reqFrame = HTTP2Frame(streamID: clientStreamID, payload: .headers(.init(headers: headers))) childChannel.writeAndFlush(reqFrame, promise: nil) @@ -98,17 +127,27 @@ class SimpleClientServerTests: XCTestCase { self.serverChannel.assertNoFramesReceived() // Ok, we're gonna send the body here. - let reqBodyFrame = HTTP2Frame(streamID: clientStreamID, payload: .data(.init(data: .fileRegion(region), endStream: true))) + let reqBodyFrame = HTTP2Frame( + streamID: clientStreamID, + payload: .data(.init(data: .fileRegion(region), endStream: true)) + ) childChannel.writeAndFlush(reqBodyFrame, promise: nil) self.interactInMemory(self.clientChannel, self.serverChannel) // We now expect 3 frames. - let dataFrames = (0..<3).map { idx in HTTP2Frame(streamID: clientStreamID, payload: .data(.init(data: .byteBuffer(bodyData), endStream: idx == 2))) } + let dataFrames = (0..<3).map { idx in + HTTP2Frame( + streamID: clientStreamID, + payload: .data(.init(data: .byteBuffer(bodyData), endStream: idx == 2)) + ) + } serverHandler.receivedFrames.assertFramesMatch([reqFrame] + dataFrames) // The client will have seen a pair of window updates: one on the connection, one on the stream. try self.clientChannel.assertReceivedFrame().assertWindowUpdateFrame(streamID: 0, windowIncrement: 32768) - clientHandler.receivedFrames.assertFramesMatch([HTTP2Frame(streamID: clientStreamID, payload: .windowUpdate(windowSizeIncrement: 32768))]) + clientHandler.receivedFrames.assertFramesMatch([ + HTTP2Frame(streamID: clientStreamID, payload: .windowUpdate(windowSizeIncrement: 32768)) + ]) // No frames left. self.clientChannel.assertNoFramesReceived() @@ -123,19 +162,23 @@ class SimpleClientServerTests: XCTestCase { func testAutomaticFlowControl() throws { // Begin by getting the connection up. // We add the stream multiplexer here because it manages automatic flow control. - try self.basicHTTP2Connection() { channel, streamID in - return channel.eventLoop.makeSucceededFuture(()) + try self.basicHTTP2Connection { channel, streamID in + channel.eventLoop.makeSucceededFuture(()) } // Now we're going to send a request, including a very large body: 65536 bytes in size. To avoid spending too much // time initializing buffers, we're going to send the same 1kB data frame 64 times. - let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")]) + let headers = HPACKHeaders([ + (":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost"), + ]) var _requestBody = self.clientChannel.allocator.buffer(capacity: 1024) _requestBody.writeBytes(Array(repeating: UInt8(0x04), count: 1024)) let requestBody = _requestBody // We're going to open a stream and queue up the frames for that stream. - let handler = try self.clientChannel.pipeline.context(handlerType: HTTP2StreamMultiplexer.self).wait().handler as! HTTP2StreamMultiplexer + let handler = + try self.clientChannel.pipeline.context(handlerType: HTTP2StreamMultiplexer.self).wait().handler + as! HTTP2StreamMultiplexer let childHandler = FrameRecorderHandler() handler.createStreamChannel(promise: nil) { channel, streamID in let reqFrame = HTTP2Frame(streamID: streamID, payload: .headers(.init(headers: headers))) @@ -177,13 +220,19 @@ class SimpleClientServerTests: XCTestCase { // 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()) + 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 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)))) @@ -199,18 +248,30 @@ class SimpleClientServerTests: XCTestCase { // 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.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) + 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) + try self.assertSettingsUpdateWithAck( + [(HTTP2Setting(parameter: .initialWindowSize, value: 65535))], + sender: self.serverChannel, + receiver: self.clientChannel + ) self.clientChannel.assertNoFramesReceived() self.serverChannel.assertNoFramesReceived() @@ -238,14 +299,19 @@ class SimpleClientServerTests: XCTestCase { channel.write(respFrame, promise: nil) // Now prepare the large body. - let respBodyFrame = HTTP2Frame(streamID: streamID, payload: .data(.init(data: .byteBuffer(responseBody), endStream: true))) + let respBodyFrame = HTTP2Frame( + streamID: streamID, + payload: .data(.init(data: .byteBuffer(responseBody), endStream: true)) + ) channel.writeAndFlush(respBodyFrame, promise: nil) return channel.pipeline.addHandler(childHandler) } // Now we're going to send a small request. - let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")]) + let headers = HPACKHeaders([ + (":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost"), + ]) // We're going to open a stream and queue up the frames for that stream. let handler = try self.clientChannel.pipeline.handler(type: HTTP2StreamMultiplexer.self).wait() @@ -288,11 +354,13 @@ class SimpleClientServerTests: XCTestCase { // to correctly confirm we don't receive a frame for the child stream. let childHandler = FrameRecorderHandler() try self.basicHTTP2Connection(serverSettings: serverSettings) { channel, streamID in - return channel.eventLoop.makeSucceededFuture(()) + channel.eventLoop.makeSucceededFuture(()) } // Now we're going to send a large request: 65535 bytes in size - let headers = HPACKHeaders([(":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost")]) + let headers = HPACKHeaders([ + (":path", "/"), (":method", "POST"), (":scheme", "https"), (":authority", "localhost"), + ]) // We're going to open a stream and queue up the frames for that stream. let handler = try self.clientChannel.pipeline.handler(type: HTTP2StreamMultiplexer.self).wait() @@ -305,7 +373,10 @@ class SimpleClientServerTests: XCTestCase { requestBody.writeBytes(Array(repeating: UInt8(0x04), count: 65535)) // Now prepare the large body. We need END_STREAM set. - let reqBodyFrame = HTTP2Frame(streamID: streamID, payload: .data(.init(data: .byteBuffer(requestBody), endStream: true))) + let reqBodyFrame = HTTP2Frame( + streamID: streamID, + payload: .data(.init(data: .byteBuffer(requestBody), endStream: true)) + ) channel.writeAndFlush(reqBodyFrame, promise: nil) return channel.pipeline.addHandler(childHandler) @@ -335,30 +406,34 @@ class SimpleClientServerTests: XCTestCase { let streamAPromise = self.clientChannel.eventLoop.makePromise(of: Channel.self) multiplexer.createStreamChannel(promise: streamAPromise) { channel, _ in - return channel.eventLoop.makeSucceededFuture(()) + channel.eventLoop.makeSucceededFuture(()) } self.clientChannel.embeddedEventLoop.run() let streamA = try assertNoThrowWithValue(try streamAPromise.futureResult.wait()) let streamBPromise = self.clientChannel.eventLoop.makePromise(of: Channel.self) multiplexer.createStreamChannel(promise: streamBPromise) { channel, _ in - return channel.eventLoop.makeSucceededFuture(()) + channel.eventLoop.makeSucceededFuture(()) } self.clientChannel.embeddedEventLoop.run() let streamB = try assertNoThrowWithValue(try streamBPromise.futureResult.wait()) - let headers = HPACKHeaders([(":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https")]) + let headers = HPACKHeaders([ + (":path", "/"), (":method", "GET"), (":authority", "localhost"), (":scheme", "https"), + ]) let headersFramePayload = HTTP2Frame.FramePayload.headers(.init(headers: headers, endStream: false)) // Write on 'B' first. - let streamBHeadersWritten = streamB.getOption(HTTP2StreamChannelOptions.streamID).flatMap { streamID -> EventLoopFuture in + let streamBHeadersWritten = streamB.getOption(HTTP2StreamChannelOptions.streamID).flatMap { + streamID -> EventLoopFuture in let frame = HTTP2Frame(streamID: streamID, payload: headersFramePayload) return streamB.writeAndFlush(frame) } XCTAssertNoThrow(try streamBHeadersWritten.wait()) // Now write on stream 'A', it will fail. (This failure motivated the frame-payload based stream channel.) - let streamAHeadersWritten = streamA.getOption(HTTP2StreamChannelOptions.streamID).flatMap { streamID -> EventLoopFuture in + let streamAHeadersWritten = streamA.getOption(HTTP2StreamChannelOptions.streamID).flatMap { + streamID -> EventLoopFuture in let frame = HTTP2Frame(streamID: streamID, payload: headersFramePayload) return streamA.writeAndFlush(frame) } @@ -407,7 +482,7 @@ class SimpleClientServerTests: XCTestCase { 0x06, // frame type, ping 0x00, // flags, zeros 0x00, 0x00, 0x00, 0x00, // stream ID, 0 - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // 8 byte payload, all zeros + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // 8 byte payload, all zeros ]) ) } @@ -440,7 +515,7 @@ class SimpleClientServerTests: XCTestCase { try channel.pipeline.syncOperations.addHandlers( [ NIOHTTP2Handler(mode: .client), - recorder + recorder, ] ) @@ -472,7 +547,7 @@ class SimpleClientServerTests: XCTestCase { try channel.pipeline.syncOperations.addHandlers( [ NIOHTTP2Handler(mode: .client, tolerateImpossibleStateTransitionsInDebugMode: true), - recorder + recorder, ] ) @@ -484,7 +559,10 @@ class SimpleClientServerTests: XCTestCase { // First impossible state transition: channelActive on channelActive. var (channel, recorder) = try setUpChannel() - try channel.pipeline.syncOperations.addHandler(ActionOnFlushHandler { $0.pipeline.fireChannelActive() }, position: .first) + try channel.pipeline.syncOperations.addHandler( + ActionOnFlushHandler { $0.pipeline.fireChannelActive() }, + position: .first + ) channel.pipeline.fireChannelActive() recorder.errors.withLockedValue { errors in XCTAssertEqual(errors.count, 1) @@ -613,28 +691,28 @@ class SimpleClientServerTests: XCTestCase { // We expect the following frame bytes. The use of incremental indexing here is fine, // as the value shouldn't actually be added to the dynamic table. var expectedBytes = ByteBuffer(bytes: [ - 0x00, 0x00, 0x1f, // Frame length: 31 bytes - 0x01, // Frame type: 1, HEADERS - 0x05, // Frame flags: END_HEADERS | END_STREAM - 0x00, 0x00, 0x00, 0x01, // Stream ID: 1 - 0x20, // Max dynamic table size change, 0 - 0x84, // Indexed field, index number 4, static table - 0x87, // Indexed field, index number 7, static table - 0x41, // Literal field with incremental indexing, index 1, - 0x88, // Huffman-coded value with length 8, - 0x2f, 0x91, 0xd3, - 0x5d, 0x05, 0x5c, - 0x87, 0xa7, - 0x82, // Indexed field, index number 2, static table - 0x40, // Literal field with incremental indexing, new name, - 0x8a, // Huffman-coded name with length 10 - 0x1a, 0xd3, 0x94, - 0x72, 0x16, 0xc5, - 0xa5, 0x31, 0x68, - 0x93, - 0x84, // Huffman-coded value with length 4 - 0x32, 0x14, 0x41, - 0x53 + 0x00, 0x00, 0x1f, // Frame length: 31 bytes + 0x01, // Frame type: 1, HEADERS + 0x05, // Frame flags: END_HEADERS | END_STREAM + 0x00, 0x00, 0x00, 0x01, // Stream ID: 1 + 0x20, // Max dynamic table size change, 0 + 0x84, // Indexed field, index number 4, static table + 0x87, // Indexed field, index number 7, static table + 0x41, // Literal field with incremental indexing, index 1, + 0x88, // Huffman-coded value with length 8, + 0x2f, 0x91, 0xd3, + 0x5d, 0x05, 0x5c, + 0x87, 0xa7, + 0x82, // Indexed field, index number 2, static table + 0x40, // Literal field with incremental indexing, new name, + 0x8a, // Huffman-coded name with length 10 + 0x1a, 0xd3, 0x94, + 0x72, 0x16, 0xc5, + 0xa5, 0x31, 0x68, + 0x93, + 0x84, // Huffman-coded value with length 4 + 0x32, 0x14, 0x41, + 0x53, ]) XCTAssertEqual(expectedBytes, reads.last) @@ -648,27 +726,27 @@ class SimpleClientServerTests: XCTestCase { // This should be similar to the first, but without the dynamic table size change and a new stream ID. expectedBytes = ByteBuffer(bytes: [ - 0x00, 0x00, 0x1e, // Frame length: 30 bytes - 0x01, // Frame type: 1, HEADERS - 0x05, // Frame flags: END_HEADERS | END_STREAM - 0x00, 0x00, 0x00, 0x03, // Stream ID: 3 - 0x84, // Indexed field, index number 4, static table - 0x87, // Indexed field, index number 7, static table - 0x41, // Literal field with incremental indexing, index 1, - 0x88, // Huffman-coded value with length 8, - 0x2f, 0x91, 0xd3, - 0x5d, 0x05, 0x5c, - 0x87, 0xa7, - 0x82, // Indexed field, index number 2, static table - 0x40, // Literal field with incremental indexing, new name, - 0x8a, // Huffman-coded name with length 10 - 0x1a, 0xd3, 0x94, - 0x72, 0x16, 0xc5, - 0xa5, 0x31, 0x68, - 0x93, - 0x84, // Huffman-coded value with length 4 - 0x32, 0x14, 0x41, - 0x53 + 0x00, 0x00, 0x1e, // Frame length: 30 bytes + 0x01, // Frame type: 1, HEADERS + 0x05, // Frame flags: END_HEADERS | END_STREAM + 0x00, 0x00, 0x00, 0x03, // Stream ID: 3 + 0x84, // Indexed field, index number 4, static table + 0x87, // Indexed field, index number 7, static table + 0x41, // Literal field with incremental indexing, index 1, + 0x88, // Huffman-coded value with length 8, + 0x2f, 0x91, 0xd3, + 0x5d, 0x05, 0x5c, + 0x87, 0xa7, + 0x82, // Indexed field, index number 2, static table + 0x40, // Literal field with incremental indexing, new name, + 0x8a, // Huffman-coded name with length 10 + 0x1a, 0xd3, 0x94, + 0x72, 0x16, 0xc5, + 0xa5, 0x31, 0x68, + 0x93, + 0x84, // Huffman-coded value with length 4 + 0x32, 0x14, 0x41, + 0x53, ]) XCTAssertEqual(expectedBytes, reads.first) } @@ -705,8 +783,12 @@ class SimpleClientServerTests: XCTestCase { // Send the frame twice. This should error. buffer.clear() - XCTAssertNil(try frameEncoder.encode(frame: HTTP2Frame(streamID: 1, payload: .headers(framePayload)), to: &buffer)) - XCTAssertNil(try frameEncoder.encode(frame: HTTP2Frame(streamID: 3, payload: .headers(framePayload)), to: &buffer)) + XCTAssertNil( + try frameEncoder.encode(frame: HTTP2Frame(streamID: 1, payload: .headers(framePayload)), to: &buffer) + ) + XCTAssertNil( + try frameEncoder.encode(frame: HTTP2Frame(streamID: 3, payload: .headers(framePayload)), to: &buffer) + ) XCTAssertThrowsError(try channel.writeInbound(buffer)) { error in XCTAssertTrue(error is NIOHTTP2Errors.UnableToParseFrame) } @@ -748,27 +830,27 @@ class SimpleClientServerTests: XCTestCase { // We expect the following frame bytes. The use of incremental indexing here is expected, // as the value will be added to the dynamic table. var expectedBytes = ByteBuffer(bytes: [ - 0x00, 0x00, 0x1e, // Frame length: 30 bytes - 0x01, // Frame type: 1, HEADERS - 0x05, // Frame flags: END_HEADERS | END_STREAM - 0x00, 0x00, 0x00, 0x01, // Stream ID: 1 - 0x84, // Indexed field, index number 4, static table - 0x87, // Indexed field, index number 7, static table - 0x41, // Literal field with incremental indexing, index 1, - 0x88, // Huffman-coded value with length 8, - 0x2f, 0x91, 0xd3, - 0x5d, 0x05, 0x5c, - 0x87, 0xa7, - 0x82, // Indexed field, index number 2, static table - 0x40, // Literal field with incremental indexing, new name, - 0x8a, // Huffman-coded name with length 10 - 0x1a, 0xd3, 0x94, - 0x72, 0x16, 0xc5, - 0xa5, 0x31, 0x68, - 0x93, - 0x84, // Huffman-coded value with length 4 - 0x32, 0x14, 0x41, - 0x53 + 0x00, 0x00, 0x1e, // Frame length: 30 bytes + 0x01, // Frame type: 1, HEADERS + 0x05, // Frame flags: END_HEADERS | END_STREAM + 0x00, 0x00, 0x00, 0x01, // Stream ID: 1 + 0x84, // Indexed field, index number 4, static table + 0x87, // Indexed field, index number 7, static table + 0x41, // Literal field with incremental indexing, index 1, + 0x88, // Huffman-coded value with length 8, + 0x2f, 0x91, 0xd3, + 0x5d, 0x05, 0x5c, + 0x87, 0xa7, + 0x82, // Indexed field, index number 2, static table + 0x40, // Literal field with incremental indexing, new name, + 0x8a, // Huffman-coded name with length 10 + 0x1a, 0xd3, 0x94, + 0x72, 0x16, 0xc5, + 0xa5, 0x31, 0x68, + 0x93, + 0x84, // Huffman-coded value with length 4 + 0x32, 0x14, 0x41, + 0x53, ]) XCTAssertEqual(expectedBytes, reads.last) @@ -789,28 +871,28 @@ class SimpleClientServerTests: XCTestCase { // This should be similar to the first, but without a dynamic table size change and a new stream ID. expectedBytes = ByteBuffer(bytes: [ - 0x00, 0x00, 0x1f, // Frame length: 31 bytes - 0x01, // Frame type: 1, HEADERS - 0x05, // Frame flags: END_HEADERS | END_STREAM - 0x00, 0x00, 0x00, 0x03, // Stream ID: 3 - 0x20, // Max dynamic table size change, 0 - 0x84, // Indexed field, index number 4, static table - 0x87, // Indexed field, index number 7, static table - 0x41, // Literal field with incremental indexing, index 1, - 0x88, // Huffman-coded value with length 8, - 0x2f, 0x91, 0xd3, - 0x5d, 0x05, 0x5c, - 0x87, 0xa7, - 0x82, // Indexed field, index number 2, static table - 0x40, // Literal field with incremental indexing, new name, - 0x8a, // Huffman-coded name with length 10 - 0x1a, 0xd3, 0x94, - 0x72, 0x16, 0xc5, - 0xa5, 0x31, 0x68, - 0x93, - 0x84, // Huffman-coded value with length 4 - 0x32, 0x14, 0x41, - 0x53 + 0x00, 0x00, 0x1f, // Frame length: 31 bytes + 0x01, // Frame type: 1, HEADERS + 0x05, // Frame flags: END_HEADERS | END_STREAM + 0x00, 0x00, 0x00, 0x03, // Stream ID: 3 + 0x20, // Max dynamic table size change, 0 + 0x84, // Indexed field, index number 4, static table + 0x87, // Indexed field, index number 7, static table + 0x41, // Literal field with incremental indexing, index 1, + 0x88, // Huffman-coded value with length 8, + 0x2f, 0x91, 0xd3, + 0x5d, 0x05, 0x5c, + 0x87, 0xa7, + 0x82, // Indexed field, index number 2, static table + 0x40, // Literal field with incremental indexing, new name, + 0x8a, // Huffman-coded name with length 10 + 0x1a, 0xd3, 0x94, + 0x72, 0x16, 0xc5, + 0xa5, 0x31, 0x68, + 0x93, + 0x84, // Huffman-coded value with length 4 + 0x32, 0x14, 0x41, + 0x53, ]) XCTAssertEqual(expectedBytes, reads.last) } @@ -847,7 +929,9 @@ class SimpleClientServerTests: XCTestCase { // Send the first frame. buffer.clear() - XCTAssertNil(try frameEncoder.encode(frame: HTTP2Frame(streamID: 1, payload: .headers(framePayload)), to: &buffer)) + XCTAssertNil( + try frameEncoder.encode(frame: HTTP2Frame(streamID: 1, payload: .headers(framePayload)), to: &buffer) + ) XCTAssertNoThrow(try channel.writeInbound(buffer)) // Now, we send a settings frame that updates our settings. @@ -859,7 +943,9 @@ class SimpleClientServerTests: XCTestCase { // be rejected. buffer.clear() XCTAssertNil(try frameEncoder.encode(frame: HTTP2Frame(streamID: 0, payload: .settings(.ack)), to: &buffer)) - XCTAssertNil(try frameEncoder.encode(frame: HTTP2Frame(streamID: 3, payload: .headers(framePayload)), to: &buffer)) + XCTAssertNil( + try frameEncoder.encode(frame: HTTP2Frame(streamID: 3, payload: .headers(framePayload)), to: &buffer) + ) XCTAssertThrowsError(try channel.writeInbound(buffer)) { error in XCTAssertTrue(error is NIOHTTP2Errors.UnableToParseFrame) } diff --git a/Tests/NIOHTTP2Tests/StreamChannelFlowControllerTests.swift b/Tests/NIOHTTP2Tests/StreamChannelFlowControllerTests.swift index 9367a60..3461f65 100644 --- a/Tests/NIOHTTP2Tests/StreamChannelFlowControllerTests.swift +++ b/Tests/NIOHTTP2Tests/StreamChannelFlowControllerTests.swift @@ -13,8 +13,8 @@ //===----------------------------------------------------------------------===// import XCTest -@testable import NIOHTTP2 +@testable import NIOHTTP2 final class StreamChannelFlowControllerTests: XCTestCase { func testChannelWritabilityChangesFromFlowControl() { diff --git a/Tests/NIOHTTP2Tests/StreamIDTests.swift b/Tests/NIOHTTP2Tests/StreamIDTests.swift index df8853a..e68aeea 100644 --- a/Tests/NIOHTTP2Tests/StreamIDTests.swift +++ b/Tests/NIOHTTP2Tests/StreamIDTests.swift @@ -12,14 +12,19 @@ // //===----------------------------------------------------------------------===// -import XCTest import NIOHTTP2 - +import XCTest final class StreamIDTests: XCTestCase { func testStreamIDsAreStrideable() { - XCTAssertEqual(Array(HTTP2StreamID(1)..() + var result = [Int32]() map.forEachValue { result.append($0.streamID.networkStreamID) } @@ -76,7 +77,7 @@ final class StreamMapTests: XCTestCase { map.insert(StreamDataWithValue(number, value: number)) } - var result = Array() + var result = [Int]() map.forEachValue { result.append($0.value) } @@ -124,7 +125,7 @@ final class StreamMapTests: XCTestCase { } // Now validate what's there. - var result = Array() + var result = [Int32]() map.forEachValue { result.append($0.streamID.networkStreamID) } @@ -157,12 +158,14 @@ final class StreamMapTests: XCTestCase { } // Check all the values. - var result = Array>() + var result = [StreamDataWithValue]() map.forEachValue { result.append($0) } - XCTAssertEqual(result.sorted(by: { $0.streamID < $1.streamID }).map { $0.value }, - Array(1..<100).map { $0 % 5 == 1 ? false : true }) + XCTAssertEqual( + result.sorted(by: { $0.streamID < $1.streamID }).map { $0.value }, + Array(1..<100).map { $0 % 5 == 1 ? false : true } + ) // Modifying something that isn't present should do nothing and not execute the block. // We do this once for the server-side and once for the client-side. @@ -183,23 +186,33 @@ final class StreamMapTests: XCTestCase { } map.dropDataWithStreamIDGreaterThan(streamIDToDropFrom, initiatedBy: .client) { droppedStreams in - XCTAssertEqual(droppedStreams.map { $0.streamID }, (streamIDToDropFrom.advanced(by: 1).. ByteBuffer? { - return try? await assertNoThrowWithValue(await channel.readOutbound(as: ByteBuffer.self)) + try? await assertNoThrowWithValue(await channel.readOutbound(as: ByteBuffer.self)) } repeat { @@ -123,11 +129,16 @@ extension XCTestCase { /// Have a `NIOAsyncTestingChannel` send data to another until it makes no forward progress. @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) - static func deliverAllBytes(from source: NIOAsyncTestingChannel, to destination: NIOAsyncTestingChannel, file: StaticString = #filePath, line: UInt = #line) async throws { + static func deliverAllBytes( + from source: NIOAsyncTestingChannel, + to destination: NIOAsyncTestingChannel, + file: StaticString = #filePath, + line: UInt = #line + ) async throws { var operated: Bool func readBytesFromChannel(_ channel: NIOAsyncTestingChannel) async -> ByteBuffer? { - return try? await assertNoThrowWithValue(await channel.readOutbound(as: ByteBuffer.self)) + try? await assertNoThrowWithValue(await channel.readOutbound(as: ByteBuffer.self)) } repeat { @@ -140,10 +151,17 @@ extension XCTestCase { } /// Deliver all the bytes currently flushed on `sourceChannel` to `targetChannel`. - func deliverAllBytes(from sourceChannel: EmbeddedChannel, to targetChannel: EmbeddedChannel, file: StaticString = #filePath, line: UInt = #line) { + func deliverAllBytes( + from sourceChannel: EmbeddedChannel, + to targetChannel: EmbeddedChannel, + file: StaticString = #filePath, + line: UInt = #line + ) { // Collect the serialized data. var frameBuffer = sourceChannel.allocator.buffer(capacity: 1024) - while case .some(.byteBuffer(var buf)) = try? assertNoThrowWithValue(sourceChannel.readOutbound(as: IOData.self)) { + while case .some(.byteBuffer(var buf)) = try? assertNoThrowWithValue( + sourceChannel.readOutbound(as: IOData.self) + ) { frameBuffer.writeBuffer(&buf) } @@ -155,9 +173,14 @@ extension XCTestCase { /// /// If the handshake has not occurred, this will definitely call `XCTFail`. It may also throw if the /// channel is now in an indeterminate state. - func assertDoHandshake(client: EmbeddedChannel, server: EmbeddedChannel, - clientSettings: [HTTP2Setting] = nioDefaultSettings, serverSettings: [HTTP2Setting] = nioDefaultSettings, - file: StaticString = #filePath, line: UInt = #line) throws { + func assertDoHandshake( + client: EmbeddedChannel, + server: EmbeddedChannel, + clientSettings: [HTTP2Setting] = nioDefaultSettings, + serverSettings: [HTTP2Setting] = nioDefaultSettings, + file: StaticString = #filePath, + line: UInt = #line + ) throws { // This connects are not semantically right, but are required in order to activate the // channels. //! FIXME: Replace with registerAlreadyConfigured0 once EmbeddedChannel propagates this @@ -178,8 +201,18 @@ extension XCTestCase { let serverReceivedSettingsAck = try server.assertReceivedFrame(file: (file), line: line) // Check that these SETTINGS frames are ok. - clientReceivedSettings.assertSettingsFrame(expectedSettings: serverSettings, ack: false, file: (file), line: line) - serverReceivedSettings.assertSettingsFrame(expectedSettings: clientSettings, ack: false, file: (file), line: line) + clientReceivedSettings.assertSettingsFrame( + expectedSettings: serverSettings, + ack: false, + file: (file), + line: line + ) + serverReceivedSettings.assertSettingsFrame( + expectedSettings: clientSettings, + ack: false, + file: (file), + line: line + ) clientReceivedSettingsAck.assertSettingsFrame(expectedSettings: [], ack: true, file: (file), line: line) serverReceivedSettingsAck.assertSettingsFrame(expectedSettings: [], ack: true, file: (file), line: line) @@ -193,9 +226,14 @@ extension XCTestCase { /// If the handshake has not occurred, this will definitely call `XCTFail`. It may also throw if the /// channel is now in an indeterminate state. @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) - func assertDoHandshake(client: NIOAsyncTestingChannel, server: NIOAsyncTestingChannel, - clientSettings: [HTTP2Setting] = nioDefaultSettings, serverSettings: [HTTP2Setting] = nioDefaultSettings, - file: StaticString = #filePath, line: UInt = #line) async throws { + func assertDoHandshake( + client: NIOAsyncTestingChannel, + server: NIOAsyncTestingChannel, + clientSettings: [HTTP2Setting] = nioDefaultSettings, + serverSettings: [HTTP2Setting] = nioDefaultSettings, + file: StaticString = #filePath, + line: UInt = #line + ) async throws { // This connects are not semantically right, but are required in order to activate the // channels. //! FIXME: Replace with registerAlreadyConfigured0 once EmbeddedChannel propagates this @@ -230,7 +268,13 @@ extension XCTestCase { /// /// Optionally returns the frames received. @discardableResult - func assertFramesRoundTrip(frames: [HTTP2Frame], sender: EmbeddedChannel, receiver: EmbeddedChannel, file: StaticString = #filePath, line: UInt = #line) throws -> [HTTP2Frame] { + func assertFramesRoundTrip( + frames: [HTTP2Frame], + sender: EmbeddedChannel, + receiver: EmbeddedChannel, + file: StaticString = #filePath, + line: UInt = #line + ) throws -> [HTTP2Frame] { for frame in frames { sender.write(frame, promise: nil) } @@ -251,13 +295,21 @@ extension XCTestCase { /// Asserts that sending new settings from `sender` to `receiver` leads to an appropriate settings ACK. Does not assert that no other frames have been /// received. - func assertSettingsUpdateWithAck(_ newSettings: HTTP2Settings, sender: EmbeddedChannel, receiver: EmbeddedChannel, file: StaticString = #filePath, line: UInt = #line) throws { + func assertSettingsUpdateWithAck( + _ newSettings: HTTP2Settings, + sender: EmbeddedChannel, + receiver: EmbeddedChannel, + file: StaticString = #filePath, + line: UInt = #line + ) throws { let frame = HTTP2Frame(streamID: .rootStream, payload: .settings(.settings(newSettings))) sender.writeAndFlush(frame, promise: nil) self.interactInMemory(sender, receiver, file: (file), line: line) try receiver.assertReceivedFrame(file: (file), line: line).assertFrameMatches(this: frame) - try sender.assertReceivedFrame(file: (file), line: line).assertFrameMatches(this: HTTP2Frame(streamID: .rootStream, payload: .settings(.ack))) + try sender.assertReceivedFrame(file: (file), line: line).assertFrameMatches( + this: HTTP2Frame(streamID: .rootStream, payload: .settings(.ack)) + ) } } @@ -301,7 +353,8 @@ extension EmbeddedChannel { expectClientMagic: false, maximumSequentialContinuationFrames: 5 ) - while let buffer = try assertNoThrowWithValue(self.readOutbound(as: ByteBuffer.self), file: (file), line: line) { + while let buffer = try assertNoThrowWithValue(self.readOutbound(as: ByteBuffer.self), file: (file), line: line) + { frameDecoder.append(bytes: buffer) if let (frame, _) = try frameDecoder.nextFrame() { receivedFrames.append(frame) @@ -336,25 +389,50 @@ extension NIOAsyncTestingChannel { extension HTTP2Frame { /// Asserts that the given frame is a SETTINGS frame. - func assertSettingsFrame(expectedSettings: [HTTP2Setting], ack: Bool, file: StaticString = #filePath, line: UInt = #line) { - XCTAssertEqual(self.streamID, .rootStream, "Got unexpected stream ID for SETTINGS: \(self.streamID)", - file: (file), line: line) + func assertSettingsFrame( + expectedSettings: [HTTP2Setting], + ack: Bool, + file: StaticString = #filePath, + line: UInt = #line + ) { + XCTAssertEqual( + self.streamID, + .rootStream, + "Got unexpected stream ID for SETTINGS: \(self.streamID)", + file: (file), + line: line + ) self.payload.assertSettingsFramePayload(expectedSettings: expectedSettings, ack: ack, file: (file), line: line) } func assertSettingsFrameMatches(this frame: HTTP2Frame, file: StaticString = #filePath, line: UInt = #line) { - XCTAssertEqual(self.streamID, .rootStream, "Got unexpected stream ID for SETTINGS: \(self.streamID)", - file: (file), line: line) + XCTAssertEqual( + self.streamID, + .rootStream, + "Got unexpected stream ID for SETTINGS: \(self.streamID)", + file: (file), + line: line + ) self.payload.assertSettingsFramePayloadMatches(this: frame.payload, file: (file), line: line) } /// Asserts that this frame matches a give other frame. - func assertFrameMatches(this frame: HTTP2Frame, dataFileRegionToByteBuffer: Bool = true, file: StaticString = #filePath, line: UInt = #line) { + func assertFrameMatches( + this frame: HTTP2Frame, + dataFileRegionToByteBuffer: Bool = true, + file: StaticString = #filePath, + line: UInt = #line + ) { switch frame.payload { case .headers: self.assertHeadersFrameMatches(this: frame, file: (file), line: line) case .data: - self.assertDataFrameMatches(this: frame, fileRegionToByteBuffer: dataFileRegionToByteBuffer, file: (file), line: line) + self.assertDataFrameMatches( + this: frame, + fileRegionToByteBuffer: dataFileRegionToByteBuffer, + file: (file), + line: line + ) case .goAway: self.assertGoAwayFrameMatches(this: frame, file: (file), line: line) case .ping: @@ -378,8 +456,13 @@ extension HTTP2Frame { /// Asserts that a given frame is a HEADERS frame matching this one. func assertHeadersFrameMatches(this frame: HTTP2Frame, file: StaticString = #filePath, line: UInt = #line) { - XCTAssertEqual(self.streamID, frame.streamID, - "Unexpected streamID: expected \(streamID), got \(self.streamID)", file: (file), line: line) + XCTAssertEqual( + self.streamID, + frame.streamID, + "Unexpected streamID: expected \(streamID), got \(self.streamID)", + file: (file), + line: line + ) self.payload.assertHeadersFramePayloadMatches(this: frame.payload, file: (file), line: line) } @@ -391,28 +474,71 @@ extension HTTP2Frame { } /// Asserts the given frame is a HEADERS frame. - func assertHeadersFrame(endStream: Bool, streamID: HTTP2StreamID, headers: HPACKHeaders, - priority: HTTP2Frame.StreamPriorityData? = nil, - type: HeadersType? = nil, - file: StaticString = #filePath, line: UInt = #line) { - XCTAssertEqual(self.streamID, streamID, - "Unexpected streamID: expected \(streamID), got \(self.streamID)", file: (file), line: line) - self.payload.assertHeadersFramePayload(endStream: endStream, headers: headers, priority: priority, type: type, file: file, line: line) + func assertHeadersFrame( + endStream: Bool, + streamID: HTTP2StreamID, + headers: HPACKHeaders, + priority: HTTP2Frame.StreamPriorityData? = nil, + type: HeadersType? = nil, + file: StaticString = #filePath, + line: UInt = #line + ) { + XCTAssertEqual( + self.streamID, + streamID, + "Unexpected streamID: expected \(streamID), got \(self.streamID)", + file: (file), + line: line + ) + self.payload.assertHeadersFramePayload( + endStream: endStream, + headers: headers, + priority: priority, + type: type, + file: file, + line: line + ) } /// Asserts that a given frame is a DATA frame matching this one. /// /// This function always converts the DATA frame to a bytebuffer, for use with round-trip testing. - func assertDataFrameMatches(this frame: HTTP2Frame, fileRegionToByteBuffer: Bool = true, file: StaticString = #filePath, line: UInt = #line) { - XCTAssertEqual(self.streamID, frame.streamID, - "Unexpected streamID: expected \(streamID), got \(self.streamID)", file: (file), line: line) - self.payload.assertDataFramePayloadMatches(this: frame.payload, fileRegionToByteBuffer: fileRegionToByteBuffer, file: (file), line: line) + func assertDataFrameMatches( + this frame: HTTP2Frame, + fileRegionToByteBuffer: Bool = true, + file: StaticString = #filePath, + line: UInt = #line + ) { + XCTAssertEqual( + self.streamID, + frame.streamID, + "Unexpected streamID: expected \(streamID), got \(self.streamID)", + file: (file), + line: line + ) + self.payload.assertDataFramePayloadMatches( + this: frame.payload, + fileRegionToByteBuffer: fileRegionToByteBuffer, + file: (file), + line: line + ) } /// Assert the given frame is a DATA frame with the appropriate settings. - func assertDataFrame(endStream: Bool, streamID: HTTP2StreamID, payload: ByteBuffer, file: StaticString = #filePath, line: UInt = #line) { - XCTAssertEqual(self.streamID, streamID, - "Unexpected streamID: expected \(streamID), got \(self.streamID)", file: (file), line: line) + func assertDataFrame( + endStream: Bool, + streamID: HTTP2StreamID, + payload: ByteBuffer, + file: StaticString = #filePath, + line: UInt = #line + ) { + XCTAssertEqual( + self.streamID, + streamID, + "Unexpected streamID: expected \(streamID), got \(self.streamID)", + file: (file), + line: line + ) self.payload.assertDataFramePayload(endStream: endStream, payload: payload, file: file, line: line) } @@ -421,9 +547,21 @@ extension HTTP2Frame { self.payload.assertGoAwayFramePayloadMatches(this: frame.payload) } - func assertGoAwayFrame(lastStreamID: HTTP2StreamID, errorCode: UInt32, opaqueData: [UInt8]?, file: StaticString = #filePath, line: UInt = #line) { + func assertGoAwayFrame( + lastStreamID: HTTP2StreamID, + errorCode: UInt32, + opaqueData: [UInt8]?, + file: StaticString = #filePath, + line: UInt = #line + ) { XCTAssertEqual(self.streamID, .rootStream, "Goaway frame must be on the root stream!", file: (file), line: line) - self.payload.assertGoAwayFramePayload(lastStreamID: lastStreamID, errorCode: errorCode, opaqueData: opaqueData, file: (file), line: line) + self.payload.assertGoAwayFramePayload( + lastStreamID: lastStreamID, + errorCode: errorCode, + opaqueData: opaqueData, + file: (file), + line: line + ) } func assertPingFrameMatches(this frame: HTTP2Frame, file: StaticString = #filePath, line: UInt = #line) { @@ -441,69 +579,178 @@ extension HTTP2Frame { self.payload.assertWindowUpdateFramePayloadMatches(this: frame.payload, file: (file), line: line) } - func assertWindowUpdateFrame(streamID: HTTP2StreamID, windowIncrement: Int, file: StaticString = #filePath, line: UInt = #line) { + func assertWindowUpdateFrame( + streamID: HTTP2StreamID, + windowIncrement: Int, + file: StaticString = #filePath, + line: UInt = #line + ) { XCTAssertEqual(self.streamID, streamID, "Unexpected stream ID!", file: (file), line: line) self.payload.assertWindowUpdateFramePayload(windowIncrement: windowIncrement, file: (file), line: line) } func assertRstStreamFrameMatches(this frame: HTTP2Frame, file: StaticString = #filePath, line: UInt = #line) { - XCTAssertEqual(self.streamID, frame.streamID, "Non matching stream IDs: expected \(streamID), got \(self.streamID)!", file: (file), line: line) + XCTAssertEqual( + self.streamID, + frame.streamID, + "Non matching stream IDs: expected \(streamID), got \(self.streamID)!", + file: (file), + line: line + ) self.payload.assertRstStreamFramePayloadMatches(this: frame.payload, file: (file), line: line) } - func assertRstStreamFrame(streamID: HTTP2StreamID, errorCode: HTTP2ErrorCode, file: StaticString = #filePath, line: UInt = #line) { - XCTAssertEqual(self.streamID, streamID, "Non matching stream IDs: expected \(streamID), got \(self.streamID)!", file: (file), line: line) + func assertRstStreamFrame( + streamID: HTTP2StreamID, + errorCode: HTTP2ErrorCode, + file: StaticString = #filePath, + line: UInt = #line + ) { + XCTAssertEqual( + self.streamID, + streamID, + "Non matching stream IDs: expected \(streamID), got \(self.streamID)!", + file: (file), + line: line + ) self.payload.assertRstStreamFramePayload(errorCode: errorCode, file: (file), line: line) } func assertPriorityFrameMatches(this frame: HTTP2Frame, file: StaticString = #filePath, line: UInt = #line) { - XCTAssertEqual(self.streamID, frame.streamID, "Non matching stream IDs: expected \(streamID), got \(self.streamID)!", file: (file), line: line) + XCTAssertEqual( + self.streamID, + frame.streamID, + "Non matching stream IDs: expected \(streamID), got \(self.streamID)!", + file: (file), + line: line + ) self.payload.assertPriorityFramePayloadMatches(this: frame.payload, file: (file), line: line) } - func assertPriorityFrame(streamPriorityData: HTTP2Frame.StreamPriorityData, file: StaticString = #filePath, line: UInt = #line) { - XCTAssertEqual(self.streamID, streamID, "Non matching stream IDs: expected \(streamID), got \(self.streamID)!", file: (file), line: line) + func assertPriorityFrame( + streamPriorityData: HTTP2Frame.StreamPriorityData, + file: StaticString = #filePath, + line: UInt = #line + ) { + XCTAssertEqual( + self.streamID, + streamID, + "Non matching stream IDs: expected \(streamID), got \(self.streamID)!", + file: (file), + line: line + ) self.payload.assertPriorityFramePayload(streamPriorityData: streamPriorityData, file: (file), line: line) } func assertPushPromiseFrameMatches(this frame: HTTP2Frame, file: StaticString = #filePath, line: UInt = #line) { - XCTAssertEqual(self.streamID, frame.streamID, "Non matching stream IDs: expected \(streamID), got \(self.streamID)!", file: (file), line: line) + XCTAssertEqual( + self.streamID, + frame.streamID, + "Non matching stream IDs: expected \(streamID), got \(self.streamID)!", + file: (file), + line: line + ) self.payload.assertPushPromiseFramePayloadMatches(this: frame.payload, file: (file), line: line) } - func assertPushPromiseFrame(streamID: HTTP2StreamID, pushedStreamID: HTTP2StreamID, headers: HPACKHeaders, file: StaticString = #filePath, line: UInt = #line) { - XCTAssertEqual(self.streamID, streamID, "Non matching stream IDs: expected \(streamID), got \(self.streamID)!", file: (file), line: line) - self.payload.assertPushPromiseFramePayload(pushedStreamID: pushedStreamID, headers: headers, file: (file), line: line) + func assertPushPromiseFrame( + streamID: HTTP2StreamID, + pushedStreamID: HTTP2StreamID, + headers: HPACKHeaders, + file: StaticString = #filePath, + line: UInt = #line + ) { + XCTAssertEqual( + self.streamID, + streamID, + "Non matching stream IDs: expected \(streamID), got \(self.streamID)!", + file: (file), + line: line + ) + self.payload.assertPushPromiseFramePayload( + pushedStreamID: pushedStreamID, + headers: headers, + file: (file), + line: line + ) } - func assertAlternativeServiceFrameMatches(this frame: HTTP2Frame, file: StaticString = #filePath, line: UInt = #line) { - XCTAssertEqual(.rootStream, self.streamID, "ALTSVC frame must be on the root stream!, got \(self.streamID)!", file: (file), line: line) + func assertAlternativeServiceFrameMatches( + this frame: HTTP2Frame, + file: StaticString = #filePath, + line: UInt = #line + ) { + XCTAssertEqual( + .rootStream, + self.streamID, + "ALTSVC frame must be on the root stream!, got \(self.streamID)!", + file: (file), + line: line + ) self.payload.assertAlternativeServiceFramePayloadMatches(this: frame.payload, file: (file), line: line) } - func assertAlternativeServiceFrame(origin: String?, field: ByteBuffer?, file: StaticString = #filePath, line: UInt = #line) { - XCTAssertEqual(.rootStream, self.streamID, "ALTSVC frame must be on the root stream!, got \(self.streamID)!", file: (file), line: line) + func assertAlternativeServiceFrame( + origin: String?, + field: ByteBuffer?, + file: StaticString = #filePath, + line: UInt = #line + ) { + XCTAssertEqual( + .rootStream, + self.streamID, + "ALTSVC frame must be on the root stream!, got \(self.streamID)!", + file: (file), + line: line + ) self.payload.assertAlternativeServiceFramePayload(origin: origin, field: field, file: (file), line: line) } func assertOriginFrameMatches(this frame: HTTP2Frame, file: StaticString = #filePath, line: UInt = #line) { - XCTAssertEqual(.rootStream, self.streamID, "ORIGIN frame must be on the root stream!, got \(self.streamID)!", file: (file), line: line) + XCTAssertEqual( + .rootStream, + self.streamID, + "ORIGIN frame must be on the root stream!, got \(self.streamID)!", + file: (file), + line: line + ) self.payload.assertOriginFramePayloadMatches(this: frame.payload, file: (file), line: line) } - func assertOriginFrame(streamID: HTTP2StreamID, origins: [String], file: StaticString = #filePath, line: UInt = #line) { - XCTAssertEqual(.rootStream, self.streamID, "ORIGIN frame must be on the root stream!, got \(self.streamID)!", file: (file), line: line) + func assertOriginFrame( + streamID: HTTP2StreamID, + origins: [String], + file: StaticString = #filePath, + line: UInt = #line + ) { + XCTAssertEqual( + .rootStream, + self.streamID, + "ORIGIN frame must be on the root stream!, got \(self.streamID)!", + file: (file), + line: line + ) self.payload.assertOriginFramePayload(origins: origins, file: (file), line: line) } } extension HTTP2Frame.FramePayload { - func assertFramePayloadMatches(this payload: HTTP2Frame.FramePayload, dataFileRegionToByteBuffer: Bool = true, file: StaticString = #filePath, line: UInt = #line) { + func assertFramePayloadMatches( + this payload: HTTP2Frame.FramePayload, + dataFileRegionToByteBuffer: Bool = true, + file: StaticString = #filePath, + line: UInt = #line + ) { switch self { case .headers: self.assertHeadersFramePayloadMatches(this: payload, file: (file), line: line) case .data: - self.assertDataFramePayloadMatches(this: payload, fileRegionToByteBuffer: dataFileRegionToByteBuffer, file: (file), line: line) + self.assertDataFramePayloadMatches( + this: payload, + fileRegionToByteBuffer: dataFileRegionToByteBuffer, + file: (file), + line: line + ) case .goAway: self.assertGoAwayFramePayloadMatches(this: payload, file: (file), line: line) case .ping: @@ -526,56 +773,103 @@ extension HTTP2Frame.FramePayload { } /// Asserts that a given frame is a HEADERS frame matching this one. - func assertHeadersFramePayloadMatches(this payload: HTTP2Frame.FramePayload, file: StaticString = #filePath, line: UInt = #line) { + func assertHeadersFramePayloadMatches( + this payload: HTTP2Frame.FramePayload, + file: StaticString = #filePath, + line: UInt = #line + ) { guard case .headers(let payload) = self else { preconditionFailure("Headers frames can never match non-headers frames") } - self.assertHeadersFramePayload(endStream: payload.endStream, - headers: payload.headers, - priority: payload.priorityData, - file: file, - line: line) + self.assertHeadersFramePayload( + endStream: payload.endStream, + headers: payload.headers, + priority: payload.priorityData, + file: file, + line: line + ) } - func assertHeadersFramePayload(endStream: Bool, headers: HPACKHeaders, - priority: HTTP2Frame.StreamPriorityData? = nil, - type: HTTP2Frame.HeadersType? = nil, - file: StaticString = #filePath, line: UInt = #line) { + func assertHeadersFramePayload( + endStream: Bool, + headers: HPACKHeaders, + priority: HTTP2Frame.StreamPriorityData? = nil, + type: HTTP2Frame.HeadersType? = nil, + file: StaticString = #filePath, + line: UInt = #line + ) { guard case .headers(let actualPayload) = self else { XCTFail("Expected HEADERS payload, got \(self) instead", file: (file), line: line) return } - XCTAssertEqual(actualPayload.endStream, endStream, - "Unexpected endStream: expected \(endStream), got \(actualPayload.endStream)", file: (file), line: line) - XCTAssertEqual(headers, actualPayload.headers, "Non-equal headers: expected \(headers), got \(actualPayload.headers)", file: (file), line: line) - XCTAssertEqual(priority, actualPayload.priorityData, "Non-equal priorities: expected \(String(describing: priority)), got \(String(describing: actualPayload.priorityData))", file: (file), line: line) + XCTAssertEqual( + actualPayload.endStream, + endStream, + "Unexpected endStream: expected \(endStream), got \(actualPayload.endStream)", + file: (file), + line: line + ) + XCTAssertEqual( + headers, + actualPayload.headers, + "Non-equal headers: expected \(headers), got \(actualPayload.headers)", + file: (file), + line: line + ) + XCTAssertEqual( + priority, + actualPayload.priorityData, + "Non-equal priorities: expected \(String(describing: priority)), got \(String(describing: actualPayload.priorityData))", + file: (file), + line: line + ) switch type { case .some(.request): - XCTAssertNoThrow(try actualPayload.headers.validateRequestBlock(supportsExtendedConnect: true), - "\(actualPayload.headers) not a valid \(type!) headers block", file: (file), line: line) + XCTAssertNoThrow( + try actualPayload.headers.validateRequestBlock(supportsExtendedConnect: true), + "\(actualPayload.headers) not a valid \(type!) headers block", + file: (file), + line: line + ) case .some(.response): - XCTAssertNoThrow(try actualPayload.headers.validateResponseBlock(), - "\(actualPayload.headers) not a valid \(type!) headers block", file: (file), line: line) + XCTAssertNoThrow( + try actualPayload.headers.validateResponseBlock(), + "\(actualPayload.headers) not a valid \(type!) headers block", + file: (file), + line: line + ) case .some(.trailers): - XCTAssertNoThrow(try actualPayload.headers.validateTrailersBlock(), - "\(actualPayload.headers) not a valid \(type!) headers block", file: (file), line: line) + XCTAssertNoThrow( + try actualPayload.headers.validateTrailersBlock(), + "\(actualPayload.headers) not a valid \(type!) headers block", + file: (file), + line: line + ) case .some(.doNotValidate): - () // alright, let's not validate then + () // alright, let's not validate then case .none: - XCTAssertTrue((try? actualPayload.headers.validateRequestBlock(supportsExtendedConnect: true)) != nil || - (try? actualPayload.headers.validateResponseBlock()) != nil || - (try? actualPayload.headers.validateTrailersBlock()) != nil, - "\(actualPayload.headers) not a valid request/response/trailers header block", - file: (file), line: line) + XCTAssertTrue( + (try? actualPayload.headers.validateRequestBlock(supportsExtendedConnect: true)) != nil + || (try? actualPayload.headers.validateResponseBlock()) != nil + || (try? actualPayload.headers.validateTrailersBlock()) != nil, + "\(actualPayload.headers) not a valid request/response/trailers header block", + file: (file), + line: line + ) } } /// Asserts that a given frame is a DATA frame matching this one. /// /// This function always converts the DATA frame to a bytebuffer, for use with round-trip testing. - func assertDataFramePayloadMatches(this payload: HTTP2Frame.FramePayload, fileRegionToByteBuffer: Bool = true, file: StaticString = #filePath, line: UInt = #line) { + func assertDataFramePayloadMatches( + this payload: HTTP2Frame.FramePayload, + fileRegionToByteBuffer: Bool = true, + file: StaticString = #filePath, + line: UInt = #line + ) { guard case .data(let actualPayload) = payload else { XCTFail("Expected DATA frame, got \(self) instead", file: (file), line: line) return @@ -583,26 +877,37 @@ extension HTTP2Frame.FramePayload { switch (actualPayload.data, fileRegionToByteBuffer) { case (.byteBuffer(let bufferPayload), _): - self.assertDataFramePayload(endStream: actualPayload.endStream, - payload: bufferPayload, - file: (file), - line: line) + self.assertDataFramePayload( + endStream: actualPayload.endStream, + payload: bufferPayload, + file: (file), + line: line + ) case (.fileRegion(let filePayload), true): // Sorry about creating an allocator from thin air here! let expectedPayload = filePayload.asByteBuffer(allocator: ByteBufferAllocator()) - self.assertDataFramePayload(endStream: actualPayload.endStream, - payload: expectedPayload, - file: (file), - line: line) + self.assertDataFramePayload( + endStream: actualPayload.endStream, + payload: expectedPayload, + file: (file), + line: line + ) case (.fileRegion(let filePayload), false): - self.assertDataFramePayload(endStream: actualPayload.endStream, - payload: filePayload, - file: (file), - line: line) + self.assertDataFramePayload( + endStream: actualPayload.endStream, + payload: filePayload, + file: (file), + line: line + ) } } - func assertDataFramePayload(endStream: Bool, payload: ByteBuffer, file: StaticString = #filePath, line: UInt = #line) { + func assertDataFramePayload( + endStream: Bool, + payload: ByteBuffer, + file: StaticString = #filePath, + line: UInt = #line + ) { guard case .data(let actualFrameBody) = self else { XCTFail("Expected DATA payload, got \(self) instead", file: (file), line: line) return @@ -613,13 +918,28 @@ extension HTTP2Frame.FramePayload { return } - XCTAssertEqual(actualFrameBody.endStream, endStream, - "Unexpected endStream: expected \(endStream), got \(actualFrameBody.endStream)", file: (file), line: line) - XCTAssertEqual(actualPayload, payload, - "Unexpected body: expected \(payload), got \(actualPayload)", file: (file), line: line) + XCTAssertEqual( + actualFrameBody.endStream, + endStream, + "Unexpected endStream: expected \(endStream), got \(actualFrameBody.endStream)", + file: (file), + line: line + ) + XCTAssertEqual( + actualPayload, + payload, + "Unexpected body: expected \(payload), got \(actualPayload)", + file: (file), + line: line + ) } - func assertDataFramePayload(endStream: Bool, payload: FileRegion, file: StaticString = #filePath, line: UInt = #line) { + func assertDataFramePayload( + endStream: Bool, + payload: FileRegion, + file: StaticString = #filePath, + line: UInt = #line + ) { guard case .data(let actualFrameBody) = self else { XCTFail("Expected DATA frame, got \(self) instead", file: (file), line: line) return @@ -630,25 +950,47 @@ extension HTTP2Frame.FramePayload { return } - XCTAssertEqual(actualFrameBody.endStream, endStream, - "Unexpected endStream: expected \(endStream), got \(actualFrameBody.endStream)", file: (file), line: line) - XCTAssertEqual(actualPayload, payload, - "Unexpected body: expected \(payload), got \(actualPayload)", file: (file), line: line) + XCTAssertEqual( + actualFrameBody.endStream, + endStream, + "Unexpected endStream: expected \(endStream), got \(actualFrameBody.endStream)", + file: (file), + line: line + ) + XCTAssertEqual( + actualPayload, + payload, + "Unexpected body: expected \(payload), got \(actualPayload)", + file: (file), + line: line + ) } - func assertGoAwayFramePayloadMatches(this payload: HTTP2Frame.FramePayload, file: StaticString = #filePath, line: UInt = #line) { + func assertGoAwayFramePayloadMatches( + this payload: HTTP2Frame.FramePayload, + file: StaticString = #filePath, + line: UInt = #line + ) { guard case .goAway(let lastStreamID, let errorCode, let opaqueData) = payload else { preconditionFailure("Goaway frames can never match non-Goaway frames.") } - self.assertGoAwayFramePayload(lastStreamID: lastStreamID, - errorCode: UInt32(http2ErrorCode: errorCode), - opaqueData: opaqueData.flatMap { $0.getBytes(at: $0.readerIndex, length: $0.readableBytes) }, - file: (file), - line: line) + self.assertGoAwayFramePayload( + lastStreamID: lastStreamID, + errorCode: UInt32(http2ErrorCode: errorCode), + opaqueData: opaqueData.flatMap { $0.getBytes(at: $0.readerIndex, length: $0.readableBytes) }, + file: (file), + line: line + ) } - func assertGoAwayFramePayload(lastStreamID: HTTP2StreamID, errorCode: UInt32, opaqueData: [UInt8]?, file: StaticString = #filePath, line: UInt = #line) { + func assertGoAwayFramePayload( + lastStreamID: HTTP2StreamID, + errorCode: UInt32, + opaqueData: [UInt8]?, + file: StaticString = #filePath, + line: UInt = #line + ) { guard case .goAway(let actualLastStreamID, let actualErrorCode, let actualOpaqueData) = self else { XCTFail("Expected GOAWAY frame, got \(self) instead", file: (file), line: line) return @@ -657,34 +999,68 @@ extension HTTP2Frame.FramePayload { let integerErrorCode = UInt32(http2ErrorCode: actualErrorCode) let byteArrayOpaqueData = actualOpaqueData.flatMap { $0.getBytes(at: $0.readerIndex, length: $0.readableBytes) } - XCTAssertEqual(lastStreamID, actualLastStreamID, - "Unexpected last stream ID: expected \(lastStreamID), got \(actualLastStreamID)", file: (file), line: line) - XCTAssertEqual(integerErrorCode, errorCode, - "Unexpected error code: expected \(errorCode), got \(integerErrorCode)", file: (file), line: line) - XCTAssertEqual(byteArrayOpaqueData, opaqueData, - "Unexpected opaque data: expected \(String(describing: opaqueData)), got \(String(describing: byteArrayOpaqueData))", file: (file), line: line) + XCTAssertEqual( + lastStreamID, + actualLastStreamID, + "Unexpected last stream ID: expected \(lastStreamID), got \(actualLastStreamID)", + file: (file), + line: line + ) + XCTAssertEqual( + integerErrorCode, + errorCode, + "Unexpected error code: expected \(errorCode), got \(integerErrorCode)", + file: (file), + line: line + ) + XCTAssertEqual( + byteArrayOpaqueData, + opaqueData, + "Unexpected opaque data: expected \(String(describing: opaqueData)), got \(String(describing: byteArrayOpaqueData))", + file: (file), + line: line + ) } - func assertPingFramePayloadMatches(this payload: HTTP2Frame.FramePayload, file: StaticString = #filePath, line: UInt = #line) { + func assertPingFramePayloadMatches( + this payload: HTTP2Frame.FramePayload, + file: StaticString = #filePath, + line: UInt = #line + ) { guard case .ping(let opaqueData, let ack) = payload else { preconditionFailure("Ping frames can never match non-Ping frames.") } self.assertPingFramePayload(ack: ack, opaqueData: opaqueData, file: (file), line: line) } - func assertPingFramePayload(ack: Bool, opaqueData: HTTP2PingData, file: StaticString = #filePath, line: UInt = #line) { + func assertPingFramePayload( + ack: Bool, + opaqueData: HTTP2PingData, + file: StaticString = #filePath, + line: UInt = #line + ) { guard case .ping(let actualPingData, let actualAck) = self else { XCTFail("Expected PING frame, got \(self) instead", file: (file), line: line) return } XCTAssertEqual(actualAck, ack, "Non-matching ACK: expected \(ack), got \(actualAck)", file: (file), line: line) - XCTAssertEqual(actualPingData, opaqueData, "Non-matching ping data: expected \(opaqueData), got \(actualPingData)", - file: (file), line: line) + XCTAssertEqual( + actualPingData, + opaqueData, + "Non-matching ping data: expected \(opaqueData), got \(actualPingData)", + file: (file), + line: line + ) } /// Asserts that the given frame is a SETTINGS frame. - func assertSettingsFramePayload(expectedSettings: [HTTP2Setting], ack: Bool, file: StaticString = #filePath, line: UInt = #line) { + func assertSettingsFramePayload( + expectedSettings: [HTTP2Setting], + ack: Bool, + file: StaticString = #filePath, + line: UInt = #line + ) { guard case .settings(let payload) = self else { XCTFail("Expected SETTINGS frame, got \(self) instead", file: (file), line: line) return @@ -692,15 +1068,31 @@ extension HTTP2Frame.FramePayload { switch payload { case .ack: - XCTAssertEqual(expectedSettings, [], "Got unexpected settings: expected \(expectedSettings), got []", file: (file), line: line) + XCTAssertEqual( + expectedSettings, + [], + "Got unexpected settings: expected \(expectedSettings), got []", + file: (file), + line: line + ) XCTAssertTrue(ack, "Got unexpected value for ack: expected \(ack), got true", file: (file), line: line) case .settings(let actualSettings): - XCTAssertEqual(expectedSettings, actualSettings, "Got unexpected settings: expected \(expectedSettings), got \(actualSettings)", file: (file), line: line) + XCTAssertEqual( + expectedSettings, + actualSettings, + "Got unexpected settings: expected \(expectedSettings), got \(actualSettings)", + file: (file), + line: line + ) XCTAssertFalse(false, "Got unexpected value for ack: expected \(ack), got false", file: (file), line: line) } } - func assertSettingsFramePayloadMatches(this framePayload: HTTP2Frame.FramePayload, file: StaticString = #filePath, line: UInt = #line) { + func assertSettingsFramePayloadMatches( + this framePayload: HTTP2Frame.FramePayload, + file: StaticString = #filePath, + line: UInt = #line + ) { guard case .settings(let payload) = framePayload else { preconditionFailure("Settings frames can never match non-settings frames") } @@ -713,7 +1105,11 @@ extension HTTP2Frame.FramePayload { } } - func assertWindowUpdateFramePayloadMatches(this payload: HTTP2Frame.FramePayload, file: StaticString = #filePath, line: UInt = #line) { + func assertWindowUpdateFramePayloadMatches( + this payload: HTTP2Frame.FramePayload, + file: StaticString = #filePath, + line: UInt = #line + ) { guard case .windowUpdate(let increment) = payload else { XCTFail("WINDOW_UPDATE frames can never match non-WINDOW_UPDATE frames", file: (file), line: line) return @@ -730,7 +1126,11 @@ extension HTTP2Frame.FramePayload { XCTAssertEqual(windowIncrement, actualWindowIncrement, "Unexpected window increment!", file: (file), line: line) } - func assertRstStreamFramePayloadMatches(this payload: HTTP2Frame.FramePayload, file: StaticString = #filePath, line: UInt = #line) { + func assertRstStreamFramePayloadMatches( + this payload: HTTP2Frame.FramePayload, + file: StaticString = #filePath, + line: UInt = #line + ) { guard case .rstStream(let errorCode) = payload else { preconditionFailure("RstStream frames can never match non-RstStream frames.") } @@ -743,17 +1143,31 @@ extension HTTP2Frame.FramePayload { return } - XCTAssertEqual(actualErrorCode, errorCode, "Non-matching error-code: expected \(errorCode), got \(actualErrorCode)", file: (file), line: line) + XCTAssertEqual( + actualErrorCode, + errorCode, + "Non-matching error-code: expected \(errorCode), got \(actualErrorCode)", + file: (file), + line: line + ) } - func assertPriorityFramePayloadMatches(this payload: HTTP2Frame.FramePayload, file: StaticString = #filePath, line: UInt = #line) { + func assertPriorityFramePayloadMatches( + this payload: HTTP2Frame.FramePayload, + file: StaticString = #filePath, + line: UInt = #line + ) { guard case .priority(let expectedPriorityData) = payload else { preconditionFailure("Priority frames can never match non-Priority frames.") } self.assertPriorityFramePayload(streamPriorityData: expectedPriorityData, file: (file), line: line) } - func assertPriorityFramePayload(streamPriorityData: HTTP2Frame.StreamPriorityData, file: StaticString = #filePath, line: UInt = #line) { + func assertPriorityFramePayload( + streamPriorityData: HTTP2Frame.StreamPriorityData, + file: StaticString = #filePath, + line: UInt = #line + ) { guard case .priority(let actualPriorityData) = self else { XCTFail("Expected PRIORITY frame, got \(self) instead", file: (file), line: line) return @@ -762,47 +1176,92 @@ extension HTTP2Frame.FramePayload { XCTAssertEqual(streamPriorityData, actualPriorityData, file: (file), line: line) } - func assertPushPromiseFramePayloadMatches(this payload: HTTP2Frame.FramePayload, file: StaticString = #filePath, line: UInt = #line) { + func assertPushPromiseFramePayloadMatches( + this payload: HTTP2Frame.FramePayload, + file: StaticString = #filePath, + line: UInt = #line + ) { guard case .pushPromise(let payload) = payload else { preconditionFailure("PushPromise frames can never match non-PushPromise frames.") } - self.assertPushPromiseFramePayload(pushedStreamID: payload.pushedStreamID, headers: payload.headers, file: (file), line: line) + self.assertPushPromiseFramePayload( + pushedStreamID: payload.pushedStreamID, + headers: payload.headers, + file: (file), + line: line + ) } - func assertPushPromiseFramePayload(pushedStreamID: HTTP2StreamID, headers: HPACKHeaders, file: StaticString = #filePath, line: UInt = #line) { + func assertPushPromiseFramePayload( + pushedStreamID: HTTP2StreamID, + headers: HPACKHeaders, + file: StaticString = #filePath, + line: UInt = #line + ) { guard case .pushPromise(let actualPayload) = self else { XCTFail("Expected PUSH_PROMISE frame, got \(self) instead", file: (file), line: line) return } - XCTAssertEqual(pushedStreamID, actualPayload.pushedStreamID, "Non matching pushed stream IDs: expected \(pushedStreamID), got \(actualPayload.pushedStreamID)", file: (file), line: line) - XCTAssertEqual(headers, actualPayload.headers, "Non matching pushed headers: expected \(headers), got \(actualPayload.headers)", file: (file), line: line) + XCTAssertEqual( + pushedStreamID, + actualPayload.pushedStreamID, + "Non matching pushed stream IDs: expected \(pushedStreamID), got \(actualPayload.pushedStreamID)", + file: (file), + line: line + ) + XCTAssertEqual( + headers, + actualPayload.headers, + "Non matching pushed headers: expected \(headers), got \(actualPayload.headers)", + file: (file), + line: line + ) } - func assertAlternativeServiceFramePayloadMatches(this payload: HTTP2Frame.FramePayload, file: StaticString = #filePath, line: UInt = #line) { + func assertAlternativeServiceFramePayloadMatches( + this payload: HTTP2Frame.FramePayload, + file: StaticString = #filePath, + line: UInt = #line + ) { guard case .alternativeService(let origin, let field) = payload else { preconditionFailure("AltSvc frames can never match non-AltSvc frames.") } self.assertAlternativeServiceFramePayload(origin: origin, field: field, file: (file), line: line) } - func assertAlternativeServiceFramePayload(origin: String?, field: ByteBuffer?, file: StaticString = #filePath, line: UInt = #line) { + func assertAlternativeServiceFramePayload( + origin: String?, + field: ByteBuffer?, + file: StaticString = #filePath, + line: UInt = #line + ) { guard case .alternativeService(let actualOrigin, let actualField) = self else { XCTFail("Expected ALTSVC frame, got \(self) instead", file: (file), line: line) return } - XCTAssertEqual(origin, - actualOrigin, - "Non matching origins: expected \(String(describing: origin)), got \(String(describing: actualOrigin))", - file: (file), line: line) - XCTAssertEqual(field, - actualField, - "Non matching field: expected \(String(describing: field)), got \(String(describing: actualField))", - file: (file), line: line) + XCTAssertEqual( + origin, + actualOrigin, + "Non matching origins: expected \(String(describing: origin)), got \(String(describing: actualOrigin))", + file: (file), + line: line + ) + XCTAssertEqual( + field, + actualField, + "Non matching field: expected \(String(describing: field)), got \(String(describing: actualField))", + file: (file), + line: line + ) } - func assertOriginFramePayloadMatches(this payload: HTTP2Frame.FramePayload, file: StaticString = #filePath, line: UInt = #line) { + func assertOriginFramePayloadMatches( + this payload: HTTP2Frame.FramePayload, + file: StaticString = #filePath, + line: UInt = #line + ) { guard case .origin(let origins) = payload else { preconditionFailure("ORIGIN frames can never match non-ORIGIN frames.") } @@ -815,32 +1274,66 @@ extension HTTP2Frame.FramePayload { return } - XCTAssertEqual(origins, actualPayload, "Non matching origins: expected \(origins), got \(actualPayload)", file: (file), line: line) + XCTAssertEqual( + origins, + actualPayload, + "Non matching origins: expected \(origins), got \(actualPayload)", + file: (file), + line: line + ) } } extension Array where Element == HTTP2Frame { - func assertFramesMatch(_ target: Candidate, dataFileRegionToByteBuffer: Bool = true, file: StaticString = #filePath, line: UInt = #line) where Candidate.Element == HTTP2Frame { + func assertFramesMatch( + _ target: Candidate, + dataFileRegionToByteBuffer: Bool = true, + file: StaticString = #filePath, + line: UInt = #line + ) where Candidate.Element == HTTP2Frame { guard self.count == target.count else { - XCTFail("Different numbers of frames: expected \(target.count), got \(self.count)", file: (file), line: line) + XCTFail( + "Different numbers of frames: expected \(target.count), got \(self.count)", + file: (file), + line: line + ) return } for (expected, actual) in zip(target, self) { - expected.assertFrameMatches(this: actual, dataFileRegionToByteBuffer: dataFileRegionToByteBuffer, file: (file), line: line) + expected.assertFrameMatches( + this: actual, + dataFileRegionToByteBuffer: dataFileRegionToByteBuffer, + file: (file), + line: line + ) } } } extension Array where Element == HTTP2Frame.FramePayload { - func assertFramePayloadsMatch(_ target: Candidate, dataFileRegionToByteBuffer: Bool = true, file: StaticString = #filePath, line: UInt = #line) where Candidate.Element == HTTP2Frame.FramePayload { + func assertFramePayloadsMatch( + _ target: Candidate, + dataFileRegionToByteBuffer: Bool = true, + file: StaticString = #filePath, + line: UInt = #line + ) where Candidate.Element == HTTP2Frame.FramePayload { guard self.count == target.count else { - XCTFail("Different numbers of frame payloads: expected \(target.count), got \(self.count)", file: (file), line: line) + XCTFail( + "Different numbers of frame payloads: expected \(target.count), got \(self.count)", + file: (file), + line: line + ) return } for (expected, actual) in zip(target, self) { - expected.assertFramePayloadMatches(this: actual, dataFileRegionToByteBuffer: dataFileRegionToByteBuffer, file: (file), line: line) + expected.assertFramePayloadMatches( + this: actual, + dataFileRegionToByteBuffer: dataFileRegionToByteBuffer, + file: (file), + line: line + ) } } } @@ -877,8 +1370,9 @@ func openTemporaryFile() -> (CInt, String) { var templateBytes = template.utf8 + [0] let templateBytesCount = templateBytes.count let fd = templateBytes.withUnsafeMutableBufferPointer { ptr in - ptr.baseAddress!.withMemoryRebound(to: Int8.self, capacity: templateBytesCount) { (ptr: UnsafeMutablePointer) in - return mkstemp(ptr) + ptr.baseAddress!.withMemoryRebound(to: Int8.self, capacity: templateBytesCount) { + (ptr: UnsafeMutablePointer) in + mkstemp(ptr) } } templateBytes.removeLast() @@ -1009,4 +1503,3 @@ internal func assertThrowsError( verify(error) } } -