HeartbeatStorage.swift 8.3 KB

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