HTTP2ServerTransport+Posix.swift 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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. /// config: .defaults(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. private struct ListenerFactory: HTTP2ListenerFactory {
  54. let config: Config
  55. func makeListeningChannel(
  56. eventLoopGroup: any EventLoopGroup,
  57. address: GRPCNIOTransportCore.SocketAddress,
  58. serverQuiescingHelper: ServerQuiescingHelper
  59. ) async throws -> NIOAsyncChannel<AcceptedChannel, Never> {
  60. let sslContext: NIOSSLContext?
  61. switch self.config.transportSecurity.wrapped {
  62. case .plaintext:
  63. sslContext = nil
  64. case .tls(let tlsConfig):
  65. do {
  66. sslContext = try NIOSSLContext(configuration: TLSConfiguration(tlsConfig))
  67. } catch {
  68. throw RuntimeError(
  69. code: .transportError,
  70. message: "Couldn't create SSL context, check your TLS configuration.",
  71. cause: error
  72. )
  73. }
  74. }
  75. let serverChannel = try await ServerBootstrap(group: eventLoopGroup)
  76. .serverChannelOption(.socketOption(.so_reuseaddr), value: 1)
  77. .serverChannelInitializer { channel in
  78. return channel.eventLoop.makeCompletedFuture {
  79. let quiescingHandler = serverQuiescingHelper.makeServerChannelHandler(
  80. channel: channel
  81. )
  82. return try channel.pipeline.syncOperations.addHandler(quiescingHandler)
  83. }
  84. }
  85. .bind(to: address) { channel in
  86. channel.eventLoop.makeCompletedFuture {
  87. if let sslContext {
  88. try channel.pipeline.syncOperations.addHandler(
  89. NIOSSLServerHandler(context: sslContext)
  90. )
  91. }
  92. let requireALPN: Bool
  93. let scheme: Scheme
  94. switch self.config.transportSecurity.wrapped {
  95. case .plaintext:
  96. requireALPN = false
  97. scheme = .http
  98. case .tls(let tlsConfig):
  99. requireALPN = tlsConfig.requireALPN
  100. scheme = .https
  101. }
  102. return try channel.pipeline.syncOperations.configureGRPCServerPipeline(
  103. channel: channel,
  104. compressionConfig: self.config.compression,
  105. connectionConfig: self.config.connection,
  106. http2Config: self.config.http2,
  107. rpcConfig: self.config.rpc,
  108. requireALPN: requireALPN,
  109. scheme: scheme
  110. )
  111. }
  112. }
  113. return serverChannel
  114. }
  115. }
  116. private let underlyingTransport: CommonHTTP2ServerTransport<ListenerFactory>
  117. /// The listening address for this server transport.
  118. ///
  119. /// It is an `async` property because it will only return once the address has been successfully bound.
  120. ///
  121. /// - Throws: A runtime error will be thrown if the address could not be bound or is not bound any
  122. /// longer, because the transport isn't listening anymore. It can also throw if the transport returned an
  123. /// invalid address.
  124. public var listeningAddress: GRPCNIOTransportCore.SocketAddress {
  125. get async throws {
  126. try await self.underlyingTransport.listeningAddress
  127. }
  128. }
  129. /// Create a new `Posix` transport.
  130. ///
  131. /// - Parameters:
  132. /// - address: The address to which the server should be bound.
  133. /// - config: The transport configuration.
  134. /// - eventLoopGroup: The ELG from which to get ELs to run this transport.
  135. public init(
  136. address: GRPCNIOTransportCore.SocketAddress,
  137. config: Config,
  138. eventLoopGroup: MultiThreadedEventLoopGroup = .singletonMultiThreadedEventLoopGroup
  139. ) {
  140. let factory = ListenerFactory(config: config)
  141. let helper = ServerQuiescingHelper(group: eventLoopGroup)
  142. self.underlyingTransport = CommonHTTP2ServerTransport(
  143. address: address,
  144. eventLoopGroup: eventLoopGroup,
  145. quiescingHelper: helper,
  146. listenerFactory: factory
  147. )
  148. }
  149. public func listen(
  150. streamHandler: @escaping @Sendable (
  151. _ stream: RPCStream<Inbound, Outbound>,
  152. _ context: ServerContext
  153. ) async -> Void
  154. ) async throws {
  155. try await self.underlyingTransport.listen(streamHandler: streamHandler)
  156. }
  157. public func beginGracefulShutdown() {
  158. self.underlyingTransport.beginGracefulShutdown()
  159. }
  160. }
  161. }
  162. extension HTTP2ServerTransport.Posix {
  163. /// Config for the `Posix` transport.
  164. public struct Config: Sendable {
  165. /// Compression configuration.
  166. public var compression: HTTP2ServerTransport.Config.Compression
  167. /// Connection configuration.
  168. public var connection: HTTP2ServerTransport.Config.Connection
  169. /// HTTP2 configuration.
  170. public var http2: HTTP2ServerTransport.Config.HTTP2
  171. /// RPC configuration.
  172. public var rpc: HTTP2ServerTransport.Config.RPC
  173. /// The transport's security.
  174. public var transportSecurity: TransportSecurity
  175. /// Construct a new `Config`.
  176. ///
  177. /// - Parameters:
  178. /// - http2: HTTP2 configuration.
  179. /// - rpc: RPC configuration.
  180. /// - connection: Connection configuration.
  181. /// - compression: Compression configuration.
  182. /// - transportSecurity: The transport's security configuration.
  183. ///
  184. /// - SeeAlso: ``defaults(transportSecurity:configure:)``
  185. public init(
  186. http2: HTTP2ServerTransport.Config.HTTP2,
  187. rpc: HTTP2ServerTransport.Config.RPC,
  188. connection: HTTP2ServerTransport.Config.Connection,
  189. compression: HTTP2ServerTransport.Config.Compression,
  190. transportSecurity: TransportSecurity
  191. ) {
  192. self.compression = compression
  193. self.connection = connection
  194. self.http2 = http2
  195. self.rpc = rpc
  196. self.transportSecurity = transportSecurity
  197. }
  198. /// Default values for the different configurations.
  199. ///
  200. /// - Parameters:
  201. /// - transportSecurity: The security settings applied to the transport.
  202. /// - configure: A closure which allows you to modify the defaults before returning them.
  203. public static func defaults(
  204. transportSecurity: TransportSecurity,
  205. configure: (_ config: inout Self) -> Void = { _ in }
  206. ) -> Self {
  207. var config = Self(
  208. http2: .defaults,
  209. rpc: .defaults,
  210. connection: .defaults,
  211. compression: .defaults,
  212. transportSecurity: transportSecurity
  213. )
  214. configure(&config)
  215. return config
  216. }
  217. }
  218. }
  219. extension ServerBootstrap {
  220. fileprivate func bind<Output: Sendable>(
  221. to address: GRPCNIOTransportCore.SocketAddress,
  222. childChannelInitializer: @escaping @Sendable (any Channel) -> EventLoopFuture<Output>
  223. ) async throws -> NIOAsyncChannel<Output, Never> {
  224. if let virtualSocket = address.virtualSocket {
  225. return try await self.bind(
  226. to: VsockAddress(virtualSocket),
  227. childChannelInitializer: childChannelInitializer
  228. )
  229. } else {
  230. return try await self.bind(
  231. to: NIOCore.SocketAddress(address),
  232. childChannelInitializer: childChannelInitializer
  233. )
  234. }
  235. }
  236. }
  237. extension ServerTransport where Self == HTTP2ServerTransport.Posix {
  238. /// Create a new `Posix` based HTTP/2 server transport.
  239. ///
  240. /// - Parameters:
  241. /// - address: The address to which the server should be bound.
  242. /// - config: The transport configuration.
  243. /// - eventLoopGroup: The underlying NIO `EventLoopGroup` to the server on. This must
  244. /// be a `MultiThreadedEventLoopGroup` or an `EventLoop` from
  245. /// a `MultiThreadedEventLoopGroup`.
  246. public static func http2NIOPosix(
  247. address: GRPCNIOTransportCore.SocketAddress,
  248. config: HTTP2ServerTransport.Posix.Config,
  249. eventLoopGroup: MultiThreadedEventLoopGroup = .singletonMultiThreadedEventLoopGroup
  250. ) -> Self {
  251. return HTTP2ServerTransport.Posix(
  252. address: address,
  253. config: config,
  254. eventLoopGroup: eventLoopGroup
  255. )
  256. }
  257. }