Server.swift 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  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 NIOCore
  19. import NIOExtras
  20. import NIOHTTP1
  21. import NIOHTTP2
  22. import NIOPosix
  23. #if canImport(NIOSSL)
  24. import NIOSSL
  25. #endif
  26. import NIOTransportServices
  27. #if canImport(Network)
  28. import Network
  29. #endif
  30. /// Wrapper object to manage the lifecycle of a gRPC server.
  31. ///
  32. /// The pipeline is configured in three stages detailed below. Note: handlers marked with
  33. /// a '*' are responsible for handling errors.
  34. ///
  35. /// 1. Initial stage, prior to pipeline configuration.
  36. ///
  37. /// ┌─────────────────────────────────┐
  38. /// │ GRPCServerPipelineConfigurator* │
  39. /// └────▲───────────────────────┬────┘
  40. /// ByteBuffer│ │ByteBuffer
  41. /// ┌─┴───────────────────────▼─┐
  42. /// │ NIOSSLHandler │
  43. /// └─▲───────────────────────┬─┘
  44. /// ByteBuffer│ │ByteBuffer
  45. /// │ ▼
  46. ///
  47. /// The `NIOSSLHandler` is optional and depends on how the framework user has configured
  48. /// their server. The `GRPCServerPipelineConfigurator` detects which HTTP version is being used
  49. /// (via ALPN if TLS is used or by parsing the first bytes on the connection otherwise) and
  50. /// configures the pipeline accordingly.
  51. ///
  52. /// 2. HTTP version detected. "HTTP Handlers" depends on the HTTP version determined by
  53. /// `GRPCServerPipelineConfigurator`. In the case of HTTP/2:
  54. ///
  55. /// ┌─────────────────────────────────┐
  56. /// │ HTTP2StreamMultiplexer │
  57. /// └─▲─────────────────────────────┬─┘
  58. /// HTTP2Frame│ │HTTP2Frame
  59. /// ┌─┴─────────────────────────────▼─┐
  60. /// │ HTTP2Handler │
  61. /// └─▲─────────────────────────────┬─┘
  62. /// ByteBuffer│ │ByteBuffer
  63. /// ┌─┴─────────────────────────────▼─┐
  64. /// │ NIOSSLHandler │
  65. /// └─▲─────────────────────────────┬─┘
  66. /// ByteBuffer│ │ByteBuffer
  67. /// │ ▼
  68. ///
  69. /// The `HTTP2StreamMultiplexer` provides one `Channel` for each HTTP/2 stream (and thus each
  70. /// RPC).
  71. ///
  72. /// 3. The frames for each stream channel are routed by the `HTTP2ToRawGRPCServerCodec` handler to
  73. /// a handler containing the user-implemented logic provided by a `CallHandlerProvider`:
  74. ///
  75. /// ┌─────────────────────────────────┐
  76. /// │ BaseCallHandler* │
  77. /// └─▲─────────────────────────────┬─┘
  78. /// GRPCServerRequestPart│ │GRPCServerResponsePart
  79. /// ┌─┴─────────────────────────────▼─┐
  80. /// │ HTTP2ToRawGRPCServerCodec │
  81. /// └─▲─────────────────────────────┬─┘
  82. /// HTTP2Frame.FramePayload│ │HTTP2Frame.FramePayload
  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. #if canImport(NIOSSL)
  95. // Making a `NIOSSLContext` is expensive, we should only do it once per TLS configuration so
  96. // we'll do it now, before accepting connections. Unfortunately our API isn't throwing so we'll
  97. // only surface any error when initializing a child channel.
  98. //
  99. // 'nil' means we're not using TLS, or we're using the Network.framework TLS backend. If we're
  100. // using the Network.framework TLS backend we'll apply the settings just below.
  101. let sslContext: Result<NIOSSLContext, Error>?
  102. if let tlsConfiguration = configuration.tlsConfiguration {
  103. do {
  104. sslContext = try tlsConfiguration.makeNIOSSLContext().map { .success($0) }
  105. } catch {
  106. sslContext = .failure(error)
  107. }
  108. } else {
  109. // No TLS configuration, no SSL context.
  110. sslContext = nil
  111. }
  112. #endif // canImport(NIOSSL)
  113. #if canImport(Network)
  114. if let tlsConfiguration = configuration.tlsConfiguration {
  115. if #available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *),
  116. let transportServicesBootstrap = bootstrap as? NIOTSListenerBootstrap {
  117. _ = transportServicesBootstrap.tlsOptions(from: tlsConfiguration)
  118. }
  119. }
  120. #endif // canImport(Network)
  121. return bootstrap
  122. // Enable `SO_REUSEADDR` to avoid "address already in use" error.
  123. .serverChannelOption(
  124. ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR),
  125. value: 1
  126. )
  127. // Set the handlers that are applied to the accepted Channels
  128. .childChannelInitializer { channel in
  129. var configuration = configuration
  130. configuration.logger[metadataKey: MetadataKey.connectionID] = "\(UUID().uuidString)"
  131. configuration.logger.addIPAddressMetadata(
  132. local: channel.localAddress,
  133. remote: channel.remoteAddress
  134. )
  135. do {
  136. let sync = channel.pipeline.syncOperations
  137. #if canImport(NIOSSL)
  138. if let sslContext = try sslContext?.get() {
  139. try sync.addHandler(NIOSSLServerHandler(context: sslContext))
  140. }
  141. #endif // canImport(NIOSSL)
  142. // Configures the pipeline based on whether the connection uses TLS or not.
  143. try sync.addHandler(GRPCServerPipelineConfigurator(configuration: configuration))
  144. // Work around the zero length write issue, if needed.
  145. let requiresZeroLengthWorkaround = PlatformSupport.requiresZeroLengthWriteWorkaround(
  146. group: configuration.eventLoopGroup,
  147. hasTLS: configuration.tlsConfiguration != nil
  148. )
  149. if requiresZeroLengthWorkaround,
  150. #available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *) {
  151. try sync.addHandler(NIOFilterEmptyWritesHandler())
  152. }
  153. } catch {
  154. return channel.eventLoop.makeFailedFuture(error)
  155. }
  156. // Run the debug initializer, if there is one.
  157. if let debugAcceptedChannelInitializer = configuration.debugChannelInitializer {
  158. return debugAcceptedChannelInitializer(channel)
  159. } else {
  160. return channel.eventLoop.makeSucceededVoidFuture()
  161. }
  162. }
  163. // Enable TCP_NODELAY and SO_REUSEADDR for the accepted Channels
  164. .childChannelOption(ChannelOptions.socket(IPPROTO_TCP, TCP_NODELAY), value: 1)
  165. .childChannelOption(
  166. ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR),
  167. value: 1
  168. )
  169. }
  170. /// Starts a server with the given configuration. See `Server.Configuration` for the options
  171. /// available to configure the server.
  172. public static func start(configuration: Configuration) -> EventLoopFuture<Server> {
  173. let quiescingHelper = ServerQuiescingHelper(group: configuration.eventLoopGroup)
  174. return self.makeBootstrap(configuration: configuration)
  175. .serverChannelInitializer { channel in
  176. channel.pipeline.addHandler(quiescingHelper.makeServerChannelHandler(channel: channel))
  177. }
  178. .bind(to: configuration.target)
  179. .map { channel in
  180. Server(
  181. channel: channel,
  182. quiescingHelper: quiescingHelper,
  183. errorDelegate: configuration.errorDelegate
  184. )
  185. }
  186. }
  187. public let channel: Channel
  188. private let quiescingHelper: ServerQuiescingHelper
  189. private var errorDelegate: ServerErrorDelegate?
  190. private init(
  191. channel: Channel,
  192. quiescingHelper: ServerQuiescingHelper,
  193. errorDelegate: ServerErrorDelegate?
  194. ) {
  195. self.channel = channel
  196. self.quiescingHelper = quiescingHelper
  197. // Maintain a strong reference to ensure it lives as long as the server.
  198. self.errorDelegate = errorDelegate
  199. // If we have an error delegate, add a server channel error handler as well. We don't need to wait for the handler to
  200. // be added.
  201. if let errorDelegate = errorDelegate {
  202. _ = channel.pipeline.addHandler(ServerChannelErrorHandler(errorDelegate: errorDelegate))
  203. }
  204. // nil out errorDelegate to avoid retain cycles.
  205. self.onClose.whenComplete { _ in
  206. self.errorDelegate = nil
  207. }
  208. }
  209. /// Fired when the server shuts down.
  210. public var onClose: EventLoopFuture<Void> {
  211. return self.channel.closeFuture
  212. }
  213. /// Initiates a graceful shutdown. Existing RPCs may run to completion, any new RPCs or
  214. /// connections will be rejected.
  215. public func initiateGracefulShutdown(promise: EventLoopPromise<Void>?) {
  216. self.quiescingHelper.initiateShutdown(promise: promise)
  217. }
  218. /// Initiates a graceful shutdown. Existing RPCs may run to completion, any new RPCs or
  219. /// connections will be rejected.
  220. public func initiateGracefulShutdown() -> EventLoopFuture<Void> {
  221. let promise = self.channel.eventLoop.makePromise(of: Void.self)
  222. self.initiateGracefulShutdown(promise: promise)
  223. return promise.futureResult
  224. }
  225. /// Shutdown the server immediately. Active RPCs and connections will be terminated.
  226. public func close(promise: EventLoopPromise<Void>?) {
  227. self.channel.close(mode: .all, promise: promise)
  228. }
  229. /// Shutdown the server immediately. Active RPCs and connections will be terminated.
  230. public func close() -> EventLoopFuture<Void> {
  231. return self.channel.close(mode: .all)
  232. }
  233. }
  234. public typealias BindTarget = ConnectionTarget
  235. extension Server {
  236. /// The configuration for a server.
  237. public struct Configuration {
  238. /// The target to bind to.
  239. public var target: BindTarget
  240. /// The event loop group to run the connection on.
  241. public var eventLoopGroup: EventLoopGroup
  242. /// Providers the server should use to handle gRPC requests.
  243. public var serviceProviders: [CallHandlerProvider] {
  244. get {
  245. return Array(self.serviceProvidersByName.values)
  246. }
  247. set {
  248. self
  249. .serviceProvidersByName = Dictionary(
  250. uniqueKeysWithValues: newValue
  251. .map { ($0.serviceName, $0) }
  252. )
  253. }
  254. }
  255. /// An error delegate which is called when errors are caught. Provided delegates **must not
  256. /// maintain a strong reference to this `Server`**. Doing so will cause a retain cycle.
  257. public var errorDelegate: ServerErrorDelegate?
  258. #if canImport(NIOSSL)
  259. /// TLS configuration for this connection. `nil` if TLS is not desired.
  260. @available(*, deprecated, renamed: "tlsConfiguration")
  261. public var tls: TLS? {
  262. get {
  263. return self.tlsConfiguration?.asDeprecatedServerConfiguration
  264. }
  265. set {
  266. self.tlsConfiguration = newValue.map { GRPCTLSConfiguration(transforming: $0) }
  267. }
  268. }
  269. #endif // canImport(NIOSSL)
  270. public var tlsConfiguration: GRPCTLSConfiguration?
  271. /// The connection keepalive configuration.
  272. public var connectionKeepalive = ServerConnectionKeepalive()
  273. /// The amount of time to wait before closing connections. The idle timeout will start only
  274. /// if there are no RPCs in progress and will be cancelled as soon as any RPCs start.
  275. public var connectionIdleTimeout: TimeAmount = .nanoseconds(.max)
  276. /// The compression configuration for requests and responses.
  277. ///
  278. /// If compression is enabled for the server it may be disabled for responses on any RPC by
  279. /// setting `compressionEnabled` to `false` on the context of the call.
  280. ///
  281. /// Compression may also be disabled at the message-level for streaming responses (i.e. server
  282. /// streaming and bidirectional streaming RPCs) by passing setting `compression` to `.disabled`
  283. /// in `sendResponse(_:compression)`.
  284. ///
  285. /// Defaults to ``ServerMessageEncoding/disabled``.
  286. public var messageEncoding: ServerMessageEncoding = .disabled
  287. /// The maximum size in bytes of a message which may be received from a client. Defaults to 4MB.
  288. public var maximumReceiveMessageLength: Int = 4 * 1024 * 1024 {
  289. willSet {
  290. precondition(newValue >= 0, "maximumReceiveMessageLength must be positive")
  291. }
  292. }
  293. /// The HTTP/2 flow control target window size. Defaults to 8MB. Values are clamped between
  294. /// 1 and 2^31-1 inclusive.
  295. public var httpTargetWindowSize = 8 * 1024 * 1024 {
  296. didSet {
  297. self.httpTargetWindowSize = self.httpTargetWindowSize.clamped(to: 1 ... Int(Int32.max))
  298. }
  299. }
  300. /// The HTTP/2 max number of concurrent streams. Defaults to 100. Must be non-negative.
  301. public var httpMaxConcurrentStreams: Int = 100 {
  302. willSet {
  303. precondition(newValue >= 0, "httpMaxConcurrentStreams must be non-negative")
  304. }
  305. }
  306. /// The HTTP/2 max frame size. Defaults to 16384. Value is clamped between 2^14 and 2^24-1
  307. /// octets inclusive (the minimum and maximum allowable values - HTTP/2 RFC 7540 4.2).
  308. public var httpMaxFrameSize: Int = 16384 {
  309. didSet {
  310. self.httpMaxFrameSize = self.httpMaxFrameSize.clamped(to: 16384 ... 16_777_215)
  311. }
  312. }
  313. /// The root server logger. Accepted connections will branch from this logger and RPCs on
  314. /// each connection will use a logger branched from the connections logger. This logger is made
  315. /// available to service providers via `context`. Defaults to a no-op logger.
  316. public var logger = Logger(label: "io.grpc", factory: { _ in SwiftLogNoOpLogHandler() })
  317. /// A channel initializer which will be run after gRPC has initialized each accepted channel.
  318. /// This may be used to add additional handlers to the pipeline and is intended for debugging.
  319. /// This is analogous to `NIO.ServerBootstrap.childChannelInitializer`.
  320. ///
  321. /// - Warning: The initializer closure may be invoked *multiple times*. More precisely: it will
  322. /// be invoked at most once per accepted connection.
  323. public var debugChannelInitializer: ((Channel) -> EventLoopFuture<Void>)?
  324. /// A calculated private cache of the service providers by name.
  325. ///
  326. /// This is how gRPC consumes the service providers internally. Caching this as stored data avoids
  327. /// the need to recalculate this dictionary each time we receive an rpc.
  328. internal var serviceProvidersByName: [Substring: CallHandlerProvider]
  329. /// CORS configuration for gRPC-Web support.
  330. public var webCORS = Configuration.CORS()
  331. #if canImport(NIOSSL)
  332. /// Create a `Configuration` with some pre-defined defaults.
  333. ///
  334. /// - Parameters:
  335. /// - target: The target to bind to.
  336. /// - eventLoopGroup: The event loop group to run the server on.
  337. /// - serviceProviders: An array of `CallHandlerProvider`s which the server should use
  338. /// to handle requests.
  339. /// - errorDelegate: The error delegate, defaulting to a logging delegate.
  340. /// - tls: TLS configuration, defaulting to `nil`.
  341. /// - connectionKeepalive: The keepalive configuration to use.
  342. /// - connectionIdleTimeout: The amount of time to wait before closing the connection, this is
  343. /// indefinite by default.
  344. /// - messageEncoding: Message compression configuration, defaulting to no compression.
  345. /// - httpTargetWindowSize: The HTTP/2 flow control target window size.
  346. /// - logger: A logger. Defaults to a no-op logger.
  347. /// - debugChannelInitializer: A channel initializer which will be called for each connection
  348. /// the server accepts after gRPC has initialized the channel. Defaults to `nil`.
  349. @available(*, deprecated, renamed: "default(target:eventLoopGroup:serviceProviders:)")
  350. public init(
  351. target: BindTarget,
  352. eventLoopGroup: EventLoopGroup,
  353. serviceProviders: [CallHandlerProvider],
  354. errorDelegate: ServerErrorDelegate? = nil,
  355. tls: TLS? = nil,
  356. connectionKeepalive: ServerConnectionKeepalive = ServerConnectionKeepalive(),
  357. connectionIdleTimeout: TimeAmount = .nanoseconds(.max),
  358. messageEncoding: ServerMessageEncoding = .disabled,
  359. httpTargetWindowSize: Int = 8 * 1024 * 1024,
  360. logger: Logger = Logger(label: "io.grpc", factory: { _ in SwiftLogNoOpLogHandler() }),
  361. debugChannelInitializer: ((Channel) -> EventLoopFuture<Void>)? = nil
  362. ) {
  363. self.target = target
  364. self.eventLoopGroup = eventLoopGroup
  365. self.serviceProvidersByName = Dictionary(
  366. uniqueKeysWithValues: serviceProviders.map { ($0.serviceName, $0) }
  367. )
  368. self.errorDelegate = errorDelegate
  369. self.tlsConfiguration = tls.map { GRPCTLSConfiguration(transforming: $0) }
  370. self.connectionKeepalive = connectionKeepalive
  371. self.connectionIdleTimeout = connectionIdleTimeout
  372. self.messageEncoding = messageEncoding
  373. self.httpTargetWindowSize = httpTargetWindowSize
  374. self.logger = logger
  375. self.debugChannelInitializer = debugChannelInitializer
  376. }
  377. #endif // canImport(NIOSSL)
  378. private init(
  379. eventLoopGroup: EventLoopGroup,
  380. target: BindTarget,
  381. serviceProviders: [CallHandlerProvider]
  382. ) {
  383. self.eventLoopGroup = eventLoopGroup
  384. self.target = target
  385. self.serviceProvidersByName = Dictionary(uniqueKeysWithValues: serviceProviders.map {
  386. ($0.serviceName, $0)
  387. })
  388. }
  389. /// Make a new configuration using default values.
  390. ///
  391. /// - Parameters:
  392. /// - target: The target to bind to.
  393. /// - eventLoopGroup: The `EventLoopGroup` the server should run on.
  394. /// - serviceProviders: An array of `CallHandlerProvider`s which the server should use
  395. /// to handle requests.
  396. /// - Returns: A configuration with default values set.
  397. public static func `default`(
  398. target: BindTarget,
  399. eventLoopGroup: EventLoopGroup,
  400. serviceProviders: [CallHandlerProvider]
  401. ) -> Configuration {
  402. return .init(
  403. eventLoopGroup: eventLoopGroup,
  404. target: target,
  405. serviceProviders: serviceProviders
  406. )
  407. }
  408. }
  409. }
  410. extension Server.Configuration {
  411. public struct CORS: Hashable, GRPCSendable {
  412. /// Determines which 'origin' header field values are permitted in a CORS request.
  413. public var allowedOrigins: AllowedOrigins
  414. /// Sets the headers which are permitted in a response to a CORS request.
  415. public var allowedHeaders: [String]
  416. /// Enabling this value allows sets the "access-control-allow-credentials" header field
  417. /// to "true" in respones to CORS requests. This must be enabled if the client intends to send
  418. /// credentials.
  419. public var allowCredentialedRequests: Bool
  420. /// The maximum age in seconds which pre-flight CORS requests may be cached for.
  421. public var preflightCacheExpiration: Int
  422. public init(
  423. allowedOrigins: AllowedOrigins = .all,
  424. allowedHeaders: [String] = ["content-type", "x-grpc-web", "x-user-agent"],
  425. allowCredentialedRequests: Bool = false,
  426. preflightCacheExpiration: Int = 86400
  427. ) {
  428. self.allowedOrigins = allowedOrigins
  429. self.allowedHeaders = allowedHeaders
  430. self.allowCredentialedRequests = allowCredentialedRequests
  431. self.preflightCacheExpiration = preflightCacheExpiration
  432. }
  433. }
  434. }
  435. extension Server.Configuration.CORS {
  436. public struct AllowedOrigins: Hashable, Sendable {
  437. enum Wrapped: Hashable, Sendable {
  438. case all
  439. case only([String])
  440. }
  441. private(set) var wrapped: Wrapped
  442. private init(_ wrapped: Wrapped) {
  443. self.wrapped = wrapped
  444. }
  445. /// Allow all origin values.
  446. public static let all = Self(.all)
  447. /// Allow only the given origin values.
  448. public static func only(_ allowed: [String]) -> Self {
  449. return Self(.only(allowed))
  450. }
  451. }
  452. }
  453. extension ServerBootstrapProtocol {
  454. fileprivate func bind(to target: BindTarget) -> EventLoopFuture<Channel> {
  455. switch target.wrapped {
  456. case let .hostAndPort(host, port):
  457. return self.bind(host: host, port: port)
  458. case let .unixDomainSocket(path):
  459. return self.bind(unixDomainSocketPath: path)
  460. case let .socketAddress(address):
  461. return self.bind(to: address)
  462. case let .connectedSocket(socket):
  463. return self.withBoundSocket(socket)
  464. }
  465. }
  466. }
  467. extension Comparable {
  468. internal func clamped(to range: ClosedRange<Self>) -> Self {
  469. return min(max(self, range.lowerBound), range.upperBound)
  470. }
  471. }