HeartbeatStorage.swift 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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. #if compiler(>=6)
  50. // In Swift 6, this property is not concurrency-safe because it is
  51. // nonisolated global shared mutable state. Because this target's
  52. // deployment version does not support Swift concurrency, it is marked as
  53. // `nonisolated(unsafe)` to disable concurrency-safety checks. The
  54. // property's access is protected by an external synchronization mechanism
  55. // (see `instancesLock` property).
  56. private nonisolated(unsafe) static var cachedInstances: AtomicBox<
  57. [String: WeakContainer<HeartbeatStorage>]
  58. > = AtomicBox([:])
  59. #else
  60. // TODO(Xcode 16): Delete this block when minimum supported Xcode is
  61. // Xcode 16.
  62. static var cachedInstances: AtomicBox<[String: WeakContainer<HeartbeatStorage>]> =
  63. AtomicBox([:])
  64. #endif // compiler(>=6)
  65. /// Gets an existing `HeartbeatStorage` instance with the given `id` if one exists. Otherwise,
  66. /// makes a new instance with the given `id`.
  67. ///
  68. /// - Parameter id: A string identifier.
  69. /// - Returns: A `HeartbeatStorage` instance.
  70. static func getInstance(id: String) -> HeartbeatStorage {
  71. cachedInstances.withLock { cachedInstances in
  72. if let cachedInstance = cachedInstances[id]?.object {
  73. return cachedInstance
  74. } else {
  75. let newInstance = HeartbeatStorage.makeHeartbeatStorage(id: id)
  76. cachedInstances[id] = WeakContainer(object: newInstance)
  77. return newInstance
  78. }
  79. }
  80. }
  81. /// Makes a `HeartbeatStorage` instance using a given `String` identifier.
  82. ///
  83. /// The created persistent storage object is platform dependent. For tvOS, user defaults
  84. /// is used as the underlying storage container due to system storage limits. For all other
  85. /// platforms,
  86. /// the file system is used.
  87. ///
  88. /// - Parameter id: A `String` identifier used to create the `HeartbeatStorage`.
  89. /// - Returns: A `HeartbeatStorage` instance.
  90. private static func makeHeartbeatStorage(id: String) -> HeartbeatStorage {
  91. #if os(tvOS)
  92. let storage = UserDefaultsStorage.makeStorage(id: id)
  93. #else
  94. let storage = FileStorage.makeStorage(id: id)
  95. #endif // os(tvOS)
  96. return HeartbeatStorage(id: id, storage: storage)
  97. }
  98. deinit {
  99. // Removes the instance if it was cached.
  100. Self.cachedInstances.withLock { value in
  101. value.removeValue(forKey: id)
  102. }
  103. }
  104. // MARK: - HeartbeatStorageProtocol
  105. /// Synchronously reads from and writes to storage using the given transform block.
  106. /// - Parameter transform: A block to transform the currently stored heartbeats bundle to a new
  107. /// heartbeats bundle value.
  108. func readAndWriteSync(using transform: (HeartbeatsBundle?) -> HeartbeatsBundle?) {
  109. queue.sync {
  110. let oldHeartbeatsBundle = try? load(from: storage)
  111. let newHeartbeatsBundle = transform(oldHeartbeatsBundle)
  112. try? save(newHeartbeatsBundle, to: storage)
  113. }
  114. }
  115. /// Asynchronously reads from and writes to storage using the given transform block.
  116. /// - Parameter transform: A block to transform the currently stored heartbeats bundle to a new
  117. /// heartbeats bundle value.
  118. func readAndWriteAsync(using transform: @escaping @Sendable (HeartbeatsBundle?)
  119. -> HeartbeatsBundle?) {
  120. queue.async { [self] in
  121. let oldHeartbeatsBundle = try? load(from: storage)
  122. let newHeartbeatsBundle = transform(oldHeartbeatsBundle)
  123. try? save(newHeartbeatsBundle, to: storage)
  124. }
  125. }
  126. /// Synchronously gets the current heartbeat data from storage and resets the storage using the
  127. /// given transform block.
  128. ///
  129. /// This API is like any `getAndSet`-style API in that it gets (and returns) the current value and
  130. /// uses
  131. /// a block to transform the current value (or, soon-to-be old value) to a new value.
  132. ///
  133. /// - Parameter transform: An optional block used to reset the currently stored heartbeat.
  134. /// - Returns: The heartbeat data that was stored (before the `transform` was applied).
  135. @discardableResult
  136. func getAndSet(using transform: (HeartbeatsBundle?) -> HeartbeatsBundle?) throws
  137. -> HeartbeatsBundle? {
  138. let heartbeatsBundle: HeartbeatsBundle? = try queue.sync {
  139. let oldHeartbeatsBundle = try? load(from: storage)
  140. let newHeartbeatsBundle = transform(oldHeartbeatsBundle)
  141. try save(newHeartbeatsBundle, to: storage)
  142. return oldHeartbeatsBundle
  143. }
  144. return heartbeatsBundle
  145. }
  146. /// Asynchronously gets the current heartbeat data from storage and resets the storage using the
  147. /// given transform block.
  148. /// - Parameters:
  149. /// - transform: An escaping block used to reset the currently stored heartbeat.
  150. /// - completion: An escaping block used to process the heartbeat data that
  151. /// was stored (before the `transform` was applied); otherwise, the error
  152. /// that occurred.
  153. func getAndSetAsync(using transform: @escaping @Sendable (HeartbeatsBundle?) -> HeartbeatsBundle?,
  154. completion: @escaping @Sendable (Result<HeartbeatsBundle?, Error>) -> Void) {
  155. queue.async {
  156. do {
  157. let oldHeartbeatsBundle = try? self.load(from: self.storage)
  158. let newHeartbeatsBundle = transform(oldHeartbeatsBundle)
  159. try self.save(newHeartbeatsBundle, to: self.storage)
  160. completion(.success(oldHeartbeatsBundle))
  161. } catch {
  162. completion(.failure(error))
  163. }
  164. }
  165. }
  166. /// Loads and decodes the stored heartbeats bundle from a given storage object.
  167. /// - Parameter storage: The storage container to read from.
  168. /// - Returns: The decoded `HeartbeatsBundle` loaded from storage; `nil` if storage is empty.
  169. /// - Throws: An error if storage could not be read or the data could not be decoded.
  170. private func load(from storage: Storage) throws -> HeartbeatsBundle? {
  171. let data = try storage.read()
  172. if data.isEmpty {
  173. return nil
  174. } else {
  175. let heartbeatData = try data.decoded(using: decoder) as HeartbeatsBundle
  176. return heartbeatData
  177. }
  178. }
  179. /// Saves the encoding of the given value to the given storage container.
  180. /// - Parameters:
  181. /// - heartbeatsBundle: The heartbeats bundle to encode and save.
  182. /// - storage: The storage container to write to.
  183. private func save(_ heartbeatsBundle: HeartbeatsBundle?, to storage: Storage) throws {
  184. if let heartbeatsBundle {
  185. let data = try heartbeatsBundle.encoded(using: encoder)
  186. try storage.write(data)
  187. } else {
  188. try storage.write(nil)
  189. }
  190. }
  191. }
  192. private extension Data {
  193. /// Returns the decoded value of this `Data` using the given decoder. Defaults to `JSONDecoder`.
  194. /// - Returns: The decoded value.
  195. func decoded<T>(using decoder: JSONDecoder = .init()) throws -> T where T: Decodable {
  196. try decoder.decode(T.self, from: self)
  197. }
  198. }
  199. private extension Encodable {
  200. /// Returns the `Data` encoding of this value using the given encoder.
  201. /// - Parameter encoder: An encoder used to encode the value. Defaults to `JSONEncoder`.
  202. /// - Returns: The data encoding of the value.
  203. func encoded(using encoder: JSONEncoder = .init()) throws -> Data {
  204. try encoder.encode(self)
  205. }
  206. }