DiskStorage.swift 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  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. } else if config.autoExtAfterHashedFileName,
  281. let ext = key.kf.ext {
  282. return "\(hashedKey).\(ext)"
  283. }
  284. return hashedKey
  285. } else {
  286. if let ext = config.pathExtension {
  287. return "\(key).\(ext)"
  288. }
  289. return key
  290. }
  291. }
  292. func allFileURLs(for propertyKeys: [URLResourceKey]) throws -> [URL] {
  293. let fileManager = config.fileManager
  294. guard let directoryEnumerator = fileManager.enumerator(
  295. at: directoryURL, includingPropertiesForKeys: propertyKeys, options: .skipsHiddenFiles) else
  296. {
  297. throw KingfisherError.cacheError(reason: .fileEnumeratorCreationFailed(url: directoryURL))
  298. }
  299. guard let urls = directoryEnumerator.allObjects as? [URL] else {
  300. throw KingfisherError.cacheError(reason: .invalidFileEnumeratorContent(url: directoryURL))
  301. }
  302. return urls
  303. }
  304. /// Removes all expired values from this storage.
  305. /// - Throws: A file manager error during removing the file.
  306. /// - Returns: The URLs for removed files.
  307. public func removeExpiredValues() throws -> [URL] {
  308. return try removeExpiredValues(referenceDate: Date())
  309. }
  310. func removeExpiredValues(referenceDate: Date) throws -> [URL] {
  311. let propertyKeys: [URLResourceKey] = [
  312. .isDirectoryKey,
  313. .contentModificationDateKey
  314. ]
  315. let urls = try allFileURLs(for: propertyKeys)
  316. let keys = Set(propertyKeys)
  317. let expiredFiles = urls.filter { fileURL in
  318. do {
  319. let meta = try FileMeta(fileURL: fileURL, resourceKeys: keys)
  320. if meta.isDirectory {
  321. return false
  322. }
  323. return meta.expired(referenceDate: referenceDate)
  324. } catch {
  325. return true
  326. }
  327. }
  328. try expiredFiles.forEach { url in
  329. try removeFile(at: url)
  330. }
  331. return expiredFiles
  332. }
  333. /// Removes all size exceeded values from this storage.
  334. /// - Throws: A file manager error during removing the file.
  335. /// - Returns: The URLs for removed files.
  336. ///
  337. /// - Note: This method checks `config.sizeLimit` and remove cached files in an LRU (Least Recently Used) way.
  338. func removeSizeExceededValues() throws -> [URL] {
  339. if config.sizeLimit == 0 { return [] } // Back compatible. 0 means no limit.
  340. var size = try totalSize()
  341. if size < config.sizeLimit { return [] }
  342. let propertyKeys: [URLResourceKey] = [
  343. .isDirectoryKey,
  344. .creationDateKey,
  345. .fileSizeKey
  346. ]
  347. let keys = Set(propertyKeys)
  348. let urls = try allFileURLs(for: propertyKeys)
  349. var pendings: [FileMeta] = urls.compactMap { fileURL in
  350. guard let meta = try? FileMeta(fileURL: fileURL, resourceKeys: keys) else {
  351. return nil
  352. }
  353. return meta
  354. }
  355. // Sort by last access date. Most recent file first.
  356. pendings.sort(by: FileMeta.lastAccessDate)
  357. var removed: [URL] = []
  358. let target = config.sizeLimit / 2
  359. while size > target, let meta = pendings.popLast() {
  360. size -= UInt(meta.fileSize)
  361. try removeFile(at: meta.url)
  362. removed.append(meta.url)
  363. }
  364. return removed
  365. }
  366. /// Gets the total file size of the folder in bytes.
  367. public func totalSize() throws -> UInt {
  368. let propertyKeys: [URLResourceKey] = [.fileSizeKey]
  369. let urls = try allFileURLs(for: propertyKeys)
  370. let keys = Set(propertyKeys)
  371. let totalSize: UInt = urls.reduce(0) { size, fileURL in
  372. do {
  373. let meta = try FileMeta(fileURL: fileURL, resourceKeys: keys)
  374. return size + UInt(meta.fileSize)
  375. } catch {
  376. return size
  377. }
  378. }
  379. return totalSize
  380. }
  381. }
  382. }
  383. extension DiskStorage {
  384. /// Represents the config used in a `DiskStorage`.
  385. public struct Config {
  386. /// The file size limit on disk of the storage in bytes. 0 means no limit.
  387. public var sizeLimit: UInt
  388. /// The `StorageExpiration` used in this disk storage. Default is `.days(7)`,
  389. /// means that the disk cache would expire in one week.
  390. public var expiration: StorageExpiration = .days(7)
  391. /// The preferred extension of cache item. It will be appended to the file name as its extension.
  392. /// Default is `nil`, means that the cache file does not contain a file extension.
  393. public var pathExtension: String? = nil
  394. /// Default is `true`, means that the cache file name will be hashed before storing.
  395. public var usesHashedFileName = true
  396. /// Default is `false`
  397. /// If set to `true`, image extension will be extracted from original file name and append to
  398. /// the hased file name and used as the cache key on disk.
  399. public var autoExtAfterHashedFileName = false
  400. let name: String
  401. let fileManager: FileManager
  402. let directory: URL?
  403. var cachePathBlock: ((_ directory: URL, _ cacheName: String) -> URL)! = {
  404. (directory, cacheName) in
  405. return directory.appendingPathComponent(cacheName, isDirectory: true)
  406. }
  407. /// Creates a config value based on given parameters.
  408. ///
  409. /// - Parameters:
  410. /// - name: The name of cache. It is used as a part of storage folder. It is used to identify the disk
  411. /// storage. Two storages with the same `name` would share the same folder in disk, and it should
  412. /// be prevented.
  413. /// - sizeLimit: The size limit in bytes for all existing files in the disk storage.
  414. /// - fileManager: The `FileManager` used to manipulate files on disk. Default is `FileManager.default`.
  415. /// - directory: The URL where the disk storage should live. The storage will use this as the root folder,
  416. /// and append a path which is constructed by input `name`. Default is `nil`, indicates that
  417. /// the cache directory under user domain mask will be used.
  418. public init(
  419. name: String,
  420. sizeLimit: UInt,
  421. fileManager: FileManager = .default,
  422. directory: URL? = nil)
  423. {
  424. self.name = name
  425. self.fileManager = fileManager
  426. self.directory = directory
  427. self.sizeLimit = sizeLimit
  428. }
  429. }
  430. }
  431. extension DiskStorage {
  432. struct FileMeta {
  433. let url: URL
  434. let lastAccessDate: Date?
  435. let estimatedExpirationDate: Date?
  436. let isDirectory: Bool
  437. let fileSize: Int
  438. static func lastAccessDate(lhs: FileMeta, rhs: FileMeta) -> Bool {
  439. return lhs.lastAccessDate ?? .distantPast > rhs.lastAccessDate ?? .distantPast
  440. }
  441. init(fileURL: URL, resourceKeys: Set<URLResourceKey>) throws {
  442. let meta = try fileURL.resourceValues(forKeys: resourceKeys)
  443. self.init(
  444. fileURL: fileURL,
  445. lastAccessDate: meta.creationDate,
  446. estimatedExpirationDate: meta.contentModificationDate,
  447. isDirectory: meta.isDirectory ?? false,
  448. fileSize: meta.fileSize ?? 0)
  449. }
  450. init(
  451. fileURL: URL,
  452. lastAccessDate: Date?,
  453. estimatedExpirationDate: Date?,
  454. isDirectory: Bool,
  455. fileSize: Int)
  456. {
  457. self.url = fileURL
  458. self.lastAccessDate = lastAccessDate
  459. self.estimatedExpirationDate = estimatedExpirationDate
  460. self.isDirectory = isDirectory
  461. self.fileSize = fileSize
  462. }
  463. func expired(referenceDate: Date) -> Bool {
  464. return estimatedExpirationDate?.isPast(referenceDate: referenceDate) ?? true
  465. }
  466. func extendExpiration(with fileManager: FileManager, extendingExpiration: ExpirationExtending) {
  467. guard let lastAccessDate = lastAccessDate,
  468. let lastEstimatedExpiration = estimatedExpirationDate else
  469. {
  470. return
  471. }
  472. let attributes: [FileAttributeKey : Any]
  473. switch extendingExpiration {
  474. case .none:
  475. // not extending expiration time here
  476. return
  477. case .cacheTime:
  478. let originalExpiration: StorageExpiration =
  479. .seconds(lastEstimatedExpiration.timeIntervalSince(lastAccessDate))
  480. attributes = [
  481. .creationDate: Date().fileAttributeDate,
  482. .modificationDate: originalExpiration.estimatedExpirationSinceNow.fileAttributeDate
  483. ]
  484. case .expirationTime(let expirationTime):
  485. attributes = [
  486. .creationDate: Date().fileAttributeDate,
  487. .modificationDate: expirationTime.estimatedExpirationSinceNow.fileAttributeDate
  488. ]
  489. }
  490. try? fileManager.setAttributes(attributes, ofItemAtPath: url.path)
  491. }
  492. }
  493. }
  494. extension DiskStorage {
  495. struct Creation {
  496. let directoryURL: URL
  497. let cacheName: String
  498. init(_ config: Config) {
  499. let url: URL
  500. if let directory = config.directory {
  501. url = directory
  502. } else {
  503. url = config.fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0]
  504. }
  505. cacheName = "com.onevcat.Kingfisher.ImageCache.\(config.name)"
  506. directoryURL = config.cachePathBlock(url, cacheName)
  507. }
  508. }
  509. }