PlatformSupport.swift 16 KB

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