HTTP2ClientTransport+TransportServices.swift 14 KB

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