Server.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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 pipeline configuration.
  29. ///
  30. /// ┌─────────────────────────────────┐
  31. /// │ GRPCServerPipelineConfigurator* │
  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 `GRPCServerPipelineConfigurator` detects which HTTP version is being used
  42. /// (via ALPN if TLS is used or by parsing the first bytes on the connection otherwise) and
  43. /// configures the pipeline accordingly.
  44. ///
  45. /// 2. HTTP version detected. "HTTP Handlers" depends on the HTTP version determined by
  46. /// `GRPCServerPipelineConfigurator`. In the case of HTTP/2:
  47. ///
  48. /// ┌─────────────────────────────────┐
  49. /// │ HTTP2StreamMultiplexer │
  50. /// └─▲─────────────────────────────┬─┘
  51. /// HTTP2Frame│ │HTTP2Frame
  52. /// ┌─┴─────────────────────────────▼─┐
  53. /// │ HTTP2Handler │
  54. /// └─▲─────────────────────────────┬─┘
  55. /// ByteBuffer│ │ByteBuffer
  56. /// ┌─┴─────────────────────────────▼─┐
  57. /// │ NIOSSLHandler │
  58. /// └─▲─────────────────────────────┬─┘
  59. /// ByteBuffer│ │ByteBuffer
  60. /// │ ▼
  61. ///
  62. /// The `HTTP2StreamMultiplexer` provides one `Channel` for each HTTP/2 stream (and thus each
  63. /// RPC).
  64. ///
  65. /// 3. The frames for each stream channel are routed by the `HTTP2ToRawGRPCServerCodec` handler to
  66. /// a handler containing the user-implemented logic provided by a `CallHandlerProvider`:
  67. ///
  68. /// ┌─────────────────────────────────┐
  69. /// │ BaseCallHandler* │
  70. /// └─▲─────────────────────────────┬─┘
  71. /// GRPCServerRequestPart│ │GRPCServerResponsePart
  72. /// ┌─┴─────────────────────────────▼─┐
  73. /// │ HTTP2ToRawGRPCServerCodec │
  74. /// └─▲─────────────────────────────┬─┘
  75. /// HTTP2Frame.FramePayload│ │HTTP2Frame.FramePayload
  76. /// │ ▼
  77. ///
  78. public final class Server {
  79. /// Makes and configures a `ServerBootstrap` using the provided configuration.
  80. public class func makeBootstrap(configuration: Configuration) -> ServerBootstrapProtocol {
  81. let bootstrap = PlatformSupport.makeServerBootstrap(group: configuration.eventLoopGroup)
  82. // Backlog is only available on `ServerBootstrap`.
  83. if bootstrap is ServerBootstrap {
  84. // Specify a backlog to avoid overloading the server.
  85. _ = bootstrap.serverChannelOption(ChannelOptions.backlog, value: 256)
  86. }
  87. return bootstrap
  88. // Enable `SO_REUSEADDR` to avoid "address already in use" error.
  89. .serverChannelOption(
  90. ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR),
  91. value: 1
  92. )
  93. // Set the handlers that are applied to the accepted Channels
  94. .childChannelInitializer { channel in
  95. var configuration = configuration
  96. configuration.logger[metadataKey: MetadataKey.connectionID] = "\(UUID().uuidString)"
  97. configuration.logger[metadataKey: MetadataKey.remoteAddress] = channel.remoteAddress
  98. .map { "\($0)" } ?? "n/a"
  99. var configured: EventLoopFuture<Void>
  100. let configurator = GRPCServerPipelineConfigurator(configuration: configuration)
  101. if let tls = configuration.tls {
  102. configured = channel.configureTLS(configuration: tls).flatMap {
  103. channel.pipeline.addHandler(configurator)
  104. }
  105. } else {
  106. configured = channel.pipeline.addHandler(configurator)
  107. }
  108. // Work around the zero length write issue, if needed.
  109. let requiresZeroLengthWorkaround = PlatformSupport.requiresZeroLengthWriteWorkaround(
  110. group: configuration.eventLoopGroup,
  111. hasTLS: configuration.tls != nil
  112. )
  113. if requiresZeroLengthWorkaround,
  114. #available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *) {
  115. configured = configured.flatMap {
  116. channel.pipeline.addHandler(NIOFilterEmptyWritesHandler())
  117. }
  118. }
  119. // Add the debug initializer, if there is one.
  120. if let debugAcceptedChannelInitializer = configuration.debugChannelInitializer {
  121. return configured.flatMap {
  122. debugAcceptedChannelInitializer(channel)
  123. }
  124. } else {
  125. return configured
  126. }
  127. }
  128. // Enable TCP_NODELAY and SO_REUSEADDR for the accepted Channels
  129. .childChannelOption(ChannelOptions.socket(IPPROTO_TCP, TCP_NODELAY), value: 1)
  130. .childChannelOption(
  131. ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR),
  132. value: 1
  133. )
  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 self.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. self.onClose.whenComplete { _ in
  157. self.errorDelegate = nil
  158. }
  159. }
  160. /// Fired when the server shuts down.
  161. public var onClose: EventLoopFuture<Void> {
  162. return self.channel.closeFuture
  163. }
  164. /// Shut down the server; this should be called to avoid leaking resources.
  165. public func close() -> EventLoopFuture<Void> {
  166. return self.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. get {
  180. return Array(self.serviceProvidersByName.values)
  181. }
  182. set {
  183. self
  184. .serviceProvidersByName = Dictionary(
  185. uniqueKeysWithValues: newValue
  186. .map { ($0.serviceName, $0) }
  187. )
  188. }
  189. }
  190. /// An error delegate which is called when errors are caught. Provided delegates **must not
  191. /// maintain a strong reference to this `Server`**. Doing so will cause a retain cycle.
  192. public var errorDelegate: ServerErrorDelegate?
  193. /// TLS configuration for this connection. `nil` if TLS is not desired.
  194. public var tls: TLS?
  195. /// The connection keepalive configuration.
  196. public var connectionKeepalive: ServerConnectionKeepalive
  197. /// The amount of time to wait before closing connections. The idle timeout will start only
  198. /// if there are no RPCs in progress and will be cancelled as soon as any RPCs start.
  199. public var connectionIdleTimeout: TimeAmount
  200. /// The compression configuration for requests and responses.
  201. ///
  202. /// If compression is enabled for the server it may be disabled for responses on any RPC by
  203. /// setting `compressionEnabled` to `false` on the context of the call.
  204. ///
  205. /// Compression may also be disabled at the message-level for streaming responses (i.e. server
  206. /// streaming and bidirectional streaming RPCs) by passing setting `compression` to `.disabled`
  207. /// in `sendResponse(_:compression)`.
  208. public var messageEncoding: ServerMessageEncoding
  209. /// The HTTP/2 flow control target window size.
  210. public var httpTargetWindowSize: Int
  211. /// The root server logger. Accepted connections will branch from this logger and RPCs on
  212. /// each connection will use a logger branched from the connections logger. This logger is made
  213. /// available to service providers via `context`. Defaults to a no-op logger.
  214. public var logger: Logger
  215. /// A channel initializer which will be run after gRPC has initialized each accepted channel.
  216. /// This may be used to add additional handlers to the pipeline and is intended for debugging.
  217. /// This is analogous to `NIO.ServerBootstrap.childChannelInitializer`.
  218. ///
  219. /// - Warning: The initializer closure may be invoked *multiple times*. More precisely: it will
  220. /// be invoked at most once per accepted connection.
  221. public var debugChannelInitializer: ((Channel) -> EventLoopFuture<Void>)?
  222. /// A calculated private cache of the service providers by name.
  223. ///
  224. /// This is how gRPC consumes the service providers internally. Caching this as stored data avoids
  225. /// the need to recalculate this dictionary each time we receive an rpc.
  226. internal var serviceProvidersByName: [Substring: CallHandlerProvider]
  227. /// Create a `Configuration` with some pre-defined defaults.
  228. ///
  229. /// - Parameters:
  230. /// - target: The target to bind to.
  231. /// - eventLoopGroup: The event loop group to run the server on.
  232. /// - serviceProviders: An array of `CallHandlerProvider`s which the server should use
  233. /// to handle requests.
  234. /// - errorDelegate: The error delegate, defaulting to a logging delegate.
  235. /// - tls: TLS configuration, defaulting to `nil`.
  236. /// - connectionKeepalive: The keepalive configuration to use.
  237. /// - connectionIdleTimeout: The amount of time to wait before closing the connection, this is
  238. /// indefinite by default.
  239. /// - messageEncoding: Message compression configuration, defaulting to no compression.
  240. /// - httpTargetWindowSize: The HTTP/2 flow control target window size.
  241. /// - logger: A logger. Defaults to a no-op logger.
  242. /// - debugChannelInitializer: A channel initializer which will be called for each connection
  243. /// the server accepts after gRPC has initialized the channel. Defaults to `nil`.
  244. public init(
  245. target: BindTarget,
  246. eventLoopGroup: EventLoopGroup,
  247. serviceProviders: [CallHandlerProvider],
  248. errorDelegate: ServerErrorDelegate? = nil,
  249. tls: TLS? = nil,
  250. connectionKeepalive: ServerConnectionKeepalive = ServerConnectionKeepalive(),
  251. connectionIdleTimeout: TimeAmount = .nanoseconds(.max),
  252. messageEncoding: ServerMessageEncoding = .disabled,
  253. httpTargetWindowSize: Int = 65535,
  254. logger: Logger = Logger(label: "io.grpc", factory: { _ in SwiftLogNoOpLogHandler() }),
  255. debugChannelInitializer: ((Channel) -> EventLoopFuture<Void>)? = nil
  256. ) {
  257. self.target = target
  258. self.eventLoopGroup = eventLoopGroup
  259. self
  260. .serviceProvidersByName = Dictionary(
  261. uniqueKeysWithValues: serviceProviders
  262. .map { ($0.serviceName, $0) }
  263. )
  264. self.errorDelegate = errorDelegate
  265. self.tls = tls
  266. self.connectionKeepalive = connectionKeepalive
  267. self.connectionIdleTimeout = connectionIdleTimeout
  268. self.messageEncoding = messageEncoding
  269. self.httpTargetWindowSize = httpTargetWindowSize
  270. self.logger = logger
  271. self.debugChannelInitializer = debugChannelInitializer
  272. }
  273. }
  274. }
  275. private extension Channel {
  276. /// Configure an SSL handler on the channel.
  277. ///
  278. /// - Parameters:
  279. /// - configuration: The configuration to use when creating the handler.
  280. /// - Returns: A future which will be succeeded when the pipeline has been configured.
  281. func configureTLS(configuration: Server.Configuration.TLS) -> EventLoopFuture<Void> {
  282. do {
  283. let context = try NIOSSLContext(configuration: configuration.configuration)
  284. return self.pipeline.addHandler(NIOSSLServerHandler(context: context))
  285. } catch {
  286. return self.pipeline.eventLoop.makeFailedFuture(error)
  287. }
  288. }
  289. }
  290. private extension ServerBootstrapProtocol {
  291. func bind(to target: BindTarget) -> EventLoopFuture<Channel> {
  292. switch target.wrapped {
  293. case let .hostAndPort(host, port):
  294. return self.bind(host: host, port: port)
  295. case let .unixDomainSocket(path):
  296. return self.bind(unixDomainSocketPath: path)
  297. case let .socketAddress(address):
  298. return self.bind(to: address)
  299. }
  300. }
  301. }