diff --git a/Demo/ShoeGazeBuilder/AppDelegate.swift b/Demo/ShoeGazeBuilder/AppDelegate.swift index 3cb2c2d..664dcbe 100644 --- a/Demo/ShoeGazeBuilder/AppDelegate.swift +++ b/Demo/ShoeGazeBuilder/AppDelegate.swift @@ -156,6 +156,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate { func applicationWillTerminate(_ notification: Notification) { RigStore.save(shoeGaze) + // Ensure any in-flight background rig-library writes finish before exit. + library.flushPendingWrites() engine.stop() } diff --git a/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSAppModel.swift b/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSAppModel.swift index 83fac10..bc7c830 100644 --- a/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSAppModel.swift +++ b/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSAppModel.swift @@ -91,6 +91,9 @@ final class ShoeGazeBuilderiOSAppModel { /// Persists the current rig. Call when the app moves to the background. func save() { RigStore.save(shoeGaze) + // Flush any in-flight background rig-library writes while we still have time in the + // background. + library.flushPendingWrites() } // MARK: - Audio session / engine construction diff --git a/Sources/LyrebirdShoeGaze/Presets/RigLibraryStore.swift b/Sources/LyrebirdShoeGaze/Presets/RigLibraryStore.swift index bd782bc..2ca26c9 100644 --- a/Sources/LyrebirdShoeGaze/Presets/RigLibraryStore.swift +++ b/Sources/LyrebirdShoeGaze/Presets/RigLibraryStore.swift @@ -61,8 +61,15 @@ public final class RigLibraryStore { /// Retained NotificationCenter tokens for the metadata-query observers. @ObservationIgnored private var observerTokens: [NSObjectProtocol] = [] + /// Serial queue for all disk writes/deletes. Mutations update the in-memory `entries` on the + /// main actor immediately (so the UI never blocks on disk or iCloud coordination), then hand the + /// file work here. Serial ordering keeps a rename's delete-then-write — and any save/delete on + /// the same file — in submission order. + @ObservationIgnored private let ioQueue: DispatchQueue = + DispatchQueue(label: "net.realizedsound.shoegaze.riglibrary.io", qos: .utility) + /// File extension of a stored rig. - private static let fileExtension: String = "json" + private nonisolated static let fileExtension: String = "json" // MARK: - Init @@ -120,46 +127,73 @@ public final class RigLibraryStore { /// rig and to overwrite an existing one (`shoeGaze.captureEntry(name:id:)`). /// /// - Parameter entry: The rig entry to persist. - /// - Throws: `JSONEncoder`, `NSFileCoordinator`, or write errors. + /// - Throws: `JSONEncoder` errors (encoding happens synchronously). The actual file write runs + /// asynchronously on a background queue and only logs on failure — call + /// ``flushPendingWrites()`` to wait for it (e.g. in tests or at app termination). public func save(_ entry: RigEntry) throws { - // Replacing an existing id whose name changed leaves a stale file behind — remove any - // current file for this id first, then write under the (possibly new) name. - if let stale: URL = existingFileURL(for: entry.id) { - removeFileIfPresent(at: stale) - } + // Encode synchronously (cheap, CPU) so an encoding failure is surfaced to the caller; then + // update the in-memory list immediately and push the disk write to the background queue. let data: Data = try encode(entry) - try writeData(data, to: fileURL(for: entry)) + let target: URL = fileURL(for: entry) + let directory: URL = self.directory + let id: UUID = entry.id + let coordinated: Bool = isICloud upsert(entry) - } - - /// Deletes `entry` from disk and memory. No-op if its file is already gone. - /// - /// - Parameter entry: The rig entry to remove. - /// - Throws: `NSFileCoordinator` or removal errors other than "file not found". - public func delete(_ entry: RigEntry) throws { - if let url: URL = existingFileURL(for: entry.id) { - try removeFile(at: url) - } - entries.removeAll { $0.id == entry.id } - } - - /// Deletes **every** rig in the library, from disk and memory. - /// - /// Removes all `*.json` files in the directory. A failure on one file propagates after the - /// remaining files have been attempted, so a single locked file cannot strand the rest. - /// - /// - Throws: The first removal error encountered, after attempting all files. - public func eraseAll() throws { - var firstError: Error? - for url: URL in rigFileURLs() { + ioQueue.async { + // Remove any prior file for this id first (a rename changes the name-prefixed filename). + if let stale: URL = RigLibraryStore.existingFileURL(for: id, in: directory), + stale.standardizedFileURL != target.standardizedFileURL { + try? RigLibraryStore.removeFile(at: stale, coordinated: coordinated) + } do { - try removeFile(at: url) + try RigLibraryStore.writeData(data, to: target, coordinated: coordinated) } catch { - if firstError == nil { firstError = error } + print("[RigLibraryStore] save write failed: \(error)") } } + } + + /// Deletes `entry` from memory immediately and removes its file on the background queue. + /// + /// - Parameter entry: The rig entry to remove. + /// - Throws: Never throws today; remains `throws` for API stability. File-removal errors are + /// logged on the background queue. + public func delete(_ entry: RigEntry) throws { + entries.removeAll { $0.id == entry.id } + let directory: URL = self.directory + let id: UUID = entry.id + let coordinated: Bool = isICloud + ioQueue.async { + if let url: URL = RigLibraryStore.existingFileURL(for: id, in: directory) { + do { try RigLibraryStore.removeFile(at: url, coordinated: coordinated) } + catch { print("[RigLibraryStore] delete failed: \(error)") } + } + } + } + + /// Clears the library in memory immediately and removes every rig file on the background queue. + /// + /// - Throws: Never throws today; remains `throws` for API stability. Per-file removal errors are + /// logged on the background queue. + public func eraseAll() throws { entries.removeAll() - if let firstError: Error = firstError { throw firstError } + let directory: URL = self.directory + let coordinated: Bool = isICloud + ioQueue.async { + for url: URL in RigLibraryStore.rigFileURLs(in: directory) { + do { try RigLibraryStore.removeFile(at: url, coordinated: coordinated) } + catch { print("[RigLibraryStore] eraseAll: removing \(url.lastPathComponent) failed: \(error)") } + } + } + } + + /// Blocks until all queued background writes/deletes have completed. + /// + /// Primarily for tests (assert on-disk state right after a mutation) and app termination (ensure + /// the last save reaches disk before exit). Avoid calling on the main thread during normal use — + /// that would reintroduce the very stall this design removes. + public func flushPendingWrites() { + ioQueue.sync { } } /// Duplicates `entry` under `newName` as an independent entry with a fresh `id`, persists it, @@ -249,11 +283,12 @@ public final class RigLibraryStore { /// are hidden `*.icloud` files) are naturally ignored and picked up on a later metadata update. private func reloadFromDirectory() { var loaded: [RigEntry] = [] - for url: URL in rigFileURLs() { - guard let data: Data = try? readData(at: url) else { continue } - guard let entry: RigEntry = try? makeDecoder().decode(RigEntry.self, from: data) else { + let decoder: JSONDecoder = makeDecoder() + for url: URL in RigLibraryStore.rigFileURLs(in: directory) { + guard let data: Data = try? RigLibraryStore.readData(at: url, coordinated: isICloud) else { continue } + guard let entry: RigEntry = try? decoder.decode(RigEntry.self, from: data) else { continue } loaded.append(entry) } entries = RigLibraryStore.sorted(loaded) @@ -299,7 +334,7 @@ public final class RigLibraryStore { for index: Int in 0...json` suffix, so renames (which - /// change the name prefix) are still located. `nil` if no file is present. - private func existingFileURL(for id: UUID) -> URL? { - let suffix: String = "-\(id.uuidString).\(RigLibraryStore.fileExtension)" - return rigFileURLs().first { $0.lastPathComponent.hasSuffix(suffix) } + /// change the name prefix) are still located. `nil` if no file is present. `static` so the + /// background I/O queue can call it without touching actor state. + private nonisolated static func existingFileURL(for id: UUID, in directory: URL) -> URL? { + let suffix: String = "-\(id.uuidString).\(fileExtension)" + return rigFileURLs(in: directory).first { $0.lastPathComponent.hasSuffix(suffix) } } - /// All `*.json` files currently in the directory (hidden iCloud placeholders excluded). - private func rigFileURLs() -> [URL] { + /// All `*.json` files currently in `directory` (hidden iCloud placeholders excluded). + private nonisolated static func rigFileURLs(in directory: URL) -> [URL] { let contents: [URL] = (try? FileManager.default.contentsOfDirectory( at: directory, includingPropertiesForKeys: nil, options: .skipsHiddenFiles )) ?? [] - return contents.filter { $0.pathExtension == RigLibraryStore.fileExtension } + return contents.filter { $0.pathExtension == fileExtension } } - /// Whether `url` is a rig file inside this library's directory. - private func isInLibrary(_ url: URL) -> Bool { + /// Whether `url` is a rig file directly inside `directory`. + private nonisolated static func isInLibrary(_ url: URL, directory: URL) -> Bool { url.deletingLastPathComponent().standardizedFileURL == directory.standardizedFileURL - && url.pathExtension == RigLibraryStore.fileExtension + && url.pathExtension == fileExtension } - // MARK: - Coordinated I/O + // MARK: - Coordinated I/O (background-queue safe) /// Writes `data` to `url`, coordinating the write through `NSFileCoordinator` when iCloud-backed. - private func writeData(_ data: Data, to url: URL) throws { - guard isICloud else { + private nonisolated static func writeData(_ data: Data, to url: URL, coordinated: Bool) throws { + guard coordinated else { try data.write(to: url, options: .atomic) return } - try coordinate(url, options: .forReplacing) { target in + try coordinateWriting(url, options: .forReplacing) { target in try data.write(to: target, options: .atomic) } } /// Reads the contents of `url`, coordinating the read when iCloud-backed. - private func readData(at url: URL) throws -> Data { - guard isICloud else { + private nonisolated static func readData(at url: URL, coordinated: Bool) throws -> Data { + guard coordinated else { return try Data(contentsOf: url) } var result: Data = Data() - try coordinate(url, options: .withoutChanges) { target in + try coordinateReading(url, options: .withoutChanges) { target in result = try Data(contentsOf: target) } return result } /// Removes `url`, coordinating the delete when iCloud-backed. - private func removeFile(at url: URL) throws { - guard isICloud else { + private nonisolated static func removeFile(at url: URL, coordinated: Bool) throws { + guard coordinated else { try FileManager.default.removeItem(at: url) return } - try coordinate(url, options: .forDeleting) { target in + try coordinateWriting(url, options: .forDeleting) { target in try FileManager.default.removeItem(at: target) } } - /// Best-effort remove that swallows "file not found" and other errors — used before a replacing - /// write where a missing prior file is expected. - private func removeFileIfPresent(at url: URL) { - try? removeFile(at: url) - } - - /// Runs `body` inside an `NSFileCoordinator` block, surfacing both the coordinator's error and - /// any error thrown by `body`. - private func coordinate( + /// Runs `body` inside an `NSFileCoordinator` write block, surfacing both the coordinator's error + /// and any error thrown by `body`. + private nonisolated static func coordinateWriting( _ url: URL, options: NSFileCoordinator.WritingOptions, _ body: (URL) throws -> Void @@ -400,8 +430,8 @@ public final class RigLibraryStore { if let thrown: Error = thrown { throw thrown } } - /// Coordinated read overload (uses the reading coordinator path). - private func coordinate( + /// Runs `body` inside an `NSFileCoordinator` read block. + private nonisolated static func coordinateReading( _ url: URL, options: NSFileCoordinator.ReadingOptions, _ body: (URL) throws -> Void diff --git a/Tests/LyrebirdShoeGazeTests/RigLibraryStoreTests.swift b/Tests/LyrebirdShoeGazeTests/RigLibraryStoreTests.swift index 2275a93..68ea1ee 100644 --- a/Tests/LyrebirdShoeGazeTests/RigLibraryStoreTests.swift +++ b/Tests/LyrebirdShoeGazeTests/RigLibraryStoreTests.swift @@ -40,6 +40,7 @@ struct RigLibraryStoreTests { // Sorted by name, case-insensitive. #expect(store.entries.map(\.name) == ["Ambient", "Crunch"]) + store.flushPendingWrites() // A fresh store over the same directory sees the persisted files. let reopened: RigLibraryStore = RigLibraryStore(directory: dir, isICloud: false) reopened.start() @@ -59,6 +60,7 @@ struct RigLibraryStoreTests { #expect(store.entries.count == 1) #expect(store.entries.first?.name == "Renamed") + store.flushPendingWrites() let files: [URL] = try FileManager.default.contentsOfDirectory( at: dir, includingPropertiesForKeys: nil ).filter { $0.pathExtension == "json" } @@ -74,6 +76,7 @@ struct RigLibraryStoreTests { let renamed: RigEntry = try store.rename(entry, to: "After") #expect(renamed.id == entry.id) #expect(store.entries.map(\.name) == ["After"]) + store.flushPendingWrites() } @Test func duplicateCreatesIndependentEntry() throws { @@ -85,6 +88,7 @@ struct RigLibraryStoreTests { let copy: RigEntry = try store.duplicate(entry, newName: "Base 2") #expect(copy.id != entry.id) #expect(store.entries.count == 2) + store.flushPendingWrites() } @Test func deleteRemovesFileAndEntry() throws { @@ -96,6 +100,7 @@ struct RigLibraryStoreTests { try store.delete(entry) #expect(store.entries.isEmpty) + store.flushPendingWrites() let files: [URL] = try FileManager.default.contentsOfDirectory( at: dir, includingPropertiesForKeys: nil ).filter { $0.pathExtension == "json" } @@ -112,6 +117,7 @@ struct RigLibraryStoreTests { try store.eraseAll() #expect(store.entries.isEmpty) + store.flushPendingWrites() let reopened: RigLibraryStore = RigLibraryStore(directory: dir, isICloud: false) reopened.start() #expect(reopened.entries.isEmpty) @@ -131,6 +137,8 @@ struct RigLibraryStoreTests { let added: Int = try other.importArchive(from: archiveData) #expect(added == 2) #expect(other.entries.map(\.name) == ["One", "Two"]) + store.flushPendingWrites() + other.flushPendingWrites() } @Test func importColludingIdGetsFreshId() throws { @@ -146,6 +154,7 @@ struct RigLibraryStoreTests { let added: Int = try store.importArchive(from: data) #expect(added == 1) #expect(store.entries.count == 2, "colliding id should be imported as a new entry") + store.flushPendingWrites() } @Test func importLegacySingleRigFile() throws { @@ -158,5 +167,6 @@ struct RigLibraryStoreTests { let added: Int = try store.importArchive(from: data, legacyRigName: "Recovered") #expect(added == 1) #expect(store.entries.first?.name == "Recovered") + store.flushPendingWrites() } } diff --git a/docs/plans/1.2-rig-library.md b/docs/plans/1.2-rig-library.md index 09cde92..37f5ce7 100644 --- a/docs/plans/1.2-rig-library.md +++ b/docs/plans/1.2-rig-library.md @@ -60,13 +60,16 @@ still works; the sidebar shows the `icloud.slash` glyph. ### Known limitations / deferred (from pre-PR review) -- **Main-thread iCloud I/O.** `RigLibraryLocation.resolve()` does a blocking ubiquity lookup, and - `RigLibraryStore`'s `NSFileCoordinator` reads/writes run on the main actor. Mitigated for the - common case: `resolve()` short-circuits to local (no blocking call) when no iCloud account is - signed in, and coordinated writes only happen on explicit, occasional user saves. A full fix - needs an async resolve + a loading state in the builder, and must move seeding *after* the iCloud - state is known — otherwise a first-launch seed races the synced library and creates a spurious - "Default" rig on every device. Deferred deliberately. +- **Background writes.** Save/delete/erase update the in-memory `entries` on the main actor + instantly (UI never blocks) and run the file write/delete — including `NSFileCoordinator` — on a + serial background queue (`ioQueue`). `flushPendingWrites()` drains it (used by tests and at app + termination / iOS background). This removed the save-time UI stall. +- **Remaining main-thread I/O.** `RigLibraryLocation.resolve()` still does a blocking ubiquity + lookup (short-circuited to local when no iCloud account is signed in), and the *reads* in + `reloadFromDirectory()` (launch + iCloud metadata updates) are still synchronous on the main + actor. A full fix needs an async resolve + a loading state in the builder, and must move seeding + *after* the iCloud state is known — otherwise a first-launch seed races the synced library and + creates a spurious "Default" rig on every device. Deferred deliberately. - **`eraseAll()`** clears the in-memory list even if a file deletion fails (it still throws the first error). A re-`start()` re-scans and re-surfaces any undeleted rigs, so state self-heals. - Possible later work: conflict UI for simultaneous multi-device edits; the async-resolve redesign