HTTP2ServerTransport+Posix.swift 10 KB

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