ConnectivityState.swift 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. /*
  2. * Copyright 2019, 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. import Foundation
  17. import Logging
  18. import NIOConcurrencyHelpers
  19. import NIOCore
  20. /// The connectivity state of a client connection. Note that this is heavily lifted from the gRPC
  21. /// documentation: https://github.com/grpc/grpc/blob/master/doc/connectivity-semantics-and-api.md.
  22. public enum ConnectivityState: GRPCSendable {
  23. /// This is the state where the channel has not yet been created.
  24. case idle
  25. /// The channel is trying to establish a connection and is waiting to make progress on one of the
  26. /// steps involved in name resolution, TCP connection establishment or TLS handshake.
  27. case connecting
  28. /// The channel has successfully established a connection all the way through TLS handshake (or
  29. /// equivalent) and protocol-level (HTTP/2, etc) handshaking.
  30. case ready
  31. /// There has been some transient failure (such as a TCP 3-way handshake timing out or a socket
  32. /// error). Channels in this state will eventually switch to the `.connecting` state and try to
  33. /// establish a connection again. Since retries are done with exponential backoff, channels that
  34. /// fail to connect will start out spending very little time in this state but as the attempts
  35. /// fail repeatedly, the channel will spend increasingly large amounts of time in this state.
  36. case transientFailure
  37. /// This channel has started shutting down. Any new RPCs should fail immediately. Pending RPCs
  38. /// may continue running till the application cancels them. Channels may enter this state either
  39. /// because the application explicitly requested a shutdown or if a non-recoverable error has
  40. /// happened during attempts to connect. Channels that have entered this state will never leave
  41. /// this state.
  42. case shutdown
  43. }
  44. public protocol ConnectivityStateDelegate: AnyObject, GRPCPreconcurrencySendable {
  45. /// Called when a change in `ConnectivityState` has occurred.
  46. ///
  47. /// - Parameter oldState: The old connectivity state.
  48. /// - Parameter newState: The new connectivity state.
  49. func connectivityStateDidChange(from oldState: ConnectivityState, to newState: ConnectivityState)
  50. /// Called when the connection has started quiescing, that is, the connection is going away but
  51. /// existing RPCs may continue to run.
  52. ///
  53. /// - Important: When this is called no new RPCs may be created until the connectivity state
  54. /// changes to 'idle' (the connection successfully quiesced) or 'transientFailure' (the
  55. /// connection was closed before quiescing completed). Starting RPCs before these state changes
  56. /// will lead to a connection error and the immediate failure of any outstanding RPCs.
  57. func connectionStartedQuiescing()
  58. }
  59. extension ConnectivityStateDelegate {
  60. public func connectionStartedQuiescing() {}
  61. }
  62. #if compiler(>=5.6)
  63. // Unchecked because all mutable state is protected by locks.
  64. extension ConnectivityStateMonitor: @unchecked Sendable {}
  65. #endif // compiler(>=5.6)
  66. public class ConnectivityStateMonitor {
  67. private let stateLock = Lock()
  68. private var _state: ConnectivityState = .idle
  69. private let delegateLock = Lock()
  70. private var _delegate: ConnectivityStateDelegate?
  71. private let delegateCallbackQueue: DispatchQueue
  72. /// Creates a new connectivity state monitor.
  73. ///
  74. /// - Parameter delegate: A delegate to call when the connectivity state changes.
  75. /// - Parameter queue: The `DispatchQueue` on which the delegate will be called.
  76. init(delegate: ConnectivityStateDelegate?, queue: DispatchQueue?) {
  77. self._delegate = delegate
  78. self.delegateCallbackQueue = DispatchQueue(label: "io.grpc.connectivity", target: queue)
  79. }
  80. /// The current state of connectivity.
  81. public var state: ConnectivityState {
  82. return self.stateLock.withLock {
  83. self._state
  84. }
  85. }
  86. /// A delegate to call when the connectivity state changes.
  87. public var delegate: ConnectivityStateDelegate? {
  88. get {
  89. return self.delegateLock.withLock {
  90. return self._delegate
  91. }
  92. }
  93. set {
  94. self.delegateLock.withLockVoid {
  95. self._delegate = newValue
  96. }
  97. }
  98. }
  99. internal func updateState(to newValue: ConnectivityState, logger: Logger) {
  100. let change: (ConnectivityState, ConnectivityState)? = self.stateLock.withLock {
  101. let oldValue = self._state
  102. if oldValue != newValue {
  103. self._state = newValue
  104. return (oldValue, newValue)
  105. } else {
  106. return nil
  107. }
  108. }
  109. if let (oldState, newState) = change {
  110. logger.debug("connectivity state change", metadata: [
  111. "old_state": "\(oldState)",
  112. "new_state": "\(newState)",
  113. ])
  114. self.delegateCallbackQueue.async {
  115. if let delegate = self.delegate {
  116. delegate.connectivityStateDidChange(from: oldState, to: newState)
  117. }
  118. }
  119. }
  120. }
  121. internal func beginQuiescing() {
  122. self.delegateCallbackQueue.async {
  123. if let delegate = self.delegate {
  124. delegate.connectionStartedQuiescing()
  125. }
  126. }
  127. }
  128. }
  129. extension ConnectivityStateMonitor: ConnectionManagerConnectivityDelegate {
  130. internal func connectionStateDidChange(
  131. _ connectionManager: ConnectionManager,
  132. from oldState: _ConnectivityState,
  133. to newState: _ConnectivityState
  134. ) {
  135. self.updateState(to: ConnectivityState(newState), logger: connectionManager.logger)
  136. }
  137. internal func connectionIsQuiescing(_ connectionManager: ConnectionManager) {
  138. self.beginQuiescing()
  139. }
  140. }