diff --git a/Sources/NIOHTTP1/HTTPEncoder.swift b/Sources/NIOHTTP1/HTTPEncoder.swift index da3fa33a6..c79283ef8 100644 --- a/Sources/NIOHTTP1/HTTPEncoder.swift +++ b/Sources/NIOHTTP1/HTTPEncoder.swift @@ -15,26 +15,24 @@ import NIOCore private func writeChunk(wrapOutboundOut: (IOData) -> NIOAny, context: ChannelHandlerContext, isChunked: Bool, chunk: IOData, promise: EventLoopPromise?) { - let (mW1, mW2, mW3): (EventLoopPromise?, EventLoopPromise?, EventLoopPromise?) - - switch (isChunked, promise) { - case (true, .some(let p)): - /* chunked encoding and the user's interested: we need three promises and need to cascade into the users promise */ - let (w1, w2, w3) = (context.eventLoop.makePromise() as EventLoopPromise, context.eventLoop.makePromise() as EventLoopPromise, context.eventLoop.makePromise() as EventLoopPromise) - w1.futureResult.and(w2.futureResult).and(w3.futureResult).map { (_: ((((), ()), ()))) in }.cascade(to: p) - (mW1, mW2, mW3) = (w1, w2, w3) - case (false, .some(let p)): - /* not chunked, so just use the user's promise for the actual data */ - (mW1, mW2, mW3) = (nil, p, nil) - case (_, .none): - /* user isn't interested, let's not bother even allocating promises */ - (mW1, mW2, mW3) = (nil, nil, nil) - } - let readableBytes = chunk.readableBytes - /* we don't want to copy the chunk unnecessarily and therefore call write an annoyingly large number of times */ - if isChunked { + // we don't want to copy the chunk unnecessarily and therefore call write an annoyingly large number of times + // we also don't frame empty chunks as they would otherwise end the response stream + // we still need to write the empty IODate to complete the promise in the right order but is otherwise a no-op. + if isChunked && readableBytes > 0 { + let (mW1, mW2, mW3): (EventLoopPromise?, EventLoopPromise?, EventLoopPromise?) + + if let p = promise { + /* chunked encoding and the user's interested: we need three promises and need to cascade into the users promise */ + let (w1, w2, w3) = (context.eventLoop.makePromise() as EventLoopPromise, context.eventLoop.makePromise() as EventLoopPromise, context.eventLoop.makePromise() as EventLoopPromise) + w1.futureResult.and(w2.futureResult).and(w3.futureResult).map { (_: ((((), ()), ()))) in }.cascade(to: p) + (mW1, mW2, mW3) = (w1, w2, w3) + } else { + /* user isn't interested, let's not bother even allocating promises */ + (mW1, mW2, mW3) = (nil, nil, nil) + } + var buffer = context.channel.allocator.buffer(capacity: 32) let len = String(readableBytes, radix: 16) buffer.writeString(len) @@ -47,7 +45,7 @@ private func writeChunk(wrapOutboundOut: (IOData) -> NIOAny, context: ChannelHan buffer.moveReaderIndex(forwardBy: buffer.readableBytes - 2) context.write(wrapOutboundOut(.byteBuffer(buffer)), promise: mW3) } else { - context.write(wrapOutboundOut(chunk), promise: mW2) + context.write(wrapOutboundOut(chunk), promise: promise) } } @@ -195,12 +193,6 @@ public final class HTTPRequestEncoder: ChannelOutboundHandler, RemovableChannelH buffer.write(request: request) }, context: context, headers: request.headers, promise: promise) case .body(let bodyPart): - guard bodyPart.readableBytes > 0 else { - // Empty writes shouldn't send any bytes in chunked or identity encoding. - context.write(self.wrapOutboundOut(bodyPart), promise: promise) - return - } - writeChunk(wrapOutboundOut: self.wrapOutboundOut, context: context, isChunked: self.isChunked, chunk: bodyPart, promise: promise) case .end(let trailers): writeTrailers(wrapOutboundOut: self.wrapOutboundOut, context: context, isChunked: self.isChunked, trailers: trailers, promise: promise) diff --git a/Tests/NIOHTTP1Tests/HTTPServerClientTest.swift b/Tests/NIOHTTP1Tests/HTTPServerClientTest.swift index c3ab6fbce..dc6b82fdf 100644 --- a/Tests/NIOHTTP1Tests/HTTPServerClientTest.swift +++ b/Tests/NIOHTTP1Tests/HTTPServerClientTest.swift @@ -251,6 +251,25 @@ class HTTPServerClientTest : XCTestCase { self.sentEnd = true self.maybeClose(context: context) } + case "/zero-length-body-part": + + let r = HTTPServerResponsePart.head(.init(version: req.version, status: .ok)) + context.write(self.wrapOutboundOut(r)).whenFailure { error in + XCTFail("unexpected error \(error)") + } + + context.writeAndFlush(self.wrapOutboundOut(.body(.byteBuffer(ByteBuffer())))).whenFailure { error in + XCTFail("unexpected error \(error)") + } + context.writeAndFlush(self.wrapOutboundOut(.body(.byteBuffer(ByteBuffer(string: "Hello World"))))).whenFailure { error in + XCTFail("unexpected error \(error)") + } + context.write(self.wrapOutboundOut(.end(nil))).recover { error in + XCTFail("unexpected error \(error)") + }.whenComplete { (_: Result) in + self.sentEnd = true + self.maybeClose(context: context) + } default: XCTFail("received request to unknown URI \(req.uri)") } @@ -437,6 +456,53 @@ class HTTPServerClientTest : XCTestCase { func testSimpleGetTrailersFileRegion() throws { try testSimpleGetTrailers(.fileRegion) } + + func testSimpleGetChunkedEncodingWithZeroLengthBodyPart() throws { + let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) + defer { + XCTAssertNoThrow(try group.syncShutdownGracefully()) + } + + var expectedHeaders = HTTPHeaders() + expectedHeaders.add(name: "transfer-encoding", value: "chunked") + + let accumulation = HTTPClientResponsePartAssertHandler(.http1_1, .ok, expectedHeaders, "Hello World") + + let httpHandler = SimpleHTTPServer(.byteBuffer) + let serverChannel = try assertNoThrowWithValue(ServerBootstrap(group: group) + .serverChannelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1) + + // Set the handlers that are appled to the accepted Channels + .childChannelInitializer { channel in + // Ensure we don't read faster then we can write by adding the BackPressureHandler into the pipeline. + channel.pipeline.configureHTTPServerPipeline(withPipeliningAssistance: true).flatMap { + channel.pipeline.addHandler(httpHandler) + } + }.bind(host: "127.0.0.1", port: 0).wait()) + + defer { + XCTAssertNoThrow(try serverChannel.syncCloseAcceptingAlreadyClosed()) + } + + let clientChannel = try assertNoThrowWithValue(ClientBootstrap(group: group) + .channelInitializer { channel in + channel.pipeline.addHTTPClientHandlers().flatMap { + channel.pipeline.addHandler(accumulation) + } + } + .connect(to: serverChannel.localAddress!) + .wait()) + + defer { + XCTAssertNoThrow(try clientChannel.syncCloseAcceptingAlreadyClosed()) + } + + var head = HTTPRequestHead(version: .http1_1, method: .GET, uri: "/zero-length-body-part") + head.headers.add(name: "Host", value: "apple.com") + clientChannel.write(NIOAny(HTTPClientRequestPart.head(head)), promise: nil) + try clientChannel.writeAndFlush(NIOAny(HTTPClientRequestPart.end(nil))).wait() + accumulation.syncWaitForCompletion() + } private func testSimpleGetTrailers(_ mode: SendMode) throws { let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)