ConnectivityState.swift 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  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 NIOConcurrencyHelpers
  18. import Logging
  19. /// The connectivity state of a client connection. Note that this is heavily lifted from the gRPC
  20. /// documentation: https://github.com/grpc/grpc/blob/master/doc/connectivity-semantics-and-api.md.
  21. public enum ConnectivityState {
  22. /// This is the state where the channel has not yet been created.
  23. case idle
  24. /// The channel is trying to establish a connection and is waiting to make progress on one of the
  25. /// steps involved in name resolution, TCP connection establishment or TLS handshake.
  26. case connecting
  27. /// The channel has successfully established a connection all the way through TLS handshake (or
  28. /// equivalent) and protocol-level (HTTP/2, etc) handshaking.
  29. case ready
  30. /// There has been some transient failure (such as a TCP 3-way handshake timing out or a socket
  31. /// error). Channels in this state will eventually switch to the `.connecting` state and try to
  32. /// establish a connection again. Since retries are done with exponential backoff, channels that
  33. /// fail to connect will start out spending very little time in this state but as the attempts
  34. /// fail repeatedly, the channel will spend increasingly large amounts of time in this state.
  35. case transientFailure
  36. /// This channel has started shutting down. Any new RPCs should fail immediately. Pending RPCs
  37. /// may continue running till the application cancels them. Channels may enter this state either
  38. /// because the application explicitly requested a shutdown or if a non-recoverable error has
  39. /// happened during attempts to connect. Channels that have entered this state will never leave
  40. /// this state.
  41. case shutdown
  42. }
  43. public protocol ConnectivityStateDelegate: class {
  44. /// Called when a change in `ConnectivityState` has occurred.
  45. ///
  46. /// - Parameter oldState: The old connectivity state.
  47. /// - Parameter newState: The new connectivity state.
  48. func connectivityStateDidChange(from oldState: ConnectivityState, to newState: ConnectivityState)
  49. }
  50. public class ConnectivityStateMonitor {
  51. private let logger: Logger
  52. private let lock = Lock()
  53. private var _state: ConnectivityState = .idle
  54. private var _userInitiatedShutdown = false
  55. private var _delegate: ConnectivityStateDelegate?
  56. /// Creates a new connectivity state monitor.
  57. ///
  58. /// - Parameter delegate: A delegate to call when the connectivity state changes.
  59. init(delegate: ConnectivityStateDelegate?, logger: Logger) {
  60. self._delegate = delegate
  61. self.logger = logger
  62. }
  63. /// The current state of connectivity.
  64. public internal(set) var state: ConnectivityState {
  65. get {
  66. return self.lock.withLock {
  67. self._state
  68. }
  69. }
  70. set {
  71. self.lock.withLockVoid {
  72. self.setNewState(to: newValue)
  73. }
  74. }
  75. }
  76. /// A delegate to call when the connectivity state changes.
  77. public var delegate: ConnectivityStateDelegate? {
  78. get {
  79. return self.lock.withLock {
  80. return self._delegate
  81. }
  82. }
  83. set {
  84. self.lock.withLockVoid {
  85. self._delegate = newValue
  86. }
  87. }
  88. }
  89. /// Updates `_state` to `newValue`.
  90. ///
  91. /// If the user has initiated shutdown then state updates are _ignored_. This may happen if the
  92. /// connection is being established as the user initiates shutdown.
  93. ///
  94. /// - Important: This is **not** thread safe.
  95. private func setNewState(to newValue: ConnectivityState) {
  96. if self._userInitiatedShutdown {
  97. self.logger.debug("user has initiated shutdown: ignoring new state", metadata: ["new_state": "\(newValue)"])
  98. return
  99. }
  100. let oldValue = self._state
  101. if oldValue != newValue {
  102. self.logger.debug("connectivity state change", metadata: ["old_state": "\(oldValue)", "new_state": "\(newValue)"])
  103. self._state = newValue
  104. self._delegate?.connectivityStateDidChange(from: oldValue, to: newValue)
  105. }
  106. }
  107. /// Initiates a user shutdown.
  108. func initiateUserShutdown() {
  109. self.lock.withLockVoid {
  110. self.logger.debug("user has initiated shutdown")
  111. self.setNewState(to: .shutdown)
  112. self._userInitiatedShutdown = true
  113. }
  114. }
  115. /// Whether the user has initiated a shutdown or not.
  116. var userHasInitiatedShutdown: Bool {
  117. return self.lock.withLock {
  118. return self._userInitiatedShutdown
  119. }
  120. }
  121. /// Whether we can attempt a reconnection, that is the user has not initiated a shutdown and we
  122. /// are in the `.ready` state.
  123. var canAttemptReconnect: Bool {
  124. return self.lock.withLock {
  125. return !self._userInitiatedShutdown && self._state == .ready
  126. }
  127. }
  128. }