Repository navigation
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 directoryURL, 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 aclockparameter onCache.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
maxCountparameter onCache.initthat evicts down to a maximum entry count after each addition. TextDiskStorageSerializer, a non-generic replacement forStringDiskStorageSerializer.- An
accessCountparameter onCacheEntry.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
expiresAfterparameter on theaddmethods, andCacheEntry.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
costLimitparameter onCache.inittakes 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.totalCostandCacheEntry.costreport 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
DiskStorageEngineinitializer accepts an optionalencryptionKey. 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
DiskStorageEnginereads 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 newStorageEnginerequirementsloadMetadata()andloadValue(for:), which have default implementations, and returningCacheEntryMetadata. WhenloadValue(for:)returnsnil, the cache forgets the entry without deleting it from storage, so engines remove stored entries they can't read.
Changed
- Breaking:
NetworkTimeClockmoved to a newSwiftStashNetworkTimelibrary, so only apps that use network time depend on Kronos. Caches now default toSystemClock, a new clock that reads the system date; to keep network time, add the library,import SwiftStashNetworkTime, and passclock: 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 likedelete(_:). - Breaking:
Cachehas a single generic parameter, its storage engine. ReplaceCache<Engine, Value>withCache<Engine>; the value type is available asCache.CacheType. - Reads (the subscript,
entry(for:), andvalues()) 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.initis synchronous. Existingawait Cache(...)calls still compile, with a warning.DiskStorageEnginecreates its named directory during initialization.DiskStorageEngine.clear()removes only.cache_entryfiles, leaving other files in the directory.DiskStorageEnginestores 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-cachedirectory. 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.
EvictionPolicyis a top-levelSendable,Equatableenum.Cache.EvictionPolicyremains 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:
MonotonicClockis renamedNetworkTimeClock. Its test controls (set(unixTimestamp:),reset(...), andtick(...)) are removed; pass aManualClockto the cache instead.Date.monotonicandDate.timeIntervalSinceMonotonicare removed; useNetworkTimeClock.shared.now.Cache.init(policy:storagePolicy:clock:)is renamedinit(policy:storageEngine:clock:).Cache.evictUntil(maxNbItems:)is renamedevictUntil(maxCount:).CacheableDataTypeis removed; useSendable.- The
Cachesubscript setter is removed, since code outside the cache can't call it. Useadd(_:for:expiresAfter:)andremove(_:). StringDiskStorageSerializer<NSString>is replaced byTextDiskStorageSerializer, andStringDiskStorageSerializerErroris renamedTextDiskStorageSerializerError.- Android and Windows are no longer supported. The package no longer declares dependencies for them, and they were never built or tested.
Fixed
DiskStorageEnginedeleted every entry when loading a directory whose path goes through a symbolic link, such as/varon 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.totalCostnow saturates atInt.max. Negative costs read from storage count as zero. DiskStorageEnginereported the errors it recovers from nowhere on Linux. It now writes them to standard error there, and on Apple platforms logs them with theSwiftStashsubsystem andDiskStorageEnginecategory instead of the default log.NetworkTimeClock.nowread 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.DiskStorageEnginerecreates 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
DiskStorageEngineinstances 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. DiskStorageEngineno longer deletes entry files it can't open, such as files written with.completeFileProtectionand 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