HTTP2ServerTransport+Posix.swift 9.8 KB

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