HeartbeatStorage.swift 7.2 KB

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