Channel.swift 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  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. private let mutex = Mutex()
  23. /// Pointer to underlying C representation
  24. private let underlyingChannel: UnsafeMutableRawPointer
  25. /// Completion queue for channel call operations
  26. private let completionQueue: CompletionQueue
  27. /// Observer for connectivity state changes. Created lazily if needed
  28. private var connectivityObserver: ConnectivityObserver?
  29. /// Timeout for new calls
  30. public var timeout: TimeInterval = 600.0
  31. /// Default host to use for new calls
  32. public var host: String
  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, kRootCertificates, 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 = kRootCertificates, 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. self.mutex.synchronize {
  88. self.connectivityObserver?.shutdown()
  89. }
  90. cgrpc_channel_destroy(self.underlyingChannel)
  91. self.completionQueue.shutdown()
  92. }
  93. /// Constructs a Call object to make a gRPC API call
  94. ///
  95. /// - Parameter method: the gRPC method name for the call
  96. /// - Parameter host: the gRPC host name for the call. If unspecified, defaults to the Client host
  97. /// - Parameter timeout: a timeout value in seconds
  98. /// - Returns: a Call object that can be used to perform the request
  99. public func makeCall(_ method: String, host: String = "", timeout: TimeInterval? = nil) -> Call {
  100. let host = host.isEmpty ? self.host : host
  101. let timeout = timeout ?? self.timeout
  102. let underlyingCall = cgrpc_channel_create_call(underlyingChannel, method, host, timeout)!
  103. return Call(underlyingCall: underlyingCall, owned: true, completionQueue: completionQueue)
  104. }
  105. /// Check the current connectivity state
  106. ///
  107. /// - Parameter tryToConnect: boolean value to indicate if should try to connect if channel's connectivity state is idle
  108. /// - Returns: a ConnectivityState value representing the current connectivity state of the channel
  109. public func connectivityState(tryToConnect: Bool = false) -> ConnectivityState {
  110. return ConnectivityState(cgrpc_channel_check_connectivity_state(underlyingChannel, tryToConnect ? 1 : 0))
  111. }
  112. /// Subscribe to connectivity state changes
  113. ///
  114. /// - Parameter callback: block executed every time a new connectivity state is detected
  115. public func addConnectivityObserver(callback: @escaping (ConnectivityState) -> Void) {
  116. self.mutex.synchronize {
  117. let observer: ConnectivityObserver
  118. if let existingObserver = self.connectivityObserver {
  119. observer = existingObserver
  120. } else {
  121. observer = ConnectivityObserver(underlyingChannel: self.underlyingChannel)
  122. self.connectivityObserver = observer
  123. }
  124. observer.addConnectivityObserver(callback: callback)
  125. }
  126. }
  127. }