Channel.swift 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  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. public init(address: String, secure: Bool = true) {
  38. host = address
  39. if secure {
  40. underlyingChannel = cgrpc_channel_create_secure(address, roots_pem(), nil)
  41. } else {
  42. underlyingChannel = cgrpc_channel_create(address)
  43. }
  44. completionQueue = CompletionQueue(underlyingCompletionQueue: cgrpc_channel_completion_queue(underlyingChannel), name: "Client")
  45. completionQueue.run() // start a loop that watches the channel's completion queue
  46. }
  47. /// Initializes a gRPC channel
  48. ///
  49. /// - Parameter address: the address of the server to be called
  50. /// - Parameter certificates: a PEM representation of certificates to use
  51. /// - Parameter host: an optional hostname override
  52. public init(address: String, certificates: String, host: String?) {
  53. self.host = address
  54. underlyingChannel = cgrpc_channel_create_secure(address, certificates, &argumentValues, Int32(arguments.count))
  55. completionQueue = CompletionQueue(underlyingCompletionQueue: cgrpc_channel_completion_queue(underlyingChannel), name: "Client")
  56. completionQueue.run() // start a loop that watches the channel's completion queue
  57. }
  58. deinit {
  59. connectivityObservers.forEach { $0.polling = false }
  60. cgrpc_channel_destroy(underlyingChannel)
  61. completionQueue.shutdown()
  62. }
  63. /// Constructs a Call object to make a gRPC API call
  64. ///
  65. /// - Parameter method: the gRPC method name for the call
  66. /// - Parameter host: the gRPC host name for the call. If unspecified, defaults to the Client host
  67. /// - Parameter timeout: a timeout value in seconds
  68. /// - Returns: a Call object that can be used to perform the request
  69. public func makeCall(_ method: String, host: String = "") -> Call {
  70. let host = (host == "") ? self.host : host
  71. let underlyingCall = cgrpc_channel_create_call(underlyingChannel, method, host, timeout)!
  72. return Call(underlyingCall: underlyingCall, owned: true, completionQueue: completionQueue)
  73. }
  74. public func connectivityState(tryToConnect: Bool = false) -> ConnectivityState {
  75. return ConnectivityState.connectivityState(cgrpc_channel_check_connectivity_state(underlyingChannel, tryToConnect ? 1 : 0))
  76. }
  77. public func subscribe(callback: @escaping (ConnectivityState) -> ()) {
  78. let observer = ConnectivityObserver(underlyingChannel: underlyingChannel, callback: callback)
  79. observer.polling = true
  80. connectivityObservers.append(observer)
  81. }
  82. }
  83. private extension Channel {
  84. class ConnectivityObserver {
  85. private let completionQueue: CompletionQueue
  86. private let underlyingChannel: UnsafeMutableRawPointer
  87. private let underlyingCompletionQueue: UnsafeMutableRawPointer
  88. private let callback: (ConnectivityState) -> ()
  89. private var lastState: ConnectivityState
  90. private let queue: OperationQueue
  91. var polling: Bool = false {
  92. didSet {
  93. queue.addOperation { [weak self] in
  94. guard let `self` = self else { return }
  95. if self.polling == true && oldValue == false {
  96. self.run()
  97. } else if self.polling == false && oldValue == true {
  98. self.shutdown()
  99. }
  100. }
  101. }
  102. }
  103. init(underlyingChannel: UnsafeMutableRawPointer, callback: @escaping (ConnectivityState) -> ()) {
  104. self.underlyingChannel = underlyingChannel
  105. self.underlyingCompletionQueue = cgrpc_completion_queue_create_for_next()
  106. self.completionQueue = CompletionQueue(underlyingCompletionQueue: self.underlyingCompletionQueue, name: "Connectivity State")
  107. self.callback = callback
  108. self.lastState = ConnectivityState.connectivityState(cgrpc_channel_check_connectivity_state(self.underlyingChannel, 0))
  109. queue = OperationQueue()
  110. queue.maxConcurrentOperationCount = 1
  111. queue.qualityOfService = .background
  112. }
  113. deinit {
  114. shutdown()
  115. }
  116. private func run() {
  117. DispatchQueue.global().async { [weak self] in
  118. guard let `self` = self else { return }
  119. while self.polling {
  120. guard let underlyingState = self.lastState.underlyingState else { return }
  121. let deadline: TimeInterval = 0.2
  122. cgrpc_channel_watch_connectivity_state(self.underlyingChannel, self.underlyingCompletionQueue, underlyingState, deadline, nil)
  123. let event = self.completionQueue.wait(timeout: deadline)
  124. if event.success == 1 {
  125. let newState = ConnectivityState.connectivityState(cgrpc_channel_check_connectivity_state(self.underlyingChannel, 1))
  126. guard newState != self.lastState else { continue }
  127. defer { self.lastState = newState }
  128. self.callback(newState)
  129. }
  130. }
  131. }
  132. }
  133. private func shutdown() {
  134. completionQueue.shutdown()
  135. }
  136. }
  137. }
  138. extension Channel {
  139. public enum ConnectivityState {
  140. /// Channel has just been initialized
  141. case initialized
  142. /// Channel is idle
  143. case idle
  144. /// Channel is connecting
  145. case connecting
  146. /// Channel is ready for work
  147. case ready
  148. /// Channel has seen a failure but expects to recover
  149. case transientFailure
  150. /// Channel has seen a failure that it cannot recover from
  151. case shutdown
  152. /// Channel connectivity state is unknown
  153. case unknown
  154. fileprivate static func connectivityState(_ value: grpc_connectivity_state) -> ConnectivityState {
  155. switch value {
  156. case GRPC_CHANNEL_INIT:
  157. return .initialized
  158. case GRPC_CHANNEL_IDLE:
  159. return .idle
  160. case GRPC_CHANNEL_CONNECTING:
  161. return .connecting
  162. case GRPC_CHANNEL_READY:
  163. return .ready
  164. case GRPC_CHANNEL_TRANSIENT_FAILURE:
  165. return .transientFailure
  166. case GRPC_CHANNEL_SHUTDOWN:
  167. return .shutdown
  168. default:
  169. return .unknown
  170. }
  171. }
  172. fileprivate var underlyingState: grpc_connectivity_state? {
  173. switch self {
  174. case .initialized:
  175. return GRPC_CHANNEL_INIT
  176. case .idle:
  177. return GRPC_CHANNEL_IDLE
  178. case .connecting:
  179. return GRPC_CHANNEL_CONNECTING
  180. case .ready:
  181. return GRPC_CHANNEL_READY
  182. case .transientFailure:
  183. return GRPC_CHANNEL_TRANSIENT_FAILURE
  184. case .shutdown:
  185. return GRPC_CHANNEL_SHUTDOWN
  186. default:
  187. return nil
  188. }
  189. }
  190. }
  191. }