Ensure we always update the promise before calling fire* methods and also udate channel state before. (#181)

Motivation:

We not always ensure correct ordering which made it quite hard to reason about things. We should always first notify the promise before we call the fire* method that belongs to the event. Beside this we sometimes fired events or notified promised before correctly update the active state / addresses of a Channel which could result in unexpected results when query the Channel during execution of callbacks and handlers.

Modifications:

- Ensure we always notify promise first
- Always correctly update channel state before notify promise
- Add test to verify notification order.

Result:

Correct ordering of events which makes things easier to reason about and which follows what netty is doing.
This commit is contained in:
Norman Maurer authored and Cory Benfield committed 2018-03-19 20:52:31 +09:00
1 parent 54c68db6fb
commit edfbe50fc8
5 files changed
+397 -16

No files matched your search

+32 -13
View File
@@ -482,8 +482,14 @@ class BaseSocketChannel<T: BaseSocket>: SelectableChannel, ChannelCore {
pipeline.fireErrorCaught0(error: err)
}
executeAndComplete(promise) {
let p: EventLoopPromise<Void>?
do {
try socket.close()
p = promise
} catch {
promise?.fail(error: error)
// Set p to nil as we want to ensure we pass nil to becomeInactive0(...) so we not try to notify the promise again.
p = nil
}
// Fail all pending writes and so ensure all pending promises are notified
@@ -492,7 +498,9 @@ class BaseSocketChannel<T: BaseSocket>: SelectableChannel, ChannelCore {
self.cancelWritesOnClose(error: error)
if !self.neverActivated {
becomeInactive0()
becomeInactive0(promise: p)
} else if let p = p {
p.succeed(result: ())
}
if !self.neverRegistered {
@@ -556,11 +564,15 @@ class BaseSocketChannel<T: BaseSocket>: SelectableChannel, ChannelCore {
if let connectPromise = pendingConnect {
pendingConnect = nil
do {
try finishConnectSocket()
} catch {
connectPromise.fail(error: error)
return
}
// We already know what the local address is.
self.updateCachedAddressesFromSocket(updateLocal: false, updateRemote: true)
executeAndComplete(connectPromise) {
try finishConnectSocket()
}
becomeActive0(promise: connectPromise)
}
}
@@ -718,20 +730,30 @@ class BaseSocketChannel<T: BaseSocket>: SelectableChannel, ChannelCore {
}
}
fileprivate func becomeActive0() {
fileprivate func becomeActive0(promise: EventLoopPromise<Void>?) {
assert(eventLoop.inEventLoop)
assert(!self.active.load())
assert(self._isOpen)
self.neverActivated = false
active.store(true)
// Notify the promise before firing the inbound event through the pipeline.
if let promise = promise {
promise.succeed(result: ())
}
pipeline.fireChannelActive0()
}
fileprivate func becomeInactive0() {
fileprivate func becomeInactive0(promise: EventLoopPromise<Void>?) {
assert(eventLoop.inEventLoop)
assert(self.active.load())
active.store(false)
// Notify the promise before firing the inbound event through the pipeline.
if let promise = promise {
promise.succeed(result: ())
}
pipeline.fireChannelInactive0()
}
}
@@ -899,7 +921,6 @@ final class SocketChannel: BaseSocketChannel<Socket> {
scheduled.cancel()
}
try self.socket.finishConnect()
becomeActive0()
}
override func close0(error: Error, mode: CloseMode, promise: EventLoopPromise<Void>?) {
@@ -1046,9 +1067,8 @@ final class ServerSocketChannel: BaseSocketChannel<ServerSocket> {
let p: EventLoopPromise<Void> = eventLoop.newPromise()
p.futureResult.map {
// Its important to call the methods before we actual notify the original promise for ordering reasons.
self.becomeActive0()
self.becomeActive0(promise: promise)
self.readIfNeeded0()
promise?.succeed(result: ())
}.whenFailure{ error in
promise?.fail(error: error)
}
@@ -1120,7 +1140,7 @@ final class ServerSocketChannel: BaseSocketChannel<ServerSocket> {
guard ch.isOpen else {
throw ChannelError.ioOnClosedChannel
}
ch.becomeActive0()
ch.becomeActive0(promise: nil)
ch.readIfNeeded0()
}.whenFailure { error in
ch.close(promise: nil)
@@ -1322,8 +1342,7 @@ final class DatagramChannel: BaseSocketChannel<Socket> {
do {
try socket.bind(to: address)
self.updateCachedAddressesFromSocket(updateRemote: false)
promise?.succeed(result: ())
becomeActive0()
becomeActive0(promise: promise)
readIfNeeded0()
} catch let err {
promise?.fail(error: err)
+1
View File
@@ -39,6 +39,7 @@ import XCTest
testCase(BlockingIOThreadPoolTest.allTests),
testCase(ByteBufferTest.allTests),
testCase(ByteToMessageDecoderTest.allTests),
testCase(ChannelNotificationTest.allTests),
testCase(ChannelPipelineTest.allTests),
testCase(ChannelTests.allTests),
testCase(CircularBufferTests.allTests),
@@ -0,0 +1,33 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
//
// ChannelNotificationTest+XCTest.swift
//
import XCTest
///
/// NOTE: This file was generated by generate_linux_tests.rb
///
/// Do NOT edit this file directly as it will be regenerated automatically when needed.
///
extension ChannelNotificationTest {
static var allTests : [(String, (ChannelNotificationTest) -> () throws -> Void)] {
return [
("testNotificationOrder", testNotificationOrder),
]
}
}
@@ -0,0 +1,328 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
@testable import NIO
import XCTest
class ChannelNotificationTest: XCTestCase {
private static func assertFulfilled(promise: EventLoopPromise<Void>?, promiseName: String, trigger: String, setter: String, file: StaticString = #file, line: UInt = #line) {
if let promise = promise {
XCTAssertTrue(promise.futureResult.fulfilled, "\(promiseName) not fulfilled before \(trigger) was called", file: file, line: line)
} else {
XCTFail("\(setter) not called before \(trigger)", file: file, line: line)
}
}
// Handler that verifies the notification order of the different promises + the inbound events that are fired.
class SocketChannelLifecycleVerificationHandler: ChannelDuplexHandler {
typealias InboundIn = Any
typealias OutboundIn = Any
private var registerPromise: EventLoopPromise<Void>?
private var connectPromise: EventLoopPromise<Void>?
private var closePromise: EventLoopPromise<Void>?
public func channelActive(ctx: ChannelHandlerContext) {
XCTAssertTrue(ctx.channel.isActive)
assertFulfilled(promise: self.registerPromise, promiseName: "registerPromise", trigger: "channelActive", setter: "register")
assertFulfilled(promise: self.connectPromise, promiseName: "connectPromise", trigger: "channelActive", setter: "connect")
XCTAssertNil(self.closePromise)
XCTAssertFalse(ctx.channel.closeFuture.fulfilled)
}
public func channelInactive(ctx: ChannelHandlerContext) {
XCTAssertFalse(ctx.channel.isActive)
assertFulfilled(promise: self.registerPromise, promiseName: "registerPromise", trigger: "channelInactive", setter: "register")
assertFulfilled(promise: self.connectPromise, promiseName: "connectPromise", trigger: "channelInactive", setter: "connect")
assertFulfilled(promise: self.closePromise, promiseName: "closePromise", trigger: "channelInactive", setter: "close")
XCTAssertFalse(ctx.channel.closeFuture.fulfilled)
}
public func channelRegistered(ctx: ChannelHandlerContext) {
XCTAssertFalse(ctx.channel.isActive)
XCTAssertNil(self.connectPromise)
XCTAssertNil(self.closePromise)
assertFulfilled(promise: self.registerPromise, promiseName: "registerPromise", trigger: "channelRegistered", setter: "register")
XCTAssertFalse(ctx.channel.closeFuture.fulfilled)
}
public func channelUnregistered(ctx: ChannelHandlerContext) {
XCTAssertFalse(ctx.channel.isActive)
assertFulfilled(promise: self.registerPromise, promiseName: "registerPromise", trigger: "channelInactive", setter: "register")
assertFulfilled(promise: self.connectPromise, promiseName: "connectPromise", trigger: "channelInactive", setter: "connect")
assertFulfilled(promise: self.closePromise, promiseName: "closePromise", trigger: "channelInactive", setter: "close")
XCTAssertFalse(ctx.channel.closeFuture.fulfilled)
}
public func register(ctx: ChannelHandlerContext, promise: EventLoopPromise<Void>?) {
XCTAssertNil(self.registerPromise)
XCTAssertNil(self.connectPromise)
XCTAssertNil(self.closePromise)
promise!.futureResult.whenSuccess {
XCTAssertFalse(ctx.channel.isActive)
}
self.registerPromise = promise
ctx.register(promise: promise)
}
public func bind(ctx: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise<Void>?) {
XCTFail("bind(...) should not be called")
ctx.bind(to: address, promise: promise)
}
public func connect(ctx: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise<Void>?) {
XCTAssertNotNil(self.registerPromise)
XCTAssertNil(self.connectPromise)
XCTAssertNil(self.closePromise)
promise!.futureResult.whenSuccess {
XCTAssertTrue(ctx.channel.isActive)
}
self.connectPromise = promise
ctx.connect(to: address, promise: promise)
}
public func close(ctx: ChannelHandlerContext, mode: CloseMode, promise: EventLoopPromise<Void>?) {
XCTAssertNotNil(self.registerPromise)
XCTAssertNotNil(self.connectPromise)
XCTAssertNil(self.closePromise)
promise!.futureResult.whenSuccess {
XCTAssertFalse(ctx.channel.isActive)
}
self.closePromise = promise
ctx.close(mode: mode, promise: promise)
}
}
class AcceptedSocketChannelLifecycleVerificationHandler: ChannelDuplexHandler {
typealias InboundIn = Any
typealias OutboundIn = Any
private var registerPromise: EventLoopPromise<Void>?
private let activeChannelPromise: EventLoopPromise<Channel>
init(_ activeChannelPromise: EventLoopPromise<Channel>) {
self.activeChannelPromise = activeChannelPromise
}
public func channelActive(ctx: ChannelHandlerContext) {
XCTAssertTrue(ctx.channel.isActive)
assertFulfilled(promise: self.registerPromise, promiseName: "registerPromise", trigger: "channelActive", setter: "register")
XCTAssertFalse(ctx.channel.closeFuture.fulfilled)
XCTAssertFalse(self.activeChannelPromise.futureResult.fulfilled)
self.activeChannelPromise.succeed(result: ctx.channel)
}
public func channelInactive(ctx: ChannelHandlerContext) {
XCTAssertFalse(ctx.channel.isActive)
assertFulfilled(promise: self.registerPromise, promiseName: "registerPromise", trigger: "channelInactive", setter: "register")
XCTAssertFalse(ctx.channel.closeFuture.fulfilled)
}
public func channelRegistered(ctx: ChannelHandlerContext) {
XCTAssertFalse(ctx.channel.isActive)
assertFulfilled(promise: self.registerPromise, promiseName: "registerPromise", trigger: "channelRegistered", setter: "register")
XCTAssertFalse(ctx.channel.closeFuture.fulfilled)
}
public func channelUnregistered(ctx: ChannelHandlerContext) {
XCTAssertFalse(ctx.channel.isActive)
assertFulfilled(promise: self.registerPromise, promiseName: "registerPromise", trigger: "channelUnregistered", setter: "register")
XCTAssertFalse(ctx.channel.closeFuture.fulfilled)
}
public func register(ctx: ChannelHandlerContext, promise: EventLoopPromise<Void>?) {
XCTAssertNil(self.registerPromise)
let p = promise ?? ctx.eventLoop.newPromise()
p.futureResult.whenSuccess {
XCTAssertFalse(ctx.channel.isActive)
}
self.registerPromise = p
ctx.register(promise: p)
}
public func connect(ctx: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise<Void>?) {
XCTFail("connect(...) should not be called")
ctx.connect(to: address, promise: promise)
}
public func bind(ctx: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise<Void>?) {
XCTFail("bind(...) should not be called")
ctx.bind(to: address, promise: promise)
}
public func close(ctx: ChannelHandlerContext, mode: CloseMode, promise: EventLoopPromise<Void>?) {
XCTFail("close(...) should not be called")
ctx.close(mode: mode, promise: promise)
}
}
class ServerSocketChannelLifecycleVerificationHandler: ChannelDuplexHandler {
typealias InboundIn = Any
typealias OutboundIn = Any
private var registerPromise: EventLoopPromise<Void>?
private var bindPromise: EventLoopPromise<Void>?
private var closePromise: EventLoopPromise<Void>?
public func channelActive(ctx: ChannelHandlerContext) {
XCTAssertTrue(ctx.channel.isActive)
assertFulfilled(promise: self.registerPromise, promiseName: "registerPromise", trigger: "channelActive", setter: "register")
XCTAssertNil(self.closePromise)
XCTAssertFalse(ctx.channel.closeFuture.fulfilled)
}
public func channelInactive(ctx: ChannelHandlerContext) {
XCTAssertFalse(ctx.channel.isActive)
assertFulfilled(promise: self.registerPromise, promiseName: "registerPromise", trigger: "channelInactive", setter: "register")
assertFulfilled(promise: self.closePromise, promiseName: "closePromise", trigger: "channelInactive", setter: "close")
XCTAssertFalse(ctx.channel.closeFuture.fulfilled)
}
public func channelRegistered(ctx: ChannelHandlerContext) {
XCTAssertFalse(ctx.channel.isActive)
XCTAssertNil(closePromise)
assertFulfilled(promise: self.registerPromise, promiseName: "registerPromise", trigger: "channelRegistered", setter: "register")
XCTAssertFalse(ctx.channel.closeFuture.fulfilled)
}
public func channelUnregistered(ctx: ChannelHandlerContext) {
XCTAssertFalse(ctx.channel.isActive)
assertFulfilled(promise: self.registerPromise, promiseName: "registerPromise", trigger: "channelUnregistered", setter: "register")
assertFulfilled(promise: self.closePromise, promiseName: "closePromise", trigger: "channelInactive", setter: "close")
XCTAssertFalse(ctx.channel.closeFuture.fulfilled)
}
public func register(ctx: ChannelHandlerContext, promise: EventLoopPromise<Void>?) {
XCTAssertNil(self.registerPromise)
XCTAssertNil(self.bindPromise)
XCTAssertNil(self.closePromise)
let p = promise ?? ctx.eventLoop.newPromise()
p.futureResult.whenSuccess {
XCTAssertFalse(ctx.channel.isActive)
}
self.registerPromise = p
ctx.register(promise: p)
}
public func connect(ctx: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise<Void>?) {
XCTFail("connect(...) should not be called")
ctx.connect(to: address, promise: promise)
}
public func bind(ctx: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise<Void>?) {
XCTAssertNotNil(self.registerPromise)
XCTAssertNil(self.bindPromise)
XCTAssertNil(self.closePromise)
promise?.futureResult.whenSuccess {
XCTAssertTrue(ctx.channel.isActive)
}
self.bindPromise = promise
ctx.bind(to: address, promise: promise)
}
public func close(ctx: ChannelHandlerContext, mode: CloseMode, promise: EventLoopPromise<Void>?) {
XCTAssertNotNil(self.registerPromise)
XCTAssertNotNil(self.bindPromise)
XCTAssertNil(self.closePromise)
let p = promise ?? ctx.eventLoop.newPromise()
p.futureResult.whenSuccess {
XCTAssertFalse(ctx.channel.isActive)
}
self.closePromise = p
ctx.close(mode: mode, promise: p)
}
}
func testNotificationOrder() throws {
let group = MultiThreadedEventLoopGroup(numThreads: 1)
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
let acceptedChannelPromise: EventLoopPromise<Channel> = group.next().newPromise()
let serverChannel = try ServerBootstrap(group: group)
.serverChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
.serverChannelInitializer { channel in
channel.pipeline.add(handler: ServerSocketChannelLifecycleVerificationHandler())
}
.childChannelOption(ChannelOptions.autoRead, value: false)
.childChannelInitializer { channel in
channel.pipeline.add(handler: AcceptedSocketChannelLifecycleVerificationHandler(acceptedChannelPromise))
}
.bind(host: "127.0.0.1", port: 0).wait()
let clientChannel = try ClientBootstrap(group: group)
.channelInitializer { channel in
channel.pipeline.add(handler: SocketChannelLifecycleVerificationHandler())
}
.connect(to: serverChannel.localAddress!).wait()
try clientChannel.close().wait()
try clientChannel.closeFuture.wait()
let channel = try acceptedChannelPromise.futureResult.wait()
var buffer = channel.allocator.buffer(capacity: 8)
buffer.write(string: "test")
while let result = try? channel.writeAndFlush(buffer).wait() {
// Just write in a loop until it fails to ensure we detect the closed connection in a timely manner.
}
try channel.closeFuture.wait()
try serverChannel.close().wait()
try serverChannel.closeFuture.wait()
}
}
+3 -3
View File
@@ -211,7 +211,7 @@ class EchoServerClientTest : XCTestCase {
_ = clientChannel.close()
}
handler.assertChannelActiveFired()
try handler.assertChannelActiveFired()
}
func testWriteThenRead() throws {
@@ -263,8 +263,8 @@ class EchoServerClientTest : XCTestCase {
ctx.fireChannelActive()
}
func assertChannelActiveFired() {
XCTAssert(promise.futureResult.fulfilled)
func assertChannelActiveFired() throws {
try promise.futureResult.wait()
}
}