ConnectivityState.swift 5.0 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 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(subsystem: .connectivityState)
  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. public init(delegate: ConnectivityStateDelegate?) {
  60. self._delegate = delegate
  61. }
  62. /// The current state of connectivity.
  63. public internal(set) var state: ConnectivityState {
  64. get {
  65. return self.lock.withLock {
  66. self._state
  67. }
  68. }
  69. set {
  70. self.lock.withLockVoid {
  71. self.setNewState(to: newValue)
  72. }
  73. }
  74. }
  75. /// A delegate to call when the connectivity state changes.
  76. public var delegate: ConnectivityStateDelegate? {
  77. get {
  78. return self.lock.withLock {
  79. return self._delegate
  80. }
  81. }
  82. set {
  83. self.lock.withLockVoid {
  84. self._delegate = newValue
  85. }
  86. }
  87. }
  88. /// Updates `_state` to `newValue`.
  89. ///
  90. /// If the user has initiated shutdown then state updates are _ignored_. This may happen if the
  91. /// connection is being established as the user initiates shutdown.
  92. ///
  93. /// - Important: This is **not** thread safe.
  94. private func setNewState(to newValue: ConnectivityState) {
  95. if self._userInitiatedShutdown {
  96. self.logger.debug("user has initiated shutdown: ignoring new state: \(newValue)")
  97. return
  98. }
  99. let oldValue = self._state
  100. if oldValue != newValue {
  101. self.logger.debug("connectivity state change: \(oldValue) to \(newValue)")
  102. self._state = newValue
  103. self._delegate?.connectivityStateDidChange(from: oldValue, to: newValue)
  104. }
  105. }
  106. /// Initiates a user shutdown.
  107. func initiateUserShutdown() {
  108. self.lock.withLockVoid {
  109. self.logger.debug("user has initiated shutdown")
  110. self.setNewState(to: .shutdown)
  111. self._userInitiatedShutdown = true
  112. }
  113. }
  114. /// Whether the user has initiated a shutdown or not.
  115. var userHasInitiatedShutdown: Bool {
  116. return self.lock.withLock {
  117. return self._userInitiatedShutdown
  118. }
  119. }
  120. /// Whether we can attempt a reconnection, that is the user has not initiated a shutdown and we
  121. /// are in the `.ready` state.
  122. var canAttemptReconnect: Bool {
  123. return self.lock.withLock {
  124. return !self._userInitiatedShutdown && self._state == .ready
  125. }
  126. }
  127. }