ConnectivityState.swift 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  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 NIO
  19. import NIOConcurrencyHelpers
  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 {
  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 {
  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. public class ConnectivityStateMonitor {
  63. private let stateLock = Lock()
  64. private var _state: ConnectivityState = .idle
  65. private let delegateLock = Lock()
  66. private var _delegate: ConnectivityStateDelegate?
  67. private let delegateCallbackQueue: DispatchQueue
  68. /// Creates a new connectivity state monitor.
  69. ///
  70. /// - Parameter delegate: A delegate to call when the connectivity state changes.
  71. /// - Parameter queue: The `DispatchQueue` on which the delegate will be called.
  72. init(delegate: ConnectivityStateDelegate?, queue: DispatchQueue?) {
  73. self._delegate = delegate
  74. self.delegateCallbackQueue = queue ?? DispatchQueue(label: "io.grpc.connectivity")
  75. }
  76. /// The current state of connectivity.
  77. public var state: ConnectivityState {
  78. return self.stateLock.withLock {
  79. self._state
  80. }
  81. }
  82. /// A delegate to call when the connectivity state changes.
  83. public var delegate: ConnectivityStateDelegate? {
  84. get {
  85. return self.delegateLock.withLock {
  86. return self._delegate
  87. }
  88. }
  89. set {
  90. self.delegateLock.withLockVoid {
  91. self._delegate = newValue
  92. }
  93. }
  94. }
  95. internal func updateState(to newValue: ConnectivityState, logger: Logger) {
  96. let change: (ConnectivityState, ConnectivityState)? = self.stateLock.withLock {
  97. let oldValue = self._state
  98. if oldValue != newValue {
  99. self._state = newValue
  100. return (oldValue, newValue)
  101. } else {
  102. return nil
  103. }
  104. }
  105. if let (oldState, newState) = change {
  106. logger.info("connectivity state change", metadata: [
  107. "old_state": "\(oldState)",
  108. "new_state": "\(newState)",
  109. ])
  110. self.delegateCallbackQueue.async {
  111. if let delegate = self.delegate {
  112. delegate.connectivityStateDidChange(from: oldState, to: newState)
  113. }
  114. }
  115. }
  116. }
  117. internal func beginQuiescing() {
  118. self.delegateCallbackQueue.async {
  119. if let delegate = self.delegate {
  120. delegate.connectionStartedQuiescing()
  121. }
  122. }
  123. }
  124. }