Workouts 2.0: re-base persistence on iCloud Drive documents
Replace Core Data + NSPersistentCloudKitContainer + App-Group store + WatchConnectivity dictionary sync with the QuickRabbit iCloud-documents architecture: - iCloud Drive JSON documents are the sole source of truth (one file per aggregate: Splits/<ULID>.json, Workouts/YYYY/MM/<ULID>.json), with a rebuildable SwiftData cache populated only by an NSMetadataQuery observer and a connect-time reconcile. Soft-delete tombstones; hard iCloud gate. - Shared model layer (ULID, Codable *Documents + stateless mappers, @Model cache entities, SwiftData container) compiled into both targets. - New iPhone<->Watch bridge over WatchConnectivity keyed by ULIDs; the phone is the sole writer of iCloud Drive, the watch round-trips documents. - AppServices DI + iCloud-required root gate; Swift 6 strict concurrency. - Starter splits generated on demand from the bundled YAML catalogs. - Migrate to XcodeGen (project.yml), iOS 26 / watchOS 26; CloudDocuments entitlement (drop CloudKit/App Group/aps-environment). - Duration stored as Int seconds (was a Date epoch hack); fix workout end-on-create, undismissable delete dialog, toolbar-hiding nav stacks, and the Settings placeholder. - Add README/CHANGELOG/LICENSE, .gitignore, refreshed REQUIREMENTS, and the Scripts/ TestFlight pipeline (release.sh + ASC API scripts). MARKETING_VERSION 2.0.
This commit is contained in:
@@ -0,0 +1,118 @@
|
||||
import Foundation
|
||||
|
||||
/// All iCloud Drive file I/O, isolated to an actor so blocking `NSFileCoordinator`
|
||||
/// calls stay off the main thread. Paths are relative to the container's
|
||||
/// `Documents/` directory (e.g. `Splits/<ULID>.json`, `Stubs/<ULID>.json`).
|
||||
actor ICloudFileManager {
|
||||
let documentsURL: URL
|
||||
|
||||
init(containerURL: URL) {
|
||||
self.documentsURL = containerURL.appendingPathComponent("Documents", isDirectory: true)
|
||||
}
|
||||
|
||||
/// Create the directory skeleton. Actor-isolated (NOT in init) so the
|
||||
/// potentially-blocking file touch runs on the actor's executor, never main.
|
||||
func prepareDirectories() {
|
||||
for sub in ["Splits", "Workouts", "Stubs"] {
|
||||
let url = documentsURL.appendingPathComponent(sub, isDirectory: true)
|
||||
try? FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Coordinated primitives
|
||||
|
||||
func write(_ data: Data, to relativePath: String) throws {
|
||||
let fileURL = documentsURL.appendingPathComponent(relativePath)
|
||||
try FileManager.default.createDirectory(at: fileURL.deletingLastPathComponent(),
|
||||
withIntermediateDirectories: true)
|
||||
var coordError: NSError?
|
||||
var writeError: Error?
|
||||
NSFileCoordinator().coordinate(writingItemAt: fileURL, options: .forReplacing, error: &coordError) { url in
|
||||
do { try data.write(to: url, options: .atomic) }
|
||||
catch { writeError = error }
|
||||
}
|
||||
if let error = coordError ?? writeError { throw error }
|
||||
}
|
||||
|
||||
func read(relativePath: String) throws -> Data {
|
||||
let fileURL = documentsURL.appendingPathComponent(relativePath)
|
||||
var coordError: NSError?
|
||||
var result: Result<Data, Error>?
|
||||
NSFileCoordinator().coordinate(readingItemAt: fileURL, options: [], error: &coordError) { url in
|
||||
do { result = .success(try Data(contentsOf: url)) }
|
||||
catch { result = .failure(error) }
|
||||
}
|
||||
if let coordError { throw coordError }
|
||||
switch result {
|
||||
case .success(let data): return data
|
||||
case .failure(let error): throw error
|
||||
case .none: throw CocoaError(.fileReadUnknown)
|
||||
}
|
||||
}
|
||||
|
||||
func remove(relativePath: String) throws {
|
||||
let fileURL = documentsURL.appendingPathComponent(relativePath)
|
||||
guard FileManager.default.fileExists(atPath: fileURL.path) else { return }
|
||||
var coordError: NSError?
|
||||
var deleteError: Error?
|
||||
NSFileCoordinator().coordinate(writingItemAt: fileURL, options: .forDeleting, error: &coordError) { url in
|
||||
do { try FileManager.default.removeItem(at: url) }
|
||||
catch { deleteError = error }
|
||||
}
|
||||
if let error = coordError ?? deleteError { throw error }
|
||||
}
|
||||
|
||||
func fileExists(_ relativePath: String) -> Bool {
|
||||
FileManager.default.fileExists(atPath: documentsURL.appendingPathComponent(relativePath).path)
|
||||
}
|
||||
|
||||
// MARK: - Soft delete
|
||||
|
||||
/// Writes a tombstone stub then removes the live file. Other devices learn of
|
||||
/// the delete via the stub even if they were offline for the file removal.
|
||||
func writeTombstoneAndRemove(_ tombstone: Tombstone, livePath: String) throws {
|
||||
let data = try DocumentCoder.encoder.encode(tombstone)
|
||||
try write(data, to: tombstone.relativePath)
|
||||
try remove(relativePath: livePath)
|
||||
}
|
||||
|
||||
// MARK: - Enumeration
|
||||
|
||||
/// Relative paths of all live data files (`Splits/…`, `Workouts/…`), excluding `Stubs/`.
|
||||
func listDataFiles() -> [String] {
|
||||
listJSON().filter { !$0.hasPrefix("Stubs/") }
|
||||
}
|
||||
|
||||
/// All tombstones currently on disk.
|
||||
func listTombstones() -> [Tombstone] {
|
||||
listJSON().filter { $0.hasPrefix("Stubs/") }.compactMap { path in
|
||||
guard let data = try? read(relativePath: path) else { return nil }
|
||||
return try? DocumentCoder.decoder.decode(Tombstone.self, from: data)
|
||||
}
|
||||
}
|
||||
|
||||
private func listJSON() -> [String] {
|
||||
let base = documentsURL.path + "/"
|
||||
guard let enumerator = FileManager.default.enumerator(
|
||||
at: documentsURL,
|
||||
includingPropertiesForKeys: nil,
|
||||
options: [.skipsHiddenFiles]
|
||||
) else { return [] }
|
||||
var paths: [String] = []
|
||||
for case let url as URL in enumerator where url.pathExtension == "json" {
|
||||
let full = url.path
|
||||
if full.hasPrefix(base) { paths.append(String(full.dropFirst(base.count))) }
|
||||
}
|
||||
return paths
|
||||
}
|
||||
|
||||
// MARK: - Eviction
|
||||
|
||||
/// Triggers a download for an evicted file and polls until it materializes.
|
||||
func ensureDownloaded(relativePath: String) {
|
||||
let fileURL = documentsURL.appendingPathComponent(relativePath)
|
||||
guard let values = try? fileURL.resourceValues(forKeys: [.ubiquitousItemDownloadingStatusKey]),
|
||||
let status = values.ubiquitousItemDownloadingStatus, status != .current else { return }
|
||||
try? FileManager.default.startDownloadingUbiquitousItem(at: fileURL)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import Foundation
|
||||
|
||||
/// Wraps a single `NSMetadataQuery` over the container's `Documents/` scope and
|
||||
/// emits add/modify/remove events (paths relative to `Documents/`) via an
|
||||
/// `AsyncStream`. `@MainActor` because `NSMetadataQuery` posts on, and must be
|
||||
/// driven from, the main thread.
|
||||
@MainActor
|
||||
final class ICloudFileMonitor {
|
||||
enum FileChangeEvent: Sendable {
|
||||
case added(relativePath: String)
|
||||
case modified(relativePath: String)
|
||||
case removed(relativePath: String)
|
||||
}
|
||||
|
||||
private let documentsURL: URL
|
||||
private var query: NSMetadataQuery?
|
||||
private var knownFiles: Set<String> = []
|
||||
private var continuation: AsyncStream<FileChangeEvent>.Continuation?
|
||||
|
||||
init(documentsURL: URL) {
|
||||
self.documentsURL = documentsURL
|
||||
}
|
||||
|
||||
func events() -> AsyncStream<FileChangeEvent> {
|
||||
AsyncStream { continuation in
|
||||
self.continuation = continuation
|
||||
continuation.onTermination = { @Sendable _ in
|
||||
Task { @MainActor in self.stop() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func start() {
|
||||
let query = NSMetadataQuery()
|
||||
query.searchScopes = [NSMetadataQueryUbiquitousDocumentsScope]
|
||||
query.predicate = NSPredicate(format: "%K LIKE '*.json'", NSMetadataItemFSNameKey)
|
||||
self.query = query
|
||||
|
||||
NotificationCenter.default.addObserver(
|
||||
self, selector: #selector(queryDidFinishGathering(_:)),
|
||||
name: .NSMetadataQueryDidFinishGathering, object: query)
|
||||
NotificationCenter.default.addObserver(
|
||||
self, selector: #selector(queryDidUpdate(_:)),
|
||||
name: .NSMetadataQueryDidUpdate, object: query)
|
||||
|
||||
query.start()
|
||||
}
|
||||
|
||||
func stop() {
|
||||
query?.stop()
|
||||
if let query { NotificationCenter.default.removeObserver(self, name: nil, object: query) }
|
||||
query = nil
|
||||
}
|
||||
|
||||
// MARK: - Notifications
|
||||
|
||||
@objc private func queryDidFinishGathering(_ notification: Notification) {
|
||||
query?.disableUpdates()
|
||||
defer { query?.enableUpdates() }
|
||||
// Seed the baseline only; do NOT emit (else every existing file would fire
|
||||
// `.added` on each launch). The engine's connect-time `reconcile()` does the
|
||||
// initial import; this query then reports only live deltas after the baseline.
|
||||
knownFiles = Set(currentRelativePaths())
|
||||
}
|
||||
|
||||
@objc private func queryDidUpdate(_ notification: Notification) {
|
||||
query?.disableUpdates()
|
||||
defer { query?.enableUpdates() }
|
||||
|
||||
let currentFiles = Set(currentRelativePaths())
|
||||
|
||||
for file in currentFiles.subtracting(knownFiles) {
|
||||
continuation?.yield(.added(relativePath: file))
|
||||
}
|
||||
for file in knownFiles.subtracting(currentFiles) {
|
||||
continuation?.yield(.removed(relativePath: file))
|
||||
}
|
||||
if let updated = notification.userInfo?[NSMetadataQueryUpdateChangedItemsKey] as? [NSMetadataItem] {
|
||||
for item in updated {
|
||||
if let url = item.value(forAttribute: NSMetadataItemURLKey) as? URL,
|
||||
let path = relativePath(from: url), knownFiles.contains(path) {
|
||||
continuation?.yield(.modified(relativePath: path))
|
||||
}
|
||||
}
|
||||
}
|
||||
knownFiles = currentFiles
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
private func currentRelativePaths() -> [String] {
|
||||
guard let query else { return [] }
|
||||
var paths: [String] = []
|
||||
for i in 0..<query.resultCount {
|
||||
if let item = query.result(at: i) as? NSMetadataItem,
|
||||
let url = item.value(forAttribute: NSMetadataItemURLKey) as? URL,
|
||||
let path = relativePath(from: url) {
|
||||
paths.append(path)
|
||||
}
|
||||
}
|
||||
return paths
|
||||
}
|
||||
|
||||
private func relativePath(from url: URL) -> String? {
|
||||
let base = documentsURL.path + "/"
|
||||
let full = url.path
|
||||
guard full.hasPrefix(base) else { return nil }
|
||||
let relative = String(full.dropFirst(base.count))
|
||||
return relative.hasSuffix(".json") ? relative : nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
import Foundation
|
||||
import SwiftData
|
||||
import Observation
|
||||
|
||||
enum ICloudStatus: Equatable {
|
||||
case checking
|
||||
case available
|
||||
case unavailable
|
||||
}
|
||||
|
||||
/// Orchestrates the iCloud Drive file layer and the SwiftData cache. iCloud is
|
||||
/// the sole source of truth: every save/delete writes files only; the metadata
|
||||
/// observer (and the connect-time reconcile) is the sole mutator of the cache.
|
||||
@Observable
|
||||
@MainActor
|
||||
final class SyncEngine {
|
||||
nonisolated static let containerIdentifier = "iCloud.dev.rzen.indie.Workouts"
|
||||
|
||||
private(set) var iCloudStatus: ICloudStatus = .checking
|
||||
private(set) var isSyncing = false
|
||||
|
||||
/// Called after the cache changes (local or remote). The watch bridge uses
|
||||
/// this to push fresh state to the watch.
|
||||
var onCacheChanged: (() -> Void)?
|
||||
|
||||
private let modelContainer: ModelContainer
|
||||
private var fileManager: ICloudFileManager?
|
||||
private var monitor: ICloudFileMonitor?
|
||||
private var monitorTask: Task<Void, Never>?
|
||||
private var connectAttempt = 0
|
||||
|
||||
private var context: ModelContext { modelContainer.mainContext }
|
||||
|
||||
init(container: ModelContainer) {
|
||||
self.modelContainer = container
|
||||
}
|
||||
|
||||
// MARK: - Connection (deferred, time-boxed)
|
||||
|
||||
func connect() async {
|
||||
guard iCloudStatus != .available else { return }
|
||||
connectAttempt += 1
|
||||
let attempt = connectAttempt
|
||||
iCloudStatus = .checking
|
||||
|
||||
let url = await Task.detached {
|
||||
FileManager.default.url(forUbiquityContainerIdentifier: Self.containerIdentifier)
|
||||
}.value
|
||||
guard let containerURL = url else {
|
||||
if attempt == connectAttempt { iCloudStatus = .unavailable }
|
||||
return
|
||||
}
|
||||
|
||||
let fm = ICloudFileManager(containerURL: containerURL)
|
||||
|
||||
let timeout = Task { [weak self] in
|
||||
try? await Task.sleep(for: .seconds(20))
|
||||
guard let self, !Task.isCancelled else { return }
|
||||
if self.iCloudStatus == .checking, attempt == self.connectAttempt {
|
||||
self.iCloudStatus = .unavailable
|
||||
}
|
||||
}
|
||||
await fm.prepareDirectories()
|
||||
timeout.cancel()
|
||||
guard attempt == connectAttempt else { return }
|
||||
|
||||
self.fileManager = fm
|
||||
iCloudStatus = .available
|
||||
WorkoutsModelContainer.persistCurrentIdentityToken()
|
||||
|
||||
await reconcile()
|
||||
startMonitoring(documentsURL: fm.documentsURL)
|
||||
cleanupOldStubs()
|
||||
}
|
||||
|
||||
// MARK: - Monitoring
|
||||
|
||||
private func startMonitoring(documentsURL: URL) {
|
||||
monitorTask?.cancel()
|
||||
let monitor = ICloudFileMonitor(documentsURL: documentsURL)
|
||||
self.monitor = monitor
|
||||
monitor.start()
|
||||
monitorTask = Task { [weak self] in
|
||||
for await event in monitor.events() {
|
||||
await self?.handle(event)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func handle(_ event: ICloudFileMonitor.FileChangeEvent) async {
|
||||
switch event {
|
||||
case .added(let path), .modified(let path):
|
||||
if path.hasPrefix("Stubs/") {
|
||||
deleteCachedEntity(id: idFromStubPath(path))
|
||||
} else {
|
||||
await importFile(relativePath: path)
|
||||
}
|
||||
case .removed(let path):
|
||||
if !path.hasPrefix("Stubs/") {
|
||||
deleteCachedEntity(jsonRelativePath: path)
|
||||
}
|
||||
}
|
||||
try? context.save()
|
||||
onCacheChanged?()
|
||||
}
|
||||
|
||||
/// Apply a workout received from the watch through the normal write path
|
||||
/// (file → observer → cache), keeping iCloud Drive the single source of truth.
|
||||
func ingestFromWatch(_ doc: WorkoutDocument) async {
|
||||
await save(workout: doc)
|
||||
}
|
||||
|
||||
// MARK: - Public CRUD (write path: files only)
|
||||
|
||||
func save(split doc: SplitDocument) async {
|
||||
guard let fm = fileManager else { return }
|
||||
do { try await fm.write(try DocumentCoder.encoder.encode(doc), to: doc.relativePath) }
|
||||
catch { print("[Sync] write failed for \(doc.relativePath): \(error)") }
|
||||
// Cache updates reactively via the monitor.
|
||||
}
|
||||
|
||||
func save(workout doc: WorkoutDocument) async {
|
||||
guard let fm = fileManager else { return }
|
||||
do { try await fm.write(try DocumentCoder.encoder.encode(doc), to: doc.relativePath) }
|
||||
catch { print("[Sync] write failed for \(doc.relativePath): \(error)") }
|
||||
}
|
||||
|
||||
func delete(split: Split) async {
|
||||
await softDelete(id: split.id, kind: .split, livePath: split.jsonRelativePath)
|
||||
}
|
||||
|
||||
func delete(workout: Workout) async {
|
||||
await softDelete(id: workout.id, kind: .workout, livePath: workout.jsonRelativePath)
|
||||
}
|
||||
|
||||
private func softDelete(id: String, kind: Tombstone.Kind, livePath: String) async {
|
||||
guard let fm = fileManager else { return }
|
||||
let tombstone = Tombstone(id: id, kind: kind, deletedAt: Date())
|
||||
do {
|
||||
try await fm.writeTombstoneAndRemove(tombstone, livePath: livePath)
|
||||
} catch {
|
||||
print("[Sync] delete failed for \(id): \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Import / reconcile
|
||||
|
||||
private func importFile(relativePath: String) async {
|
||||
guard let fm = fileManager else { return }
|
||||
guard let data = try? await fm.read(relativePath: relativePath) else { return }
|
||||
|
||||
if relativePath.hasPrefix("Splits/") {
|
||||
guard let doc = try? DocumentCoder.decoder.decode(SplitDocument.self, from: data), doc.isReadable else { return }
|
||||
if await fm.fileExists("Stubs/\(doc.id).json") { try? await fm.remove(relativePath: relativePath); return }
|
||||
CacheMapper.upsertSplit(doc, relativePath: relativePath, into: context)
|
||||
} else if relativePath.hasPrefix("Workouts/") {
|
||||
guard let doc = try? DocumentCoder.decoder.decode(WorkoutDocument.self, from: data), doc.isReadable else { return }
|
||||
if await fm.fileExists("Stubs/\(doc.id).json") { try? await fm.remove(relativePath: relativePath); return }
|
||||
CacheMapper.upsertWorkout(doc, relativePath: relativePath, into: context)
|
||||
}
|
||||
}
|
||||
|
||||
/// Full sync against the current file set — imports new/changed files and
|
||||
/// prunes entities whose file is gone or tombstoned. Runs on connect so
|
||||
/// changes accumulated while the app was closed are picked up.
|
||||
private func reconcile() async {
|
||||
guard let fm = fileManager else { return }
|
||||
isSyncing = true
|
||||
defer { isSyncing = false }
|
||||
|
||||
let tombstoned = Set(await fm.listTombstones().map(\.id))
|
||||
let dataFiles = await fm.listDataFiles()
|
||||
|
||||
var liveSplitIDs = Set<String>()
|
||||
var liveWorkoutIDs = Set<String>()
|
||||
|
||||
for path in dataFiles {
|
||||
guard let data = try? await fm.read(relativePath: path) else { continue }
|
||||
if path.hasPrefix("Splits/") {
|
||||
guard let doc = try? DocumentCoder.decoder.decode(SplitDocument.self, from: data), doc.isReadable else { continue }
|
||||
if tombstoned.contains(doc.id) { try? await fm.remove(relativePath: path); continue }
|
||||
CacheMapper.upsertSplit(doc, relativePath: path, into: context)
|
||||
liveSplitIDs.insert(doc.id)
|
||||
} else if path.hasPrefix("Workouts/") {
|
||||
guard let doc = try? DocumentCoder.decoder.decode(WorkoutDocument.self, from: data), doc.isReadable else { continue }
|
||||
if tombstoned.contains(doc.id) { try? await fm.remove(relativePath: path); continue }
|
||||
CacheMapper.upsertWorkout(doc, relativePath: path, into: context)
|
||||
liveWorkoutIDs.insert(doc.id)
|
||||
}
|
||||
}
|
||||
|
||||
// Prune cache entities no longer backed by a live file.
|
||||
if let splits = try? context.fetch(FetchDescriptor<Split>()) {
|
||||
for s in splits where !liveSplitIDs.contains(s.id) { context.delete(s) }
|
||||
}
|
||||
if let workouts = try? context.fetch(FetchDescriptor<Workout>()) {
|
||||
for w in workouts where !liveWorkoutIDs.contains(w.id) { context.delete(w) }
|
||||
}
|
||||
try? context.save()
|
||||
onCacheChanged?()
|
||||
}
|
||||
|
||||
// MARK: - Cache deletes
|
||||
|
||||
private func deleteCachedEntity(id: String) {
|
||||
if let s = CacheMapper.fetchSplit(id: id, in: context) { context.delete(s) }
|
||||
if let w = CacheMapper.fetchWorkout(id: id, in: context) { context.delete(w) }
|
||||
}
|
||||
|
||||
private func deleteCachedEntity(jsonRelativePath path: String) {
|
||||
if let splits = try? context.fetch(FetchDescriptor<Split>(predicate: #Predicate { $0.jsonRelativePath == path })) {
|
||||
splits.forEach(context.delete)
|
||||
}
|
||||
if let workouts = try? context.fetch(FetchDescriptor<Workout>(predicate: #Predicate { $0.jsonRelativePath == path })) {
|
||||
workouts.forEach(context.delete)
|
||||
}
|
||||
}
|
||||
|
||||
private func idFromStubPath(_ path: String) -> String {
|
||||
(path as NSString).lastPathComponent.replacingOccurrences(of: ".json", with: "")
|
||||
}
|
||||
|
||||
// MARK: - Maintenance
|
||||
|
||||
private func cleanupOldStubs() {
|
||||
guard let fm = fileManager else { return }
|
||||
Task.detached(priority: .utility) {
|
||||
let cutoff = Date().addingTimeInterval(-Tombstone.gracePeriod)
|
||||
for tombstone in await fm.listTombstones() where tombstone.deletedAt < cutoff {
|
||||
try? await fm.remove(relativePath: tombstone.relativePath)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user