ConnectivityState.swift 4.4 KB

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