ServerBuilder.swift 8.1 KB

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