ServerBuilder.swift 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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 NIO
  18. import NIOSSL
  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. private var tls: GRPCTLSConfiguration
  37. override var maybeTLS: GRPCTLSConfiguration? {
  38. return self.tls
  39. }
  40. fileprivate 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. }
  53. }
  54. extension Server.Builder {
  55. /// Sets the server error delegate.
  56. @discardableResult
  57. public func withErrorDelegate(_ delegate: ServerErrorDelegate?) -> Self {
  58. self.configuration.errorDelegate = delegate
  59. return self
  60. }
  61. }
  62. extension Server.Builder {
  63. /// Sets the service providers that this server should offer. Note that calling this multiple
  64. /// times will override any previously set providers.
  65. @discardableResult
  66. public func withServiceProviders(_ providers: [CallHandlerProvider]) -> Self {
  67. self.configuration.serviceProviders = providers
  68. return self
  69. }
  70. }
  71. extension Server.Builder {
  72. @discardableResult
  73. public func withKeepalive(_ keepalive: ServerConnectionKeepalive) -> Self {
  74. self.configuration.connectionKeepalive = keepalive
  75. return self
  76. }
  77. }
  78. extension Server.Builder {
  79. /// The amount of time to wait before closing connections. The idle timeout will start only
  80. /// if there are no RPCs in progress and will be cancelled as soon as any RPCs start. Unless a
  81. /// an idle timeout it set connections will not be idled by default.
  82. @discardableResult
  83. public func withConnectionIdleTimeout(_ timeout: TimeAmount) -> Self {
  84. self.configuration.connectionIdleTimeout = timeout
  85. return self
  86. }
  87. }
  88. extension Server.Builder {
  89. /// Sets the message compression configuration. Compression is disabled if this is not configured
  90. /// and any RPCs using compression will not be accepted.
  91. @discardableResult
  92. public func withMessageCompression(_ encoding: ServerMessageEncoding) -> Self {
  93. self.configuration.messageEncoding = encoding
  94. return self
  95. }
  96. /// Sets the maximum message size in bytes the server may receive.
  97. ///
  98. /// - Precondition: `limit` must not be negative.
  99. @discardableResult
  100. public func withMaximumReceiveMessageLength(_ limit: Int) -> Self {
  101. self.configuration.maximumReceiveMessageLength = limit
  102. return self
  103. }
  104. }
  105. extension Server.Builder.Secure {
  106. /// Sets the trust roots to use to validate certificates. This only needs to be provided if you
  107. /// intend to validate certificates. Defaults to the system provided trust store (`.default`) if
  108. /// not set.
  109. ///
  110. /// - Note: May only be used with the 'NIOSSL' TLS backend.
  111. @discardableResult
  112. public func withTLS(trustRoots: NIOSSLTrustRoots) -> Self {
  113. self.tls.updateNIOTrustRoots(to: trustRoots)
  114. return self
  115. }
  116. /// Sets whether certificates should be verified. Defaults to `.none` if not set.
  117. ///
  118. /// - Note: May only be used with the 'NIOSSL' TLS backend.
  119. @discardableResult
  120. public func withTLS(certificateVerification: CertificateVerification) -> Self {
  121. self.tls.updateNIOCertificateVerification(to: certificateVerification)
  122. return self
  123. }
  124. /// Sets whether the server's TLS handshake requires a protocol to be negotiated via ALPN. This
  125. /// defaults to `true` if not otherwise set.
  126. ///
  127. /// If this option is set to `false` and no protocol is negotiated via ALPN then the server will
  128. /// parse the initial bytes on the connection to determine whether HTTP/2 or HTTP/1.1 (gRPC-Web)
  129. /// is being used and configure the connection appropriately.
  130. ///
  131. /// - Note: May only be used with the 'NIOSSL' TLS backend.
  132. @discardableResult
  133. public func withTLS(requiringALPN: Bool) -> Self {
  134. self.tls.requireALPN = requiringALPN
  135. return self
  136. }
  137. }
  138. extension Server.Builder {
  139. /// Sets the HTTP/2 flow control target window size. Defaults to 65,535 if not explicitly set.
  140. @discardableResult
  141. public func withHTTPTargetWindowSize(_ httpTargetWindowSize: Int) -> Self {
  142. self.configuration.httpTargetWindowSize = httpTargetWindowSize
  143. return self
  144. }
  145. }
  146. extension Server.Builder {
  147. @discardableResult
  148. public func withHTTPMaxConcurrentStreams(_ httpMaxConcurrentStreams: Int) -> Self {
  149. self.configuration.httpMaxConcurrentStreams = httpMaxConcurrentStreams
  150. return self
  151. }
  152. }
  153. extension Server.Builder {
  154. /// Sets the root server logger. Accepted connections will branch from this logger and RPCs on
  155. /// each connection will use a logger branched from the connections logger. This logger is made
  156. /// available to service providers via `context`. Defaults to a no-op logger.
  157. @discardableResult
  158. public func withLogger(_ logger: Logger) -> Self {
  159. self.configuration.logger = logger
  160. return self
  161. }
  162. }
  163. extension Server.Builder {
  164. /// A channel initializer which will be run after gRPC has initialized each accepted channel.
  165. /// This may be used to add additional handlers to the pipeline and is intended for debugging.
  166. /// This is analogous to `NIO.ServerBootstrap.childChannelInitializer`.
  167. ///
  168. /// - Warning: The initializer closure may be invoked *multiple times*. More precisely: it will
  169. /// be invoked at most once per accepted connection.
  170. @discardableResult
  171. public func withDebugChannelInitializer(
  172. _ debugChannelInitializer: @escaping (Channel) -> EventLoopFuture<Void>
  173. ) -> Self {
  174. self.configuration.debugChannelInitializer = debugChannelInitializer
  175. return self
  176. }
  177. }
  178. extension Server {
  179. /// Returns an insecure `Server` builder which is *not configured with TLS*.
  180. public static func insecure(group: EventLoopGroup) -> Builder {
  181. return Builder(group: group)
  182. }
  183. /// Returns a `Server` builder configured with TLS.
  184. @available(
  185. *, deprecated,
  186. message: "Use one of 'usingTLSBackedByNIOSSL(on:certificateChain:privateKey:)', 'usingTLSBackedByNetworkFramework(on:with:)' or 'usingTLS(with:on:)'"
  187. )
  188. public static func secure(
  189. group: EventLoopGroup,
  190. certificateChain: [NIOSSLCertificate],
  191. privateKey: NIOSSLPrivateKey
  192. ) -> Builder.Secure {
  193. return Server.usingTLSBackedByNIOSSL(
  194. on: group,
  195. certificateChain: certificateChain,
  196. privateKey: privateKey
  197. )
  198. }
  199. /// Returns a `Server` builder configured with the 'NIOSSL' TLS backend.
  200. ///
  201. /// This builder may use either a `MultiThreadedEventLoopGroup` or a `NIOTSEventLoopGroup` (or an
  202. /// `EventLoop` from either group).
  203. public static func usingTLSBackedByNIOSSL(
  204. on group: EventLoopGroup,
  205. certificateChain: [NIOSSLCertificate],
  206. privateKey: NIOSSLPrivateKey
  207. ) -> Builder.Secure {
  208. return Builder.Secure(
  209. group: group,
  210. tlsConfiguration: .makeServerConfigurationBackedByNIOSSL(
  211. certificateChain: certificateChain.map { .certificate($0) },
  212. privateKey: .privateKey(privateKey)
  213. )
  214. )
  215. }
  216. #if canImport(Network)
  217. /// Returns a `Server` builder configured with the 'Network.framework' TLS backend.
  218. ///
  219. /// This builder must use a `NIOTSEventLoopGroup`.
  220. @available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *)
  221. public static func usingTLSBackedByNetworkFramework(
  222. on group: EventLoopGroup,
  223. with identity: SecIdentity
  224. ) -> Builder.Secure {
  225. precondition(
  226. PlatformSupport.isTransportServicesEventLoopGroup(group),
  227. "'usingTLSBackedByNetworkFramework(on:with:)' requires 'eventLoopGroup' to be a 'NIOTransportServices.NIOTSEventLoopGroup' or 'NIOTransportServices.QoSEventLoop' (but was '\(type(of: group))'"
  228. )
  229. return Builder.Secure(
  230. group: group,
  231. tlsConfiguration: .makeServerConfigurationBackedByNetworkFramework(identity: identity)
  232. )
  233. }
  234. #endif
  235. /// Returns a `Server` builder configured with the TLS backend appropriate for the
  236. /// provided `configuration` and `EventLoopGroup`.
  237. ///
  238. /// - Important: The caller is responsible for ensuring the provided `configuration` may be used
  239. /// the the `group`.
  240. public static func usingTLS(
  241. with configuration: GRPCTLSConfiguration,
  242. on group: EventLoopGroup
  243. ) -> Builder.Secure {
  244. return Builder.Secure(group: group, tlsConfiguration: configuration)
  245. }
  246. }