HeartbeatStorage.swift 9.2 KB

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