ServerBuilder.swift 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  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. extension Server {
  20. public class Builder {
  21. private var configuration: Server.Configuration
  22. private var maybeTLS: Server.Configuration.TLS? { return nil }
  23. fileprivate init(group: EventLoopGroup) {
  24. self.configuration = Configuration(
  25. // This is okay: the configuration is only consumed on a call to `bind` which sets the host
  26. // and port.
  27. target: .hostAndPort("", .max),
  28. eventLoopGroup: group,
  29. serviceProviders: []
  30. )
  31. }
  32. public class Secure: Builder {
  33. private var tls: Server.Configuration.TLS
  34. override var maybeTLS: Server.Configuration.TLS? {
  35. return self.tls
  36. }
  37. fileprivate init(
  38. group: EventLoopGroup,
  39. certificateChain: [NIOSSLCertificate],
  40. privateKey: NIOSSLPrivateKey
  41. ) {
  42. self.tls = .init(
  43. certificateChain: certificateChain.map { .certificate($0) },
  44. privateKey: .privateKey(privateKey)
  45. )
  46. super.init(group: group)
  47. }
  48. }
  49. public func bind(host: String, port: Int) -> EventLoopFuture<Server> {
  50. // Finish setting up the configuration.
  51. self.configuration.target = .hostAndPort(host, port)
  52. self.configuration.tls = self.maybeTLS
  53. return Server.start(configuration: self.configuration)
  54. }
  55. }
  56. }
  57. extension Server.Builder {
  58. /// Sets the server error delegate.
  59. @discardableResult
  60. public func withErrorDelegate(_ delegate: ServerErrorDelegate?) -> Self {
  61. self.configuration.errorDelegate = delegate
  62. return self
  63. }
  64. }
  65. extension Server.Builder {
  66. /// Sets the service providers that this server should offer. Note that calling this multiple
  67. /// times will override any previously set providers.
  68. @discardableResult
  69. public func withServiceProviders(_ providers: [CallHandlerProvider]) -> Self {
  70. self.configuration.serviceProviders = providers
  71. return self
  72. }
  73. }
  74. extension Server.Builder {
  75. @discardableResult
  76. public func withKeepalive(_ keepalive: ServerConnectionKeepalive) -> Self {
  77. self.configuration.connectionKeepalive = keepalive
  78. return self
  79. }
  80. }
  81. extension Server.Builder {
  82. /// The amount of time to wait before closing connections. The idle timeout will start only
  83. /// if there are no RPCs in progress and will be cancelled as soon as any RPCs start. Unless a
  84. /// an idle timeout it set connections will not be idled by default.
  85. @discardableResult
  86. public func withConnectionIdleTimeout(_ timeout: TimeAmount) -> Self {
  87. self.configuration.connectionIdleTimeout = timeout
  88. return self
  89. }
  90. }
  91. extension Server.Builder {
  92. /// Sets the message compression configuration. Compression is disabled if this is not configured
  93. /// and any RPCs using compression will not be accepted.
  94. @discardableResult
  95. public func withMessageCompression(_ encoding: ServerMessageEncoding) -> Self {
  96. self.configuration.messageEncoding = encoding
  97. return self
  98. }
  99. }
  100. extension Server.Builder.Secure {
  101. /// Sets the trust roots to use to validate certificates. This only needs to be provided if you
  102. /// intend to validate certificates. Defaults to the system provided trust store (`.default`) if
  103. /// not set.
  104. @discardableResult
  105. public func withTLS(trustRoots: NIOSSLTrustRoots) -> Self {
  106. self.tls.trustRoots = trustRoots
  107. return self
  108. }
  109. /// Sets whether certificates should be verified. Defaults to `.none` if not set.
  110. @discardableResult
  111. public func withTLS(certificateVerification: CertificateVerification) -> Self {
  112. self.tls.certificateVerification = certificateVerification
  113. return self
  114. }
  115. /// Sets whether the server's TLS handshake requires a protocol to be negotiated via ALPN. This
  116. /// defaults to `true` if not otherwise set.
  117. ///
  118. /// If this option is set to `false` and no protocol is negotiated via ALPN then the server will
  119. /// parse the initial bytes on the connection to determine whether HTTP/2 or HTTP/1.1 (gRPC-Web)
  120. /// is being used and configure the connection appropriately.
  121. @discardableResult
  122. public func withTLS(requiringALPN: Bool) -> Self {
  123. self.tls.requireALPN = requiringALPN
  124. return self
  125. }
  126. }
  127. extension Server.Builder {
  128. /// Sets the HTTP/2 flow control target window size. Defaults to 65,535 if not explicitly set.
  129. @discardableResult
  130. public func withHTTPTargetWindowSize(_ httpTargetWindowSize: Int) -> Self {
  131. self.configuration.httpTargetWindowSize = httpTargetWindowSize
  132. return self
  133. }
  134. }
  135. extension Server.Builder {
  136. /// Sets the root server logger. Accepted connections will branch from this logger and RPCs on
  137. /// each connection will use a logger branched from the connections logger. This logger is made
  138. /// available to service providers via `context`. Defaults to a no-op logger.
  139. @discardableResult
  140. public func withLogger(_ logger: Logger) -> Self {
  141. self.configuration.logger = logger
  142. return self
  143. }
  144. }
  145. extension Server.Builder {
  146. /// A channel initializer which will be run after gRPC has initialized each accepted channel.
  147. /// This may be used to add additional handlers to the pipeline and is intended for debugging.
  148. /// This is analogous to `NIO.ServerBootstrap.childChannelInitializer`.
  149. ///
  150. /// - Warning: The initializer closure may be invoked *multiple times*. More precisely: it will
  151. /// be invoked at most once per accepted connection.
  152. @discardableResult
  153. public func withDebugChannelInitializer(
  154. _ debugChannelInitializer: @escaping (Channel) -> EventLoopFuture<Void>
  155. ) -> Self {
  156. self.configuration.debugChannelInitializer = debugChannelInitializer
  157. return self
  158. }
  159. }
  160. extension Server {
  161. /// Returns an insecure `Server` builder which is *not configured with TLS*.
  162. public static func insecure(group: EventLoopGroup) -> Builder {
  163. return Builder(group: group)
  164. }
  165. /// Returns a `Server` builder configured with TLS.
  166. public static func secure(
  167. group: EventLoopGroup,
  168. certificateChain: [NIOSSLCertificate],
  169. privateKey: NIOSSLPrivateKey
  170. ) -> Builder.Secure {
  171. return Builder.Secure(
  172. group: group,
  173. certificateChain: certificateChain,
  174. privateKey: privateKey
  175. )
  176. }
  177. }