HeartbeatController.swift 5.6 KB

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