Server.swift 16 KB

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