From 6e7a3de8e81bf612c92a82ebffe376f08f4d95ff Mon Sep 17 00:00:00 2001 From: Johannes Weiss Date: Tue, 12 Feb 2019 19:06:39 +0100 Subject: [PATCH] make all removals go through the RemovableChannelHandler API (#815) Motivation: Some of the ChannelPipeline removal methods did not go through the RemovableChannelHandler API. Modifications: make all removal APIs go through the RemovableChannelHandler API Result: fewer bugs --- Sources/NIO/ChannelHandlers.swift | 6 +- Sources/NIO/ChannelPipeline.swift | 18 +++-- Sources/NIOHTTP1/HTTPDecoder.swift | 2 +- Tests/NIOHTTP1Tests/HTTPDecoderTest.swift | 4 +- .../NIOTests/ChannelPipelineTest+XCTest.swift | 2 + Tests/NIOTests/ChannelPipelineTest.swift | 74 ++++++++++++++++++- .../WebSocketFrameDecoderTest.swift | 9 ++- 7 files changed, 97 insertions(+), 18 deletions(-) diff --git a/Sources/NIO/ChannelHandlers.swift b/Sources/NIO/ChannelHandlers.swift index 9cf8e212e..bd151297b 100644 --- a/Sources/NIO/ChannelHandlers.swift +++ b/Sources/NIO/ChannelHandlers.swift @@ -18,7 +18,7 @@ /// A `ChannelHandler` that implements a backoff for a `ServerChannel` when accept produces an `IOError`. /// These errors are often recoverable by reducing the rate at which we call accept. -public final class AcceptBackoffHandler: ChannelDuplexHandler { +public final class AcceptBackoffHandler: ChannelDuplexHandler, RemovableChannelHandler { public typealias InboundIn = Channel public typealias OutboundIn = Channel @@ -107,7 +107,7 @@ public final class AcceptBackoffHandler: ChannelDuplexHandler { ChannelHandler implementation which enforces back-pressure by stopping to read from the remote peer when it cannot write back fast enough. It will start reading again once pending data was written. */ -public class BackPressureHandler: ChannelDuplexHandler { +public class BackPressureHandler: ChannelDuplexHandler, RemovableChannelHandler { public typealias OutboundIn = NIOAny public typealias InboundIn = ByteBuffer public typealias InboundOut = ByteBuffer @@ -151,7 +151,7 @@ public class BackPressureHandler: ChannelDuplexHandler { } /// Triggers an IdleStateEvent when a Channel has not performed read, write, or both operation for a while. -public class IdleStateHandler: ChannelDuplexHandler { +public class IdleStateHandler: ChannelDuplexHandler, RemovableChannelHandler { public typealias InboundIn = NIOAny public typealias InboundOut = NIOAny public typealias OutboundIn = NIOAny diff --git a/Sources/NIO/ChannelPipeline.swift b/Sources/NIO/ChannelPipeline.swift index 38181b2cf..f250393f7 100644 --- a/Sources/NIO/ChannelPipeline.swift +++ b/Sources/NIO/ChannelPipeline.swift @@ -307,7 +307,7 @@ public final class ChannelPipeline: ChannelInvoker { try ctx.invokeHandlerAdded() promise.succeed(()) } catch let err { - remove0(ctx: ctx, promise: nil) + removeHandlerFromPipeline(ctx: ctx, promise: nil) promise.fail(err) } } @@ -392,7 +392,7 @@ public final class ChannelPipeline: ChannelInvoker { let contextFuture = self.context0 { return $0.handler === handler }.map { ctx in - self.remove0(ctx: ctx, promise: promise) + self.remove(ctx: ctx, promise: promise) } contextFuture.cascadeFailure(to: promise) @@ -407,7 +407,7 @@ public final class ChannelPipeline: ChannelInvoker { let contextFuture = self.context0 { $0.name == name }.map { ctx in - self.remove0(ctx: ctx, promise: promise) + self.remove(ctx: ctx, promise: promise) } contextFuture.cascadeFailure(to: promise) @@ -503,8 +503,10 @@ public final class ChannelPipeline: ChannelInvoker { return nil } - /// Remove a `ChannelHandlerContext` from the `ChannelPipeline`. Must only be called from within the `EventLoop`. - internal func remove0(ctx: ChannelHandlerContext, promise: EventLoopPromise?) { + /// Remove a `ChannelHandlerContext` from the `ChannelPipeline` directly without going through the + /// `RemovableChannelHandler` API. This must only be used to clear the pipeline on `Channel` tear down and + /// as a result of the `leavePipeline` call in the `RemovableChannelHandler` API. + internal func removeHandlerFromPipeline(ctx: ChannelHandlerContext, promise: EventLoopPromise?) { self.eventLoop.assertInEventLoop() let nextCtx = ctx.next @@ -546,9 +548,9 @@ public final class ChannelPipeline: ChannelInvoker { if let head = self.head { while let ctx = head.next { - remove0(ctx: ctx, promise: nil) + removeHandlerFromPipeline(ctx: ctx, promise: nil) } - remove0(ctx: self.head!, promise: nil) + removeHandlerFromPipeline(ctx: self.head!, promise: nil) } self.head = nil self.tail = nil @@ -1492,7 +1494,7 @@ extension ChannelHandlerContext { /// - removalToken: The removal token received from `RemovableChannelHandler.removeHandler` public func leavePipeline(removalToken: RemovalToken) { self.eventLoop.preconditionInEventLoop() - self.pipeline.remove0(ctx: self, promise: removalToken.promise) + self.pipeline.removeHandlerFromPipeline(ctx: self, promise: removalToken.promise) } } diff --git a/Sources/NIOHTTP1/HTTPDecoder.swift b/Sources/NIOHTTP1/HTTPDecoder.swift index 8aed15bb0..e60a49dde 100644 --- a/Sources/NIOHTTP1/HTTPDecoder.swift +++ b/Sources/NIOHTTP1/HTTPDecoder.swift @@ -165,7 +165,7 @@ public final class HTTPRequestDecoder: HTTPDecoder, Remov /// were for accurate decoding. /// /// Rather than set this up manually, consider using `ChannelPipeline.addHTTPClientHandlers`. -public final class HTTPResponseDecoder: HTTPDecoder, ChannelOutboundHandler { +public final class HTTPResponseDecoder: HTTPDecoder, ChannelOutboundHandler, RemovableChannelHandler { public typealias OutboundIn = HTTPClientRequestPart public typealias OutboundOut = HTTPClientRequestPart diff --git a/Tests/NIOHTTP1Tests/HTTPDecoderTest.swift b/Tests/NIOHTTP1Tests/HTTPDecoderTest.swift index d401ed2b6..07c580a5c 100644 --- a/Tests/NIOHTTP1Tests/HTTPDecoderTest.swift +++ b/Tests/NIOHTTP1Tests/HTTPDecoderTest.swift @@ -329,7 +329,7 @@ class HTTPDecoderTest: XCTestCase { } } - class Reciever: ChannelInboundHandler, RemovableChannelHandler { + class Receiver: ChannelInboundHandler, RemovableChannelHandler { typealias InboundIn = HTTPClientResponsePart typealias InboundOut = HTTPClientResponsePart typealias OutboundOut = HTTPClientRequestPart @@ -359,7 +359,7 @@ class HTTPDecoderTest: XCTestCase { } XCTAssertNoThrow(try channel.pipeline.add(name: "decoder", handler: HTTPResponseDecoder(leftOverBytesStrategy: .forwardBytes)).wait()) - XCTAssertNoThrow(try channel.pipeline.add(handler: Reciever()).wait()) + XCTAssertNoThrow(try channel.pipeline.add(handler: Receiver()).wait()) XCTAssertNoThrow(try channel.connect(to: SocketAddress(ipAddress: "127.0.0.1", port: 8888)).wait()) diff --git a/Tests/NIOTests/ChannelPipelineTest+XCTest.swift b/Tests/NIOTests/ChannelPipelineTest+XCTest.swift index b310dcd3e..b91090491 100644 --- a/Tests/NIOTests/ChannelPipelineTest+XCTest.swift +++ b/Tests/NIOTests/ChannelPipelineTest+XCTest.swift @@ -53,6 +53,8 @@ extension ChannelPipelineTest { ("testRemovingByReferenceWithFutureNotInChannel", testRemovingByReferenceWithFutureNotInChannel), ("testFireChannelReadInInactiveChannelDoesNotCrash", testFireChannelReadInInactiveChannelDoesNotCrash), ("testTeardownDuringFormalRemovalProcess", testTeardownDuringFormalRemovalProcess), + ("testVariousChannelRemovalAPIsGoThroughRemovableChannelHandler", testVariousChannelRemovalAPIsGoThroughRemovableChannelHandler), + ("testNonRemovableChannelHandlerIsNotRemovable", testNonRemovableChannelHandlerIsNotRemovable), ] } } diff --git a/Tests/NIOTests/ChannelPipelineTest.swift b/Tests/NIOTests/ChannelPipelineTest.swift index d66a4c15f..5e2263490 100644 --- a/Tests/NIOTests/ChannelPipelineTest.swift +++ b/Tests/NIOTests/ChannelPipelineTest.swift @@ -755,7 +755,7 @@ class ChannelPipelineTest: XCTestCase { } func testRemovingByNameWithPromiseStillInChannel() throws { - class NoOpHandler: ChannelInboundHandler { + class NoOpHandler: ChannelInboundHandler, RemovableChannelHandler { typealias InboundIn = Never } class DummyError: Error { } @@ -774,9 +774,11 @@ class ChannelPipelineTest: XCTestCase { buffer.writeStaticString("Hello, world!") let removalPromise = channel.eventLoop.makePromise(of: Void.self) - removalPromise.futureResult.whenSuccess { + removalPromise.futureResult.map { context.writeAndFlush(NIOAny(buffer), promise: nil) context.fireErrorCaught(DummyError()) + }.whenFailure { + XCTFail("unexpected error: \($0)") } XCTAssertNil(channel.readOutbound()) @@ -972,4 +974,72 @@ class ChannelPipelineTest: XCTestCase { // verify that the handler has now been removed, despite the fact it should be mid-removal XCTAssertNoThrow(try handlerRemovedPromise.futureResult.wait()) } + + func testVariousChannelRemovalAPIsGoThroughRemovableChannelHandler() { + class Handler: ChannelInboundHandler, RemovableChannelHandler { + typealias InboundIn = Never + + var removeHandlerCalled = false + var withinRemoveHandler = false + + func removeHandler(ctx: ChannelHandlerContext, removalToken: ChannelHandlerContext.RemovalToken) { + self.removeHandlerCalled = true + self.withinRemoveHandler = true + defer { + self.withinRemoveHandler = false + } + ctx.leavePipeline(removalToken: removalToken) + } + + func handlerRemoved(ctx: ChannelHandlerContext) { + XCTAssertTrue(self.removeHandlerCalled) + XCTAssertTrue(self.withinRemoveHandler) + } + } + + let channel = EmbeddedChannel() + let allHandlers = [Handler(), Handler(), Handler()] + XCTAssertNoThrow(try channel.pipeline.add(name: "the first one to remove", handler: allHandlers[0]).wait()) + XCTAssertNoThrow(try channel.pipeline.add(handler: allHandlers[1]).wait()) + XCTAssertNoThrow(try channel.pipeline.add(name: "the last one to remove", handler: allHandlers[2]).wait()) + + let lastContext = try! channel.pipeline.context(name: "the last one to remove").wait() + + XCTAssertNoThrow(try channel.pipeline.remove(name: "the first one to remove").wait()) + XCTAssertNoThrow(try channel.pipeline.remove(handler: allHandlers[1]).wait()) + XCTAssertNoThrow(try channel.pipeline.remove(ctx: lastContext).wait()) + + allHandlers.forEach { + XCTAssertTrue($0.removeHandlerCalled) + XCTAssertFalse($0.withinRemoveHandler) + } + } + + func testNonRemovableChannelHandlerIsNotRemovable() { + class NonRemovableHandler: ChannelInboundHandler { + typealias InboundIn = Never + } + + let channel = EmbeddedChannel() + let allHandlers = [NonRemovableHandler(), NonRemovableHandler(), NonRemovableHandler()] + XCTAssertNoThrow(try channel.pipeline.add(name: "1", handler: allHandlers[0]).wait()) + XCTAssertNoThrow(try channel.pipeline.add(name: "2", handler: allHandlers[1]).wait()) + + let lastContext = try! channel.pipeline.context(name: "1").wait() + + XCTAssertThrowsError(try channel.pipeline.remove(name: "2").wait()) { error in + if let error = error as? ChannelError { + XCTAssertEqual(ChannelError.unremovableHandler, error) + } else { + XCTFail("unexpected error: \(error)") + } + } + XCTAssertThrowsError(try channel.pipeline.remove(ctx: lastContext).wait()) { error in + if let error = error as? ChannelError { + XCTAssertEqual(ChannelError.unremovableHandler, error) + } else { + XCTFail("unexpected error: \(error)") + } + } + } } diff --git a/Tests/NIOWebSocketTests/WebSocketFrameDecoderTest.swift b/Tests/NIOWebSocketTests/WebSocketFrameDecoderTest.swift index 1508b3a09..c40a35458 100644 --- a/Tests/NIOWebSocketTests/WebSocketFrameDecoderTest.swift +++ b/Tests/NIOWebSocketTests/WebSocketFrameDecoderTest.swift @@ -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: ByteToMessageHandler.self).flatMapThrowing { + let f = self.decoderChannel.pipeline.context(handlerType: ByteToMessageHandler.self).flatMapThrowing { if let handler = $0.handler as? RemovableChannelHandler { return handler } else { @@ -111,7 +111,12 @@ public class WebSocketFrameDecoderTest: XCTestCase { } }.flatMap { self.decoderChannel.pipeline.remove(handler: $0) - }.flatMap { + } + + // we need to run the event loop here because removal is not synchronous + (self.decoderChannel.eventLoop as! EmbeddedEventLoop).run() + + XCTAssertNoThrow(try f.flatMap { self.decoderChannel.pipeline.add(handler: handler) }.wait()) }