diff --git a/Sources/NIO/Channel.swift b/Sources/NIO/Channel.swift index 9febc9e92..4e1488ad6 100644 --- a/Sources/NIO/Channel.swift +++ b/Sources/NIO/Channel.swift @@ -341,6 +341,9 @@ public enum ChannelError: Error { /// An operation that was inappropriate given the current `Channel` state was attempted. case inappropriateOperationForState + + /// An attempt was made to remove a ChannelHandler that is not removable. + case unremovableHandler } extension ChannelError: Equatable { } diff --git a/Sources/NIO/ChannelHandler.swift b/Sources/NIO/ChannelHandler.swift index 7369b5296..341260cd4 100644 --- a/Sources/NIO/ChannelHandler.swift +++ b/Sources/NIO/ChannelHandler.swift @@ -309,3 +309,37 @@ extension _ChannelInboundHandler { } } +/// A `RemovableChannelHandler` is a `ChannelHandler` that can be dynamically removed from a `ChannelPipeline` whilst +/// the `Channel` is operating normally. +/// A `RemovableChannelHandler` is required to remove itself from the `ChannelPipline` (using +/// `ChannelHandlerContext.removeHandler`) as soon as possible. +/// +/// - note: When a `Channel` gets torn down, every `ChannelHandler` in the `Channel`'s `ChannelPipeline` will be +/// removed from the `ChannelPipeline`. Those removals however happen synchronously and are not going through +/// the methods of this protocol. +public protocol RemovableChannelHandler: ChannelHandler { + /// Ask the receiving `RemovableChannelHandler` to remove itself from the `ChannelPipeline` as soon as possible. + /// The receiving `RemovableChannelHandler` may elect to remove itself sometime after this method call, rather than + /// immediately, but if it does so it must take the necessary precautions to handle events arriving between the + /// invocation of this method and the call to `ChannelHandlerContext.removeHandler` that triggers the actual + /// removal. + /// + /// - note: Like the other `ChannelHandler` methods, this method should not be invoked by the user directly. To + /// remove a `RemovableChannelHandler` from the `ChannelPipeline`, use `ChannelPipeline.remove`. + /// + /// - parameters: + /// - ctx: The `ChannelHandlerContext` of the `RemovableChannelHandler` to be removed from the `ChannelPipeline`. + /// - removalToken: The removal token to hand to `ChannelHandlerContext.removeHandler` to trigger the actual + /// removal from the `ChannelPipeline`. + func removeHandler(ctx: ChannelHandlerContext, removalToken: ChannelHandlerContext.RemovalToken) +} + +extension RemovableChannelHandler { + // Implements the default behaviour which is to synchronously remove the handler from the pipeline. Thanks to this, + // stateless `ChannelHandler`s can just use `RemovableChannelHandler` as a marker-protocol and declare themselves + // as removable without writing any extra code. + public func removeHandler(ctx: ChannelHandlerContext, removalToken: ChannelHandlerContext.RemovalToken) { + precondition(ctx.handler === self) + ctx.leavePipeline(removalToken: removalToken) + } +} diff --git a/Sources/NIO/ChannelPipeline.swift b/Sources/NIO/ChannelPipeline.swift index 403069ebf..38181b2cf 100644 --- a/Sources/NIO/ChannelPipeline.swift +++ b/Sources/NIO/ChannelPipeline.swift @@ -355,8 +355,8 @@ public final class ChannelPipeline: ChannelInvoker { /// - parameters: /// - handler: the `ChannelHandler` to remove. /// - returns: the `EventLoopFuture` which will be notified once the `ChannelHandler` was removed. - public func remove(handler: ChannelHandler) -> EventLoopFuture { - let promise = self.eventLoop.makePromise(of: Bool.self) + public func remove(handler: RemovableChannelHandler) -> EventLoopFuture { + let promise = self.eventLoop.makePromise(of: Void.self) self.remove(handler: handler, promise: promise) return promise.futureResult } @@ -366,8 +366,8 @@ public final class ChannelPipeline: ChannelInvoker { /// - parameters: /// - name: the name that was used to add the `ChannelHandler` to the `ChannelPipeline` before. /// - returns: the `EventLoopFuture` which will be notified once the `ChannelHandler` was removed. - public func remove(name: String) -> EventLoopFuture { - let promise = self.eventLoop.makePromise(of: Bool.self) + public func remove(name: String) -> EventLoopFuture { + let promise = self.eventLoop.makePromise(of: Void.self) self.remove(name: name, promise: promise) return promise.futureResult } @@ -377,8 +377,8 @@ public final class ChannelPipeline: ChannelInvoker { /// - parameters: /// - ctx: the `ChannelHandlerContext` that belongs to `ChannelHandler` that should be removed. /// - returns: the `EventLoopFuture` which will be notified once the `ChannelHandler` was removed. - public func remove(ctx: ChannelHandlerContext) -> EventLoopFuture { - let promise = self.eventLoop.makePromise(of: Bool.self) + public func remove(ctx: ChannelHandlerContext) -> EventLoopFuture { + let promise = self.eventLoop.makePromise(of: Void.self) self.remove(ctx: ctx, promise: promise) return promise.futureResult } @@ -388,7 +388,7 @@ public final class ChannelPipeline: ChannelInvoker { /// - parameters: /// - handler: the `ChannelHandler` to remove. /// - promise: An `EventLoopPromise` that will complete when the `ChannelHandler` is removed. - public func remove(handler: ChannelHandler, promise: EventLoopPromise?) { + public func remove(handler: RemovableChannelHandler, promise: EventLoopPromise?) { let contextFuture = self.context0 { return $0.handler === handler }.map { ctx in @@ -403,7 +403,7 @@ public final class ChannelPipeline: ChannelInvoker { /// - parameters: /// - name: the name that was used to add the `ChannelHandler` to the `ChannelPipeline` before. /// - promise: An `EventLoopPromise` that will complete when the `ChannelHandler` is removed. - public func remove(name: String, promise: EventLoopPromise?) { + public func remove(name: String, promise: EventLoopPromise?) { let contextFuture = self.context0 { $0.name == name }.map { ctx in @@ -418,12 +418,16 @@ public final class ChannelPipeline: ChannelInvoker { /// - parameters: /// - ctx: the `ChannelHandlerContext` that belongs to `ChannelHandler` that should be removed. /// - promise: An `EventLoopPromise` that will complete when the `ChannelHandler` is removed. - public func remove(ctx: ChannelHandlerContext, promise: EventLoopPromise?) { + public func remove(ctx: ChannelHandlerContext, promise: EventLoopPromise?) { + guard let handler = ctx.handler as? RemovableChannelHandler else { + promise?.fail(ChannelError.unremovableHandler) + return + } if self.eventLoop.inEventLoop { - self.remove0(ctx: ctx, promise: promise) + handler.removeHandler(ctx: ctx, removalToken: .init(promise: promise)) } else { self.eventLoop.execute { - self.remove0(ctx: ctx, promise: promise) + handler.removeHandler(ctx: ctx, removalToken: .init(promise: promise)) } } } @@ -500,7 +504,7 @@ public final class ChannelPipeline: ChannelInvoker { } /// Remove a `ChannelHandlerContext` from the `ChannelPipeline`. Must only be called from within the `EventLoop`. - private func remove0(ctx: ChannelHandlerContext, promise: EventLoopPromise?) { + internal func remove0(ctx: ChannelHandlerContext, promise: EventLoopPromise?) { self.eventLoop.assertInEventLoop() let nextCtx = ctx.next @@ -514,7 +518,7 @@ public final class ChannelPipeline: ChannelInvoker { do { try ctx.invokeHandlerRemoved() - promise?.succeed(true) + promise?.succeed(()) } catch let err { promise?.fail(err) } @@ -1471,6 +1475,27 @@ public final class ChannelHandlerContext: ChannelInvoker { } } +extension ChannelHandlerContext { + /// A `RemovalToken` is handed to a `RemovableChannelHandler` when its `removeHandler` function is invoked. A + /// `RemovableChannelHandler` is then required to remove itself from the `ChannelPipeline`. The removal process + /// is finalized by handing the `RemovalToken` to the `ChannelHandlerContext.leavePipeline` function. + public struct RemovalToken { + internal let promise: EventLoopPromise? + } + + /// Synchronously remove the `ChannelHandler` with the given `ChannelHandlerContext`. + /// + /// - note: This function must only be used from a `RemovableChannelHandler` to remove itself. Calling this method + /// on any other `ChannelHandlerContext` leads to undefined behaviour. + /// + /// - parameters: + /// - removalToken: The removal token received from `RemovableChannelHandler.removeHandler` + public func leavePipeline(removalToken: RemovalToken) { + self.eventLoop.preconditionInEventLoop() + self.pipeline.remove0(ctx: self, promise: removalToken.promise) + } +} + extension ChannelPipeline: CustomDebugStringConvertible { public var debugDescription: String { var desc = "ChannelPipeline (\(ObjectIdentifier(self))):\n" diff --git a/Sources/NIO/Codec.swift b/Sources/NIO/Codec.swift index 7045d3fdd..29f2c6c0e 100644 --- a/Sources/NIO/Codec.swift +++ b/Sources/NIO/Codec.swift @@ -251,6 +251,12 @@ public class ByteToMessageHandler { case last } + private enum RemovalState { + case notBeingRemoved + case removalStarted + case removalCompleted + } + private enum State { case active case leftoversNeedProcessing @@ -259,6 +265,7 @@ public class ByteToMessageHandler { 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 removalState: RemovalState = .notBeingRemoved private var buffer: B2MDBuffer = B2MDBuffer() public init(_ decoder: Decoder) { @@ -266,7 +273,8 @@ public class ByteToMessageHandler { } deinit { - assert(self.state == .done) + assert(self.removalState == .removalCompleted, "illegal state in deinit: removalState = \(self.removalState)") + assert(self.state == .done, "illegal state in deinit: state = \(self.state)") } } @@ -321,7 +329,7 @@ extension ByteToMessageHandler { } private func decodeLoop(ctx: ChannelHandlerContext, decodeMode: DecodeMode) throws -> B2MDBuffer.BufferProcessingResult { - while true { + while decodeMode == .last || self.removalState == .notBeingRemoved { let result = try self.withNextBuffer { decoder, buffer in if decodeMode == .normal { return try decoder.decode(ctx: ctx, buffer: &buffer) @@ -338,6 +346,7 @@ extension ByteToMessageHandler { return .cannotProcessReentrantly } } + return .didProcess(.continue) } } @@ -351,7 +360,10 @@ extension ByteToMessageHandler: ChannelInboundHandler { public func handlerRemoved(ctx: ChannelHandlerContext) { - self.processLeftovers(ctx: ctx) + // very likely, the removal state is `.notBeingRemoved` or `.removalCompleted` here but we can't assert it + // because the pipeline might be torn down during the formal removal process. + self.removalState = .removalCompleted + self.state = .done } /// Calls `decode` until there is nothing left to decode. @@ -430,3 +442,17 @@ extension MessageToByteEncoder { return ctx.channel.allocator.buffer(capacity: 256) } } + +extension ByteToMessageHandler: RemovableChannelHandler { + public func removeHandler(ctx: ChannelHandlerContext, removalToken: ChannelHandlerContext.RemovalToken) { + precondition(self.removalState == .notBeingRemoved) + self.removalState = .removalStarted + ctx.eventLoop.execute { + self.processLeftovers(ctx: ctx) + assert(self.state != .leftoversNeedProcessing) + assert(self.removalState == .removalStarted) + self.removalState = .removalCompleted + ctx.leavePipeline(removalToken: removalToken) + } + } +} diff --git a/Sources/NIOHTTP1/HTTPDecoder.swift b/Sources/NIOHTTP1/HTTPDecoder.swift index 0f566f146..dd1836306 100644 --- a/Sources/NIOHTTP1/HTTPDecoder.swift +++ b/Sources/NIOHTTP1/HTTPDecoder.swift @@ -143,7 +143,7 @@ private protocol AnyHTTPDecoder: class { /// `ChannelPipeline` than the `HTTPResponseEncoder`. /// /// Rather than set this up manually, consider using `ChannelPipeline.addHTTPServerHandlers`. -public final class HTTPRequestDecoder: HTTPDecoder { +public final class HTTPRequestDecoder: HTTPDecoder, RemovableChannelHandler { public convenience init() { self.init(leftOverBytesStrategy: .dropBytes) } diff --git a/Sources/NIOHTTP1/HTTPEncoder.swift b/Sources/NIOHTTP1/HTTPEncoder.swift index 2f70cae1a..beb94bebb 100644 --- a/Sources/NIOHTTP1/HTTPEncoder.swift +++ b/Sources/NIOHTTP1/HTTPEncoder.swift @@ -161,7 +161,7 @@ public final class HTTPRequestEncoder: ChannelOutboundHandler { /// /// This channel handler is used to translate messages from a series of /// `HTTPServerResponsePart` into the HTTP/1.1 wire format. -public final class HTTPResponseEncoder: ChannelOutboundHandler { +public final class HTTPResponseEncoder: ChannelOutboundHandler, RemovableChannelHandler { public typealias OutboundIn = HTTPServerResponsePart public typealias OutboundOut = IOData diff --git a/Sources/NIOHTTP1/HTTPPipelineSetup.swift b/Sources/NIOHTTP1/HTTPPipelineSetup.swift index 17619d4e4..870e080ce 100644 --- a/Sources/NIOHTTP1/HTTPPipelineSetup.swift +++ b/Sources/NIOHTTP1/HTTPPipelineSetup.swift @@ -64,7 +64,7 @@ public extension ChannelPipeline { let responseEncoder = HTTPResponseEncoder() let requestDecoder = HTTPRequestDecoder(leftOverBytesStrategy: upgrade == nil ? .dropBytes : .forwardBytes) - var handlers: [ChannelHandler] = [responseEncoder, requestDecoder] + var handlers: [RemovableChannelHandler] = [responseEncoder, requestDecoder] if pipelining { handlers.append(HTTPServerPipelineHandler()) diff --git a/Sources/NIOHTTP1/HTTPServerPipelineHandler.swift b/Sources/NIOHTTP1/HTTPServerPipelineHandler.swift index 3528c12fb..195a7d81a 100644 --- a/Sources/NIOHTTP1/HTTPServerPipelineHandler.swift +++ b/Sources/NIOHTTP1/HTTPServerPipelineHandler.swift @@ -57,7 +57,7 @@ internal func debugOnly(_ body: () -> Void) { /// or during a request body upload, it will be delivered immediately. If a half-close is /// received immediately after `HTTPServerRequestPart.end`, it will also be passed along /// immediately, allowing this signal to be seen by the HTTP server as early as possible. -public final class HTTPServerPipelineHandler: ChannelDuplexHandler { +public final class HTTPServerPipelineHandler: ChannelDuplexHandler, RemovableChannelHandler { public typealias InboundIn = HTTPServerRequestPart public typealias InboundOut = HTTPServerRequestPart public typealias OutboundIn = HTTPServerResponsePart diff --git a/Sources/NIOHTTP1/HTTPServerProtocolErrorHandler.swift b/Sources/NIOHTTP1/HTTPServerProtocolErrorHandler.swift index 4cc7db3ba..7aeaa05a6 100644 --- a/Sources/NIOHTTP1/HTTPServerProtocolErrorHandler.swift +++ b/Sources/NIOHTTP1/HTTPServerProtocolErrorHandler.swift @@ -21,7 +21,7 @@ import NIO /// servers want. This handler does not suppress the parser errors: it allows them to /// continue to pass through the pipeline so that other handlers (e.g. logging ones) can /// deal with the error. -public final class HTTPServerProtocolErrorHandler: ChannelDuplexHandler { +public final class HTTPServerProtocolErrorHandler: ChannelDuplexHandler, RemovableChannelHandler { public typealias InboundIn = HTTPServerRequestPart public typealias InboundOut = HTTPServerRequestPart public typealias OutboundIn = HTTPServerResponsePart diff --git a/Sources/NIOHTTP1/HTTPUpgradeHandler.swift b/Sources/NIOHTTP1/HTTPUpgradeHandler.swift index 083016874..0e6d12564 100644 --- a/Sources/NIOHTTP1/HTTPUpgradeHandler.swift +++ b/Sources/NIOHTTP1/HTTPUpgradeHandler.swift @@ -59,7 +59,7 @@ public protocol HTTPServerProtocolUpgrader { /// sufficiently difficult to ensure that the upgrade happens at a safe time while dealing with pipelined /// requests that we choose to punt on it entirely and not allow it. As it happens this is mostly fine: /// the odds of someone needing to upgrade midway through the lifetime of a connection are very low. -public class HTTPServerUpgradeHandler: ChannelInboundHandler { +public class HTTPServerUpgradeHandler: ChannelInboundHandler, RemovableChannelHandler { public typealias InboundIn = HTTPServerRequestPart public typealias InboundOut = HTTPServerRequestPart public typealias OutboundOut = HTTPServerResponsePart @@ -68,7 +68,7 @@ public class HTTPServerUpgradeHandler: ChannelInboundHandler { private let upgradeCompletionHandler: (ChannelHandlerContext) -> Void private let httpEncoder: HTTPResponseEncoder? - private let extraHTTPHandlers: [ChannelHandler] + private let extraHTTPHandlers: [RemovableChannelHandler] /// Whether we've already seen the first request. private var seenFirstRequest = false @@ -88,7 +88,7 @@ public class HTTPServerUpgradeHandler: ChannelInboundHandler { /// this should include the `HTTPDecoder`, but should also include any other handler that cannot tolerate /// receiving non-HTTP data. /// - Parameter upgradeCompletionHandler: A block that will be fired when HTTP upgrade is complete. - public init(upgraders: [HTTPServerProtocolUpgrader], httpEncoder: HTTPResponseEncoder, extraHTTPHandlers: [ChannelHandler], upgradeCompletionHandler: @escaping (ChannelHandlerContext) -> Void) { + public init(upgraders: [HTTPServerProtocolUpgrader], httpEncoder: HTTPResponseEncoder, extraHTTPHandlers: [RemovableChannelHandler], upgradeCompletionHandler: @escaping (ChannelHandlerContext) -> Void) { var upgraderMap = [String: HTTPServerProtocolUpgrader]() for upgrader in upgraders { upgraderMap[upgrader.supportedProtocol.lowercased()] = upgrader @@ -189,7 +189,7 @@ public class HTTPServerUpgradeHandler: ChannelInboundHandler { self.sendUpgradeResponse(ctx: ctx, upgradeRequest: request, responseHeaders: responseHeaders) }.flatMap { self.removeHandler(ctx: ctx, handler: self.httpEncoder) - }.map { (_: Bool) in + }.map { self.upgradeCompletionHandler(ctx) }.flatMap { upgrader.upgrade(ctx: ctx, upgradeRequest: request) @@ -235,11 +235,11 @@ public class HTTPServerUpgradeHandler: ChannelInboundHandler { } /// Removes the given channel handler from the channel pipeline. - private func removeHandler(ctx: ChannelHandlerContext, handler: ChannelHandler?) -> EventLoopFuture { + private func removeHandler(ctx: ChannelHandlerContext, handler: RemovableChannelHandler?) -> EventLoopFuture { if let handler = handler { return ctx.pipeline.remove(handler: handler) } else { - return ctx.eventLoop.makeSucceededFuture(true) + return ctx.eventLoop.makeSucceededFuture(()) } } @@ -249,7 +249,7 @@ public class HTTPServerUpgradeHandler: ChannelInboundHandler { return ctx.eventLoop.makeSucceededFuture(()) } - return .andAllSucceed(self.extraHTTPHandlers.map { ctx.pipeline.remove(handler: $0).map { (_: Bool) in () }}, + return .andAllSucceed(self.extraHTTPHandlers.map { ctx.pipeline.remove(handler: $0) }, on: ctx.eventLoop) } } diff --git a/Sources/NIOTLS/ApplicationProtocolNegotiationHandler.swift b/Sources/NIOTLS/ApplicationProtocolNegotiationHandler.swift index dcff5b22d..e9dbad45b 100644 --- a/Sources/NIOTLS/ApplicationProtocolNegotiationHandler.swift +++ b/Sources/NIOTLS/ApplicationProtocolNegotiationHandler.swift @@ -56,7 +56,7 @@ public enum ALPNResult: Equatable { /// down the channel. Then, finally, this channel handler will automatically remove /// itself from the channel pipeline, leaving the pipeline in its final /// configuration. -public class ApplicationProtocolNegotiationHandler: ChannelInboundHandler { +public class ApplicationProtocolNegotiationHandler: ChannelInboundHandler, RemovableChannelHandler { public typealias InboundIn = Any public typealias InboundOut = Any diff --git a/Sources/NIOWebSocketServer/main.swift b/Sources/NIOWebSocketServer/main.swift index ab4559652..e4ca76a04 100644 --- a/Sources/NIOWebSocketServer/main.swift +++ b/Sources/NIOWebSocketServer/main.swift @@ -40,7 +40,7 @@ let websocketResponse = """ """ -private final class HTTPHandler: ChannelInboundHandler { +private final class HTTPHandler: ChannelInboundHandler, RemovableChannelHandler { typealias InboundIn = HTTPServerRequestPart typealias OutboundOut = HTTPServerResponsePart @@ -216,8 +216,8 @@ let bootstrap = ServerBootstrap(group: group) .childChannelInitializer { channel in let httpHandler = HTTPHandler() let config: HTTPUpgradeConfiguration = ( - upgraders: [ upgrader ], - completionHandler: { _ in + upgraders: [ upgrader ], + completionHandler: { _ in channel.pipeline.remove(handler: httpHandler, promise: nil) } ) diff --git a/Tests/NIOHTTP1Tests/HTTPDecoderTest.swift b/Tests/NIOHTTP1Tests/HTTPDecoderTest.swift index ce13d8637..fea77aa8b 100644 --- a/Tests/NIOHTTP1Tests/HTTPDecoderTest.swift +++ b/Tests/NIOHTTP1Tests/HTTPDecoderTest.swift @@ -278,7 +278,7 @@ class HTTPDecoderTest: XCTestCase { } } - class Receiver: ChannelInboundHandler { + class Receiver: ChannelInboundHandler, RemovableChannelHandler { typealias InboundIn = HTTPServerRequestPart let collector = ByteCollector() @@ -329,7 +329,7 @@ class HTTPDecoderTest: XCTestCase { } } - class Reciever: ChannelInboundHandler { + class Reciever: ChannelInboundHandler, RemovableChannelHandler { typealias InboundIn = HTTPClientResponsePart typealias InboundOut = HTTPClientResponsePart typealias OutboundOut = HTTPClientRequestPart diff --git a/Tests/NIOTests/AcceptBackoffHandlerTest.swift b/Tests/NIOTests/AcceptBackoffHandlerTest.swift index cae72fcf7..9008667d5 100644 --- a/Tests/NIOTests/AcceptBackoffHandlerTest.swift +++ b/Tests/NIOTests/AcceptBackoffHandlerTest.swift @@ -95,7 +95,7 @@ public class AcceptBackoffHandlerTest: XCTestCase { return readCountHandler.readCount }.wait()) - XCTAssertTrue(try serverChannel.pipeline.remove(name: acceptHandlerName).wait()) + XCTAssertNoThrow(try serverChannel.pipeline.remove(name: acceptHandlerName).wait()) if read { // Removal should have triggered a read. diff --git a/Tests/NIOTests/ChannelPipelineTest+XCTest.swift b/Tests/NIOTests/ChannelPipelineTest+XCTest.swift index c09840865..b310dcd3e 100644 --- a/Tests/NIOTests/ChannelPipelineTest+XCTest.swift +++ b/Tests/NIOTests/ChannelPipelineTest+XCTest.swift @@ -52,6 +52,7 @@ extension ChannelPipelineTest { ("testRemovingByReferenceWithPromiseStillInChannel", testRemovingByReferenceWithPromiseStillInChannel), ("testRemovingByReferenceWithFutureNotInChannel", testRemovingByReferenceWithFutureNotInChannel), ("testFireChannelReadInInactiveChannelDoesNotCrash", testFireChannelReadInInactiveChannelDoesNotCrash), + ("testTeardownDuringFormalRemovalProcess", testTeardownDuringFormalRemovalProcess), ] } } diff --git a/Tests/NIOTests/ChannelPipelineTest.swift b/Tests/NIOTests/ChannelPipelineTest.swift index 302593496..b0f3a4e8a 100644 --- a/Tests/NIOTests/ChannelPipelineTest.swift +++ b/Tests/NIOTests/ChannelPipelineTest.swift @@ -171,7 +171,7 @@ class ChannelPipelineTest: XCTestCase { } } - private final class FireChannelReadOnRemoveHandler: ChannelInboundHandler { + private final class FireChannelReadOnRemoveHandler: ChannelInboundHandler, RemovableChannelHandler { typealias InboundIn = Never typealias InboundOut = Int @@ -330,7 +330,7 @@ class ChannelPipelineTest: XCTestCase { } func testChannelInfrastructureIsNotLeaked() throws { - class SomeHandler: ChannelInboundHandler { + class SomeHandler: ChannelInboundHandler, RemovableChannelHandler { typealias InboundIn = Never let body: (ChannelHandlerContext) -> Void @@ -347,7 +347,7 @@ class ChannelPipelineTest: XCTestCase { let channel = EmbeddedChannel() let loop = channel.eventLoop as! EmbeddedEventLoop - weak var weakHandler1: ChannelHandler? + weak var weakHandler1: RemovableChannelHandler? weak var weakHandler2: ChannelHandler? weak var weakHandlerContext1: ChannelHandlerContext? weak var weakHandlerContext2: ChannelHandlerContext? @@ -680,7 +680,7 @@ class ChannelPipelineTest: XCTestCase { } func testRemovingByContextWithPromiseStillInChannel() throws { - class NoOpHandler: ChannelInboundHandler { + class NoOpHandler: ChannelInboundHandler, RemovableChannelHandler { typealias InboundIn = Never } class DummyError: Error { } @@ -698,8 +698,8 @@ class ChannelPipelineTest: XCTestCase { var buffer = channel.allocator.buffer(capacity: 1024) buffer.write(staticString: "Hello, world!") - let removalPromise = channel.eventLoop.makePromise(of: Bool.self) - removalPromise.futureResult.whenSuccess { (_: Bool) in + let removalPromise = channel.eventLoop.makePromise(of: Void.self) + removalPromise.futureResult.whenSuccess { context.writeAndFlush(NIOAny(buffer), promise: nil) context.fireErrorCaught(DummyError()) } @@ -708,7 +708,12 @@ class ChannelPipelineTest: XCTestCase { XCTAssertNoThrow(try channel.throwIfErrorCaught()) channel.pipeline.remove(ctx: context, promise: removalPromise) - XCTAssertEqual(channel.readOutbound(), buffer) + XCTAssertNoThrow(try removalPromise.futureResult.wait()) + guard case .some(.byteBuffer(let receivedBuffer)) = channel.readOutbound(as: IOData.self) else { + XCTFail("No buffer") + return + } + XCTAssertEqual(receivedBuffer, buffer) do { try channel.throwIfErrorCaught() @@ -741,7 +746,7 @@ class ChannelPipelineTest: XCTestCase { XCTAssertNil(channel.readOutbound()) XCTAssertNoThrow(try channel.throwIfErrorCaught()) - channel.pipeline.remove(ctx: context).whenSuccess { (_: Bool) in + channel.pipeline.remove(ctx: context).whenSuccess { context.writeAndFlush(NIOAny(buffer), promise: nil) context.fireErrorCaught(DummyError()) } @@ -768,8 +773,8 @@ class ChannelPipelineTest: XCTestCase { var buffer = channel.allocator.buffer(capacity: 1024) buffer.write(staticString: "Hello, world!") - let removalPromise = channel.eventLoop.makePromise(of: Bool.self) - removalPromise.futureResult.whenSuccess { (_: Bool) in + let removalPromise = channel.eventLoop.makePromise(of: Void.self) + removalPromise.futureResult.whenSuccess { context.writeAndFlush(NIOAny(buffer), promise: nil) context.fireErrorCaught(DummyError()) } @@ -811,7 +816,7 @@ class ChannelPipelineTest: XCTestCase { XCTAssertNil(channel.readOutbound()) XCTAssertNoThrow(try channel.throwIfErrorCaught()) - channel.pipeline.remove(name: "TestHandler").whenSuccess { (_: Bool) in + channel.pipeline.remove(name: "TestHandler").whenSuccess { context.writeAndFlush(NIOAny(buffer), promise: nil) context.fireErrorCaught(DummyError()) } @@ -820,7 +825,7 @@ class ChannelPipelineTest: XCTestCase { } func testRemovingByReferenceWithPromiseStillInChannel() throws { - class NoOpHandler: ChannelInboundHandler { + class NoOpHandler: ChannelInboundHandler, RemovableChannelHandler { typealias InboundIn = Never } class DummyError: Error { } @@ -839,8 +844,8 @@ class ChannelPipelineTest: XCTestCase { var buffer = channel.allocator.buffer(capacity: 1024) buffer.write(staticString: "Hello, world!") - let removalPromise = channel.eventLoop.makePromise(of: Bool.self) - removalPromise.futureResult.whenSuccess { (_: Bool) in + let removalPromise = channel.eventLoop.makePromise(of: Void.self) + removalPromise.futureResult.whenSuccess { context.writeAndFlush(NIOAny(buffer), promise: nil) context.fireErrorCaught(DummyError()) } @@ -862,7 +867,7 @@ class ChannelPipelineTest: XCTestCase { } func testRemovingByReferenceWithFutureNotInChannel() throws { - class NoOpHandler: ChannelInboundHandler { + class NoOpHandler: ChannelInboundHandler, RemovableChannelHandler { typealias InboundIn = Never } class DummyError: Error { } @@ -883,7 +888,7 @@ class ChannelPipelineTest: XCTestCase { XCTAssertNil(channel.readOutbound()) XCTAssertNoThrow(try channel.throwIfErrorCaught()) - channel.pipeline.remove(handler: handler).whenSuccess { (_: Bool) in + channel.pipeline.remove(handler: handler).whenSuccess { context.writeAndFlush(NIOAny(buffer), promise: nil) context.fireErrorCaught(DummyError()) } @@ -917,4 +922,54 @@ class ChannelPipelineTest: XCTestCase { .wait()) XCTAssertNoThrow(try client.close().wait()) } + + func testTeardownDuringFormalRemovalProcess() { + class NeverCompleteRemovalHandler: ChannelInboundHandler, RemovableChannelHandler { + typealias InboundIn = Never + + private let removalTokenPromise: EventLoopPromise + private let handlerRemovedPromise: EventLoopPromise + + init(removalTokenPromise: EventLoopPromise, + handlerRemovedPromise: EventLoopPromise) { + self.removalTokenPromise = removalTokenPromise + self.handlerRemovedPromise = handlerRemovedPromise + } + + func handlerRemoved(ctx: ChannelHandlerContext) { + self.handlerRemovedPromise.succeed(()) + } + + func removeHandler(ctx: ChannelHandlerContext, removalToken: ChannelHandlerContext.RemovalToken) { + self.removalTokenPromise.succeed(removalToken) + } + } + + let eventLoop = EmbeddedEventLoop() + let removalTokenPromise = eventLoop.makePromise(of: ChannelHandlerContext.RemovalToken.self) + let handlerRemovedPromise = eventLoop.makePromise(of: Void.self) + + let channel = EmbeddedChannel(handler: NeverCompleteRemovalHandler(removalTokenPromise: removalTokenPromise, + handlerRemovedPromise: handlerRemovedPromise), + loop: eventLoop) + + // pretend we're real and connect + XCTAssertNoThrow(try channel.connect(to: .init(ipAddress: "1.2.3.4", port: 5)).wait()) + + // let's trigger the removal process + XCTAssertNoThrow(try channel.pipeline.context(handlerType: NeverCompleteRemovalHandler.self).map { handler in + channel.pipeline.remove(ctx: handler, promise: nil) + }.wait()) + + XCTAssertNoThrow(try removalTokenPromise.futureResult.map { removalToken in + // we know that the removal process has been started, so let's tear down the pipeline + func workaroundSR9815withAUselessFunction() { + XCTAssertNoThrow(XCTAssertFalse(try channel.finish())) + } + workaroundSR9815withAUselessFunction() + }.wait()) + + // verify that the handler has now been removed, despite the fact it should be mid-removal + XCTAssertNoThrow(try handlerRemovedPromise.futureResult.wait()) + } } diff --git a/Tests/NIOTests/CodecTest+XCTest.swift b/Tests/NIOTests/CodecTest+XCTest.swift index 6a8f52863..e35ebc3c1 100644 --- a/Tests/NIOTests/CodecTest+XCTest.swift +++ b/Tests/NIOTests/CodecTest+XCTest.swift @@ -38,6 +38,9 @@ extension ByteToMessageDecoderTest { ("testStructsWorkAsByteToMessageDecoders", testStructsWorkAsByteToMessageDecoders), ("testReentrantChannelReadWhileWholeBufferIsBeingProcessed", testReentrantChannelReadWhileWholeBufferIsBeingProcessed), ("testReentrantChannelCloseInChannelRead", testReentrantChannelCloseInChannelRead), + ("testHandlerRemoveInChannelRead", testHandlerRemoveInChannelRead), + ("testChannelCloseInChannelRead", testChannelCloseInChannelRead), + ("testDecodeLoopGetsInterruptedWhenRemovalIsTriggered", testDecodeLoopGetsInterruptedWhenRemovalIsTriggered), ] } } diff --git a/Tests/NIOTests/CodecTest.swift b/Tests/NIOTests/CodecTest.swift index 1a411c7e4..5be800ce2 100644 --- a/Tests/NIOTests/CodecTest.swift +++ b/Tests/NIOTests/CodecTest.swift @@ -374,7 +374,8 @@ public class ByteToMessageDecoderTest: XCTestCase { func testRemovingHandlerMakesLeftoversAppearInDecodeLast() { let lastPromise = EmbeddedEventLoop().makePromise(of: ByteBuffer.self) - let channel = EmbeddedChannel(handler: ByteToMessageHandler(PairOfBytesDecoder(lastPromise: lastPromise))) + let decoder = PairOfBytesDecoder(lastPromise: lastPromise) + let channel = EmbeddedChannel(handler: ByteToMessageHandler(decoder)) defer { XCTAssertNoThrow(XCTAssertFalse(try channel.finish())) } @@ -392,8 +393,6 @@ public class ByteToMessageDecoderTest: XCTestCase { channel.pipeline.context(handlerType: ByteToMessageHandler.self).flatMap { ctx in return channel.pipeline.remove(ctx: ctx) - }.map { - XCTAssertTrue($0) }.whenFailure { error in XCTFail("unexpected error: \(error)") } @@ -404,9 +403,11 @@ public class ByteToMessageDecoderTest: XCTestCase { XCTAssertEqual("78", channel.readInbound(as: ByteBuffer.self).map { String(decoding: $0.readableBytesView, as: Unicode.UTF8.self) }) XCTAssertEqual("90", channel.readInbound(as: ByteBuffer.self).map { String(decoding: $0.readableBytesView, as: Unicode.UTF8.self) }) XCTAssertNil(channel.readInbound()) + (channel.eventLoop as! EmbeddedEventLoop).run() XCTAssertNoThrow(XCTAssertEqual("x", String(decoding: try lastPromise.futureResult.wait().readableBytesView, as: Unicode.UTF8.self))) + XCTAssertEqual(1, decoder.decodeLastCalls) } func testStructsWorkAsByteToMessageDecoders() { @@ -521,6 +522,123 @@ public class ByteToMessageDecoderTest: XCTestCase { XCTAssertNil(channel.readInbound()) } + func testHandlerRemoveInChannelRead() { + struct Take16BytesThenCloseAndPassOnDecoder: ByteToMessageDecoder { + typealias InboundOut = ByteBuffer + + mutating func decode(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { + if let slice = buffer.readSlice(length: 16) { + ctx.fireChannelRead(self.wrapInboundOut(slice)) + ctx.pipeline.remove(ctx: ctx).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)}) + (channel.eventLoop as! EmbeddedEventLoop).run() + XCTAssertEqual("QWER", (channel.readInbound() as ByteBuffer?).map { String(decoding: $0.readableBytesView, as: Unicode.UTF8.self)}) + XCTAssertNil(channel.readInbound()) + } + + func testChannelCloseInChannelRead() { + struct Take16BytesThenCloseAndPassOnDecoder: ByteToMessageDecoder { + typealias InboundOut = ByteBuffer + + mutating func decode(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { + if let slice = buffer.readSlice(length: 16) { + ctx.fireChannelRead(self.wrapInboundOut(slice)) + ctx.close().whenFailure { error in + XCTFail("unexpected error: \(error)") + } + return .continue + } else { + return .needMoreData + } + } + + mutating func decodeLast(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { + return .needMoreData + } + } + class DoNotForwardChannelInactiveHandler: ChannelInboundHandler { + typealias InboundIn = Never + + func channelInactive(ctx: ChannelHandlerContext) { + // just eat this event + } + } + let channel = EmbeddedChannel(handler: ByteToMessageHandler(Take16BytesThenCloseAndPassOnDecoder())) + XCTAssertNoThrow(try channel.pipeline.add(handler: DoNotForwardChannelInactiveHandler(), first: true).wait()) + 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)}) + (channel.eventLoop as! EmbeddedEventLoop).run() + XCTAssertNil(channel.readInbound()) // no leftovers are forwarded + } + + func testDecodeLoopGetsInterruptedWhenRemovalIsTriggered() { + struct Decoder: ByteToMessageDecoder { + typealias InboundOut = String + + var callsToDecode = 0 + var callsToDecodeLast = 0 + + mutating func decode(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { + XCTAssertEqual(9, buffer.readableBytes) + self.callsToDecode += 1 + XCTAssertEqual(1, self.callsToDecode) + ctx.fireChannelRead(self.wrapInboundOut(String(decoding: buffer.readBytes(length: 1)!, + as: Unicode.UTF8.self))) + ctx.pipeline.remove(ctx: ctx).whenFailure { error in + XCTFail("unexpected error: \(error)") + } + return .continue + } + + mutating func decodeLast(ctx: ChannelHandlerContext, buffer: inout ByteBuffer) throws -> DecodingState { + self.callsToDecodeLast += 1 + XCTAssertLessThanOrEqual(self.callsToDecodeLast, 2) + ctx.fireChannelRead(self.wrapInboundOut(String(decoding: buffer.readBytes(length: 4) ?? + [ /* "no bytes" */ + 0x6e, 0x6f, 0x20, + 0x62, 0x79, 0x74, 0x65, 0x73], + as: Unicode.UTF8.self) + "#\(self.callsToDecodeLast)")) + return .continue + } + } + + let handler = ByteToMessageHandler(Decoder()) + let channel = EmbeddedChannel(handler: handler) + defer { + XCTAssertNoThrow(XCTAssertFalse(try channel.finish())) + } + + var buffer = channel.allocator.buffer(capacity: 9) + buffer.write(staticString: "012345678") + XCTAssertNoThrow(try channel.writeInbound(buffer)) + (channel.eventLoop as! EmbeddedEventLoop).run() + XCTAssertEqual(1, handler.decoder?.callsToDecode) + XCTAssertEqual(2, handler.decoder?.callsToDecodeLast) + ["0", "1234#1", "5678#2"].forEach { + XCTAssertEqual($0, channel.readInbound()) + } + } } public class MessageToByteEncoderTest: XCTestCase { @@ -580,7 +698,7 @@ private class PairOfBytesDecoder: ByteToMessageDecoder { typealias InboundOut = ByteBuffer private let lastPromise: EventLoopPromise - private var decodeLastCalls = 0 + var decodeLastCalls = 0 init(lastPromise: EventLoopPromise) { self.lastPromise = lastPromise diff --git a/Tests/NIOTests/TestUtils.swift b/Tests/NIOTests/TestUtils.swift index 462f97d38..3cff387f4 100644 --- a/Tests/NIOTests/TestUtils.swift +++ b/Tests/NIOTests/TestUtils.swift @@ -110,7 +110,7 @@ internal extension Channel { } } -final class ByteCountingHandler : ChannelInboundHandler { +final class ByteCountingHandler : ChannelInboundHandler, RemovableChannelHandler { typealias InboundIn = ByteBuffer private let numBytes: Int diff --git a/Tests/NIOWebSocketTests/WebSocketFrameDecoderTest.swift b/Tests/NIOWebSocketTests/WebSocketFrameDecoderTest.swift index 37055658f..b923a231a 100644 --- a/Tests/NIOWebSocketTests/WebSocketFrameDecoderTest.swift +++ b/Tests/NIOWebSocketTests/WebSocketFrameDecoderTest.swift @@ -16,7 +16,7 @@ import XCTest import NIO import NIOWebSocket -private class CloseSwallower: ChannelOutboundHandler { +private class CloseSwallower: ChannelOutboundHandler, RemovableChannelHandler { typealias OutboundIn = Any typealias OutboundOut = Any @@ -103,9 +103,15 @@ 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: ByteToMessageHandler.self).flatMap { - self.decoderChannel.pipeline.remove(handler: $0.handler) - }.flatMap { (_: Bool) in + XCTAssertNoThrow(try self.decoderChannel.pipeline.context(handlerType: ByteToMessageHandler.self).flatMapThrowing { + if let handler = $0.handler as? RemovableChannelHandler { + return handler + } else { + throw ChannelError.unremovableHandler + } + }.flatMap { + self.decoderChannel.pipeline.remove(handler: $0) + }.flatMap { self.decoderChannel.pipeline.add(handler: handler) }.wait()) } diff --git a/docker/docker-compose.1804.50.yaml b/docker/docker-compose.1804.50.yaml index e1fef4d04..9d64e7aed 100644 --- a/docker/docker-compose.1804.50.yaml +++ b/docker/docker-compose.1804.50.yaml @@ -20,7 +20,7 @@ services: image: swift-nio:18.04-5.0 environment: - MAX_ALLOCS_ALLOWED_1000_reqs_1_conn=36750 - - MAX_ALLOCS_ALLOWED_1_reqs_1000_conn=691050 + - MAX_ALLOCS_ALLOWED_1_reqs_1000_conn=692050 - MAX_ALLOCS_ALLOWED_ping_pong_1000_reqs_1_conn=4600 - MAX_ALLOCS_ALLOWED_bytebuffer_lots_of_rw=2100 - MAX_ALLOCS_ALLOWED_future_lots_of_callbacks=99100 @@ -30,7 +30,7 @@ services: command: /bin/bash -cl "swift test -Xswiftc -warnings-as-errors -Xswiftc -DNIO_CI_BUILD && ./scripts/integration_tests.sh" environment: - MAX_ALLOCS_ALLOWED_1000_reqs_1_conn=36750 - - MAX_ALLOCS_ALLOWED_1_reqs_1000_conn=691050 + - MAX_ALLOCS_ALLOWED_1_reqs_1000_conn=692050 - MAX_ALLOCS_ALLOWED_ping_pong_1000_reqs_1_conn=4600 - MAX_ALLOCS_ALLOWED_bytebuffer_lots_of_rw=2100 - MAX_ALLOCS_ALLOWED_future_lots_of_callbacks=99100 diff --git a/docs/public-api-changes-NIO1-to-NIO2.md b/docs/public-api-changes-NIO1-to-NIO2.md index 249fdb65d..d9c9c5d61 100644 --- a/docs/public-api-changes-NIO1-to-NIO2.md +++ b/docs/public-api-changes-NIO1-to-NIO2.md @@ -43,3 +43,4 @@ - `EventLoopFuture.cascade(promise: EventLoopPromise)` had its label changed to `EventLoopFuture.cascade(to: EventLoopPromise)` - `EventLoopFuture.cascadeFailure(promise: EventLoopPromise)` had its label changed to `EventLoopFuture.cascade(to: EventLoopPromise)` - renamed `EventLoopFuture.andAll(_:eventLoop:)` to `EventLoopFuture.andAllSucceed(_:on:)` +- all ChannelPipeline.remove(...) now return `EventLoopFuture` instead of `EventLoopFuture`