GRPCClientConnection.swift 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  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 `GRPCClient` may share an instance of this class.
  23. open class GRPCClientConnection {
  24. public static func start(
  25. host: String,
  26. port: Int,
  27. eventLoopGroup: EventLoopGroup,
  28. tls tlsMode: TLSMode = .none
  29. ) throws -> EventLoopFuture<GRPCClientConnection> {
  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 GRPCClientConnection(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 let httpProtocol: HTTP2ToHTTP1ClientCodec.HTTPProtocol
  70. init(channel: Channel, multiplexer: HTTP2StreamMultiplexer, host: String, httpProtocol: HTTP2ToHTTP1ClientCodec.HTTPProtocol) {
  71. self.channel = channel
  72. self.multiplexer = multiplexer
  73. self.host = host
  74. self.httpProtocol = httpProtocol
  75. }
  76. /// Fired when the client shuts down.
  77. public var onClose: EventLoopFuture<Void> {
  78. return channel.closeFuture
  79. }
  80. public func close() -> EventLoopFuture<Void> {
  81. return channel.close(mode: .all)
  82. }
  83. }
  84. extension GRPCClientConnection {
  85. public enum TLSMode {
  86. case none
  87. case anonymous
  88. case custom(NIOSSLContext)
  89. /// Returns an SSL context for the TLS mode.
  90. ///
  91. /// - Returns: An SSL context for the TLS mode, or `nil` if TLS is not being used.
  92. public func makeSSLContext() throws -> NIOSSLContext? {
  93. switch self {
  94. case .none:
  95. return nil
  96. case .anonymous:
  97. return try NIOSSLContext(configuration: .forClient())
  98. case .custom(let context):
  99. return context
  100. }
  101. }
  102. /// Rethrns the HTTP protocol for the TLS mode.
  103. public var httpProtocol: HTTP2ToHTTP1ClientCodec.HTTPProtocol {
  104. switch self {
  105. case .none:
  106. return .http
  107. case .anonymous, .custom:
  108. return .https
  109. }
  110. }
  111. }
  112. }