2
0

MemoryStorage.swift 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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. var keys = Set<String>()
  44. var cleanTimer: Timer? = nil
  45. let lock = NSLock()
  46. let cacheDelegate = CacheDelegate<StorageObject<T>>()
  47. /// The config used in this storage. It is a value you can set and
  48. /// use to config the storage in air.
  49. public var config: Config {
  50. didSet {
  51. storage.totalCostLimit = config.totalCostLimit
  52. storage.countLimit = config.countLimit
  53. }
  54. }
  55. /// Creates a `MemoryStorage` with a given `config`.
  56. ///
  57. /// - Parameter config: The config used to create the storage. It determines the max size limitation,
  58. /// default expiration setting and more.
  59. public init(config: Config) {
  60. self.config = config
  61. storage.totalCostLimit = config.totalCostLimit
  62. storage.countLimit = config.countLimit
  63. storage.delegate = cacheDelegate
  64. cacheDelegate.onObjectRemoved.delegate(on: self) { (self, obj) in
  65. self.keys.remove(obj.key)
  66. }
  67. cleanTimer = .scheduledTimer(withTimeInterval: config.cleanInterval, repeats: true) { [weak self] _ in
  68. guard let self = self else { return }
  69. self.removeExpired()
  70. }
  71. }
  72. func removeExpired() {
  73. lock.lock()
  74. defer { lock.unlock() }
  75. for key in keys {
  76. let nsKey = key as NSString
  77. guard let object = storage.object(forKey: nsKey) else {
  78. keys.remove(key)
  79. continue
  80. }
  81. if object.estimatedExpiration.isPast {
  82. storage.removeObject(forKey: nsKey)
  83. keys.remove(key)
  84. }
  85. }
  86. }
  87. // Storing in memory will not throw. It is just for meeting protocol requirement and
  88. // forwarding to no throwing method.
  89. func store(
  90. value: T,
  91. forKey key: String,
  92. expiration: StorageExpiration? = nil) throws
  93. {
  94. storeNoThrow(value: value, forKey: key, expiration: expiration)
  95. }
  96. // The no throw version for storing value in cache. Kingfisher knows the detail so it
  97. // could use this version to make syntax simpler internally.
  98. func storeNoThrow(
  99. value: T,
  100. forKey key: String,
  101. expiration: StorageExpiration? = nil)
  102. {
  103. lock.lock()
  104. defer { lock.unlock() }
  105. let expiration = expiration ?? config.expiration
  106. // The expiration indicates that already expired, no need to store.
  107. guard !expiration.isExpired else { return }
  108. let object = StorageObject(value, key: key, expiration: expiration)
  109. storage.setObject(object, forKey: key as NSString, cost: value.cacheCost)
  110. keys.insert(key)
  111. }
  112. /// Use this when you actually access the memory cached item.
  113. /// By default, this will extend the expired data for the accessed item.
  114. ///
  115. /// - Parameters:
  116. /// - key: Cache Key
  117. /// - extendingExpiration: expiration value to extend item expiration time:
  118. /// * .none: The item expires after the original time, without extending after access.
  119. /// * .cacheTime: The item expiration extends by the original cache time after each access.
  120. /// * .expirationTime: The item expiration extends by the provided time after each access.
  121. /// - Returns: cached object or nil
  122. func value(forKey key: String, extendingExpiration: ExpirationExtending = .cacheTime) -> T? {
  123. guard let object = storage.object(forKey: key as NSString) else {
  124. return nil
  125. }
  126. if object.expired {
  127. return nil
  128. }
  129. object.extendExpiration(extendingExpiration)
  130. return object.value
  131. }
  132. func isCached(forKey key: String) -> Bool {
  133. guard let _ = value(forKey: key, extendingExpiration: .none) else {
  134. return false
  135. }
  136. return true
  137. }
  138. func remove(forKey key: String) throws {
  139. lock.lock()
  140. defer { lock.unlock() }
  141. storage.removeObject(forKey: key as NSString)
  142. keys.remove(key)
  143. }
  144. func removeAll() throws {
  145. lock.lock()
  146. defer { lock.unlock() }
  147. storage.removeAllObjects()
  148. keys.removeAll()
  149. }
  150. class CacheDelegate<T>: NSObject, NSCacheDelegate {
  151. let onObjectRemoved = Delegate<T, Void>()
  152. func cache(_ cache: NSCache<AnyObject, AnyObject>, willEvictObject obj: Any) {
  153. if let obj = obj as? T {
  154. onObjectRemoved.call(obj)
  155. }
  156. }
  157. }
  158. }
  159. }
  160. extension MemoryStorage {
  161. /// Represents the config used in a `MemoryStorage`.
  162. public struct Config {
  163. /// Total cost limit of the storage in bytes.
  164. public var totalCostLimit: Int
  165. /// The item count limit of the memory storage.
  166. public var countLimit: Int = .max
  167. /// The `StorageExpiration` used in this memory storage. Default is `.seconds(300)`,
  168. /// means that the memory cache would expire in 5 minutes.
  169. public var expiration: StorageExpiration = .seconds(300)
  170. /// The time interval between the storage do clean work for swiping expired items.
  171. public let cleanInterval: TimeInterval
  172. /// Creates a config from a given `totalCostLimit` value.
  173. ///
  174. /// - Parameters:
  175. /// - totalCostLimit: Total cost limit of the storage in bytes.
  176. /// - cleanInterval: The time interval between the storage do clean work for swiping expired items.
  177. /// Default is 120, means the auto eviction happens once per two minutes.
  178. ///
  179. /// - Note:
  180. /// Other members of `MemoryStorage.Config` will use their default values when created.
  181. public init(totalCostLimit: Int, cleanInterval: TimeInterval = 120) {
  182. self.totalCostLimit = totalCostLimit
  183. self.cleanInterval = cleanInterval
  184. }
  185. }
  186. }
  187. extension MemoryStorage {
  188. class StorageObject<T> {
  189. let value: T
  190. let expiration: StorageExpiration
  191. let key: String
  192. private(set) var estimatedExpiration: Date
  193. init(_ value: T, key: String, expiration: StorageExpiration) {
  194. self.value = value
  195. self.key = key
  196. self.expiration = expiration
  197. self.estimatedExpiration = expiration.estimatedExpirationSinceNow
  198. }
  199. func extendExpiration(_ extendingExpiration: ExpirationExtending = .cacheTime) {
  200. switch extendingExpiration {
  201. case .none:
  202. return
  203. case .cacheTime:
  204. self.estimatedExpiration = expiration.estimatedExpirationSinceNow
  205. case .expirationTime(let expirationTime):
  206. self.estimatedExpiration = expirationTime.estimatedExpirationSinceNow
  207. }
  208. }
  209. var expired: Bool {
  210. return estimatedExpiration.isPast
  211. }
  212. }
  213. }