HeartbeatController.swift 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  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. /// Used for standardizing dates for calendar-day comparison.
  18. private enum DateStandardizer {
  19. private static let calendar: Calendar = {
  20. var calendar = Calendar(identifier: .iso8601)
  21. calendar.locale = Locale(identifier: "en_US_POSIX")
  22. calendar.timeZone = TimeZone(secondsFromGMT: 0)!
  23. return calendar
  24. }()
  25. static func standardize(_ date: Date) -> (Date) {
  26. return calendar.startOfDay(for: date)
  27. }
  28. }
  29. /// The thread-safe storage object to log and flush heartbeats from.
  30. private let storage: HeartbeatStorageProtocol
  31. /// The max capacity of heartbeats to store in storage.
  32. private let heartbeatsStorageCapacity: Int = 30
  33. /// Current date provider. It is used for testability.
  34. private let dateProvider: () -> Date
  35. /// Used for standardizing dates for calendar-day comparison.
  36. private static let dateStandardizer = DateStandardizer.self
  37. /// Public initializer.
  38. /// - Parameter id: The `id` to associate this controller's heartbeat storage with.
  39. public convenience init(id: String) {
  40. self.init(id: id, dateProvider: Date.init)
  41. }
  42. /// Convenience initializer. Mirrors the semantics of the public initializer with the added
  43. /// benefit of
  44. /// injecting a custom date provider for improved testability.
  45. /// - Parameters:
  46. /// - id: The id to associate this controller's heartbeat storage with.
  47. /// - dateProvider: A date provider.
  48. convenience init(id: String, dateProvider: @escaping () -> Date) {
  49. let storage = HeartbeatStorage.getInstance(id: id)
  50. self.init(storage: storage, dateProvider: dateProvider)
  51. }
  52. /// Designated initializer.
  53. /// - Parameters:
  54. /// - storage: A heartbeat storage container.
  55. /// - dateProvider: A date provider. Defaults to providing the current date.
  56. init(storage: HeartbeatStorageProtocol,
  57. dateProvider: @escaping () -> Date = Date.init) {
  58. self.storage = storage
  59. self.dateProvider = { Self.dateStandardizer.standardize(dateProvider()) }
  60. }
  61. /// Asynchronously logs a new heartbeat, if needed.
  62. ///
  63. /// - Note: This API is thread-safe.
  64. /// - Parameter agent: The string agent (i.e. Firebase User Agent) to associate the logged
  65. /// heartbeat with.
  66. public func log(_ agent: String) {
  67. let date = dateProvider()
  68. storage.readAndWriteAsync { heartbeatsBundle in
  69. var heartbeatsBundle = heartbeatsBundle ??
  70. HeartbeatsBundle(capacity: self.heartbeatsStorageCapacity)
  71. // Filter for the time periods where the last heartbeat to be logged for
  72. // that time period was logged more than one time period (i.e. day) ago.
  73. let timePeriods = heartbeatsBundle.lastAddedHeartbeatDates.filter { timePeriod, lastDate in
  74. date.timeIntervalSince(lastDate) >= timePeriod.timeInterval
  75. }
  76. .map { timePeriod, _ in timePeriod }
  77. if !timePeriods.isEmpty {
  78. // A heartbeat should only be logged if there is a time period(s) to
  79. // associate it with.
  80. let heartbeat = Heartbeat(agent: agent, date: date, timePeriods: timePeriods)
  81. heartbeatsBundle.append(heartbeat)
  82. }
  83. return heartbeatsBundle
  84. }
  85. }
  86. /// Synchronously flushes heartbeats from storage into a heartbeats payload.
  87. ///
  88. /// - Note: This API is thread-safe.
  89. /// - Returns: The flushed heartbeats in the form of `HeartbeatsPayload`.
  90. @discardableResult
  91. public func flush() -> HeartbeatsPayload {
  92. let resetTransform = { (heartbeatsBundle: HeartbeatsBundle?) -> HeartbeatsBundle? in
  93. guard let oldHeartbeatsBundle = heartbeatsBundle else {
  94. return nil // Storage was empty.
  95. }
  96. // The new value that's stored will use the old's cache to prevent the
  97. // logging of duplicates after flushing.
  98. return HeartbeatsBundle(
  99. capacity: self.heartbeatsStorageCapacity,
  100. cache: oldHeartbeatsBundle.lastAddedHeartbeatDates
  101. )
  102. }
  103. do {
  104. // Synchronously gets and returns the stored heartbeats, resetting storage
  105. // using the given transform.
  106. let heartbeatsBundle = try storage.getAndSet(using: resetTransform)
  107. // If no heartbeats bundle was stored, return an empty payload.
  108. return heartbeatsBundle?.makeHeartbeatsPayload() ?? HeartbeatsPayload.emptyPayload
  109. } catch {
  110. // If the operation throws, assume no heartbeat(s) were retrieved or set.
  111. return HeartbeatsPayload.emptyPayload
  112. }
  113. }
  114. /// Synchronously flushes the heartbeat for today.
  115. ///
  116. /// If no heartbeat was logged today, the returned payload is empty.
  117. ///
  118. /// - Note: This API is thread-safe.
  119. /// - Returns: A heartbeats payload for the flushed heartbeat.
  120. @discardableResult
  121. public func flushHeartbeatFromToday() -> HeartbeatsPayload {
  122. let todaysDate = dateProvider()
  123. var todaysHeartbeat: Heartbeat?
  124. storage.readAndWriteSync { heartbeatsBundle in
  125. guard var heartbeatsBundle = heartbeatsBundle else {
  126. return nil // Storage was empty.
  127. }
  128. todaysHeartbeat = heartbeatsBundle.removeHeartbeat(from: todaysDate)
  129. return heartbeatsBundle
  130. }
  131. // Note that `todaysHeartbeat` is updated in the above read/write block.
  132. if todaysHeartbeat != nil {
  133. return todaysHeartbeat!.makeHeartbeatsPayload()
  134. } else {
  135. return HeartbeatsPayload.emptyPayload
  136. }
  137. }
  138. }