diff --git a/Sources/NIO/Bootstrap.swift b/Sources/NIO/Bootstrap.swift index f4fc315b1..d5bbbe537 100644 --- a/Sources/NIO/Bootstrap.swift +++ b/Sources/NIO/Bootstrap.swift @@ -218,7 +218,8 @@ public final class ServerBootstrap { } return eventLoop.submit { - return serverChannelInit(serverChannel).flatMap { + // We need to hop to `eventLoop` as the user might have returned a future from a different `EventLoop`. + return serverChannelInit(serverChannel).hop(to: eventLoop).flatMap { serverChannel.pipeline.addHandler(AcceptHandler(childChannelInitializer: childChannelInit, childChannelOptions: childChannelOptions)) }.flatMap { @@ -485,17 +486,27 @@ public final class ClientBootstrap { return eventLoop.makeFailedFuture(error) } - return channelInitializer(channel).flatMap { - self._channelOptions.applyAllChannelOptions(to: channel) - }.flatMap { - let promise = eventLoop.makePromise(of: Void.self) - channel.registerAlreadyConfigured0(promise: promise) - return promise.futureResult - }.map { - channel - }.flatMapError { error in - channel.close0(error: error, mode: .all, promise: nil) - return channel.eventLoop.makeFailedFuture(error) + func setupChannel() -> EventLoopFuture { + eventLoop.assertInEventLoop() + // We need to hop to `eventLoop` as the user might have returned a future from a different `EventLoop`. + return channelInitializer(channel).hop(to: eventLoop).flatMap { + self._channelOptions.applyAllChannelOptions(to: channel) + }.flatMap { + let promise = eventLoop.makePromise(of: Void.self) + channel.registerAlreadyConfigured0(promise: promise) + return promise.futureResult + }.map { + channel + }.flatMapError { error in + channel.close0(error: error, mode: .all, promise: nil) + return channel.eventLoop.makeFailedFuture(error) + } + } + + if eventLoop.inEventLoop { + return setupChannel() + } else { + return eventLoop.submit{ setupChannel() }.flatMap { $0 } } } @@ -517,7 +528,8 @@ public final class ClientBootstrap { @inline(__always) func setupChannel() -> EventLoopFuture { eventLoop.assertInEventLoop() - channelInitializer(channel).flatMap { + // We need to hop to `eventLoop` as the user might have returned a future from a different `EventLoop`. + channelInitializer(channel).hop(to: eventLoop).flatMap { channelOptions.applyAllChannelOptions(to: channel) }.flatMap { channel.registerAndDoSynchronously(body) @@ -671,14 +683,25 @@ public final class DatagramBootstrap { return eventLoop.makeFailedFuture(error) } - return channelInitializer(channel).flatMap { - channelOptions.applyAllChannelOptions(to: channel) - }.flatMap { - registerAndBind(eventLoop, channel) - }.map { - channel - }.flatMapError { error in - eventLoop.makeFailedFuture(error) + func setupChannel() -> EventLoopFuture { + eventLoop.assertInEventLoop() + // We need to hop to `eventLoop` as the user might have returned a future from a different `EventLoop`. + return channelInitializer(channel).hop(to: eventLoop).flatMap { + eventLoop.assertInEventLoop() + return channelOptions.applyAllChannelOptions(to: channel) + }.flatMap { + registerAndBind(eventLoop, channel) + }.map { + channel + }.flatMapError { error in + eventLoop.makeFailedFuture(error) + } + } + + if eventLoop.inEventLoop { + return setupChannel() + } else { + return eventLoop.submit(setupChannel).flatMap { $0 } } } } diff --git a/Tests/NIOTests/BootstrapTest+XCTest.swift b/Tests/NIOTests/BootstrapTest+XCTest.swift index d341cfeb3..f21329acc 100644 --- a/Tests/NIOTests/BootstrapTest+XCTest.swift +++ b/Tests/NIOTests/BootstrapTest+XCTest.swift @@ -27,6 +27,10 @@ extension BootstrapTest { static var allTests : [(String, (BootstrapTest) -> () throws -> Void)] { return [ ("testBootstrapsCallInitializersOnCorrectEventLoop", testBootstrapsCallInitializersOnCorrectEventLoop), + ("testTCPBootstrapsTolerateFuturesFromDifferentEventLoopsReturnedInInitializers", testTCPBootstrapsTolerateFuturesFromDifferentEventLoopsReturnedInInitializers), + ("testUDPBootstrapToleratesFuturesFromDifferentEventLoopsReturnedInInitializers", testUDPBootstrapToleratesFuturesFromDifferentEventLoopsReturnedInInitializers), + ("testPreConnectedClientSocketToleratesFuturesFromDifferentEventLoopsReturnedInInitializers", testPreConnectedClientSocketToleratesFuturesFromDifferentEventLoopsReturnedInInitializers), + ("testPreConnectedServerSocketToleratesFuturesFromDifferentEventLoopsReturnedInInitializers", testPreConnectedServerSocketToleratesFuturesFromDifferentEventLoopsReturnedInInitializers), ] } } diff --git a/Tests/NIOTests/BootstrapTest.swift b/Tests/NIOTests/BootstrapTest.swift index 5eb4a2dd6..3daa57bc0 100644 --- a/Tests/NIOTests/BootstrapTest.swift +++ b/Tests/NIOTests/BootstrapTest.swift @@ -13,9 +13,41 @@ //===----------------------------------------------------------------------===// @testable import NIO +import NIOConcurrencyHelpers import XCTest class BootstrapTest: XCTestCase { + var groupBag: [MultiThreadedEventLoopGroup]? = nil // protected by `self.lock` + let lock = Lock() + + override func setUp() { + self.lock.withLock { + XCTAssertNil(self.groupBag) + self.groupBag = [] + } + } + + override func tearDown() { + XCTAssertNoThrow(try self.lock.withLock { + guard let groupBag = self.groupBag else { + XCTFail() + return + } + XCTAssertNoThrow(try groupBag.forEach { + XCTAssertNoThrow(try $0.syncShutdownGracefully()) + }) + self.groupBag = nil + }) + } + + func freshEventLoop() -> EventLoop { + let group: MultiThreadedEventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1) + self.lock.withLock { + self.groupBag!.append(group) + } + return group.next() + } + func testBootstrapsCallInitializersOnCorrectEventLoop() throws { for numThreads in [1 /* everything on one event loop */, 2 /* some stuff has shared event loops */, @@ -58,4 +90,121 @@ class BootstrapTest: XCTestCase { XCTAssertNoThrow(try serverChannelDone.futureResult.wait()) } } + + func testTCPBootstrapsTolerateFuturesFromDifferentEventLoopsReturnedInInitializers() throws { + let childChannelDone = self.freshEventLoop().makePromise(of: Void.self) + let serverChannelDone = self.freshEventLoop().makePromise(of: Void.self) + let serverChannel = try assertNoThrowWithValue(ServerBootstrap(group: self.freshEventLoop()) + .childChannelInitializer { channel in + XCTAssert(channel.eventLoop.inEventLoop) + defer { + childChannelDone.succeed(()) + } + return self.freshEventLoop().makeSucceededFuture(()) + } + .serverChannelInitializer { channel in + XCTAssert(channel.eventLoop.inEventLoop) + defer { + serverChannelDone.succeed(()) + } + return self.freshEventLoop().makeSucceededFuture(()) + } + .bind(host: "127.0.0.1", port: 0) + .wait()) + defer { + XCTAssertNoThrow(try serverChannel.close().wait()) + } + + let client = try assertNoThrowWithValue(ClientBootstrap(group: self.freshEventLoop()) + .channelInitializer { channel in + XCTAssert(channel.eventLoop.inEventLoop) + return self.freshEventLoop().makeSucceededFuture(()) + } + .connect(to: serverChannel.localAddress!) + .wait()) + defer { + XCTAssertNoThrow(try client.syncCloseAcceptingAlreadyClosed()) + } + XCTAssertNoThrow(try childChannelDone.futureResult.wait()) + XCTAssertNoThrow(try serverChannelDone.futureResult.wait()) + } + + func testUDPBootstrapToleratesFuturesFromDifferentEventLoopsReturnedInInitializers() throws { + XCTAssertNoThrow(try DatagramBootstrap(group: self.freshEventLoop()) + .channelInitializer { channel in + XCTAssert(channel.eventLoop.inEventLoop) + return self.freshEventLoop().makeSucceededFuture(()) + } + .bind(host: "127.0.0.1", port: 0) + .wait() + .close() + .wait()) + } + + func testPreConnectedClientSocketToleratesFuturesFromDifferentEventLoopsReturnedInInitializers() throws { + var socketFDs: [CInt] = [-1, -1] + #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) + let err = socketpair(PF_LOCAL, SOCK_STREAM, 0, &socketFDs) + #else + let err = socketpair(PF_LOCAL, CInt(SOCK_STREAM.rawValue), 0, &socketFDs) + #endif + XCTAssertEqual(0, err) + defer { + // 0 is closed together with the Channel below. + XCTAssertNoThrow(try Posix.close(descriptor: socketFDs[1])) + } + + XCTAssertNoThrow(try ClientBootstrap(group: self.freshEventLoop()) + .channelInitializer { channel in + XCTAssert(channel.eventLoop.inEventLoop) + return self.freshEventLoop().makeSucceededFuture(()) + } + .withConnectedSocket(descriptor: socketFDs[0]) + .wait() + .close() + .wait()) + } + + func testPreConnectedServerSocketToleratesFuturesFromDifferentEventLoopsReturnedInInitializers() throws { + let socket = try Posix.socket(domain: AF_INET, type: Posix.SOCK_STREAM, protocol: 0) + + let serverAddress = try assertNoThrowWithValue(SocketAddress.makeAddressResolvingHost("127.0.0.1", port: 0)) + try serverAddress.withSockAddr { serverAddressPtr, size in + try Posix.bind(descriptor: socket, ptr: serverAddressPtr, + bytes: size) + } + + let childChannelDone = self.freshEventLoop().next().makePromise(of: Void.self) + let serverChannelDone = self.freshEventLoop().next().makePromise(of: Void.self) + + let serverChannel = try assertNoThrowWithValue(try ServerBootstrap(group: self.freshEventLoop()) + .childChannelInitializer { channel in + XCTAssert(channel.eventLoop.inEventLoop) + defer { + childChannelDone.succeed(()) + } + return self.freshEventLoop().makeSucceededFuture(()) + } + .serverChannelInitializer { channel in + XCTAssert(channel.eventLoop.inEventLoop) + defer { + serverChannelDone.succeed(()) + } + return self.freshEventLoop().makeSucceededFuture(()) + } + .withBoundSocket(descriptor: socket) + .wait()) + let client = try assertNoThrowWithValue(ClientBootstrap(group: self.freshEventLoop()) + .channelInitializer { channel in + XCTAssert(channel.eventLoop.inEventLoop) + return self.freshEventLoop().makeSucceededFuture(()) + } + .connect(to: serverChannel.localAddress!) + .wait()) + defer { + XCTAssertNoThrow(try client.syncCloseAcceptingAlreadyClosed()) + } + XCTAssertNoThrow(try childChannelDone.futureResult.wait()) + XCTAssertNoThrow(try serverChannelDone.futureResult.wait()) + } }