DiskStorage.swift 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. //
  2. // DiskStorage.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 disk.
  28. /// This is a namespace for the disk 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 DiskStorage {
  31. /// Represents a storage back-end for the `DiskStorage`. The value is serialized to data
  32. /// and stored as file in the file system under a specified location.
  33. ///
  34. /// You can config a `DiskStorage.Backend` in its initializer by passing a `DiskStorage.Config` value.
  35. /// or modifying the `config` property after it being created. `DiskStorage` will use file's attributes to keep
  36. /// track of a file for its expiration or size limitation.
  37. public class Backend<T: DataTransformable> {
  38. /// The config used for this disk storage.
  39. public var config: Config
  40. // The final storage URL on disk, with `name` and `cachePathBlock` considered.
  41. public let directoryURL: URL
  42. let metaChangingQueue: DispatchQueue
  43. var maybeCached : Set<String>?
  44. let maybeCachedCheckingQueue = DispatchQueue(label: "com.onevcat.Kingfisher.maybeCachedCheckingQueue")
  45. // `false` if the storage initialized with an error. This prevents unexpected forcibly crash when creating
  46. // storage in the default cache.
  47. private var storageReady: Bool = true
  48. /// Creates a disk storage with the given `DiskStorage.Config`.
  49. ///
  50. /// - Parameter config: The config used for this disk storage.
  51. /// - Throws: An error if the folder for storage cannot be got or created.
  52. public convenience init(config: Config) throws {
  53. self.init(noThrowConfig: config, creatingDirectory: false)
  54. try prepareDirectory()
  55. }
  56. // If `creatingDirectory` is `false`, the directory preparation will be skipped.
  57. // We need to call `prepareDirectory` manually after this returns.
  58. init(noThrowConfig config: Config, creatingDirectory: Bool) {
  59. var config = config
  60. let creation = Creation(config)
  61. self.directoryURL = creation.directoryURL
  62. // Break any possible retain cycle set by outside.
  63. config.cachePathBlock = nil
  64. self.config = config
  65. metaChangingQueue = DispatchQueue(label: creation.cacheName)
  66. setupCacheChecking()
  67. if creatingDirectory {
  68. try? prepareDirectory()
  69. }
  70. }
  71. private func setupCacheChecking() {
  72. maybeCachedCheckingQueue.async {
  73. do {
  74. self.maybeCached = Set()
  75. try self.config.fileManager.contentsOfDirectory(atPath: self.directoryURL.path).forEach { fileName in
  76. self.maybeCached?.insert(fileName)
  77. }
  78. } catch {
  79. // Just disable the functionality if we fail to initialize it properly. This will just revert to
  80. // the behavior which is to check file existence on disk directly.
  81. self.maybeCached = nil
  82. }
  83. }
  84. }
  85. // Creates the storage folder.
  86. private func prepareDirectory() throws {
  87. let fileManager = config.fileManager
  88. let path = directoryURL.path
  89. guard !fileManager.fileExists(atPath: path) else { return }
  90. do {
  91. try fileManager.createDirectory(
  92. atPath: path,
  93. withIntermediateDirectories: true,
  94. attributes: nil)
  95. } catch {
  96. self.storageReady = false
  97. throw KingfisherError.cacheError(reason: .cannotCreateDirectory(path: path, error: error))
  98. }
  99. }
  100. /// Stores a value to the storage under the specified key and expiration policy.
  101. /// - Parameters:
  102. /// - value: The value to be stored.
  103. /// - key: The key to which the `value` will be stored. If there is already a value under the key,
  104. /// the old value will be overwritten by `value`.
  105. /// - expiration: The expiration policy used by this store action.
  106. /// - Throws: An error during converting the value to a data format or during writing it to disk.
  107. public func store(
  108. value: T,
  109. forKey key: String,
  110. expiration: StorageExpiration? = nil) throws
  111. {
  112. guard storageReady else {
  113. throw KingfisherError.cacheError(reason: .diskStorageIsNotReady(cacheURL: directoryURL))
  114. }
  115. let expiration = expiration ?? config.expiration
  116. // The expiration indicates that already expired, no need to store.
  117. guard !expiration.isExpired else { return }
  118. let data: Data
  119. do {
  120. data = try value.toData()
  121. } catch {
  122. throw KingfisherError.cacheError(reason: .cannotConvertToData(object: value, error: error))
  123. }
  124. let fileURL = cacheFileURL(forKey: key)
  125. do {
  126. try data.write(to: fileURL)
  127. } catch {
  128. throw KingfisherError.cacheError(
  129. reason: .cannotCreateCacheFile(fileURL: fileURL, key: key, data: data, error: error)
  130. )
  131. }
  132. let now = Date()
  133. let attributes: [FileAttributeKey : Any] = [
  134. // The last access date.
  135. .creationDate: now.fileAttributeDate,
  136. // The estimated expiration date.
  137. .modificationDate: expiration.estimatedExpirationSinceNow.fileAttributeDate
  138. ]
  139. do {
  140. try config.fileManager.setAttributes(attributes, ofItemAtPath: fileURL.path)
  141. } catch {
  142. try? config.fileManager.removeItem(at: fileURL)
  143. throw KingfisherError.cacheError(
  144. reason: .cannotSetCacheFileAttribute(
  145. filePath: fileURL.path,
  146. attributes: attributes,
  147. error: error
  148. )
  149. )
  150. }
  151. maybeCachedCheckingQueue.async {
  152. self.maybeCached?.insert(fileURL.lastPathComponent)
  153. }
  154. }
  155. /// Gets a value from the storage.
  156. /// - Parameters:
  157. /// - key: The cache key of value.
  158. /// - extendingExpiration: The expiration policy used by this getting action.
  159. /// - Throws: An error during converting the data to a value or during operation of disk files.
  160. /// - Returns: The value under `key` if it is valid and found in the storage. Otherwise, `nil`.
  161. public func value(forKey key: String, extendingExpiration: ExpirationExtending = .cacheTime) throws -> T? {
  162. return try value(forKey: key, referenceDate: Date(), actuallyLoad: true, extendingExpiration: extendingExpiration)
  163. }
  164. func value(
  165. forKey key: String,
  166. referenceDate: Date,
  167. actuallyLoad: Bool,
  168. extendingExpiration: ExpirationExtending) throws -> T?
  169. {
  170. guard storageReady else {
  171. throw KingfisherError.cacheError(reason: .diskStorageIsNotReady(cacheURL: directoryURL))
  172. }
  173. let fileManager = config.fileManager
  174. let fileURL = cacheFileURL(forKey: key)
  175. let filePath = fileURL.path
  176. let fileMaybeCached = maybeCachedCheckingQueue.sync {
  177. return maybeCached?.contains(fileURL.lastPathComponent) ?? true
  178. }
  179. guard fileMaybeCached else {
  180. return nil
  181. }
  182. guard fileManager.fileExists(atPath: filePath) else {
  183. return nil
  184. }
  185. let meta: FileMeta
  186. do {
  187. let resourceKeys: Set<URLResourceKey> = [.contentModificationDateKey, .creationDateKey]
  188. meta = try FileMeta(fileURL: fileURL, resourceKeys: resourceKeys)
  189. } catch {
  190. throw KingfisherError.cacheError(
  191. reason: .invalidURLResource(error: error, key: key, url: fileURL))
  192. }
  193. if meta.expired(referenceDate: referenceDate) {
  194. return nil
  195. }
  196. if !actuallyLoad { return T.empty }
  197. do {
  198. let data = try Data(contentsOf: fileURL)
  199. let obj = try T.fromData(data)
  200. metaChangingQueue.async {
  201. meta.extendExpiration(with: fileManager, extendingExpiration: extendingExpiration)
  202. }
  203. return obj
  204. } catch {
  205. throw KingfisherError.cacheError(reason: .cannotLoadDataFromDisk(url: fileURL, error: error))
  206. }
  207. }
  208. /// Whether there is valid cached data under a given key.
  209. /// - Parameter key: The cache key of value.
  210. /// - Returns: If there is valid data under the key, `true`. Otherwise, `false`.
  211. ///
  212. /// - Note:
  213. /// This method does not actually load the data from disk, so it is faster than directly loading the cached value
  214. /// by checking the nullability of `value(forKey:extendingExpiration:)` method.
  215. ///
  216. public func isCached(forKey key: String) -> Bool {
  217. return isCached(forKey: key, referenceDate: Date())
  218. }
  219. /// Whether there is valid cached data under a given key and a reference date.
  220. /// - Parameters:
  221. /// - key: The cache key of value.
  222. /// - referenceDate: A reference date to check whether the cache is still valid.
  223. /// - Returns: If there is valid data under the key, `true`. Otherwise, `false`.
  224. ///
  225. /// - Note:
  226. /// If you pass `Date()` to `referenceDate`, this method is identical to `isCached(forKey:)`. Use the
  227. /// `referenceDate` to determine whether the cache is still valid for a future date.
  228. public func isCached(forKey key: String, referenceDate: Date) -> Bool {
  229. do {
  230. let result = try value(
  231. forKey: key,
  232. referenceDate: referenceDate,
  233. actuallyLoad: false,
  234. extendingExpiration: .none
  235. )
  236. return result != nil
  237. } catch {
  238. return false
  239. }
  240. }
  241. /// Removes a value from a specified key.
  242. /// - Parameter key: The cache key of value.
  243. /// - Throws: An error during removing the value.
  244. public func remove(forKey key: String) throws {
  245. let fileURL = cacheFileURL(forKey: key)
  246. try removeFile(at: fileURL)
  247. }
  248. func removeFile(at url: URL) throws {
  249. try config.fileManager.removeItem(at: url)
  250. }
  251. /// Removes all values in this storage.
  252. /// - Throws: An error during removing the values.
  253. public func removeAll() throws {
  254. try removeAll(skipCreatingDirectory: false)
  255. }
  256. func removeAll(skipCreatingDirectory: Bool) throws {
  257. try config.fileManager.removeItem(at: directoryURL)
  258. if !skipCreatingDirectory {
  259. try prepareDirectory()
  260. }
  261. }
  262. /// The URL of the cached file with a given computed `key`.
  263. ///
  264. /// - Parameter key: The final computed key used when caching the image. Please note that usually this is not
  265. /// the `cacheKey` of an image `Source`. It is the computed key with processor identifier considered.
  266. ///
  267. /// - Note:
  268. /// This method does not guarantee there is an image already cached in the returned URL. It just gives your
  269. /// the URL that the image should be if it exists in disk storage, with the give key.
  270. ///
  271. public func cacheFileURL(forKey key: String) -> URL {
  272. let fileName = cacheFileName(forKey: key)
  273. return directoryURL.appendingPathComponent(fileName, isDirectory: false)
  274. }
  275. func cacheFileName(forKey key: String) -> String {
  276. if config.usesHashedFileName {
  277. let hashedKey = key.kf.md5
  278. if let ext = config.pathExtension {
  279. return "\(hashedKey).\(ext)"
  280. }
  281. return hashedKey
  282. } else {
  283. if let ext = config.pathExtension {
  284. return "\(key).\(ext)"
  285. }
  286. return key
  287. }
  288. }
  289. func allFileURLs(for propertyKeys: [URLResourceKey]) throws -> [URL] {
  290. let fileManager = config.fileManager
  291. guard let directoryEnumerator = fileManager.enumerator(
  292. at: directoryURL, includingPropertiesForKeys: propertyKeys, options: .skipsHiddenFiles) else
  293. {
  294. throw KingfisherError.cacheError(reason: .fileEnumeratorCreationFailed(url: directoryURL))
  295. }
  296. guard let urls = directoryEnumerator.allObjects as? [URL] else {
  297. throw KingfisherError.cacheError(reason: .invalidFileEnumeratorContent(url: directoryURL))
  298. }
  299. return urls
  300. }
  301. /// Removes all expired values from this storage.
  302. /// - Throws: A file manager error during removing the file.
  303. /// - Returns: The URLs for removed files.
  304. public func removeExpiredValues() throws -> [URL] {
  305. return try removeExpiredValues(referenceDate: Date())
  306. }
  307. func removeExpiredValues(referenceDate: Date) throws -> [URL] {
  308. let propertyKeys: [URLResourceKey] = [
  309. .isDirectoryKey,
  310. .contentModificationDateKey
  311. ]
  312. let urls = try allFileURLs(for: propertyKeys)
  313. let keys = Set(propertyKeys)
  314. let expiredFiles = urls.filter { fileURL in
  315. do {
  316. let meta = try FileMeta(fileURL: fileURL, resourceKeys: keys)
  317. if meta.isDirectory {
  318. return false
  319. }
  320. return meta.expired(referenceDate: referenceDate)
  321. } catch {
  322. return true
  323. }
  324. }
  325. try expiredFiles.forEach { url in
  326. try removeFile(at: url)
  327. }
  328. return expiredFiles
  329. }
  330. /// Removes all size exceeded values from this storage.
  331. /// - Throws: A file manager error during removing the file.
  332. /// - Returns: The URLs for removed files.
  333. ///
  334. /// - Note: This method checks `config.sizeLimit` and remove cached files in an LRU (Least Recently Used) way.
  335. func removeSizeExceededValues() throws -> [URL] {
  336. if config.sizeLimit == 0 { return [] } // Back compatible. 0 means no limit.
  337. var size = try totalSize()
  338. if size < config.sizeLimit { return [] }
  339. let propertyKeys: [URLResourceKey] = [
  340. .isDirectoryKey,
  341. .creationDateKey,
  342. .fileSizeKey
  343. ]
  344. let keys = Set(propertyKeys)
  345. let urls = try allFileURLs(for: propertyKeys)
  346. var pendings: [FileMeta] = urls.compactMap { fileURL in
  347. guard let meta = try? FileMeta(fileURL: fileURL, resourceKeys: keys) else {
  348. return nil
  349. }
  350. return meta
  351. }
  352. // Sort by last access date. Most recent file first.
  353. pendings.sort(by: FileMeta.lastAccessDate)
  354. var removed: [URL] = []
  355. let target = config.sizeLimit / 2
  356. while size > target, let meta = pendings.popLast() {
  357. size -= UInt(meta.fileSize)
  358. try removeFile(at: meta.url)
  359. removed.append(meta.url)
  360. }
  361. return removed
  362. }
  363. /// Gets the total file size of the folder in bytes.
  364. public func totalSize() throws -> UInt {
  365. let propertyKeys: [URLResourceKey] = [.fileSizeKey]
  366. let urls = try allFileURLs(for: propertyKeys)
  367. let keys = Set(propertyKeys)
  368. let totalSize: UInt = urls.reduce(0) { size, fileURL in
  369. do {
  370. let meta = try FileMeta(fileURL: fileURL, resourceKeys: keys)
  371. return size + UInt(meta.fileSize)
  372. } catch {
  373. return size
  374. }
  375. }
  376. return totalSize
  377. }
  378. }
  379. }
  380. extension DiskStorage {
  381. /// Represents the config used in a `DiskStorage`.
  382. public struct Config {
  383. /// The file size limit on disk of the storage in bytes. 0 means no limit.
  384. public var sizeLimit: UInt
  385. /// The `StorageExpiration` used in this disk storage. Default is `.days(7)`,
  386. /// means that the disk cache would expire in one week.
  387. public var expiration: StorageExpiration = .days(7)
  388. /// The preferred extension of cache item. It will be appended to the file name as its extension.
  389. /// Default is `nil`, means that the cache file does not contain a file extension.
  390. public var pathExtension: String? = nil
  391. /// Default is `true`, means that the cache file name will be hashed before storing.
  392. public var usesHashedFileName = true
  393. let name: String
  394. let fileManager: FileManager
  395. let directory: URL?
  396. var cachePathBlock: ((_ directory: URL, _ cacheName: String) -> URL)! = {
  397. (directory, cacheName) in
  398. return directory.appendingPathComponent(cacheName, isDirectory: true)
  399. }
  400. /// Creates a config value based on given parameters.
  401. ///
  402. /// - Parameters:
  403. /// - name: The name of cache. It is used as a part of storage folder. It is used to identify the disk
  404. /// storage. Two storages with the same `name` would share the same folder in disk, and it should
  405. /// be prevented.
  406. /// - sizeLimit: The size limit in bytes for all existing files in the disk storage.
  407. /// - fileManager: The `FileManager` used to manipulate files on disk. Default is `FileManager.default`.
  408. /// - directory: The URL where the disk storage should live. The storage will use this as the root folder,
  409. /// and append a path which is constructed by input `name`. Default is `nil`, indicates that
  410. /// the cache directory under user domain mask will be used.
  411. public init(
  412. name: String,
  413. sizeLimit: UInt,
  414. fileManager: FileManager = .default,
  415. directory: URL? = nil)
  416. {
  417. self.name = name
  418. self.fileManager = fileManager
  419. self.directory = directory
  420. self.sizeLimit = sizeLimit
  421. }
  422. }
  423. }
  424. extension DiskStorage {
  425. struct FileMeta {
  426. let url: URL
  427. let lastAccessDate: Date?
  428. let estimatedExpirationDate: Date?
  429. let isDirectory: Bool
  430. let fileSize: Int
  431. static func lastAccessDate(lhs: FileMeta, rhs: FileMeta) -> Bool {
  432. return lhs.lastAccessDate ?? .distantPast > rhs.lastAccessDate ?? .distantPast
  433. }
  434. init(fileURL: URL, resourceKeys: Set<URLResourceKey>) throws {
  435. let meta = try fileURL.resourceValues(forKeys: resourceKeys)
  436. self.init(
  437. fileURL: fileURL,
  438. lastAccessDate: meta.creationDate,
  439. estimatedExpirationDate: meta.contentModificationDate,
  440. isDirectory: meta.isDirectory ?? false,
  441. fileSize: meta.fileSize ?? 0)
  442. }
  443. init(
  444. fileURL: URL,
  445. lastAccessDate: Date?,
  446. estimatedExpirationDate: Date?,
  447. isDirectory: Bool,
  448. fileSize: Int)
  449. {
  450. self.url = fileURL
  451. self.lastAccessDate = lastAccessDate
  452. self.estimatedExpirationDate = estimatedExpirationDate
  453. self.isDirectory = isDirectory
  454. self.fileSize = fileSize
  455. }
  456. func expired(referenceDate: Date) -> Bool {
  457. return estimatedExpirationDate?.isPast(referenceDate: referenceDate) ?? true
  458. }
  459. func extendExpiration(with fileManager: FileManager, extendingExpiration: ExpirationExtending) {
  460. guard let lastAccessDate = lastAccessDate,
  461. let lastEstimatedExpiration = estimatedExpirationDate else
  462. {
  463. return
  464. }
  465. let attributes: [FileAttributeKey : Any]
  466. switch extendingExpiration {
  467. case .none:
  468. // not extending expiration time here
  469. return
  470. case .cacheTime:
  471. let originalExpiration: StorageExpiration =
  472. .seconds(lastEstimatedExpiration.timeIntervalSince(lastAccessDate))
  473. attributes = [
  474. .creationDate: Date().fileAttributeDate,
  475. .modificationDate: originalExpiration.estimatedExpirationSinceNow.fileAttributeDate
  476. ]
  477. case .expirationTime(let expirationTime):
  478. attributes = [
  479. .creationDate: Date().fileAttributeDate,
  480. .modificationDate: expirationTime.estimatedExpirationSinceNow.fileAttributeDate
  481. ]
  482. }
  483. try? fileManager.setAttributes(attributes, ofItemAtPath: url.path)
  484. }
  485. }
  486. }
  487. extension DiskStorage {
  488. struct Creation {
  489. let directoryURL: URL
  490. let cacheName: String
  491. init(_ config: Config) {
  492. let url: URL
  493. if let directory = config.directory {
  494. url = directory
  495. } else {
  496. url = config.fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0]
  497. }
  498. cacheName = "com.onevcat.Kingfisher.ImageCache.\(config.name)"
  499. directoryURL = config.cachePathBlock(url, cacheName)
  500. }
  501. }
  502. }