diff --git a/Sources/NIO/Codec.swift b/Sources/NIO/Codec.swift index 5919b855b..06b796754 100644 --- a/Sources/NIO/Codec.swift +++ b/Sources/NIO/Codec.swift @@ -45,9 +45,8 @@ public enum DecodingState { /// Please note, however, that the numerical value of the `readerIndex` itself is not preserved, and may not be the same from one call to the next. Please do not rely on this numerical value: if you need /// to recall where a byte is relative to the `readerIndex`, use an offset rather than an absolute value. /// 2. Mutating the bytes in the buffer will cause undefined behaviour and likely crash your program -public protocol ByteToMessageDecoder: ChannelInboundHandler where InboundIn == ByteBuffer { - /// The cumulationBuffer which will be used to buffer any data. - var cumulationBuffer: ByteBuffer? { get set } +public protocol ByteToMessageDecoder { + associatedtype InboundOut /// Decode from a `ByteBuffer`. This method will be called till either the input /// `ByteBuffer` has nothing to read left or `DecodingState.needMoreData` is returned. @@ -57,7 +56,7 @@ public protocol ByteToMessageDecoder: ChannelInboundHandler where InboundIn == B /// - buffer: The `ByteBuffer` from which we decode. /// - returns: `DecodingState.continue` if we should continue calling this method or `DecodingState.needMoreData` if it should be called // again once more data is present in the `ByteBuffer`. - func decode(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState + mutating func decode(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState /// This method is called once, when the `ChannelHandlerContext` goes inactive (i.e. when `channelInactive` is fired) /// @@ -66,19 +65,19 @@ public protocol ByteToMessageDecoder: ChannelInboundHandler where InboundIn == B /// - buffer: The `ByteBuffer` from which we decode. /// - returns: `DecodingState.continue` if we should continue calling this method or `DecodingState.needMoreData` if it should be called // again when more data is present in the `ByteBuffer`. - func decodeLast(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState + mutating func decodeLast(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState /// Called once this `ByteToMessageDecoder` is removed from the `ChannelPipeline`. /// /// - parameters: /// - ctx: The `ChannelHandlerContext` which this `ByteToMessageDecoder` belongs to. - func decoderRemoved(ctx: ChannelHandlerContext) + mutating func decoderRemoved(ctx: ChannelHandlerContext) /// Called when this `ByteToMessageDecoder` is added to the `ChannelPipeline`. /// /// - parameters: /// - ctx: The `ChannelHandlerContext` which this `ByteToMessageDecoder` belongs to. - func decoderAdded(ctx: ChannelHandlerContext) + mutating func decoderAdded(ctx: ChannelHandlerContext) /// Determine if the read bytes in the given `ByteBuffer` should be reclaimed and their associated memory freed. /// Be aware that reclaiming memory may involve memory copies and so is not free. @@ -86,7 +85,36 @@ public protocol ByteToMessageDecoder: ChannelInboundHandler where InboundIn == B /// - parameters: /// - buffer: The `ByteBuffer` to check /// - return: `true` if memory should be reclaimed, `false` otherwise. - func shouldReclaimBytes(buffer: ByteBuffer) -> Bool + mutating func shouldReclaimBytes(buffer: ByteBuffer) -> Bool +} + +extension ByteToMessageDecoder { + public mutating func decoderRemoved(ctx: ChannelHandlerContext) { + } + + public mutating func decoderAdded(ctx: ChannelHandlerContext) { + } + + /// Default implementation to detect once bytes should be reclaimed. + public func shouldReclaimBytes(buffer: ByteBuffer) -> Bool { + // We want to reclaim in the following cases: + // + // 1. If there is more than 2kB of memory to reclaim + // 2. If the buffer is more than 50% reclaimable memory and is at least + // 1kB in size. + if buffer.readerIndex > 2048 { + return true + } + return buffer.capacity > 1024 && (buffer.capacity - buffer.readerIndex) >= buffer.readerIndex + } + + public func decodeLast(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { + return .needMoreData + } + + public func wrapInboundOut(_ value: InboundOut) -> NIOAny { + return NIOAny(value) + } } private extension ChannelHandlerContext { @@ -101,116 +129,266 @@ private extension ChannelHandlerContext { } } -extension ByteToMessageDecoder { +private struct B2MDBuffer { + /// `B2MDBuffer`'s internal state, either we're already processing a buffer or we're ready to. + private enum State { + case processingInProgress + case ready + } - /// Decode in a loop until there is nothing more to decode. - private func decodeLoop(ctx: ChannelHandlerContext, decodeFunc: (ChannelHandlerContext, inout ByteBuffer) throws -> DecodingState) throws { - while var slice = self.cumulationBuffer?.slice(), slice.readableBytes > 0 { - // Needed to later calculate how much we need to advance the readerIndex of the cumulationBuffer. - let sliceReadable = slice.readableBytes - let sliceWriterIndex = slice.writerIndex + /// Can we produce a buffer to be processed right now or not? + enum BufferAvailability { + /// No, because no bytes available + case nothingAvailable + /// No, because we're already processing one + case bufferAlreadyBeingProcessed + /// Yes please, here we go. + case available(ByteBuffer) + } - // We fetch the writerIndex of the cumulationBuffer to make a good guess about if the cumulationBuffer changed in between due re-entrant call to - // channelRead after we called decodeFunc(...). - let writerIndex = self.cumulationBuffer!.writerIndex - let result = try decodeFunc(ctx, &slice) + /// Result of a try to process a buffer. + enum BufferProcessingResult { + /// Could not process a buffer because we are already processing one on the same call stack. + case cannotProcessReentrantly + /// Yes, we did process some. + case didProcess(DecodingState) + } - guard self.cumulationBuffer != nil else { - // The cumulationBuffer was set to nil by either removing the decoder or closing the channel, just break the loop. - break + private var state: State = .ready + private var buffers: CircularBuffer = CircularBuffer(initialRingCapacity: 4) +} + +// MARK: B2MDBuffer Main API +extension B2MDBuffer { + /// Start processing some bytes if possible, if we receive a returned buffer (through `.available(ByteBuffer)`) + /// we _must_ indicate the processing has finished by calling `finishProcessing`. + mutating func startProcessing() -> BufferAvailability { + switch self.state { + case .processingInProgress: + return .bufferAlreadyBeingProcessed + case .ready where self.buffers.count > 0: + var buffer = self.buffers.removeFirst() + buffer.writeBuffers(self.buffers) + self.buffers.removeAll(keepingCapacity: true) + if buffer.readableBytes > 0 { + self.state = .processingInProgress + return .available(buffer) + } else { + return .nothingAvailable } + case .ready: + assert(self.buffers.count == 0) + return .nothingAvailable + } + } - precondition(slice.writerIndex == sliceWriterIndex, "Writing to the buffer is not allowed") - self.cumulationBuffer!.moveReaderIndex(forwardBy: sliceReadable - slice.readableBytes) + mutating func finishProcessing(remainder buffer: ByteBuffer) -> Void { + assert(self.state == .processingInProgress) + self.state = .ready + if buffer.readableBytes > 0 { + self.buffers.prepend(buffer) + } else { + var buffer = buffer + buffer.clear() + buffer.writeBuffers(self.buffers) + self.buffers.removeAll(keepingCapacity: true) + self.buffers.append(buffer) + } + } - // If the user told us more data is needed we also need to ensure the writerIndex did not change in between. - // If the writerIndex changed we need to retry as there is more data delivered via re-entrance maybe. - if result == .needMoreData && self.cumulationBuffer!.writerIndex == writerIndex { - break + mutating func append(buffer: ByteBuffer) { + if buffer.readableBytes > 0 { + self.buffers.append(buffer) + } + } +} + +// MARK: B2MDBuffer Helpers +private extension ByteBuffer { + mutating func writeBuffers(_ buffers: CircularBuffer) { + guard buffers.count > 0 else { + return + } + var allReadableBytes: Int = 0 + for buffer in buffers { + allReadableBytes += buffer.readableBytes + } + self.reserveCapacity(self.writerIndex + allReadableBytes) + for var buffer in buffers { + self.write(buffer: &buffer) + } + } +} + +private extension B2MDBuffer { + func _testOnlyOneBuffer() -> ByteBuffer? { + if buffers.count == 0 { + return nil + } else if buffers.count == 1 { + return self.buffers.first + } else { + let firstIndex = self.buffers.startIndex + var firstBuffer = self.buffers[firstIndex] + for var buffer in self.buffers[self.buffers.index(after: firstIndex)...] { + firstBuffer.write(buffer: &buffer) + } + return firstBuffer + } + } +} + +public class ByteToMessageHandler { + public typealias InboundIn = ByteBuffer + public typealias InboundOut = Decoder.InboundOut + + private enum DecodeMode { + /// This is a usual decode, ie. not the last chunk + case normal + + /// Last chunk + case last + } + + private enum State { + case active + case leftoversNeedProcessing + case done + } + + internal private(set) var decoder: Decoder? // only `nil` if we're already decoding (ie. we're re-entered) + private var state: State = .active + private var buffer: B2MDBuffer = B2MDBuffer() + + public init(_ decoder: Decoder) { + self.decoder = decoder + } + + deinit { + assert(self.state == .done) + } +} + +// MARK: ByteToMessageHandler: Test Helpers +extension ByteToMessageHandler { + internal var cumulationBuffer: ByteBuffer? { + return self.buffer._testOnlyOneBuffer() + } +} + +// MARK: ByteToMessageHandler's Main API +extension ByteToMessageHandler { + private func withNextBuffer(_ body: (inout Decoder, inout ByteBuffer) throws -> DecodingState) rethrows -> B2MDBuffer.BufferProcessingResult { + switch self.buffer.startProcessing() { + case .bufferAlreadyBeingProcessed: + return .cannotProcessReentrantly + case .nothingAvailable: + return .didProcess(.needMoreData) + case .available(var buffer): + var decoder: Decoder? = nil + swap(&decoder, &self.decoder) + assert(decoder != nil) // self.decoder only `nil` if we're being re-entered, but .available means we're not + defer { + swap(&decoder, &self.decoder) + if buffer.readableBytes > 0 { + // we asserted above that the decoder we just swapped back in was non-nil so now `self.decoder` must + // be non-nil. + if self.decoder!.shouldReclaimBytes(buffer: buffer) { + buffer.discardReadBytes() + } + } + self.buffer.finishProcessing(remainder: buffer) + } + return .didProcess(try body(&decoder!, &buffer)) + } + } + + private func processLeftovers(ctx: ChannelHandlerContext) { + guard self.state == .active else { + // we are processing or have already processed the leftovers + return + } + + ctx.withThrowingToFireErrorAndClose { + switch try self.decodeLoop(ctx: ctx, decodeMode: .last) { + case .didProcess: + self.state = .done + case .cannotProcessReentrantly: + self.state = .leftoversNeedProcessing } } } + private func decodeLoop(ctx: ChannelHandlerContext, decodeMode: DecodeMode) throws -> B2MDBuffer.BufferProcessingResult { + while true { + let result = try self.withNextBuffer { decoder, buffer in + if decodeMode == .normal { + return try decoder.decode(ctx: ctx, buffer: &buffer) + } else { + return try decoder.decodeLast(ctx: ctx, buffer: &buffer) + } + } + switch result { + case .didProcess(.continue): + continue + case .didProcess(.needMoreData): + return .didProcess(.needMoreData) + case .cannotProcessReentrantly: + return .cannotProcessReentrantly + } + } + } +} + +// MARK: ByteToMessageHandler: ChannelInboundHandler +extension ByteToMessageHandler: ChannelInboundHandler { + + public func handlerAdded(ctx: ChannelHandlerContext) { + // here we can force it because we know that the decoder isn't in use if we're just adding this handler + self.decoder!.decoderAdded(ctx: ctx) + } + + + public func handlerRemoved(ctx: ChannelHandlerContext) { + self.processLeftovers(ctx: ctx) + } + /// Calls `decode` until there is nothing left to decode. public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { - // Either merge the received data into the existing cumulationBuffer or use it as the cumulationBuffer if none exists yet. - if self.cumulationBuffer != nil { - var buffer = self.unwrapInboundIn(data) - self.cumulationBuffer!.write(buffer: &buffer) - } else { - self.cumulationBuffer = self.unwrapInboundIn(data) - } - + self.buffer.append(buffer: self.unwrapInboundIn(data)) ctx.withThrowingToFireErrorAndClose { - try self.decodeLoop(ctx: ctx, decodeFunc: self.decode) - } - - // Discard the cumulationBuffer or discard read bytes if needed. - guard let buffer = self.cumulationBuffer, buffer.readableBytes > 0 else { - self.cumulationBuffer = nil - return - } - - // Check if we should reclaim some bytes and if so do it. - if self.shouldReclaimBytes(buffer: self.cumulationBuffer!) { - self.cumulationBuffer!.discardReadBytes() + switch try self.decodeLoop(ctx: ctx, decodeMode: .normal) { + case .didProcess: + switch self.state { + case .active: + () // cool, all normal + case .done: + () // 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(ctx: ctx, decodeMode: .last) { + case .didProcess: + () // expected and cool + case .cannotProcessReentrantly: + preconditionFailure("bug in NIO: non-reentrant decode loop couldn't run \(self), \(self.state)") + } + } + case .cannotProcessReentrantly: + // fine, will be done later + () + } } } /// Call `decodeLast` before forward the event through the pipeline. public func channelInactive(ctx: ChannelHandlerContext) { - if self.cumulationBuffer != nil { - ctx.withThrowingToFireErrorAndClose { - try self.decodeLoop(ctx: ctx, decodeFunc: self.decodeLast) - } - // Once the Channel goes inactive we can just drop all previous buffered data. - self.cumulationBuffer = nil - } + self.processLeftovers(ctx: ctx) ctx.fireChannelInactive() } - - public func handlerAdded(ctx: ChannelHandlerContext) { - self.decoderAdded(ctx: ctx) - } - - public func handlerRemoved(ctx: ChannelHandlerContext) { - if let buffer = self.cumulationBuffer as? InboundOut { - ctx.fireChannelRead(self.wrapInboundOut(buffer)) - } else { - /* please note that we're dropping the partially received bytes (if any) on the floor here as we can't - send a full message to the next handler. */ - } - self.cumulationBuffer = nil - self.decoderRemoved(ctx: ctx) - } - - /// Just call `decode`. Users may implement their own logic. - public func decodeLast(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { - return try self.decode(ctx: ctx, buffer: &buffer) - } - - /// Do nothing by default. - public func decoderRemoved(ctx: ChannelHandlerContext) { - } - - /// Do nothing by default. - public func decoderAdded(ctx: ChannelHandlerContext) { - } - - /// Default implementation to detect once bytes should be reclaimed. - public func shouldReclaimBytes(buffer: ByteBuffer) -> Bool { - // We want to reclaim in the following cases: - // - // 1. If there is more than 2kB of memory to reclaim - // 2. If the buffer is more than 50% reclaimable memory and is at least - // 1kB in size. - if buffer.readerIndex > 2048 { - return true - } - return buffer.capacity > 1024 && (buffer.capacity - buffer.readerIndex) >= buffer.readerIndex - } } /// `ChannelOutboundHandler` which allows users to encode custom messages to a `ByteBuffer` easily. diff --git a/Sources/NIOChatServer/main.swift b/Sources/NIOChatServer/main.swift index ca34e14e6..61432e6c6 100644 --- a/Sources/NIOChatServer/main.swift +++ b/Sources/NIOChatServer/main.swift @@ -122,7 +122,7 @@ let bootstrap = ServerBootstrap(group: group) // Set the handlers that are applied to the accepted Channels .childChannelInitializer { channel in // Add handler that will buffer data until a \n is received - channel.pipeline.add(handler: LineDelimiterCodec()).then { v in + channel.pipeline.add(handler: ByteToMessageHandler(LineDelimiterCodec())).then { v in // It's important we use the same handler for all accepted channels. The ChatHandler is thread-safe! channel.pipeline.add(handler: chatHandler) } diff --git a/Sources/NIOHTTP1/HTTPDecoder.swift b/Sources/NIOHTTP1/HTTPDecoder.swift index df9008787..e727d1cdb 100644 --- a/Sources/NIOHTTP1/HTTPDecoder.swift +++ b/Sources/NIOHTTP1/HTTPDecoder.swift @@ -210,7 +210,7 @@ public enum RemoveAfterUpgradeStrategy { /// either the form of `HTTPClientResponsePart` or `HTTPServerRequestPart`: that is, /// it produces messages that correspond to the semantic units of HTTP produced by /// the remote peer. -public class HTTPDecoder: ByteToMessageDecoder, AnyHTTPDecoder { +public class HTTPDecoder: ChannelInboundHandler, AnyHTTPDecoder { public typealias InboundIn = ByteBuffer public typealias InboundOut = HTTPMessageT @@ -274,7 +274,7 @@ public class HTTPDecoder: ByteToMessageDecoder, AnyHTTPDecoder { self.cumulationBuffer = nil } - public func decoderAdded(ctx: ChannelHandlerContext) { + public func handlerAdded(ctx: ChannelHandlerContext) { if HTTPMessageT.self == HTTPServerRequestPart.self { c_nio_http_parser_init(&self.parser, HTTP_REQUEST) } else if HTTPMessageT.self == HTTPClientResponsePart.self { @@ -573,6 +573,18 @@ public class HTTPDecoder: ByteToMessageDecoder, AnyHTTPDecoder { } } + private func shouldReclaimBytes(buffer: ByteBuffer) -> Bool { + // We want to reclaim in the following cases: + // + // 1. If there is more than 2kB of memory to reclaim + // 2. If the buffer is more than 50% reclaimable memory and is at least + // 1kB in size. + if buffer.readerIndex > 2048 { + return true + } + return buffer.capacity > 1024 && (buffer.capacity - buffer.readerIndex) >= buffer.readerIndex + } + /// Will discard bytes till readerIndex if it's needed and then call `fn`. private func mayDiscardDecodedBytes(upTo: Int, _ fn: () -> Void) { assert(self.cumulationBuffer!.readerIndex == self.cumulationBuffer!.writerIndex) diff --git a/Sources/NIOTLS/SNIHandler.swift b/Sources/NIOTLS/SNIHandler.swift index 22be940fb..f287067b5 100644 --- a/Sources/NIOTLS/SNIHandler.swift +++ b/Sources/NIOTLS/SNIHandler.swift @@ -114,12 +114,16 @@ public class SniHandler: ByteToMessageDecoder { private var waitingForUser: Bool public init(sniCompleteHandler: @escaping (SniResult) -> EventLoopFuture) { - self.cumulationBuffer = nil self.completionHandler = sniCompleteHandler self.waitingForUser = false } - // A note to maintainers: this method *never* returns true. + public func decodeLast(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { + ctx.fireChannelRead(NIOAny(buffer)) + return .needMoreData + } + + // A note to maintainers: this method *never* returns `.continue`. public func decode(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) -> DecodingState { // If we've asked the user to mutate the pipeline already, we're not interested in // this data. Keep waiting. @@ -428,7 +432,7 @@ public class SniHandler: ByteToMessageDecoder { private func sniComplete(result: SniResult, ctx: ChannelHandlerContext) { waitingForUser = true completionHandler(result).whenSuccess { - ctx.pipeline.remove(handler: self, promise: nil) + ctx.pipeline.remove(ctx: ctx, promise: nil) } } } diff --git a/Sources/NIOWebSocket/WebSocketFrameDecoder.swift b/Sources/NIOWebSocket/WebSocketFrameDecoder.swift index 8b9e16063..8eed16a2e 100644 --- a/Sources/NIOWebSocket/WebSocketFrameDecoder.swift +++ b/Sources/NIOWebSocket/WebSocketFrameDecoder.swift @@ -224,7 +224,6 @@ public final class WebSocketFrameDecoder: ByteToMessageDecoder { public typealias InboundIn = ByteBuffer public typealias InboundOut = WebSocketFrame public typealias OutboundOut = WebSocketFrame - public var cumulationBuffer: ByteBuffer? = nil /// The maximum frame size the decoder is willing to tolerate from the remote peer. /* private but tests */ let maxFrameSize: Int @@ -310,7 +309,7 @@ public final class WebSocketFrameDecoder: ByteToMessageDecoder { let frame = WebSocketFrame(fin: true, opcode: .connectionClose, data: data) - ctx.writeAndFlush(self.wrapOutboundOut(frame)).whenComplete { + ctx.writeAndFlush(self.wrapInboundOut(frame)).whenComplete { ctx.close(promise: nil) } } diff --git a/Sources/NIOWebSocket/WebSocketUpgrader.swift b/Sources/NIOWebSocket/WebSocketUpgrader.swift index 35aec8cf9..1983f998f 100644 --- a/Sources/NIOWebSocket/WebSocketUpgrader.swift +++ b/Sources/NIOWebSocket/WebSocketUpgrader.swift @@ -148,7 +148,7 @@ public final class WebSocketUpgrader: HTTPProtocolUpgrader { /// We never use the automatic error handling feature of the WebSocketFrameDecoder: we always use the separate channel /// handler. var upgradeFuture = ctx.pipeline.add(handler: WebSocketFrameEncoder()).then { - ctx.pipeline.add(handler: WebSocketFrameDecoder(maxFrameSize: self.maxFrameSize, automaticErrorHandling: false)) + ctx.pipeline.add(handler: ByteToMessageHandler(WebSocketFrameDecoder(maxFrameSize: self.maxFrameSize, automaticErrorHandling: false))) } if self.automaticErrorHandling { diff --git a/Tests/NIOTLSTests/SNIHandlerTests.swift b/Tests/NIOTLSTests/SNIHandlerTests.swift index afdd2fd60..a82e26231 100644 --- a/Tests/NIOTLSTests/SNIHandlerTests.swift +++ b/Tests/NIOTLSTests/SNIHandlerTests.swift @@ -264,11 +264,11 @@ class SniHandlerTest: XCTestCase { let loop = channel.eventLoop as! EmbeddedEventLoop let continuePromise = loop.newPromise(of: Void.self) - let handler = SniHandler { result in + let handler = ByteToMessageHandler(SniHandler { result in XCTAssertEqual(expectedResult, result) called = true return continuePromise.futureResult - } + }) try channel.pipeline.add(handler: handler).wait() @@ -296,7 +296,7 @@ class SniHandlerTest: XCTestCase { continuePromise.succeed(result: ()) loop.run() - let writtenBuffer: ByteBuffer = channel.readInbound()! + let writtenBuffer: ByteBuffer = channel.readInbound() ?? channel.allocator.buffer(capacity: 0) let writtenData = writtenBuffer.getData(at: writtenBuffer.readerIndex, length: writtenBuffer.readableBytes) let expectedData = Data(base64Encoded: clientHello, options: .ignoreUnknownCharacters)! XCTAssertEqual(writtenData, expectedData) @@ -315,11 +315,11 @@ class SniHandlerTest: XCTestCase { let loop = channel.eventLoop as! EmbeddedEventLoop let continuePromise = loop.newPromise(of: Void.self) - let handler = SniHandler { result in + let handler = ByteToMessageHandler(SniHandler { result in XCTAssertEqual(expectedResult, result) called = true return continuePromise.futureResult - } + }) try channel.pipeline.add(handler: handler).wait() @@ -356,10 +356,10 @@ class SniHandlerTest: XCTestCase { let channel = EmbeddedChannel() let loop = channel.eventLoop as! EmbeddedEventLoop - let handler = SniHandler { result in + let handler = ByteToMessageHandler(SniHandler { result in XCTFail("Handler was called") return loop.newSucceededFuture(result: ()) - } + }) try channel.pipeline.add(handler: handler).wait() diff --git a/Tests/NIOTests/CodecTest+XCTest.swift b/Tests/NIOTests/CodecTest+XCTest.swift index 6ed42bc7a..6a8f52863 100644 --- a/Tests/NIOTests/CodecTest+XCTest.swift +++ b/Tests/NIOTests/CodecTest+XCTest.swift @@ -32,7 +32,12 @@ extension ByteToMessageDecoderTest { ("testMemoryIsReclaimedIfMostIsConsumed", testMemoryIsReclaimedIfMostIsConsumed), ("testMemoryIsReclaimedIfLotsIsAvailable", testMemoryIsReclaimedIfLotsIsAvailable), ("testDecoderReentranceChannelRead", testDecoderReentranceChannelRead), - ("testDecoderWriteIntoCumulationBuffer", testDecoderWriteIntoCumulationBuffer), + ("testTrivialDecoderDoesSensibleStuffWhenCloseInRead", testTrivialDecoderDoesSensibleStuffWhenCloseInRead), + ("testLeftOversMakeDecodeLastCalled", testLeftOversMakeDecodeLastCalled), + ("testRemovingHandlerMakesLeftoversAppearInDecodeLast", testRemovingHandlerMakesLeftoversAppearInDecodeLast), + ("testStructsWorkAsByteToMessageDecoders", testStructsWorkAsByteToMessageDecoders), + ("testReentrantChannelReadWhileWholeBufferIsBeingProcessed", testReentrantChannelReadWhileWholeBufferIsBeingProcessed), + ("testReentrantChannelCloseInChannelRead", testReentrantChannelCloseInChannelRead), ] } } diff --git a/Tests/NIOTests/CodecTest.swift b/Tests/NIOTests/CodecTest.swift index 63fd76804..a53079f3b 100644 --- a/Tests/NIOTests/CodecTest.swift +++ b/Tests/NIOTests/CodecTest.swift @@ -55,9 +55,6 @@ public class ByteToMessageDecoderTest: XCTestCase { typealias InboundIn = ByteBuffer typealias InboundOut = Int32 - var cumulationBuffer: ByteBuffer? - - func decode(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) -> DecodingState { guard buffer.readableBytes >= MemoryLayout.size else { return .needMoreData @@ -71,8 +68,6 @@ public class ByteToMessageDecoderTest: XCTestCase { typealias InboundIn = ByteBuffer typealias InboundOut = Never - var cumulationBuffer: ByteBuffer? - func decode(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) -> DecodingState { return .needMoreData } @@ -82,8 +77,6 @@ public class ByteToMessageDecoderTest: XCTestCase { typealias InboundIn = ByteBuffer typealias InboundOut = ByteBuffer - var cumulationBuffer: ByteBuffer? - func decode(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) -> DecodingState { guard case .some(let buffer) = buffer.readSlice(length: 512) else { return .needMoreData @@ -100,8 +93,6 @@ public class ByteToMessageDecoderTest: XCTestCase { typealias InboundIn = ByteBuffer typealias InboundOut = ByteBuffer - var cumulationBuffer: ByteBuffer? - func decode(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) -> DecodingState { guard buffer.readableBytes >= 5120 else { return .needMoreData @@ -115,7 +106,7 @@ public class ByteToMessageDecoderTest: XCTestCase { func testDecoder() throws { let channel = EmbeddedChannel() - _ = try channel.pipeline.add(handler: ByteToInt32Decoder()).wait() + _ = try channel.pipeline.add(handler: ByteToMessageHandler(ByteToInt32Decoder())).wait() var buffer = channel.allocator.buffer(capacity: 32) buffer.write(integer: Int32(1)) @@ -146,7 +137,7 @@ public class ByteToMessageDecoderTest: XCTestCase { XCTAssertNoThrow(try channel.finish()) } let inactivePromiser = ChannelInactivePromiser(channel: channel) - _ = try channel.pipeline.add(handler: ByteToInt32Decoder()).wait() + _ = try channel.pipeline.add(handler: ByteToMessageHandler(ByteToInt32Decoder())).wait() _ = try channel.pipeline.add(handler: inactivePromiser).wait() var buffer = channel.allocator.buffer(capacity: 32) @@ -168,7 +159,7 @@ public class ByteToMessageDecoderTest: XCTestCase { XCTAssertEqual(testDecoderIsNotQuadratic_mallocs, 0) XCTAssertEqual(testDecoderIsNotQuadratic_reallocs, 0) - XCTAssertNoThrow(try channel.pipeline.add(handler: ForeverDecoder()).wait()) + XCTAssertNoThrow(try channel.pipeline.add(handler: ByteToMessageHandler(ForeverDecoder())).wait()) let dummyAllocator = ByteBufferAllocator(hookedMalloc: testDecoderIsNotQuadratic_mallocHook, hookedRealloc: testDecoderIsNotQuadratic_reallocHook, @@ -194,7 +185,7 @@ public class ByteToMessageDecoderTest: XCTestCase { XCTAssertNoThrow(try channel.finish()) } - let decoder = LargeChunkDecoder() + let decoder = ByteToMessageHandler(LargeChunkDecoder()) _ = try channel.pipeline.add(handler: decoder).wait() // We're going to send in 513 bytes. This will cause a chunk to be passed on, and will leave @@ -220,7 +211,7 @@ public class ByteToMessageDecoderTest: XCTestCase { XCTAssertNoThrow(try channel.finish()) } - let decoder = OnceDecoder() + let decoder = ByteToMessageHandler(OnceDecoder()) _ = try channel.pipeline.add(handler: decoder).wait() // We're going to send in 5119 bytes. This will be held. @@ -249,81 +240,287 @@ public class ByteToMessageDecoderTest: XCTestCase { typealias InboundIn = ByteBuffer typealias InboundOut = ByteBuffer - var cumulationBuffer: ByteBuffer? - var reentranced: Bool = false - var decode: Bool = false + var numberOfDecodeCalls = 0 + var hasReentranced = false func decode(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { - guard !self.decode else { - self.reentranced = true - return .needMoreData + self.numberOfDecodeCalls += 1 + print("\(numberOfDecodeCalls): \(String(decoding: buffer.readableBytesView, as: UTF8.self))") + var reentrantWriteBuffer = ctx.channel.allocator.buffer(capacity: 1) + if self.numberOfDecodeCalls == 2 { + // this is the first time, let's fireChannelRead + self.hasReentranced = true + reentrantWriteBuffer.clear() + reentrantWriteBuffer.write(staticString: "3") + ctx.channel.pipeline.fireChannelRead(self.wrapInboundOut(reentrantWriteBuffer)) } - self.decode = true - defer { - self.decode = false + ctx.fireChannelRead(self.wrapInboundOut(buffer.readSlice(length: 1)!)) + if self.numberOfDecodeCalls == 2 { + reentrantWriteBuffer.clear() + reentrantWriteBuffer.write(staticString: "4") + ctx.channel.pipeline.fireChannelRead(self.wrapInboundOut(reentrantWriteBuffer)) } - - if !self.reentranced { - ctx.channel.pipeline.fireChannelRead(self.wrapInboundOut(buffer)) - } - ctx.fireChannelRead(self.wrapInboundOut(buffer.readSlice(length: 2)!)) return .continue } } - XCTAssertNoThrow(try channel.pipeline.add(handler: TestDecoder()).wait()) + let testDecoder = TestDecoder() + + XCTAssertNoThrow(try channel.pipeline.add(handler: ByteToMessageHandler(testDecoder)).wait()) var inputBuffer = channel.allocator.buffer(capacity: 4) - inputBuffer.write(staticString: "xxxx") + /* 1 */ + inputBuffer.write(staticString: "1") XCTAssertTrue(try channel.writeInbound(inputBuffer)) + inputBuffer.clear() - let buffer = inputBuffer.readSlice(length: 2)! - XCTAssertEqual(buffer, channel.readInbound()) - XCTAssertEqual(buffer, channel.readInbound()) - XCTAssertEqual(buffer, channel.readInbound()) - XCTAssertEqual(buffer, channel.readInbound()) - XCTAssertNil(channel.readInbound()) - } + /* 2 */ + inputBuffer.write(staticString: "2") + XCTAssertTrue(try channel.writeInbound(inputBuffer)) + inputBuffer.clear() - func testDecoderWriteIntoCumulationBuffer() throws { - let channel = EmbeddedChannel() - defer { - XCTAssertNoThrow(try channel.finish()) + /* 3 */ + inputBuffer.write(staticString: "5") + XCTAssertTrue(try channel.writeInbound(inputBuffer)) + inputBuffer.clear() + + func readOneInboundString() -> String { + switch channel.readInbound() as ByteBuffer? { + case .some(let buffer): + return String(decoding: buffer.readableBytesView, as: Unicode.UTF8.self) + case .none: + XCTFail("expected ByteBuffer found nothing") + return "no, error from \(#line)" + } } - class WriteDecoder: ByteToMessageDecoder { + (channel.eventLoop as! EmbeddedEventLoop).run() + XCTAssertEqual("1", readOneInboundString()) + XCTAssertEqual("2", readOneInboundString()) + XCTAssertEqual("3", readOneInboundString()) + XCTAssertEqual("4", readOneInboundString()) + XCTAssertEqual("5", readOneInboundString()) + XCTAssertNil(channel.readInbound() as IOData?) + XCTAssertTrue(testDecoder.hasReentranced) + } - typealias InboundIn = ByteBuffer + func testTrivialDecoderDoesSensibleStuffWhenCloseInRead() { + class HandItThroughDecoder: ByteToMessageDecoder { typealias InboundOut = ByteBuffer - var cumulationBuffer: ByteBuffer? - func decode(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { - XCTAssertTrue(buffer.readableBytes <= 4) - - ctx.fireChannelRead(self.wrapInboundOut(buffer.readSlice(length: 2)!)) - - if buffer.readableBytes > 0 { - // This should not be visible anymore after we exit the method which also means we should never see more then 4 readableBytes. - buffer.set(integer: UInt(0), at: buffer.readerIndex) - XCTAssertEqual(UInt(0), buffer.getInteger(at: buffer.readerIndex)) + ctx.fireChannelRead(self.wrapInboundOut(buffer.readSlice(length: buffer.readableBytes)!)) + if buffer.readableBytesView.last == "0".utf8.last { + ctx.close().whenFailure { error in + XCTFail("unexpected error: \(error)") + } } + return .needMoreData + } + func decodeLast(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { + XCTFail("shouldn't be called") return .continue } } - XCTAssertNoThrow(try channel.pipeline.add(handler: WriteDecoder()).wait()) + let channel = EmbeddedChannel(handler: ByteToMessageHandler(HandItThroughDecoder())) - var inputBuffer = channel.allocator.buffer(capacity: 4) - inputBuffer.write(staticString: "xxxx") - XCTAssertTrue(try channel.writeInbound(inputBuffer)) + var buffer = channel.allocator.buffer(capacity: 16) + buffer.clear() + buffer.write(staticString: "1") + XCTAssertNoThrow(try channel.writeInbound(buffer)) + buffer.clear() + buffer.write(staticString: "23") + XCTAssertNoThrow(try channel.writeInbound(buffer)) + buffer.clear() + buffer.write(staticString: "4567890") + XCTAssertNoThrow(try channel.writeInbound(buffer)) + XCTAssertFalse(channel.isActive) - let buffer = inputBuffer.readSlice(length: 2)! - XCTAssertEqual(buffer, channel.readInbound()) - XCTAssertEqual(buffer, channel.readInbound()) + XCTAssertEqual("1", (channel.readInbound() as ByteBuffer?).map { String(decoding: $0.readableBytesView, as: Unicode.UTF8.self) }) + XCTAssertEqual("23", (channel.readInbound() as ByteBuffer?).map { String(decoding: $0.readableBytesView, as: Unicode.UTF8.self) }) + XCTAssertEqual("4567890", (channel.readInbound() as ByteBuffer?).map { String(decoding: $0.readableBytesView, as: Unicode.UTF8.self) }) XCTAssertNil(channel.readInbound()) } + + func testLeftOversMakeDecodeLastCalled() { + let lastPromise = EmbeddedEventLoop().newPromise(of: ByteBuffer.self) + let channel = EmbeddedChannel(handler: ByteToMessageHandler(PairOfBytesDecoder(lastPromise: lastPromise))) + + var buffer = channel.allocator.buffer(capacity: 16) + buffer.clear() + buffer.write(staticString: "1") + XCTAssertNoThrow(try channel.writeInbound(buffer)) + buffer.clear() + buffer.write(staticString: "23") + XCTAssertNoThrow(try channel.writeInbound(buffer)) + buffer.clear() + buffer.write(staticString: "4567890x") + XCTAssertNoThrow(try channel.writeInbound(buffer)) + XCTAssertNoThrow(try channel.close().wait()) + XCTAssertFalse(channel.isActive) + + XCTAssertEqual("12", (channel.readInbound() as ByteBuffer?).map { String(decoding: $0.readableBytesView, as: Unicode.UTF8.self) }) + XCTAssertEqual("34", (channel.readInbound() as ByteBuffer?).map { String(decoding: $0.readableBytesView, as: Unicode.UTF8.self) }) + XCTAssertEqual("56", (channel.readInbound() as ByteBuffer?).map { String(decoding: $0.readableBytesView, as: Unicode.UTF8.self) }) + XCTAssertEqual("78", (channel.readInbound() as ByteBuffer?).map { String(decoding: $0.readableBytesView, as: Unicode.UTF8.self) }) + XCTAssertEqual("90", (channel.readInbound() as ByteBuffer?).map { String(decoding: $0.readableBytesView, as: Unicode.UTF8.self) }) + XCTAssertNil(channel.readInbound()) + + XCTAssertNoThrow(XCTAssertEqual("x", String(decoding: try lastPromise.futureResult.wait().readableBytesView, + as: Unicode.UTF8.self))) + } + + func testRemovingHandlerMakesLeftoversAppearInDecodeLast() { + let lastPromise = EmbeddedEventLoop().newPromise(of: ByteBuffer.self) + let channel = EmbeddedChannel(handler: ByteToMessageHandler(PairOfBytesDecoder(lastPromise: lastPromise))) + defer { + XCTAssertNoThrow(XCTAssertFalse(try channel.finish())) + } + + var buffer = channel.allocator.buffer(capacity: 16) + buffer.clear() + buffer.write(staticString: "1") + XCTAssertNoThrow(try channel.writeInbound(buffer)) + buffer.clear() + buffer.write(staticString: "23") + XCTAssertNoThrow(try channel.writeInbound(buffer)) + buffer.clear() + buffer.write(staticString: "4567890x") + XCTAssertNoThrow(try channel.writeInbound(buffer)) + + channel.pipeline.context(handlerType: ByteToMessageHandler.self).then { ctx in + return channel.pipeline.remove(ctx: ctx) + }.map { + XCTAssertTrue($0) + }.whenFailure { error in + XCTFail("unexpected error: \(error)") + } + + XCTAssertEqual("12", (channel.readInbound() as ByteBuffer?).map { String(decoding: $0.readableBytesView, as: Unicode.UTF8.self) }) + XCTAssertEqual("34", (channel.readInbound() as ByteBuffer?).map { String(decoding: $0.readableBytesView, as: Unicode.UTF8.self) }) + XCTAssertEqual("56", (channel.readInbound() as ByteBuffer?).map { String(decoding: $0.readableBytesView, as: Unicode.UTF8.self) }) + XCTAssertEqual("78", (channel.readInbound() as ByteBuffer?).map { String(decoding: $0.readableBytesView, as: Unicode.UTF8.self) }) + XCTAssertEqual("90", (channel.readInbound() as ByteBuffer?).map { String(decoding: $0.readableBytesView, as: Unicode.UTF8.self) }) + XCTAssertNil(channel.readInbound()) + + XCTAssertNoThrow(XCTAssertEqual("x", String(decoding: try lastPromise.futureResult.wait().readableBytesView, + as: Unicode.UTF8.self))) + } + + func testStructsWorkAsByteToMessageDecoders() { + struct WantsOneThenTwoBytesDecoder: ByteToMessageDecoder { + typealias InboundOut = Int + + var state: Int = 1 + + mutating func decode(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { + if let slice = buffer.readSlice(length: self.state) { + defer { + self.state += 1 + } + ctx.fireChannelRead(self.wrapInboundOut(self.state)) + return .continue + } else { + return .needMoreData + } + } + + mutating func decodeLast(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { + ctx.fireChannelRead(self.wrapInboundOut(buffer.readableBytes * -1)) + return .needMoreData + } + } + let channel = EmbeddedChannel(handler: ByteToMessageHandler(WantsOneThenTwoBytesDecoder())) + + var buffer = channel.allocator.buffer(capacity: 16) + buffer.clear() + buffer.write(staticString: "1") + XCTAssertNoThrow(try channel.writeInbound(buffer)) + buffer.clear() + buffer.write(staticString: "23") + XCTAssertNoThrow(try channel.writeInbound(buffer)) + buffer.clear() + buffer.write(staticString: "4567890qwer") + XCTAssertNoThrow(try channel.writeInbound(buffer)) + + XCTAssertEqual(1, (channel.readInbound() as Int?)) + XCTAssertEqual(2, (channel.readInbound() as Int?)) + XCTAssertEqual(3, (channel.readInbound() as Int?)) + XCTAssertEqual(4, (channel.readInbound() as Int?)) + XCTAssertNil(channel.readInbound()) + + XCTAssertNoThrow(try channel.close().wait()) + XCTAssertFalse(channel.isActive) + + XCTAssertEqual(-4, (channel.readInbound() as Int?)) + XCTAssertNil(channel.readInbound()) + } + + func testReentrantChannelReadWhileWholeBufferIsBeingProcessed() { + struct ProcessAndReentrantylyProcessExponentiallyLessStuffDecoder: ByteToMessageDecoder { + typealias InboundOut = String + var state = 16 + + mutating func decode(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { + XCTAssertGreaterThan(self.state, 0) + if let slice = buffer.readSlice(length: self.state) { + self.state >>= 1 + for i in 0.. DecodingState { + if let slice = buffer.readSlice(length: 16) { + ctx.fireChannelRead(self.wrapInboundOut(slice)) + ctx.channel.close().whenFailure { error in + XCTFail("unexpected error: \(error)") + } + return .continue + } else { + return .needMoreData + } + } + + mutating func decodeLast(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { + ctx.fireChannelRead(self.wrapInboundOut(buffer)) + return .needMoreData + } + } + let channel = EmbeddedChannel(handler: ByteToMessageHandler(Take16BytesThenCloseAndPassOnDecoder())) + var buffer = channel.allocator.buffer(capacity: 16) + buffer.write(staticString: "0123456789abcdefQWER") + XCTAssertNoThrow(try channel.writeInbound(buffer)) + + XCTAssertEqual("0123456789abcdef", (channel.readInbound() as ByteBuffer?).map { String(decoding: $0.readableBytesView, as: Unicode.UTF8.self)}) + XCTAssertEqual("QWER", (channel.readInbound() as ByteBuffer?).map { String(decoding: $0.readableBytesView, as: Unicode.UTF8.self)}) + XCTAssertNil(channel.readInbound()) + } + } public class MessageToByteEncoderTest: XCTestCase { @@ -378,3 +575,30 @@ public class MessageToByteEncoderTest: XCTestCase { } } + +private class PairOfBytesDecoder: ByteToMessageDecoder { + typealias InboundOut = ByteBuffer + + private let lastPromise: EventLoopPromise + private var decodeLastCalls = 0 + + init(lastPromise: EventLoopPromise) { + self.lastPromise = lastPromise + } + + func decode(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { + if let slice = buffer.readSlice(length: 2) { + ctx.fireChannelRead(self.wrapInboundOut(slice)) + return .continue + } else { + return .needMoreData + } + } + + func decodeLast(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { + self.decodeLastCalls += 1 + XCTAssertEqual(1, self.decodeLastCalls) + self.lastPromise.succeed(result: buffer) + return .needMoreData + } +} diff --git a/Tests/NIOWebSocketTests/EndToEndTests.swift b/Tests/NIOWebSocketTests/EndToEndTests.swift index b305f89df..af5da5c9e 100644 --- a/Tests/NIOWebSocketTests/EndToEndTests.swift +++ b/Tests/NIOWebSocketTests/EndToEndTests.swift @@ -13,7 +13,7 @@ //===----------------------------------------------------------------------===// import XCTest -import NIO +@testable import NIO import NIOHTTP1 @testable import NIOWebSocket @@ -397,8 +397,8 @@ class EndToEndTests: XCTestCase { expectedResponseLine: "HTTP/1.1 101 Switching Protocols", expectedResponseHeaders: ["Upgrade: websocket", "Sec-WebSocket-Accept: OfS0wDaT5NoxF2gqm7Zj2YtetzM=", "Connection: upgrade"]) - let decoder = (try server.pipeline.context(handlerType: WebSocketFrameDecoder.self).wait()).handler as! WebSocketFrameDecoder - XCTAssertEqual(16, decoder.maxFrameSize) + let decoder = ((try server.pipeline.context(handlerType: ByteToMessageHandler.self).wait()).handler as! ByteToMessageHandler).decoder + XCTAssertEqual(16, decoder?.maxFrameSize) } func testAutomaticErrorHandling() throws { diff --git a/Tests/NIOWebSocketTests/WebSocketFrameDecoderTest.swift b/Tests/NIOWebSocketTests/WebSocketFrameDecoderTest.swift index 6afb3c404..4c1ae67a4 100644 --- a/Tests/NIOWebSocketTests/WebSocketFrameDecoderTest.swift +++ b/Tests/NIOWebSocketTests/WebSocketFrameDecoderTest.swift @@ -65,7 +65,7 @@ public class WebSocketFrameDecoderTest: XCTestCase { self.decoderChannel = EmbeddedChannel() self.encoderChannel = EmbeddedChannel() self.buffer = decoderChannel.allocator.buffer(capacity: 128) - XCTAssertNoThrow(try self.decoderChannel.pipeline.add(handler: WebSocketFrameDecoder()).wait()) + XCTAssertNoThrow(try self.decoderChannel.pipeline.add(handler: ByteToMessageHandler(WebSocketFrameDecoder())).wait()) XCTAssertNoThrow(try self.encoderChannel.pipeline.add(handler: WebSocketFrameEncoder()).wait()) } @@ -103,7 +103,7 @@ public class WebSocketFrameDecoderTest: XCTestCase { private func swapDecoder(for handler: ChannelHandler) { // We need to insert a decoder that doesn't do error handling. We still insert // an encoder because we want to fail gracefully if a frame is written. - XCTAssertNoThrow(try self.decoderChannel.pipeline.context(handlerType: WebSocketFrameDecoder.self).then { + XCTAssertNoThrow(try self.decoderChannel.pipeline.context(handlerType: ByteToMessageHandler.self).then { self.decoderChannel.pipeline.remove(handler: $0.handler) }.then { (_: Bool) in self.decoderChannel.pipeline.add(handler: handler) @@ -160,7 +160,7 @@ public class WebSocketFrameDecoderTest: XCTestCase { // We need a new decoder channel here, because the max length would otherwise trigger an error. _ = try! self.decoderChannel.finish() self.decoderChannel = EmbeddedChannel() - XCTAssertNoThrow(try self.decoderChannel.pipeline.add(handler: WebSocketFrameDecoder(maxFrameSize: 80000)).wait()) + XCTAssertNoThrow(try self.decoderChannel.pipeline.add(handler: ByteToMessageHandler(WebSocketFrameDecoder(maxFrameSize: 80000))).wait()) self.buffer.write(bytes: Array(repeating: UInt8(4), count: 66000)) let frame = WebSocketFrame(fin: true, @@ -344,7 +344,7 @@ public class WebSocketFrameDecoderTest: XCTestCase { public func testDecoderRejectsOverlongFramesWithNoAutomaticErrorHandling() throws { // We need to insert a decoder that doesn't do error handling. We still insert // an encoder because we want to fail gracefully if a frame is written. - self.swapDecoder(for: WebSocketFrameDecoder(automaticErrorHandling: false)) + self.swapDecoder(for: ByteToMessageHandler(WebSocketFrameDecoder(automaticErrorHandling: false))) XCTAssertNoThrow(try self.decoderChannel.pipeline.add(handler: WebSocketFrameEncoder(), first: true).wait()) // A fake frame header that claims that the length of the frame is 16385 bytes, @@ -368,7 +368,7 @@ public class WebSocketFrameDecoderTest: XCTestCase { public func testDecoderRejectsFragmentedControlFramesWithNoAutomaticErrorHandling() throws { // We need to insert a decoder that doesn't do error handling. We still insert // an encoder because we want to fail gracefully if a frame is written. - self.swapDecoder(for: WebSocketFrameDecoder(automaticErrorHandling: false)) + self.swapDecoder(for: ByteToMessageHandler(WebSocketFrameDecoder(automaticErrorHandling: false))) XCTAssertNoThrow(try self.decoderChannel.pipeline.add(handler: WebSocketFrameEncoder(), first: true).wait()) // A fake frame header that claims this is a fragmented ping frame. @@ -391,7 +391,7 @@ public class WebSocketFrameDecoderTest: XCTestCase { public func testDecoderRejectsMultibyteControlFrameLengthsWithNoAutomaticErrorHandling() throws { // We need to insert a decoder that doesn't do error handling. We still insert // an encoder because we want to fail gracefully if a frame is written. - self.swapDecoder(for: WebSocketFrameDecoder(automaticErrorHandling: false)) + self.swapDecoder(for: ByteToMessageHandler(WebSocketFrameDecoder(automaticErrorHandling: false))) XCTAssertNoThrow(try self.decoderChannel.pipeline.add(handler: WebSocketFrameEncoder(), first: true).wait()) // A fake frame header that claims this is a ping frame with 126 bytes of data. @@ -414,7 +414,7 @@ public class WebSocketFrameDecoderTest: XCTestCase { func testIgnoresFurtherDataAfterRejectedFrameWithNoAutomaticErrorHandling() throws { // We need to insert a decoder that doesn't do error handling. We still insert // an encoder because we want to fail gracefully if a frame is written. - self.swapDecoder(for: WebSocketFrameDecoder(automaticErrorHandling: false)) + self.swapDecoder(for: ByteToMessageHandler(WebSocketFrameDecoder(automaticErrorHandling: false))) XCTAssertNoThrow(try self.decoderChannel.pipeline.add(handler: WebSocketFrameEncoder(), first: true).wait()) // A fake frame header that claims this is a fragmented ping frame. @@ -446,7 +446,7 @@ public class WebSocketFrameDecoderTest: XCTestCase { public func testDecoderRejectsOverlongFramesWithSeparateErrorHandling() throws { // We need to insert a decoder that doesn't do error handling, and then a separate error // handler. - self.swapDecoder(for: WebSocketFrameDecoder(automaticErrorHandling: false)) + self.swapDecoder(for: ByteToMessageHandler(WebSocketFrameDecoder(automaticErrorHandling: false))) XCTAssertNoThrow(try self.decoderChannel.pipeline.add(handler: WebSocketFrameEncoder(), first: true).wait()) XCTAssertNoThrow(try self.decoderChannel.pipeline.add(handler: WebSocketProtocolErrorHandler()).wait()) @@ -471,7 +471,7 @@ public class WebSocketFrameDecoderTest: XCTestCase { public func testDecoderRejectsFragmentedControlFramesWithSeparateErrorHandling() throws { // We need to insert a decoder that doesn't do error handling, and then a separate error // handler. - self.swapDecoder(for: WebSocketFrameDecoder(automaticErrorHandling: false)) + self.swapDecoder(for: ByteToMessageHandler(WebSocketFrameDecoder(automaticErrorHandling: false))) XCTAssertNoThrow(try self.decoderChannel.pipeline.add(handler: WebSocketFrameEncoder(), first: true).wait()) XCTAssertNoThrow(try self.decoderChannel.pipeline.add(handler: WebSocketProtocolErrorHandler()).wait()) @@ -495,7 +495,7 @@ public class WebSocketFrameDecoderTest: XCTestCase { public func testDecoderRejectsMultibyteControlFrameLengthsWithSeparateErrorHandling() throws { // We need to insert a decoder that doesn't do error handling, and then a separate error // handler. - self.swapDecoder(for: WebSocketFrameDecoder(automaticErrorHandling: false)) + self.swapDecoder(for: ByteToMessageHandler(WebSocketFrameDecoder(automaticErrorHandling: false))) XCTAssertNoThrow(try self.decoderChannel.pipeline.add(handler: WebSocketFrameEncoder(), first: true).wait()) XCTAssertNoThrow(try self.decoderChannel.pipeline.add(handler: WebSocketProtocolErrorHandler()).wait()) @@ -520,7 +520,7 @@ public class WebSocketFrameDecoderTest: XCTestCase { let swallower = CloseSwallower() // We need to insert a decoder that doesn't do error handling, and then a separate error // handler. - self.swapDecoder(for: WebSocketFrameDecoder(automaticErrorHandling: false)) + self.swapDecoder(for: ByteToMessageHandler(WebSocketFrameDecoder(automaticErrorHandling: false))) XCTAssertNoThrow(try self.decoderChannel.pipeline.add(handler: WebSocketFrameEncoder(), first: true).wait()) XCTAssertNoThrow(try self.decoderChannel.pipeline.add(handler: WebSocketProtocolErrorHandler()).wait()) XCTAssertNoThrow(try self.decoderChannel.pipeline.add(handler: swallower, first: true).wait()) diff --git a/docs/public-api-changes-NIO1-to-NIO2.md b/docs/public-api-changes-NIO1-to-NIO2.md index d8674fae0..094248d57 100644 --- a/docs/public-api-changes-NIO1-to-NIO2.md +++ b/docs/public-api-changes-NIO1-to-NIO2.md @@ -4,4 +4,7 @@ - made `EventLoopGroup.makeIterator()` a required method - `TimeAmount.Value` is now `Int64` (from `Int` on 64 bit platforms, no change for 32 bit platforms) +- `ByteToMessageDecoder`s now need to be wrapped in `ByteToMessageHandler` + before they can be added to the pipeline. + before: `pipeline.add(MyDecoder())`, after: `pipeline.add(ByteToMessageHandler(MyDecoder()))`