mirror of
https://github.com/apple/swift-nio
synced 2026-11-27 05:04:22 +00:00
Create a ClientBootstrap protocol (#1253)
This allows other EventLoopGroup implementations to swap in other bootstrap implementations. By default, it is unimplemented and will throw an error once `connect` is called on the returned Bootstrap. Support is implemented for `MultiThreadedEventLoopGroup`, `SelectableEventLoop` and `EmbeddedEventLoop`.
This commit is contained in:
1 parent
3f04a5c056
commit
06dab4e04b
5 files changed
+138
-6
No files matched your search
@@ -330,6 +330,40 @@ private extension Channel {
|
||||
}
|
||||
}
|
||||
|
||||
/// `NIOTCPClientBootstrap` is implemented by various underlying transport mechanisms. Typically,
|
||||
/// this will be the BSD Sockets API implemented by `ClientBootstrap`.
|
||||
internal protocol NIOTCPClientBootstrap {
|
||||
/// Initialize the connected `Channel` with `initializer`. The most common task in initializer is to add
|
||||
/// `ChannelHandler`s to the `ChannelPipeline`.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - handler: A closure that initializes the provided `Channel`.
|
||||
func channelInitializer(_ handler: @escaping (Channel) -> EventLoopFuture<Void>) -> Self
|
||||
|
||||
/// Specifies a `ChannelOption` to be applied to the `Channel`.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - option: The option to be applied.
|
||||
/// - value: The value for the option.
|
||||
@inlinable
|
||||
func channelOption<Option: ChannelOption>(_ option: Option, value: Option.Value) -> Self
|
||||
|
||||
/// Specifies a timeout to apply to a connection attempt.
|
||||
//
|
||||
/// - parameters:
|
||||
/// - timeout: The timeout that will apply to the connection attempt.
|
||||
func connectTimeout(_ timeout: TimeAmount) -> Self
|
||||
|
||||
/// Specify the `host` and `port` to connect to for the `Channel` that will be established.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - host: The host to connect to.
|
||||
/// - port: The port to connect to.
|
||||
/// - returns: An `EventLoopFuture<Channel>` to deliver the `Channel` when connected.
|
||||
func connect(host: String, port: Int) -> EventLoopFuture<Channel>
|
||||
}
|
||||
|
||||
|
||||
/// A `ClientBootstrap` is an easy way to bootstrap a `SocketChannel` when creating network clients.
|
||||
///
|
||||
/// Usually you re-use a `ClientBootstrap` once you set it up and called `connect` multiple times on it.
|
||||
@@ -356,7 +390,7 @@ private extension Channel {
|
||||
/// ```
|
||||
///
|
||||
/// The connected `SocketChannel` will operate on `ByteBuffer` as inbound and on `IOData` as outbound messages.
|
||||
public final class ClientBootstrap {
|
||||
public final class ClientBootstrap: NIOTCPClientBootstrap {
|
||||
|
||||
private let group: EventLoopGroup
|
||||
private var channelInitializer: Optional<ChannelInitializerCallback>
|
||||
|
||||
@@ -60,6 +60,11 @@ public final class EmbeddedEventLoop: EventLoop {
|
||||
/// Initialize a new `EmbeddedEventLoop`.
|
||||
public init() { }
|
||||
|
||||
/// Provide a valid `ClientBootstrap` to setup an `EmbeddedEventLoop`.
|
||||
internal func makeTCPClientBootstrap() -> NIOTCPClientBootstrap {
|
||||
return ClientBootstrap(group: self)
|
||||
}
|
||||
|
||||
/// - see: `EventLoop.scheduleTask(deadline:_:)`
|
||||
@discardableResult
|
||||
public func scheduleTask<T>(deadline: NIODeadline, _ task: @escaping () throws -> T) -> Scheduled<T> {
|
||||
|
||||
@@ -744,6 +744,11 @@ internal final class SelectableEventLoop: EventLoop {
|
||||
_addresses.deallocate()
|
||||
}
|
||||
|
||||
/// Provide a valid `ClientBootstrap` to setup this `SelectableEventLoop` with a `SocketChannel`.
|
||||
internal func makeTCPClientBootstrap() -> NIOTCPClientBootstrap {
|
||||
return ClientBootstrap(group: self)
|
||||
}
|
||||
|
||||
/// Is this `SelectableEventLoop` still open (ie. not shutting down or shut down)
|
||||
internal var isOpen: Bool {
|
||||
self.assertInEventLoop()
|
||||
@@ -1128,6 +1133,47 @@ extension EventLoopGroup {
|
||||
}
|
||||
}
|
||||
|
||||
/// The default, non-functional implementation used to encourage EventLoopGroup implementations to conform to `NIOTCPClientBootstrap`.
|
||||
internal struct CannotBootstrap: NIOTCPClientBootstrap {
|
||||
/// Thrown when an EventLoopGroup has not implemented `NIOTCPClientBootstrap` properly.
|
||||
public struct CannotBootstrapError: Error {
|
||||
let message: String
|
||||
|
||||
public init(_ message: String) {
|
||||
self.message = message
|
||||
}
|
||||
}
|
||||
|
||||
let group: EventLoopGroup
|
||||
|
||||
init(group: EventLoopGroup) {
|
||||
self.group = group
|
||||
}
|
||||
|
||||
func channelInitializer(_ handler: @escaping (Channel) -> EventLoopFuture<Void>) -> CannotBootstrap {
|
||||
return self
|
||||
}
|
||||
|
||||
func channelOption<Option>(_ option: Option, value: Option.Value) -> CannotBootstrap where Option : ChannelOption {
|
||||
return self
|
||||
}
|
||||
|
||||
func connectTimeout(_ timeout: TimeAmount) -> CannotBootstrap {
|
||||
return self
|
||||
}
|
||||
|
||||
func connect(host: String, port: Int) -> EventLoopFuture<Channel> {
|
||||
return self.group.next().makeFailedFuture(CannotBootstrapError(#"Your EventLoopGroup of type \#(type(of: self)) is not compatible with "NIOTCPClientBootstrap", please implement "public func makeTCPClientBootstrap() -> NIOTCPClientBootstrap" "#))
|
||||
}
|
||||
}
|
||||
|
||||
internal extension EventLoopGroup {
|
||||
/// If implemented, this provides the corresponding `Bootstrap` to create the `Channel` associated with this `EventLoopGroup`
|
||||
func makeTCPClientBootstrap() -> NIOTCPClientBootstrap {
|
||||
return CannotBootstrap(group: self)
|
||||
}
|
||||
}
|
||||
|
||||
private let nextEventLoopGroupID = NIOAtomic.makeAtomic(value: 0)
|
||||
|
||||
/// Called per `NIOThread` that is created for an EventLoop to do custom initialization of the `NIOThread` before the actual `EventLoop` is run on it.
|
||||
@@ -1224,6 +1270,11 @@ public final class MultiThreadedEventLoopGroup: EventLoopGroup {
|
||||
}
|
||||
}
|
||||
|
||||
/// Provide a `ClientBootstrap` to setup this `MultiThreadedEventLoopGroup` with a `SocketChannel`.
|
||||
internal func makeTCPClientBootstrap() -> NIOTCPClientBootstrap? {
|
||||
return ClientBootstrap(group: self)
|
||||
}
|
||||
|
||||
/// Returns the `EventLoop` for the calling thread.
|
||||
///
|
||||
/// - returns: The current `EventLoop` for the calling thread or `nil` if none is assigned to the thread.
|
||||
|
||||
@@ -32,6 +32,7 @@ extension BootstrapTest {
|
||||
("testUDPBootstrapToleratesFuturesFromDifferentEventLoopsReturnedInInitializers", testUDPBootstrapToleratesFuturesFromDifferentEventLoopsReturnedInInitializers),
|
||||
("testPreConnectedClientSocketToleratesFuturesFromDifferentEventLoopsReturnedInInitializers", testPreConnectedClientSocketToleratesFuturesFromDifferentEventLoopsReturnedInInitializers),
|
||||
("testPreConnectedServerSocketToleratesFuturesFromDifferentEventLoopsReturnedInInitializers", testPreConnectedServerSocketToleratesFuturesFromDifferentEventLoopsReturnedInInitializers),
|
||||
("testTCPClientBootstrapAllowsConformanceCorrectly", testTCPClientBootstrapAllowsConformanceCorrectly),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -134,11 +134,11 @@ class BootstrapTest: XCTestCase {
|
||||
.channelInitializer { channel in
|
||||
XCTAssert(channel.eventLoop.inEventLoop)
|
||||
return self.freshEventLoop().makeSucceededFuture(())
|
||||
}
|
||||
.bind(host: "127.0.0.1", port: 0)
|
||||
.wait()
|
||||
.close()
|
||||
.wait())
|
||||
}
|
||||
.bind(host: "127.0.0.1", port: 0)
|
||||
.wait()
|
||||
.close()
|
||||
.wait())
|
||||
}
|
||||
|
||||
func testPreConnectedClientSocketToleratesFuturesFromDifferentEventLoopsReturnedInInitializers() throws {
|
||||
@@ -205,4 +205,45 @@ class BootstrapTest: XCTestCase {
|
||||
XCTAssertNoThrow(try childChannelDone.futureResult.wait())
|
||||
XCTAssertNoThrow(try serverChannelDone.futureResult.wait())
|
||||
}
|
||||
|
||||
func testTCPClientBootstrapAllowsConformanceCorrectly() throws {
|
||||
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
|
||||
defer {
|
||||
XCTAssertNoThrow(try group.syncShutdownGracefully())
|
||||
}
|
||||
|
||||
func restrictBootstrapType(clientBootstrap: NIOTCPClientBootstrap) throws {
|
||||
let serverAcceptedChannelPromise = group.next().makePromise(of: Channel.self)
|
||||
let serverChannel = try assertNoThrowWithValue(ServerBootstrap(group: group)
|
||||
.serverChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
|
||||
.childChannelInitializer { channel in
|
||||
serverAcceptedChannelPromise.succeed(channel)
|
||||
return channel.eventLoop.makeSucceededFuture(())
|
||||
}.bind(host: "127.0.0.1", port: 0).wait())
|
||||
|
||||
let clientChannel = try assertNoThrowWithValue(clientBootstrap
|
||||
.channelInitializer({ (channel: Channel) in channel.eventLoop.makeSucceededFuture(()) })
|
||||
.connect(host: "127.0.0.1", port: serverChannel.localAddress!.port!).wait())
|
||||
|
||||
var buffer = clientChannel.allocator.buffer(capacity: 1)
|
||||
buffer.writeString("a")
|
||||
try clientChannel.writeAndFlush(NIOAny(buffer)).wait()
|
||||
|
||||
let serverAcceptedChannel = try serverAcceptedChannelPromise.futureResult.wait()
|
||||
|
||||
// Start shutting stuff down.
|
||||
XCTAssertNoThrow(try clientChannel.close().wait())
|
||||
|
||||
// Wait for the close promises. These fire last.
|
||||
XCTAssertNoThrow(try EventLoopFuture.andAllSucceed([clientChannel.closeFuture,
|
||||
serverAcceptedChannel.closeFuture],
|
||||
on: group.next()).wait())
|
||||
}
|
||||
|
||||
if let bootstrap = group.makeTCPClientBootstrap() {
|
||||
try restrictBootstrapType(clientBootstrap: bootstrap)
|
||||
} else {
|
||||
XCTFail("Did not generate a valid Bootstrap")
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user