HTTP2ServerTransport+Posix.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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. internal import NIOCore
  19. internal import NIOExtras
  20. internal import NIOHTTP2
  21. public import NIOPosix // has to be public because of default argument value in init
  22. private import NIOSSL
  23. private import Synchronization
  24. extension HTTP2ServerTransport {
  25. /// A `ServerTransport` using HTTP/2 built on top of `NIOPosix`.
  26. ///
  27. /// This transport builds on top of SwiftNIO's Posix networking layer and is suitable for use
  28. /// on Linux and Darwin based platform (macOS, iOS, etc.) However, it's *strongly* recommended
  29. /// that if you are targeting Darwin platforms then you should use the `NIOTS` variant of
  30. /// the `HTTP2ServerTransport`.
  31. ///
  32. /// You can control various aspects of connection creation, management, security and RPC behavior via
  33. /// the ``Config``.
  34. ///
  35. /// Beyond creating the transport you don't need to interact with it directly, instead, pass it
  36. /// to a `GRPCServer`:
  37. ///
  38. /// ```swift
  39. /// try await withThrowingDiscardingTaskGroup { group in
  40. /// let transport = HTTP2ServerTransport.Posix(
  41. /// address: .ipv4(host: "127.0.0.1", port: 0),
  42. /// transportSecurity: .plaintext
  43. /// )
  44. /// let server = GRPCServer(transport: transport, services: someServices)
  45. /// group.addTask {
  46. /// try await server.serve()
  47. /// }
  48. ///
  49. /// // ...
  50. /// }
  51. /// ```
  52. public struct Posix: ServerTransport, ListeningServerTransport {
  53. public typealias Bytes = GRPCNIOTransportBytes
  54. private struct ListenerFactory: HTTP2ListenerFactory {
  55. let config: Config
  56. let transportSecurity: TransportSecurity
  57. func makeListeningChannel(
  58. eventLoopGroup: any EventLoopGroup,
  59. address: GRPCNIOTransportCore.SocketAddress,
  60. serverQuiescingHelper: ServerQuiescingHelper
  61. ) async throws -> NIOAsyncChannel<AcceptedChannel, Never> {
  62. let sslContext: NIOSSLContext?
  63. switch self.transportSecurity.wrapped {
  64. case .plaintext:
  65. sslContext = nil
  66. case .tls(let tlsConfig):
  67. do {
  68. sslContext = try NIOSSLContext(configuration: TLSConfiguration(tlsConfig))
  69. } catch {
  70. throw RuntimeError(
  71. code: .transportError,
  72. message: "Couldn't create SSL context, check your TLS configuration.",
  73. cause: error
  74. )
  75. }
  76. }
  77. let serverChannel = try await ServerBootstrap(group: eventLoopGroup)
  78. .serverChannelOption(.socketOption(.so_reuseaddr), value: 1)
  79. .serverChannelInitializer { channel in
  80. return channel.eventLoop.makeCompletedFuture {
  81. let quiescingHandler = serverQuiescingHelper.makeServerChannelHandler(
  82. channel: channel
  83. )
  84. try channel.pipeline.syncOperations.addHandler(quiescingHandler)
  85. }.runInitializerIfSet(
  86. self.config.channelDebuggingCallbacks.onBindTCPListener,
  87. on: channel
  88. )
  89. }
  90. .bind(to: address) { channel in
  91. channel.eventLoop.makeCompletedFuture {
  92. if let sslContext {
  93. try channel.pipeline.syncOperations.addHandler(
  94. NIOSSLServerHandler(context: sslContext)
  95. )
  96. }
  97. let requireALPN: Bool
  98. let scheme: Scheme
  99. switch self.transportSecurity.wrapped {
  100. case .plaintext:
  101. requireALPN = false
  102. scheme = .http
  103. case .tls(let tlsConfig):
  104. requireALPN = tlsConfig.requireALPN
  105. scheme = .https
  106. }
  107. return try channel.pipeline.syncOperations.configureGRPCServerPipeline(
  108. channel: channel,
  109. compressionConfig: self.config.compression,
  110. connectionConfig: self.config.connection,
  111. http2Config: self.config.http2,
  112. rpcConfig: self.config.rpc,
  113. debugConfig: self.config.channelDebuggingCallbacks,
  114. requireALPN: requireALPN,
  115. scheme: scheme
  116. )
  117. }.runInitializerIfSet(
  118. self.config.channelDebuggingCallbacks.onAcceptTCPConnection,
  119. on: channel
  120. )
  121. }
  122. return serverChannel
  123. }
  124. }
  125. private let underlyingTransport: CommonHTTP2ServerTransport<ListenerFactory>
  126. /// The listening address for this server transport.
  127. ///
  128. /// It is an `async` property because it will only return once the address has been successfully bound.
  129. ///
  130. /// - Throws: A runtime error will be thrown if the address could not be bound or is not bound any
  131. /// longer, because the transport isn't listening anymore. It can also throw if the transport returned an
  132. /// invalid address.
  133. public var listeningAddress: GRPCNIOTransportCore.SocketAddress {
  134. get async throws {
  135. try await self.underlyingTransport.listeningAddress
  136. }
  137. }
  138. /// Create a new `Posix` transport.
  139. ///
  140. /// - Parameters:
  141. /// - address: The address to which the server should be bound.
  142. /// - transportSecurity: The configuration for securing network traffic.
  143. /// - config: The transport configuration.
  144. /// - eventLoopGroup: The ELG from which to get ELs to run this transport.
  145. public init(
  146. address: GRPCNIOTransportCore.SocketAddress,
  147. transportSecurity: TransportSecurity,
  148. config: Config = .defaults,
  149. eventLoopGroup: MultiThreadedEventLoopGroup = .singletonMultiThreadedEventLoopGroup
  150. ) {
  151. let factory = ListenerFactory(config: config, transportSecurity: transportSecurity)
  152. let helper = ServerQuiescingHelper(group: eventLoopGroup)
  153. self.underlyingTransport = CommonHTTP2ServerTransport(
  154. address: address,
  155. eventLoopGroup: eventLoopGroup,
  156. quiescingHelper: helper,
  157. listenerFactory: factory
  158. )
  159. }
  160. public func listen(
  161. streamHandler: @escaping @Sendable (
  162. _ stream: RPCStream<Inbound, Outbound>,
  163. _ context: ServerContext
  164. ) async -> Void
  165. ) async throws {
  166. try await self.underlyingTransport.listen(streamHandler: streamHandler)
  167. }
  168. public func beginGracefulShutdown() {
  169. self.underlyingTransport.beginGracefulShutdown()
  170. }
  171. }
  172. }
  173. extension HTTP2ServerTransport.Posix {
  174. /// Config for the `Posix` transport.
  175. public struct Config: Sendable {
  176. /// Compression configuration.
  177. public var compression: HTTP2ServerTransport.Config.Compression
  178. /// Connection configuration.
  179. public var connection: HTTP2ServerTransport.Config.Connection
  180. /// HTTP2 configuration.
  181. public var http2: HTTP2ServerTransport.Config.HTTP2
  182. /// RPC configuration.
  183. public var rpc: HTTP2ServerTransport.Config.RPC
  184. /// Channel callbacks for debugging.
  185. public var channelDebuggingCallbacks: HTTP2ServerTransport.Config.ChannelDebuggingCallbacks
  186. /// Construct a new `Config`.
  187. ///
  188. /// - Parameters:
  189. /// - http2: HTTP2 configuration.
  190. /// - rpc: RPC configuration.
  191. /// - connection: Connection configuration.
  192. /// - compression: Compression configuration.
  193. /// - channelDebuggingCallbacks: Channel callbacks for debugging.
  194. ///
  195. /// - SeeAlso: ``defaults(configure:)`` and ``defaults``.
  196. public init(
  197. http2: HTTP2ServerTransport.Config.HTTP2,
  198. rpc: HTTP2ServerTransport.Config.RPC,
  199. connection: HTTP2ServerTransport.Config.Connection,
  200. compression: HTTP2ServerTransport.Config.Compression,
  201. channelDebuggingCallbacks: HTTP2ServerTransport.Config.ChannelDebuggingCallbacks
  202. ) {
  203. self.compression = compression
  204. self.connection = connection
  205. self.http2 = http2
  206. self.rpc = rpc
  207. self.channelDebuggingCallbacks = channelDebuggingCallbacks
  208. }
  209. /// Default configuration.
  210. public static var defaults: Self {
  211. Self.defaults()
  212. }
  213. /// Default values for the different configurations.
  214. ///
  215. /// - Parameters:
  216. /// - configure: A closure which allows you to modify the defaults before returning them.
  217. public static func defaults(
  218. configure: (_ config: inout Self) -> Void = { _ in }
  219. ) -> Self {
  220. var config = Self(
  221. http2: .defaults,
  222. rpc: .defaults,
  223. connection: .defaults,
  224. compression: .defaults,
  225. channelDebuggingCallbacks: .defaults
  226. )
  227. configure(&config)
  228. return config
  229. }
  230. }
  231. }
  232. extension ServerBootstrap {
  233. fileprivate func bind<Output: Sendable>(
  234. to address: GRPCNIOTransportCore.SocketAddress,
  235. childChannelInitializer: @escaping @Sendable (any Channel) -> EventLoopFuture<Output>
  236. ) async throws -> NIOAsyncChannel<Output, Never> {
  237. if let virtualSocket = address.virtualSocket {
  238. return try await self.bind(
  239. to: VsockAddress(virtualSocket),
  240. childChannelInitializer: childChannelInitializer
  241. )
  242. } else if let uds = address.unixDomainSocket {
  243. return try await self.bind(
  244. unixDomainSocketPath: uds.path,
  245. cleanupExistingSocketFile: true,
  246. childChannelInitializer: childChannelInitializer
  247. )
  248. } else {
  249. return try await self.bind(
  250. to: NIOCore.SocketAddress(address),
  251. childChannelInitializer: childChannelInitializer
  252. )
  253. }
  254. }
  255. }
  256. extension ServerTransport where Self == HTTP2ServerTransport.Posix {
  257. /// Create a new `Posix` based HTTP/2 server transport.
  258. ///
  259. /// - Parameters:
  260. /// - address: The address to which the server should be bound.
  261. /// - transportSecurity: The configuration for securing network traffic.
  262. /// - config: The transport configuration.
  263. /// - eventLoopGroup: The underlying NIO `EventLoopGroup` to the server on. This must
  264. /// be a `MultiThreadedEventLoopGroup` or an `EventLoop` from
  265. /// a `MultiThreadedEventLoopGroup`.
  266. public static func http2NIOPosix(
  267. address: GRPCNIOTransportCore.SocketAddress,
  268. transportSecurity: HTTP2ServerTransport.Posix.TransportSecurity,
  269. config: HTTP2ServerTransport.Posix.Config = .defaults,
  270. eventLoopGroup: MultiThreadedEventLoopGroup = .singletonMultiThreadedEventLoopGroup
  271. ) -> Self {
  272. return HTTP2ServerTransport.Posix(
  273. address: address,
  274. transportSecurity: transportSecurity,
  275. config: config,
  276. eventLoopGroup: eventLoopGroup
  277. )
  278. }
  279. }