HTTP2ClientTransport+TransportServices.swift 13 KB

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