PlatformSupport.swift 16 KB

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