PlatformSupport.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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 withConnectedSocket(_ socket: NIOBSDSocket.Handle) -> EventLoopFuture<Channel>
  107. func connectTimeout(_ timeout: TimeAmount) -> Self
  108. func channelOption<T>(_ option: T, value: T.Value) -> Self where T: ChannelOption
  109. func channelInitializer(_ handler: @escaping (Channel) -> EventLoopFuture<Void>) -> Self
  110. }
  111. extension ClientBootstrapProtocol {
  112. public func withConnectedSocket(_ socket: NIOBSDSocket.Handle) -> EventLoopFuture<Channel> {
  113. preconditionFailure("withConnectedSocket(_:) is not implemented")
  114. }
  115. }
  116. extension ClientBootstrap: ClientBootstrapProtocol {}
  117. #if canImport(Network)
  118. @available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *)
  119. extension NIOTSConnectionBootstrap: ClientBootstrapProtocol {
  120. public func withConnectedSocket(_ socket: NIOBSDSocket.Handle) -> EventLoopFuture<Channel> {
  121. preconditionFailure("NIOTSConnectionBootstrap does not support withConnectedSocket(_:)")
  122. }
  123. }
  124. #endif
  125. /// This protocol is intended as a layer of abstraction over `ServerBootstrap` and
  126. /// `NIOTSListenerBootstrap`.
  127. public protocol ServerBootstrapProtocol {
  128. func bind(to: SocketAddress) -> EventLoopFuture<Channel>
  129. func bind(host: String, port: Int) -> EventLoopFuture<Channel>
  130. func bind(unixDomainSocketPath: String) -> EventLoopFuture<Channel>
  131. func withBoundSocket(_ connectedSocket: NIOBSDSocket.Handle) -> EventLoopFuture<Channel>
  132. func serverChannelInitializer(_ initializer: @escaping (Channel) -> EventLoopFuture<Void>) -> Self
  133. func serverChannelOption<T>(_ option: T, value: T.Value) -> Self where T: ChannelOption
  134. func childChannelInitializer(_ initializer: @escaping (Channel) -> EventLoopFuture<Void>) -> Self
  135. func childChannelOption<T>(_ option: T, value: T.Value) -> Self where T: ChannelOption
  136. }
  137. extension ServerBootstrapProtocol {
  138. public func withBoundSocket(_ connectedSocket: NIOBSDSocket.Handle) -> EventLoopFuture<Channel> {
  139. preconditionFailure("withBoundSocket(_:) is not implemented")
  140. }
  141. }
  142. extension ServerBootstrap: ServerBootstrapProtocol {}
  143. #if canImport(Network)
  144. @available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *)
  145. extension NIOTSListenerBootstrap: ServerBootstrapProtocol {
  146. public func withBoundSocket(_ connectedSocket: NIOBSDSocket.Handle) -> EventLoopFuture<Channel> {
  147. preconditionFailure("NIOTSListenerBootstrap does not support withConnectedSocket(_:)")
  148. }
  149. }
  150. #endif
  151. // MARK: - Bootstrap / EventLoopGroup helpers
  152. public enum PlatformSupport {
  153. /// Makes a new event loop group based on the network preference.
  154. ///
  155. /// If `.best` is chosen and `Network.framework` is available then `NIOTSEventLoopGroup` will
  156. /// be returned. A `MultiThreadedEventLoopGroup` will be returned otherwise.
  157. ///
  158. /// - Parameter loopCount: The number of event loops to create in the event loop group.
  159. /// - Parameter networkPreference: Network preference; defaulting to `.best`.
  160. public static func makeEventLoopGroup(
  161. loopCount: Int,
  162. networkPreference: NetworkPreference = .best,
  163. logger: Logger = Logger(label: "io.grpc", factory: { _ in SwiftLogNoOpLogHandler() })
  164. ) -> EventLoopGroup {
  165. logger.debug("making EventLoopGroup for \(networkPreference) network preference")
  166. switch networkPreference.implementation.wrapped {
  167. case .networkFramework:
  168. #if canImport(Network)
  169. guard #available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *) else {
  170. logger.critical("Network.framework can be imported but is not supported on this platform")
  171. // This is gated by the availability of `.networkFramework` so should never happen.
  172. fatalError(".networkFramework is being used on an unsupported platform")
  173. }
  174. logger.debug("created NIOTSEventLoopGroup for \(networkPreference) preference")
  175. return NIOTSEventLoopGroup(loopCount: loopCount)
  176. #else
  177. fatalError(".networkFramework is being used on an unsupported platform")
  178. #endif
  179. case .posix:
  180. logger.debug("created MultiThreadedEventLoopGroup for \(networkPreference) preference")
  181. return MultiThreadedEventLoopGroup(numberOfThreads: loopCount)
  182. }
  183. }
  184. /// Makes a new client bootstrap using the given `EventLoopGroup`.
  185. ///
  186. /// If the `EventLoopGroup` is a `NIOTSEventLoopGroup` then the returned bootstrap will be a
  187. /// `NIOTSConnectionBootstrap`, otherwise it will be a `ClientBootstrap`.
  188. ///
  189. /// - Parameter group: The `EventLoopGroup` to use.
  190. public static func makeClientBootstrap(
  191. group: EventLoopGroup,
  192. logger: Logger = Logger(label: "io.grpc", factory: { _ in SwiftLogNoOpLogHandler() })
  193. ) -> ClientBootstrapProtocol {
  194. logger.debug("making client bootstrap with event loop group of type \(type(of: group))")
  195. #if canImport(Network)
  196. if #available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *) {
  197. if isTransportServicesEventLoopGroup(group) {
  198. logger.debug(
  199. "Network.framework is available and the EventLoopGroup is compatible with NIOTS, creating a NIOTSConnectionBootstrap"
  200. )
  201. return NIOTSConnectionBootstrap(group: group)
  202. } else {
  203. logger.debug(
  204. "Network.framework is available but the EventLoopGroup is not compatible with NIOTS, falling back to ClientBootstrap"
  205. )
  206. }
  207. }
  208. #endif
  209. logger.debug("creating a ClientBootstrap")
  210. return ClientBootstrap(group: group)
  211. }
  212. internal static func isTransportServicesEventLoopGroup(_ group: EventLoopGroup) -> Bool {
  213. #if canImport(Network)
  214. if #available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *) {
  215. return group is NIOTSEventLoopGroup || group is QoSEventLoop
  216. }
  217. #endif
  218. return false
  219. }
  220. internal static func makeClientBootstrap(
  221. group: EventLoopGroup,
  222. tlsConfiguration: GRPCTLSConfiguration?,
  223. logger: Logger
  224. ) -> ClientBootstrapProtocol {
  225. let bootstrap = self.makeClientBootstrap(group: group, logger: logger)
  226. guard let tlsConfigruation = tlsConfiguration else {
  227. return bootstrap
  228. }
  229. #if canImport(Network)
  230. if #available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *),
  231. let transportServicesBootstrap = bootstrap as? NIOTSConnectionBootstrap {
  232. return transportServicesBootstrap.tlsOptions(from: tlsConfigruation)
  233. }
  234. #endif
  235. return bootstrap
  236. }
  237. /// Makes a new server bootstrap using the given `EventLoopGroup`.
  238. ///
  239. /// If the `EventLoopGroup` is a `NIOTSEventLoopGroup` then the returned bootstrap will be a
  240. /// `NIOTSListenerBootstrap`, otherwise it will be a `ServerBootstrap`.
  241. ///
  242. /// - Parameter group: The `EventLoopGroup` to use.
  243. public static func makeServerBootstrap(
  244. group: EventLoopGroup,
  245. logger: Logger = Logger(label: "io.grpc", factory: { _ in SwiftLogNoOpLogHandler() })
  246. ) -> ServerBootstrapProtocol {
  247. logger.debug("making server bootstrap with event loop group of type \(type(of: group))")
  248. #if canImport(Network)
  249. if #available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *) {
  250. if let tsGroup = group as? NIOTSEventLoopGroup {
  251. logger
  252. .debug(
  253. "Network.framework is available and the group is correctly typed, creating a NIOTSListenerBootstrap"
  254. )
  255. return NIOTSListenerBootstrap(group: tsGroup)
  256. } else if let qosEventLoop = group as? QoSEventLoop {
  257. logger
  258. .debug(
  259. "Network.framework is available and the group is correctly typed, creating a NIOTSListenerBootstrap"
  260. )
  261. return NIOTSListenerBootstrap(group: qosEventLoop)
  262. }
  263. logger
  264. .debug(
  265. "Network.framework is available but the group is not typed for NIOTS, falling back to ServerBootstrap"
  266. )
  267. }
  268. #endif
  269. logger.debug("creating a ServerBootstrap")
  270. return ServerBootstrap(group: group)
  271. }
  272. /// Determines whether we may need to work around an issue in Network.framework with zero-length writes.
  273. ///
  274. /// See https://github.com/apple/swift-nio-transport-services/pull/72 for more.
  275. static func requiresZeroLengthWriteWorkaround(group: EventLoopGroup, hasTLS: Bool) -> Bool {
  276. #if canImport(Network)
  277. if #available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *) {
  278. if group is NIOTSEventLoopGroup || group is QoSEventLoop {
  279. // We need the zero-length write workaround on NIOTS when not using TLS.
  280. return !hasTLS
  281. } else {
  282. return false
  283. }
  284. } else {
  285. return false
  286. }
  287. #else
  288. return false
  289. #endif
  290. }
  291. }
  292. extension PlatformSupport {
  293. /// Make an `EventLoopGroup` which is compatible with the given TLS configuration/
  294. ///
  295. /// - Parameters:
  296. /// - configuration: The configuration to make a compatible `EventLoopGroup` for.
  297. /// - loopCount: The number of loops the `EventLoopGroup` should have.
  298. /// - Returns: An `EventLoopGroup` compatible with the given `configuration`.
  299. public static func makeEventLoopGroup(
  300. compatibleWith configuration: GRPCTLSConfiguration,
  301. loopCount: Int
  302. ) -> EventLoopGroup {
  303. #if canImport(Network)
  304. if #available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *) {
  305. if configuration.isNetworkFrameworkTLSBackend {
  306. return NIOTSEventLoopGroup(loopCount: loopCount)
  307. }
  308. }
  309. #endif
  310. return MultiThreadedEventLoopGroup(numberOfThreads: loopCount)
  311. }
  312. }
  313. extension GRPCTLSConfiguration {
  314. /// Provides a `GRPCTLSConfiguration` suitable for the given `EventLoopGroup`.
  315. public static func makeClientDefault(
  316. compatibleWith eventLoopGroup: EventLoopGroup
  317. ) -> GRPCTLSConfiguration {
  318. let networkImplementation: NetworkImplementation = .matchingEventLoopGroup(eventLoopGroup)
  319. return GRPCTLSConfiguration.makeClientDefault(for: .userDefined(networkImplementation))
  320. }
  321. /// Provides a `GRPCTLSConfiguration` suitable for the given network preference.
  322. public static func makeClientDefault(
  323. for networkPreference: NetworkPreference
  324. ) -> GRPCTLSConfiguration {
  325. switch networkPreference.implementation.wrapped {
  326. case .networkFramework:
  327. #if canImport(Network)
  328. guard #available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *) else {
  329. // This is gated by the availability of `.networkFramework` so should never happen.
  330. fatalError(".networkFramework is being used on an unsupported platform")
  331. }
  332. return .makeClientConfigurationBackedByNetworkFramework()
  333. #else
  334. fatalError(".networkFramework is being used on an unsupported platform")
  335. #endif
  336. case .posix:
  337. #if canImport(NIOSSL)
  338. return .makeClientConfigurationBackedByNIOSSL()
  339. #else
  340. fatalError("Default client TLS configuration for '.posix' requires NIOSSL")
  341. #endif
  342. }
  343. }
  344. }
  345. extension EventLoopGroup {
  346. internal func isCompatible(with tlsConfiguration: GRPCTLSConfiguration) -> Bool {
  347. let isTransportServicesGroup = PlatformSupport.isTransportServicesEventLoopGroup(self)
  348. let isNetworkFrameworkTLSBackend = tlsConfiguration.isNetworkFrameworkTLSBackend
  349. // If the group is from NIOTransportServices then we can use either the NIOSSL or the
  350. // Network.framework TLS backend.
  351. //
  352. // If it isn't then we must not use the Network.Framework TLS backend.
  353. return isTransportServicesGroup || !isNetworkFrameworkTLSBackend
  354. }
  355. internal func preconditionCompatible(
  356. with tlsConfiguration: GRPCTLSConfiguration,
  357. file: StaticString = #file,
  358. line: UInt = #line
  359. ) {
  360. precondition(
  361. self.isCompatible(with: tlsConfiguration),
  362. "Unsupported 'EventLoopGroup' and 'GRPCLSConfiguration' pairing (Network.framework backed TLS configurations MUST use an EventLoopGroup from NIOTransportServices)",
  363. file: file,
  364. line: line
  365. )
  366. }
  367. }