DiskStorage.swift 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  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. func store(
  101. value: T,
  102. forKey key: String,
  103. expiration: StorageExpiration? = nil) throws
  104. {
  105. guard storageReady else {
  106. throw KingfisherError.cacheError(reason: .diskStorageIsNotReady(cacheURL: directoryURL))
  107. }
  108. let expiration = expiration ?? config.expiration
  109. // The expiration indicates that already expired, no need to store.
  110. guard !expiration.isExpired else { return }
  111. let data: Data
  112. do {
  113. data = try value.toData()
  114. } catch {
  115. throw KingfisherError.cacheError(reason: .cannotConvertToData(object: value, error: error))
  116. }
  117. let fileURL = cacheFileURL(forKey: key)
  118. do {
  119. try data.write(to: fileURL)
  120. } catch {
  121. throw KingfisherError.cacheError(
  122. reason: .cannotCreateCacheFile(fileURL: fileURL, key: key, data: data, error: error)
  123. )
  124. }
  125. let now = Date()
  126. let attributes: [FileAttributeKey : Any] = [
  127. // The last access date.
  128. .creationDate: now.fileAttributeDate,
  129. // The estimated expiration date.
  130. .modificationDate: expiration.estimatedExpirationSinceNow.fileAttributeDate
  131. ]
  132. do {
  133. try config.fileManager.setAttributes(attributes, ofItemAtPath: fileURL.path)
  134. } catch {
  135. try? config.fileManager.removeItem(at: fileURL)
  136. throw KingfisherError.cacheError(
  137. reason: .cannotSetCacheFileAttribute(
  138. filePath: fileURL.path,
  139. attributes: attributes,
  140. error: error
  141. )
  142. )
  143. }
  144. maybeCachedCheckingQueue.async {
  145. self.maybeCached?.insert(fileURL.lastPathComponent)
  146. }
  147. }
  148. func value(forKey key: String, extendingExpiration: ExpirationExtending = .cacheTime) throws -> T? {
  149. return try value(forKey: key, referenceDate: Date(), actuallyLoad: true, extendingExpiration: extendingExpiration)
  150. }
  151. func value(
  152. forKey key: String,
  153. referenceDate: Date,
  154. actuallyLoad: Bool,
  155. extendingExpiration: ExpirationExtending) throws -> T?
  156. {
  157. guard storageReady else {
  158. throw KingfisherError.cacheError(reason: .diskStorageIsNotReady(cacheURL: directoryURL))
  159. }
  160. let fileManager = config.fileManager
  161. let fileURL = cacheFileURL(forKey: key)
  162. let filePath = fileURL.path
  163. let fileMaybeCached = maybeCachedCheckingQueue.sync {
  164. return maybeCached?.contains(fileURL.lastPathComponent) ?? true
  165. }
  166. guard fileMaybeCached else {
  167. return nil
  168. }
  169. guard fileManager.fileExists(atPath: filePath) else {
  170. return nil
  171. }
  172. let meta: FileMeta
  173. do {
  174. let resourceKeys: Set<URLResourceKey> = [.contentModificationDateKey, .creationDateKey]
  175. meta = try FileMeta(fileURL: fileURL, resourceKeys: resourceKeys)
  176. } catch {
  177. throw KingfisherError.cacheError(
  178. reason: .invalidURLResource(error: error, key: key, url: fileURL))
  179. }
  180. if meta.expired(referenceDate: referenceDate) {
  181. return nil
  182. }
  183. if !actuallyLoad { return T.empty }
  184. do {
  185. let data = try Data(contentsOf: fileURL)
  186. let obj = try T.fromData(data)
  187. metaChangingQueue.async {
  188. meta.extendExpiration(with: fileManager, extendingExpiration: extendingExpiration)
  189. }
  190. return obj
  191. } catch {
  192. throw KingfisherError.cacheError(reason: .cannotLoadDataFromDisk(url: fileURL, error: error))
  193. }
  194. }
  195. func isCached(forKey key: String) -> Bool {
  196. return isCached(forKey: key, referenceDate: Date())
  197. }
  198. func isCached(forKey key: String, referenceDate: Date) -> Bool {
  199. do {
  200. let result = try value(
  201. forKey: key,
  202. referenceDate: referenceDate,
  203. actuallyLoad: false,
  204. extendingExpiration: .none
  205. )
  206. return result != nil
  207. } catch {
  208. return false
  209. }
  210. }
  211. func remove(forKey key: String) throws {
  212. let fileURL = cacheFileURL(forKey: key)
  213. try removeFile(at: fileURL)
  214. }
  215. func removeFile(at url: URL) throws {
  216. try config.fileManager.removeItem(at: url)
  217. }
  218. func removeAll() throws {
  219. try removeAll(skipCreatingDirectory: false)
  220. }
  221. func removeAll(skipCreatingDirectory: Bool) throws {
  222. try config.fileManager.removeItem(at: directoryURL)
  223. if !skipCreatingDirectory {
  224. try prepareDirectory()
  225. }
  226. }
  227. /// The URL of the cached file with a given computed `key`.
  228. ///
  229. /// - Note:
  230. /// This method does not guarantee there is an image already cached in the returned URL. It just gives your
  231. /// the URL that the image should be if it exists in disk storage, with the give key.
  232. ///
  233. /// - Parameter key: The final computed key used when caching the image. Please note that usually this is not
  234. /// the `cacheKey` of an image `Source`. It is the computed key with processor identifier considered.
  235. public func cacheFileURL(forKey key: String) -> URL {
  236. let fileName = cacheFileName(forKey: key)
  237. return directoryURL.appendingPathComponent(fileName, isDirectory: false)
  238. }
  239. func cacheFileName(forKey key: String) -> String {
  240. if config.usesHashedFileName {
  241. let hashedKey = key.kf.md5
  242. if let ext = config.pathExtension {
  243. return "\(hashedKey).\(ext)"
  244. }
  245. return hashedKey
  246. } else {
  247. if let ext = config.pathExtension {
  248. return "\(key).\(ext)"
  249. }
  250. return key
  251. }
  252. }
  253. func allFileURLs(for propertyKeys: [URLResourceKey]) throws -> [URL] {
  254. let fileManager = config.fileManager
  255. guard let directoryEnumerator = fileManager.enumerator(
  256. at: directoryURL, includingPropertiesForKeys: propertyKeys, options: .skipsHiddenFiles) else
  257. {
  258. throw KingfisherError.cacheError(reason: .fileEnumeratorCreationFailed(url: directoryURL))
  259. }
  260. guard let urls = directoryEnumerator.allObjects as? [URL] else {
  261. throw KingfisherError.cacheError(reason: .invalidFileEnumeratorContent(url: directoryURL))
  262. }
  263. return urls
  264. }
  265. func removeExpiredValues(referenceDate: Date = Date()) throws -> [URL] {
  266. let propertyKeys: [URLResourceKey] = [
  267. .isDirectoryKey,
  268. .contentModificationDateKey
  269. ]
  270. let urls = try allFileURLs(for: propertyKeys)
  271. let keys = Set(propertyKeys)
  272. let expiredFiles = urls.filter { fileURL in
  273. do {
  274. let meta = try FileMeta(fileURL: fileURL, resourceKeys: keys)
  275. if meta.isDirectory {
  276. return false
  277. }
  278. return meta.expired(referenceDate: referenceDate)
  279. } catch {
  280. return true
  281. }
  282. }
  283. try expiredFiles.forEach { url in
  284. try removeFile(at: url)
  285. }
  286. return expiredFiles
  287. }
  288. func removeSizeExceededValues() throws -> [URL] {
  289. if config.sizeLimit == 0 { return [] } // Back compatible. 0 means no limit.
  290. var size = try totalSize()
  291. if size < config.sizeLimit { return [] }
  292. let propertyKeys: [URLResourceKey] = [
  293. .isDirectoryKey,
  294. .creationDateKey,
  295. .fileSizeKey
  296. ]
  297. let keys = Set(propertyKeys)
  298. let urls = try allFileURLs(for: propertyKeys)
  299. var pendings: [FileMeta] = urls.compactMap { fileURL in
  300. guard let meta = try? FileMeta(fileURL: fileURL, resourceKeys: keys) else {
  301. return nil
  302. }
  303. return meta
  304. }
  305. // Sort by last access date. Most recent file first.
  306. pendings.sort(by: FileMeta.lastAccessDate)
  307. var removed: [URL] = []
  308. let target = config.sizeLimit / 2
  309. while size > target, let meta = pendings.popLast() {
  310. size -= UInt(meta.fileSize)
  311. try removeFile(at: meta.url)
  312. removed.append(meta.url)
  313. }
  314. return removed
  315. }
  316. /// Get the total file size of the folder in bytes.
  317. func totalSize() throws -> UInt {
  318. let propertyKeys: [URLResourceKey] = [.fileSizeKey]
  319. let urls = try allFileURLs(for: propertyKeys)
  320. let keys = Set(propertyKeys)
  321. let totalSize: UInt = urls.reduce(0) { size, fileURL in
  322. do {
  323. let meta = try FileMeta(fileURL: fileURL, resourceKeys: keys)
  324. return size + UInt(meta.fileSize)
  325. } catch {
  326. return size
  327. }
  328. }
  329. return totalSize
  330. }
  331. }
  332. }
  333. extension DiskStorage {
  334. /// Represents the config used in a `DiskStorage`.
  335. public struct Config {
  336. /// The file size limit on disk of the storage in bytes. 0 means no limit.
  337. public var sizeLimit: UInt
  338. /// The `StorageExpiration` used in this disk storage. Default is `.days(7)`,
  339. /// means that the disk cache would expire in one week.
  340. public var expiration: StorageExpiration = .days(7)
  341. /// The preferred extension of cache item. It will be appended to the file name as its extension.
  342. /// Default is `nil`, means that the cache file does not contain a file extension.
  343. public var pathExtension: String? = nil
  344. /// Default is `true`, means that the cache file name will be hashed before storing.
  345. public var usesHashedFileName = true
  346. let name: String
  347. let fileManager: FileManager
  348. let directory: URL?
  349. var cachePathBlock: ((_ directory: URL, _ cacheName: String) -> URL)! = {
  350. (directory, cacheName) in
  351. return directory.appendingPathComponent(cacheName, isDirectory: true)
  352. }
  353. /// Creates a config value based on given parameters.
  354. ///
  355. /// - Parameters:
  356. /// - name: The name of cache. It is used as a part of storage folder. It is used to identify the disk
  357. /// storage. Two storages with the same `name` would share the same folder in disk, and it should
  358. /// be prevented.
  359. /// - sizeLimit: The size limit in bytes for all existing files in the disk storage.
  360. /// - fileManager: The `FileManager` used to manipulate files on disk. Default is `FileManager.default`.
  361. /// - directory: The URL where the disk storage should live. The storage will use this as the root folder,
  362. /// and append a path which is constructed by input `name`. Default is `nil`, indicates that
  363. /// the cache directory under user domain mask will be used.
  364. public init(
  365. name: String,
  366. sizeLimit: UInt,
  367. fileManager: FileManager = .default,
  368. directory: URL? = nil)
  369. {
  370. self.name = name
  371. self.fileManager = fileManager
  372. self.directory = directory
  373. self.sizeLimit = sizeLimit
  374. }
  375. }
  376. }
  377. extension DiskStorage {
  378. struct FileMeta {
  379. let url: URL
  380. let lastAccessDate: Date?
  381. let estimatedExpirationDate: Date?
  382. let isDirectory: Bool
  383. let fileSize: Int
  384. static func lastAccessDate(lhs: FileMeta, rhs: FileMeta) -> Bool {
  385. return lhs.lastAccessDate ?? .distantPast > rhs.lastAccessDate ?? .distantPast
  386. }
  387. init(fileURL: URL, resourceKeys: Set<URLResourceKey>) throws {
  388. let meta = try fileURL.resourceValues(forKeys: resourceKeys)
  389. self.init(
  390. fileURL: fileURL,
  391. lastAccessDate: meta.creationDate,
  392. estimatedExpirationDate: meta.contentModificationDate,
  393. isDirectory: meta.isDirectory ?? false,
  394. fileSize: meta.fileSize ?? 0)
  395. }
  396. init(
  397. fileURL: URL,
  398. lastAccessDate: Date?,
  399. estimatedExpirationDate: Date?,
  400. isDirectory: Bool,
  401. fileSize: Int)
  402. {
  403. self.url = fileURL
  404. self.lastAccessDate = lastAccessDate
  405. self.estimatedExpirationDate = estimatedExpirationDate
  406. self.isDirectory = isDirectory
  407. self.fileSize = fileSize
  408. }
  409. func expired(referenceDate: Date) -> Bool {
  410. return estimatedExpirationDate?.isPast(referenceDate: referenceDate) ?? true
  411. }
  412. func extendExpiration(with fileManager: FileManager, extendingExpiration: ExpirationExtending) {
  413. guard let lastAccessDate = lastAccessDate,
  414. let lastEstimatedExpiration = estimatedExpirationDate else
  415. {
  416. return
  417. }
  418. let attributes: [FileAttributeKey : Any]
  419. switch extendingExpiration {
  420. case .none:
  421. // not extending expiration time here
  422. return
  423. case .cacheTime:
  424. let originalExpiration: StorageExpiration =
  425. .seconds(lastEstimatedExpiration.timeIntervalSince(lastAccessDate))
  426. attributes = [
  427. .creationDate: Date().fileAttributeDate,
  428. .modificationDate: originalExpiration.estimatedExpirationSinceNow.fileAttributeDate
  429. ]
  430. case .expirationTime(let expirationTime):
  431. attributes = [
  432. .creationDate: Date().fileAttributeDate,
  433. .modificationDate: expirationTime.estimatedExpirationSinceNow.fileAttributeDate
  434. ]
  435. }
  436. try? fileManager.setAttributes(attributes, ofItemAtPath: url.path)
  437. }
  438. }
  439. }
  440. extension DiskStorage {
  441. struct Creation {
  442. let directoryURL: URL
  443. let cacheName: String
  444. init(_ config: Config) {
  445. let url: URL
  446. if let directory = config.directory {
  447. url = directory
  448. } else {
  449. url = config.fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0]
  450. }
  451. cacheName = "com.onevcat.Kingfisher.ImageCache.\(config.name)"
  452. directoryURL = config.cachePathBlock(url, cacheName)
  453. }
  454. }
  455. }