ServerBuilder.swift 9.4 KB

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