mirror of
https://github.com/apple/swift-nio
synced 2026-11-28 05:14:23 +00:00
Shorthand way of setting options in universal bootstrap (#1547)
Motivation: Guide novice users towards the options they are most likely to want to use. Modifications: New type to represent shorthand TCP client options containing only the options which are sensible for novice users. New type to represent a collection of these options. A method to allow underlying bootstraps to override universal behaviour - default implementation is to do nothing. A test case to demonstrate that shorthand options match old style options. A test case to demonstrate that overriding option behaviour is possible. Result: For universal botostrap there will be an new way of setting options involving less typing which guides the user towards the common options.
This commit is contained in:
1 parent
7b93c22836
commit
9f732b2382
6 files changed
+340
No files matched your search
@@ -0,0 +1,186 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the SwiftNIO open source project
|
||||
//
|
||||
// Copyright (c) 2020 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
// MARK: Universal Client Bootstrap
|
||||
extension NIOClientTCPBootstrapProtocol {
|
||||
/// Apply any understood convenience options to the bootstrap, removing them from the set of options if they are consumed.
|
||||
/// - parameters:
|
||||
/// - options: The options to try applying - the options applied should be consumed from here.
|
||||
/// - returns: The updated bootstrap with and options applied.
|
||||
public func _applyChannelConvenienceOptions(_ options: inout ChannelOptions.TCPConvenienceOptions) -> Self {
|
||||
// Default is to consume no options and not update self.
|
||||
return self
|
||||
}
|
||||
}
|
||||
|
||||
extension NIOClientTCPBootstrap {
|
||||
/// Specifies some `TCPConvenienceOption`s to be applied to the channel.
|
||||
/// These are preferred over regular channel options as they are easier to use and restrict
|
||||
/// options to those which a normal user would consider.
|
||||
/// - Parameter options: Set of convenience options to apply.
|
||||
/// - Returns: The updated bootstrap (`self` being mutated)
|
||||
public func channelConvenienceOptions(_ options: ChannelOptions.TCPConvenienceOptions) -> NIOClientTCPBootstrap {
|
||||
var optionsRemaining = options
|
||||
// First give the underlying a chance to consume options.
|
||||
let withUnderlyingOverrides =
|
||||
NIOClientTCPBootstrap(self,
|
||||
updating: underlyingBootstrap._applyChannelConvenienceOptions(&optionsRemaining))
|
||||
// Default apply any remaining options.
|
||||
return optionsRemaining.applyFallbackMapping(withUnderlyingOverrides)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Utility
|
||||
extension ChannelOptions.Types {
|
||||
/// Has an option been set?
|
||||
/// Option has a value of generic type ValueType.
|
||||
public enum ConvenienceOptionValue<ValueType> {
|
||||
/// The option was not set.
|
||||
case notSet
|
||||
/// The option was set with a value of type ValueType.
|
||||
case set(ValueType)
|
||||
}
|
||||
}
|
||||
|
||||
extension ChannelOptions.Types.ConvenienceOptionValue where ValueType == () {
|
||||
/// Convenience method working with bool options as bool values for set.
|
||||
public var isSet: Bool {
|
||||
get {
|
||||
switch self {
|
||||
case .notSet:
|
||||
return false
|
||||
case .set(()):
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension ChannelOptions.Types.ConvenienceOptionValue where ValueType == () {
|
||||
fileprivate init(flag: Bool) {
|
||||
if flag {
|
||||
self = .set(())
|
||||
} else {
|
||||
self = .notSet
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: TCP - data
|
||||
extension ChannelOptions {
|
||||
/// A TCP channel option which can be applied to a bootstrap using convenience notation.
|
||||
public struct TCPConvenienceOption: Hashable {
|
||||
fileprivate var data: ConvenienceOption
|
||||
|
||||
private init(_ data: ConvenienceOption) {
|
||||
self.data = data
|
||||
}
|
||||
|
||||
fileprivate enum ConvenienceOption: Hashable {
|
||||
case allowLocalEndpointReuse
|
||||
case disableAutoRead
|
||||
case allowRemoteHalfClosure
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Approved convenience options.
|
||||
extension ChannelOptions.TCPConvenienceOption {
|
||||
/// Allow immediately reusing a local address.
|
||||
public static let allowLocalEndpointReuse = ChannelOptions.TCPConvenienceOption(.allowLocalEndpointReuse)
|
||||
|
||||
/// The user will manually call `Channel.read` once all the data is read from the transport.
|
||||
public static let disableAutoRead = ChannelOptions.TCPConvenienceOption(.disableAutoRead)
|
||||
|
||||
/// Allows users to configure whether the `Channel` will close itself when its remote
|
||||
/// peer shuts down its send stream, or whether it will remain open. If set to `false` (the default), the `Channel`
|
||||
/// will be closed automatically if the remote peer shuts down its send stream. If set to true, the `Channel` will
|
||||
/// not be closed: instead, a `ChannelEvent.inboundClosed` user event will be sent on the `ChannelPipeline`,
|
||||
/// and no more data will be received.
|
||||
public static let allowRemoteHalfClosure =
|
||||
ChannelOptions.TCPConvenienceOption(.allowRemoteHalfClosure)
|
||||
}
|
||||
|
||||
extension ChannelOptions {
|
||||
/// A set of `TCPConvenienceOption`s
|
||||
public struct TCPConvenienceOptions: ExpressibleByArrayLiteral, Hashable {
|
||||
var allowLocalEndpointReuse = false
|
||||
var disableAutoRead = false
|
||||
var allowRemoteHalfClosure = false
|
||||
|
||||
/// Construct from an array literal.
|
||||
@inlinable
|
||||
public init(arrayLiteral elements: TCPConvenienceOption...) {
|
||||
for element in elements {
|
||||
self.add(element)
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
mutating func add(_ element: TCPConvenienceOption) {
|
||||
switch element.data {
|
||||
case .allowLocalEndpointReuse:
|
||||
self.allowLocalEndpointReuse = true
|
||||
case .allowRemoteHalfClosure:
|
||||
self.allowRemoteHalfClosure = true
|
||||
case .disableAutoRead:
|
||||
self.disableAutoRead = true
|
||||
}
|
||||
}
|
||||
|
||||
/// Caller is consuming the knowledge that `allowLocalEndpointReuse` was set or not.
|
||||
/// The setting will nolonger be set after this call.
|
||||
/// - Returns: If `allowLocalEndpointReuse` was set.
|
||||
public mutating func consumeAllowLocalEndpointReuse() -> Types.ConvenienceOptionValue<Void> {
|
||||
defer {
|
||||
self.allowLocalEndpointReuse = false
|
||||
}
|
||||
return Types.ConvenienceOptionValue<Void>(flag: self.allowLocalEndpointReuse)
|
||||
}
|
||||
|
||||
/// Caller is consuming the knowledge that disableAutoRead was set or not.
|
||||
/// The setting will nolonger be set after this call.
|
||||
/// - Returns: If disableAutoRead was set.
|
||||
public mutating func consumeDisableAutoRead() -> Types.ConvenienceOptionValue<Void> {
|
||||
defer {
|
||||
self.disableAutoRead = false
|
||||
}
|
||||
return Types.ConvenienceOptionValue<Void>(flag: self.disableAutoRead)
|
||||
}
|
||||
|
||||
/// Caller is consuming the knowledge that allowRemoteHalfClosure was set or not.
|
||||
/// The setting will nolonger be set after this call.
|
||||
/// - Returns: If allowRemoteHalfClosure was set.
|
||||
public mutating func consumeAllowRemoteHalfClosure() -> Types.ConvenienceOptionValue<Void> {
|
||||
defer {
|
||||
self.allowRemoteHalfClosure = false
|
||||
}
|
||||
return Types.ConvenienceOptionValue<Void>(flag: self.allowRemoteHalfClosure)
|
||||
}
|
||||
|
||||
mutating func applyFallbackMapping(_ universalBootstrap: NIOClientTCPBootstrap) -> NIOClientTCPBootstrap {
|
||||
var result = universalBootstrap
|
||||
if self.consumeAllowLocalEndpointReuse().isSet {
|
||||
result = result.channelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1)
|
||||
}
|
||||
if self.consumeAllowRemoteHalfClosure().isSet {
|
||||
result = result.channelOption(ChannelOptions.allowRemoteHalfClosure, value: true)
|
||||
}
|
||||
if self.consumeDisableAutoRead().isSet {
|
||||
result = result.channelOption(ChannelOptions.autoRead, value: false)
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -48,6 +48,13 @@ public protocol NIOClientTCPBootstrapProtocol {
|
||||
/// - option: The option to be applied.
|
||||
/// - value: The value for the option.
|
||||
func channelOption<Option: ChannelOption>(_ option: Option, value: Option.Value) -> Self
|
||||
|
||||
/// Apply any understood convenience options to the bootstrap, removing them from the set of options if they are consumed.
|
||||
/// Method is optional to implement and should never be directly called by users.
|
||||
/// - parameters:
|
||||
/// - options: The options to try applying - the options applied should be consumed from here.
|
||||
/// - returns: The updated bootstrap with and options applied.
|
||||
func _applyChannelConvenienceOptions(_ options: inout ChannelOptions.TCPConvenienceOptions) -> Self
|
||||
|
||||
/// - parameters:
|
||||
/// - timeout: The timeout that will apply to the connection attempt.
|
||||
@@ -158,6 +165,11 @@ public struct NIOClientTCPBootstrap {
|
||||
self.underlyingBootstrap = bootstrap
|
||||
self.tlsEnablerTypeErased = tlsEnabler
|
||||
}
|
||||
|
||||
internal init(_ original : NIOClientTCPBootstrap, updating underlying : NIOClientTCPBootstrapProtocol) {
|
||||
self.underlyingBootstrap = underlying
|
||||
self.tlsEnablerTypeErased = original.tlsEnablerTypeErased
|
||||
}
|
||||
|
||||
/// Initialize the connected `SocketChannel` with `initializer`. The most common task in initializer is to add
|
||||
/// `ChannelHandler`s to the `ChannelPipeline`.
|
||||
|
||||
@@ -48,6 +48,7 @@ extension BootstrapTest {
|
||||
("testDatagramBootstrapRejectsNotWorkingELGsCorrectly", testDatagramBootstrapRejectsNotWorkingELGsCorrectly),
|
||||
("testNIOPipeBootstrapValidatesWorkingELGsCorrectly", testNIOPipeBootstrapValidatesWorkingELGsCorrectly),
|
||||
("testNIOPipeBootstrapRejectsNotWorkingELGsCorrectly", testNIOPipeBootstrapRejectsNotWorkingELGsCorrectly),
|
||||
("testConvenienceOptionsAreEquivalentUniversalClient", testConvenienceOptionsAreEquivalentUniversalClient),
|
||||
("testClientBindWorksOnSocketsBoundToEitherIPv4OrIPv6Only", testClientBindWorksOnSocketsBoundToEitherIPv4OrIPv6Only),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -529,6 +529,52 @@ class BootstrapTest: XCTestCase {
|
||||
XCTAssertNil(NIOPipeBootstrap(validatingGroup: elg))
|
||||
XCTAssertNil(NIOPipeBootstrap(validatingGroup: el))
|
||||
}
|
||||
|
||||
func testConvenienceOptionsAreEquivalentUniversalClient() throws {
|
||||
func setAndGetOption<Option>(option: Option, _ applyOptions : (NIOClientTCPBootstrap) -> NIOClientTCPBootstrap) throws
|
||||
-> Option.Value where Option : ChannelOption {
|
||||
var optionRead : EventLoopFuture<Option.Value>?
|
||||
XCTAssertNoThrow(try withTCPServerChannel(group: self.group) { server in
|
||||
var channel: Channel? = nil
|
||||
XCTAssertNoThrow(channel = try applyOptions(NIOClientTCPBootstrap(
|
||||
ClientBootstrap(group: self.group), tls: NIOInsecureNoTLS()))
|
||||
.channelInitializer { channel in optionRead = channel.getOption(option)
|
||||
return channel.eventLoop.makeSucceededFuture(())
|
||||
}
|
||||
.connect(to: server.localAddress!)
|
||||
.wait())
|
||||
XCTAssertNotNil(optionRead)
|
||||
XCTAssertNotNil(channel)
|
||||
XCTAssertNoThrow(try channel?.close().wait())
|
||||
})
|
||||
return try optionRead!.wait()
|
||||
}
|
||||
|
||||
func checkOptionEquivalence<Option>(longOption: Option, setValue: Option.Value,
|
||||
shortOption: ChannelOptions.TCPConvenienceOption) throws
|
||||
where Option : ChannelOption, Option.Value : Equatable {
|
||||
let longSetValue = try setAndGetOption(option: longOption) { bs in
|
||||
bs.channelOption(longOption, value: setValue)
|
||||
}
|
||||
let shortSetValue = try setAndGetOption(option: longOption) { bs in
|
||||
bs.channelConvenienceOptions([shortOption])
|
||||
}
|
||||
let unsetValue = try setAndGetOption(option: longOption) { $0 }
|
||||
|
||||
XCTAssertEqual(longSetValue, shortSetValue)
|
||||
XCTAssertNotEqual(longSetValue, unsetValue)
|
||||
}
|
||||
|
||||
try checkOptionEquivalence(longOption: ChannelOptions.socketOption(.so_reuseaddr),
|
||||
setValue: 1,
|
||||
shortOption: .allowLocalEndpointReuse)
|
||||
try checkOptionEquivalence(longOption: ChannelOptions.allowRemoteHalfClosure,
|
||||
setValue: true,
|
||||
shortOption: .allowRemoteHalfClosure)
|
||||
try checkOptionEquivalence(longOption: ChannelOptions.autoRead,
|
||||
setValue: false,
|
||||
shortOption: .disableAutoRead)
|
||||
}
|
||||
|
||||
func testClientBindWorksOnSocketsBoundToEitherIPv4OrIPv6Only() {
|
||||
for isIPv4 in [true, false] {
|
||||
|
||||
@@ -28,6 +28,7 @@ extension UniversalBootstrapSupportTest {
|
||||
static var allTests : [(String, (UniversalBootstrapSupportTest) -> () throws -> Void)] {
|
||||
return [
|
||||
("testBootstrappingWorks", testBootstrappingWorks),
|
||||
("testBootstrapOverrideOfShortcutOptions", testBootstrapOverrideOfShortcutOptions),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -135,4 +135,98 @@ class UniversalBootstrapSupportTest: XCTestCase {
|
||||
XCTAssertEqual(0, counter2.channelReadCalls)
|
||||
})
|
||||
}
|
||||
|
||||
func testBootstrapOverrideOfShortcutOptions() {
|
||||
final class FakeBootstrap : NIOClientTCPBootstrapProtocol {
|
||||
func channelInitializer(_ handler: @escaping (Channel) -> EventLoopFuture<Void>) -> Self {
|
||||
fatalError("Not implemented")
|
||||
}
|
||||
|
||||
func protocolHandlers(_ handlers: @escaping () -> [ChannelHandler]) -> Self {
|
||||
fatalError("Not implemented")
|
||||
}
|
||||
|
||||
var regularOptionsSeen = false
|
||||
func channelOption<Option>(_ option: Option, value: Option.Value) -> Self where Option : ChannelOption {
|
||||
regularOptionsSeen = true
|
||||
return self
|
||||
}
|
||||
|
||||
var convenienceOptionConsumed = false
|
||||
func _applyChannelConvenienceOptions(_ options: inout ChannelOptions.TCPConvenienceOptions) -> FakeBootstrap {
|
||||
if options.consumeAllowLocalEndpointReuse().isSet {
|
||||
convenienceOptionConsumed = true
|
||||
}
|
||||
return self
|
||||
}
|
||||
|
||||
func connectTimeout(_ timeout: TimeAmount) -> Self {
|
||||
fatalError("Not implemented")
|
||||
}
|
||||
|
||||
func connect(host: String, port: Int) -> EventLoopFuture<Channel> {
|
||||
fatalError("Not implemented")
|
||||
}
|
||||
|
||||
func connect(to address: SocketAddress) -> EventLoopFuture<Channel> {
|
||||
fatalError("Not implemented")
|
||||
}
|
||||
|
||||
func connect(unixDomainSocketPath: String) -> EventLoopFuture<Channel> {
|
||||
fatalError("Not implemented")
|
||||
}
|
||||
}
|
||||
|
||||
// Check consumption works.
|
||||
let consumingFake = FakeBootstrap()
|
||||
_ = NIOClientTCPBootstrap(consumingFake, tls: NIOInsecureNoTLS())
|
||||
.channelConvenienceOptions([.allowLocalEndpointReuse])
|
||||
XCTAssertTrue(consumingFake.convenienceOptionConsumed)
|
||||
XCTAssertFalse(consumingFake.regularOptionsSeen)
|
||||
|
||||
// Check default behaviour works.
|
||||
let nonConsumingFake = FakeBootstrap()
|
||||
_ = NIOClientTCPBootstrap(nonConsumingFake, tls: NIOInsecureNoTLS())
|
||||
.channelConvenienceOptions([.allowRemoteHalfClosure])
|
||||
XCTAssertFalse(nonConsumingFake.convenienceOptionConsumed)
|
||||
XCTAssertTrue(nonConsumingFake.regularOptionsSeen)
|
||||
|
||||
// Both at once.
|
||||
let bothFake = FakeBootstrap()
|
||||
_ = NIOClientTCPBootstrap(bothFake, tls: NIOInsecureNoTLS())
|
||||
.channelConvenienceOptions([.allowRemoteHalfClosure, .allowLocalEndpointReuse])
|
||||
XCTAssertTrue(bothFake.convenienceOptionConsumed)
|
||||
XCTAssertTrue(bothFake.regularOptionsSeen)
|
||||
}
|
||||
}
|
||||
|
||||
// Prove we've not broken implementors of NIOClientTCPBootstrapProtocol by adding a new method.
|
||||
private class UniversalWithoutNewMethods : NIOClientTCPBootstrapProtocol {
|
||||
func channelInitializer(_ handler: @escaping (Channel) -> EventLoopFuture<Void>) -> Self {
|
||||
return self
|
||||
}
|
||||
|
||||
func protocolHandlers(_ handlers: @escaping () -> [ChannelHandler]) -> Self {
|
||||
return self
|
||||
}
|
||||
|
||||
func channelOption<Option>(_ option: Option, value: Option.Value) -> Self where Option : ChannelOption {
|
||||
return self
|
||||
}
|
||||
|
||||
func connectTimeout(_ timeout: TimeAmount) -> Self {
|
||||
return self
|
||||
}
|
||||
|
||||
func connect(host: String, port: Int) -> EventLoopFuture<Channel> {
|
||||
return EmbeddedEventLoop().makePromise(of: Channel.self).futureResult
|
||||
}
|
||||
|
||||
func connect(to address: SocketAddress) -> EventLoopFuture<Channel> {
|
||||
return EmbeddedEventLoop().makePromise(of: Channel.self).futureResult
|
||||
}
|
||||
|
||||
func connect(unixDomainSocketPath: String) -> EventLoopFuture<Channel> {
|
||||
return EmbeddedEventLoop().makePromise(of: Channel.self).futureResult
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user