Skip to content
Closed
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
11 changes: 11 additions & 0 deletions .github/diag/urlnul.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import Foundation
// Builds URLs and prints them. No file system calls.
let root = FileManager.default.temporaryDirectory.appendingPathComponent("CacheTests-1", isDirectory: true)
print("root:", root.absoluteString, root.path.debugDescription)
for part in ["\u{0}", "\u{0}x", "a\u{0}b"] {
let u = root.appendingPathComponent(part, isDirectory: true)
let c = u.appendingPathComponent("cache", isDirectory: true)
let fs = c.withUnsafeFileSystemRepresentation { $0.map { String(cString: $0) } ?? "nil" }
print(part.debugDescription, "| abs:", u.absoluteString, "| path:", u.path.debugDescription,
"| isFile:", u.isFileURL, "| child path:", c.path.debugDescription, "| child fsRep:", fs)
}
54 changes: 4 additions & 50 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -1,62 +1,16 @@
name: CI

on:
push:
branches: [master]
pull_request:

permissions:
contents: read

concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true

jobs:
test-macos:
name: Test on macOS
runs-on: macos-26
timeout-minutes: 15
steps:
- uses: actions/checkout@v7
- run: swift test

# File protection is only compiled for iOS and tvOS, so its tests only run here.
test-ios:
name: Test on the iOS Simulator
runs-on: macos-26
timeout-minutes: 20
steps:
- uses: actions/checkout@v7
- name: Find an iPhone simulator
id: simulator
run: |
udid=$(xcrun simctl list devices available -j | jq -r '
[.devices | to_entries | sort_by(.key)[]
| select(.key | contains("iOS"))
| .value[]
| select(.name | startswith("iPhone"))]
| last | .udid')
test "$udid" != "null"
echo "udid=$udid" >> "$GITHUB_OUTPUT"
- run: xcodebuild test -scheme Cache -destination "id=${{ steps.simulator.outputs.udid }}"

build:
name: Build for ${{ matrix.name }}
diagnose-url:
name: Print how URL handles NUL
runs-on: macos-26
timeout-minutes: 15
strategy:
fail-fast: false
matrix:
include:
- name: watchOS
destination: generic/platform=watchOS
- name: tvOS
destination: generic/platform=tvOS
- name: visionOS
destination: generic/platform=visionOS
- name: Mac Catalyst
destination: generic/platform=macOS,variant=Mac Catalyst
timeout-minutes: 10
steps:
- uses: actions/checkout@v7
- run: xcodebuild build -quiet -scheme Cache -destination "${{ matrix.destination }}" CODE_SIGNING_ALLOWED=NO
- run: sw_vers && swiftc -o urlnul .github/diag/urlnul.swift && ./urlnul
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. File system calls stop reading a path at a NUL, 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.

`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
4 changes: 3 additions & 1 deletion Sources/Cache/Configuration/DiskConfig.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ 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
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
Loading
Loading