Server.swift 17 KB

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