2
0

MemoryStorage.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. //
  2. // MemoryStorage.swift
  3. // Kingfisher
  4. //
  5. // Created by Wei Wang on 2018/10/15.
  6. //
  7. // Copyright (c) 2019 Wei Wang <onevcat@gmail.com>
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining a copy
  10. // of this software and associated documentation files (the "Software"), to deal
  11. // in the Software without restriction, including without limitation the rights
  12. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. // copies of the Software, and to permit persons to whom the Software is
  14. // furnished to do so, subject to the following conditions:
  15. //
  16. // The above copyright notice and this permission notice shall be included in
  17. // all copies or substantial portions of the Software.
  18. //
  19. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. // THE SOFTWARE.
  26. import Foundation
  27. /// Represents the concepts related to storage that stores a specific type of value in memory.
  28. ///
  29. /// This serves as a namespace for memory storage types. A ``MemoryStorage/Backend`` with a particular
  30. /// ``MemoryStorage/Config`` is used to define the storage.
  31. ///
  32. /// Refer to these composite types for further details.
  33. public enum MemoryStorage {
  34. /// Represents a storage that stores a specific type of value in memory.
  35. ///
  36. /// It provides fast access but has a limited storage size. The stored value type needs to conform to the
  37. /// ``CacheCostCalculable`` protocol, and its ``CacheCostCalculable/cacheCost`` will be used to determine the cost
  38. /// of the cache item's size in the memory.
  39. ///
  40. /// You can configure a ``MemoryStorage/Backend`` in its ``MemoryStorage/Backend/init(config:)`` method by passing
  41. /// a ``MemoryStorage/Config`` value or by modifying the ``MemoryStorage/Backend/config`` property after it's
  42. /// created.
  43. ///
  44. /// The ``MemoryStorage`` backend has an upper limit on the total cost size in memory and item count. All items in
  45. /// the storage have an expiration date. When retrieved, if the target item is already expired, it will be
  46. /// recognized as if it does not exist in the storage.
  47. ///
  48. /// The `MemoryStorage` also includes a scheduled self-cleaning task to evict expired items from memory.
  49. ///
  50. /// > This class is thready safe.
  51. public class Backend<T: CacheCostCalculable>: @unchecked Sendable {
  52. let storage = NSCache<NSString, StorageObject<T>>()
  53. // Keys track the objects once inside the storage.
  54. //
  55. // For object removing triggered by user, the corresponding key would be also removed. However, for the object
  56. // removing triggered by cache rule/policy of system, the key will be remained there until next `removeExpired`
  57. // happens.
  58. //
  59. // Breaking the strict tracking could save additional locking behaviors and improve the cache performance.
  60. // See https://github.com/onevcat/Kingfisher/issues/1233
  61. var keys = Set<String>()
  62. private var cleanTimer: Timer? = nil
  63. private let lock = NSLock()
  64. /// The configuration used in this storage.
  65. ///
  66. /// It is a value you can set and use to configure the storage as needed.
  67. public var config: Config {
  68. didSet {
  69. storage.totalCostLimit = config.totalCostLimit
  70. storage.countLimit = config.countLimit
  71. }
  72. }
  73. /// Creates a ``MemoryStorage/Backend`` with a given ``MemoryStorage/Config`` value.
  74. ///
  75. /// - Parameter config: The configuration used to create the storage. It determines the maximum size limitation,
  76. /// default expiration settings, and more.
  77. public init(config: Config) {
  78. self.config = config
  79. storage.totalCostLimit = config.totalCostLimit
  80. storage.countLimit = config.countLimit
  81. cleanTimer = .scheduledTimer(withTimeInterval: config.cleanInterval, repeats: true) { [weak self] _ in
  82. guard let self = self else { return }
  83. self.removeExpired()
  84. }
  85. }
  86. /// Removes the expired values from the storage.
  87. public func removeExpired() {
  88. lock.lock()
  89. defer { lock.unlock() }
  90. for key in keys {
  91. let nsKey = key as NSString
  92. guard let object = storage.object(forKey: nsKey) else {
  93. // This could happen if the object is moved by cache `totalCostLimit` or `countLimit` rule.
  94. // We didn't remove the key yet until now, since we do not want to introduce additional lock.
  95. // See https://github.com/onevcat/Kingfisher/issues/1233
  96. keys.remove(key)
  97. continue
  98. }
  99. if object.isExpired {
  100. storage.removeObject(forKey: nsKey)
  101. keys.remove(key)
  102. }
  103. }
  104. }
  105. /// Stores a value in the storage under the specified key and expiration policy.
  106. ///
  107. /// - Parameters:
  108. /// - value: The value to be stored.
  109. /// - key: The key to which the `value` will be stored.
  110. /// - expiration: The expiration policy used by this storage action.
  111. public func store(
  112. value: T,
  113. forKey key: String,
  114. expiration: StorageExpiration? = nil)
  115. {
  116. storeNoThrow(value: value, forKey: key, expiration: expiration)
  117. }
  118. // The no throw version for storing value in cache. Kingfisher knows the detail so it
  119. // could use this version to make syntax simpler internally.
  120. func storeNoThrow(
  121. value: T,
  122. forKey key: String,
  123. expiration: StorageExpiration? = nil)
  124. {
  125. lock.lock()
  126. defer { lock.unlock() }
  127. let expiration = expiration ?? config.expiration
  128. // The expiration indicates that already expired, no need to store.
  129. guard !expiration.isExpired else { return }
  130. let object: StorageObject<T>
  131. if config.keepWhenEnteringBackground {
  132. object = BackgroundKeepingStorageObject(value, expiration: expiration)
  133. } else {
  134. object = StorageObject(value, expiration: expiration)
  135. }
  136. storage.setObject(object, forKey: key as NSString, cost: value.cacheCost)
  137. keys.insert(key)
  138. }
  139. /// Gets a value from the storage.
  140. ///
  141. /// - Parameters:
  142. /// - key: The cache key of the value.
  143. /// - extendingExpiration: The expiration policy used by this retrieval action.
  144. /// - Returns: The value under `key` if it is valid and found in the storage. Otherwise, `nil`.
  145. public func value(forKey key: String, extendingExpiration: ExpirationExtending = .cacheTime) -> T? {
  146. guard let object = storage.object(forKey: key as NSString) else {
  147. return nil
  148. }
  149. if object.isExpired {
  150. return nil
  151. }
  152. object.extendExpiration(extendingExpiration)
  153. return object.value
  154. }
  155. /// Determines whether there is valid cached data under a given key.
  156. ///
  157. /// - Parameter key: The cache key of the value.
  158. /// - Returns: `true` if there is valid data under the key, otherwise `false`.
  159. public func isCached(forKey key: String) -> Bool {
  160. guard let _ = value(forKey: key, extendingExpiration: .none) else {
  161. return false
  162. }
  163. return true
  164. }
  165. /// Removes a value from a specified key.
  166. ///
  167. /// - Parameter key: The cache key of the value.
  168. public func remove(forKey key: String) {
  169. lock.lock()
  170. defer { lock.unlock() }
  171. storage.removeObject(forKey: key as NSString)
  172. keys.remove(key)
  173. }
  174. /// Removes all values in this storage.
  175. public func removeAll() {
  176. lock.lock()
  177. defer { lock.unlock() }
  178. storage.removeAllObjects()
  179. keys.removeAll()
  180. }
  181. }
  182. }
  183. extension MemoryStorage {
  184. /// Represents the configuration used in a ``MemoryStorage/Backend``.
  185. public struct Config {
  186. /// The total cost limit of the storage.
  187. ///
  188. /// This counts up the value of ``CacheCostCalculable/cacheCost``. If adding this object to the cache causes
  189. /// the cache’s total cost to rise above totalCostLimit, the cache may automatically evict objects until its
  190. /// total cost falls below this value.
  191. public var totalCostLimit: Int
  192. /// The item count limit of the memory storage.
  193. ///
  194. /// The default value is `Int.max`, which means no hard limitation of the item count.
  195. public var countLimit: Int = .max
  196. /// The ``StorageExpiration`` used in this memory storage.
  197. ///
  198. /// The default is `.seconds(300)`, which means that the memory cache will expire in 5 minutes if not accessed.
  199. public var expiration: StorageExpiration = .seconds(300)
  200. /// The time interval between the storage performing cleaning work for sweeping expired items.
  201. public var cleanInterval: TimeInterval
  202. /// Determine whether newly added items to memory cache should be purged when the app goes to the background.
  203. ///
  204. /// By default, cached items in memory will be purged as soon as the app goes to the background to ensure a
  205. /// minimal memory footprint. Enabling this prevents this behavior and keeps the items alive in the cache even
  206. /// when your app is not in the foreground.
  207. ///
  208. /// The default value is `false`. After setting it to `true`, only newly added cache objects are affected.
  209. /// Existing objects that were already in the cache while this value was `false` will still be purged when the
  210. /// app enters the background.
  211. public var keepWhenEnteringBackground: Bool = false
  212. /// Creates a configuration from a given ``MemoryStorage/Config/totalCostLimit`` value and a
  213. /// ``MemoryStorage/Config/cleanInterval``.
  214. ///
  215. /// - Parameters:
  216. /// - totalCostLimit: The total cost limit of the storage in bytes.
  217. /// - cleanInterval: The time interval between the storage performing cleaning work for sweeping expired items.
  218. /// The default is 120, which means auto eviction happens once every two minutes.
  219. ///
  220. /// > Other properties of the ``MemoryStorage/Config`` will use their default values when created.
  221. public init(totalCostLimit: Int, cleanInterval: TimeInterval = 120) {
  222. self.totalCostLimit = totalCostLimit
  223. self.cleanInterval = cleanInterval
  224. }
  225. }
  226. }
  227. extension MemoryStorage {
  228. class BackgroundKeepingStorageObject<T>: StorageObject<T>, NSDiscardableContent {
  229. var accessing = true
  230. func beginContentAccess() -> Bool {
  231. if value != nil {
  232. accessing = true
  233. } else {
  234. accessing = false
  235. }
  236. return accessing
  237. }
  238. func endContentAccess() {
  239. accessing = false
  240. }
  241. func discardContentIfPossible() {
  242. value = nil
  243. }
  244. func isContentDiscarded() -> Bool {
  245. return value == nil
  246. }
  247. }
  248. class StorageObject<T> {
  249. var value: T?
  250. let expiration: StorageExpiration
  251. private(set) var estimatedExpiration: Date
  252. init(_ value: T, expiration: StorageExpiration) {
  253. self.value = value
  254. self.expiration = expiration
  255. self.estimatedExpiration = expiration.estimatedExpirationSinceNow
  256. }
  257. func extendExpiration(_ extendingExpiration: ExpirationExtending = .cacheTime) {
  258. switch extendingExpiration {
  259. case .none:
  260. return
  261. case .cacheTime:
  262. self.estimatedExpiration = expiration.estimatedExpirationSinceNow
  263. case .expirationTime(let expirationTime):
  264. self.estimatedExpiration = expirationTime.estimatedExpirationSinceNow
  265. }
  266. }
  267. var isExpired: Bool {
  268. return estimatedExpiration.isPast
  269. }
  270. }
  271. }