PlatformSupport.swift 16 KB

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