Server.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. /*
  2. * Copyright 2019, 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. import Foundation
  17. import NIO
  18. import NIOHTTP1
  19. import NIOHTTP2
  20. import NIOSSL
  21. import Logging
  22. /// Wrapper object to manage the lifecycle of a gRPC server.
  23. ///
  24. /// The pipeline is configured in three stages detailed below. Note: handlers marked with
  25. /// a '*' are responsible for handling errors.
  26. ///
  27. /// 1. Initial stage, prior to HTTP protocol detection.
  28. ///
  29. /// ┌───────────────────────────┐
  30. /// │ HTTPProtocolSwitcher* │
  31. /// └─▲───────────────────────┬─┘
  32. /// ByteBuffer│ │ByteBuffer
  33. /// ┌─┴───────────────────────▼─┐
  34. /// │ NIOSSLHandler │
  35. /// └─▲───────────────────────┬─┘
  36. /// ByteBuffer│ │ByteBuffer
  37. /// │ ▼
  38. ///
  39. /// The `NIOSSLHandler` is optional and depends on how the framework user has configured
  40. /// their server. The `HTTPProtocolSwitcher` detects which HTTP version is being used and
  41. /// configures the pipeline accordingly.
  42. ///
  43. /// 2. HTTP version detected. "HTTP Handlers" depends on the HTTP version determined by
  44. /// `HTTPProtocolSwitcher`. All of these handlers are provided by NIO except for the
  45. /// `WebCORSHandler` which is used for HTTP/1.
  46. ///
  47. /// ┌─────────────────────────────────┐
  48. /// │ GRPCServerRequestRoutingHandler │
  49. /// └─▲─────────────────────────────┬─┘
  50. /// HTTPServerRequestPart│ │HTTPServerResponsePart
  51. /// ┌─┴─────────────────────────────▼─┐
  52. /// │ HTTP Handlers │
  53. /// └─▲─────────────────────────────┬─┘
  54. /// ByteBuffer│ │ByteBuffer
  55. /// ┌─┴─────────────────────────────▼─┐
  56. /// │ NIOSSLHandler │
  57. /// └─▲─────────────────────────────┬─┘
  58. /// ByteBuffer│ │ByteBuffer
  59. /// │ ▼
  60. ///
  61. /// The `GRPCServerRequestRoutingHandler` resolves the request head and configures the rest of
  62. /// the pipeline based on the RPC call being made.
  63. ///
  64. /// 3. The call has been resolved and is a function that this server can handle. Responses are
  65. /// written into `BaseCallHandler` by a user-implemented `CallHandlerProvider`.
  66. ///
  67. /// ┌─────────────────────────────────┐
  68. /// │ BaseCallHandler* │
  69. /// └─▲─────────────────────────────┬─┘
  70. /// GRPCServerRequestPart<T1>│ │GRPCServerResponsePart<T2>
  71. /// ┌─┴─────────────────────────────▼─┐
  72. /// │ HTTP1ToGRPCServerCodec │
  73. /// └─▲─────────────────────────────┬─┘
  74. /// HTTPServerRequestPart│ │HTTPServerResponsePart
  75. /// ┌─┴─────────────────────────────▼─┐
  76. /// │ HTTP Handlers │
  77. /// └─▲─────────────────────────────┬─┘
  78. /// ByteBuffer│ │ByteBuffer
  79. /// ┌─┴─────────────────────────────▼─┐
  80. /// │ NIOSSLHandler │
  81. /// └─▲─────────────────────────────┬─┘
  82. /// ByteBuffer│ │ByteBuffer
  83. /// │ ▼
  84. ///
  85. public final class Server {
  86. /// Makes and configures a `ServerBootstrap` using the provided configuration.
  87. public class func makeBootstrap(configuration: Configuration) -> ServerBootstrapProtocol {
  88. let bootstrap = PlatformSupport.makeServerBootstrap(group: configuration.eventLoopGroup)
  89. // Backlog is only available on `ServerBootstrap`.
  90. if bootstrap is ServerBootstrap {
  91. // Specify a backlog to avoid overloading the server.
  92. _ = bootstrap.serverChannelOption(ChannelOptions.backlog, value: 256)
  93. }
  94. return bootstrap
  95. // Enable `SO_REUSEADDR` to avoid "address already in use" error.
  96. .serverChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
  97. // Set the handlers that are applied to the accepted Channels
  98. .childChannelInitializer { channel in
  99. let protocolSwitcher = HTTPProtocolSwitcher(
  100. errorDelegate: configuration.errorDelegate,
  101. httpTargetWindowSize: configuration.httpTargetWindowSize,
  102. keepAlive: configuration.connectionKeepalive,
  103. idleTimeout: configuration.connectionIdleTimeout,
  104. logger: configuration.logger
  105. ) { (channel, logger) -> EventLoopFuture<Void> in
  106. let handler = GRPCServerRequestRoutingHandler(
  107. servicesByName: configuration.serviceProvidersByName,
  108. encoding: configuration.messageEncoding,
  109. errorDelegate: configuration.errorDelegate,
  110. logger: logger
  111. )
  112. return channel.pipeline.addHandler(handler)
  113. }
  114. let configured: EventLoopFuture<Void>
  115. if let tls = configuration.tls {
  116. configured = channel.configureTLS(configuration: tls).flatMap {
  117. channel.pipeline.addHandler(protocolSwitcher)
  118. }
  119. } else {
  120. configured = channel.pipeline.addHandler(protocolSwitcher)
  121. }
  122. // Add the debug initializer, if there is one.
  123. if let debugAcceptedChannelInitializer = configuration.debugChannelInitializer {
  124. return configured.flatMap {
  125. debugAcceptedChannelInitializer(channel)
  126. }
  127. } else {
  128. return configured
  129. }
  130. }
  131. // Enable TCP_NODELAY and SO_REUSEADDR for the accepted Channels
  132. .childChannelOption(ChannelOptions.socket(IPPROTO_TCP, TCP_NODELAY), value: 1)
  133. .childChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
  134. }
  135. /// Starts a server with the given configuration. See `Server.Configuration` for the options
  136. /// available to configure the server.
  137. public static func start(configuration: Configuration) -> EventLoopFuture<Server> {
  138. return makeBootstrap(configuration: configuration)
  139. .bind(to: configuration.target)
  140. .map { channel in
  141. Server(channel: channel, errorDelegate: configuration.errorDelegate)
  142. }
  143. }
  144. public let channel: Channel
  145. private var errorDelegate: ServerErrorDelegate?
  146. private init(channel: Channel, errorDelegate: ServerErrorDelegate?) {
  147. self.channel = channel
  148. // Maintain a strong reference to ensure it lives as long as the server.
  149. self.errorDelegate = errorDelegate
  150. // If we have an error delegate, add a server channel error handler as well. We don't need to wait for the handler to
  151. // be added.
  152. if let errorDelegate = errorDelegate {
  153. _ = channel.pipeline.addHandler(ServerChannelErrorHandler(errorDelegate: errorDelegate))
  154. }
  155. // nil out errorDelegate to avoid retain cycles.
  156. onClose.whenComplete { _ in
  157. self.errorDelegate = nil
  158. }
  159. }
  160. /// Fired when the server shuts down.
  161. public var onClose: EventLoopFuture<Void> {
  162. return channel.closeFuture
  163. }
  164. /// Shut down the server; this should be called to avoid leaking resources.
  165. public func close() -> EventLoopFuture<Void> {
  166. return channel.close(mode: .all)
  167. }
  168. }
  169. public typealias BindTarget = ConnectionTarget
  170. extension Server {
  171. /// The configuration for a server.
  172. public struct Configuration {
  173. /// The target to bind to.
  174. public var target: BindTarget
  175. /// The event loop group to run the connection on.
  176. public var eventLoopGroup: EventLoopGroup
  177. /// Providers the server should use to handle gRPC requests.
  178. public var serviceProviders: [CallHandlerProvider]
  179. /// An error delegate which is called when errors are caught. Provided delegates **must not
  180. /// maintain a strong reference to this `Server`**. Doing so will cause a retain cycle.
  181. public var errorDelegate: ServerErrorDelegate?
  182. /// TLS configuration for this connection. `nil` if TLS is not desired.
  183. public var tls: TLS?
  184. /// The connection keepalive configuration.
  185. public var connectionKeepalive: ServerConnectionKeepalive
  186. /// The amount of time to wait before closing connections. The idle timeout will start only
  187. /// if there are no RPCs in progress and will be cancelled as soon as any RPCs start.
  188. public var connectionIdleTimeout: TimeAmount
  189. /// The compression configuration for requests and responses.
  190. ///
  191. /// If compression is enabled for the server it may be disabled for responses on any RPC by
  192. /// setting `compressionEnabled` to `false` on the context of the call.
  193. ///
  194. /// Compression may also be disabled at the message-level for streaming responses (i.e. server
  195. /// streaming and bidirectional streaming RPCs) by passing setting `compression` to `.disabled`
  196. /// in `sendResponse(_:compression)`.
  197. public var messageEncoding: ServerMessageEncoding
  198. /// The HTTP/2 flow control target window size.
  199. public var httpTargetWindowSize: Int
  200. /// The root server logger. Accepted connections will branch from this logger and RPCs on
  201. /// each connection will use a logger branched from the connections logger. This logger is made
  202. /// available to service providers via `context`. Defaults to a no-op logger.
  203. public var logger: Logger
  204. /// A channel initializer which will be run after gRPC has initialized each accepted channel.
  205. /// This may be used to add additional handlers to the pipeline and is intended for debugging.
  206. /// This is analogous to `NIO.ServerBootstrap.childChannelInitializer`.
  207. ///
  208. /// - Warning: The initializer closure may be invoked *multiple times*. More precisely: it will
  209. /// be invoked at most once per accepted connection.
  210. public var debugChannelInitializer: ((Channel) -> EventLoopFuture<Void>)?
  211. /// Create a `Configuration` with some pre-defined defaults.
  212. ///
  213. /// - Parameters:
  214. /// - target: The target to bind to.
  215. /// - eventLoopGroup: The event loop group to run the server on.
  216. /// - serviceProviders: An array of `CallHandlerProvider`s which the server should use
  217. /// to handle requests.
  218. /// - errorDelegate: The error delegate, defaulting to a logging delegate.
  219. /// - tls: TLS configuration, defaulting to `nil`.
  220. /// - connectionKeepalive: The keepalive configuration to use.
  221. /// - connectionIdleTimeout: The amount of time to wait before closing the connection, defaulting to 5 minutes.
  222. /// - messageEncoding: Message compression configuration, defaulting to no compression.
  223. /// - httpTargetWindowSize: The HTTP/2 flow control target window size.
  224. /// - logger: A logger. Defaults to a no-op logger.
  225. /// - debugChannelInitializer: A channel initializer which will be called for each connection
  226. /// the server accepts after gRPC has initialized the channel. Defaults to `nil`.
  227. public init(
  228. target: BindTarget,
  229. eventLoopGroup: EventLoopGroup,
  230. serviceProviders: [CallHandlerProvider],
  231. errorDelegate: ServerErrorDelegate? = nil,
  232. tls: TLS? = nil,
  233. connectionKeepalive: ServerConnectionKeepalive = ServerConnectionKeepalive(),
  234. connectionIdleTimeout: TimeAmount = .minutes(5),
  235. messageEncoding: ServerMessageEncoding = .disabled,
  236. httpTargetWindowSize: Int = 65535,
  237. logger: Logger = Logger(label: "io.grpc", factory: { _ in SwiftLogNoOpLogHandler() }),
  238. debugChannelInitializer: ((Channel) -> EventLoopFuture<Void>)? = nil
  239. ) {
  240. self.target = target
  241. self.eventLoopGroup = eventLoopGroup
  242. self.serviceProviders = serviceProviders
  243. self.errorDelegate = errorDelegate
  244. self.tls = tls
  245. self.connectionKeepalive = connectionKeepalive
  246. self.connectionIdleTimeout = connectionIdleTimeout
  247. self.messageEncoding = messageEncoding
  248. self.httpTargetWindowSize = httpTargetWindowSize
  249. self.logger = logger
  250. self.debugChannelInitializer = debugChannelInitializer
  251. }
  252. }
  253. }
  254. fileprivate extension Server.Configuration {
  255. var serviceProvidersByName: [String: CallHandlerProvider] {
  256. return Dictionary(uniqueKeysWithValues: self.serviceProviders.map { ($0.serviceName, $0) })
  257. }
  258. }
  259. fileprivate extension Channel {
  260. /// Configure an SSL handler on the channel.
  261. ///
  262. /// - Parameters:
  263. /// - configuration: The configuration to use when creating the handler.
  264. /// - Returns: A future which will be succeeded when the pipeline has been configured.
  265. func configureTLS(configuration: Server.Configuration.TLS) -> EventLoopFuture<Void> {
  266. do {
  267. let context = try NIOSSLContext(configuration: configuration.configuration)
  268. return self.pipeline.addHandler(NIOSSLServerHandler(context: context))
  269. } catch {
  270. return self.pipeline.eventLoop.makeFailedFuture(error)
  271. }
  272. }
  273. }
  274. fileprivate extension ServerBootstrapProtocol {
  275. func bind(to target: BindTarget) -> EventLoopFuture<Channel> {
  276. switch target.wrapped {
  277. case .hostAndPort(let host, let port):
  278. return self.bind(host: host, port: port)
  279. case .unixDomainSocket(let path):
  280. return self.bind(unixDomainSocketPath: path)
  281. case .socketAddress(let address):
  282. return self.bind(to: address)
  283. }
  284. }
  285. }