Annotate code with availability attributes (#42)

* Annotate code with availability attributes

Motivation:

It was not possible to import NIOTS into a project where
Network.framework was not supported by all deployment targets.

Modifications:

All NIOTS code, where applicable, was annotated with availability
attributes.

Result:

It is possible for application developers to import NIOTS on platforms
which do not support Network.framework without a compile time error.
This commit is contained in:
George Barnett 2019-05-10 19:02:02 +01:00 committed by Johannes Weiss
parent e95a1e26d5
commit 3d0713dc43
16 changed files with 83 additions and 32 deletions

View File

@ -17,9 +17,6 @@ import PackageDescription
let package = Package(
name: "swift-nio-transport-services",
platforms: [
.macOS(.v10_14), .iOS(.v12), .tvOS(.v12),
],
products: [
.library(name: "NIOTransportServices", targets: ["NIOTransportServices"]),
.executable(name: "NIOTSHTTPClient", targets: ["NIOTSHTTPClient"]),

View File

@ -20,6 +20,7 @@ import NIOTransportServices
import NIOHTTP1
import Network
@available(OSX 10.14, iOS 12.0, tvOS 12.0, *)
final class HTTP1ClientHandler: ChannelInboundHandler {
typealias OutboundOut = HTTPClientRequestPart
typealias InboundIn = HTTPClientResponsePart
@ -58,17 +59,19 @@ final class HTTP1ClientHandler: ChannelInboundHandler {
}
}
let group = NIOTSEventLoopGroup()
let channel = try! NIOTSConnectionBootstrap(group: group)
.connectTimeout(.hours(1))
.channelOption(ChannelOptions.socket(IPPROTO_TCP, TCP_NODELAY), value: 1)
.tlsOptions(NWProtocolTLS.Options())
.channelInitializer { channel in
channel.pipeline.addHTTPClientHandlers().flatMap {
channel.pipeline.addHandler(HTTP1ClientHandler())
}
}.connect(host: "httpbin.org", port: 443).wait()
if #available(OSX 10.14, *) {
let group = NIOTSEventLoopGroup()
let channel = try! NIOTSConnectionBootstrap(group: group)
.connectTimeout(.hours(1))
.channelOption(ChannelOptions.socket(IPPROTO_TCP, TCP_NODELAY), value: 1)
.tlsOptions(NWProtocolTLS.Options())
.channelInitializer { channel in
channel.pipeline.addHTTPClientHandlers().flatMap {
channel.pipeline.addHandler(HTTP1ClientHandler())
}
}.connect(host: "httpbin.org", port: 443).wait()
// Wait for the request to complete
try! channel.closeFuture.wait()
// Wait for the request to complete
try! channel.closeFuture.wait()
}
#endif

View File

@ -20,6 +20,7 @@ import NIOTransportServices
import NIOHTTP1
import Network
@available(OSX 10.14, iOS 12.0, tvOS 12.0, *)
final class HTTP1ServerHandler: ChannelInboundHandler {
typealias InboundIn = HTTPServerRequestPart
typealias OutboundOut = HTTPServerResponsePart
@ -38,16 +39,18 @@ final class HTTP1ServerHandler: ChannelInboundHandler {
}
}
let group = NIOTSEventLoopGroup()
let channel = try! NIOTSListenerBootstrap(group: group)
.childChannelInitializer { channel in
channel.pipeline.configureHTTPServerPipeline(withPipeliningAssistance: true, withErrorHandling: true).flatMap {
channel.pipeline.addHandler(HTTP1ServerHandler())
}
}.bind(host: "127.0.0.1", port: 8888).wait()
if #available(OSX 10.14, *) {
let group = NIOTSEventLoopGroup()
let channel = try! NIOTSListenerBootstrap(group: group)
.childChannelInitializer { channel in
channel.pipeline.configureHTTPServerPipeline(withPipeliningAssistance: true, withErrorHandling: true).flatMap {
channel.pipeline.addHandler(HTTP1ServerHandler())
}
}.bind(host: "127.0.0.1", port: 8888).wait()
print("Server listening on \(channel.localAddress!)")
print("Server listening on \(channel.localAddress!)")
// Wait for the request to complete
try! channel.closeFuture.wait()
// Wait for the request to complete
try! channel.closeFuture.wait()
}
#endif

View File

@ -13,6 +13,7 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if canImport(Network)
import NIO
@ -24,6 +25,7 @@ import NIO
/// transitioning into the `failed` state, causing immediate connection failure.
///
/// This option is only valid with `NIOTSConnectionBootstrap`.
@available(OSX 10.14, iOS 12.0, tvOS 12.0, *)
public struct NIOTSWaitForActivityOption: ChannelOption, Equatable {
public typealias Value = Bool
@ -36,6 +38,7 @@ public struct NIOTSWaitForActivityOption: ChannelOption, Equatable {
/// `true`. By default this option is set to `false`.
///
/// This option must be set on the bootstrap: setting it after the channel is initialized will have no effect.
@available(OSX 10.14, iOS 12.0, tvOS 12.0, *)
public struct NIOTSEnablePeerToPeerOption: ChannelOption, Equatable {
public typealias Value = Bool
@ -44,9 +47,11 @@ public struct NIOTSEnablePeerToPeerOption: ChannelOption, Equatable {
/// Options that can be set explicitly and only on bootstraps provided by `NIOTransportServices`.
@available(OSX 10.14, iOS 12.0, tvOS 12.0, *)
public struct NIOTSChannelOptions {
/// - seealso: `NIOTSWaitForActivityOption`.
public static let waitForActivity = NIOTSWaitForActivityOption()
public static let enablePeerToPeer = NIOTSEnablePeerToPeerOption()
}
#endif

View File

@ -19,6 +19,7 @@ import NIO
import Dispatch
import Network
@available(OSX 10.14, iOS 12.0, tvOS 12.0, *)
public final class NIOTSConnectionBootstrap {
private let group: NIOTSEventLoopGroup
private var channelInitializer: ((Channel) -> EventLoopFuture<Void>)?
@ -177,6 +178,7 @@ public final class NIOTSConnectionBootstrap {
// This is a backport of ChannelOptions.Storage from SwiftNIO because the initializer wasn't public, so we couldn't actually build it.
// When https://github.com/apple/swift-nio/pull/988 is in a shipped release, we can remove this and simply bump our lowest supported version of SwiftNIO.
@available(OSX 10.14, iOS 12.0, tvOS 12.0, *)
internal struct ChannelOptionsStorage {
internal var _storage: [(Any, (Any, (Channel) -> (Any, Any) -> EventLoopFuture<Void>))] = []

View File

@ -25,6 +25,7 @@ import Network
import Security
/// Execute the given function and synchronously complete the given `EventLoopPromise` (if not `nil`).
@available(OSX 10.14, iOS 12.0, tvOS 12.0, *)
func executeAndComplete<T>(_ promise: EventLoopPromise<T>?, _ body: () throws -> T) {
do {
let result = try body()
@ -35,6 +36,7 @@ func executeAndComplete<T>(_ promise: EventLoopPromise<T>?, _ body: () throws ->
}
/// Merge two possible promises together such that firing the result will fire both.
@available(OSX 10.14, iOS 12.0, tvOS 12.0, *)
private func mergePromises(_ first: EventLoopPromise<Void>?, _ second: EventLoopPromise<Void>?) -> EventLoopPromise<Void>? {
if let first = first {
if let second = second {
@ -48,6 +50,7 @@ private func mergePromises(_ first: EventLoopPromise<Void>?, _ second: EventLoop
/// Channel options for the connection channel.
@available(OSX 10.14, iOS 12.0, tvOS 12.0, *)
private struct ConnectionChannelOptions {
/// Whether autoRead is enabled for this channel.
internal var autoRead: Bool = true
@ -65,6 +68,7 @@ private typealias PendingWrite = (data: ByteBuffer, promise: EventLoopPromise<Vo
/// A structure that manages backpressure signaling on this channel.
@available(OSX 10.14, iOS 12.0, tvOS 12.0, *)
private struct BackpressureManager {
/// Whether the channel is writable, given the current watermark state.
///
@ -140,6 +144,7 @@ private struct BackpressureManager {
}
@available(OSX 10.14, iOS 12.0, tvOS 12.0, *)
internal final class NIOTSConnectionChannel {
/// The `ByteBufferAllocator` for this `Channel`.
public let allocator = ByteBufferAllocator()
@ -243,6 +248,7 @@ internal final class NIOTSConnectionChannel {
// MARK:- NIOTSConnectionChannel implementation of Channel
@available(OSX 10.14, iOS 12.0, tvOS 12.0, *)
extension NIOTSConnectionChannel: Channel {
/// The `ChannelPipeline` for this `Channel`.
public var pipeline: ChannelPipeline {
@ -378,6 +384,7 @@ extension NIOTSConnectionChannel: Channel {
// MARK:- NIOTSConnectionChannel implementation of StateManagedChannel.
@available(OSX 10.14, iOS 12.0, tvOS 12.0, *)
extension NIOTSConnectionChannel: StateManagedChannel {
typealias ActiveSubstate = TCPSubstate
@ -625,6 +632,7 @@ extension NIOTSConnectionChannel: StateManagedChannel {
// MARK:- Implementations of the callbacks passed to NWConnection.
@available(OSX 10.14, iOS 12.0, tvOS 12.0, *)
extension NIOTSConnectionChannel {
/// Called by the underlying `NWConnection` when its internal state has changed.
private func stateUpdateHandler(newState: NWConnection.State) {
@ -653,7 +661,7 @@ extension NIOTSConnectionChannel {
// This is the network telling us we're closed. We don't need to actually do anything here
// other than check our state is ok.
assert(self.closed)
self.nwConnection = nil
self.nwConnection = nil
case .failed(let err):
// The connection has failed for some reason.
self.close0(error: err, mode: .all, promise: nil)
@ -724,6 +732,7 @@ extension NIOTSConnectionChannel {
// MARK:- Implementations of state management for the channel.
@available(OSX 10.14, iOS 12.0, tvOS 12.0, *)
extension NIOTSConnectionChannel {
/// Whether the inbound side of the connection is still open.
private var inboundStreamOpen: Bool {
@ -780,6 +789,7 @@ extension NIOTSConnectionChannel {
// MARK:- Managing TCP substate.
@available(OSX 10.14, iOS 12.0, tvOS 12.0, *)
fileprivate extension ChannelState where ActiveSubstate == NIOTSConnectionChannel.TCPSubstate {
/// Close the input side of the TCP state machine.
mutating func closeInput() throws {

View File

@ -13,13 +13,16 @@
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if canImport(Network)
import NIO
/// A tag protocol that can be used to cover all errors thrown by `NIOTransportServices`.
///
/// Users are strongly encouraged not to conform their own types to this protocol.
@available(OSX 10.14, iOS 12.0, tvOS 12.0, *)
public protocol NIOTSError: Error, Equatable { }
@available(OSX 10.14, iOS 12.0, tvOS 12.0, *)
public enum NIOTSErrors {
/// `InvalidChannelStateTransition` is thrown when a channel has been asked to do something
/// that is incompatible with its current channel state: e.g. attempting to register an
@ -55,3 +58,4 @@ public enum NIOTSErrors {
/// insufficient information is available to create it.
public struct UnableToResolveEndpoint: NIOTSError { }
}
#endif

View File

@ -27,6 +27,7 @@ import NIOConcurrencyHelpers
/// `EventLoop`s that implement `QoSEventLoop` can interact with `Dispatch` to propagate information
/// about the QoS required for a specific task block. This allows tasks to be dispatched onto an
/// event loop with a different priority than the majority of tasks on that loop.
@available(OSX 10.14, iOS 12.0, tvOS 12.0, *)
public protocol QoSEventLoop: EventLoop {
/// Submit a given task to be executed by the `EventLoop` at a given `qos`.
func execute(qos: DispatchQoS, _ task: @escaping () -> Void) -> Void
@ -44,6 +45,7 @@ public protocol QoSEventLoop: EventLoop {
/// new registrations, but it will continue to accept new scheduled work items. When a loop is closed, it
/// will accept neither new registrations nor new scheduled work items, but it will continue to process
/// the queue until it has drained.
@available(OSX 10.14, iOS 12.0, tvOS 12.0, *)
fileprivate enum LifecycleState {
case active
case closing
@ -51,6 +53,7 @@ fileprivate enum LifecycleState {
}
@available(OSX 10.14, iOS 12.0, tvOS 12.0, *)
internal class NIOTSEventLoop: QoSEventLoop {
private let loop: DispatchQueue
private let taskQueue: DispatchQueue
@ -85,7 +88,7 @@ internal class NIOTSEventLoop: QoSEventLoop {
}
public init(qos: DispatchQoS) {
self.loop = DispatchQueue(label: "nio.transportservices.eventloop.loop", qos: qos, autoreleaseFrequency: .workItem)
self.loop = DispatchQueue(label: "nio.transportservices.eventloop.loop", qos: qos, autoreleaseFrequency: .workItem)
self.taskQueue = DispatchQueue(label: "nio.transportservices.eventloop.taskqueue", target: self.loop)
self.loopID = UUID()
self.inQueueKey = DispatchSpecificKey()
@ -153,6 +156,7 @@ internal class NIOTSEventLoop: QoSEventLoop {
}
}
@available(OSX 10.14, iOS 12.0, tvOS 12.0, *)
extension NIOTSEventLoop {
/// Create a `DispatchQueue` to use for events on a given `Channel`.
///
@ -165,6 +169,7 @@ extension NIOTSEventLoop {
}
}
@available(OSX 10.14, iOS 12.0, tvOS 12.0, *)
extension NIOTSEventLoop {
internal func closeGently() -> EventLoopFuture<Void> {
let p: EventLoopPromise<Void> = self.makePromise()
@ -203,6 +208,7 @@ extension NIOTSEventLoop {
}
}
@available(OSX 10.14, iOS 12.0, tvOS 12.0, *)
extension NIOTSEventLoop {
/// Record a given channel with this event loop.
internal func register(_ channel: Channel) throws {

View File

@ -47,6 +47,7 @@ import Network
/// platforms, the `NIOTSEventLoopGroup` should be preferred over the
/// `MultiThreadedEventLoopGroup`. In particular, on iOS, the `NIOTSEventLoopGroup` is the
/// preferred networking backend.
@available(OSX 10.14, iOS 12.0, tvOS 12.0, *)
public final class NIOTSEventLoopGroup: EventLoopGroup {
private let index = Atomic<Int>(value: 0)
private let eventLoops: [NIOTSEventLoop]

View File

@ -19,6 +19,7 @@ import NIO
import Dispatch
import Network
@available(OSX 10.14, iOS 12.0, tvOS 12.0, *)
public final class NIOTSListenerBootstrap {
private let group: EventLoopGroup
private let childGroup: EventLoopGroup
@ -237,6 +238,7 @@ public final class NIOTSListenerBootstrap {
}
@available(OSX 10.14, iOS 12.0, tvOS 12.0, *)
private class AcceptHandler: ChannelInboundHandler {
typealias InboundIn = NWConnection
typealias InboundOut = NIOTSConnectionChannel

View File

@ -22,6 +22,7 @@ import NIOConcurrencyHelpers
import Dispatch
import Network
@available(OSX 10.14, iOS 12.0, tvOS 12.0, *)
internal final class NIOTSListenerChannel {
/// The `ByteBufferAllocator` for this `Channel`.
public let allocator = ByteBufferAllocator()
@ -102,6 +103,7 @@ internal final class NIOTSListenerChannel {
// MARK:- NIOTSListenerChannel implementation of Channel
@available(OSX 10.14, iOS 12.0, tvOS 12.0, *)
extension NIOTSListenerChannel: Channel {
/// The `ChannelPipeline` for this `Channel`.
public var pipeline: ChannelPipeline {
@ -217,6 +219,7 @@ extension NIOTSListenerChannel: Channel {
// MARK:- NIOTSListenerChannel implementation of StateManagedChannel.
@available(OSX 10.14, iOS 12.0, tvOS 12.0, *)
extension NIOTSListenerChannel: StateManagedChannel {
typealias ActiveSubstate = ListenerActiveSubstate
@ -329,7 +332,7 @@ extension NIOTSListenerChannel: StateManagedChannel {
if let listener = self.nwListener {
listener.cancel()
}
// Step 2: fail any pending bind promise.
if let pendingBind = self.bindPromise {
self.bindPromise = nil
@ -376,6 +379,7 @@ extension NIOTSListenerChannel: StateManagedChannel {
// MARK:- Implementations of the callbacks passed to NWListener.
@available(OSX 10.14, iOS 12.0, tvOS 12.0, *)
extension NIOTSListenerChannel {
/// Called by the underlying `NWListener` when its internal state has changed.
private func stateUpdateHandler(newState: NWListener.State) {
@ -391,7 +395,7 @@ extension NIOTSListenerChannel {
// This is the network telling us we're closed. We don't need to actually do anything here
// other than check our state is ok.
assert(self.closed)
self.nwListener = nil
self.nwListener = nil
case .failed(let err):
// The connection has failed for some reason.
self.close0(error: err, mode: .all, promise: nil)
@ -415,6 +419,7 @@ extension NIOTSListenerChannel {
// MARK:- Implementations of state management for the channel.
@available(OSX 10.14, iOS 12.0, tvOS 12.0, *)
extension NIOTSListenerChannel {
/// Make the channel active.
private func bindComplete0() {

View File

@ -21,8 +21,10 @@ import NIO
/// A tag protocol that can be used to cover all network events emitted by `NIOTS`.
///
/// Users are strongly encouraged not to conform their own types to this protocol.
@available(OSX 10.14, iOS 12.0, tvOS 12.0, *)
public protocol NIOTSNetworkEvent: Equatable { }
@available(OSX 10.14, iOS 12.0, tvOS 12.0, *)
public enum NIOTSNetworkEvents {
/// This event is fired whenever the OS has informed NIO that there is a better
/// path available to the endpoint that this `Channel` is currently connected to,

View File

@ -20,6 +20,7 @@ import Foundation
import NIO
import Network
@available(OSX 10.14, iOS 12.0, tvOS 12.0, *)
extension IPv4Address {
/// Create an `IPv4Address` object from a `sockaddr_in`.
internal init(fromSockAddr sockAddr: sockaddr_in) {
@ -32,6 +33,7 @@ extension IPv4Address {
}
}
@available(OSX 10.14, iOS 12.0, tvOS 12.0, *)
extension IPv6Address {
internal init(fromSockAddr sockAddr: sockaddr_in6) {
var localAddr = sockAddr
@ -46,6 +48,7 @@ extension IPv6Address {
}
}
@available(OSX 10.14, iOS 12.0, tvOS 12.0, *)
extension NWEndpoint {
/// Create an `NWEndpoint` value from a NIO `SocketAddress`.
internal init(fromSocketAddress socketAddress: SocketAddress) {
@ -71,6 +74,7 @@ extension NWEndpoint {
// TODO: We'll want to get rid of this when we support returning NWEndpoint directly from
// the various address-handling functions.
@available(OSX 10.14, iOS 12.0, tvOS 12.0, *)
extension SocketAddress {
internal init(fromNWEndpoint endpoint: NWEndpoint) throws {
switch endpoint {
@ -106,6 +110,7 @@ extension SocketAddress {
}
}
@available(OSX 10.14, iOS 12.0, tvOS 12.0, *)
internal extension SocketAddress {
/// Change the port on this `SocketAddress` to a new value.
mutating func newPort(_ port: UInt16) {

View File

@ -27,6 +27,7 @@ import Network
/// active state. This can be used to provide more fine-grained tracking of states
/// within the active state of a channel. Example uses include for tracking TCP half-closure
/// state in a TCP stream channel.
@available(OSX 10.14, iOS 12.0, tvOS 12.0, *)
internal protocol ActiveChannelSubstate {
/// Create the substate in its default initial state.
init()
@ -34,6 +35,7 @@ internal protocol ActiveChannelSubstate {
/// A state machine enum that tracks the state of the connection channel.
@available(OSX 10.14, iOS 12.0, tvOS 12.0, *)
internal enum ChannelState<ActiveSubstate: ActiveChannelSubstate> {
case idle
case registered
@ -83,6 +85,7 @@ internal enum ChannelState<ActiveSubstate: ActiveChannelSubstate> {
/// The kinds of activation that a channel may support.
@available(OSX 10.14, iOS 12.0, tvOS 12.0, *)
internal enum ActivationType {
case connect
case bind
@ -95,6 +98,7 @@ internal enum ActivationType {
/// This protocol provides default hooks for managing state appropriately for a
/// given channel. It also provides some default implementations of `Channel` methods
/// for simple behaviours.
@available(OSX 10.14, iOS 12.0, tvOS 12.0, *)
internal protocol StateManagedChannel: Channel, ChannelCore {
associatedtype ActiveSubstate: ActiveChannelSubstate
@ -121,6 +125,7 @@ internal protocol StateManagedChannel: Channel, ChannelCore {
func readIfNeeded0() -> Void
}
@available(OSX 10.14, iOS 12.0, tvOS 12.0, *)
extension StateManagedChannel {
public var eventLoop: EventLoop {
return self.tsEventLoop

View File

@ -19,6 +19,7 @@ import Foundation
import NIO
import Network
@available(OSX 10.14, iOS 12.0, tvOS 12.0, *)
internal extension NWProtocolTCP.Options {
/// Apply a given channel `SocketOption` to this protocol options state.
func applyChannelOption(option: SocketOption, value: SocketOptionValue) throws {

View File

@ -62,9 +62,9 @@ Pod::Spec.new do |s|
s.swift_version = '5.0'
s.cocoapods_version = '>=1.6.0'
s.ios.deployment_target = '12.0'
s.osx.deployment_target = '10.14'
s.tvos.deployment_target = '12.0'
s.ios.deployment_target = '10.0'
s.osx.deployment_target = '10.12'
s.tvos.deployment_target = '10.0'
s.source_files = 'Sources/NIOTransportServices/**/*.swift'
s.dependency 'SwiftNIO', '~> 2.0'