diff --git a/Sources/NIO/SocketChannel.swift b/Sources/NIO/SocketChannel.swift index e3838f50a..565cb3633 100644 --- a/Sources/NIO/SocketChannel.swift +++ b/Sources/NIO/SocketChannel.swift @@ -482,8 +482,14 @@ class BaseSocketChannel: SelectableChannel, ChannelCore { pipeline.fireErrorCaught0(error: err) } - executeAndComplete(promise) { + let p: EventLoopPromise? + 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: 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: 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: SelectableChannel, ChannelCore { } } - fileprivate func becomeActive0() { + fileprivate func becomeActive0(promise: EventLoopPromise?) { 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?) { 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 { scheduled.cancel() } try self.socket.finishConnect() - becomeActive0() } override func close0(error: Error, mode: CloseMode, promise: EventLoopPromise?) { @@ -1046,9 +1067,8 @@ final class ServerSocketChannel: BaseSocketChannel { let p: EventLoopPromise = 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 { 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 { 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) diff --git a/Tests/LinuxMain.swift b/Tests/LinuxMain.swift index cc05ecf35..dd1bbd019 100644 --- a/Tests/LinuxMain.swift +++ b/Tests/LinuxMain.swift @@ -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), diff --git a/Tests/NIOTests/ChannelNotificationTest+XCTest.swift b/Tests/NIOTests/ChannelNotificationTest+XCTest.swift new file mode 100644 index 000000000..8fc7c0356 --- /dev/null +++ b/Tests/NIOTests/ChannelNotificationTest+XCTest.swift @@ -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), + ] + } +} + diff --git a/Tests/NIOTests/ChannelNotificationTest.swift b/Tests/NIOTests/ChannelNotificationTest.swift new file mode 100644 index 000000000..e3a024a8f --- /dev/null +++ b/Tests/NIOTests/ChannelNotificationTest.swift @@ -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?, 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? + private var connectPromise: EventLoopPromise? + private var closePromise: EventLoopPromise? + + + 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?) { + 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?) { + XCTFail("bind(...) should not be called") + ctx.bind(to: address, promise: promise) + } + + public func connect(ctx: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise?) { + 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?) { + 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? + private let activeChannelPromise: EventLoopPromise + + init(_ activeChannelPromise: EventLoopPromise) { + 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?) { + 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?) { + XCTFail("connect(...) should not be called") + ctx.connect(to: address, promise: promise) + } + + public func bind(ctx: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise?) { + XCTFail("bind(...) should not be called") + ctx.bind(to: address, promise: promise) + } + + public func close(ctx: ChannelHandlerContext, mode: CloseMode, promise: EventLoopPromise?) { + 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? + private var bindPromise: EventLoopPromise? + + private var closePromise: EventLoopPromise? + + 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?) { + 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?) { + XCTFail("connect(...) should not be called") + ctx.connect(to: address, promise: promise) + } + + public func bind(ctx: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise?) { + 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?) { + 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 = 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() + } +} diff --git a/Tests/NIOTests/EchoServerClientTest.swift b/Tests/NIOTests/EchoServerClientTest.swift index 8ea0dbb77..fe4280382 100644 --- a/Tests/NIOTests/EchoServerClientTest.swift +++ b/Tests/NIOTests/EchoServerClientTest.swift @@ -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() } }