HTTP2ClientTransport+TransportServices.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. /*
  2. * Copyright 2024, 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. #if canImport(Network)
  17. public import GRPCCore
  18. public import GRPCNIOTransportCore
  19. public import NIOTransportServices // has to be public because of default argument value in init
  20. public import NIOCore // has to be public because of EventLoopGroup param in init
  21. private import Network
  22. extension HTTP2ClientTransport {
  23. /// A `ClientTransport` using HTTP/2 built on top of `NIOTransportServices`.
  24. ///
  25. /// This transport builds on top of SwiftNIO's Transport Services networking layer and is the recommended
  26. /// variant for use on Darwin-based platforms (macOS, iOS, etc.).
  27. /// If you are targeting Linux platforms then you should use the `NIOPosix` variant of
  28. /// the `HTTP2ClientTransport`.
  29. ///
  30. /// To use this transport you need to provide a 'target' to connect to which will be resolved
  31. /// by an appropriate resolver from the resolver registry. By default the resolver registry can
  32. /// resolve DNS targets, IPv4 and IPv6 targets, and Unix domain socket targets. Virtual Socket
  33. /// targets are not supported with this transport. If you use a custom target you must also provide an
  34. /// appropriately configured registry.
  35. ///
  36. /// You can control various aspects of connection creation, management, security and RPC behavior via
  37. /// the ``Config``. Load balancing policies and other RPC specific behavior can be configured via
  38. /// the `ServiceConfig` (if it isn't provided by a resolver).
  39. ///
  40. /// Beyond creating the transport you don't need to interact with it directly, instead, pass it
  41. /// to a `GRPCClient`:
  42. ///
  43. /// ```swift
  44. /// try await withThrowingDiscardingTaskGroup { group in
  45. /// let transport = try HTTP2ClientTransport.TransportServices(
  46. /// target: .ipv4(host: "example.com"),
  47. /// transportSecurity: .plaintext
  48. /// )
  49. /// let client = GRPCClient(transport: transport)
  50. /// group.addTask {
  51. /// try await client.run()
  52. /// }
  53. ///
  54. /// // ...
  55. /// }
  56. /// ```
  57. public struct TransportServices: ClientTransport {
  58. private let channel: GRPCChannel
  59. public var retryThrottle: RetryThrottle? {
  60. self.channel.retryThrottle
  61. }
  62. /// Creates a new NIOTransportServices-based HTTP/2 client transport.
  63. ///
  64. /// - Parameters:
  65. /// - target: A target to resolve.
  66. /// - transportSecurity: The configuration for securing network traffic.
  67. /// - config: Configuration for the transport.
  68. /// - resolverRegistry: A registry of resolver factories.
  69. /// - serviceConfig: Service config controlling how the transport should establish and
  70. /// load-balance connections.
  71. /// - eventLoopGroup: The underlying NIO `EventLoopGroup` to run connections on. This must
  72. /// be a `MultiThreadedEventLoopGroup` or an `EventLoop` from
  73. /// a `MultiThreadedEventLoopGroup`.
  74. /// - Throws: When no suitable resolver could be found for the `target`.
  75. public init(
  76. target: any ResolvableTarget,
  77. transportSecurity: TransportSecurity,
  78. config: Config = .defaults,
  79. resolverRegistry: NameResolverRegistry = .defaults,
  80. serviceConfig: ServiceConfig = ServiceConfig(),
  81. eventLoopGroup: any EventLoopGroup = .singletonNIOTSEventLoopGroup
  82. ) throws {
  83. guard let resolver = resolverRegistry.makeResolver(for: target) else {
  84. throw RuntimeError(
  85. code: .transportError,
  86. message: """
  87. No suitable resolvers to resolve '\(target)'. You must make sure that the resolver \
  88. registry has a suitable name resolver factory registered for the given target.
  89. """
  90. )
  91. }
  92. self.channel = GRPCChannel(
  93. resolver: resolver,
  94. connector: Connector(
  95. eventLoopGroup: eventLoopGroup,
  96. config: config,
  97. transportSecurity: transportSecurity
  98. ),
  99. config: GRPCChannel.Config(transportServices: config),
  100. defaultServiceConfig: serviceConfig
  101. )
  102. }
  103. public func connect() async throws {
  104. await self.channel.connect()
  105. }
  106. public func beginGracefulShutdown() {
  107. self.channel.beginGracefulShutdown()
  108. }
  109. public func withStream<T: Sendable>(
  110. descriptor: MethodDescriptor,
  111. options: CallOptions,
  112. _ closure: (RPCStream<Inbound, Outbound>) async throws -> T
  113. ) async throws -> T {
  114. try await self.channel.withStream(descriptor: descriptor, options: options, closure)
  115. }
  116. public func config(forMethod descriptor: MethodDescriptor) -> MethodConfig? {
  117. self.channel.config(forMethod: descriptor)
  118. }
  119. }
  120. }
  121. extension HTTP2ClientTransport.TransportServices {
  122. struct Connector: HTTP2Connector {
  123. private let config: HTTP2ClientTransport.TransportServices.Config
  124. private let transportSecurity: HTTP2ClientTransport.TransportServices.TransportSecurity
  125. private let eventLoopGroup: any EventLoopGroup
  126. init(
  127. eventLoopGroup: any EventLoopGroup,
  128. config: HTTP2ClientTransport.TransportServices.Config,
  129. transportSecurity: HTTP2ClientTransport.TransportServices.TransportSecurity
  130. ) {
  131. self.eventLoopGroup = eventLoopGroup
  132. self.config = config
  133. self.transportSecurity = transportSecurity
  134. }
  135. func establishConnection(
  136. to address: GRPCNIOTransportCore.SocketAddress,
  137. authority: String?
  138. ) async throws -> HTTP2Connection {
  139. let bootstrap: NIOTSConnectionBootstrap
  140. let isPlainText: Bool
  141. switch self.transportSecurity.wrapped {
  142. case .plaintext:
  143. isPlainText = true
  144. bootstrap = NIOTSConnectionBootstrap(group: self.eventLoopGroup)
  145. .channelOption(NIOTSChannelOptions.waitForActivity, value: false)
  146. case .tls(let tlsConfig):
  147. isPlainText = false
  148. do {
  149. let options = try NWProtocolTLS.Options(tlsConfig, authority: authority)
  150. bootstrap = NIOTSConnectionBootstrap(group: self.eventLoopGroup)
  151. .channelOption(NIOTSChannelOptions.waitForActivity, value: false)
  152. .tlsOptions(options)
  153. } catch {
  154. throw RuntimeError(
  155. code: .transportError,
  156. message: "Couldn't create NWProtocolTLS.Options, check your TLS configuration.",
  157. cause: error
  158. )
  159. }
  160. }
  161. let (channel, multiplexer) = try await bootstrap.connect(to: address) { channel in
  162. channel.eventLoop.makeCompletedFuture {
  163. try channel.pipeline.syncOperations.configureGRPCClientPipeline(
  164. channel: channel,
  165. config: GRPCChannel.Config(transportServices: self.config)
  166. )
  167. }
  168. }
  169. return HTTP2Connection(
  170. channel: channel,
  171. multiplexer: multiplexer,
  172. isPlaintext: isPlainText
  173. )
  174. }
  175. }
  176. }
  177. extension HTTP2ClientTransport.TransportServices {
  178. /// Configuration for the `TransportServices` transport.
  179. public struct Config: Sendable {
  180. /// Configuration for HTTP/2 connections.
  181. public var http2: HTTP2ClientTransport.Config.HTTP2
  182. /// Configuration for backoff used when establishing a connection.
  183. public var backoff: HTTP2ClientTransport.Config.Backoff
  184. /// Configuration for connection management.
  185. public var connection: HTTP2ClientTransport.Config.Connection
  186. /// Compression configuration.
  187. public var compression: HTTP2ClientTransport.Config.Compression
  188. /// Creates a new connection configuration.
  189. ///
  190. /// - Parameters:
  191. /// - http2: HTTP2 configuration.
  192. /// - backoff: Backoff configuration.
  193. /// - connection: Connection configuration.
  194. /// - compression: Compression configuration.
  195. ///
  196. /// - SeeAlso: ``defaults(configure:)`` and ``defaults``.
  197. public init(
  198. http2: HTTP2ClientTransport.Config.HTTP2,
  199. backoff: HTTP2ClientTransport.Config.Backoff,
  200. connection: HTTP2ClientTransport.Config.Connection,
  201. compression: HTTP2ClientTransport.Config.Compression
  202. ) {
  203. self.http2 = http2
  204. self.connection = connection
  205. self.backoff = backoff
  206. self.compression = compression
  207. }
  208. /// Default configuration.
  209. public static var defaults: Self {
  210. Self.defaults()
  211. }
  212. /// Default values.
  213. ///
  214. /// - Parameters:
  215. /// - configure: A closure which allows you to modify the defaults before returning them.
  216. public static func defaults(
  217. configure: (_ config: inout Self) -> Void = { _ in }
  218. ) -> Self {
  219. var config = Self(
  220. http2: .defaults,
  221. backoff: .defaults,
  222. connection: .defaults,
  223. compression: .defaults
  224. )
  225. configure(&config)
  226. return config
  227. }
  228. }
  229. }
  230. extension GRPCChannel.Config {
  231. init(transportServices config: HTTP2ClientTransport.TransportServices.Config) {
  232. self.init(
  233. http2: config.http2,
  234. backoff: config.backoff,
  235. connection: config.connection,
  236. compression: config.compression
  237. )
  238. }
  239. }
  240. extension NIOTSConnectionBootstrap {
  241. fileprivate func connect<Output: Sendable>(
  242. to address: GRPCNIOTransportCore.SocketAddress,
  243. childChannelInitializer: @escaping @Sendable (any Channel) -> EventLoopFuture<Output>
  244. ) async throws -> Output {
  245. if address.virtualSocket != nil {
  246. throw RuntimeError(
  247. code: .transportError,
  248. message: """
  249. Virtual sockets are not supported by 'HTTP2ClientTransport.TransportServices'. \
  250. Please use the 'HTTP2ClientTransport.Posix' transport.
  251. """
  252. )
  253. } else {
  254. return try await self.connect(
  255. to: NIOCore.SocketAddress(address),
  256. channelInitializer: childChannelInitializer
  257. )
  258. }
  259. }
  260. }
  261. extension ClientTransport where Self == HTTP2ClientTransport.TransportServices {
  262. /// Create a new `TransportServices` based HTTP/2 client transport.
  263. ///
  264. /// - Parameters:
  265. /// - target: A target to resolve.
  266. /// - transportSecurity: The security settings applied to the transport.
  267. /// - config: Configuration for the transport.
  268. /// - resolverRegistry: A registry of resolver factories.
  269. /// - serviceConfig: Service config controlling how the transport should establish and
  270. /// load-balance connections.
  271. /// - eventLoopGroup: The underlying NIO `EventLoopGroup` to run connections on. This must
  272. /// be a `NIOTSEventLoopGroup` or an `EventLoop` from
  273. /// a `NIOTSEventLoopGroup`.
  274. /// - Throws: When no suitable resolver could be found for the `target`.
  275. public static func http2NIOTS(
  276. target: any ResolvableTarget,
  277. transportSecurity: HTTP2ClientTransport.TransportServices.TransportSecurity,
  278. config: HTTP2ClientTransport.TransportServices.Config = .defaults,
  279. resolverRegistry: NameResolverRegistry = .defaults,
  280. serviceConfig: ServiceConfig = ServiceConfig(),
  281. eventLoopGroup: any EventLoopGroup = .singletonNIOTSEventLoopGroup
  282. ) throws -> Self {
  283. try HTTP2ClientTransport.TransportServices(
  284. target: target,
  285. transportSecurity: transportSecurity,
  286. config: config,
  287. resolverRegistry: resolverRegistry,
  288. serviceConfig: serviceConfig,
  289. eventLoopGroup: eventLoopGroup
  290. )
  291. }
  292. }
  293. extension NWProtocolTLS.Options {
  294. convenience init(
  295. _ tlsConfig: HTTP2ClientTransport.TransportServices.TLS,
  296. authority: String?
  297. ) throws {
  298. self.init()
  299. if let identityProvider = tlsConfig.identityProvider {
  300. guard let sec_identity = sec_identity_create(try identityProvider()) else {
  301. throw RuntimeError(
  302. code: .transportError,
  303. message: """
  304. There was an issue creating the SecIdentity required to set up TLS. \
  305. Please check your TLS configuration.
  306. """
  307. )
  308. }
  309. sec_protocol_options_set_local_identity(
  310. self.securityProtocolOptions,
  311. sec_identity
  312. )
  313. }
  314. switch tlsConfig.serverCertificateVerification.wrapped {
  315. case .doNotVerify:
  316. sec_protocol_options_set_peer_authentication_required(
  317. self.securityProtocolOptions,
  318. false
  319. )
  320. case .fullVerification:
  321. sec_protocol_options_set_peer_authentication_required(
  322. self.securityProtocolOptions,
  323. true
  324. )
  325. authority?.withCString { serverName in
  326. sec_protocol_options_set_tls_server_name(
  327. self.securityProtocolOptions,
  328. serverName
  329. )
  330. }
  331. case .noHostnameVerification:
  332. sec_protocol_options_set_peer_authentication_required(
  333. self.securityProtocolOptions,
  334. true
  335. )
  336. }
  337. sec_protocol_options_set_min_tls_protocol_version(
  338. self.securityProtocolOptions,
  339. .TLSv12
  340. )
  341. for `protocol` in ["grpc-exp", "h2"] {
  342. sec_protocol_options_add_tls_application_protocol(
  343. self.securityProtocolOptions,
  344. `protocol`
  345. )
  346. }
  347. self.setUpVerifyBlock(trustRootsSource: tlsConfig.trustRoots)
  348. }
  349. }
  350. #endif