RPCStats.swift 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. /*
  2. * Copyright 2024, 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 GRPCCore
  18. import NIOConcurrencyHelpers
  19. /// Stores the real time latency histogram and error code count dictionary,
  20. /// for the RPCs made by a particular GRPCClient. It gets updated after
  21. /// each finished RPC.
  22. ///
  23. /// The time latency is measured in nanoseconds.
  24. struct RPCStats {
  25. var latencyHistogram: LatencyHistogram
  26. var requestResultCount: [RPCError.Code: Int64]
  27. init(latencyHistogram: LatencyHistogram, requestResultCount: [RPCError.Code: Int64] = [:]) {
  28. self.latencyHistogram = latencyHistogram
  29. self.requestResultCount = requestResultCount
  30. }
  31. /// Histograms are stored with exponentially increasing bucket sizes.
  32. /// The first bucket is [0, `multiplier`) where `multiplier` = 1 + resolution
  33. /// Bucket n (n>=1) contains [`multiplier`**n, `multiplier`**(n+1))
  34. /// There are sufficient buckets to reach max_bucket_start
  35. struct LatencyHistogram {
  36. var sum: Double
  37. var sumOfSquares: Double
  38. var countOfValuesSeen: Double
  39. var multiplier: Double
  40. var oneOnLogMultiplier: Double
  41. var minSeen: Double
  42. var maxSeen: Double
  43. var maxPossible: Double
  44. var buckets: [UInt32]
  45. /// Initialise a histogram.
  46. /// - parameters:
  47. /// - resolution: Defines the width of the buckets - see the description of this structure.
  48. /// - maxBucketStart: Defines the start of the greatest valued bucket.
  49. init(resolution: Double = 0.01, maxBucketStart: Double = 60e9) {
  50. precondition(resolution > 0.0)
  51. precondition(maxBucketStart > resolution)
  52. self.sum = 0.0
  53. self.sumOfSquares = 0.0
  54. self.multiplier = 1.0 + resolution
  55. self.oneOnLogMultiplier = 1.0 / log(1.0 + resolution)
  56. self.maxPossible = maxBucketStart
  57. self.countOfValuesSeen = 0.0
  58. self.minSeen = maxBucketStart
  59. self.maxSeen = 0.0
  60. let numBuckets =
  61. LatencyHistogram.uncheckedBucket(
  62. forValue: maxBucketStart,
  63. oneOnLogMultiplier: self.oneOnLogMultiplier
  64. ) + 1
  65. precondition(numBuckets > 1)
  66. precondition(numBuckets < 100_000_000)
  67. self.buckets = .init(repeating: 0, count: numBuckets)
  68. }
  69. struct HistorgramShapeMismatch: Error {}
  70. /// Determine a bucket index given a value - does no bounds checking
  71. private static func uncheckedBucket(forValue value: Double, oneOnLogMultiplier: Double) -> Int {
  72. return Int(log(value) * oneOnLogMultiplier)
  73. }
  74. private func bucket(forValue value: Double) -> Int {
  75. let bucket = LatencyHistogram.uncheckedBucket(
  76. forValue: min(self.maxPossible, max(0, value)),
  77. oneOnLogMultiplier: self.oneOnLogMultiplier
  78. )
  79. assert(bucket < self.buckets.count)
  80. assert(bucket >= 0)
  81. return bucket
  82. }
  83. /// Add a value to this histogram, updating buckets and stats
  84. /// - parameters:
  85. /// - value: The value to add.
  86. public mutating func record(_ value: Double) {
  87. self.sum += value
  88. self.sumOfSquares += value * value
  89. self.countOfValuesSeen += 1
  90. if value < self.minSeen {
  91. self.minSeen = value
  92. }
  93. if value > self.maxSeen {
  94. self.maxSeen = value
  95. }
  96. self.buckets[self.bucket(forValue: value)] += 1
  97. }
  98. /// Merge two histograms together updating `self`
  99. /// - parameters:
  100. /// - other: the other histogram to merge into this.
  101. public mutating func merge(_ other: LatencyHistogram) throws {
  102. guard (self.buckets.count == other.buckets.count) || (self.multiplier == other.multiplier)
  103. else {
  104. // Fail because these histograms don't match.
  105. throw HistorgramShapeMismatch()
  106. }
  107. self.sum += other.sum
  108. self.sumOfSquares += other.sumOfSquares
  109. self.countOfValuesSeen += other.countOfValuesSeen
  110. if other.minSeen < self.minSeen {
  111. self.minSeen = other.minSeen
  112. }
  113. if other.maxSeen > self.maxSeen {
  114. self.maxSeen = other.maxSeen
  115. }
  116. for bucket in 0 ..< self.buckets.count {
  117. self.buckets[bucket] += other.buckets[bucket]
  118. }
  119. }
  120. }
  121. @available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
  122. mutating func merge(_ other: RPCStats) throws {
  123. try self.latencyHistogram.merge(
  124. other.latencyHistogram
  125. )
  126. self.requestResultCount.merge(other.requestResultCount) { (current, new) in
  127. current + new
  128. }
  129. }
  130. }