Server.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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 Logging
  18. import NIO
  19. import NIOHTTP1
  20. import NIOHTTP2
  21. import NIOSSL
  22. import NIOTransportServices
  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(
  98. ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR),
  99. value: 1
  100. )
  101. // Set the handlers that are applied to the accepted Channels
  102. .childChannelInitializer { channel in
  103. let protocolSwitcher = HTTPProtocolSwitcher(
  104. errorDelegate: configuration.errorDelegate,
  105. httpTargetWindowSize: configuration.httpTargetWindowSize,
  106. keepAlive: configuration.connectionKeepalive,
  107. idleTimeout: configuration.connectionIdleTimeout,
  108. logger: configuration.logger
  109. ) { (channel, logger) -> EventLoopFuture<Void> in
  110. let handler = GRPCServerRequestRoutingHandler(
  111. servicesByName: configuration.serviceProvidersByName,
  112. encoding: configuration.messageEncoding,
  113. errorDelegate: configuration.errorDelegate,
  114. logger: logger
  115. )
  116. return channel.pipeline.addHandler(handler)
  117. }
  118. var configured: EventLoopFuture<Void>
  119. if let tls = configuration.tls {
  120. configured = channel.configureTLS(configuration: tls).flatMap {
  121. channel.pipeline.addHandler(protocolSwitcher)
  122. }
  123. } else {
  124. configured = channel.pipeline.addHandler(protocolSwitcher)
  125. }
  126. // Work around the zero length write issue, if needed.
  127. let requiresZeroLengthWorkaround = PlatformSupport.requiresZeroLengthWriteWorkaround(
  128. group: configuration.eventLoopGroup,
  129. hasTLS: configuration.tls != nil
  130. )
  131. if requiresZeroLengthWorkaround,
  132. #available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *) {
  133. configured = configured.flatMap {
  134. channel.pipeline.addHandler(NIOFilterEmptyWritesHandler())
  135. }
  136. }
  137. // Add the debug initializer, if there is one.
  138. if let debugAcceptedChannelInitializer = configuration.debugChannelInitializer {
  139. return configured.flatMap {
  140. debugAcceptedChannelInitializer(channel)
  141. }
  142. } else {
  143. return configured
  144. }
  145. }
  146. // Enable TCP_NODELAY and SO_REUSEADDR for the accepted Channels
  147. .childChannelOption(ChannelOptions.socket(IPPROTO_TCP, TCP_NODELAY), value: 1)
  148. .childChannelOption(
  149. ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR),
  150. value: 1
  151. )
  152. }
  153. /// Starts a server with the given configuration. See `Server.Configuration` for the options
  154. /// available to configure the server.
  155. public static func start(configuration: Configuration) -> EventLoopFuture<Server> {
  156. return self.makeBootstrap(configuration: configuration)
  157. .bind(to: configuration.target)
  158. .map { channel in
  159. Server(channel: channel, errorDelegate: configuration.errorDelegate)
  160. }
  161. }
  162. public let channel: Channel
  163. private var errorDelegate: ServerErrorDelegate?
  164. private init(channel: Channel, errorDelegate: ServerErrorDelegate?) {
  165. self.channel = channel
  166. // Maintain a strong reference to ensure it lives as long as the server.
  167. self.errorDelegate = errorDelegate
  168. // If we have an error delegate, add a server channel error handler as well. We don't need to wait for the handler to
  169. // be added.
  170. if let errorDelegate = errorDelegate {
  171. _ = channel.pipeline.addHandler(ServerChannelErrorHandler(errorDelegate: errorDelegate))
  172. }
  173. // nil out errorDelegate to avoid retain cycles.
  174. self.onClose.whenComplete { _ in
  175. self.errorDelegate = nil
  176. }
  177. }
  178. /// Fired when the server shuts down.
  179. public var onClose: EventLoopFuture<Void> {
  180. return self.channel.closeFuture
  181. }
  182. /// Shut down the server; this should be called to avoid leaking resources.
  183. public func close() -> EventLoopFuture<Void> {
  184. return self.channel.close(mode: .all)
  185. }
  186. }
  187. public typealias BindTarget = ConnectionTarget
  188. extension Server {
  189. /// The configuration for a server.
  190. public struct Configuration {
  191. /// The target to bind to.
  192. public var target: BindTarget
  193. /// The event loop group to run the connection on.
  194. public var eventLoopGroup: EventLoopGroup
  195. /// Providers the server should use to handle gRPC requests.
  196. public var serviceProviders: [CallHandlerProvider] {
  197. get {
  198. return Array(self.serviceProvidersByName.values)
  199. }
  200. set {
  201. self
  202. .serviceProvidersByName = Dictionary(
  203. uniqueKeysWithValues: newValue
  204. .map { ($0.serviceName, $0) }
  205. )
  206. }
  207. }
  208. /// An error delegate which is called when errors are caught. Provided delegates **must not
  209. /// maintain a strong reference to this `Server`**. Doing so will cause a retain cycle.
  210. public var errorDelegate: ServerErrorDelegate?
  211. /// TLS configuration for this connection. `nil` if TLS is not desired.
  212. public var tls: TLS?
  213. /// The connection keepalive configuration.
  214. public var connectionKeepalive: ServerConnectionKeepalive
  215. /// The amount of time to wait before closing connections. The idle timeout will start only
  216. /// if there are no RPCs in progress and will be cancelled as soon as any RPCs start.
  217. public var connectionIdleTimeout: TimeAmount
  218. /// The compression configuration for requests and responses.
  219. ///
  220. /// If compression is enabled for the server it may be disabled for responses on any RPC by
  221. /// setting `compressionEnabled` to `false` on the context of the call.
  222. ///
  223. /// Compression may also be disabled at the message-level for streaming responses (i.e. server
  224. /// streaming and bidirectional streaming RPCs) by passing setting `compression` to `.disabled`
  225. /// in `sendResponse(_:compression)`.
  226. public var messageEncoding: ServerMessageEncoding
  227. /// The HTTP/2 flow control target window size.
  228. public var httpTargetWindowSize: Int
  229. /// The root server logger. Accepted connections will branch from this logger and RPCs on
  230. /// each connection will use a logger branched from the connections logger. This logger is made
  231. /// available to service providers via `context`. Defaults to a no-op logger.
  232. public var logger: Logger
  233. /// A channel initializer which will be run after gRPC has initialized each accepted channel.
  234. /// This may be used to add additional handlers to the pipeline and is intended for debugging.
  235. /// This is analogous to `NIO.ServerBootstrap.childChannelInitializer`.
  236. ///
  237. /// - Warning: The initializer closure may be invoked *multiple times*. More precisely: it will
  238. /// be invoked at most once per accepted connection.
  239. public var debugChannelInitializer: ((Channel) -> EventLoopFuture<Void>)?
  240. /// A calculated private cache of the service providers by name.
  241. ///
  242. /// This is how gRPC consumes the service providers internally. Caching this as stored data avoids
  243. /// the need to recalculate this dictionary each time we receive an rpc.
  244. fileprivate private(set) var serviceProvidersByName: [Substring: CallHandlerProvider]
  245. /// Create a `Configuration` with some pre-defined defaults.
  246. ///
  247. /// - Parameters:
  248. /// - target: The target to bind to.
  249. /// - eventLoopGroup: The event loop group to run the server on.
  250. /// - serviceProviders: An array of `CallHandlerProvider`s which the server should use
  251. /// to handle requests.
  252. /// - errorDelegate: The error delegate, defaulting to a logging delegate.
  253. /// - tls: TLS configuration, defaulting to `nil`.
  254. /// - connectionKeepalive: The keepalive configuration to use.
  255. /// - connectionIdleTimeout: The amount of time to wait before closing the connection, defaulting to 5 minutes.
  256. /// - messageEncoding: Message compression configuration, defaulting to no compression.
  257. /// - httpTargetWindowSize: The HTTP/2 flow control target window size.
  258. /// - logger: A logger. Defaults to a no-op logger.
  259. /// - debugChannelInitializer: A channel initializer which will be called for each connection
  260. /// the server accepts after gRPC has initialized the channel. Defaults to `nil`.
  261. public init(
  262. target: BindTarget,
  263. eventLoopGroup: EventLoopGroup,
  264. serviceProviders: [CallHandlerProvider],
  265. errorDelegate: ServerErrorDelegate? = nil,
  266. tls: TLS? = nil,
  267. connectionKeepalive: ServerConnectionKeepalive = ServerConnectionKeepalive(),
  268. connectionIdleTimeout: TimeAmount = .minutes(5),
  269. messageEncoding: ServerMessageEncoding = .disabled,
  270. httpTargetWindowSize: Int = 65535,
  271. logger: Logger = Logger(label: "io.grpc", factory: { _ in SwiftLogNoOpLogHandler() }),
  272. debugChannelInitializer: ((Channel) -> EventLoopFuture<Void>)? = nil
  273. ) {
  274. self.target = target
  275. self.eventLoopGroup = eventLoopGroup
  276. self
  277. .serviceProvidersByName = Dictionary(
  278. uniqueKeysWithValues: serviceProviders
  279. .map { ($0.serviceName, $0) }
  280. )
  281. self.errorDelegate = errorDelegate
  282. self.tls = tls
  283. self.connectionKeepalive = connectionKeepalive
  284. self.connectionIdleTimeout = connectionIdleTimeout
  285. self.messageEncoding = messageEncoding
  286. self.httpTargetWindowSize = httpTargetWindowSize
  287. self.logger = logger
  288. self.debugChannelInitializer = debugChannelInitializer
  289. }
  290. }
  291. }
  292. private extension Channel {
  293. /// Configure an SSL handler on the channel.
  294. ///
  295. /// - Parameters:
  296. /// - configuration: The configuration to use when creating the handler.
  297. /// - Returns: A future which will be succeeded when the pipeline has been configured.
  298. func configureTLS(configuration: Server.Configuration.TLS) -> EventLoopFuture<Void> {
  299. do {
  300. let context = try NIOSSLContext(configuration: configuration.configuration)
  301. return self.pipeline.addHandler(NIOSSLServerHandler(context: context))
  302. } catch {
  303. return self.pipeline.eventLoop.makeFailedFuture(error)
  304. }
  305. }
  306. }
  307. private extension ServerBootstrapProtocol {
  308. func bind(to target: BindTarget) -> EventLoopFuture<Channel> {
  309. switch target.wrapped {
  310. case let .hostAndPort(host, port):
  311. return self.bind(host: host, port: port)
  312. case let .unixDomainSocket(path):
  313. return self.bind(unixDomainSocketPath: path)
  314. case let .socketAddress(address):
  315. return self.bind(to: address)
  316. }
  317. }
  318. }