HTTP2ServerTransport+Posix.swift 10 KB

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