PoolManagerStateMachine+PerPoolState.swift 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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 NIOCore
  17. extension PoolManagerStateMachine.ActiveState {
  18. internal struct PerPoolState {
  19. /// The index of the connection pool associated with this state.
  20. internal var poolIndex: PoolManager.ConnectionPoolIndex
  21. /// The number of streams reserved in the pool.
  22. internal private(set) var reservedStreams: Int
  23. /// The total number of streams which may be available in the pool.
  24. internal var maxAvailableStreams: Int
  25. /// The number of available streams.
  26. internal var availableStreams: Int {
  27. return self.maxAvailableStreams - self.reservedStreams
  28. }
  29. init(poolIndex: PoolManager.ConnectionPoolIndex, assumedMaxAvailableStreams: Int) {
  30. self.poolIndex = poolIndex
  31. self.reservedStreams = 0
  32. self.maxAvailableStreams = assumedMaxAvailableStreams
  33. }
  34. /// Reserve a stream and return the pool.
  35. internal mutating func reserveStream() -> PoolManager.ConnectionPoolIndex {
  36. self.reservedStreams += 1
  37. return self.poolIndex
  38. }
  39. /// Return a reserved stream.
  40. internal mutating func returnReservedStreams(_ count: Int) {
  41. self.reservedStreams -= count
  42. assert(self.reservedStreams >= 0)
  43. }
  44. }
  45. }
  46. extension PoolManager {
  47. internal struct ConnectionPoolIndex: Hashable {
  48. var value: Int
  49. init(_ value: Int) {
  50. self.value = value
  51. }
  52. }
  53. internal struct ConnectionPoolKey: Hashable {
  54. /// The index of the connection pool.
  55. var index: ConnectionPoolIndex
  56. /// The ID of the`EventLoop` the connection pool uses.
  57. var eventLoopID: EventLoopID
  58. }
  59. }
  60. internal struct EventLoopID: Hashable, CustomStringConvertible {
  61. private let id: ObjectIdentifier
  62. internal init(_ eventLoop: EventLoop) {
  63. self.id = ObjectIdentifier(eventLoop)
  64. }
  65. internal var description: String {
  66. return String(describing: self.id)
  67. }
  68. }
  69. extension EventLoop {
  70. internal var id: EventLoopID {
  71. return EventLoopID(self)
  72. }
  73. }