HTTP2ClientTransport+Posix.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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. public import GRPCCore
  17. public import GRPCNIOTransportCore // should be @usableFromInline
  18. public import NIOCore // has to be public because of EventLoopGroup param in init
  19. public import NIOPosix // has to be public because of default argument value in init
  20. private import NIOSSL
  21. @available(gRPCSwiftNIOTransport 2.0, *)
  22. extension HTTP2ClientTransport {
  23. /// A `ClientTransport` using HTTP/2 built on top of `NIOPosix`.
  24. ///
  25. /// This transport builds on top of SwiftNIO's Posix networking layer and is suitable for use
  26. /// on Linux and Darwin based platforms (macOS, iOS, etc.). However, it's *strongly* recommended
  27. /// that if you are targeting Darwin platforms then you should use the `NIOTS` 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, Unix domain socket targets, and Virtual Socket
  33. /// targets. If you use a custom target you must also provide an appropriately configured
  34. /// 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.Posix(
  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 Posix: ClientTransport {
  58. public typealias Bytes = GRPCNIOTransportBytes
  59. private let channel: GRPCChannel
  60. /// Creates a new NIOPosix-based HTTP/2 client transport.
  61. ///
  62. /// - Parameters:
  63. /// - target: A target to resolve.
  64. /// - transportSecurity: The configuration for securing network traffic.
  65. /// - config: Configuration for the transport.
  66. /// - resolverRegistry: A registry of resolver factories.
  67. /// - serviceConfig: Service config controlling how the transport should establish and
  68. /// load-balance connections.
  69. /// - eventLoopGroup: The underlying NIO `EventLoopGroup` to run connections on. This must
  70. /// be a `MultiThreadedEventLoopGroup` or an `EventLoop` from
  71. /// a `MultiThreadedEventLoopGroup`.
  72. /// - Throws: When no suitable resolver could be found for the `target`.
  73. public init(
  74. target: any ResolvableTarget,
  75. transportSecurity: TransportSecurity,
  76. config: Config = .defaults,
  77. resolverRegistry: NameResolverRegistry = .defaults,
  78. serviceConfig: ServiceConfig = ServiceConfig(),
  79. eventLoopGroup: any EventLoopGroup = .singletonMultiThreadedEventLoopGroup
  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: try Connector(
  93. eventLoopGroup: eventLoopGroup,
  94. config: config,
  95. transportSecurity: transportSecurity
  96. ),
  97. config: GRPCChannel.Config(posix: config),
  98. defaultServiceConfig: serviceConfig
  99. )
  100. }
  101. public var retryThrottle: RetryThrottle? {
  102. self.channel.retryThrottle
  103. }
  104. public func connect() async throws {
  105. await self.channel.connect()
  106. }
  107. public func config(forMethod descriptor: MethodDescriptor) -> MethodConfig? {
  108. self.channel.config(forMethod: descriptor)
  109. }
  110. public func beginGracefulShutdown() {
  111. self.channel.beginGracefulShutdown()
  112. }
  113. public func withStream<T: Sendable>(
  114. descriptor: MethodDescriptor,
  115. options: CallOptions,
  116. _ closure: (RPCStream<Inbound, Outbound>, ClientContext) async throws -> T
  117. ) async throws -> T {
  118. try await self.channel.withStream(descriptor: descriptor, options: options, closure)
  119. }
  120. }
  121. }
  122. @available(gRPCSwiftNIOTransport 2.0, *)
  123. extension HTTP2ClientTransport.Posix {
  124. struct Connector: HTTP2Connector {
  125. private let config: HTTP2ClientTransport.Posix.Config
  126. private let eventLoopGroup: any EventLoopGroup
  127. private let sslContext: NIOSSLContext?
  128. private let isPlainText: Bool
  129. private let customVerificationCallback:
  130. (
  131. @Sendable (
  132. [NIOSSLCertificate], EventLoopPromise<NIOSSLVerificationResultWithMetadata>
  133. ) -> Void
  134. )?
  135. init(
  136. eventLoopGroup: any EventLoopGroup,
  137. config: HTTP2ClientTransport.Posix.Config,
  138. transportSecurity: HTTP2ClientTransport.Posix.TransportSecurity
  139. ) throws {
  140. self.eventLoopGroup = eventLoopGroup
  141. self.config = config
  142. switch transportSecurity.wrapped {
  143. case .plaintext:
  144. self.sslContext = nil
  145. self.isPlainText = true
  146. self.customVerificationCallback = nil
  147. case .tls(let tlsConfig):
  148. do {
  149. self.sslContext = try NIOSSLContext(configuration: TLSConfiguration(tlsConfig))
  150. self.isPlainText = false
  151. self.customVerificationCallback = tlsConfig.customVerificationCallback
  152. } catch {
  153. throw RuntimeError(
  154. code: .transportError,
  155. message: "Couldn't create SSL context, check your TLS configuration.",
  156. cause: error
  157. )
  158. }
  159. }
  160. }
  161. func establishConnection(
  162. to address: GRPCNIOTransportCore.SocketAddress,
  163. sniServerHostname: String?
  164. ) async throws -> HTTP2Connection {
  165. let (channel, multiplexer) = try await ClientBootstrap(
  166. group: self.eventLoopGroup
  167. ).connect(to: address) { channel in
  168. channel.eventLoop.makeCompletedFuture {
  169. if let sslContext = self.sslContext {
  170. if let customVerificationCallback = self.customVerificationCallback {
  171. try channel.pipeline.syncOperations.addHandler(
  172. NIOSSLClientHandler(
  173. context: sslContext,
  174. serverHostname: sniServerHostname,
  175. customVerificationCallbackWithMetadata: customVerificationCallback
  176. )
  177. )
  178. } else {
  179. try channel.pipeline.syncOperations.addHandler(
  180. NIOSSLClientHandler(
  181. context: sslContext,
  182. serverHostname: sniServerHostname
  183. )
  184. )
  185. }
  186. }
  187. return try channel.pipeline.syncOperations.configureGRPCClientPipeline(
  188. channel: channel,
  189. config: GRPCChannel.Config(posix: self.config)
  190. )
  191. }.runInitializerIfSet(
  192. self.config.channelDebuggingCallbacks.onCreateTCPConnection,
  193. on: channel
  194. )
  195. }
  196. return HTTP2Connection(
  197. channel: channel,
  198. multiplexer: multiplexer,
  199. isPlaintext: self.isPlainText,
  200. onCreateHTTP2Stream: self.config.channelDebuggingCallbacks.onCreateHTTP2Stream
  201. )
  202. }
  203. }
  204. }
  205. @available(gRPCSwiftNIOTransport 2.0, *)
  206. extension HTTP2ClientTransport.Posix {
  207. public struct Config: Sendable {
  208. /// Configuration for HTTP/2 connections.
  209. public var http2: HTTP2ClientTransport.Config.HTTP2
  210. /// Configuration for backoff used when establishing a connection.
  211. public var backoff: HTTP2ClientTransport.Config.Backoff
  212. /// Configuration for backoff used when resolving names.
  213. @available(gRPCSwiftNIOTransport 2.4, *)
  214. package var resolverBackoff: HTTP2ClientTransport.Config.Backoff
  215. /// Configuration for connection management.
  216. public var connection: HTTP2ClientTransport.Config.Connection
  217. /// Compression configuration.
  218. public var compression: HTTP2ClientTransport.Config.Compression
  219. /// Channel callbacks for debugging.
  220. public var channelDebuggingCallbacks: HTTP2ClientTransport.Config.ChannelDebuggingCallbacks
  221. /// Creates a new connection configuration.
  222. ///
  223. /// - Parameters:
  224. /// - http2: HTTP2 configuration.
  225. /// - backoff: Backoff configuration.
  226. /// - connection: Connection configuration.
  227. /// - compression: Compression configuration.
  228. /// - channelDebuggingCallbacks: Channel callbacks for debugging.
  229. ///
  230. /// - SeeAlso: ``defaults(configure:)`` and ``defaults``.
  231. public init(
  232. http2: HTTP2ClientTransport.Config.HTTP2,
  233. backoff: HTTP2ClientTransport.Config.Backoff,
  234. connection: HTTP2ClientTransport.Config.Connection,
  235. compression: HTTP2ClientTransport.Config.Compression,
  236. channelDebuggingCallbacks: HTTP2ClientTransport.Config.ChannelDebuggingCallbacks
  237. ) {
  238. self.init(
  239. http2: http2,
  240. backoff: backoff,
  241. resolverBackoff: Self.defaults.resolverBackoff,
  242. connection: connection,
  243. compression: compression,
  244. channelDebuggingCallbacks: channelDebuggingCallbacks
  245. )
  246. }
  247. private init(
  248. http2: HTTP2ClientTransport.Config.HTTP2,
  249. backoff: HTTP2ClientTransport.Config.Backoff,
  250. resolverBackoff: HTTP2ClientTransport.Config.Backoff,
  251. connection: HTTP2ClientTransport.Config.Connection,
  252. compression: HTTP2ClientTransport.Config.Compression,
  253. channelDebuggingCallbacks: HTTP2ClientTransport.Config.ChannelDebuggingCallbacks
  254. ) {
  255. self.http2 = http2
  256. self.connection = connection
  257. self.backoff = backoff
  258. self.resolverBackoff = resolverBackoff
  259. self.compression = compression
  260. self.channelDebuggingCallbacks = channelDebuggingCallbacks
  261. }
  262. /// Default configuration.
  263. public static var defaults: Self {
  264. Self.defaults()
  265. }
  266. /// Default values.
  267. ///
  268. /// - Parameters:
  269. /// - configure: A closure which allows you to modify the defaults before returning them.
  270. public static func defaults(
  271. configure: (_ config: inout Self) -> Void = { _ in }
  272. ) -> Self {
  273. var config = Self(
  274. http2: .defaults,
  275. backoff: .defaults,
  276. resolverBackoff: .defaults,
  277. connection: .defaults,
  278. compression: .defaults,
  279. channelDebuggingCallbacks: .defaults
  280. )
  281. configure(&config)
  282. return config
  283. }
  284. }
  285. }
  286. @available(gRPCSwiftNIOTransport 2.0, *)
  287. extension GRPCChannel.Config {
  288. init(posix: HTTP2ClientTransport.Posix.Config) {
  289. self.init(
  290. http2: posix.http2,
  291. backoff: posix.backoff,
  292. resolverBackoff: posix.backoff,
  293. connection: posix.connection,
  294. compression: posix.compression
  295. )
  296. }
  297. }
  298. @available(gRPCSwiftNIOTransport 2.0, *)
  299. extension ClientTransport where Self == HTTP2ClientTransport.Posix {
  300. /// Creates a new Posix based HTTP/2 client transport.
  301. ///
  302. /// - Parameters:
  303. /// - target: A target to resolve.
  304. /// - transportSecurity: The configuration for securing network traffic.
  305. /// - config: Configuration for the transport.
  306. /// - resolverRegistry: A registry of resolver factories.
  307. /// - serviceConfig: Service config controlling how the transport should establish and
  308. /// load-balance connections.
  309. /// - eventLoopGroup: The underlying NIO `EventLoopGroup` to run connections on. This must
  310. /// be a `MultiThreadedEventLoopGroup` or an `EventLoop` from
  311. /// a `MultiThreadedEventLoopGroup`.
  312. /// - Throws: When no suitable resolver could be found for the `target`.
  313. public static func http2NIOPosix(
  314. target: any ResolvableTarget,
  315. transportSecurity: HTTP2ClientTransport.Posix.TransportSecurity,
  316. config: HTTP2ClientTransport.Posix.Config = .defaults,
  317. resolverRegistry: NameResolverRegistry = .defaults,
  318. serviceConfig: ServiceConfig = ServiceConfig(),
  319. eventLoopGroup: any EventLoopGroup = .singletonMultiThreadedEventLoopGroup
  320. ) throws -> Self {
  321. return try HTTP2ClientTransport.Posix(
  322. target: target,
  323. transportSecurity: transportSecurity,
  324. config: config,
  325. resolverRegistry: resolverRegistry,
  326. serviceConfig: serviceConfig,
  327. eventLoopGroup: eventLoopGroup
  328. )
  329. }
  330. }