Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,14 @@ jobs:
- uses: actions/checkout@v7
- run: swift test

test-thread-sanitizer:
name: Test with Thread Sanitizer
runs-on: macos-26
timeout-minutes: 15
steps:
- uses: actions/checkout@v7
- run: swift test --sanitize=thread

# File protection is only compiled for iOS and tvOS, so its tests only run here.
test-ios:
name: Test on the iOS Simulator
Expand Down
20 changes: 20 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,25 @@
# Changelog

## 5.0.1

Bug fixes
- With both disk and memory, an object could stay readable after its file expired, because the copy in memory used `MemoryConfig.expiry`. An object now has one expiry, and `entry(ofType:forKey:)` reports the same one from memory and from disk.
- A `DiskConfig` name that isn't a single folder is refused, because purging or `removeAll()` could delete files outside the cache. With an empty name, they emptied `directory` itself. `Storage` now throws `CocoaError(.fileWriteInvalidFileName)`.
- A `DiskConfig` name with a control character such as NUL is refused too, and so is a `directory` with a NUL in it, or the root folder. File system calls stop reading a path at a NUL, and on macOS 26 a folder's URL with a NUL added comes out as the root folder, so purging could act on files far outside the cache.
- `removeExpiredObjects()` and `removeAll()` only delete files named like the storage's objects, directly in its folder. Purging used to delete every other file in the folder and in its subfolders, and `removeAll()` deleted the whole folder, so a wrong path could cost files that had nothing to do with the cache.
- An object in memory no longer waits for disk access or encoding of another object.
- An object's relative expiry, like `.seconds(10)`, starts once it's being saved. Waiting for another write or a disk read used to use it up, so a short-lived object could be saved already expired.
- Encoding and decoding no longer hold any lock, so a slow `Codable` type doesn't hold up other objects, and its code can use the storage it's being saved in.

Behaviour changes
- `MemoryConfig.expiry` is now only used by memory-only storage. With a disk, objects use the expiry from `DiskConfig`.
- Files in the cache folder that aren't the storage's, hidden ones included, are no longer deleted by `removeExpiredObjects()` or `removeAll()`. They still count toward `diskSize()`.
- A `DiskConfig` name with a `/`, like `"Images/Thumbnails"`, used to create nested folders and now throws. Pass the parent folder as `directory` instead. Use the same full path to keep what's already cached there.

Other
- Documented that objects should be read with the type they were written as. On disk, `Data` returns a file's bytes without checking what was written, so an object written as `Data?` comes back as JSON.
- Added tests that compare all kinds of storage, cover the config's default expiry and use storage from many threads. CI also runs the tests with Thread Sanitizer.

## 5.0.0

Removed
Expand Down
10 changes: 8 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

Stores `Codable & Sendable` values on disk, in memory, or both, with expiry. Thread safe.

Requires iOS 16, macOS 13, tvOS 16, watchOS 9 or visionOS 1.
Requires Swift 6.2, and iOS 16, macOS 13, tvOS 16, watchOS 9 or visionOS 1.

## Installation

Expand Down Expand Up @@ -40,6 +40,8 @@ try storage.removeAll()
let bytes = try storage.diskSize()
```

Read an object with the type it was written as. With any other type, the result depends on the kind of storage. Files don't record their type, so a file may decode as another type if its JSON fits, and asking for `Data` returns the file's bytes as they are. That includes an object written as `Data?`, whose file holds JSON rather than the original bytes.

## Configuration

```swift
Expand All @@ -56,12 +58,16 @@ MemoryConfig(
)
```

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.
The name must be a single folder name. An empty name, `.`, `..`, and anything with a `/` or a control character such as NUL make `Storage` throw `CocoaError(.fileWriteInvalidFileName)`. So does a `directory` with a NUL in it, or the root folder, which is what a URL with a NUL can turn into.

`removeExpiredObjects()` and `removeAll()` only delete files named like the storage's objects, directly in its folder. Anything else in the folder, including subfolders, is left alone.

## Expiry

`.never`, `.seconds(TimeInterval)` or `.date(Date)`. It's set by the config, or per object in `setObject`.

With both disk and memory, an object has one expiry, and the config's default comes from `DiskConfig`. `MemoryConfig.expiry` is only used by memory-only storage.

An expired object counts as missing, but its file stays on disk until `removeExpiredObjects()`.

## Errors
Expand Down
7 changes: 5 additions & 2 deletions Sources/Cache/Configuration/DiskConfig.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,15 @@ import Foundation

public struct DiskConfig: Sendable {
/// 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.
/// It must be a single folder name: `Storage` refuses an empty name, `.`, `..`, and anything with
/// a `/` or a control character such as NUL. The storage only ever deletes files named like its
/// objects, directly in this folder, so anything else kept there is left alone.
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
/// A folder to store the disk cache contents. Defaults to the Caches directory if nil
/// A folder to store the disk cache contents. Defaults to the Caches directory if nil.
/// `Storage` refuses the root folder, and a URL with a NUL in it.
public let directory: URL?
#if os(iOS) || os(tvOS)
/// Data protection is used to store files in an encrypted format on disk and to decrypt them on demand.
Expand Down
3 changes: 2 additions & 1 deletion Sources/Cache/Configuration/MemoryConfig.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ public struct MemoryConfig: Sendable {
// MARK: Public

/// Expiry date that will be applied by default for every added object
/// if it's not overridden in the `setObject(_:forKey:expiry:)` method
/// if it's not overridden in the `setObject(_:forKey:expiry:)` method.
/// Only used by memory-only storage. With a disk, objects use the expiry from `DiskConfig`.
public let expiry: Expiry
/// The maximum number of objects in memory the cache should hold. 0 means no limit.
public let countLimit: UInt
Expand Down
161 changes: 113 additions & 48 deletions Sources/Cache/Storage/DiskStorage.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ final class DiskStorage: Sendable {
// MARK: Lifecycle

init(config: DiskConfig, fileManager: FileManager = FileManager.default) throws {
// First, because the folder gets emptied later on, and these names could point at someone else's
guard Self.isSingleFolderName(config.name) else {
throw CocoaError(.fileWriteInvalidFileName, userInfo: [NSFilePathErrorKey: config.name])
}

self.config = config
self.fileManager = fileManager

Expand All @@ -19,16 +24,32 @@ final class DiskStorage: Sendable {
}

// path
self.path = url.appendingPathComponent(config.name, isDirectory: true).path
// A NUL in a URL can make it come out as the root folder, depending on the OS version: on
// macOS 26, appending "a\u{0}b" to a folder's URL gives file:///. So the root folder is refused,
// and the name is joined as a string rather than with URL methods, then checked.
let directoryPath = url.standardizedFileURL.path
let path = (directoryPath as NSString).appendingPathComponent(config.name)
guard url.isFileURL, !directoryPath.isEmpty, directoryPath != "/",
!path.unicodeScalars.contains("\u{0}"),
url.absoluteString.range(of: "%00", options: .caseInsensitive) == nil,
(path as NSString).deletingLastPathComponent == directoryPath,
(path as NSString).lastPathComponent == config.name
else {
throw CocoaError(.fileWriteInvalidFileName, userInfo: [NSFilePathErrorKey: path])
}
self.path = path
try createDirectory()
}

// MARK: Internal

/// Files in the current format end in this. Anything else was left by an older version, whose
/// Files in the current format end in this. A file named with just the hash was left by 4.x, whose
/// format can't be read any more, so it's never looked up and `removeExpiredObjects()` removes it.
static let fileExtension = "cache"

/// Configuration
let config: DiskConfig

// MARK: Private

private enum Error: Swift.Error {
Expand All @@ -37,17 +58,16 @@ final class DiskStorage: Sendable {

/// File manager to read/write to the disk (access protected by lock)
private nonisolated(unsafe) let fileManager: FileManager
/// Configuration
private let config: DiskConfig
/// The computed path `directory+name`
private let path: String
/// Lock protecting all file I/O operations
/// Lock protecting all file I/O operations. Encoding and decoding stay outside of it, because
/// they run the type's own code, which may be slow or use this storage.
private let lock = OSAllocatedUnfairLock()
}

extension DiskStorage: StorageAware {
func entry<T: Codable & Sendable>(ofType type: T.Type, forKey key: String) throws -> Entry<T> {
try self.lock.withLockUnchecked {
let (data, date) = try self.lock.withLockUnchecked {
let filePath = makeFilePath(for: key)
do {
// The expiry comes first, so that an expired object isn't read or decoded
Expand All @@ -59,38 +79,19 @@ extension DiskStorage: StorageAware {
throw StorageError.notFound(key: key)
}

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)
}

return Entry(object: object, expiry: Expiry.date(date))
return (try Data(contentsOf: URL(fileURLWithPath: filePath)), date)
}
catch CocoaError.fileReadNoSuchFile, CocoaError.fileNoSuchFile {
throw StorageError.notFound(key: key)
}
}

let object: T = try decode(data, forKey: key)
return Entry(object: object, expiry: Expiry.date(date))
}

func setObject<T: Codable & Sendable>(_ object: T, forKey key: String, expiry: Expiry? = nil) throws {
try self.lock.withLockUnchecked {
let expiry = expiry ?? self.config.expiry

// 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 {
try encode(object, forKey: key)
}

let filePath = makeFilePath(for: key)
try writeFile(data, atPath: filePath)
try self.fileManager.setAttributes([.modificationDate: expiry.date], ofItemAtPath: filePath)
}
try self.write(self.encode(object, forKey: key), forKey: key, expiry: expiry)
}

func existsObject(forKey key: String) throws -> Bool {
Expand All @@ -113,18 +114,28 @@ extension DiskStorage: StorageAware {
}
}

/// Removes this storage's files one by one rather than the whole folder, so that a wrong path
/// can't take anything else with it.
func removeAll() throws {
try self.lock.withLockUnchecked {
try removeItemIfPresent(atPath: self.path)
var firstError: Swift.Error?

for file in try listOwnFiles(keys: [], firstError: &firstError) {
removeFile(at: file.url, firstError: &firstError)
}
try createDirectory()

if let firstError {
throw firstError
}
}
}

func removeExpiredObjects() throws {
try self.lock.withLockUnchecked {
var firstError: Swift.Error?

for file in try listFiles(keys: [.contentModificationDateKey], firstError: &firstError) {
for file in try listOwnFiles(keys: [.contentModificationDateKey], firstError: &firstError) {
let isExpired = file.resourceValues.contentModificationDate?.inThePast ?? false
if isExpired || file.url.pathExtension != Self.fileExtension {
removeFile(at: file.url, firstError: &firstError)
Expand Down Expand Up @@ -154,10 +165,73 @@ extension DiskStorage: StorageAware {
}
}

/// The two halves of `setObject`, so that hybrid storage can encode before taking its own lock.
extension DiskStorage {
/// Wraps encoding failures in a `StorageError`, unless the type's own `Codable` code already threw one.
func encode<T: Encodable>(_ object: T, forKey key: String) throws -> Data {
// Exactly `Data`, like when reading. `as? Data` alone would also unwrap a `Data?`.
if T.self == Data.self, let data = object as? Data {
return data
}

do {
return try DataSerializer.serialize(object: object)
}
catch let error as StorageError {
throw error
}
catch {
throw StorageError.encodingFailed(context: "DiskStorage: failed to encode object for key: \(key)", underlyingError: error)
}
}

/// Works out the expiry date while holding the lock, so that waiting for it doesn't use up the
/// object's lifetime.
/// - Returns: The expiry date the file got
@discardableResult
func write(_ data: Data, forKey key: String, expiry: Expiry?) throws -> Date {
try self.lock.withLockUnchecked {
let filePath = makeFilePath(for: key)
try writeFile(data, atPath: filePath)
let date = (expiry ?? self.config.expiry).date
try self.fileManager.setAttributes([.modificationDate: date], ofItemAtPath: filePath)
return date
}
}
}

private extension DiskStorage {
/// Whether the name is one folder inside the directory, rather than the directory itself or a path out of it.
/// Control characters are refused too: file system calls stop reading a path at a NUL.
static func isSingleFolderName(_ name: String) -> Bool {
!name.isEmpty && name != "." && name != ".." && !name.contains("/")
&& !name.unicodeScalars.contains { $0.properties.generalCategory == .control }
}

/// Whether the file is named like one of this storage's objects: the key's hash, with the extension
/// or without it like in 4.x. Nothing else is ever deleted, even if the folder holds other files.
static func isOwnFileName(_ name: String) -> Bool {
let suffix = ".\(Self.fileExtension)"
let hash = name.hasSuffix(suffix) ? name.dropLast(suffix.count) : Substring(name)
return hash.count == 32 && hash.allSatisfy { $0.isASCII && $0.isHexDigit }
}

/// Lists this storage's own files: directly in the cache folder, and named like its objects.
/// Must be called while holding the lock.
func listOwnFiles(keys: Set<URLResourceKey>,
firstError: inout Swift.Error?) throws -> [(url: URL, resourceValues: URLResourceValues)]
{
let folder = URL(fileURLWithPath: self.path, isDirectory: true).resolvingSymlinksInPath().path
return try listFiles(keys: keys, firstError: &firstError).filter { file in
Self.isOwnFileName(file.url.lastPathComponent)
&& file.url.deletingLastPathComponent().resolvingSymlinksInPath().path == folder
}
}

/**
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.
Lists the files directly in the cache directory, hidden ones included, without looking inside folders.
Keeps 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
*/
Expand All @@ -169,7 +243,7 @@ private extension DiskStorage {
let fileEnumerator = self.fileManager.enumerator(
at: URL(fileURLWithPath: self.path),
includingPropertiesForKeys: Array(resourceKeys),
options: [],
options: [.skipsSubdirectoryDescendants],
errorHandler: { _, error in
let code = (error as? CocoaError)?.code
if code != .fileReadNoSuchFile, code != .fileNoSuchFile {
Expand Down Expand Up @@ -281,21 +355,12 @@ private extension DiskStorage {
}
}

/// Wraps encoding failures in a `StorageError`, unless the type's own `Codable` code already threw one.
func encode(_ object: some Encodable, forKey key: String) throws -> Data {
do {
return try DataSerializer.serialize(object: object)
}
catch let error as StorageError {
throw error
}
catch {
throw StorageError.encodingFailed(context: "DiskStorage: failed to encode object for key: \(key)", underlyingError: error)
}
}

/// Wraps decoding failures in a `StorageError`, unless the type's own `Codable` code already threw one.
func decode<T: Decodable>(_ data: Data, forKey key: String) throws -> T {
if T.self == Data.self, let data = data as? T {
return data
}

do {
return try DataSerializer.deserialize(data: data)
}
Expand Down
Loading
Loading