Channel.swift 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. /*
  2. * Copyright 2016, 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. #if SWIFT_PACKAGE
  17. import CgRPC
  18. import Dispatch
  19. #endif
  20. import Foundation
  21. /// A gRPC Channel
  22. public class Channel {
  23. /// Pointer to underlying C representation
  24. private let underlyingChannel: UnsafeMutableRawPointer
  25. /// Completion queue for channel call operations
  26. private let completionQueue: CompletionQueue
  27. /// Timeout for new calls
  28. public var timeout: TimeInterval = 600.0
  29. /// Default host to use for new calls
  30. public var host: String
  31. /// Connectivity state observers
  32. private var connectivityObservers: [ConnectivityObserver] = []
  33. /// Initializes a gRPC channel
  34. ///
  35. /// - Parameter address: the address of the server to be called
  36. /// - Parameter secure: if true, use TLS
  37. /// - Parameter arguments: list of channel configuration options
  38. public init(address: String, secure: Bool = true, arguments: [Argument] = []) {
  39. gRPC.initialize()
  40. host = address
  41. let argumentWrappers = arguments.map { $0.toCArg() }
  42. var argumentValues = argumentWrappers.map { $0.wrapped }
  43. if secure {
  44. underlyingChannel = cgrpc_channel_create_secure(address, roots_pem(), &argumentValues, Int32(arguments.count))
  45. } else {
  46. underlyingChannel = cgrpc_channel_create(address, &argumentValues, Int32(arguments.count))
  47. }
  48. completionQueue = CompletionQueue(underlyingCompletionQueue: cgrpc_channel_completion_queue(underlyingChannel), name: "Client")
  49. completionQueue.run() // start a loop that watches the channel's completion queue
  50. }
  51. /// Initializes a gRPC channel
  52. ///
  53. /// - Parameter address: the address of the server to be called
  54. /// - Parameter certificates: a PEM representation of certificates to use
  55. /// - Parameter arguments: list of channel configuration options
  56. public init(address: String, certificates: String, arguments: [Argument] = []) {
  57. gRPC.initialize()
  58. host = address
  59. let argumentWrappers = arguments.map { $0.toCArg() }
  60. var argumentValues = argumentWrappers.map { $0.wrapped }
  61. underlyingChannel = cgrpc_channel_create_secure(address, certificates, &argumentValues, Int32(arguments.count))
  62. completionQueue = CompletionQueue(underlyingCompletionQueue: cgrpc_channel_completion_queue(underlyingChannel), name: "Client")
  63. completionQueue.run() // start a loop that watches the channel's completion queue
  64. }
  65. deinit {
  66. connectivityObservers.forEach { $0.shutdown() }
  67. cgrpc_channel_destroy(underlyingChannel)
  68. completionQueue.shutdown()
  69. }
  70. /// Constructs a Call object to make a gRPC API call
  71. ///
  72. /// - Parameter method: the gRPC method name for the call
  73. /// - Parameter host: the gRPC host name for the call. If unspecified, defaults to the Client host
  74. /// - Parameter timeout: a timeout value in seconds
  75. /// - Returns: a Call object that can be used to perform the request
  76. public func makeCall(_ method: String, host: String = "") -> Call {
  77. let host = (host == "") ? self.host : host
  78. let underlyingCall = cgrpc_channel_create_call(underlyingChannel, method, host, timeout)!
  79. return Call(underlyingCall: underlyingCall, owned: true, completionQueue: completionQueue)
  80. }
  81. /// Check the current connectivity state
  82. ///
  83. /// - Parameter tryToConnect: boolean value to indicate if should try to connect if channel's connectivity state is idle
  84. /// - Returns: a ConnectivityState value representing the current connectivity state of the channel
  85. public func connectivityState(tryToConnect: Bool = false) -> ConnectivityState {
  86. return ConnectivityState.connectivityState(cgrpc_channel_check_connectivity_state(underlyingChannel, tryToConnect ? 1 : 0))
  87. }
  88. /// Subscribe to connectivity state changes
  89. ///
  90. /// - Parameter callback: block executed every time a new connectivity state is detected
  91. public func subscribe(callback: @escaping (ConnectivityState) -> Void) {
  92. connectivityObservers.append(ConnectivityObserver(underlyingChannel: underlyingChannel, currentState: connectivityState(), callback: callback))
  93. }
  94. }
  95. private extension Channel {
  96. class ConnectivityObserver {
  97. private let completionQueue: CompletionQueue
  98. private let underlyingChannel: UnsafeMutableRawPointer
  99. private let underlyingCompletionQueue: UnsafeMutableRawPointer
  100. private let callback: (ConnectivityState) -> Void
  101. private var lastState: ConnectivityState
  102. init(underlyingChannel: UnsafeMutableRawPointer, currentState: ConnectivityState, callback: @escaping (ConnectivityState) -> ()) {
  103. self.underlyingChannel = underlyingChannel
  104. self.underlyingCompletionQueue = cgrpc_completion_queue_create_for_next()
  105. self.completionQueue = CompletionQueue(underlyingCompletionQueue: self.underlyingCompletionQueue, name: "Connectivity State")
  106. self.callback = callback
  107. self.lastState = currentState
  108. run()
  109. }
  110. deinit {
  111. shutdown()
  112. }
  113. private func run() {
  114. let spinloopThreadQueue = DispatchQueue(label: "SwiftGRPC.ConnectivityObserver.run.spinloopThread")
  115. spinloopThreadQueue.async {
  116. while true {
  117. guard let underlyingState = self.lastState.underlyingState else { return }
  118. let deadline: TimeInterval = 0.2
  119. cgrpc_channel_watch_connectivity_state(self.underlyingChannel, self.underlyingCompletionQueue, underlyingState, deadline, nil)
  120. let event = self.completionQueue.wait(timeout: deadline)
  121. switch event.type {
  122. case .complete:
  123. let newState = ConnectivityState.connectivityState(cgrpc_channel_check_connectivity_state(self.underlyingChannel, 0))
  124. if newState != self.lastState {
  125. self.callback(newState)
  126. }
  127. self.lastState = newState
  128. case .queueTimeout:
  129. continue
  130. case .queueShutdown:
  131. return
  132. default:
  133. continue
  134. }
  135. }
  136. }
  137. }
  138. func shutdown() {
  139. completionQueue.shutdown()
  140. }
  141. }
  142. }
  143. extension Channel {
  144. public enum ConnectivityState {
  145. /// Channel has just been initialized
  146. case initialized
  147. /// Channel is idle
  148. case idle
  149. /// Channel is connecting
  150. case connecting
  151. /// Channel is ready for work
  152. case ready
  153. /// Channel has seen a failure but expects to recover
  154. case transientFailure
  155. /// Channel has seen a failure that it cannot recover from
  156. case shutdown
  157. /// Channel connectivity state is unknown
  158. case unknown
  159. fileprivate static func connectivityState(_ value: grpc_connectivity_state) -> ConnectivityState {
  160. switch value {
  161. case GRPC_CHANNEL_INIT:
  162. return .initialized
  163. case GRPC_CHANNEL_IDLE:
  164. return .idle
  165. case GRPC_CHANNEL_CONNECTING:
  166. return .connecting
  167. case GRPC_CHANNEL_READY:
  168. return .ready
  169. case GRPC_CHANNEL_TRANSIENT_FAILURE:
  170. return .transientFailure
  171. case GRPC_CHANNEL_SHUTDOWN:
  172. return .shutdown
  173. default:
  174. return .unknown
  175. }
  176. }
  177. fileprivate var underlyingState: grpc_connectivity_state? {
  178. switch self {
  179. case .initialized:
  180. return GRPC_CHANNEL_INIT
  181. case .idle:
  182. return GRPC_CHANNEL_IDLE
  183. case .connecting:
  184. return GRPC_CHANNEL_CONNECTING
  185. case .ready:
  186. return GRPC_CHANNEL_READY
  187. case .transientFailure:
  188. return GRPC_CHANNEL_TRANSIENT_FAILURE
  189. case .shutdown:
  190. return GRPC_CHANNEL_SHUTDOWN
  191. default:
  192. return nil
  193. }
  194. }
  195. }
  196. }