2
0

Channel.swift 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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. #endif
  19. import Foundation
  20. /// A gRPC Channel
  21. public class Channel {
  22. /// Pointer to underlying C representation
  23. private let underlyingChannel: UnsafeMutableRawPointer
  24. /// Completion queue for channel call operations
  25. private let completionQueue: CompletionQueue
  26. /// Timeout for new calls
  27. public var timeout: TimeInterval = 600.0
  28. /// Default host to use for new calls
  29. public var host: String
  30. /// Connectivity state observers
  31. private var observers: [ConnectivityObserver] = []
  32. /// Initializes a gRPC channel
  33. ///
  34. /// - Parameter address: the address of the server to be called
  35. /// - Parameter secure: if true, use TLS
  36. public init(address: String, secure: Bool = true) {
  37. host = address
  38. if secure {
  39. underlyingChannel = cgrpc_channel_create_secure(address, roots_pem(), nil)
  40. } else {
  41. underlyingChannel = cgrpc_channel_create(address)
  42. }
  43. completionQueue = CompletionQueue(
  44. 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, host)
  55. completionQueue = CompletionQueue(
  56. underlyingCompletionQueue: cgrpc_channel_completion_queue(underlyingChannel), name: "Client")
  57. completionQueue.run() // start a loop that watches the channel's completion queue
  58. }
  59. deinit {
  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(sourceState: ConnectivityState, tryToConnect: Bool = false, callback: @escaping (ConnectivityState) -> ()) {
  78. var observer = observers.first(where: { $0.state == sourceState })
  79. if observer == nil {
  80. let newObserver = ConnectivityObserver(state: sourceState, underlyingChannel: underlyingChannel, tryToConnect: tryToConnect)
  81. observers.append(newObserver)
  82. observer = newObserver
  83. }
  84. observer?.callbacks.append(callback)
  85. observer?.polling = true
  86. }
  87. }
  88. private extension Channel {
  89. class ConnectivityObserver: Equatable {
  90. let state: ConnectivityState
  91. let queue: CompletionQueue
  92. let underlyingChannel: UnsafeMutableRawPointer
  93. let underlyingCompletionQueue: UnsafeMutableRawPointer
  94. private(set) var tryToConnect: Bool
  95. var callbacks: [(ConnectivityState) -> ()] = []
  96. private var lastState: ConnectivityState
  97. var polling: Bool = false {
  98. didSet {
  99. if polling == true && oldValue == false {
  100. run()
  101. }
  102. }
  103. }
  104. init(state: ConnectivityState, underlyingChannel: UnsafeMutableRawPointer, tryToConnect: Bool) {
  105. self.state = state
  106. self.underlyingChannel = underlyingChannel
  107. self.tryToConnect = tryToConnect
  108. self.underlyingCompletionQueue = cgrpc_completion_queue_create_for_next()
  109. self.queue = CompletionQueue(underlyingCompletionQueue: self.underlyingCompletionQueue, name: "Connectivity State")
  110. self.lastState = ConnectivityState.connectivityState(cgrpc_channel_check_connectivity_state(self.underlyingChannel, 0))
  111. }
  112. deinit {
  113. queue.shutdown()
  114. }
  115. private func run() {
  116. DispatchQueue.global().async { [weak self] in
  117. guard let `self` = self, let underlyingState = self.lastState.underlyingState else { return }
  118. while self.polling {
  119. guard !self.callbacks.isEmpty && !self.tryToConnect else {
  120. self.polling = false
  121. break
  122. }
  123. defer { self.tryToConnect = false }
  124. let deadline: TimeInterval = 0.2
  125. cgrpc_channel_watch_connectivity_state(self.underlyingChannel, self.underlyingCompletionQueue, underlyingState, deadline, nil)
  126. let event = self.queue.wait(timeout: deadline)
  127. if event.success == 1 || self.tryToConnect {
  128. let newState = ConnectivityState.connectivityState(cgrpc_channel_check_connectivity_state(self.underlyingChannel, self.tryToConnect ? 1 : 0))
  129. guard newState != self.lastState else { continue }
  130. defer { self.lastState = newState }
  131. if self.lastState == self.state {
  132. self.callbacks.forEach({ $0(newState) })
  133. }
  134. }
  135. }
  136. }
  137. }
  138. static func == (lhs: ConnectivityObserver, rhs: ConnectivityObserver) -> Bool {
  139. return lhs.state == rhs.state
  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. }