HeartbeatController.swift 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  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. /// Used for standardizing dates for calendar-day comparision.
  24. static let dateStandardizer: (Date) -> (Date) = {
  25. var calendar = Calendar(identifier: .iso8601)
  26. calendar.locale = Locale(identifier: "en_US_POSIX")
  27. calendar.timeZone = TimeZone(secondsFromGMT: 0)!
  28. return calendar.startOfDay(for:)
  29. }()
  30. /// Public initializer.
  31. /// - Parameter id: The `id` to associate this controller's heartbeat storage with.
  32. public convenience init(id: String) {
  33. self.init(id: id, dateProvider: Date.init)
  34. }
  35. /// Convenience initializer. Mirrors the semantics of the public initializer with the added
  36. /// 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
  58. /// heartbeat with.
  59. public func log(_ agent: String) {
  60. let date = dateProvider()
  61. storage.readAndWriteAsync { heartbeatsBundle in
  62. var heartbeatsBundle = heartbeatsBundle ??
  63. HeartbeatsBundle(capacity: self.heartbeatsStorageCapacity)
  64. // Filter for the time periods where the last heartbeat to be logged for
  65. // that time period was logged more than one time period (i.e. day) ago.
  66. let timePeriods = heartbeatsBundle.lastAddedHeartbeatDates.filter { timePeriod, lastDate in
  67. date.timeIntervalSince(lastDate) >= timePeriod.timeInterval
  68. }
  69. .map { timePeriod, _ in timePeriod }
  70. if !timePeriods.isEmpty {
  71. // A heartbeat should only be logged if there is a time period(s) to
  72. // associate it with.
  73. let heartbeat = Heartbeat(agent: agent, date: date, timePeriods: timePeriods)
  74. heartbeatsBundle.append(heartbeat)
  75. }
  76. return heartbeatsBundle
  77. }
  78. }
  79. /// Synchronously flushes heartbeats from storage into a heartbeats payload.
  80. ///
  81. /// - Note: This API is thread-safe.
  82. /// - Returns: The flushed heartbeats in the form of `HeartbeatsPayload`.
  83. @discardableResult
  84. public func flush() -> HeartbeatsPayload {
  85. let resetTransform = { (heartbeatsBundle: HeartbeatsBundle?) -> HeartbeatsBundle? in
  86. guard let oldHeartbeatsBundle = heartbeatsBundle else {
  87. return nil // Storage was empty.
  88. }
  89. // The new value that's stored will use the old's cache to prevent the
  90. // logging of duplicates after flushing.
  91. return HeartbeatsBundle(
  92. capacity: self.heartbeatsStorageCapacity,
  93. cache: oldHeartbeatsBundle.lastAddedHeartbeatDates
  94. )
  95. }
  96. do {
  97. // Synchronously gets and returns the stored heartbeats, resetting storage
  98. // using the given transform.
  99. let heartbeatsBundle = try storage.getAndSet(using: resetTransform)
  100. // If no heartbeats bundle was stored, return an empty payload.
  101. return heartbeatsBundle?.makeHeartbeatsPayload() ?? HeartbeatsPayload.emptyPayload
  102. } catch {
  103. // If the operation throws, assume no heartbeat(s) were retrieved or set.
  104. return HeartbeatsPayload.emptyPayload
  105. }
  106. }
  107. /// Synchronously flushes the heartbeat for today.
  108. ///
  109. /// If no heartbeat was logged today, the returned payload is empty.
  110. ///
  111. /// - Note: This API is thread-safe.
  112. /// - Returns: A heartbeats payload for the flushed heartbeat.
  113. @discardableResult
  114. public func flushHeartbeatFromToday() -> HeartbeatsPayload {
  115. let todaysDate = dateProvider()
  116. var todaysHeartbeat: Heartbeat?
  117. storage.readAndWriteSync { heartbeatsBundle in
  118. guard var heartbeatsBundle = heartbeatsBundle else {
  119. return nil // Storage was empty.
  120. }
  121. todaysHeartbeat = heartbeatsBundle.removeHeartbeat(from: todaysDate)
  122. return heartbeatsBundle
  123. }
  124. // Note that `todaysHeartbeat` is updated in the above read/write block.
  125. if todaysHeartbeat != nil {
  126. return todaysHeartbeat!.makeHeartbeatsPayload()
  127. } else {
  128. return HeartbeatsPayload.emptyPayload
  129. }
  130. }
  131. }