GRPCClient.swift 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. /*
  2. * Copyright 2019, 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 Foundation
  17. import NIO
  18. import NIOHTTP2
  19. import NIOSSL
  20. /// Underlying channel and HTTP/2 stream multiplexer.
  21. ///
  22. /// Different service clients implementing `GRPCServiceClient` may share an instance of this class.
  23. open class GRPCClient {
  24. public static func start(
  25. host: String,
  26. port: Int,
  27. eventLoopGroup: EventLoopGroup,
  28. tls tlsMode: TLSMode = .none
  29. ) throws -> EventLoopFuture<GRPCClient> {
  30. // We need to capture the multiplexer from the channel initializer to store it after connection.
  31. let multiplexerPromise: EventLoopPromise<HTTP2StreamMultiplexer> = eventLoopGroup.next().makePromise()
  32. let bootstrap = ClientBootstrap(group: eventLoopGroup)
  33. // Enable SO_REUSEADDR.
  34. .channelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
  35. .channelInitializer { channel in
  36. let multiplexer = configureTLS(mode: tlsMode, channel: channel, host: host).flatMap {
  37. channel.configureHTTP2Pipeline(mode: .client)
  38. }
  39. multiplexer.cascade(to: multiplexerPromise)
  40. return multiplexer.map { _ in }
  41. }
  42. return bootstrap.connect(host: host, port: port)
  43. .and(multiplexerPromise.futureResult)
  44. .map { channel, multiplexer in GRPCClient(channel: channel, multiplexer: multiplexer, host: host, httpProtocol: tlsMode.httpProtocol) }
  45. }
  46. /// Configure an SSL handler on the channel, if one is required.
  47. ///
  48. /// - Parameters:
  49. /// - mode: TLS mode to use when creating the new handler.
  50. /// - channel: The channel on which to add the SSL handler.
  51. /// - host: The hostname of the server we're connecting to.
  52. /// - Returns: A future which will be succeeded when the pipeline has been configured.
  53. private static func configureTLS(mode tls: TLSMode, channel: Channel, host: String) -> EventLoopFuture<Void> {
  54. let handlerAddedPromise: EventLoopPromise<Void> = channel.eventLoop.makePromise()
  55. do {
  56. guard let sslContext = try tls.makeSSLContext() else {
  57. handlerAddedPromise.succeed(())
  58. return handlerAddedPromise.futureResult
  59. }
  60. channel.pipeline.addHandler(try NIOSSLClientHandler(context: sslContext, serverHostname: host)).cascade(to: handlerAddedPromise)
  61. } catch {
  62. handlerAddedPromise.fail(error)
  63. }
  64. return handlerAddedPromise.futureResult
  65. }
  66. public let channel: Channel
  67. public let multiplexer: HTTP2StreamMultiplexer
  68. public let host: String
  69. public var defaultCallOptions: CallOptions
  70. public let httpProtocol: HTTP2ToHTTP1ClientCodec.HTTPProtocol
  71. init(channel: Channel, multiplexer: HTTP2StreamMultiplexer, host: String, httpProtocol: HTTP2ToHTTP1ClientCodec.HTTPProtocol, defaultCallOptions: CallOptions = CallOptions()) {
  72. self.channel = channel
  73. self.multiplexer = multiplexer
  74. self.host = host
  75. self.defaultCallOptions = defaultCallOptions
  76. self.httpProtocol = httpProtocol
  77. }
  78. /// Fired when the client shuts down.
  79. public var onClose: EventLoopFuture<Void> {
  80. return channel.closeFuture
  81. }
  82. public func close() -> EventLoopFuture<Void> {
  83. return channel.close(mode: .all)
  84. }
  85. }
  86. /// A GRPC client for a given service.
  87. public protocol GRPCServiceClient {
  88. /// The client providing the underlying HTTP/2 channel for this client.
  89. var client: GRPCClient { get }
  90. /// Name of the service this client is for (e.g. "echo.Echo").
  91. var service: String { get }
  92. /// The call options to use should the user not provide per-call options.
  93. var defaultCallOptions: CallOptions { get set }
  94. /// Return the path for the given method in the format "/Service-Name/Method-Name".
  95. ///
  96. /// This may be overriden if consumers require a different path format.
  97. ///
  98. /// - Parameter forMethod: name of method to return a path for.
  99. /// - Returns: path for the given method used in gRPC request headers.
  100. func path(forMethod method: String) -> String
  101. }
  102. extension GRPCClient {
  103. public enum TLSMode {
  104. case none
  105. case anonymous
  106. case custom(NIOSSLContext)
  107. /// Returns an SSL context for the TLS mode.
  108. ///
  109. /// - Returns: An SSL context for the TLS mode, or `nil` if TLS is not being used.
  110. public func makeSSLContext() throws -> NIOSSLContext? {
  111. switch self {
  112. case .none:
  113. return nil
  114. case .anonymous:
  115. return try NIOSSLContext(configuration: .forClient())
  116. case .custom(let context):
  117. return context
  118. }
  119. }
  120. /// Rethrns the HTTP protocol for the TLS mode.
  121. public var httpProtocol: HTTP2ToHTTP1ClientCodec.HTTPProtocol {
  122. switch self {
  123. case .none:
  124. return .http
  125. case .anonymous, .custom:
  126. return .https
  127. }
  128. }
  129. }
  130. }
  131. extension GRPCServiceClient {
  132. public func path(forMethod method: String) -> String {
  133. return "/\(service)/\(method)"
  134. }
  135. }