diff --git a/Sources/NIO/Codec.swift b/Sources/NIO/Codec.swift index 057285e26..e42257d7d 100644 --- a/Sources/NIO/Codec.swift +++ b/Sources/NIO/Codec.swift @@ -523,15 +523,13 @@ extension ByteToMessageHandler: ChannelInboundHandler { () // fair, all done already case .leftoversNeedProcessing: // seems like we received a `channelInactive` or `handlerRemoved` whilst we were processing a read - defer { - self.state = .done - } switch try self.decodeLoop(context: context, decodeMode: .last) { case .didProcess: () // expected and cool case .cannotProcessReentrantly: preconditionFailure("bug in NIO: non-reentrant decode loop couldn't run \(self), \(self.state)") } + self.state = .done } case .cannotProcessReentrantly: // fine, will be done later diff --git a/Tests/NIOTests/CodecTest+XCTest.swift b/Tests/NIOTests/CodecTest+XCTest.swift index 408d9a831..d671d7eef 100644 --- a/Tests/NIOTests/CodecTest+XCTest.swift +++ b/Tests/NIOTests/CodecTest+XCTest.swift @@ -54,6 +54,7 @@ extension ByteToMessageDecoderTest { ("testDecodeLoopStopsOnChannelInactive", testDecodeLoopStopsOnChannelInactive), ("testDecodeLoopStopsOnInboundHalfClosure", testDecodeLoopStopsOnInboundHalfClosure), ("testWeForwardReadEOFAndChannelInactive", testWeForwardReadEOFAndChannelInactive), + ("testErrorInDecodeLastWhenCloseIsReceivedReentrantlyInDecode", testErrorInDecodeLastWhenCloseIsReceivedReentrantlyInDecode), ] } } diff --git a/Tests/NIOTests/CodecTest.swift b/Tests/NIOTests/CodecTest.swift index 492176c7d..c926ca76e 100644 --- a/Tests/NIOTests/CodecTest.swift +++ b/Tests/NIOTests/CodecTest.swift @@ -1304,6 +1304,31 @@ public final class ByteToMessageDecoderTest: XCTestCase { XCTAssertEqual(1, checker.channelInactiveEvents) XCTAssertEqual(1, checker.readEOFEvents) } + + func testErrorInDecodeLastWhenCloseIsReceivedReentrantlyInDecode() { + struct DummyError: Error {} + struct Decoder: ByteToMessageDecoder { + typealias InboundOut = Never + + func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { + // simulate a re-entrant trigger of reading EOF + context.channel.pipeline.fireUserInboundEventTriggered(ChannelEvent.inputClosed) + return .needMoreData + } + + func decodeLast(context: ChannelHandlerContext, buffer: inout ByteBuffer, seenEOF: Bool) throws -> DecodingState { + XCTAssertEqual("X", buffer.readString(length: buffer.readableBytes)) + throw DummyError() + } + } + + let channel = EmbeddedChannel(handler: ByteToMessageHandler(Decoder())) + var buffer = channel.allocator.buffer(capacity: 1) + buffer.writeString("X") + XCTAssertThrowsError(try channel.writeInbound(buffer)) { error in + XCTAssertTrue(error is DummyError) + } + } } public final class MessageToByteEncoderTest: XCTestCase {