diff --git a/.github/diag/urlnul.swift b/.github/diag/urlnul.swift new file mode 100644 index 0000000..d0d18b2 --- /dev/null +++ b/.github/diag/urlnul.swift @@ -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) +} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7e92d36..18e2745 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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 diff --git a/CHANGELOG.md b/CHANGELOG.md index 143a0da..06f8a9c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/README.md b/README.md index 25cd7ab..2bfd719 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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 @@ -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 diff --git a/Sources/Cache/Configuration/DiskConfig.swift b/Sources/Cache/Configuration/DiskConfig.swift index 0fb6e1a..0f1782f 100644 --- a/Sources/Cache/Configuration/DiskConfig.swift +++ b/Sources/Cache/Configuration/DiskConfig.swift @@ -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 diff --git a/Sources/Cache/Configuration/MemoryConfig.swift b/Sources/Cache/Configuration/MemoryConfig.swift index 40ce8a5..6032982 100644 --- a/Sources/Cache/Configuration/MemoryConfig.swift +++ b/Sources/Cache/Configuration/MemoryConfig.swift @@ -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 diff --git a/Sources/Cache/Storage/DiskStorage.swift b/Sources/Cache/Storage/DiskStorage.swift index 1f3ca39..56dca1e 100644 --- a/Sources/Cache/Storage/DiskStorage.swift +++ b/Sources/Cache/Storage/DiskStorage.swift @@ -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 @@ -19,16 +24,28 @@ final class DiskStorage: Sendable { } // path - self.path = url.appendingPathComponent(config.name, isDirectory: true).path + let path = url.appendingPathComponent(config.name, isDirectory: true).path + // File system calls stop reading a path at a NUL, so they would act on a different folder. + // The URL keeps a NUL as %00, which its path may or may not decode, so both are checked. + guard url.isFileURL, !path.unicodeScalars.contains("\u{0}"), + url.absoluteString.range(of: "%00", options: .caseInsensitive) == nil, + URL(fileURLWithPath: path, isDirectory: true).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 { @@ -37,17 +54,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(ofType type: T.Type, forKey key: String) throws -> Entry { - 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 @@ -59,38 +75,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(_ 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 { @@ -113,10 +110,20 @@ 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 + } } } @@ -124,7 +131,7 @@ extension DiskStorage: StorageAware { 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) @@ -154,10 +161,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(_ 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, + 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 */ @@ -169,7 +239,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 { @@ -281,21 +351,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(_ 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) } diff --git a/Sources/Cache/Storage/HybridStorage.swift b/Sources/Cache/Storage/HybridStorage.swift index 9c84dd9..bc8e4c9 100644 --- a/Sources/Cache/Storage/HybridStorage.swift +++ b/Sources/Cache/Storage/HybridStorage.swift @@ -14,66 +14,74 @@ final class HybridStorage: Sendable { private let memoryStorage: MemoryStorage private let diskStorage: DiskStorage - /// Lock for atomic cross-storage operations - private let lock = OSAllocatedUnfairLock() + /// Keeps memory and disk in step when changing them, and counts those changes. The count lets + /// a read notice that the object it just decoded may be out of date. + private let lock = OSAllocatedUnfairLock(initialState: 0) } extension HybridStorage: StorageAware { func entry(ofType type: T.Type, forKey key: String) throws -> Entry { - try self.lock.withLockUnchecked { - do { - return try self.memoryStorage.entry(ofType: type, forKey: key) - } - catch { - let entry = try diskStorage.entry(ofType: type, forKey: key) - // set back to memoryStorage + // Without the lock, so that a hit doesn't wait for another object's disk access + if let entry = try? self.memoryStorage.entry(ofType: type, forKey: key) { + return entry + } + + // Decoding happens without the lock too, so the object may be removed or replaced meanwhile. + // Memory is only filled if nothing changed, or this would bring back the old object. + let changeCount = self.lock.withLockUnchecked { $0 } + let entry = try diskStorage.entry(ofType: type, forKey: key) + self.lock.withLockUnchecked { currentCount in + if currentCount == changeCount { self.memoryStorage.setObject(entry.object, forKey: key, expiry: entry.expiry) - return entry } } + return entry } func existsObject(forKey key: String) throws -> Bool { - try lock.withLockUnchecked { - if memoryStorage.existsObject(forKey: key) { - return true - } - return try diskStorage.existsObject(forKey: key) + if self.memoryStorage.existsObject(forKey: key) { + return true } + return try self.diskStorage.existsObject(forKey: key) } func removeObject(forKey key: String) throws { - try self.lock.withLockUnchecked { + try self.lock.withLockUnchecked { changeCount in + changeCount += 1 self.memoryStorage.removeObject(forKey: key) try self.diskStorage.removeObject(forKey: key) } } func setObject(_ object: some Codable & Sendable, forKey key: String, expiry: Expiry? = nil) throws { - try self.lock.withLockUnchecked { + let data = try diskStorage.encode(object, forKey: key) + + try self.lock.withLockUnchecked { changeCount in + changeCount += 1 // Disk first, because it's the one that can fail. Memory then never holds what wasn't saved. - try self.diskStorage.setObject(object, forKey: key, expiry: expiry) - self.memoryStorage.setObject(object, forKey: key, expiry: expiry) + // An object has one expiry: the disk works it out once it has its own lock, and the copy + // in memory gets the same date, so it can't outlive the file. + let date = try self.diskStorage.write(data, forKey: key, expiry: expiry) + self.memoryStorage.setObject(object, forKey: key, expiry: .date(date)) } } func removeAll() throws { - try self.lock.withLockUnchecked { + try self.lock.withLockUnchecked { changeCount in + changeCount += 1 self.memoryStorage.removeAll() try self.diskStorage.removeAll() } } func removeExpiredObjects() throws { - try self.lock.withLockUnchecked { + try self.lock.withLockUnchecked { _ in self.memoryStorage.removeExpiredObjects() try self.diskStorage.removeExpiredObjects() } } func diskSize() throws -> UInt64 { - try self.lock.withLockUnchecked { - try self.diskStorage.diskSize() - } + try self.diskStorage.diskSize() } } diff --git a/Sources/Cache/Storage/Storage.swift b/Sources/Cache/Storage/Storage.swift index eb4ad7f..fd9b1a3 100644 --- a/Sources/Cache/Storage/Storage.swift +++ b/Sources/Cache/Storage/Storage.swift @@ -9,7 +9,8 @@ public final class Storage: Sendable { /// - Parameters: /// - diskConfig: Configuration for disk storage /// - memoryConfig: Optional. Pass config to add an in-memory layer - /// - Throws: Throw StorageError if any. + /// - Throws: `CocoaError(.fileWriteInvalidFileName)` if the config's name isn't a single folder name, + /// or the file system's error if the folder can't be created. public init(diskConfig: DiskConfig, memoryConfig: MemoryConfig? = nil) throws { let disk = try DiskStorage(config: diskConfig) @@ -37,7 +38,9 @@ public final class Storage: Sendable { extension Storage: StorageAware { /** - Tries to retrieve the object from the storage. + Tries to retrieve the object from the storage. Use the type the object was written as: with + any other type, the kinds of storage can give different results, including the file's raw + bytes when asking for `Data`. - 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 @@ -85,16 +88,17 @@ extension Storage: StorageAware { } /** - Removes all objects from the cache storage. + Removes all objects from the cache storage. On disk, it deletes the storage's own files, + including ones from an older version of this package, and leaves anything else in the folder. + A file that can't be removed doesn't stop the others. The first failure is thrown at the end. */ 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. + Clears all expired objects, and files left behind by an older version of this package, whatever + their age. Only files named like the storage's objects, directly in its folder, are ever deleted. A file that can't be removed doesn't stop the others. The first failure is thrown at the end. */ public func removeExpiredObjects() throws { diff --git a/Tests/CacheTests/ConcurrencyTests.swift b/Tests/CacheTests/ConcurrencyTests.swift new file mode 100644 index 0000000..2d16d1c --- /dev/null +++ b/Tests/CacheTests/ConcurrencyTests.swift @@ -0,0 +1,225 @@ +import Foundation +import os +import Testing +@testable import Cache + +@Suite("Concurrency") +struct ConcurrencyTests { + // MARK: Using it from many threads + + /// Mostly here for Thread Sanitizer, which CI runs it under. Values carry their key, to catch mix-ups. + @Test("Many threads can use a storage at once", arguments: Sandbox.Mode.allCases) + func manyThreads(mode: Sandbox.Mode) throws { + let sandbox = try Sandbox() + // A small limit, so that NSCache evicts while this runs + let storage = try sandbox.storage(mode, countLimit: 5) + let failures = OSAllocatedUnfairLock(initialState: [String]()) + + DispatchQueue.concurrentPerform(iterations: 8) { thread in + for iteration in 0 ..< 300 { + let keyNumber = (iteration + thread) % 10 + let key = "key\(keyNumber)" + do { + try storage.setObject(iteration * 10 + keyNumber, forKey: key, + expiry: iteration % 3 == 0 ? .seconds(-1) : .seconds(60)) + _ = try storage.existsObject(forKey: key) + do { + let value = try storage.object(ofType: Int.self, forKey: key) + if value % 10 != keyNumber { + failures.withLock { $0.append("\(key) held \(value)") } + } + } + catch StorageError.notFound { + // It expired, or another thread removed it + } + if iteration % 20 == 0 { try storage.removeObject(forKey: key) } + if iteration % 50 == 0 { + try storage.removeExpiredObjects() + _ = try storage.diskSize() + } + if iteration % 120 == 0 { try storage.removeAll() } + } + catch { + failures.withLock { $0.append("\(error)") } + } + } + } + + #expect(failures.withLock { $0 } == []) + } + + // MARK: Not waiting for each other + + /// Runs the code on another thread while `write` is stuck at the gate. + private func whileHeldUp(at gate: Gate, write: @escaping @Sendable () -> Void, _ code: () throws -> Void) throws { + let finished = DispatchSemaphore(value: 0) + DispatchQueue.global().async { + write() + finished.signal() + } + let entered = gate.waitUntilEntered() + defer { + gate.release() + finished.wait() + #expect(!gate.timedOut, "The code had to wait for the write to finish") + } + try #require(entered, "The write never got to the gate") + try code() + } + + @Test("A slow encode doesn't hold up other objects", arguments: [Sandbox.Mode.disk, .hybrid]) + func slowEncode(mode: Sandbox.Mode) throws { + let sandbox = try Sandbox() + let storage = try sandbox.storage(mode) + try storage.setObject(1, forKey: "existing") + let gate = Gate() + + try whileHeldUp(at: gate, write: { try? storage.setObject(HeldUpWhileEncoding(gate: gate), forKey: "slow") }) { + #expect(try storage.object(ofType: Int.self, forKey: "existing") == 1) + try storage.setObject(2, forKey: "other") + #expect(try storage.object(ofType: Int.self, forKey: "other") == 2) + try storage.removeObject(forKey: "other") + } + } + + @Test("A slow disk doesn't hold up an object that's in memory") + func slowDisk() throws { + let sandbox = try Sandbox() + let fileManager = HookedFileManager() + let disk = try DiskStorage(config: DiskConfig(name: "cache", directory: sandbox.root), fileManager: fileManager) + let storage = HybridStorage(memoryStorage: MemoryStorage(config: MemoryConfig()), diskStorage: disk) + try storage.setObject(1, forKey: "inMemory", expiry: nil) + let gate = Gate() + fileManager.beforeSettingAttributes = { _ in gate.enter() } + + try whileHeldUp(at: gate, write: { try? storage.setObject(2, forKey: "slow", expiry: nil) }) { + let value = try storage.object(ofType: Int.self, forKey: "inMemory") + let exists = try storage.existsObject(forKey: "inMemory") + #expect(value == 1) + #expect(exists) + } + } + + /// Saves an object with a short expiry while `holdUp` is stuck at the gate, and waits longer than + /// that expiry before letting it go. The object's expiry should only start once it got through. + private func expectExpiryStartsAfterWaiting(storage: HybridStorage, sandbox: Sandbox, gate: Gate, + holdUp: @escaping @Sendable () -> Void) throws + { + let finished = DispatchSemaphore(value: 0) + var endOfWait = Date.distantFuture + + try whileHeldUp(at: gate, write: holdUp) { + DispatchQueue.global().async { + try? storage.setObject(2, forKey: "short", expiry: .seconds(0.1)) + finished.signal() + } + // Longer than the object's expiry + Thread.sleep(forTimeInterval: 0.3) + endOfWait = Date() + } + finished.wait() + + // The file's date rather than a read, which would depend on how quickly this gets there + let file = sandbox.folder().appendingPathComponent(fileName(for: "short")) + let expiry = try FileManager.default.attributesOfItem(atPath: file.path)[.modificationDate] as? Date + #expect(try #require(expiry) > endOfWait) + } + + @Test("Waiting for another write doesn't use up an object's expiry") + func expiryStartsAfterWaiting() throws { + let sandbox = try Sandbox() + let fileManager = HookedFileManager() + let disk = try DiskStorage(config: DiskConfig(name: "cache", directory: sandbox.root), fileManager: fileManager) + let storage = HybridStorage(memoryStorage: MemoryStorage(config: MemoryConfig()), diskStorage: disk) + let gate = Gate() + let slowFile = fileName(for: "slow") + fileManager.beforeSettingAttributes = { path in + if path.hasSuffix(slowFile) { + gate.enter() + } + } + + try expectExpiryStartsAfterWaiting(storage: storage, sandbox: sandbox, gate: gate) { + try? storage.setObject(1, forKey: "slow", expiry: nil) + } + } + + /// Disk reads don't take hybrid storage's own lock, only the disk's. + @Test("Waiting for a disk read doesn't use up an object's expiry") + func expiryStartsAfterWaitingForRead() throws { + let sandbox = try Sandbox() + let fileManager = HookedFileManager() + let disk = try DiskStorage(config: DiskConfig(name: "cache", directory: sandbox.root), fileManager: fileManager) + // On disk only, so that reading it goes to the disk + try disk.setObject(1, forKey: "slow") + let storage = HybridStorage(memoryStorage: MemoryStorage(config: MemoryConfig()), diskStorage: disk) + let gate = Gate() + let slowFile = fileName(for: "slow") + fileManager.beforeReadingAttributes = { path in + if path.hasSuffix(slowFile) { + gate.enter() + } + } + + try expectExpiryStartsAfterWaiting(storage: storage, sandbox: sandbox, gate: gate) { + _ = try? storage.entry(ofType: Int.self, forKey: "slow") + } + } + + // MARK: Using the storage from Codable code + + @Test("A type's Codable code can use the storage it's being saved in", arguments: [Sandbox.Mode.disk, .hybrid]) + func codableCodeUsesStorage(mode: Sandbox.Mode) throws { + let sandbox = try Sandbox() + let storage = try sandbox.storage(mode) + // A new instance, because hybrid storage would otherwise answer from memory without decoding + let reader = try sandbox.storage(mode) + let writerRan = OSAllocatedUnfairLock(initialState: false) + let readerRan = OSAllocatedUnfairLock(initialState: false) + + try RunsCodeInCodable.$code.withValue({ + try? storage.setObject(1, forKey: "other") + writerRan.withLock { $0 = true } + }) { + try storage.setObject(RunsCodeInCodable(), forKey: "key") + } + _ = try RunsCodeInCodable.$code.withValue({ + _ = try? reader.object(ofType: Int.self, forKey: "other") + readerRan.withLock { $0 = true } + }) { + try reader.object(ofType: RunsCodeInCodable.self, forKey: "key") + } + + #expect(writerRan.withLock { $0 }) + #expect(readerRan.withLock { $0 }) + } + + // MARK: Filling memory from disk + + @Test("An object removed during decoding doesn't come back into memory") + func removedWhileDecoding() throws { + let sandbox = try Sandbox() + try sandbox.storage(.hybrid).setObject(RunsCodeInCodable(), forKey: "key") + let storage = try sandbox.storage(.hybrid) + + _ = try RunsCodeInCodable.$code.withValue({ + try? storage.removeObject(forKey: "key") + }) { + try storage.object(ofType: RunsCodeInCodable.self, forKey: "key") + } + + #expect(try storage.existsObject(forKey: "key") == false) + } + + @Test("An object from disk is kept in memory after reading it") + func readingFillsMemory() throws { + let sandbox = try Sandbox() + try sandbox.storage(.hybrid).setObject(1, forKey: "key") + let storage = try sandbox.storage(.hybrid) + + #expect(try storage.object(ofType: Int.self, forKey: "key") == 1) + try FileManager.default.removeItem(at: sandbox.folder()) + + #expect(try storage.object(ofType: Int.self, forKey: "key") == 1) + } +} diff --git a/Tests/CacheTests/ParityTests.swift b/Tests/CacheTests/ParityTests.swift new file mode 100644 index 0000000..7c16e92 --- /dev/null +++ b/Tests/CacheTests/ParityTests.swift @@ -0,0 +1,282 @@ +import Foundation +import Testing +@testable import Cache + +/// What a read came to, in a form that can be compared between kinds of storage. +enum ReadOutcome: Hashable { + /// The value as JSON, which shows the bytes of a `Data` too + case value(String) + case notFound + /// `typeNotMatch` from memory and `decodingFailed` from disk mean the same thing to the caller + case wrongType + case otherError(String) +} + +/// Writes a value, and reads it back as some type. +struct ReadCase: Sendable, CustomTestStringConvertible { + // MARK: Internal + + let testDescription: String + let write: @Sendable (Storage) throws -> Void + let read: @Sendable (Storage) throws -> String + let expected: ReadOutcome? + + /// Written and read as the same type, which must give back the same value. + static func same(_ value: T, _ name: String = "\(T.self)") -> ReadCase { + ReadCase(testDescription: name, write: self.writing(value), read: self.reading(T.self), + expected: .value(self.json(value))) + } + + /// Read as a type that doesn't fit what was written. + static func mismatch(_ value: T, as _: U.Type) -> ReadCase { + ReadCase(testDescription: "\(T.self) as \(U.self)", write: self.writing(value), read: self.reading(U.self), + expected: .wrongType) + } + + /// Read as a different type, where the kinds of storage are known to disagree. + static func disagreeing(_ value: T, as _: U.Type) -> ReadCase { + ReadCase(testDescription: "\(T.self) as \(U.self)", write: self.writing(value), read: self.reading(U.self), + expected: nil) + } + + // MARK: Private + + private static func writing(_ value: some Codable & Sendable) -> @Sendable (Storage) throws -> Void { + { try $0.setObject(value, forKey: "key") } + } + + private static func reading(_: T.Type) -> @Sendable (Storage) throws -> String { + { try self.json($0.object(ofType: T.self, forKey: "key")) } + } + + private static func json(_ value: some Encodable) -> String { + (try? JSONEncoder().encode(value)).map { String(decoding: $0, as: UTF8.self) } ?? "can't be encoded" + } +} + +/// Every way of reading: from the instance that wrote the object, which for hybrid means from +/// memory, and from a new instance, which for disk and hybrid means from the file. +private func outcomes(of readCase: ReadCase) throws -> [String: ReadOutcome] { + var outcomes = [String: ReadOutcome]() + for (mode, reopened) in [(Sandbox.Mode.disk, true), (.memory, false), (.hybrid, false), (.hybrid, true)] { + let sandbox = try Sandbox() + let writer = try sandbox.storage(mode) + try readCase.write(writer) + let reader = reopened ? try sandbox.storage(mode) : writer + + let name = "\(mode)\(reopened ? " reopened" : "")" + do { + outcomes[name] = try .value(readCase.read(reader)) + } + catch StorageError.notFound { + outcomes[name] = .notFound + } + catch StorageError.typeNotMatch, StorageError.decodingFailed { + outcomes[name] = .wrongType + } + catch { + outcomes[name] = .otherError("\(error)") + } + } + return outcomes +} + +@Suite("All kinds of storage agree") +struct ParityTests { + static let sameTypeCases: [ReadCase] = [ + .same(42), + .same(-1.5), + .same(true), + .same("text"), + .same(""), + .same(Date(timeIntervalSince1970: 1000)), + .same(Person(name: "Ada")), + .same([1, 2, 3]), + .same(["a": 1]), + .same(Data([0, 255, 254, 1]), "Data"), + .same(Data(), "empty Data"), + .same([Data([0, 255])]), + .same(Data?(Data([0, 255, 254, 1])), "Data? with a value"), + .same(Data?.none, "Data? without a value"), + .same(Int?(1), "Int? with a value"), + .same(Int?.none, "Int? without a value"), + ] + + static let mismatchCases: [ReadCase] = [ + .mismatch(1, as: Person.self), + .mismatch("text", as: Int.self), + .mismatch(Person(name: "Ada"), as: String.self), + .mismatch(Int?.none, as: Int.self), + ] + + /// Files don't record the type they were written with. `Data` is read as it is without looking + /// inside, and anything else is decoded if its JSON happens to fit, while memory compares types. + /// The README tells callers to read with the type they wrote. If one of these starts passing, + /// that's good news: move it up to `sameTypeCases` or `mismatchCases`. + static let disagreeingCases: [ReadCase] = [ + .disagreeing(Data?(Data([0, 255])), as: Data.self), + .disagreeing(Data([0, 255]), as: Data?.self), + .disagreeing(Person(name: "Ada"), as: Data.self), + .disagreeing(1, as: Double.self), + ] + + @Test("Reading with the type that was written gives back the value", arguments: sameTypeCases) + func sameType(readCase: ReadCase) throws { + for (reader, outcome) in try outcomes(of: readCase) { + #expect(outcome == readCase.expected, "Read by \(reader)") + } + } + + @Test("Reading with a type that doesn't fit is an error", arguments: mismatchCases) + func mismatch(readCase: ReadCase) throws { + for (reader, outcome) in try outcomes(of: readCase) { + #expect(outcome == readCase.expected, "Read by \(reader)") + } + } + + @Test("Reading with another type that happens to fit depends on the storage", arguments: disagreeingCases) + func knownDisagreement(readCase: ReadCase) throws { + let results = try outcomes(of: readCase) + withKnownIssue("Files don't record the type they were written with") { + #expect(Set(results.values).count == 1, "\(results)") + } + } + + // MARK: The config's default expiry + + @Test("The config's expiry applies when an object has none of its own", arguments: Sandbox.Mode.allCases) + func configExpiry(mode: Sandbox.Mode) throws { + let sandbox = try Sandbox() + let storage = try sandbox.storage(mode, expiry: .seconds(-10)) + + try storage.setObject(1, forKey: "key") + + #expect(try storage.existsObject(forKey: "key") == false) + #expect(throws: StorageError.self) { + try storage.object(ofType: Int.self, forKey: "key") + } + } + + @Test("The config's expiry is reported in the entry", arguments: Sandbox.Mode.allCases) + func configExpiryInEntry(mode: Sandbox.Mode) throws { + let sandbox = try Sandbox() + let storage = try sandbox.storage(mode, expiry: .seconds(3600)) + + try storage.setObject(1, forKey: "key") + + let expiry = try storage.entry(ofType: Int.self, forKey: "key").expiry.date + #expect(abs(expiry.timeIntervalSinceNow - 3600) < 60) + } + + @Test("An object's own expiry beats an expired config", arguments: Sandbox.Mode.allCases) + func objectExpiryOverridesExpiredConfig(mode: Sandbox.Mode) throws { + let sandbox = try Sandbox() + let storage = try sandbox.storage(mode, expiry: .seconds(-10)) + + try storage.setObject(1, forKey: "key", expiry: .seconds(3600)) + + #expect(try storage.object(ofType: Int.self, forKey: "key") == 1) + } + + @Test("An object's own expiry beats a config that never expires", arguments: Sandbox.Mode.allCases) + func objectExpiryOverridesLastingConfig(mode: Sandbox.Mode) throws { + let sandbox = try Sandbox() + let storage = try sandbox.storage(mode, expiry: .never) + + try storage.setObject(1, forKey: "key", expiry: .seconds(-10)) + + #expect(try storage.existsObject(forKey: "key") == false) + } +} + +@Suite("Hybrid storage's expiry") +struct HybridExpiryTests { + private func makeStorage(in sandbox: Sandbox, disk: Expiry, memory: Expiry) throws -> Storage { + try Storage(diskConfig: DiskConfig(name: "cache", expiry: disk, directory: sandbox.root), + memoryConfig: MemoryConfig(expiry: memory)) + } + + @Test("The copy in memory doesn't outlive the file") + func memoryDoesNotOutliveDisk() throws { + let sandbox = try Sandbox() + let storage = try makeStorage(in: sandbox, disk: .seconds(-10), memory: .never) + + try storage.setObject("stale", forKey: "key") + + #expect(try storage.existsObject(forKey: "key") == false) + #expect(throws: StorageError.self) { + try storage.object(ofType: String.self, forKey: "key") + } + } + + @Test("MemoryConfig's expiry doesn't cut an object short") + func memoryExpiryIsNotUsed() throws { + let sandbox = try Sandbox() + let storage = try makeStorage(in: sandbox, disk: .never, memory: .seconds(-10)) + + try storage.setObject("kept", forKey: "key") + + #expect(try storage.object(ofType: String.self, forKey: "key") == "kept") + } + + @Test("An entry reports the same expiry from memory and from disk") + func sameExpiryFromMemoryAndDisk() throws { + let sandbox = try Sandbox() + let writer = try makeStorage(in: sandbox, disk: .seconds(3600), memory: .seconds(60)) + try writer.setObject("value", forKey: "key") + + let fromMemory = try writer.entry(ofType: String.self, forKey: "key").expiry.date + let reader = try makeStorage(in: sandbox, disk: .seconds(3600), memory: .seconds(60)) + let fromDisk = try reader.entry(ofType: String.self, forKey: "key").expiry.date + let refilled = try reader.entry(ofType: String.self, forKey: "key").expiry.date + + #expect(abs(fromMemory.timeIntervalSince(fromDisk)) < 1) + #expect(abs(fromDisk.timeIntervalSince(refilled)) < 1) + #expect(abs(fromDisk.timeIntervalSinceNow - 3600) < 60) + } +} + +@Suite("Folder names") +struct FolderNameTests { + @Test("A name that isn't a single folder is refused, with nothing touched", + arguments: ["", ".", "..", "../escaped", "a/b", "/absolute", "a/", + "\u{0}", "\u{0}x", "a\u{0}b", "a\nb", "\t", "\u{7F}"]) + func refused(name: String) throws { + let sandbox = try Sandbox() + let bystander = sandbox.root.appendingPathComponent("bystander.txt") + try Data([1]).write(to: bystander) + + let error = try #require(throws: CocoaError.self) { + try Storage(diskConfig: DiskConfig(name: name, directory: sandbox.root)) + } + + #expect(error.code == .fileWriteInvalidFileName) + #expect(try FileManager.default.contentsOfDirectory(atPath: sandbox.root.path) == ["bystander.txt"]) + } + + @Test("A directory with a NUL in it is refused, with nothing touched") + func refusedDirectory() throws { + let sandbox = try Sandbox() + let bystander = sandbox.root.appendingPathComponent("bystander.txt") + try Data([1]).write(to: bystander) + let directory = sandbox.root.appendingPathComponent("a\u{0}b", isDirectory: true) + + let error = try #require(throws: CocoaError.self) { + try Storage(diskConfig: DiskConfig(name: "cache", directory: directory)) + } + + #expect(error.code == .fileWriteInvalidFileName) + #expect(try FileManager.default.contentsOfDirectory(atPath: sandbox.root.path) == ["bystander.txt"]) + } + + @Test("Other names work", arguments: ["Floppy", "with space", "a.b", ".hidden", "..dots", "…", "日本語"]) + func accepted(name: String) throws { + let sandbox = try Sandbox() + let storage = try Storage(diskConfig: DiskConfig(name: name, directory: sandbox.root)) + + try storage.setObject(1, forKey: "key") + + #expect(try storage.object(ofType: Int.self, forKey: "key") == 1) + #expect(try FileManager.default.contentsOfDirectory(atPath: sandbox.root.path) == [name]) + } +} diff --git a/Tests/CacheTests/StorageTests.swift b/Tests/CacheTests/StorageTests.swift index e7e29b8..9a615ab 100644 --- a/Tests/CacheTests/StorageTests.swift +++ b/Tests/CacheTests/StorageTests.swift @@ -331,21 +331,43 @@ struct StorageTests { #expect(try storage.diskSize() == 0) } - @Test("Hidden files count toward diskSize, and purging removes them") + @Test("Hidden files count toward diskSize") 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) + } + + @Test("Purging and removeAll leave files that aren't the storage's", arguments: [Sandbox.Mode.disk, .hybrid]) + func othersFilesAreKept(mode: Sandbox.Mode) throws { + let sandbox = try Sandbox() + let storage = try sandbox.storage(mode) + try storage.setObject("old", forKey: "old", expiry: .seconds(-10)) + try storage.setObject("new", forKey: "new") + let others = [".hidden", "notes.txt", "README", "ABC.cache", "\(MD5.hash("key")).txt"] + for name in others { + try Data([1]).write(to: sandbox.folder().appendingPathComponent(name)) + } + // A folder named like an object, with a file inside named like one too + let subfolder = sandbox.folder().appendingPathComponent(MD5.hash("folder"), isDirectory: true) + try FileManager.default.createDirectory(at: subfolder, withIntermediateDirectories: true) + try Data([1]).write(to: subfolder.appendingPathComponent(fileName(for: "inside"))) + try FileManager.default.setAttributes([.modificationDate: Date.distantPast], + ofItemAtPath: subfolder.appendingPathComponent(fileName(for: "inside")).path) + let kept = Set(others + [MD5.hash("folder")]) try storage.removeExpiredObjects() + #expect(try Set(sandbox.files()) == kept.union([fileName(for: "new")])) - #expect(try sandbox.files().isEmpty) + try storage.removeAll() + #expect(try Set(sandbox.files()) == kept) + #expect(try FileManager.default.contentsOfDirectory(atPath: subfolder.path) == [fileName(for: "inside")]) } - @Test("A folder that can't be read makes diskSize and purging throw, after doing what they can") - func unreadableFolder() throws { + @Test("Purging and diskSize don't look inside folders, even ones that can't be read") + func unreadableSubfolder() throws { let sandbox = try Sandbox() let storage = try sandbox.storage(.disk) try storage.setObject(1, forKey: "old", expiry: .seconds(-10)) @@ -357,12 +379,8 @@ struct StorageTests { 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() - } + _ = try storage.diskSize() + try storage.removeExpiredObjects() #expect(try sandbox.files() == ["locked"]) } @@ -446,21 +464,6 @@ struct MemoryStorageTests { } } -/// Runs a hook before each removal, which can fail it or delete the file first. -private final class HookedFileManager: FileManager, @unchecked Sendable { - var beforeRemoving: (String) throws -> Void = { _ in } - - override func removeItem(atPath path: String) throws { - try self.beforeRemoving(path) - try super.removeItem(atPath: path) - } - - override func removeItem(at url: URL) throws { - try self.beforeRemoving(url.path) - try super.removeItem(at: url) - } -} - @Suite("Purging with failures") struct PurgeFailureTests { struct RemovalFailed: Error {} diff --git a/Tests/CacheTests/TestSupport.swift b/Tests/CacheTests/TestSupport.swift index c8dc571..f420737 100644 --- a/Tests/CacheTests/TestSupport.swift +++ b/Tests/CacheTests/TestSupport.swift @@ -1,4 +1,5 @@ import Foundation +import os @testable import Cache /// A folder that lasts as long as a test, with the three kinds of storage inside it. @@ -25,13 +26,14 @@ final class Sandbox { let root: URL - func folder(named name: String = "cache") -> URL { - self.root.appendingPathComponent(name, isDirectory: true) + func folder() -> URL { + self.root.appendingPathComponent("cache", isDirectory: true) } - 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) + /// - Parameter expiry: The default expiry, in the config of whichever kinds of storage are used + func storage(_ mode: Mode, expiry: Expiry = .never, countLimit: UInt = 0) throws -> Storage { + let disk = DiskConfig(name: "cache", expiry: expiry, directory: self.root) + let memory = MemoryConfig(expiry: expiry, countLimit: countLimit) return switch mode { case .disk: try Storage(diskConfig: disk) @@ -42,8 +44,8 @@ final class Sandbox { } } - func files(named name: String = "cache") throws -> [String] { - try FileManager.default.contentsOfDirectory(atPath: self.folder(named: name).path) + func files() throws -> [String] { + try FileManager.default.contentsOfDirectory(atPath: self.folder().path) } } @@ -71,3 +73,111 @@ struct UnencodableWithStorageError: Codable, Sendable { throw StorageError.encodingFailed(context: "inner", underlyingError: nil) } } + +/// Runs hooks during file operations, which can fail them, delete the file first, or hold them up. +final class HookedFileManager: FileManager, @unchecked Sendable { + var beforeRemoving: (String) throws -> Void = { _ in } + var beforeSettingAttributes: (String) -> Void = { _ in } + var beforeReadingAttributes: (String) -> Void = { _ in } + + override func attributesOfItem(atPath path: String) throws -> [FileAttributeKey: Any] { + self.beforeReadingAttributes(path) + return try super.attributesOfItem(atPath: path) + } + + override func removeItem(atPath path: String) throws { + try self.beforeRemoving(path) + try super.removeItem(atPath: path) + } + + override func removeItem(at url: URL) throws { + try self.beforeRemoving(url.path) + try super.removeItem(at: url) + } + + override func setAttributes(_ attributes: [FileAttributeKey: Any], ofItemAtPath path: String) throws { + self.beforeSettingAttributes(path) + try super.setAttributes(attributes, ofItemAtPath: path) + } +} + +/// Holds one thread up until another has done something. Gives up after a while and remembers +/// that it did, so that a test fails if the other thread was stuck behind it, rather than hanging. +final class Gate: Sendable { + // MARK: Internal + + var timedOut: Bool { + self.didTimeOut.withLock { $0 } + } + + /// Called by the thread being held up. + func enter() { + self.entered.signal() + if self.released.wait(timeout: .now() + 5) == .timedOut { + self.didTimeOut.withLock { $0 = true } + } + } + + /// Gives up after a while too, because a thread that failed before getting to the gate never will. + /// - Returns: Whether the other thread got to the gate in time + func waitUntilEntered() -> Bool { + self.entered.wait(timeout: .now() + 5) == .success + } + + func release() { + self.released.signal() + } + + // MARK: Private + + private let entered = DispatchSemaphore(value: 0) + private let released = DispatchSemaphore(value: 0) + private let didTimeOut = OSAllocatedUnfairLock(initialState: false) +} + +/// Waits at a gate while it's being encoded. +struct HeldUpWhileEncoding: Codable, Sendable { + // MARK: Lifecycle + + init(gate: Gate) { + self.gate = gate + } + + init(from _: Decoder) throws { + self.gate = nil + } + + // MARK: Internal + + func encode(to encoder: Encoder) throws { + self.gate?.enter() + var container = encoder.singleValueContainer() + try container.encode(1) + } + + // MARK: Private + + private let gate: Gate? +} + +/// Runs some code of the test's while it's being encoded or decoded, like a type whose `Codable` +/// code uses the storage it's being saved in. +struct RunsCodeInCodable: Codable, Sendable { + // MARK: Lifecycle + + init() {} + + init(from _: Decoder) throws { + Self.code?() + } + + // MARK: Internal + + @TaskLocal static var code: (@Sendable () -> Void)? + + func encode(to encoder: Encoder) throws { + Self.code?() + var container = encoder.singleValueContainer() + try container.encode(1) + } +}