MemoryStorage.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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 a set of conception related to storage which stores a certain type of value in memory.
  28. /// This is a namespace for the memory storage types. A `Backend` with a certain `Config` will be used to describe the
  29. /// storage. See these composed types for more information.
  30. public enum MemoryStorage {
  31. /// Represents a storage which stores a certain type of value in memory. It provides fast access,
  32. /// but limited storing size. The stored value type needs to conform to `CacheCostCalculable`,
  33. /// and its `cacheCost` will be used to determine the cost of size for the cache item.
  34. ///
  35. /// You can config a `MemoryStorage.Backend` in its initializer by passing a `MemoryStorage.Config` value.
  36. /// or modifying the `config` property after it being created. The backend of `MemoryStorage` has
  37. /// upper limitation on cost size in memory and item count. All items in the storage has an expiration
  38. /// date. When retrieved, if the target item is already expired, it will be recognized as it does not
  39. /// exist in the storage. The `MemoryStorage` also contains a scheduled self clean task, to evict expired
  40. /// items from memory.
  41. public class Backend<T: CacheCostCalculable> {
  42. let storage = NSCache<NSString, StorageObject<T>>()
  43. // Keys trackes the objects once inside the storage. For object removing triggered by user, the corresponding
  44. // key would be also removed. However, for the object removing triggered by cache rule/policy of system, the
  45. // key will be remained there until next `removeExpired` happens.
  46. //
  47. // Breaking the strict tracking could save additional locking behaviors.
  48. // See https://github.com/onevcat/Kingfisher/issues/1233
  49. var keys = Set<String>()
  50. private var cleanTimer: Timer? = nil
  51. private let lock = NSLock()
  52. /// The config used in this storage. It is a value you can set and
  53. /// use to config the storage in air.
  54. public var config: Config {
  55. didSet {
  56. storage.totalCostLimit = config.totalCostLimit
  57. storage.countLimit = config.countLimit
  58. }
  59. }
  60. /// Creates a `MemoryStorage` with a given `config`.
  61. ///
  62. /// - Parameter config: The config used to create the storage. It determines the max size limitation,
  63. /// default expiration setting and more.
  64. public init(config: Config) {
  65. self.config = config
  66. storage.totalCostLimit = config.totalCostLimit
  67. storage.countLimit = config.countLimit
  68. cleanTimer = .scheduledTimer(withTimeInterval: config.cleanInterval, repeats: true) { [weak self] _ in
  69. guard let self = self else { return }
  70. self.removeExpired()
  71. }
  72. }
  73. /// Removes the expired values from the storage.
  74. public func removeExpired() {
  75. lock.lock()
  76. defer { lock.unlock() }
  77. for key in keys {
  78. let nsKey = key as NSString
  79. guard let object = storage.object(forKey: nsKey) else {
  80. // This could happen if the object is moved by cache `totalCostLimit` or `countLimit` rule.
  81. // We didn't remove the key yet until now, since we do not want to introduce additional lock.
  82. // See https://github.com/onevcat/Kingfisher/issues/1233
  83. keys.remove(key)
  84. continue
  85. }
  86. if object.isExpired {
  87. storage.removeObject(forKey: nsKey)
  88. keys.remove(key)
  89. }
  90. }
  91. }
  92. /// Stores a value to the storage under the specified key and expiration policy.
  93. /// - Parameters:
  94. /// - value: The value to be stored.
  95. /// - key: The key to which the `value` will be stored.
  96. /// - expiration: The expiration policy used by this store action.
  97. /// - Throws: No error will
  98. public func store(
  99. value: T,
  100. forKey key: String,
  101. expiration: StorageExpiration? = nil)
  102. {
  103. storeNoThrow(value: value, forKey: key, expiration: expiration)
  104. }
  105. // The no throw version for storing value in cache. Kingfisher knows the detail so it
  106. // could use this version to make syntax simpler internally.
  107. func storeNoThrow(
  108. value: T,
  109. forKey key: String,
  110. expiration: StorageExpiration? = nil)
  111. {
  112. lock.lock()
  113. defer { lock.unlock() }
  114. let expiration = expiration ?? config.expiration
  115. // The expiration indicates that already expired, no need to store.
  116. guard !expiration.isExpired else { return }
  117. let object: StorageObject<T>
  118. if config.keepWhenEnteringBackground {
  119. object = BackgroundKeepingStorageObject(value, expiration: expiration)
  120. } else {
  121. object = StorageObject(value, expiration: expiration)
  122. }
  123. storage.setObject(object, forKey: key as NSString, cost: value.cacheCost)
  124. keys.insert(key)
  125. }
  126. /// Gets a value from the storage.
  127. ///
  128. /// - Parameters:
  129. /// - key: The cache key of value.
  130. /// - extendingExpiration: The expiration policy used by this getting action.
  131. /// - Returns: The value under `key` if it is valid and found in the storage. Otherwise, `nil`.
  132. public func value(forKey key: String, extendingExpiration: ExpirationExtending = .cacheTime) -> T? {
  133. guard let object = storage.object(forKey: key as NSString) else {
  134. return nil
  135. }
  136. if object.isExpired {
  137. return nil
  138. }
  139. object.extendExpiration(extendingExpiration)
  140. return object.value
  141. }
  142. /// Whether there is valid cached data under a given key.
  143. /// - Parameter key: The cache key of value.
  144. /// - Returns: If there is valid data under the key, `true`. Otherwise, `false`.
  145. public func isCached(forKey key: String) -> Bool {
  146. guard let _ = value(forKey: key, extendingExpiration: .none) else {
  147. return false
  148. }
  149. return true
  150. }
  151. /// Removes a value from a specified key.
  152. /// - Parameter key: The cache key of value.
  153. public func remove(forKey key: String) {
  154. lock.lock()
  155. defer { lock.unlock() }
  156. storage.removeObject(forKey: key as NSString)
  157. keys.remove(key)
  158. }
  159. /// Removes all values in this storage.
  160. public func removeAll() {
  161. lock.lock()
  162. defer { lock.unlock() }
  163. storage.removeAllObjects()
  164. keys.removeAll()
  165. }
  166. }
  167. }
  168. extension MemoryStorage {
  169. /// Represents the config used in a `MemoryStorage`.
  170. public struct Config {
  171. /// Total cost limit of the storage in bytes.
  172. public var totalCostLimit: Int
  173. /// The item count limit of the memory storage.
  174. public var countLimit: Int = .max
  175. /// The `StorageExpiration` used in this memory storage. Default is `.seconds(300)`,
  176. /// means that the memory cache would expire in 5 minutes.
  177. public var expiration: StorageExpiration = .seconds(300)
  178. /// The time interval between the storage do clean work for swiping expired items.
  179. public var cleanInterval: TimeInterval
  180. /// Whether the newly added items to memory cache should be purged when the app goes to background.
  181. ///
  182. /// By default, the cached items in memory will be purged as soon as the app goes to background to ensure
  183. /// least memory footprint. Enabling this would prevent this behavior and keep the items alive in cache even
  184. /// when your app is not in foreground anymore.
  185. ///
  186. /// Default is `false`. After setting `true`, only the newly added cache objects are affected. Existing
  187. /// objects which are already in the cache while this value was `false` will be still be purged when entering
  188. /// background.
  189. public var keepWhenEnteringBackground: Bool = false
  190. /// Creates a config from a given `totalCostLimit` value.
  191. ///
  192. /// - Parameters:
  193. /// - totalCostLimit: Total cost limit of the storage in bytes.
  194. /// - cleanInterval: The time interval between the storage do clean work for swiping expired items.
  195. /// Default is 120, means the auto eviction happens once per two minutes.
  196. ///
  197. /// - Note:
  198. /// Other members of `MemoryStorage.Config` will use their default values when created.
  199. public init(totalCostLimit: Int, cleanInterval: TimeInterval = 120) {
  200. self.totalCostLimit = totalCostLimit
  201. self.cleanInterval = cleanInterval
  202. }
  203. }
  204. }
  205. extension MemoryStorage {
  206. class BackgroundKeepingStorageObject<T>: StorageObject<T>, NSDiscardableContent {
  207. var accessing = true
  208. func beginContentAccess() -> Bool {
  209. if value != nil {
  210. accessing = true
  211. } else {
  212. accessing = false
  213. }
  214. return accessing
  215. }
  216. func endContentAccess() {
  217. accessing = false
  218. }
  219. func discardContentIfPossible() {
  220. value = nil
  221. }
  222. func isContentDiscarded() -> Bool {
  223. return value == nil
  224. }
  225. }
  226. class StorageObject<T> {
  227. var value: T?
  228. let expiration: StorageExpiration
  229. private(set) var estimatedExpiration: Date
  230. init(_ value: T, expiration: StorageExpiration) {
  231. self.value = value
  232. self.expiration = expiration
  233. self.estimatedExpiration = expiration.estimatedExpirationSinceNow
  234. }
  235. func extendExpiration(_ extendingExpiration: ExpirationExtending = .cacheTime) {
  236. switch extendingExpiration {
  237. case .none:
  238. return
  239. case .cacheTime:
  240. self.estimatedExpiration = expiration.estimatedExpirationSinceNow
  241. case .expirationTime(let expirationTime):
  242. self.estimatedExpiration = expirationTime.estimatedExpirationSinceNow
  243. }
  244. }
  245. var isExpired: Bool {
  246. return estimatedExpiration.isPast
  247. }
  248. }
  249. }