2
0

ConnectivityState.swift 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  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. /// A delegate to call when the connectivity state changes.
  52. public var delegate: ConnectivityStateDelegate?
  53. private let logger = Logger(subsystem: .connectivityState)
  54. private let lock = Lock()
  55. private var _state: ConnectivityState = .idle
  56. private var _userInitiatedShutdown = false
  57. /// Creates a new connectivity state monitor.
  58. ///
  59. /// - Parameter delegate: A delegate to call when the connectivity state changes.
  60. public init(delegate: ConnectivityStateDelegate?) {
  61. self.delegate = delegate
  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. /// Updates `_state` to `newValue`.
  77. ///
  78. /// If the user has initiated shutdown then state updates are _ignored_. This may happen if the
  79. /// connection is being estabilshed as the user initiates shutdown.
  80. ///
  81. /// - Important: This is **not** thread safe.
  82. private func setNewState(to newValue: ConnectivityState) {
  83. if self._userInitiatedShutdown {
  84. self.logger.debug("user has initiated shutdown: ignoring new state: \(newValue)")
  85. return
  86. }
  87. let oldValue = self._state
  88. if oldValue != newValue {
  89. self.logger.info("connectivity state change: \(oldValue) to \(newValue)")
  90. self._state = newValue
  91. self.delegate?.connectivityStateDidChange(from: oldValue, to: newValue)
  92. }
  93. }
  94. /// Initiates a user shutdown.
  95. func initiateUserShutdown() {
  96. self.lock.withLockVoid {
  97. self.logger.debug("user has initiated shutdown")
  98. self.setNewState(to: .shutdown)
  99. self._userInitiatedShutdown = true
  100. }
  101. }
  102. /// Whether the user has initiated a shutdown or not.
  103. var userHasInitiatedShutdown: Bool {
  104. return self.lock.withLock {
  105. return self._userInitiatedShutdown
  106. }
  107. }
  108. /// Whether we can attempt a reconnection, that is the user has not initiated a shutdown and we
  109. /// are in the `.ready` state.
  110. var canAttemptReconnect: Bool {
  111. return self.lock.withLock {
  112. return !self._userInitiatedShutdown && self._state == .ready
  113. }
  114. }
  115. }