2
0

PlatformSupport.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. /*
  2. * Copyright 2019, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import Logging
  17. import NIOCore
  18. import NIOPosix
  19. import NIOTransportServices
  20. /// How a network implementation should be chosen.
  21. public struct NetworkPreference: Hashable {
  22. private enum Wrapped: Hashable {
  23. case best
  24. case userDefined(NetworkImplementation)
  25. }
  26. private var wrapped: Wrapped
  27. private init(_ wrapped: Wrapped) {
  28. self.wrapped = wrapped
  29. }
  30. /// Use the best available, that is, Network.framework (and NIOTransportServices) when it is
  31. /// available on Darwin platforms (macOS 10.14+, iOS 12.0+, tvOS 12.0+, watchOS 6.0+), and
  32. /// falling back to the POSIX network model otherwise.
  33. public static let best = NetworkPreference(.best)
  34. /// Use the given implementation. Doing so may require additional availability checks depending
  35. /// on the implementation.
  36. public static func userDefined(_ implementation: NetworkImplementation) -> NetworkPreference {
  37. return NetworkPreference(.userDefined(implementation))
  38. }
  39. }
  40. /// The network implementation to use: POSIX sockets or Network.framework. This also determines
  41. /// which variant of NIO to use; NIO or NIOTransportServices, respectively.
  42. public struct NetworkImplementation: Hashable {
  43. fileprivate enum Wrapped: Hashable {
  44. case networkFramework
  45. case posix
  46. }
  47. fileprivate var wrapped: Wrapped
  48. private init(_ wrapped: Wrapped) {
  49. self.wrapped = wrapped
  50. }
  51. #if canImport(Network)
  52. /// Network.framework (NIOTransportServices).
  53. @available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *)
  54. public static let networkFramework = NetworkImplementation(.networkFramework)
  55. #endif
  56. /// POSIX (NIO).
  57. public static let posix = NetworkImplementation(.posix)
  58. internal static func matchingEventLoopGroup(_ group: EventLoopGroup) -> NetworkImplementation {
  59. #if canImport(Network)
  60. if #available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *) {
  61. if PlatformSupport.isTransportServicesEventLoopGroup(group) {
  62. return .networkFramework
  63. }
  64. }
  65. #endif
  66. return .posix
  67. }
  68. }
  69. extension NetworkPreference {
  70. /// The network implementation, and by extension the NIO variant which will be used.
  71. ///
  72. /// Network.framework is available on macOS 10.14+, iOS 12.0+, tvOS 12.0+ and watchOS 6.0+.
  73. ///
  74. /// This isn't directly useful when implementing code which branches on the network preference
  75. /// since that code will still need the appropriate availability check:
  76. ///
  77. /// - `@available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *)`, or
  78. /// - `#available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *)`.
  79. public var implementation: NetworkImplementation {
  80. switch self.wrapped {
  81. case .best:
  82. #if canImport(Network)
  83. if #available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *) {
  84. return .networkFramework
  85. } else {
  86. // Older platforms must use the POSIX loop.
  87. return .posix
  88. }
  89. #else
  90. return .posix
  91. #endif
  92. case let .userDefined(implementation):
  93. return implementation
  94. }
  95. }
  96. }
  97. // MARK: - Generic Bootstraps
  98. // TODO: Revisit the handling of NIO/NIOTS once https://github.com/apple/swift-nio/issues/796
  99. // is addressed.
  100. /// This protocol is intended as a layer of abstraction over `ClientBootstrap` and
  101. /// `NIOTSConnectionBootstrap`.
  102. public protocol ClientBootstrapProtocol {
  103. func connect(to: SocketAddress) -> EventLoopFuture<Channel>
  104. func connect(host: String, port: Int) -> EventLoopFuture<Channel>
  105. func connect(unixDomainSocketPath: String) -> EventLoopFuture<Channel>
  106. func connectTimeout(_ timeout: TimeAmount) -> Self
  107. func channelOption<T>(_ option: T, value: T.Value) -> Self where T: ChannelOption
  108. func channelInitializer(_ handler: @escaping (Channel) -> EventLoopFuture<Void>) -> Self
  109. }
  110. extension ClientBootstrap: ClientBootstrapProtocol {}
  111. #if canImport(Network)
  112. @available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *)
  113. extension NIOTSConnectionBootstrap: ClientBootstrapProtocol {}
  114. #endif
  115. /// This protocol is intended as a layer of abstraction over `ServerBootstrap` and
  116. /// `NIOTSListenerBootstrap`.
  117. public protocol ServerBootstrapProtocol {
  118. func bind(to: SocketAddress) -> EventLoopFuture<Channel>
  119. func bind(host: String, port: Int) -> EventLoopFuture<Channel>
  120. func bind(unixDomainSocketPath: String) -> EventLoopFuture<Channel>
  121. func serverChannelInitializer(_ initializer: @escaping (Channel) -> EventLoopFuture<Void>) -> Self
  122. func serverChannelOption<T>(_ option: T, value: T.Value) -> Self where T: ChannelOption
  123. func childChannelInitializer(_ initializer: @escaping (Channel) -> EventLoopFuture<Void>) -> Self
  124. func childChannelOption<T>(_ option: T, value: T.Value) -> Self where T: ChannelOption
  125. }
  126. extension ServerBootstrap: ServerBootstrapProtocol {}
  127. #if canImport(Network)
  128. @available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *)
  129. extension NIOTSListenerBootstrap: ServerBootstrapProtocol {}
  130. #endif
  131. // MARK: - Bootstrap / EventLoopGroup helpers
  132. public enum PlatformSupport {
  133. /// Makes a new event loop group based on the network preference.
  134. ///
  135. /// If `.best` is chosen and `Network.framework` is available then `NIOTSEventLoopGroup` will
  136. /// be returned. A `MultiThreadedEventLoopGroup` will be returned otherwise.
  137. ///
  138. /// - Parameter loopCount: The number of event loops to create in the event loop group.
  139. /// - Parameter networkPreference: Network preference; defaulting to `.best`.
  140. public static func makeEventLoopGroup(
  141. loopCount: Int,
  142. networkPreference: NetworkPreference = .best,
  143. logger: Logger = Logger(label: "io.grpc", factory: { _ in SwiftLogNoOpLogHandler() })
  144. ) -> EventLoopGroup {
  145. logger.debug("making EventLoopGroup for \(networkPreference) network preference")
  146. switch networkPreference.implementation.wrapped {
  147. case .networkFramework:
  148. #if canImport(Network)
  149. guard #available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *) else {
  150. logger.critical("Network.framework can be imported but is not supported on this platform")
  151. // This is gated by the availability of `.networkFramework` so should never happen.
  152. fatalError(".networkFramework is being used on an unsupported platform")
  153. }
  154. logger.debug("created NIOTSEventLoopGroup for \(networkPreference) preference")
  155. return NIOTSEventLoopGroup(loopCount: loopCount)
  156. #else
  157. fatalError(".networkFramework is being used on an unsupported platform")
  158. #endif
  159. case .posix:
  160. logger.debug("created MultiThreadedEventLoopGroup for \(networkPreference) preference")
  161. return MultiThreadedEventLoopGroup(numberOfThreads: loopCount)
  162. }
  163. }
  164. /// Makes a new client bootstrap using the given `EventLoopGroup`.
  165. ///
  166. /// If the `EventLoopGroup` is a `NIOTSEventLoopGroup` then the returned bootstrap will be a
  167. /// `NIOTSConnectionBootstrap`, otherwise it will be a `ClientBootstrap`.
  168. ///
  169. /// - Parameter group: The `EventLoopGroup` to use.
  170. public static func makeClientBootstrap(
  171. group: EventLoopGroup,
  172. logger: Logger = Logger(label: "io.grpc", factory: { _ in SwiftLogNoOpLogHandler() })
  173. ) -> ClientBootstrapProtocol {
  174. logger.debug("making client bootstrap with event loop group of type \(type(of: group))")
  175. #if canImport(Network)
  176. if #available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *) {
  177. if isTransportServicesEventLoopGroup(group) {
  178. logger.debug(
  179. "Network.framework is available and the EventLoopGroup is compatible with NIOTS, creating a NIOTSConnectionBootstrap"
  180. )
  181. return NIOTSConnectionBootstrap(group: group)
  182. } else {
  183. logger.debug(
  184. "Network.framework is available but the EventLoopGroup is not compatible with NIOTS, falling back to ClientBootstrap"
  185. )
  186. }
  187. }
  188. #endif
  189. logger.debug("creating a ClientBootstrap")
  190. return ClientBootstrap(group: group)
  191. }
  192. internal static func isTransportServicesEventLoopGroup(_ group: EventLoopGroup) -> Bool {
  193. #if canImport(Network)
  194. if #available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *) {
  195. return group is NIOTSEventLoopGroup || group is QoSEventLoop
  196. }
  197. #endif
  198. return false
  199. }
  200. internal static func makeClientBootstrap(
  201. group: EventLoopGroup,
  202. tlsConfiguration: GRPCTLSConfiguration?,
  203. logger: Logger
  204. ) -> ClientBootstrapProtocol {
  205. let bootstrap = self.makeClientBootstrap(group: group, logger: logger)
  206. guard let tlsConfigruation = tlsConfiguration else {
  207. return bootstrap
  208. }
  209. #if canImport(Network)
  210. if #available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *),
  211. let transportServicesBootstrap = bootstrap as? NIOTSConnectionBootstrap {
  212. return transportServicesBootstrap.tlsOptions(from: tlsConfigruation)
  213. }
  214. #endif
  215. return bootstrap
  216. }
  217. /// Makes a new server bootstrap using the given `EventLoopGroup`.
  218. ///
  219. /// If the `EventLoopGroup` is a `NIOTSEventLoopGroup` then the returned bootstrap will be a
  220. /// `NIOTSListenerBootstrap`, otherwise it will be a `ServerBootstrap`.
  221. ///
  222. /// - Parameter group: The `EventLoopGroup` to use.
  223. public static func makeServerBootstrap(
  224. group: EventLoopGroup,
  225. logger: Logger = Logger(label: "io.grpc", factory: { _ in SwiftLogNoOpLogHandler() })
  226. ) -> ServerBootstrapProtocol {
  227. logger.debug("making server bootstrap with event loop group of type \(type(of: group))")
  228. #if canImport(Network)
  229. if #available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *) {
  230. if let tsGroup = group as? NIOTSEventLoopGroup {
  231. logger
  232. .debug(
  233. "Network.framework is available and the group is correctly typed, creating a NIOTSListenerBootstrap"
  234. )
  235. return NIOTSListenerBootstrap(group: tsGroup)
  236. } else if let qosEventLoop = group as? QoSEventLoop {
  237. logger
  238. .debug(
  239. "Network.framework is available and the group is correctly typed, creating a NIOTSListenerBootstrap"
  240. )
  241. return NIOTSListenerBootstrap(group: qosEventLoop)
  242. }
  243. logger
  244. .debug(
  245. "Network.framework is available but the group is not typed for NIOTS, falling back to ServerBootstrap"
  246. )
  247. }
  248. #endif
  249. logger.debug("creating a ServerBootstrap")
  250. return ServerBootstrap(group: group)
  251. }
  252. /// Determines whether we may need to work around an issue in Network.framework with zero-length writes.
  253. ///
  254. /// See https://github.com/apple/swift-nio-transport-services/pull/72 for more.
  255. static func requiresZeroLengthWriteWorkaround(group: EventLoopGroup, hasTLS: Bool) -> Bool {
  256. #if canImport(Network)
  257. if #available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *) {
  258. if group is NIOTSEventLoopGroup || group is QoSEventLoop {
  259. // We need the zero-length write workaround on NIOTS when not using TLS.
  260. return !hasTLS
  261. } else {
  262. return false
  263. }
  264. } else {
  265. return false
  266. }
  267. #else
  268. return false
  269. #endif
  270. }
  271. }
  272. extension PlatformSupport {
  273. /// Make an `EventLoopGroup` which is compatible with the given TLS configuration/
  274. ///
  275. /// - Parameters:
  276. /// - configuration: The configuration to make a compatible `EventLoopGroup` for.
  277. /// - loopCount: The number of loops the `EventLoopGroup` should have.
  278. /// - Returns: An `EventLoopGroup` compatible with the given `configuration`.
  279. public static func makeEventLoopGroup(
  280. compatibleWith configuration: GRPCTLSConfiguration,
  281. loopCount: Int
  282. ) -> EventLoopGroup {
  283. #if canImport(Network)
  284. if #available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *) {
  285. if configuration.isNetworkFrameworkTLSBackend {
  286. return NIOTSEventLoopGroup(loopCount: loopCount)
  287. }
  288. }
  289. #endif
  290. return MultiThreadedEventLoopGroup(numberOfThreads: loopCount)
  291. }
  292. }
  293. extension GRPCTLSConfiguration {
  294. /// Provides a `GRPCTLSConfiguration` suitable for the given `EventLoopGroup`.
  295. public static func makeClientDefault(
  296. compatibleWith eventLoopGroup: EventLoopGroup
  297. ) -> GRPCTLSConfiguration {
  298. let networkImplementation: NetworkImplementation = .matchingEventLoopGroup(eventLoopGroup)
  299. return GRPCTLSConfiguration.makeClientDefault(for: .userDefined(networkImplementation))
  300. }
  301. /// Provides a `GRPCTLSConfiguration` suitable for the given network preference.
  302. public static func makeClientDefault(
  303. for networkPreference: NetworkPreference
  304. ) -> GRPCTLSConfiguration {
  305. switch networkPreference.implementation.wrapped {
  306. case .networkFramework:
  307. #if canImport(Network)
  308. guard #available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *) else {
  309. // This is gated by the availability of `.networkFramework` so should never happen.
  310. fatalError(".networkFramework is being used on an unsupported platform")
  311. }
  312. return .makeClientConfigurationBackedByNetworkFramework()
  313. #else
  314. fatalError(".networkFramework is being used on an unsupported platform")
  315. #endif
  316. case .posix:
  317. #if canImport(NIOSSL)
  318. return .makeClientConfigurationBackedByNIOSSL()
  319. #else
  320. fatalError("Default client TLS configuration for '.posix' requires NIOSSL")
  321. #endif
  322. }
  323. }
  324. }
  325. extension EventLoopGroup {
  326. internal func isCompatible(with tlsConfiguration: GRPCTLSConfiguration) -> Bool {
  327. let isTransportServicesGroup = PlatformSupport.isTransportServicesEventLoopGroup(self)
  328. let isNetworkFrameworkTLSBackend = tlsConfiguration.isNetworkFrameworkTLSBackend
  329. // If the group is from NIOTransportServices then we can use either the NIOSSL or the
  330. // Network.framework TLS backend.
  331. //
  332. // If it isn't then we must not use the Network.Framework TLS backend.
  333. return isTransportServicesGroup || !isNetworkFrameworkTLSBackend
  334. }
  335. internal func preconditionCompatible(
  336. with tlsConfiguration: GRPCTLSConfiguration,
  337. file: StaticString = #file,
  338. line: UInt = #line
  339. ) {
  340. precondition(
  341. self.isCompatible(with: tlsConfiguration),
  342. "Unsupported 'EventLoopGroup' and 'GRPCLSConfiguration' pairing (Network.framework backed TLS configurations MUST use an EventLoopGroup from NIOTransportServices)",
  343. file: file,
  344. line: line
  345. )
  346. }
  347. }