Channel.swift 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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. underlyingChannel = withExtendedLifetime(argumentWrappers) {
  43. var argumentValues = argumentWrappers.map { $0.wrapped }
  44. if secure {
  45. return cgrpc_channel_create_secure(address, roots_pem(), nil, nil, &argumentValues, Int32(arguments.count))
  46. } else {
  47. return cgrpc_channel_create(address, &argumentValues, Int32(arguments.count))
  48. }
  49. }
  50. completionQueue = CompletionQueue(underlyingCompletionQueue: cgrpc_channel_completion_queue(underlyingChannel), name: "Client")
  51. completionQueue.run() // start a loop that watches the channel's completion queue
  52. }
  53. /// Initializes a gRPC channel
  54. ///
  55. /// - Parameter address: the address of the server to be called
  56. /// - Parameter arguments: list of channel configuration options
  57. public init(googleAddress: String, arguments: [Argument] = []) {
  58. gRPC.initialize()
  59. host = googleAddress
  60. let argumentWrappers = arguments.map { $0.toCArg() }
  61. underlyingChannel = withExtendedLifetime(argumentWrappers) {
  62. var argumentValues = argumentWrappers.map { $0.wrapped }
  63. return cgrpc_channel_create_google(googleAddress, &argumentValues, Int32(arguments.count))
  64. }
  65. completionQueue = CompletionQueue(underlyingCompletionQueue: cgrpc_channel_completion_queue(underlyingChannel), name: "Client")
  66. completionQueue.run() // start a loop that watches the channel's completion queue
  67. }
  68. /// Initializes a gRPC channel
  69. ///
  70. /// - Parameter address: the address of the server to be called
  71. /// - Parameter certificates: a PEM representation of certificates to use.
  72. /// - Parameter clientCertificates: a PEM representation of the client certificates to use
  73. /// - Parameter clientKey: a PEM representation of the client key to use
  74. /// - Parameter arguments: list of channel configuration options
  75. public init(address: String, certificates: String = roots_pem(), clientCertificates: String? = nil, clientKey: String? = nil, arguments: [Argument] = []) {
  76. gRPC.initialize()
  77. host = address
  78. let argumentWrappers = arguments.map { $0.toCArg() }
  79. underlyingChannel = withExtendedLifetime(argumentWrappers) {
  80. var argumentValues = argumentWrappers.map { $0.wrapped }
  81. return cgrpc_channel_create_secure(address, certificates, clientCertificates, clientKey, &argumentValues, Int32(arguments.count))
  82. }
  83. completionQueue = CompletionQueue(underlyingCompletionQueue: cgrpc_channel_completion_queue(underlyingChannel), name: "Client")
  84. completionQueue.run() // start a loop that watches the channel's completion queue
  85. }
  86. deinit {
  87. connectivityObservers.forEach { $0.shutdown() }
  88. cgrpc_channel_destroy(underlyingChannel)
  89. completionQueue.shutdown()
  90. }
  91. /// Constructs a Call object to make a gRPC API call
  92. ///
  93. /// - Parameter method: the gRPC method name for the call
  94. /// - Parameter host: the gRPC host name for the call. If unspecified, defaults to the Client host
  95. /// - Parameter timeout: a timeout value in seconds
  96. /// - Returns: a Call object that can be used to perform the request
  97. public func makeCall(_ method: String, host: String = "", timeout: TimeInterval? = nil) -> Call {
  98. let host = (host == "") ? self.host : host
  99. let timeout = timeout ?? self.timeout
  100. let underlyingCall = cgrpc_channel_create_call(underlyingChannel, method, host, timeout)!
  101. return Call(underlyingCall: underlyingCall, owned: true, completionQueue: completionQueue)
  102. }
  103. /// Check the current connectivity state
  104. ///
  105. /// - Parameter tryToConnect: boolean value to indicate if should try to connect if channel's connectivity state is idle
  106. /// - Returns: a ConnectivityState value representing the current connectivity state of the channel
  107. public func connectivityState(tryToConnect: Bool = false) -> ConnectivityState {
  108. return ConnectivityState.connectivityState(cgrpc_channel_check_connectivity_state(underlyingChannel, tryToConnect ? 1 : 0))
  109. }
  110. /// Subscribe to connectivity state changes
  111. ///
  112. /// - Parameter callback: block executed every time a new connectivity state is detected
  113. public func subscribe(callback: @escaping (ConnectivityState) -> Void) {
  114. connectivityObservers.append(ConnectivityObserver(underlyingChannel: underlyingChannel, currentState: connectivityState(), callback: callback))
  115. }
  116. }
  117. private extension Channel {
  118. class ConnectivityObserver {
  119. private let completionQueue: CompletionQueue
  120. private let underlyingChannel: UnsafeMutableRawPointer
  121. private let underlyingCompletionQueue: UnsafeMutableRawPointer
  122. private let callback: (ConnectivityState) -> Void
  123. private var lastState: ConnectivityState
  124. private var hasBeenShutdown = false
  125. private let stateMutex: Mutex = Mutex()
  126. init(underlyingChannel: UnsafeMutableRawPointer, currentState: ConnectivityState, callback: @escaping (ConnectivityState) -> ()) {
  127. self.underlyingChannel = underlyingChannel
  128. self.underlyingCompletionQueue = cgrpc_completion_queue_create_for_next()
  129. self.completionQueue = CompletionQueue(underlyingCompletionQueue: self.underlyingCompletionQueue, name: "Connectivity State")
  130. self.callback = callback
  131. self.lastState = currentState
  132. run()
  133. }
  134. deinit {
  135. shutdown()
  136. }
  137. private func run() {
  138. let spinloopThreadQueue = DispatchQueue(label: "SwiftGRPC.ConnectivityObserver.run.spinloopThread")
  139. spinloopThreadQueue.async {
  140. while true {
  141. guard (self.stateMutex.synchronize{ !self.hasBeenShutdown }) else {
  142. return
  143. }
  144. guard let underlyingState = self.lastState.underlyingState else { return }
  145. let deadline: TimeInterval = 0.2
  146. cgrpc_channel_watch_connectivity_state(self.underlyingChannel, self.underlyingCompletionQueue, underlyingState, deadline, nil)
  147. let event = self.completionQueue.wait(timeout: deadline)
  148. guard (self.stateMutex.synchronize{ !self.hasBeenShutdown }) else {
  149. return
  150. }
  151. switch event.type {
  152. case .complete:
  153. let newState = ConnectivityState.connectivityState(cgrpc_channel_check_connectivity_state(self.underlyingChannel, 0))
  154. if newState != self.lastState {
  155. self.callback(newState)
  156. }
  157. self.lastState = newState
  158. case .queueTimeout:
  159. continue
  160. case .queueShutdown:
  161. return
  162. default:
  163. continue
  164. }
  165. }
  166. }
  167. }
  168. func shutdown() {
  169. stateMutex.synchronize {
  170. hasBeenShutdown = true
  171. }
  172. completionQueue.shutdown()
  173. }
  174. }
  175. }
  176. extension Channel {
  177. public enum ConnectivityState {
  178. /// Channel has just been initialized
  179. case initialized
  180. /// Channel is idle
  181. case idle
  182. /// Channel is connecting
  183. case connecting
  184. /// Channel is ready for work
  185. case ready
  186. /// Channel has seen a failure but expects to recover
  187. case transientFailure
  188. /// Channel has seen a failure that it cannot recover from
  189. case shutdown
  190. /// Channel connectivity state is unknown
  191. case unknown
  192. fileprivate static func connectivityState(_ value: grpc_connectivity_state) -> ConnectivityState {
  193. switch value {
  194. case GRPC_CHANNEL_INIT:
  195. return .initialized
  196. case GRPC_CHANNEL_IDLE:
  197. return .idle
  198. case GRPC_CHANNEL_CONNECTING:
  199. return .connecting
  200. case GRPC_CHANNEL_READY:
  201. return .ready
  202. case GRPC_CHANNEL_TRANSIENT_FAILURE:
  203. return .transientFailure
  204. case GRPC_CHANNEL_SHUTDOWN:
  205. return .shutdown
  206. default:
  207. return .unknown
  208. }
  209. }
  210. fileprivate var underlyingState: grpc_connectivity_state? {
  211. switch self {
  212. case .initialized:
  213. return GRPC_CHANNEL_INIT
  214. case .idle:
  215. return GRPC_CHANNEL_IDLE
  216. case .connecting:
  217. return GRPC_CHANNEL_CONNECTING
  218. case .ready:
  219. return GRPC_CHANNEL_READY
  220. case .transientFailure:
  221. return GRPC_CHANNEL_TRANSIENT_FAILURE
  222. case .shutdown:
  223. return GRPC_CHANNEL_SHUTDOWN
  224. default:
  225. return nil
  226. }
  227. }
  228. }
  229. }