ServerBuilder.swift 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. /*
  2. * Copyright 2020, 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 Logging
  17. import NIOCore
  18. #if canImport(Network)
  19. import Security
  20. #endif
  21. extension Server {
  22. public class Builder {
  23. private var configuration: Server.Configuration
  24. private var maybeTLS: GRPCTLSConfiguration? { return nil }
  25. fileprivate init(group: EventLoopGroup) {
  26. self.configuration = .default(
  27. // This is okay: the configuration is only consumed on a call to `bind` which sets the host
  28. // and port.
  29. target: .hostAndPort("", .max),
  30. eventLoopGroup: group,
  31. serviceProviders: []
  32. )
  33. }
  34. public class Secure: Builder {
  35. internal var tls: GRPCTLSConfiguration
  36. override var maybeTLS: GRPCTLSConfiguration? {
  37. return self.tls
  38. }
  39. internal init(group: EventLoopGroup, tlsConfiguration: GRPCTLSConfiguration) {
  40. group.preconditionCompatible(with: tlsConfiguration)
  41. self.tls = tlsConfiguration
  42. super.init(group: group)
  43. }
  44. }
  45. public func bind(host: String, port: Int) -> EventLoopFuture<Server> {
  46. // Finish setting up the configuration.
  47. self.configuration.target = .hostAndPort(host, port)
  48. self.configuration.tlsConfiguration = self.maybeTLS
  49. return Server.start(configuration: self.configuration)
  50. }
  51. public func bind(unixDomainSocketPath path: String) -> EventLoopFuture<Server> {
  52. self.configuration.target = .unixDomainSocket(path)
  53. self.configuration.tlsConfiguration = self.maybeTLS
  54. return Server.start(configuration: self.configuration)
  55. }
  56. }
  57. }
  58. extension Server.Builder {
  59. /// Sets the server error delegate.
  60. @discardableResult
  61. public func withErrorDelegate(_ delegate: ServerErrorDelegate?) -> Self {
  62. self.configuration.errorDelegate = delegate
  63. return self
  64. }
  65. }
  66. extension Server.Builder {
  67. /// Sets the service providers that this server should offer. Note that calling this multiple
  68. /// times will override any previously set providers.
  69. @discardableResult
  70. public func withServiceProviders(_ providers: [CallHandlerProvider]) -> Self {
  71. self.configuration.serviceProviders = providers
  72. return self
  73. }
  74. }
  75. extension Server.Builder {
  76. @discardableResult
  77. public func withKeepalive(_ keepalive: ServerConnectionKeepalive) -> Self {
  78. self.configuration.connectionKeepalive = keepalive
  79. return self
  80. }
  81. }
  82. extension Server.Builder {
  83. /// The amount of time to wait before closing connections. The idle timeout will start only
  84. /// if there are no RPCs in progress and will be cancelled as soon as any RPCs start. Unless a
  85. /// an idle timeout it set connections will not be idled by default.
  86. @discardableResult
  87. public func withConnectionIdleTimeout(_ timeout: TimeAmount) -> Self {
  88. self.configuration.connectionIdleTimeout = timeout
  89. return self
  90. }
  91. }
  92. extension Server.Builder {
  93. /// Sets the message compression configuration. Compression is disabled if this is not configured
  94. /// and any RPCs using compression will not be accepted.
  95. @discardableResult
  96. public func withMessageCompression(_ encoding: ServerMessageEncoding) -> Self {
  97. self.configuration.messageEncoding = encoding
  98. return self
  99. }
  100. /// Sets the maximum message size in bytes the server may receive.
  101. ///
  102. /// - Precondition: `limit` must not be negative.
  103. @discardableResult
  104. public func withMaximumReceiveMessageLength(_ limit: Int) -> Self {
  105. self.configuration.maximumReceiveMessageLength = limit
  106. return self
  107. }
  108. }
  109. extension Server.Builder.Secure {
  110. /// Sets whether the server's TLS handshake requires a protocol to be negotiated via ALPN. This
  111. /// defaults to `true` if not otherwise set.
  112. ///
  113. /// If this option is set to `false` and no protocol is negotiated via ALPN then the server will
  114. /// parse the initial bytes on the connection to determine whether HTTP/2 or HTTP/1.1 (gRPC-Web)
  115. /// is being used and configure the connection appropriately.
  116. ///
  117. /// - Note: May only be used with the 'NIOSSL' TLS backend.
  118. @discardableResult
  119. public func withTLS(requiringALPN: Bool) -> Self {
  120. self.tls.requireALPN = requiringALPN
  121. return self
  122. }
  123. }
  124. extension Server.Builder {
  125. /// Sets the HTTP/2 flow control target window size. Defaults to 8MB if not explicitly set.
  126. /// Values are clamped between 1 and 2^31-1 inclusive.
  127. @discardableResult
  128. public func withHTTPTargetWindowSize(_ httpTargetWindowSize: Int) -> Self {
  129. self.configuration.httpTargetWindowSize = httpTargetWindowSize
  130. return self
  131. }
  132. /// Sets the maximum allowed number of concurrent HTTP/2 streams a client may open for a given
  133. /// connection. Defaults to 100.
  134. @discardableResult
  135. public func withHTTPMaxConcurrentStreams(_ httpMaxConcurrentStreams: Int) -> Self {
  136. self.configuration.httpMaxConcurrentStreams = httpMaxConcurrentStreams
  137. return self
  138. }
  139. /// Sets the HTTP/2 max frame size. Defaults to 16384. Value are clamped between 2^14 and 2^24-1
  140. /// octets inclusive (the minimum and maximum permitted values per RFC 7540 § 4.2).
  141. ///
  142. /// Raising this value may lower CPU usage for large message at the cost of increasing head of
  143. /// line blocking for small messages.
  144. @discardableResult
  145. public func withHTTPMaxFrameSize(_ httpMaxFrameSize: Int) -> Self {
  146. self.configuration.httpMaxFrameSize = httpMaxFrameSize
  147. return self
  148. }
  149. }
  150. extension Server.Builder {
  151. /// Set the CORS configuration for gRPC Web.
  152. @discardableResult
  153. public func withCORSConfiguration(_ configuration: Server.Configuration.CORS) -> Self {
  154. self.configuration.webCORS = configuration
  155. return self
  156. }
  157. }
  158. extension Server.Builder {
  159. /// Sets the root server logger. Accepted connections will branch from this logger and RPCs on
  160. /// each connection will use a logger branched from the connections logger. This logger is made
  161. /// available to service providers via `context`. Defaults to a no-op logger.
  162. @discardableResult
  163. public func withLogger(_ logger: Logger) -> Self {
  164. self.configuration.logger = logger
  165. return self
  166. }
  167. }
  168. extension Server.Builder {
  169. /// A channel initializer which will be run after gRPC has initialized each accepted channel.
  170. /// This may be used to add additional handlers to the pipeline and is intended for debugging.
  171. /// This is analogous to `NIO.ServerBootstrap.childChannelInitializer`.
  172. ///
  173. /// - Warning: The initializer closure may be invoked *multiple times*. More precisely: it will
  174. /// be invoked at most once per accepted connection.
  175. @discardableResult
  176. public func withDebugChannelInitializer(
  177. _ debugChannelInitializer: @escaping (Channel) -> EventLoopFuture<Void>
  178. ) -> Self {
  179. self.configuration.debugChannelInitializer = debugChannelInitializer
  180. return self
  181. }
  182. }
  183. extension Server {
  184. /// Returns an insecure `Server` builder which is *not configured with TLS*.
  185. public static func insecure(group: EventLoopGroup) -> Builder {
  186. return Builder(group: group)
  187. }
  188. #if canImport(Network)
  189. /// Returns a `Server` builder configured with the 'Network.framework' TLS backend.
  190. ///
  191. /// This builder must use a `NIOTSEventLoopGroup`.
  192. @available(macOS 10.14, iOS 12.0, watchOS 6.0, tvOS 12.0, *)
  193. public static func usingTLSBackedByNetworkFramework(
  194. on group: EventLoopGroup,
  195. with identity: SecIdentity
  196. ) -> Builder.Secure {
  197. precondition(
  198. PlatformSupport.isTransportServicesEventLoopGroup(group),
  199. "'usingTLSBackedByNetworkFramework(on:with:)' requires 'eventLoopGroup' to be a 'NIOTransportServices.NIOTSEventLoopGroup' or 'NIOTransportServices.QoSEventLoop' (but was '\(type(of: group))'"
  200. )
  201. return Builder.Secure(
  202. group: group,
  203. tlsConfiguration: .makeServerConfigurationBackedByNetworkFramework(identity: identity)
  204. )
  205. }
  206. #endif
  207. /// Returns a `Server` builder configured with the TLS backend appropriate for the
  208. /// provided `configuration` and `EventLoopGroup`.
  209. ///
  210. /// - Important: The caller is responsible for ensuring the provided `configuration` may be used
  211. /// the the `group`.
  212. public static func usingTLS(
  213. with configuration: GRPCTLSConfiguration,
  214. on group: EventLoopGroup
  215. ) -> Builder.Secure {
  216. return Builder.Secure(group: group, tlsConfiguration: configuration)
  217. }
  218. }