HeartbeatStorage.swift 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  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 identifier.
  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
  65. /// platforms,
  66. /// the file system is used.
  67. ///
  68. /// - Parameter id: A `String` identifier used to create the `HeartbeatStorage`.
  69. /// - Returns: A `HeartbeatStorage` instance.
  70. private static func makeHeartbeatStorage(id: String) -> HeartbeatStorage {
  71. #if os(tvOS)
  72. let storage = UserDefaultsStorage.makeStorage(id: id)
  73. #else
  74. let storage = FileStorage.makeStorage(id: id)
  75. #endif // os(tvOS)
  76. return HeartbeatStorage(id: id, storage: storage)
  77. }
  78. deinit {
  79. // Removes the instance if it was cached.
  80. Self.cachedInstances.removeValue(forKey: id)
  81. }
  82. // MARK: - HeartbeatStorageProtocol
  83. /// Synchronously reads from and writes to storage using the given transform block.
  84. /// - Parameter transform: A block to transform the currently stored heartbeats bundle to a new
  85. /// heartbeats bundle value.
  86. func readAndWriteSync(using transform: (HeartbeatsBundle?) -> HeartbeatsBundle?) {
  87. queue.sync {
  88. let oldHeartbeatsBundle = try? load(from: storage)
  89. let newHeartbeatsBundle = transform(oldHeartbeatsBundle)
  90. try? save(newHeartbeatsBundle, to: storage)
  91. }
  92. }
  93. /// Asynchronously reads from and writes to storage using the given transform block.
  94. /// - Parameter transform: A block to transform the currently stored heartbeats bundle to a new
  95. /// heartbeats bundle value.
  96. func readAndWriteAsync(using transform: @escaping (HeartbeatsBundle?) -> HeartbeatsBundle?) {
  97. queue.async { [self] in
  98. let oldHeartbeatsBundle = try? load(from: storage)
  99. let newHeartbeatsBundle = transform(oldHeartbeatsBundle)
  100. try? save(newHeartbeatsBundle, to: storage)
  101. }
  102. }
  103. /// Synchronously gets the current heartbeat data from storage and resets the storage using the
  104. /// given transform block.
  105. ///
  106. /// This API is like any `getAndSet`-style API in that it gets (and returns) the current value and
  107. /// uses
  108. /// a block to transform the current value (or, soon-to-be old value) to a new value.
  109. ///
  110. /// - Parameter transform: An optional block used to reset the currently stored heartbeat.
  111. /// - Returns: The heartbeat data that was stored (before the `transform` was applied).
  112. @discardableResult
  113. func getAndSet(using transform: (HeartbeatsBundle?) -> HeartbeatsBundle?) throws
  114. -> HeartbeatsBundle? {
  115. let heartbeatsBundle: HeartbeatsBundle? = try queue.sync {
  116. let oldHeartbeatsBundle = try? load(from: storage)
  117. let newHeartbeatsBundle = transform(oldHeartbeatsBundle)
  118. try save(newHeartbeatsBundle, to: storage)
  119. return oldHeartbeatsBundle
  120. }
  121. return heartbeatsBundle
  122. }
  123. /// Loads and decodes the stored heartbeats bundle from a given storage object.
  124. /// - Parameter storage: The storage container to read from.
  125. /// - Returns: The decoded `HeartbeatsBundle` loaded from storage; `nil` if storage is empty.
  126. /// - Throws: An error if storage could not be read or the data could not be decoded.
  127. private func load(from storage: Storage) throws -> HeartbeatsBundle? {
  128. let data = try storage.read()
  129. if data.isEmpty {
  130. return nil
  131. } else {
  132. let heartbeatData = try data.decoded(using: decoder) as HeartbeatsBundle
  133. return heartbeatData
  134. }
  135. }
  136. /// Saves the encoding of the given value to the given storage container.
  137. /// - Parameters:
  138. /// - heartbeatsBundle: The heartbeats bundle to encode and save.
  139. /// - storage: The storage container to write to.
  140. private func save(_ heartbeatsBundle: HeartbeatsBundle?, to storage: Storage) throws {
  141. if let heartbeatsBundle {
  142. let data = try heartbeatsBundle.encoded(using: encoder)
  143. try storage.write(data)
  144. } else {
  145. try storage.write(nil)
  146. }
  147. }
  148. }
  149. private extension Data {
  150. /// Returns the decoded value of this `Data` using the given decoder. Defaults to `JSONDecoder`.
  151. /// - Returns: The decoded value.
  152. func decoded<T>(using decoder: JSONDecoder = .init()) throws -> T where T: Decodable {
  153. try decoder.decode(T.self, from: self)
  154. }
  155. }
  156. private extension Encodable {
  157. /// Returns the `Data` encoding of this value using the given encoder.
  158. /// - Parameter encoder: An encoder used to encode the value. Defaults to `JSONEncoder`.
  159. /// - Returns: The data encoding of the value.
  160. func encoded(using encoder: JSONEncoder = .init()) throws -> Data {
  161. try encoder.encode(self)
  162. }
  163. }