HeartbeatStorage.swift 8.5 KB

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