HTTP2ClientTransport+TransportServices.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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. /// config: .defaults(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. /// - config: Configuration for the transport.
  67. /// - resolverRegistry: A registry of resolver factories.
  68. /// - serviceConfig: Service config controlling how the transport should establish and
  69. /// load-balance connections.
  70. /// - eventLoopGroup: The underlying NIO `EventLoopGroup` to run connections on. This must
  71. /// be a `MultiThreadedEventLoopGroup` or an `EventLoop` from
  72. /// a `MultiThreadedEventLoopGroup`.
  73. /// - Throws: When no suitable resolver could be found for the `target`.
  74. public init(
  75. target: any ResolvableTarget,
  76. config: Config,
  77. resolverRegistry: NameResolverRegistry = .defaults,
  78. serviceConfig: ServiceConfig = ServiceConfig(),
  79. eventLoopGroup: any EventLoopGroup = .singletonNIOTSEventLoopGroup
  80. ) throws {
  81. guard let resolver = resolverRegistry.makeResolver(for: target) else {
  82. throw RuntimeError(
  83. code: .transportError,
  84. message: """
  85. No suitable resolvers to resolve '\(target)'. You must make sure that the resolver \
  86. registry has a suitable name resolver factory registered for the given target.
  87. """
  88. )
  89. }
  90. self.channel = GRPCChannel(
  91. resolver: resolver,
  92. connector: Connector(eventLoopGroup: eventLoopGroup, config: config),
  93. config: GRPCChannel.Config(transportServices: config),
  94. defaultServiceConfig: serviceConfig
  95. )
  96. }
  97. public func connect() async throws {
  98. await self.channel.connect()
  99. }
  100. public func beginGracefulShutdown() {
  101. self.channel.beginGracefulShutdown()
  102. }
  103. public func withStream<T: Sendable>(
  104. descriptor: MethodDescriptor,
  105. options: CallOptions,
  106. _ closure: (RPCStream<Inbound, Outbound>) async throws -> T
  107. ) async throws -> T {
  108. try await self.channel.withStream(descriptor: descriptor, options: options, closure)
  109. }
  110. public func config(forMethod descriptor: MethodDescriptor) -> MethodConfig? {
  111. self.channel.config(forMethod: descriptor)
  112. }
  113. }
  114. }
  115. extension HTTP2ClientTransport.TransportServices {
  116. struct Connector: HTTP2Connector {
  117. private let config: HTTP2ClientTransport.TransportServices.Config
  118. private let eventLoopGroup: any EventLoopGroup
  119. init(
  120. eventLoopGroup: any EventLoopGroup,
  121. config: HTTP2ClientTransport.TransportServices.Config
  122. ) {
  123. self.eventLoopGroup = eventLoopGroup
  124. self.config = config
  125. }
  126. func establishConnection(
  127. to address: GRPCNIOTransportCore.SocketAddress,
  128. authority: String?
  129. ) async throws -> HTTP2Connection {
  130. let bootstrap: NIOTSConnectionBootstrap
  131. let isPlainText: Bool
  132. switch self.config.transportSecurity.wrapped {
  133. case .plaintext:
  134. isPlainText = true
  135. bootstrap = NIOTSConnectionBootstrap(group: self.eventLoopGroup)
  136. .channelOption(NIOTSChannelOptions.waitForActivity, value: false)
  137. case .tls(let tlsConfig):
  138. isPlainText = false
  139. do {
  140. let options = try NWProtocolTLS.Options(tlsConfig, authority: authority)
  141. bootstrap = NIOTSConnectionBootstrap(group: self.eventLoopGroup)
  142. .channelOption(NIOTSChannelOptions.waitForActivity, value: false)
  143. .tlsOptions(options)
  144. } catch {
  145. throw RuntimeError(
  146. code: .transportError,
  147. message: "Couldn't create NWProtocolTLS.Options, check your TLS configuration.",
  148. cause: error
  149. )
  150. }
  151. }
  152. let (channel, multiplexer) = try await bootstrap.connect(to: address) { channel in
  153. channel.eventLoop.makeCompletedFuture {
  154. try channel.pipeline.syncOperations.configureGRPCClientPipeline(
  155. channel: channel,
  156. config: GRPCChannel.Config(transportServices: self.config)
  157. )
  158. }
  159. }
  160. return HTTP2Connection(
  161. channel: channel,
  162. multiplexer: multiplexer,
  163. isPlaintext: isPlainText
  164. )
  165. }
  166. }
  167. }
  168. extension HTTP2ClientTransport.TransportServices {
  169. /// Configuration for the `TransportServices` transport.
  170. public struct Config: Sendable {
  171. /// Configuration for HTTP/2 connections.
  172. public var http2: HTTP2ClientTransport.Config.HTTP2
  173. /// Configuration for backoff used when establishing a connection.
  174. public var backoff: HTTP2ClientTransport.Config.Backoff
  175. /// Configuration for connection management.
  176. public var connection: HTTP2ClientTransport.Config.Connection
  177. /// Compression configuration.
  178. public var compression: HTTP2ClientTransport.Config.Compression
  179. /// The transport's security.
  180. public var transportSecurity: TransportSecurity
  181. /// Creates a new connection configuration.
  182. ///
  183. /// - Parameters:
  184. /// - http2: HTTP2 configuration.
  185. /// - backoff: Backoff configuration.
  186. /// - connection: Connection configuration.
  187. /// - compression: Compression configuration.
  188. /// - transportSecurity: The transport's security configuration.
  189. ///
  190. /// - SeeAlso: ``defaults(transportSecurity:configure:)``
  191. public init(
  192. http2: HTTP2ClientTransport.Config.HTTP2,
  193. backoff: HTTP2ClientTransport.Config.Backoff,
  194. connection: HTTP2ClientTransport.Config.Connection,
  195. compression: HTTP2ClientTransport.Config.Compression,
  196. transportSecurity: TransportSecurity
  197. ) {
  198. self.http2 = http2
  199. self.connection = connection
  200. self.backoff = backoff
  201. self.compression = compression
  202. self.transportSecurity = transportSecurity
  203. }
  204. /// Default values.
  205. ///
  206. /// - Parameters:
  207. /// - transportSecurity: The security settings applied to the transport.
  208. /// - configure: A closure which allows you to modify the defaults before returning them.
  209. public static func defaults(
  210. transportSecurity: TransportSecurity,
  211. configure: (_ config: inout Self) -> Void = { _ in }
  212. ) -> Self {
  213. var config = Self(
  214. http2: .defaults,
  215. backoff: .defaults,
  216. connection: .defaults,
  217. compression: .defaults,
  218. transportSecurity: transportSecurity
  219. )
  220. configure(&config)
  221. return config
  222. }
  223. }
  224. }
  225. extension GRPCChannel.Config {
  226. init(transportServices config: HTTP2ClientTransport.TransportServices.Config) {
  227. self.init(
  228. http2: config.http2,
  229. backoff: config.backoff,
  230. connection: config.connection,
  231. compression: config.compression
  232. )
  233. }
  234. }
  235. extension NIOTSConnectionBootstrap {
  236. fileprivate func connect<Output: Sendable>(
  237. to address: GRPCNIOTransportCore.SocketAddress,
  238. childChannelInitializer: @escaping @Sendable (any Channel) -> EventLoopFuture<Output>
  239. ) async throws -> Output {
  240. if address.virtualSocket != nil {
  241. throw RuntimeError(
  242. code: .transportError,
  243. message: """
  244. Virtual sockets are not supported by 'HTTP2ClientTransport.TransportServices'. \
  245. Please use the 'HTTP2ClientTransport.Posix' transport.
  246. """
  247. )
  248. } else {
  249. return try await self.connect(
  250. to: NIOCore.SocketAddress(address),
  251. channelInitializer: childChannelInitializer
  252. )
  253. }
  254. }
  255. }
  256. extension ClientTransport where Self == HTTP2ClientTransport.TransportServices {
  257. /// Create a new `TransportServices` based HTTP/2 client transport.
  258. ///
  259. /// - Parameters:
  260. /// - target: A target to resolve.
  261. /// - config: Configuration for the transport.
  262. /// - resolverRegistry: A registry of resolver factories.
  263. /// - serviceConfig: Service config controlling how the transport should establish and
  264. /// load-balance connections.
  265. /// - eventLoopGroup: The underlying NIO `EventLoopGroup` to run connections on. This must
  266. /// be a `NIOTSEventLoopGroup` or an `EventLoop` from
  267. /// a `NIOTSEventLoopGroup`.
  268. /// - Throws: When no suitable resolver could be found for the `target`.
  269. public static func http2NIOTS(
  270. target: any ResolvableTarget,
  271. config: HTTP2ClientTransport.TransportServices.Config,
  272. resolverRegistry: NameResolverRegistry = .defaults,
  273. serviceConfig: ServiceConfig = ServiceConfig(),
  274. eventLoopGroup: any EventLoopGroup = .singletonNIOTSEventLoopGroup
  275. ) throws -> Self {
  276. try HTTP2ClientTransport.TransportServices(
  277. target: target,
  278. config: config,
  279. resolverRegistry: resolverRegistry,
  280. serviceConfig: serviceConfig,
  281. eventLoopGroup: eventLoopGroup
  282. )
  283. }
  284. }
  285. extension NWProtocolTLS.Options {
  286. convenience init(
  287. _ tlsConfig: HTTP2ClientTransport.TransportServices.Config.TLS,
  288. authority: String?
  289. ) throws {
  290. self.init()
  291. if let identityProvider = tlsConfig.identityProvider {
  292. guard let sec_identity = sec_identity_create(try identityProvider()) else {
  293. throw RuntimeError(
  294. code: .transportError,
  295. message: """
  296. There was an issue creating the SecIdentity required to set up TLS. \
  297. Please check your TLS configuration.
  298. """
  299. )
  300. }
  301. sec_protocol_options_set_local_identity(
  302. self.securityProtocolOptions,
  303. sec_identity
  304. )
  305. }
  306. switch tlsConfig.serverCertificateVerification.wrapped {
  307. case .doNotVerify:
  308. sec_protocol_options_set_peer_authentication_required(
  309. self.securityProtocolOptions,
  310. false
  311. )
  312. case .fullVerification:
  313. sec_protocol_options_set_peer_authentication_required(
  314. self.securityProtocolOptions,
  315. true
  316. )
  317. authority?.withCString { serverName in
  318. sec_protocol_options_set_tls_server_name(
  319. self.securityProtocolOptions,
  320. serverName
  321. )
  322. }
  323. case .noHostnameVerification:
  324. sec_protocol_options_set_peer_authentication_required(
  325. self.securityProtocolOptions,
  326. true
  327. )
  328. }
  329. sec_protocol_options_set_min_tls_protocol_version(
  330. self.securityProtocolOptions,
  331. .TLSv12
  332. )
  333. for `protocol` in ["grpc-exp", "h2"] {
  334. sec_protocol_options_add_tls_application_protocol(
  335. self.securityProtocolOptions,
  336. `protocol`
  337. )
  338. }
  339. self.setUpVerifyBlock(trustRootsSource: tlsConfig.trustRoots)
  340. }
  341. }
  342. #endif