Skip to content

2.0.0

Latest

Choose a tag to compare

@choule99 choule99 released this 31 Oct 18:00
Immutable release. Only release title and notes can be modified.
2.0.0
aa491f0

Added

  • Cache.value(for:expiresAfter:orFetch:), which returns a cached value or fetches, adds, and returns it. Concurrent calls for the same key share one fetch, and a fetch that throws adds nothing.
  • DiskStorageEngine.init(directory:keyType:serializer:options:encryptionKey:) with a directory URL, to store entries outside the app cache directory, such as in Application Support or an app group container.
  • CacheClock, a protocol for the cache's source of time, and a clock parameter on Cache.init.
  • ManualClock, an independent clock for testing expiration and eviction.
  • SystemClock, the default clock, which reads the system date.
  • Cache.contains(_:), which checks for an unexpired entry without recording an access.
  • A maxCount parameter on Cache.init that evicts down to a maximum entry count after each addition.
  • TextDiskStorageSerializer, a non-generic replacement for StringDiskStorageSerializer.
  • An accessCount parameter on CacheEntry.init(key:value:creation:lastAccess:).
  • CI coverage for Swift 6.0, the example packages, and tests on tvOS, watchOS, and visionOS simulators.
  • Per-entry lifetimes: an expiresAfter parameter on the add methods, and CacheEntry.expiration. An entry expires at its own expiration date or at the policy's threshold, whichever comes first. Disk storage persists the expiration.
  • Cost limits: a costLimit parameter on Cache.init takes a maximum total cost and a function that computes each value's cost. The cache evicts entries in policy order after each addition to stay within the limit. Cache.totalCost and CacheEntry.cost report the costs.
  • An encrypted disk cache example. On Linux, apps add swift-crypto to their own package to create a SymmetricKey; SwiftStash doesn't re-export it.
  • DiskStorageEngine.init(directory:keyType:serializer:options:encryptionKey:), which takes writing options for a typed key without spelling out the engine's generic parameters.
  • Entry file encryption: every DiskStorageEngine initializer accepts an optional encryptionKey. With one, each entry file is encrypted with AES-256-GCM, including its cache key and entry metadata, and named with a keyed hash of its cache key. SwiftStash doesn't create or store encryption keys; the app supplies its own. An encryption key shorter than 256 bits stops the process. The Encrypting entries on disk guide covers the threat model, recommended practices, and sample code for storing an encryption key in the Keychain.
  • Lazy loading: a cache backed by DiskStorageEngine reads only entry metadata when it's created and reads each value on first use. Cache.unloadValues() releases loaded values from memory, and on Apple platforms the cache calls it whenever the system reports memory pressure. Custom storage engines can opt in by implementing the new StorageEngine requirements loadMetadata() and loadValue(for:), which have default implementations, and returning CacheEntryMetadata. When loadValue(for:) returns nil, the cache forgets the entry without deleting it from storage, so engines remove stored entries they can't read.

Changed

  • Breaking: NetworkTimeClock moved to a new SwiftStashNetworkTime library, so only apps that use network time depend on Kronos. Caches now default to SystemClock, a new clock that reads the system date; to keep network time, add the library, import SwiftStashNetworkTime, and pass clock: NetworkTimeClock.shared. CacheEntry.init(key:value:) uses the system date.
  • An addition persists its entries after enforcing the cache's maximum count and cost, so entries evicted as they're added, such as a value over the cost limit, are no longer written to storage and deleted again.
  • LRU caches persist an entry's access at most once every 1% of the policy's threshold, and at most once a minute, instead of on every read, so frequently read entries no longer write to disk on each read. An entry reloaded from storage can expire up to 1% of the threshold early, and its persisted access count can trail the in-memory count.
  • Breaking: StorageEngine.delete(forKey:) is a requirement without a default implementation, so an engine that loads values on demand can't silently keep the entries a cache removes. Engines that don't load values on demand can implement it like delete(_:).
  • Breaking: Cache has a single generic parameter, its storage engine. Replace Cache<Engine, Value> with Cache<Engine>; the value type is available as Cache.CacheType.
  • Reads (the subscript, entry(for:), and values()) no longer return expired entries; reading one removes it.
  • Caches with the FIFO or LIFO policy no longer persist an access on every read. LRU caches still do.
  • Cache.init is synchronous. Existing await Cache(...) calls still compile, with a warning.
  • DiskStorageEngine creates its named directory during initialization.
  • DiskStorageEngine.clear() removes only .cache_entry files, leaving other files in the directory.
  • DiskStorageEngine stores each entry's access count. Older releases ignore it; entries they wrote load with a count of zero.
  • Processes without a bundle identifier, such as command-line tools, store disk entries under their process name instead of a shared app-cache-cache directory. Entries they stored before are no longer found.
  • Disk entry filenames are SHA-256 hashes on every platform. Linux uses swift-crypto, a new dependency on non-Apple platforms. Existing entries are renamed when loaded.
  • Eviction breaks ties between equal dates by key, so the order no longer varies between runs.
  • The minimum macOS version is 14.
  • swift-docc-plugin is required from 1.5.0 instead of exactly 1.5.0.
  • EvictionPolicy is a top-level Sendable, Equatable enum. Cache.EvictionPolicy remains as an alias.
  • values() no longer records an access to each entry, so it doesn't change LRU order or lifetimes.
  • Disk entry files hold a small metadata header followed by the raw serialized value, instead of pretty-printed JSON with a base64-encoded value, so they take about a quarter less space. Files from earlier releases are rewritten in the new format when loaded; earlier releases can't read the new format.
  • With the LRU policy, a read updates only the metadata header of its disk entry file instead of rewriting the value. Storage engines can support this by implementing the new StorageEngine.persistMetadata(_:) requirement, which has a default implementation.
  • Each cache runs on its own serial dispatch queue, so storage engine I/O no longer blocks a thread of Swift's cooperative pool. Creating a cache no longer loads its entries; it loads them on that queue when first used.

Removed

These are breaking changes. Each removed API has a replacement:

  • MonotonicClock is renamed NetworkTimeClock. Its test controls (set(unixTimestamp:), reset(...), and tick(...)) are removed; pass a ManualClock to the cache instead.
  • Date.monotonic and Date.timeIntervalSinceMonotonic are removed; use NetworkTimeClock.shared.now.
  • Cache.init(policy:storagePolicy:clock:) is renamed init(policy:storageEngine:clock:).
  • Cache.evictUntil(maxNbItems:) is renamed evictUntil(maxCount:).
  • CacheableDataType is removed; use Sendable.
  • The Cache subscript setter is removed, since code outside the cache can't call it. Use add(_:for:expiresAfter:) and remove(_:).
  • StringDiskStorageSerializer<NSString> is replaced by TextDiskStorageSerializer, and StringDiskStorageSerializerError is renamed TextDiskStorageSerializerError.
  • Android and Windows are no longer supported. The package no longer declares dependencies for them, and they were never built or tested.

Fixed

  • DiskStorageEngine deleted every entry when loading a directory whose path goes through a symbolic link, such as /var on Apple platforms. Directory listings resolve the link, so each entry file looked like a legacy copy of itself, and the engine rewrote it and then removed it. The engine now lists entry files by name.
  • A cache's total cost could overflow and stop the process when costs summed past Int.max. totalCost now saturates at Int.max. Negative costs read from storage count as zero.
  • DiskStorageEngine reported the errors it recovers from nowhere on Linux. It now writes them to standard error there, and on Apple platforms logs them with the SwiftStash subsystem and DiskStorageEngine category instead of the default log.
  • NetworkTimeClock.now read Kronos's state from each cache's queue while Kronos updated it on the main thread, a data race. The clock now reads Kronos only on the main thread and advances the synchronized date with a monotonic clock. synchronize() starts synchronization on the main queue.
  • DiskStorageEngine recreates its directory when a write finds it removed, for example by the system purging caches. Before, the engine stopped persisting entries until the app relaunched.
  • Two DiskStorageEngine instances with different key types, value types, serializers, or encryption keys could share a directory and delete each other's entry files as unreadable. Creating an engine for a directory that a live engine with another configuration uses now stops the process. Engines with the same configuration can still share a directory.
  • DiskStorageEngine no longer deletes entry files it can't open, such as files written with .completeFileProtection and read while the device is locked. It leaves them in place, and a cache treats their entries as missing.
  • Keys longer than about 190 bytes could not be persisted on Linux, because their filenames exceeded the file-system limit.
  • DiskStorageEngine.persist(_:) produced an unused-result warning.

Full Changelog: 1.1.1...2.0.0