HeartbeatController.swift 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. // Copyright 2021 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. import Foundation
  15. /// An object that provides API to log and flush heartbeats from a synchronized storage container.
  16. public final class HeartbeatController {
  17. /// The thread-safe storage object to log and flush heartbeats from.
  18. private let storage: HeartbeatStorageProtocol
  19. /// The max capacity of heartbeats to store in storage.
  20. private let heartbeatsStorageCapacity: Int = 30
  21. /// Current date provider. It is used for testability.
  22. private let dateProvider: () -> Date
  23. // TODO: Maybe share config with HeartbeatsPayload's DateFormatter?
  24. /// Used for standardizing dates for calendar-day comparision.
  25. static let dateStandardizer: (Date) -> (Date) = {
  26. var calendar = Calendar(identifier: .iso8601)
  27. calendar.locale = Locale(identifier: "en_US_POSIX")
  28. calendar.timeZone = TimeZone(secondsFromGMT: 0)!
  29. return calendar.startOfDay(for:)
  30. }()
  31. /// Public initializer.
  32. /// - Parameter id: The `id` to associate this controller's heartbeat storage with.
  33. public convenience init(id: String) {
  34. self.init(id: id, dateProvider: Date.init)
  35. }
  36. /// Convenience initializer. Mirrors the semantics of the public intializer with the added benefit of
  37. /// injecting a custom date provider for improved testability.
  38. /// - Parameters:
  39. /// - id: The id to associate this controller's heartbeat storage with.
  40. /// - dateProvider: A date provider.
  41. convenience init(id: String, dateProvider: @escaping () -> Date) {
  42. let storage = HeartbeatStorage.getInstance(id: id)
  43. self.init(storage: storage, dateProvider: dateProvider)
  44. }
  45. /// Designated initializer.
  46. /// - Parameters:
  47. /// - storage: A heartbeat storage container.
  48. /// - dateProvider: A date provider. Defaults to providing the current date.
  49. init(storage: HeartbeatStorageProtocol,
  50. dateProvider: @escaping () -> Date = Date.init) {
  51. self.storage = storage
  52. self.dateProvider = { Self.dateStandardizer(dateProvider()) }
  53. }
  54. /// Asynchronously logs a new heartbeat, if needed.
  55. ///
  56. /// - Note: This API is thread-safe.
  57. /// - Parameter agent: The string agent (i.e. Firebase User Agent) to associate the logged heartbeat with.
  58. public func log(_ agent: String) {
  59. let date = dateProvider()
  60. storage.readAndWriteAsync { heartbeatsBundle in
  61. var heartbeatsBundle = heartbeatsBundle ??
  62. HeartbeatsBundle(capacity: self.heartbeatsStorageCapacity)
  63. // Filter for the time periods where the last heartbeat to be logged for
  64. // that time period was logged more than one time period (i.e. day) ago.
  65. let timePeriods = heartbeatsBundle.lastAddedHeartbeatDates.filter { timePeriod, lastDate in
  66. date.timeIntervalSince(lastDate) >= timePeriod.timeInterval
  67. }
  68. .map { timePeriod, _ in timePeriod }
  69. if !timePeriods.isEmpty {
  70. // A heartbeat should only be logged if there is a time period(s) to
  71. // associate it with.
  72. let heartbeat = Heartbeat(agent: agent, date: date, timePeriods: timePeriods)
  73. heartbeatsBundle.append(heartbeat)
  74. }
  75. return heartbeatsBundle
  76. }
  77. }
  78. /// Synchronously flushes heartbeats from storage into a heartbeats payload.
  79. ///
  80. /// - Note: This API is thread-safe.
  81. /// - Returns: The flushed heartbeats in the form of `HeartbeatsPayload`.
  82. @discardableResult
  83. public func flush() -> HeartbeatsPayload {
  84. let resetTransform = { (heartbeatsBundle: HeartbeatsBundle?) -> HeartbeatsBundle? in
  85. guard let oldHeartbeatsBundle = heartbeatsBundle else {
  86. return nil // Storage was empty.
  87. }
  88. // The new value that's stored will use the old's cache to prevent the
  89. // logging of duplicates after flushing.
  90. return HeartbeatsBundle(
  91. capacity: self.heartbeatsStorageCapacity,
  92. cache: oldHeartbeatsBundle.lastAddedHeartbeatDates
  93. )
  94. }
  95. // Synchronously gets and returns the stored heartbeats, resetting storage
  96. // using the given transform. If the operation throws, assume no
  97. // heartbeat(s) were retrieved or set.
  98. if let heartbeatsBundle = try? storage.getAndSet(using: resetTransform) {
  99. return heartbeatsBundle.makeHeartbeatsPayload()
  100. } else {
  101. return HeartbeatsPayload.emptyPayload
  102. }
  103. }
  104. /// Synchronously flushes the heartbeat for today.
  105. ///
  106. /// If no heartbeat was logged today, the returned payload is empty.
  107. ///
  108. /// - Note: This API is thread-safe.
  109. /// - Returns: A heartbeats payload for the flushed heartbeat.
  110. @discardableResult
  111. public func flushHeartbeatFromToday() -> HeartbeatsPayload {
  112. let todaysDate = dateProvider()
  113. var todaysHeartbeat: Heartbeat?
  114. storage.readAndWriteSync { heartbeatsBundle in
  115. guard var heartbeatsBundle = heartbeatsBundle else {
  116. return nil // Storage was empty.
  117. }
  118. todaysHeartbeat = heartbeatsBundle.removeHeartbeat(from: todaysDate)
  119. return heartbeatsBundle
  120. }
  121. // Note that `todaysHeartbeat` is updated in the above read/write block.
  122. if todaysHeartbeat != nil {
  123. return todaysHeartbeat!.makeHeartbeatsPayload()
  124. } else {
  125. return HeartbeatsPayload.emptyPayload
  126. }
  127. }
  128. }