HTTP2Connections.swift 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. /*
  2. * Copyright 2021, 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 Logging
  17. import NIO
  18. import NIOHTTP2
  19. internal struct HTTP2Connections {
  20. // TODO: The number of connections is likely to be low and insertions and deletions should be
  21. // infrequent. We may benefit from using an array and doing linear scans instead.
  22. private var connections: [ObjectIdentifier: HTTP2ConnectionState]
  23. /// Returns the number of connections.
  24. internal var count: Int {
  25. return self.connections.count
  26. }
  27. /// The maximum number of connections which may be stored.
  28. private let capacity: Int
  29. internal init(capacity: Int) {
  30. self.connections = [:]
  31. self.capacity = capacity
  32. self.connections.reserveCapacity(capacity)
  33. }
  34. /// Insert a connection.
  35. ///
  36. /// - Important: A connection with the same `id` must not already exist in the collection, and
  37. /// a connection may only be inserted if the number of connections is less than its capacity.
  38. /// - Parameter connection: The connection state to add.
  39. internal mutating func insert(_ connection: HTTP2ConnectionState) {
  40. assert(self.count < self.capacity)
  41. let oldValue = self.connections.updateValue(connection, forKey: connection.id)
  42. precondition(oldValue == nil)
  43. }
  44. /// Remove a connection with the given ID.
  45. ///
  46. /// - Parameter id: The ID of the connection to remove.
  47. /// - Returns: The connection, if one matching the given ID was returned.
  48. @discardableResult
  49. internal mutating func removeConnection(withID id: ObjectIdentifier) -> HTTP2ConnectionState? {
  50. return self.connections.removeValue(forKey: id)
  51. }
  52. /// Remove all connections
  53. internal mutating func removeAll() {
  54. self.connections.removeAll()
  55. }
  56. /// Returns the ID of the first connection matching the predicate, if one exists.
  57. internal func firstConnectionID(
  58. where predicate: (HTTP2ConnectionState) -> Bool
  59. ) -> ObjectIdentifier? {
  60. return self.connections.first { _, value in
  61. predicate(value)
  62. }?.key
  63. }
  64. // MARK: - Tokens
  65. /// Returns the number of tokens available for the connection with the given ID.
  66. ///
  67. /// Only active connections may have tokens available, idle connections or those actively
  68. /// connecting have zero tokens available.
  69. ///
  70. /// - Parameter id: The ID of the connection to return the number of available tokens for.
  71. /// - Returns: The number of tokens available for the connection identified by the given `id`
  72. /// or `nil` if no such connection exists.
  73. internal func availableTokensForConnection(withID id: ObjectIdentifier) -> Int? {
  74. return self.connections[id]?.availableTokens
  75. }
  76. /// Borrow tokens from the connection identified by `id`.
  77. ///
  78. /// - Precondition: A connection must exist with the given `id`.
  79. /// - Precondition: `count` must be greater than zero and must not exceed the tokens available for
  80. /// the connection.
  81. /// - Parameters:
  82. /// - count: The number of tokens to borrow.
  83. /// - id: The `id` of the connection to borrow tokens from.
  84. /// - Returns: The connection's HTTP/2 multiplexer and the total number of tokens currently
  85. /// borrowed from the connection.
  86. internal mutating func borrowTokens(
  87. _ count: Int,
  88. fromConnectionWithID id: ObjectIdentifier
  89. ) -> (HTTP2StreamMultiplexer, borrowedTokens: Int) {
  90. return self.connections[id]!.borrowTokens(count)
  91. }
  92. /// Return a single token to the connection with the given identifier.
  93. ///
  94. /// - Parameter id: The `id` of the connection to return a token to.
  95. internal mutating func returnTokenToConnection(withID id: ObjectIdentifier) {
  96. self.connections[id]?.returnToken()
  97. }
  98. /// Update the maximum number of tokens a connection may lend at a given time.
  99. ///
  100. /// - Parameters:
  101. /// - maximumTokens: The maximum number of tokens the connection may vend,
  102. /// - id: The `id` of the connection the new limit applies to.
  103. /// - Returns: The previous maximum token limit if the connection exists.
  104. internal mutating func updateMaximumAvailableTokens(
  105. _ maximumTokens: Int,
  106. forConnectionWithID id: ObjectIdentifier
  107. ) -> Int? {
  108. return self.connections[id]?.updateMaximumTokens(maximumTokens)
  109. }
  110. /// Start connecting the connection with the given `id`.
  111. ///
  112. /// - Parameters:
  113. /// - id: The `id` of the connection to start.
  114. /// - multiplexerFactory: A closure which returns an `EventLoopFuture<HTTP2StreamMultiplexer>`.
  115. /// - onConnected: A closure to execute when the connection has successfully been established.
  116. internal mutating func startConnection(
  117. withID id: ObjectIdentifier,
  118. http2StreamMultiplexerFactory multiplexerFactory: () -> EventLoopFuture<HTTP2StreamMultiplexer>,
  119. whenConnected onConnected: @escaping (HTTP2StreamMultiplexer) -> Void
  120. ) {
  121. self.connections[id]?.willStartConnecting()
  122. multiplexerFactory().whenSuccess(onConnected)
  123. }
  124. /// Update the state of the connection identified by `id` to 'ready'.
  125. internal mutating func connectionIsReady(
  126. withID id: ObjectIdentifier,
  127. multiplexer: HTTP2StreamMultiplexer
  128. ) {
  129. self.connections[id]?.connected(multiplexer: multiplexer)
  130. }
  131. /// Update connectivity state of the connection identified by `id`.
  132. ///
  133. /// - Parameters:
  134. /// - state: The new state of the underlying connection.
  135. /// - id: The `id` of the connection whose state has changed.
  136. /// - Returns: An action to perform as a result of the state change.
  137. internal mutating func updateConnectivityState(
  138. _ state: ConnectivityState,
  139. forConnectionWithID id: ObjectIdentifier
  140. ) -> HTTP2ConnectionState.StateChangeAction? {
  141. return self.connections[id]?.connectivityStateChanged(to: state)
  142. }
  143. }