HeartbeatStorage.swift 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  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. /// A type that can perform atomic operations using block-based transformations.
  16. protocol HeartbeatStorageProtocol {
  17. func readAndWriteSync(using transform: (HeartbeatsBundle?) -> HeartbeatsBundle?)
  18. func readAndWriteAsync(using transform: @escaping (HeartbeatsBundle?) -> HeartbeatsBundle?)
  19. func getAndSet(using transform: (HeartbeatsBundle?) -> HeartbeatsBundle?) throws
  20. -> HeartbeatsBundle?
  21. }
  22. /// Thread-safe storage object designed for transforming heartbeat data that is persisted to disk.
  23. final class HeartbeatStorage: HeartbeatStorageProtocol {
  24. /// The identifier used to differentiate instances.
  25. private let id: String
  26. /// The underlying storage container to read from and write to.
  27. private let storage: Storage
  28. /// The encoder used for encoding heartbeat data.
  29. private let encoder: JSONEncoder = .init()
  30. /// The decoder used for decoding heartbeat data.
  31. private let decoder: JSONDecoder = .init()
  32. /// The queue for synchronizing storage operations.
  33. private let queue: DispatchQueue
  34. /// Designated initializer.
  35. /// - Parameters:
  36. /// - id: A string identifer.
  37. /// - storage: The underlying storage container where heartbeat data is stored.
  38. init(id: String,
  39. storage: Storage) {
  40. self.id = id
  41. self.storage = storage
  42. queue = DispatchQueue(label: "com.heartbeat.storage.\(id)")
  43. }
  44. // MARK: - Instance Management
  45. /// Statically allocated cache of `HeartbeatStorage` instances keyed by string IDs.
  46. private static var cachedInstances: [String: WeakContainer<HeartbeatStorage>] = [:]
  47. /// Gets an existing `HeartbeatStorage` instance with the given `id` if one exists. Otherwise,
  48. /// makes a new instance with the given `id`.
  49. ///
  50. /// - Parameter id: A string identifier.
  51. /// - Returns: A `HeartbeatStorage` instance.
  52. static func getInstance(id: String) -> HeartbeatStorage {
  53. if let cachedInstance = cachedInstances[id]?.object {
  54. return cachedInstance
  55. } else {
  56. let newInstance = HeartbeatStorage.makeHeartbeatStorage(id: id)
  57. cachedInstances[id] = WeakContainer(object: newInstance)
  58. return newInstance
  59. }
  60. }
  61. /// Makes a `HeartbeatStorage` instance using a given `String` identifier.
  62. ///
  63. /// The created persistent storage object is platform dependent. For tvOS, user defaults
  64. /// is used as the underlying storage container due to system storage limits. For all other platforms,
  65. /// the file system is used.
  66. ///
  67. /// - Parameter id: A `String` identifier used to create the `HeartbeatStorage`.
  68. /// - Returns: A `HeartbeatStorage` instance.
  69. private static func makeHeartbeatStorage(id: String) -> HeartbeatStorage {
  70. #if os(tvOS)
  71. let storage = UserDefaultsStorage.makeStorage(id: id)
  72. #else
  73. let storage = FileStorage.makeStorage(id: id)
  74. #endif // os(tvOS)
  75. return HeartbeatStorage(id: id, storage: storage)
  76. }
  77. deinit {
  78. // Removes the instance if it was cached.
  79. Self.cachedInstances.removeValue(forKey: id)
  80. }
  81. // MARK: - HeartbeatStorageProtocol
  82. // TODO: Document.
  83. func readAndWriteSync(using transform: (HeartbeatsBundle?) -> HeartbeatsBundle?) {
  84. queue.sync {
  85. let oldHeartbeatsBundle = try? load(from: storage)
  86. let newHeartbeatsBundle = transform(oldHeartbeatsBundle)
  87. try? save(newHeartbeatsBundle, to: storage)
  88. }
  89. }
  90. /// Asynchronously reads from and writes to storage using the given transform block.
  91. /// - Parameter transform: A block to transform the currently stored heartbeats bundle to a new
  92. /// heartbeats bundle value.
  93. func readAndWriteAsync(using transform: @escaping (HeartbeatsBundle?) -> HeartbeatsBundle?) {
  94. queue.async { [self] in
  95. let oldHeartbeatsBundle = try? load(from: storage)
  96. let newHeartbeatsBundle = transform(oldHeartbeatsBundle)
  97. try? save(newHeartbeatsBundle, to: storage)
  98. }
  99. }
  100. /// Synchronously gets the current heartbeat data from storage and resets the storage using the
  101. /// given transform block.
  102. ///
  103. /// This API is like any `getAndSet`-style API in that it gets (and returns) the current value and uses
  104. /// a block to transform the current value (or, soon-to-be old value) to a new value.
  105. ///
  106. /// - Parameter transform: An optional block used to reset the currently stored heartbeat.
  107. /// - Returns: The heartbeat data that was stored (before the `transform` was applied).
  108. @discardableResult
  109. func getAndSet(using transform: (HeartbeatsBundle?) -> HeartbeatsBundle?) throws
  110. -> HeartbeatsBundle? {
  111. let heartbeatsBundle: HeartbeatsBundle? = try queue.sync {
  112. let oldHeartbeatsBundle = try? load(from: storage)
  113. let newHeartbeatsBundle = transform(oldHeartbeatsBundle)
  114. try save(newHeartbeatsBundle, to: storage)
  115. return oldHeartbeatsBundle
  116. }
  117. return heartbeatsBundle
  118. }
  119. /// Loads and decodes the stored heartbeats bundle from a given storage object.
  120. /// - Parameter storage: The storage container to read from.
  121. /// - Returns: The decoded `HeartbeatsBundle` that is loaded from storage.
  122. private func load(from storage: Storage) throws -> HeartbeatsBundle {
  123. let data = try storage.read()
  124. let heartbeatData = try data.decoded(using: decoder) as HeartbeatsBundle
  125. return heartbeatData
  126. }
  127. /// Saves the encoding of the given value to the given storage container.
  128. /// - Parameters:
  129. /// - heartbeatsBundle: The heartbeats bundle to encode and save.
  130. /// - storage: The storage container to write to.
  131. private func save(_ heartbeatsBundle: HeartbeatsBundle?, to storage: Storage) throws {
  132. if let heartbeatsBundle = heartbeatsBundle {
  133. let data = try heartbeatsBundle.encoded(using: encoder)
  134. try storage.write(data)
  135. } else {
  136. try storage.write(nil)
  137. }
  138. }
  139. }
  140. private extension Data {
  141. /// Returns the decoded value of this `Data` using the given decoder. Defaults to `JSONDecoder`.
  142. /// - Returns: The decoded value.
  143. func decoded<T>(using decoder: JSONDecoder = .init()) throws -> T where T: Decodable {
  144. try decoder.decode(T.self, from: self)
  145. }
  146. }
  147. private extension Encodable {
  148. /// Returns the `Data` encoding of this value using the given encoder.
  149. /// - Parameter encoder: An encoder used to encode the value. Defaults to `JSONEncoder`.
  150. /// - Returns: The data encoding of the value.
  151. func encoded(using encoder: JSONEncoder = .init()) throws -> Data {
  152. try encoder.encode(self)
  153. }
  154. }