Stats.swift 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /*
  2. * Copyright 2020, 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 BenchmarkUtils
  17. import NIOConcurrencyHelpers
  18. /// Convenience holder for collected statistics.
  19. struct Stats {
  20. /// Latency statistics.
  21. var latencies = Histogram()
  22. /// Error status counts.
  23. var statuses = StatusCounts()
  24. }
  25. /// Stats with access controlled by a lock -
  26. /// Needs locking rather than event loop hopping as the driver refuses to wait shutting
  27. /// the connection immediately after the request.
  28. /// Marked `@unchecked Sendable` since we control access to `data` via a Lock.
  29. final class StatsWithLock: @unchecked Sendable {
  30. private var data = Stats()
  31. private let lock = Lock()
  32. /// Record a latency value into the stats.
  33. /// - parameters:
  34. /// - latency: The value to record.
  35. func add(latency: Double) {
  36. self.lock.withLockVoid { self.data.latencies.add(value: latency) }
  37. }
  38. func add(latency: Nanoseconds) {
  39. self.add(latency: Double(latency.value))
  40. }
  41. /// Copy the data out.
  42. /// - parameters:
  43. /// - reset: If the statistics should be reset after collection or not.
  44. /// - returns: A copy of the statistics.
  45. func copyData(reset: Bool) -> Stats {
  46. return self.lock.withLock {
  47. let result = self.data
  48. if reset {
  49. self.data = Stats()
  50. }
  51. return result
  52. }
  53. }
  54. }