Make rig library loads/resolve fully off-main
Move the remaining synchronous main-thread I/O off the main actor: - RigLibraryStore now constructs instantly with a local placeholder and exposes an awaitable async start(): it resolves the iCloud-or-local location off-main (the blocking ubiquity lookup), loads entries off-main via the shared ioQueue (so a reload can't drop a just-saved rig), then sets isLoaded. reload() is async; iCloud metadata updates re-read via it. - Seeding moves into RigLibraryBootstrap.start(_:seedFrom:), which seeds a "Default" rig only AFTER the (possibly iCloud) library has loaded and is still empty — preventing a duplicate "Default" on every synced device on first launch. - Sidebar shows a Loading state until isLoaded; the builder restores the persisted current-rig highlight when isLoaded flips true (initialRigID param dropped). - Shells construct the store synchronously and start it asynchronously (macOS via Task in didFinishLaunching; iOS via .task). Codec + file helpers are nonisolated static so background work needs no actor hop. - Tests await store.start(). Full suite: 206 passing. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -47,11 +47,17 @@ public final class RigLibraryStore {
|
||||
public private(set) var entries: [RigEntry] = []
|
||||
|
||||
/// `true` when the library is backed by the iCloud container (changes sync); `false` for the
|
||||
/// local-only fallback.
|
||||
public let isICloud: Bool
|
||||
/// local-only fallback. Resolved during ``start()`` for an auto-resolving store.
|
||||
public private(set) var isICloud: Bool
|
||||
|
||||
/// The directory holding the per-rig JSON files.
|
||||
public let directory: URL
|
||||
/// The directory holding the per-rig JSON files. May be repointed from local to iCloud during
|
||||
/// ``start()`` for an auto-resolving store (before any writes, so no migration is needed).
|
||||
public private(set) var directory: URL
|
||||
|
||||
/// `false` until the first load completes. Views can show a loading state and callers should
|
||||
/// wait for this (or `await start()`) before deciding whether the library is empty — otherwise a
|
||||
/// first-launch seed would race a not-yet-loaded iCloud library.
|
||||
public private(set) var isLoaded: Bool = false
|
||||
|
||||
// MARK: - Private
|
||||
|
||||
@@ -71,10 +77,14 @@ public final class RigLibraryStore {
|
||||
/// File extension of a stored rig.
|
||||
private nonisolated static let fileExtension: String = "json"
|
||||
|
||||
/// When `true`, ``start()`` resolves the iCloud-or-local location off the main thread and
|
||||
/// repoints `directory`/`isICloud` before loading. `false` for the explicit test initializer.
|
||||
private let autoResolve: Bool
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a store rooted at an explicit directory. Designated initializer; used directly by
|
||||
/// tests with a temporary directory and `isICloud: false`.
|
||||
/// Creates a store rooted at an explicit directory. Used directly by tests with a temporary
|
||||
/// directory; `start()` will not re-resolve the location.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - directory: The directory holding per-rig JSON files. Created if it does not exist.
|
||||
@@ -86,25 +96,60 @@ public final class RigLibraryStore {
|
||||
) {
|
||||
self.directory = directory
|
||||
self.isICloud = isICloud
|
||||
self.autoResolve = false
|
||||
try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
||||
}
|
||||
|
||||
/// Creates a store from a resolved ``RigLibraryLocation``.
|
||||
///
|
||||
/// - Parameter resolved: The directory + iCloud flag from `RigLibraryLocation.resolve()`.
|
||||
public convenience init(resolved: RigLibraryLocation.Resolved) {
|
||||
self.init(directory: resolved.directory, isICloud: resolved.isICloud)
|
||||
/// Creates an auto-resolving store. Constructed instantly with a local placeholder directory;
|
||||
/// ``start()`` resolves the real iCloud-or-local location off the main thread before loading.
|
||||
public init() {
|
||||
self.directory = RigLibraryLocation.localDirectory()
|
||||
self.isICloud = false
|
||||
self.autoResolve = true
|
||||
}
|
||||
|
||||
// MARK: - Lifecycle
|
||||
|
||||
/// Loads the current library contents and, when iCloud-backed, begins watching for remote
|
||||
/// changes. Safe to call once after construction.
|
||||
public func start() {
|
||||
reloadFromDirectory()
|
||||
/// Resolves the location (off the main thread, for an auto-resolving store), loads the current
|
||||
/// library contents (off the main thread), and — when iCloud-backed — begins watching for
|
||||
/// remote changes. Awaitable so callers can seed/highlight only once the real library state is
|
||||
/// known. Safe to call once after construction.
|
||||
public func start() async {
|
||||
if autoResolve {
|
||||
let resolved: RigLibraryLocation.Resolved = await RigLibraryStore.resolveOffMain()
|
||||
directory = resolved.directory
|
||||
isICloud = resolved.isICloud
|
||||
try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
||||
}
|
||||
if isICloud {
|
||||
startMetadataQuery()
|
||||
}
|
||||
await reload()
|
||||
isLoaded = true
|
||||
}
|
||||
|
||||
/// Re-reads the library directory off the main thread and republishes `entries`. Ordered after
|
||||
/// any queued background writes (shares `ioQueue`), so a save followed by a reload never drops
|
||||
/// the just-saved rig.
|
||||
public func reload() async {
|
||||
let dir: URL = directory
|
||||
let coordinated: Bool = isICloud
|
||||
let loaded: [RigEntry] = await withCheckedContinuation { continuation in
|
||||
ioQueue.async {
|
||||
continuation.resume(returning: RigLibraryStore.loadEntries(in: dir, coordinated: coordinated))
|
||||
}
|
||||
}
|
||||
entries = RigLibraryStore.sorted(loaded)
|
||||
}
|
||||
|
||||
/// Resolves the iCloud-or-local location on a background queue so the blocking ubiquity lookup
|
||||
/// never runs on the main thread.
|
||||
private static func resolveOffMain() async -> RigLibraryLocation.Resolved {
|
||||
await withCheckedContinuation { continuation in
|
||||
DispatchQueue.global(qos: .userInitiated).async {
|
||||
continuation.resume(returning: RigLibraryLocation.resolve())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Stops watching for remote changes and removes observers. Call when tearing the store down;
|
||||
@@ -239,7 +284,7 @@ public final class RigLibraryStore {
|
||||
/// - Throws: `JSONEncoder` errors.
|
||||
public func exportArchiveData() throws -> Data {
|
||||
let archive: RigArchive = RigArchive(rigs: entries)
|
||||
return try makeEncoder().encode(archive)
|
||||
return try RigLibraryStore.makeEncoder().encode(archive)
|
||||
}
|
||||
|
||||
/// Imports rigs from archive `data`, saving each into the library, and returns how many were
|
||||
@@ -281,17 +326,15 @@ public final class RigLibraryStore {
|
||||
/// Rescans the directory and rebuilds `entries`. Files that cannot be read or decoded are
|
||||
/// skipped so one bad file never blocks the rest. Not-yet-downloaded iCloud placeholders (which
|
||||
/// are hidden `*.icloud` files) are naturally ignored and picked up on a later metadata update.
|
||||
private func reloadFromDirectory() {
|
||||
private nonisolated static func loadEntries(in directory: URL, coordinated: Bool) -> [RigEntry] {
|
||||
var loaded: [RigEntry] = []
|
||||
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
|
||||
}
|
||||
for url: URL in rigFileURLs(in: directory) {
|
||||
guard let data: Data = try? readData(at: url, coordinated: coordinated) else { continue }
|
||||
guard let entry: RigEntry = try? decoder.decode(RigEntry.self, from: data) else { continue }
|
||||
loaded.append(entry)
|
||||
}
|
||||
entries = RigLibraryStore.sorted(loaded)
|
||||
return loaded
|
||||
}
|
||||
|
||||
// MARK: - iCloud metadata query
|
||||
@@ -341,7 +384,8 @@ public final class RigLibraryStore {
|
||||
try? fileManager.startDownloadingUbiquitousItem(at: url)
|
||||
}
|
||||
}
|
||||
reloadFromDirectory()
|
||||
// Re-read off the main thread; the in-memory list republishes when it completes.
|
||||
Task { await self.reload() }
|
||||
}
|
||||
|
||||
// MARK: - File helpers
|
||||
@@ -450,11 +494,11 @@ public final class RigLibraryStore {
|
||||
|
||||
/// Encodes a single entry as a per-rig file would store it.
|
||||
private func encode(_ entry: RigEntry) throws -> Data {
|
||||
try makeEncoder().encode(entry)
|
||||
try RigLibraryStore.makeEncoder().encode(entry)
|
||||
}
|
||||
|
||||
/// A JSON encoder configured for human-readable, round-trip-stable preset files.
|
||||
private func makeEncoder() -> JSONEncoder {
|
||||
private nonisolated static func makeEncoder() -> JSONEncoder {
|
||||
let encoder: JSONEncoder = JSONEncoder()
|
||||
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
|
||||
encoder.dateEncodingStrategy = .secondsSince1970
|
||||
@@ -462,7 +506,7 @@ public final class RigLibraryStore {
|
||||
}
|
||||
|
||||
/// A JSON decoder matching ``makeEncoder()``.
|
||||
private func makeDecoder() -> JSONDecoder {
|
||||
private nonisolated static func makeDecoder() -> JSONDecoder {
|
||||
let decoder: JSONDecoder = JSONDecoder()
|
||||
decoder.dateDecodingStrategy = .secondsSince1970
|
||||
return decoder
|
||||
@@ -474,7 +518,7 @@ public final class RigLibraryStore {
|
||||
_ data: Data,
|
||||
legacyRigName: String
|
||||
) throws -> [RigEntry] {
|
||||
let decoder: JSONDecoder = makeDecoder()
|
||||
let decoder: JSONDecoder = RigLibraryStore.makeDecoder()
|
||||
if let archive: RigArchive = try? decoder.decode(RigArchive.self, from: data) {
|
||||
return archive.rigs
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user