You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

237 lines
9.9 KiB

  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. func removeExpired() {
  74. lock.lock()
  75. defer { lock.unlock() }
  76. for key in keys {
  77. let nsKey = key as NSString
  78. guard let object = storage.object(forKey: nsKey) else {
  79. // This could happen if the object is moved by cache `totalCostLimit` or `countLimit` rule.
  80. // We didn't remove the key yet until now, since we do not want to introduce additonal lock.
  81. // See https://github.com/onevcat/Kingfisher/issues/1233
  82. keys.remove(key)
  83. continue
  84. }
  85. if object.estimatedExpiration.isPast {
  86. storage.removeObject(forKey: nsKey)
  87. keys.remove(key)
  88. }
  89. }
  90. }
  91. // Storing in memory will not throw. It is just for meeting protocol requirement and
  92. // forwarding to no throwing method.
  93. func store(
  94. value: T,
  95. forKey key: String,
  96. expiration: StorageExpiration? = nil) throws
  97. {
  98. storeNoThrow(value: value, forKey: key, expiration: expiration)
  99. }
  100. // The no throw version for storing value in cache. Kingfisher knows the detail so it
  101. // could use this version to make syntax simpler internally.
  102. func storeNoThrow(
  103. value: T,
  104. forKey key: String,
  105. expiration: StorageExpiration? = nil)
  106. {
  107. lock.lock()
  108. defer { lock.unlock() }
  109. let expiration = expiration ?? config.expiration
  110. // The expiration indicates that already expired, no need to store.
  111. guard !expiration.isExpired else { return }
  112. let object = StorageObject(value, key: key, expiration: expiration)
  113. storage.setObject(object, forKey: key as NSString, cost: value.cacheCost)
  114. keys.insert(key)
  115. }
  116. /// Use this when you actually access the memory cached item.
  117. /// By default, this will extend the expired data for the accessed item.
  118. ///
  119. /// - Parameters:
  120. /// - key: Cache Key
  121. /// - extendingExpiration: expiration value to extend item expiration time:
  122. /// * .none: The item expires after the original time, without extending after access.
  123. /// * .cacheTime: The item expiration extends by the original cache time after each access.
  124. /// * .expirationTime: The item expiration extends by the provided time after each access.
  125. /// - Returns: cached object or nil
  126. func value(forKey key: String, extendingExpiration: ExpirationExtending = .cacheTime) -> T? {
  127. guard let object = storage.object(forKey: key as NSString) else {
  128. return nil
  129. }
  130. if object.expired {
  131. return nil
  132. }
  133. object.extendExpiration(extendingExpiration)
  134. return object.value
  135. }
  136. func isCached(forKey key: String) -> Bool {
  137. guard let _ = value(forKey: key, extendingExpiration: .none) else {
  138. return false
  139. }
  140. return true
  141. }
  142. func remove(forKey key: String) throws {
  143. lock.lock()
  144. defer { lock.unlock() }
  145. storage.removeObject(forKey: key as NSString)
  146. keys.remove(key)
  147. }
  148. func removeAll() throws {
  149. lock.lock()
  150. defer { lock.unlock() }
  151. storage.removeAllObjects()
  152. keys.removeAll()
  153. }
  154. }
  155. }
  156. extension MemoryStorage {
  157. /// Represents the config used in a `MemoryStorage`.
  158. public struct Config {
  159. /// Total cost limit of the storage in bytes.
  160. public var totalCostLimit: Int
  161. /// The item count limit of the memory storage.
  162. public var countLimit: Int = .max
  163. /// The `StorageExpiration` used in this memory storage. Default is `.seconds(300)`,
  164. /// means that the memory cache would expire in 5 minutes.
  165. public var expiration: StorageExpiration = .seconds(300)
  166. /// The time interval between the storage do clean work for swiping expired items.
  167. public let cleanInterval: TimeInterval
  168. /// Creates a config from a given `totalCostLimit` value.
  169. ///
  170. /// - Parameters:
  171. /// - totalCostLimit: Total cost limit of the storage in bytes.
  172. /// - cleanInterval: The time interval between the storage do clean work for swiping expired items.
  173. /// Default is 120, means the auto eviction happens once per two minutes.
  174. ///
  175. /// - Note:
  176. /// Other members of `MemoryStorage.Config` will use their default values when created.
  177. public init(totalCostLimit: Int, cleanInterval: TimeInterval = 120) {
  178. self.totalCostLimit = totalCostLimit
  179. self.cleanInterval = cleanInterval
  180. }
  181. }
  182. }
  183. extension MemoryStorage {
  184. class StorageObject<T> {
  185. let value: T
  186. let expiration: StorageExpiration
  187. let key: String
  188. private(set) var estimatedExpiration: Date
  189. init(_ value: T, key: String, expiration: StorageExpiration) {
  190. self.value = value
  191. self.key = key
  192. self.expiration = expiration
  193. self.estimatedExpiration = expiration.estimatedExpirationSinceNow
  194. }
  195. func extendExpiration(_ extendingExpiration: ExpirationExtending = .cacheTime) {
  196. switch extendingExpiration {
  197. case .none:
  198. return
  199. case .cacheTime:
  200. self.estimatedExpiration = expiration.estimatedExpirationSinceNow
  201. case .expirationTime(let expirationTime):
  202. self.estimatedExpiration = expirationTime.estimatedExpirationSinceNow
  203. }
  204. }
  205. var expired: Bool {
  206. return estimatedExpiration.isPast
  207. }
  208. }
  209. }