Tolerate empty HTTP response body parts (#2531)

* Tolerate empty HTTP response body parts

### Motivation

Empty HTTP response body parts currently eagerly end a response. This is unexpected and against NIOs documented behaviour.

### Modification

- add test which send an empty response body part and would previously fail
- skip empty response body parts

### Result

Users can send empty body parts without ending the response.

* add comment explaining why we do it here instead of fixing it at the source

* move empty body part logic to `writeChunk`
This commit is contained in:
David Nadoba authored and GitHub committed 2023-10-04 06:42:26 -07:00
1 parent f114f99f20
commit d367dc0a87
2 files changed
+83 -25

No files matched your search

+17 -25
View File
@@ -15,26 +15,24 @@
import NIOCore
private func writeChunk(wrapOutboundOut: (IOData) -> NIOAny, context: ChannelHandlerContext, isChunked: Bool, chunk: IOData, promise: EventLoopPromise<Void>?) {
let (mW1, mW2, mW3): (EventLoopPromise<Void>?, EventLoopPromise<Void>?, EventLoopPromise<Void>?)
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<Void>, context.eventLoop.makePromise() as EventLoopPromise<Void>, context.eventLoop.makePromise() as EventLoopPromise<Void>)
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<Void>?, EventLoopPromise<Void>?, EventLoopPromise<Void>?)
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<Void>, context.eventLoop.makePromise() as EventLoopPromise<Void>, context.eventLoop.makePromise() as EventLoopPromise<Void>)
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)
@@ -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<Void, Error>) 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)