diff --git a/CHANGELOG.md b/CHANGELOG.md index 1532075..4506a5e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,26 @@ # Changelog +## Unreleased + +Removed +- `ImageWrapper`, the `Image` typealias, `JSONArrayWrapper`, `JSONDictionaryWrapper`, `JSONArray` and `JSONDictionary`. The package no longer depends on UIKit or AppKit. +- `DiskConfig.maxSize`, which was only enforced by `removeExpiredObjects()`. +- `Entry.meta`, which was always empty. +- The public `StorageAware` protocol. Use `Storage`. + +Behaviour changes +- `entry(ofType:forKey:)` treats an expired object as missing and throws `StorageError.notFound`, like `object(ofType:forKey:)`. Disk reads check the expiry first, so an expired object isn't read or decoded. +- Objects are stored without a wrapper, and `Data` is stored as it is instead of base64 in JSON. That takes about a quarter less disk space for `Data`. + +Added +- `Storage.diskSize()`. + +Upgrading +- Existing caches start empty. Files from 4.x are never read, and `removeExpiredObjects()` removes them. They stay on disk until then, or until `removeAll()`. +- `removeExpiredObjects()` deletes every file in the folder that isn't one of the storage's objects, hidden files included, so keep nothing else in it. +- Replace `entry(...)` followed by an `isExpired` check with `object(...)`, or just remove the check. +- Remove `maxSize:` from `DiskConfig(...)`. + ## 4.10.1 Bug fixes diff --git a/Playgrounds/Storage.playground/Contents.swift b/Playgrounds/Storage.playground/Contents.swift index b795ec4..be2313f 100644 --- a/Playgrounds/Storage.playground/Contents.swift +++ b/Playgrounds/Storage.playground/Contents.swift @@ -4,19 +4,6 @@ import UIKit import Cache enum Helper { - static func image(_ color: UIColor = .red, size: CGSize = .init(width: 1, height: 1)) -> UIImage { - UIGraphicsBeginImageContextWithOptions(size, false, 1) - - let context = UIGraphicsGetCurrentContext() - context?.setFillColor(color.cgColor) - context?.fill(CGRect(x: 0, y: 0, width: size.width, height: size.height)) - - let image = UIGraphicsGetImageFromCurrentImageContext() - UIGraphicsEndImageContext() - - return image! - } - static func data(length: Int) -> Data { var buffer = [UInt8](repeating: 0, count: length) return Data(bytes: &buffer, count: length) @@ -29,19 +16,12 @@ let diskConfig = DiskConfig(name: "Mix") let storage = try! Storage(diskConfig: diskConfig) -// We already have Codable conformances for: -// String, UIImage, NSData and NSDate (just for fun =) - let string = "This is a string" -let image = Helper.image() -let imageWrapper = ImageWrapper(image: image) -let newImage = imageWrapper.image let data = Helper.data(length: 64) let date = Date(timeInterval: 100_000, since: Date()) // Add objects to the cache try storage.setObject(string, forKey: "string") -try storage.setObject(imageWrapper, forKey: "imageWrapper") try storage.setObject(data, forKey: "data") try storage.setObject(date, forKey: "date") /// @@ -49,11 +29,6 @@ try storage.setObject(date, forKey: "date") let cachedString = try? storage.object(ofType: String.self, forKey: "string") print(cachedString ?? "") -if let imageWrapper = try? storage.object(ofType: ImageWrapper.self, forKey: "imageWrapper") { - let image = imageWrapper.image - print(image) -} - if let data = try? storage.object(ofType: Data.self, forKey: "data") { print(data) } diff --git a/README.md b/README.md index 34a167a..7bb4e71 100644 --- a/README.md +++ b/README.md @@ -1,228 +1,90 @@ -## Table of Contents - -* [Description](#description) -* [Key features](#key-features) -* [Usage](#usage) - * [Storage](#storage) - * [Configuration](#configuration) - * [APIs](#apis) - * [Expiry date](#expiry-date) -* [What about images?](#what-about-images) -* [Authors](#authors) -* [License](#license) - -## Description - -**Cache** doesn't claim to be unique in this area, but it's not another monster -library that gives you a god's power. It does nothing but caching, but it does it well. It offers a good public API -with out-of-box implementations and great customization possibilities. `Cache` utilizes `Codable` to perform serialization. - -## Key features - -- [x] Works with `Codable` and `Sendable`. Anything conforming to both will be saved and loaded easily by `Storage`. -- [x] Disk, memory, or hybrid storage modes. -- [x] Many options via `DiskConfig` and `MemoryConfig`. -- [x] Support `expiry` and clean up of expired objects. -- [x] Thread safe. `Storage` is `Sendable` and can be accessed from any queue. -- [x] Store images via `ImageWrapper`. -- [x] iOS, tvOS, macOS, watchOS and visionOS support. +# Cache -## Usage - -### Storage +Stores `Codable & Sendable` values on disk, in memory, or both, with expiry. Thread safe. -`Cache` is built based on [Chain-of-responsibility pattern](https://en.wikipedia.org/wiki/Chain-of-responsibility_pattern), in which there are many processing objects, each knows how to do 1 task and delegates to the next one. But that's just implementation detail. All you need to know is `Storage`, it saves and loads `Codable` objects. +Requires iOS 16, macOS 13, tvOS 16, watchOS 9 or visionOS 1. -`Storage` supports three modes: disk-only, memory-only, or hybrid (memory + disk). Memory storage is fast but volatile, while disk storage persists across application launches. +## Installation ```swift -// Disk only -let diskConfig = DiskConfig(name: "Floppy") -let storage = try Storage(diskConfig: diskConfig) - -// Hybrid (memory + disk) -let memoryConfig = MemoryConfig(expiry: .never, countLimit: 10) -let storage = try Storage(diskConfig: diskConfig, memoryConfig: memoryConfig) - -// Memory only -let storage = Storage(memoryConfig: MemoryConfig(expiry: .never, countLimit: 50)) +.package(url: "https://github.com/voyager-software/Cache.git", from: "5.0.0") ``` -#### Codable types - -`Storage` supports any objects that conform to [Codable](https://developer.apple.com/documentation/swift/codable) protocol. You can [make your own things conform to Codable](https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types) so that can be saved and loaded from `Storage`. - -The supported types are +## Usage -- Primitives like `Int`, `Float`, `String`, `Bool`, ... -- Array of primitives like `[Int]`, `[Float]`, `[Double]`, ... -- Set of primitives like `Set`, `Set`, ... -- Simply dictionary like `[String: Int]`, `[String: String]`, ... -- `Date` -- `URL` -- `Data` +```swift +// Disk +let storage = try Storage(diskConfig: DiskConfig(name: "Floppy")) -#### Error handling +// Disk, with objects also kept in memory +let storage = try Storage(diskConfig: DiskConfig(name: "Floppy"), memoryConfig: MemoryConfig(countLimit: 50)) -Error handling is done via `try catch`. `Storage` throws `StorageError` when an object is missing or can't be encoded, decoded or written. Other file system errors, such as a protected file that can't be read while the device is locked, are passed through unchanged. +// Memory +let storage = Storage(memoryConfig: MemoryConfig(countLimit: 50)) +``` ```swift -public enum StorageError: Error { - /// Object can not be found - case notFound(key: String) - /// Object is found, but casting to requested type failed - case typeNotMatch(key: String) - /// The file attributes are malformed - case malformedFileAttributes(key: String) - /// The stored data can't be decoded as the requested type - case decodingFailed(context: String, underlyingError: Error?) - /// The object can't be encoded, or the encoded data can't be written to disk - case encodingFailed(context: String, underlyingError: Error?) -} -``` +try storage.setObject(user, forKey: "user") +try storage.setObject(user, forKey: "user", expiry: .seconds(3600)) -A type mismatch is reported as `typeNotMatch` from memory, and as `decodingFailed` from disk. +let user = try storage.object(ofType: User.self, forKey: "user") +let entry = try storage.entry(ofType: User.self, forKey: "user") // entry.object, entry.expiry +let exists = try storage.existsObject(forKey: "user") -There can be errors because of disk problem or type mismatch when loading from storage, so if want to handle errors, you need to do `try catch` +try storage.removeObject(forKey: "user") +try storage.removeExpiredObjects() +try storage.removeAll() -```swift -do { - let storage = try Storage(diskConfig: diskConfig, memoryConfig: memoryConfig) -} catch { - print(error) -} +let bytes = try storage.diskSize() ``` -### Configuration - -Here is how you can play with many configuration options +## Configuration ```swift -let diskConfig = DiskConfig( - // The name of disk storage, this will be used as folder name within directory - name: "Floppy", - // Expiry date that will be applied by default for every added object - // if it's not overridden in the `setObject(forKey:expiry:)` method - expiry: .date(Date().addingTimeInterval(2*3600)), - // Maximum size of the disk cache storage (in bytes). 0 means no limit. Only enforced by `removeExpiredObjects()`, - // which then removes the objects closest to expiring until the storage is under half of this size. - maxSize: 10000, - // Where to store the disk cache. If nil, it is placed in `cachesDirectory` directory. - directory: try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, - appropriateFor: nil, create: true).appendingPathComponent("MyPreferences"), - // Data protection is used to store files in an encrypted format on disk and to decrypt them on demand - protectionType: .complete +DiskConfig( + name: "Floppy", // Folder name + expiry: .never, // Default expiry + directory: nil, // Where the folder goes. nil means the Caches directory + protectionType: .complete // iOS and tvOS only ) -``` -```swift -let memoryConfig = MemoryConfig( - // Expiry date that will be applied by default for every added object - // if it's not overridden in the `setObject(forKey:expiry:)` method - expiry: .date(Date().addingTimeInterval(2*60)), - /// The maximum number of objects in memory the cache should hold. 0 means no limit. - countLimit: 50 +MemoryConfig( + expiry: .never, // Default expiry + countLimit: 0 // Maximum number of objects. 0 means no limit ) ``` -On iOS, tvOS we can also specify `protectionType` on `DiskConfig` to add a level of security to files stored on disk by your app in the app’s container. For more information, see [FileProtectionType](https://developer.apple.com/documentation/foundation/fileprotectiontype) +The folder must be used only by the storage: `removeExpiredObjects()` deletes every file in it that isn't one of its objects, whatever its age and hidden files included. -A few things to know about `protectionType`: +## Expiry -- It applies to files written from now on. A file that's already there keeps its protection until it's overwritten, so adding it to an existing cache doesn't protect what's already saved. -- With `.complete`, reading from disk and writing throw while the device is locked. Opening a `Storage` still works, and so does `existsObject(forKey:)`, which can return `true` for an object that can't be read at that moment. -- It only protects files on disk. With hybrid storage, an object already in memory stays readable while the device is locked, so use disk-only storage for sensitive data. +`.never`, `.seconds(TimeInterval)` or `.date(Date)`. It's set by the config, or per object in `setObject`. -### APIs - -`Storage` is thread safe and `Sendable` — you can access it from any queue or task. All functions are constrained by the `StorageAware` protocol. - -```swift -// Save to storage -try? storage.setObject(10, forKey: "score") -try? storage.setObject("Oslo", forKey: "my favorite city", expiry: .never) -try? storage.setObject(["alert", "sounds", "badge"], forKey: "notifications") -try? storage.setObject(data, forKey: "a bunch of bytes") -try? storage.setObject(authorizeURL, forKey: "authorization URL") +An expired object counts as missing, but its file stays on disk until `removeExpiredObjects()`. -// Load from storage -let score = try? storage.object(ofType: Int.self, forKey: "score") -let favoriteCharacter = try? storage.object(ofType: String.self, forKey: "my favorite city") +## Errors -// Check if an object exists -let hasFavoriteCharacter = try? storage.existsObject(forKey: "my favorite city") +| Error | When | +|---|---| +| `notFound` | There's no object for the key, or it has expired | +| `typeNotMatch` | The object in memory is a different type | +| `decodingFailed` | The data on disk can't be decoded as the requested type | +| `encodingFailed` | The object can't be encoded, or the file can't be written | +| `malformedFileAttributes` | The file's expiry can't be read | -// Remove an object in storage -try? storage.removeObject(forKey: "my favorite city") +Other file system errors are passed through unchanged, for example reading a protected file while the device is locked. -// Remove all objects -try? storage.removeAll() +## File protection -// Remove expired objects -try? storage.removeExpiredObjects() -``` - -#### Entry - -There is time you want to get object together with its expiry information. You can use `Entry` - -```swift -let entry = try? storage.entry(ofType: String.self, forKey: "my favorite city") -print(entry?.object) -print(entry?.expiry) -``` - -Unlike `object(ofType:forKey:)`, `entry(ofType:forKey:)` also returns an object that has expired, so check `entry.expiry.isExpired`. - -#### Custom types - -Types stored in `Storage` must conform to both `Codable` and `Sendable`. It does not work for `[String: Any]` as `Any` conforms to neither. Convert JSON responses to strongly typed objects before saving. - -```swift -struct User: Codable, Sendable { - let firstName: String - let lastName: String -} - -let user = User(firstName: "John", lastName: "Snow") -try? storage.setObject(user, forKey: "character") -``` - -### Expiry date - -By default, all saved objects have the same expiry as the expiry you specify in `DiskConfig` or `MemoryConfig`. You can overwrite this for a specific object by specifying `expiry` for `setObject` - -```swift -// Default expiry date from configuration will be applied to the item -try? storage.setObject("This is a string", forKey: "string") - -// A given expiry date will be applied to the item -try? storage.setObject( - "This is a string", - forKey: "string", - expiry: .date(Date().addingTimeInterval(2 * 3600)) -) - -// Clear expired objects -try? storage.removeExpiredObjects() -``` - -## What about images? - -As you may know, `NSImage` and `UIImage` don't conform to `Codable` by default. To make it play well with `Codable`, we introduce `ImageWrapper`, so you can save and load images like - -```swift -let wrapper = ImageWrapper(image: starIconImage) -try? storage.setObject(wrapper, forKey: "star") - -let icon = try? storage.object(ofType: ImageWrapper.self, forKey: "star").image -``` +- `protectionType` applies to files written from now on. A file that's already there keeps its protection until it's overwritten. +- With `.complete`, reading from disk and writing throw while the device is locked. Opening a `Storage` still works, and `existsObject(forKey:)` can return `true` for an object that can't be read at that moment. +- It only covers files on disk. An object already in memory stays readable while the device is locked, so use disk-only storage for sensitive data. ## Authors -- Original idea: [Hyper](http://hyper.no) made this with ❤️ +- Original idea: [Hyper](http://hyper.no) - Reworked, simplified and modernized: Gabor S ## License -**Cache** is available under the MIT license. +MIT diff --git a/Sources/Cache/Configuration/DiskConfig.swift b/Sources/Cache/Configuration/DiskConfig.swift index 430001b..0fb6e1a 100644 --- a/Sources/Cache/Configuration/DiskConfig.swift +++ b/Sources/Cache/Configuration/DiskConfig.swift @@ -1,15 +1,12 @@ import Foundation public struct DiskConfig: Sendable { - /// The name of disk storage, this will be used as folder name within directory + /// The name of disk storage, this will be used as folder name within directory. + /// The folder must be used only by this storage: `removeExpiredObjects()` deletes anything else in it. public let name: String /// Expiry date that will be applied by default for every added object /// if it's not overridden in the `setObject(_:forKey:expiry:)` method public let expiry: Expiry - /// Maximum size of the disk cache storage (in bytes). 0 means no limit. - /// Only enforced by `removeExpiredObjects()`, which then removes the objects closest to - /// expiring until the storage is under half of this size. - public let maxSize: UInt /// A folder to store the disk cache contents. Defaults to the Caches directory if nil public let directory: URL? #if os(iOS) || os(tvOS) @@ -20,22 +17,20 @@ public struct DiskConfig: Sendable { public let protectionType: FileProtectionType? public init(name: String, expiry: Expiry = .never, - maxSize: UInt = 0, directory: URL? = nil, + directory: URL? = nil, protectionType: FileProtectionType? = nil) { self.name = name self.expiry = expiry - self.maxSize = maxSize self.directory = directory self.protectionType = protectionType } #else public init(name: String, expiry: Expiry = .never, - maxSize: UInt = 0, directory: URL? = nil) + directory: URL? = nil) { self.name = name self.expiry = expiry - self.maxSize = maxSize self.directory = directory } #endif diff --git a/Sources/Cache/Extensions/NSImage+Extensions.swift b/Sources/Cache/Extensions/NSImage+Extensions.swift deleted file mode 100644 index f1ec350..0000000 --- a/Sources/Cache/Extensions/NSImage+Extensions.swift +++ /dev/null @@ -1,38 +0,0 @@ -#if os(macOS) -import AppKit - -/// Helper NSImage extension. -extension NSImage { - /// Checks if image has alpha component - var hasAlpha: Bool { - var imageRect = CGRect(x: 0, y: 0, width: size.width, height: size.height) - - guard let imageRef = cgImage(forProposedRect: &imageRect, context: nil, hints: nil) else { - return false - } - - let result: Bool - let alpha = imageRef.alphaInfo - - switch alpha { - case .none, .noneSkipFirst, .noneSkipLast: - result = false - default: - result = true - } - - return result - } - - /// Convert to data - func cache_toData() -> Data? { - guard let data = tiffRepresentation else { - return nil - } - - let imageFileType: NSBitmapImageRep.FileType = self.hasAlpha ? .png : .jpeg - return NSBitmapImageRep(data: data)? - .representation(using: imageFileType, properties: [:]) - } -} -#endif diff --git a/Sources/Cache/Extensions/UIImage+Extensions.swift b/Sources/Cache/Extensions/UIImage+Extensions.swift deleted file mode 100644 index 610bec7..0000000 --- a/Sources/Cache/Extensions/UIImage+Extensions.swift +++ /dev/null @@ -1,31 +0,0 @@ -#if canImport(UIKit) -import UIKit - -/// Helper UIImage extension. -extension UIImage { - /// Checks if image has alpha component - var hasAlpha: Bool { - let result: Bool - - guard let alpha = cgImage?.alphaInfo else { - return false - } - - switch alpha { - case .none, .noneSkipFirst, .noneSkipLast: - result = false - default: - result = true - } - - return result - } - - /// Convert to data - func cache_toData() -> Data? { - self.hasAlpha - ? self.pngData() - : self.jpegData(compressionQuality: 1.0) - } -} -#endif diff --git a/Sources/Cache/Library/Entry.swift b/Sources/Cache/Library/Entry.swift index d4489d5..9279c0f 100644 --- a/Sources/Cache/Library/Entry.swift +++ b/Sources/Cache/Library/Entry.swift @@ -4,10 +4,9 @@ import Foundation public struct Entry: Sendable { // MARK: Lifecycle - init(object: T, expiry: Expiry, meta: [String: any Sendable] = [:]) { + init(object: T, expiry: Expiry) { self.object = object self.expiry = expiry - self.meta = meta } // MARK: Public @@ -16,6 +15,4 @@ public struct Entry: Sendable { public let object: T /// Expiry date public let expiry: Expiry - /// Associated meta data, if any. Currently always empty when read through `Storage`. - public let meta: [String: any Sendable] } diff --git a/Sources/Cache/Library/ImageWrapper.swift b/Sources/Cache/Library/ImageWrapper.swift deleted file mode 100644 index ff34b62..0000000 --- a/Sources/Cache/Library/ImageWrapper.swift +++ /dev/null @@ -1,36 +0,0 @@ -import Foundation - -public struct ImageWrapper: Codable, Sendable { - // MARK: Lifecycle - - public init(image: Image) { - self.image = image - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - let data = try container.decode(Data.self, forKey: CodingKeys.image) - guard let image = Image(data: data) else { - throw StorageError.decodingFailed(context: "ImageWrapper: failed to create Image from data", underlyingError: nil) - } - - self.image = image - } - - // MARK: Public - - public enum CodingKeys: String, CodingKey { - case image - } - - public let image: Image - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - guard let data = image.cache_toData() else { - throw StorageError.encodingFailed(context: "ImageWrapper: failed to convert Image to data", underlyingError: nil) - } - - try container.encode(data, forKey: CodingKeys.image) - } -} diff --git a/Sources/Cache/Library/JSONArrayWrapper.swift b/Sources/Cache/Library/JSONArrayWrapper.swift deleted file mode 100644 index f1af948..0000000 --- a/Sources/Cache/Library/JSONArrayWrapper.swift +++ /dev/null @@ -1,44 +0,0 @@ -import Foundation - -public typealias JSONArray = [JSONDictionary] - -public struct JSONArrayWrapper: Codable, Sendable { - // MARK: Lifecycle - - public init(jsonArray: JSONArray) { - self.jsonArray = jsonArray - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - let data = try container.decode(Data.self, forKey: CodingKeys.jsonArray) - let object = try JSONSerialization.jsonObject( - with: data, - options: [] - ) - - guard let jsonArray = object as? JSONArray else { - throw StorageError.decodingFailed(context: "JSONArrayWrapper: JSON object is not an array", underlyingError: nil) - } - - self.jsonArray = jsonArray - } - - // MARK: Public - - public enum CodingKeys: String, CodingKey { - case jsonArray - } - - public let jsonArray: JSONArray - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - let data = try JSONSerialization.data( - withJSONObject: self.jsonArray, - options: [] - ) - - try container.encode(data, forKey: CodingKeys.jsonArray) - } -} diff --git a/Sources/Cache/Library/JSONDictionaryWrapper.swift b/Sources/Cache/Library/JSONDictionaryWrapper.swift deleted file mode 100644 index 3a3dc83..0000000 --- a/Sources/Cache/Library/JSONDictionaryWrapper.swift +++ /dev/null @@ -1,44 +0,0 @@ -import Foundation - -public typealias JSONDictionary = [String: any Sendable] - -public struct JSONDictionaryWrapper: Codable, Sendable { - // MARK: Lifecycle - - public init(jsonDictionary: JSONDictionary) { - self.jsonDictionary = jsonDictionary - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - let data = try container.decode(Data.self, forKey: CodingKeys.jsonDictionary) - let object = try JSONSerialization.jsonObject( - with: data, - options: [] - ) - - guard let jsonDictionary = object as? JSONDictionary else { - throw StorageError.decodingFailed(context: "JSONDictionaryWrapper: JSON object is not a dictionary", underlyingError: nil) - } - - self.jsonDictionary = jsonDictionary - } - - // MARK: Public - - public enum CodingKeys: String, CodingKey { - case jsonDictionary - } - - public let jsonDictionary: JSONDictionary - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - let data = try JSONSerialization.data( - withJSONObject: self.jsonDictionary, - options: [] - ) - - try container.encode(data, forKey: CodingKeys.jsonDictionary) - } -} diff --git a/Sources/Cache/Library/Types.swift b/Sources/Cache/Library/Types.swift deleted file mode 100644 index 0da786c..0000000 --- a/Sources/Cache/Library/Types.swift +++ /dev/null @@ -1,9 +0,0 @@ -#if canImport(UIKit) -import UIKit - -public typealias Image = UIImage -#elseif os(macOS) -import AppKit - -public typealias Image = NSImage -#endif diff --git a/Sources/Cache/Storage/DiskStorage.swift b/Sources/Cache/Storage/DiskStorage.swift index 880cb24..1f3ca39 100644 --- a/Sources/Cache/Storage/DiskStorage.swift +++ b/Sources/Cache/Storage/DiskStorage.swift @@ -23,6 +23,12 @@ final class DiskStorage: Sendable { try createDirectory() } + // MARK: Internal + + /// Files in the current format end in this. Anything else was left by an older version, whose + /// format can't be read any more, so it's never looked up and `removeExpiredObjects()` removes it. + static let fileExtension = "cache" + // MARK: Private private enum Error: Swift.Error { @@ -43,43 +49,38 @@ extension DiskStorage: StorageAware { func entry(ofType type: T.Type, forKey key: String) throws -> Entry { try self.lock.withLockUnchecked { let filePath = makeFilePath(for: key) - let data: Data do { - data = try Data(contentsOf: URL(fileURLWithPath: filePath)) - } - catch CocoaError.fileReadNoSuchFile { - throw StorageError.notFound(key: key) - } - let attributes = try fileManager.attributesOfItem(atPath: filePath) - - guard let date = attributes[.modificationDate] as? Date else { - throw StorageError.malformedFileAttributes(key: key) - } + // The expiry comes first, so that an expired object isn't read or decoded + let attributes = try fileManager.attributesOfItem(atPath: filePath) + guard let date = attributes[.modificationDate] as? Date else { + throw StorageError.malformedFileAttributes(key: key) + } + guard !date.inThePast else { + throw StorageError.notFound(key: key) + } - let meta: [String: any Sendable] = [ - "filePath": filePath, - ] + let data = try Data(contentsOf: URL(fileURLWithPath: filePath)) + let object: T = if T.self == Data.self, let data = data as? T { + data + } + else { + try decode(data, forKey: key) + } - let object: T = if T.self == Data.self, let data = data as? T { - data + return Entry(object: object, expiry: Expiry.date(date)) } - else { - try decode(data, forKey: key) + catch CocoaError.fileReadNoSuchFile, CocoaError.fileNoSuchFile { + throw StorageError.notFound(key: key) } - - return Entry( - object: object, - expiry: Expiry.date(date), - meta: meta - ) } } - func setObject(_ object: some Codable & Sendable, forKey key: String, expiry: Expiry? = nil) throws { + func setObject(_ object: T, forKey key: String, expiry: Expiry? = nil) throws { try self.lock.withLockUnchecked { let expiry = expiry ?? self.config.expiry - let data: Data = if let rawData = object as? Data { + // Exactly `Data`, like when reading. `as? Data` alone would also unwrap a `Data?`. + let data: Data = if T.self == Data.self, let rawData = object as? Data { rawData } else { @@ -121,84 +122,96 @@ extension DiskStorage: StorageAware { func removeExpiredObjects() throws { try self.lock.withLockUnchecked { - let storageURL = URL(fileURLWithPath: path) - let resourceKeys: [URLResourceKey] = [ - .isDirectoryKey, - .contentModificationDateKey, - .totalFileAllocatedSizeKey, - ] - var resourceObjects = [ResourceObject]() - var filesToDelete = [ResourceObject]() - var totalSize: UInt = 0 var firstError: Swift.Error? - let fileEnumerator = self.fileManager.enumerator( - at: storageURL, - includingPropertiesForKeys: resourceKeys, - options: .skipsHiddenFiles, - errorHandler: nil - ) - guard let urlArray = fileEnumerator?.allObjects as? [URL] else { - throw Error.fileEnumeratorFailed - } - - for url in urlArray { - let resourceValues: URLResourceValues - do { - resourceValues = try url.resourceValues(forKeys: Set(resourceKeys)) - } - catch CocoaError.fileReadNoSuchFile, CocoaError.fileNoSuchFile { - // A file that vanished during the scan doesn't need cleaning up - continue - } - catch { - firstError = firstError ?? error - continue - } - - guard resourceValues.isDirectory != true else { - continue - } - - if let expiryDate = resourceValues.contentModificationDate, expiryDate.inThePast { - filesToDelete.append((url: url, resourceValues: resourceValues)) - continue - } - - if let fileSize = resourceValues.totalFileAllocatedSize { - totalSize += UInt(fileSize) - resourceObjects.append((url: url, resourceValues: resourceValues)) + for file in try listFiles(keys: [.contentModificationDateKey], firstError: &firstError) { + let isExpired = file.resourceValues.contentModificationDate?.inThePast ?? false + if isExpired || file.url.pathExtension != Self.fileExtension { + removeFile(at: file.url, firstError: &firstError) } } - // Remove expired objects - for file in filesToDelete { - // A file that couldn't be removed still takes up space, so it counts toward the max size - if !removeFile(at: file.url, firstError: &firstError), let fileSize = file.resourceValues.totalFileAllocatedSize { - totalSize += UInt(fileSize) - } + if let firstError { + throw firstError } + } + } - // Remove objects if storage size exceeds max size - removeResourceObjects(resourceObjects, totalSize: totalSize, firstError: &firstError) + func diskSize() throws -> UInt64 { + try self.lock.withLockUnchecked { + var firstError: Swift.Error? + var size: UInt64 = 0 + + for file in try listFiles(keys: [.totalFileAllocatedSizeKey], firstError: &firstError) { + size += UInt64(file.resourceValues.totalFileAllocatedSize ?? 0) + } if let firstError { throw firstError } + return size } } } private extension DiskStorage { - typealias ResourceObject = (url: Foundation.URL, resourceValues: URLResourceValues) + /** + Lists the files in the cache directory, hidden ones included, keeping the first failure instead + of stopping at it. A file that vanished during the scan is skipped. Must be called while holding the lock. + - Parameter keys: The resource values that the caller needs + - Parameter firstError: Keeps the first failure + */ + func listFiles(keys: Set, + firstError: inout Swift.Error?) throws -> [(url: URL, resourceValues: URLResourceValues)] + { + let resourceKeys = keys.union([.isDirectoryKey]) + var enumerationError: Swift.Error? + let fileEnumerator = self.fileManager.enumerator( + at: URL(fileURLWithPath: self.path), + includingPropertiesForKeys: Array(resourceKeys), + options: [], + errorHandler: { _, error in + let code = (error as? CocoaError)?.code + if code != .fileReadNoSuchFile, code != .fileNoSuchFile { + enumerationError = enumerationError ?? error + } + return true + } + ) + + guard let urlArray = fileEnumerator?.allObjects as? [URL] else { + throw Error.fileEnumeratorFailed + } + firstError = firstError ?? enumerationError + + var files = [(url: URL, resourceValues: URLResourceValues)]() + for url in urlArray { + let resourceValues: URLResourceValues + do { + resourceValues = try url.resourceValues(forKeys: resourceKeys) + } + catch CocoaError.fileReadNoSuchFile, CocoaError.fileNoSuchFile { + continue + } + catch { + firstError = firstError ?? error + continue + } + + if resourceValues.isDirectory != true { + files.append((url: url, resourceValues: resourceValues)) + } + } + return files + } /** Builds file name from the key. - Parameter key: Unique key to identify the object in the cache - - Returns: A md5 string + - Returns: A md5 string with the file extension */ func makeFileName(for key: String) -> String { - MD5.hash(key) + "\(MD5.hash(key)).\(Self.fileExtension)" } /** @@ -293,43 +306,4 @@ private extension DiskStorage { throw StorageError.decodingFailed(context: "DiskStorage: failed to decode object for key: \(key)", underlyingError: error) } } - - /** - Removes objects if storage size exceeds max size. - Must be called while holding the lock. - - Parameter objects: Resource objects to remove - - Parameter totalSize: Total size - - Parameter firstError: Keeps the first failure, so that the other objects still get removed - */ - func removeResourceObjects(_ objects: [ResourceObject], totalSize: UInt, firstError: inout Swift.Error?) { - guard self.config.maxSize > 0, totalSize > self.config.maxSize else { - return - } - - var remainingSize = totalSize - let targetSize = self.config.maxSize / 2 - - let sortedFiles = objects.sorted { - if let time1 = $0.resourceValues.contentModificationDate?.timeIntervalSinceReferenceDate, - let time2 = $1.resourceValues.contentModificationDate?.timeIntervalSinceReferenceDate - { - time1 < time2 - } - else { - false - } - } - - for file in sortedFiles { - guard removeFile(at: file.url, firstError: &firstError) else { - continue - } - if let fileSize = file.resourceValues.totalFileAllocatedSize { - remainingSize -= UInt(fileSize) - } - if remainingSize < targetSize { - break - } - } - } } diff --git a/Sources/Cache/Storage/HybridStorage.swift b/Sources/Cache/Storage/HybridStorage.swift index 15ccb54..9c84dd9 100644 --- a/Sources/Cache/Storage/HybridStorage.swift +++ b/Sources/Cache/Storage/HybridStorage.swift @@ -70,4 +70,10 @@ extension HybridStorage: StorageAware { try self.diskStorage.removeExpiredObjects() } } + + func diskSize() throws -> UInt64 { + try self.lock.withLockUnchecked { + try self.diskStorage.diskSize() + } + } } diff --git a/Sources/Cache/Storage/MemoryStorage.swift b/Sources/Cache/Storage/MemoryStorage.swift index e750967..925db63 100644 --- a/Sources/Cache/Storage/MemoryStorage.swift +++ b/Sources/Cache/Storage/MemoryStorage.swift @@ -25,7 +25,7 @@ final class MemoryStorage: Sendable { extension MemoryStorage: StorageAware { func entry(ofType type: T.Type, forKey key: String) throws -> Entry { - guard let capsule = cache.object(forKey: key as NSString) else { + guard let capsule = cache.object(forKey: key as NSString), !capsule.expiry.isExpired else { throw StorageError.notFound(key: key) } @@ -65,6 +65,10 @@ extension MemoryStorage: StorageAware { removeObjectIfExpired(forKey: key) } } + + func diskSize() -> UInt64 { + 0 + } } extension MemoryStorage { diff --git a/Sources/Cache/Storage/Storage.swift b/Sources/Cache/Storage/Storage.swift index b24b281..eb4ad7f 100644 --- a/Sources/Cache/Storage/Storage.swift +++ b/Sources/Cache/Storage/Storage.swift @@ -11,26 +11,22 @@ public final class Storage: Sendable { /// - memoryConfig: Optional. Pass config to add an in-memory layer /// - Throws: Throw StorageError if any. public init(diskConfig: DiskConfig, memoryConfig: MemoryConfig? = nil) throws { - let storage: StorageAware let disk = try DiskStorage(config: diskConfig) if let memoryConfig { let memory = MemoryStorage(config: memoryConfig) - storage = HybridStorage(memoryStorage: memory, diskStorage: disk) + self.internalStorage = HybridStorage(memoryStorage: memory, diskStorage: disk) } else { - storage = disk + self.internalStorage = disk } - - self.internalStorage = TypeWrapperStorage(storage: storage) } /// Initialize memory-only storage. /// /// - Parameter memoryConfig: Configuration for memory storage public init(memoryConfig: MemoryConfig) { - let memory = MemoryStorage(config: memoryConfig) - self.internalStorage = TypeWrapperStorage(storage: memory) + self.internalStorage = MemoryStorage(config: memoryConfig) } // MARK: Private @@ -40,27 +36,75 @@ public final class Storage: Sendable { } extension Storage: StorageAware { + /** + Tries to retrieve the object from the storage. + - Parameter key: Unique key to identify the object in the cache + - Returns: Cached object + - Throws: `StorageError.notFound` if there's no object for the key, or it has expired + */ + public func object(ofType type: T.Type, forKey key: String) throws -> T { + try self.internalStorage.object(ofType: type, forKey: key) + } + + /** + Tries to retrieve the object together with its expiry date. + - Parameter key: Unique key to identify the object in the cache + - Returns: Object wrapper with its expiry date + - Throws: `StorageError.notFound` if there's no object for the key, or it has expired + */ public func entry(ofType type: T.Type, forKey key: String) throws -> Entry { try self.internalStorage.entry(ofType: type, forKey: key) } + /** + Check if a non-expired object exists for the given key. + Does not read the object, so a read can still fail after this returns `true`, for example + for a file with `.complete` protection while the device is locked. + - Parameter key: Unique key to identify the object. + */ public func existsObject(forKey key: String) throws -> Bool { - try internalStorage.existsObject(forKey: key) + try self.internalStorage.existsObject(forKey: key) } + /** + Removes the object by the given key. Does nothing if there's no object for the key. + - Parameter key: Unique key to identify the object. + */ public func removeObject(forKey key: String) throws { try self.internalStorage.removeObject(forKey: key) } + /** + Saves passed object. + - Parameter object: Object that needs to be cached. + - Parameter key: Unique key to identify the object in the cache. + - Parameter expiry: Overwrite expiry for this object only. + */ public func setObject(_ object: some Codable & Sendable, forKey key: String, expiry: Expiry? = nil) throws { try self.internalStorage.setObject(object, forKey: key, expiry: expiry) } + /** + Removes all objects from the cache storage. + */ public func removeAll() throws { try self.internalStorage.removeAll() } + /** + Clears all expired objects, and deletes every other file in the storage's folder that isn't one + of its objects, whatever its age and hidden files included. That covers files left behind by an + older version of this package, so the folder must be used only by this storage. + A file that can't be removed doesn't stop the others. The first failure is thrown at the end. + */ public func removeExpiredObjects() throws { try self.internalStorage.removeExpiredObjects() } + + /** + How much disk space the storage takes up, in bytes. 0 for memory-only storage. + */ + public func diskSize() throws -> UInt64 { + try self.internalStorage.diskSize() + } } diff --git a/Sources/Cache/Storage/StorageAware.swift b/Sources/Cache/Storage/StorageAware.swift index 1578895..b4eba14 100644 --- a/Sources/Cache/Storage/StorageAware.swift +++ b/Sources/Cache/Storage/StorageAware.swift @@ -1,65 +1,19 @@ import Foundation -/// A protocol used for saving and loading from storage -public protocol StorageAware: Sendable { - /** - Tries to retrieve the object from the storage. - - Parameter key: Unique key to identify the object in the cache - - Returns: Cached object - - Throws: `StorageError.notFound` if there's no object for the key, or it has expired - */ +/// What each kind of storage has to do. `Storage` documents the behaviour. +protocol StorageAware: Sendable { func object(ofType type: T.Type, forKey key: String) throws -> T - - /** - Get cache entry which includes object with metadata. - Unlike `object(ofType:forKey:)`, this also returns an expired object, so check `expiry.isExpired`. - - Parameter key: Unique key to identify the object in the cache - - Returns: Object wrapper with metadata - - Throws: `StorageError.notFound` if there's no object for the key - */ func entry(ofType type: T.Type, forKey key: String) throws -> Entry - - /** - Removes the object by the given key. Does nothing if there's no object for the key. - - Parameter key: Unique key to identify the object. - */ func removeObject(forKey key: String) throws - - /** - Saves passed object. - - Parameter key: Unique key to identify the object in the cache. - - Parameter object: Object that needs to be cached. - - Parameter expiry: Overwrite expiry for this object only. - */ func setObject(_ object: some Codable & Sendable, forKey key: String, expiry: Expiry?) throws - - /** - Check if a non-expired object exists for the given key. - Does not read the object, so a read can still fail after this returns `true`, for example - for a file with `.complete` protection while the device is locked. - - Parameter key: Unique key to identify the object. - */ func existsObject(forKey key: String) throws -> Bool - - /** - Removes all objects from the cache storage. - */ func removeAll() throws - - /** - Clears all expired objects, and enforces `DiskConfig.maxSize`. - A file that can't be removed doesn't stop the others. The first failure is thrown at the end. - */ func removeExpiredObjects() throws - + func diskSize() throws -> UInt64 } -public extension StorageAware { +extension StorageAware { func object(ofType type: T.Type, forKey key: String) throws -> T { - let entry = try entry(ofType: type, forKey: key) - guard !entry.expiry.isExpired else { - throw StorageError.notFound(key: key) - } - return entry.object + try entry(ofType: type, forKey: key).object } } diff --git a/Sources/Cache/Storage/TypeWrapperStorage.swift b/Sources/Cache/Storage/TypeWrapperStorage.swift deleted file mode 100644 index cf3d4e9..0000000 --- a/Sources/Cache/Storage/TypeWrapperStorage.swift +++ /dev/null @@ -1,55 +0,0 @@ -import Foundation - -/// Deal with top level primitive. Use TypeWrapper as wrapper -/// Because we use `JSONEncoder` and `JSONDecoder`. -/// Avoid issue like "Top-level T encoded as number JSON fragment" -final class TypeWrapperStorage: Sendable { - // MARK: Lifecycle - - init(storage: StorageAware) { - self.internalStorage = storage - } - - // MARK: Internal - - let internalStorage: StorageAware -} - -extension TypeWrapperStorage: StorageAware { - func entry(ofType type: T.Type, forKey key: String) throws -> Entry { - let wrapperEntry = try internalStorage.entry(ofType: TypeWrapper.self, forKey: key) - return Entry(object: wrapperEntry.object.object, expiry: wrapperEntry.expiry) - } - - func existsObject(forKey key: String) throws -> Bool { - try internalStorage.existsObject(forKey: key) - } - - func removeObject(forKey key: String) throws { - try self.internalStorage.removeObject(forKey: key) - } - - func setObject(_ object: T, forKey key: String, - expiry: Expiry? = nil) throws - { - let wrapper = TypeWrapper(object: object) - try internalStorage.setObject(wrapper, forKey: key, expiry: expiry) - } - - func removeAll() throws { - try self.internalStorage.removeAll() - } - - func removeExpiredObjects() throws { - try self.internalStorage.removeExpiredObjects() - } -} - -/// Used to wrap Codable object -struct TypeWrapper: Codable, Sendable { - enum CodingKeys: String, CodingKey { - case object - } - - let object: T -} diff --git a/Tests/CacheTests/StorageTests.swift b/Tests/CacheTests/StorageTests.swift index d168b2d..e7e29b8 100644 --- a/Tests/CacheTests/StorageTests.swift +++ b/Tests/CacheTests/StorageTests.swift @@ -23,6 +23,32 @@ struct StorageTests { #expect(try storage.object(ofType: Data.self, forKey: "data") == data) } + @Test("Data is stored as it is, with nothing around it") + func dataIsStoredRaw() throws { + let sandbox = try Sandbox() + let data = Data(repeating: 7, count: 1000) + + try sandbox.storage(.disk).setObject(data, forKey: "key") + + let file = sandbox.folder().appendingPathComponent(fileName(for: "key")) + #expect(try Data(contentsOf: file) == data) + } + + @Test("An optional Data can be read back, with or without a value", arguments: Sandbox.Mode.allCases) + func optionalData(mode: Sandbox.Mode) throws { + let sandbox = try Sandbox() + let storage = try sandbox.storage(mode) + // Not valid JSON or UTF-8, so it can't get through by accident + let value: Data? = Data([0, 255, 254, 1]) + let empty: Data? = nil + + try storage.setObject(value, forKey: "value") + try storage.setObject(empty, forKey: "empty") + + #expect(try storage.object(ofType: Data?.self, forKey: "value") == value) + #expect(try storage.object(ofType: Data?.self, forKey: "empty") == nil) + } + @Test("Hybrid storage finds what an earlier instance saved") func hybridReadsFromDisk() throws { let sandbox = try Sandbox() @@ -191,20 +217,38 @@ struct StorageTests { // MARK: Expiry - @Test("An expired object counts as missing, but its entry can still be read", arguments: Sandbox.Mode.allCases) + @Test("An expired object counts as missing, however it's asked for", arguments: Sandbox.Mode.allCases) func expiredObject(mode: Sandbox.Mode) throws { let sandbox = try Sandbox() let storage = try sandbox.storage(mode) try storage.setObject("old", forKey: "key", expiry: .seconds(-10)) - #expect(throws: StorageError.self) { - try storage.object(ofType: String.self, forKey: "key") - } #expect(try storage.existsObject(forKey: "key") == false) + for read in [ + { try storage.object(ofType: String.self, forKey: "key") }, + { try storage.entry(ofType: String.self, forKey: "key").object }, + ] { + let error = try #require(throws: StorageError.self) { + _ = try read() + } + guard case .notFound = error else { + Issue.record("Expected notFound, got \(error)") + return + } + } + } + + @Test("An entry has the object and its expiry", arguments: Sandbox.Mode.allCases) + func entryOfLiveObject(mode: Sandbox.Mode) throws { + let sandbox = try Sandbox() + let storage = try sandbox.storage(mode) + let expiry = Date().addingTimeInterval(3600) + try storage.setObject("new", forKey: "key", expiry: .date(expiry)) let entry = try storage.entry(ofType: String.self, forKey: "key") - #expect(entry.object == "old") - #expect(entry.expiry.isExpired) + + #expect(entry.object == "new") + #expect(abs(entry.expiry.date.timeIntervalSince(expiry)) < 1) } @Test("removeExpiredObjects only removes expired objects", arguments: Sandbox.Mode.allCases) @@ -216,8 +260,9 @@ struct StorageTests { try storage.removeExpiredObjects() - #expect(throws: StorageError.self) { - try storage.entry(ofType: String.self, forKey: "old") + // Reads already treat an expired object as missing, so this has to look at the files + if mode != .memory { + #expect(try sandbox.files() == [fileName(for: "new")]) } #expect(try storage.object(ofType: String.self, forKey: "new") == "new") } @@ -234,21 +279,104 @@ struct StorageTests { #expect(try sandbox.storage(mode).object(ofType: String.self, forKey: "key") == "kept") } - @Test("Going over maxSize evicts the soonest to expire first") - func eviction() throws { + // MARK: Files from older versions + + /// 4.x named files with just the hash, and wrapped each object in `{"object": ...}`. + private func writeOldFormatFile(in sandbox: Sandbox, key: String) throws { + let file = sandbox.folder().appendingPathComponent(MD5.hash(key)) + try Data(#"{"object":"old"}"#.utf8).write(to: file) + try FileManager.default.setAttributes([.modificationDate: Date.distantFuture], ofItemAtPath: file.path) + } + + @Test("A file from an older version is never read", arguments: [Sandbox.Mode.disk, .hybrid]) + func oldFormatIsNotRead(mode: Sandbox.Mode) throws { let sandbox = try Sandbox() - let storage = try sandbox.storage(.disk, maxSize: 40000) - let blob = Data(repeating: 1, count: 5000) - try storage.setObject(blob, forKey: "never", expiry: .never) - for minutes in 1 ... 4 { - try storage.setObject(blob, forKey: "\(minutes)", expiry: .seconds(Double(minutes) * 60)) + let storage = try sandbox.storage(mode) + try writeOldFormatFile(in: sandbox, key: "key") + + #expect(try storage.existsObject(forKey: "key") == false) + let error = try #require(throws: StorageError.self) { + try storage.object(ofType: String.self, forKey: "key") } - try storage.setObject(blob, forKey: "latest", expiry: .seconds(6000)) + guard case .notFound = error else { + Issue.record("Expected notFound, got \(error)") + return + } + } + + @Test("Purging removes files from older versions, even if they haven't expired") + func purgeRemovesOldFormat() throws { + let sandbox = try Sandbox() + let storage = try sandbox.storage(.disk) + try writeOldFormatFile(in: sandbox, key: "old") + try storage.setObject("new", forKey: "new") try storage.removeExpiredObjects() - #expect(try storage.existsObject(forKey: "1") == false) - #expect(try storage.existsObject(forKey: "never")) + #expect(try sandbox.files() == [fileName(for: "new")]) + } + + // MARK: Disk size + + @Test("diskSize follows what's on disk", arguments: [Sandbox.Mode.disk, .hybrid]) + func diskSize(mode: Sandbox.Mode) throws { + let sandbox = try Sandbox() + let storage = try sandbox.storage(mode) + #expect(try storage.diskSize() == 0) + + try storage.setObject(Data(repeating: 1, count: 5000), forKey: "key") + #expect(try storage.diskSize() >= 5000) + + try storage.removeAll() + #expect(try storage.diskSize() == 0) + } + + @Test("Hidden files count toward diskSize, and purging removes them") + func hiddenFiles() throws { + let sandbox = try Sandbox() + let storage = try sandbox.storage(.disk) + try Data(repeating: 1, count: 5000).write(to: sandbox.folder().appendingPathComponent(".hidden")) + + #expect(try storage.diskSize() >= 5000) + + try storage.removeExpiredObjects() + + #expect(try sandbox.files().isEmpty) + } + + @Test("A folder that can't be read makes diskSize and purging throw, after doing what they can") + func unreadableFolder() throws { + let sandbox = try Sandbox() + let storage = try sandbox.storage(.disk) + try storage.setObject(1, forKey: "old", expiry: .seconds(-10)) + let locked = sandbox.folder().appendingPathComponent("locked") + try FileManager.default.createDirectory(at: locked, withIntermediateDirectories: true) + try FileManager.default.setAttributes([.posixPermissions: 0o000], ofItemAtPath: locked.path) + defer { + // Otherwise the sandbox can't clean it up + try? FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: locked.path) + } + + #expect(throws: (any Error).self) { + try storage.diskSize() + } + #expect(throws: (any Error).self) { + try storage.removeExpiredObjects() + } + + #expect(try sandbox.files() == ["locked"]) + } + + @Test("diskSize is 0 without a disk, or without the folder") + func diskSizeWithoutDisk() throws { + let sandbox = try Sandbox() + let memory = try sandbox.storage(.memory) + try memory.setObject(1, forKey: "key") + #expect(try memory.diskSize() == 0) + + let disk = try sandbox.storage(.disk) + try FileManager.default.removeItem(at: sandbox.folder()) + #expect(try disk.diskSize() == 0) } // MARK: Losing the folder @@ -372,7 +500,7 @@ struct PurgeFailureTests { try storage.setObject(1, forKey: key, expiry: .seconds(-10)) } fileManager.beforeRemoving = { path in - if path.hasSuffix(MD5.hash("b")), FileManager.default.fileExists(atPath: path) { + if path.hasSuffix(fileName(for: "b")), FileManager.default.fileExists(atPath: path) { try FileManager.default.removeItem(atPath: path) } } @@ -381,51 +509,6 @@ struct PurgeFailureTests { #expect(try sandbox.files().isEmpty) } - - @Test("Going over maxSize still evicts the others when one can't be removed") - func evictionContinuesPastFailure() throws { - let sandbox = try Sandbox() - let fileManager = HookedFileManager() - let storage = try DiskStorage(config: DiskConfig(name: "cache", maxSize: 20000, directory: sandbox.root), fileManager: fileManager) - let blob = Data(repeating: 1, count: 5000) - for minutes in 1 ... 6 { - try storage.setObject(blob, forKey: "\(minutes)", expiry: .seconds(Double(minutes) * 60)) - } - fileManager.beforeRemoving = { path in - if path.hasSuffix(MD5.hash("1")) { - throw RemovalFailed() - } - } - - #expect(throws: RemovalFailed.self) { - try storage.removeExpiredObjects() - } - - #expect(try storage.existsObject(forKey: "1")) - #expect(try storage.existsObject(forKey: "2") == false) - } - - @Test("An expired file that can't be removed still counts toward maxSize") - func stuckExpiredFileCountsTowardMaxSize() throws { - let sandbox = try Sandbox() - let fileManager = HookedFileManager() - let storage = try DiskStorage(config: DiskConfig(name: "cache", maxSize: 40000, directory: sandbox.root), fileManager: fileManager) - // Only over maxSize if the stuck file is counted - try storage.setObject(Data(repeating: 1, count: 35000), forKey: "stuck", expiry: .seconds(-10)) - try storage.setObject(Data(repeating: 1, count: 5000), forKey: "a", expiry: .seconds(60)) - try storage.setObject(Data(repeating: 1, count: 5000), forKey: "b", expiry: .seconds(120)) - fileManager.beforeRemoving = { path in - if path.hasSuffix(MD5.hash("stuck")) { - throw RemovalFailed() - } - } - - #expect(throws: RemovalFailed.self) { - try storage.removeExpiredObjects() - } - - #expect(try sandbox.files() == [MD5.hash("stuck")]) - } } #if os(iOS) || os(tvOS) diff --git a/Tests/CacheTests/TestSupport.swift b/Tests/CacheTests/TestSupport.swift index 52793af..c8dc571 100644 --- a/Tests/CacheTests/TestSupport.swift +++ b/Tests/CacheTests/TestSupport.swift @@ -29,8 +29,8 @@ final class Sandbox { self.root.appendingPathComponent(name, isDirectory: true) } - func storage(_ mode: Mode, name: String = "cache", maxSize: UInt = 0, countLimit: UInt = 0) throws -> Storage { - let disk = DiskConfig(name: name, maxSize: maxSize, directory: self.root) + func storage(_ mode: Mode, name: String = "cache", countLimit: UInt = 0) throws -> Storage { + let disk = DiskConfig(name: name, directory: self.root) let memory = MemoryConfig(countLimit: countLimit) return switch mode { case .disk: @@ -47,6 +47,11 @@ final class Sandbox { } } +/// What a key's file is called on disk. +func fileName(for key: String) -> String { + "\(MD5.hash(key)).\(DiskStorage.fileExtension)" +} + struct Person: Codable, Sendable, Equatable { let name: String }