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
This commit is contained in:
Johannes Weiss authored and GitHub committed 2019-02-12 19:06:39 +01:00
1 parent c6c1f84459
commit 6e7a3de8e8
7 files changed
+97 -18

No files matched your search

+3 -3
View File
@@ -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
+10 -8
View File
@@ -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<Void>?) {
/// 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<Void>?) {
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)
}
}
+1 -1
View File
@@ -165,7 +165,7 @@ public final class HTTPRequestDecoder: HTTPDecoder<HTTPServerRequestPart>, Remov
/// were for accurate decoding.
///
/// Rather than set this up manually, consider using `ChannelPipeline.addHTTPClientHandlers`.
public final class HTTPResponseDecoder: HTTPDecoder<HTTPClientResponsePart>, ChannelOutboundHandler {
public final class HTTPResponseDecoder: HTTPDecoder<HTTPClientResponsePart>, ChannelOutboundHandler, RemovableChannelHandler {
public typealias OutboundIn = HTTPClientRequestPart
public typealias OutboundOut = HTTPClientRequestPart
+2 -2
View File
@@ -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())
@@ -53,6 +53,8 @@ extension ChannelPipelineTest {
("testRemovingByReferenceWithFutureNotInChannel", testRemovingByReferenceWithFutureNotInChannel),
("testFireChannelReadInInactiveChannelDoesNotCrash", testFireChannelReadInInactiveChannelDoesNotCrash),
("testTeardownDuringFormalRemovalProcess", testTeardownDuringFormalRemovalProcess),
("testVariousChannelRemovalAPIsGoThroughRemovableChannelHandler", testVariousChannelRemovalAPIsGoThroughRemovableChannelHandler),
("testNonRemovableChannelHandlerIsNotRemovable", testNonRemovableChannelHandlerIsNotRemovable),
]
}
}
+72 -2
View File
@@ -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)")
}
}
}
}
@@ -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<WebSocketFrameDecoder>.self).flatMapThrowing {
let f = self.decoderChannel.pipeline.context(handlerType: ByteToMessageHandler<WebSocketFrameDecoder>.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())
}