Files
workouts/Workouts/Sync/ICloudFileMonitor.swift
rzen 85d0eaddbb 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.
2026-06-19 14:25:27 -04:00

112 lines
4.0 KiB
Swift

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
}
}