HTTP2ClientTransport+TransportServices.swift 12 KB

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