ConnectivityState.swift 4.5 KB

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