Seed starter splits deterministically with immutable clone-on-edit seeds
Starter splits ship as byte-canonical SplitDocument JSON with fixed ULIDs (Workouts/Resources/StarterSplits, regenerated by Scripts/generate_starter_splits.swift) and auto-seed after connect into a verifiably empty container, re-checked after a settle delay — wrong guesses are harmless because identical bytes make same-path conflicts empty and tombstones reap resurrected seeds. Seeds are immutable: SyncEngine.save(split:) forks an edited seed to a fresh ULID and soft-deletes the original, whose stub is exempt from pruning (IndieSync 0.3.0 prune(exempting:)) and vetoes resurrection forever; split views resolve by id through a redirect map to follow the swap. Add Starter Splits in Settings restores deleted seeds by lifting the veto stub and rewriting the bundle bytes. Also fixes ingestFromWatch bypassing the tombstone veto (a phone-deleted workout resurrected when a stale watch resent it) and reaps a live file immediately when its tombstone arrives. SplitDetailView also picks up the category-grouped exercise sections from the exercise-category work.
This commit is contained in:
@@ -25,6 +25,23 @@ final class SyncEngine {
|
||||
/// next successful write or full reconcile.
|
||||
private(set) var lastSyncError: String?
|
||||
|
||||
/// Maps a seed's id to its clone's id after a clone-on-edit fork, so a view still
|
||||
/// holding the seed's id resolves to the live clone. In-memory only (@Observable
|
||||
/// notifies on change); not persisted — a seed is edited at most once before it's
|
||||
/// gone, so nothing needs to survive a relaunch.
|
||||
private(set) var cloneRedirects: [String: String] = [:]
|
||||
|
||||
/// Follow the redirect chain from `id` to the current live split id. A seed
|
||||
/// redirects at most once, but the loop tolerates (and breaks) any chain or cycle.
|
||||
func currentSplitID(for id: String) -> String {
|
||||
var current = id
|
||||
var seen: Set<String> = [current]
|
||||
while let next = cloneRedirects[current], seen.insert(next).inserted {
|
||||
current = next
|
||||
}
|
||||
return current
|
||||
}
|
||||
|
||||
/// Called after the cache changes (local or remote). The watch bridge uses
|
||||
/// this to push fresh state to the watch.
|
||||
var onCacheChanged: (() -> Void)?
|
||||
@@ -136,6 +153,8 @@ final class SyncEngine {
|
||||
await reconcile()
|
||||
startMonitoring(documentsURL: store.rootURL)
|
||||
cleanupOldStubs()
|
||||
// Off the connect path so opening the gate isn't delayed by the settle wait.
|
||||
Task { await self.autoSeedIfEmpty() }
|
||||
}
|
||||
|
||||
/// Invoked from the connecting screen when the user chooses not to keep
|
||||
@@ -167,7 +186,12 @@ final class SyncEngine {
|
||||
switch event {
|
||||
case .added(let path), .modified(let path):
|
||||
if path.hasPrefix("Stubs/") {
|
||||
deleteCachedEntity(id: idFromStubPath(path))
|
||||
let id = idFromStubPath(path)
|
||||
deleteCachedEntity(id: id)
|
||||
// A stub can arrive before (or instead of) the deleting device's
|
||||
// live-file removal; drop any live file for this id so the delete
|
||||
// takes effect and reconcile can't re-import it.
|
||||
await removeLiveFile(forID: id)
|
||||
} else {
|
||||
await importFile(relativePath: path)
|
||||
}
|
||||
@@ -191,6 +215,14 @@ final class SyncEngine {
|
||||
/// observer re-applies idempotently if it does fire) and lets open phone screens
|
||||
/// reflect watch progress live.
|
||||
func ingestFromWatch(_ doc: WorkoutDocument) async {
|
||||
// A workout deleted on the phone leaves a tombstone; a watch that missed the
|
||||
// delete may still push its stale copy. Honor the veto — never resurrect it —
|
||||
// and re-push authoritative state (via onCacheChanged → pushAll) so the watch
|
||||
// replaces its stale set and drops the deleted workout.
|
||||
if let tombstones, await tombstones.stubExists(id: doc.id) {
|
||||
onCacheChanged?()
|
||||
return
|
||||
}
|
||||
await save(workout: doc)
|
||||
CacheMapper.upsertWorkout(doc, relativePath: doc.relativePath, into: context)
|
||||
do { try context.save() } catch { report("Cache save failed", error) }
|
||||
@@ -199,8 +231,22 @@ final class SyncEngine {
|
||||
|
||||
// MARK: - Public CRUD (write path: files only)
|
||||
|
||||
func save(split doc: SplitDocument) async {
|
||||
guard let store else { return }
|
||||
/// Returns the *effective* id of the split that was written — normally `doc.id`,
|
||||
/// but the clone's fresh id when an edited seed forks. Open views follow the swap
|
||||
/// via `currentSplitID(for:)`.
|
||||
@discardableResult
|
||||
func save(split doc: SplitDocument) async -> String {
|
||||
guard let store else { return doc.id }
|
||||
|
||||
// Seeds are immutable: a real edit forks the seed into a user-owned split and
|
||||
// soft-deletes the original, keeping the curated seed intact and restorable. A
|
||||
// pristine (no-op) save must NOT fork — the edit sheets stamp `updatedAt`
|
||||
// unconditionally, so merely opening and saving a seed's editor without a change
|
||||
// would otherwise clone it.
|
||||
if SeedLibrary.isSeed(id: doc.id), !SeedLibrary.isPristine(doc) {
|
||||
return await cloneSeedOnEdit(doc)
|
||||
}
|
||||
|
||||
do {
|
||||
try await store.write(doc, to: doc.relativePath)
|
||||
lastSyncError = nil
|
||||
@@ -208,6 +254,37 @@ final class SyncEngine {
|
||||
report("Failed to save split", error)
|
||||
}
|
||||
// Cache updates reactively via the monitor.
|
||||
return doc.id
|
||||
}
|
||||
|
||||
/// Fork an edited seed into a user-owned split. Writes the clone under a fresh
|
||||
/// ULID and upserts it into the cache immediately (same rationale as
|
||||
/// `ingestFromWatch`: a same-process write doesn't reliably wake the metadata
|
||||
/// observer, and open screens must see the clone the moment `save` returns), then
|
||||
/// soft-deletes the seed and drops its cache entity. Records the id redirect so a
|
||||
/// view still holding the seed's id follows the identity swap.
|
||||
private func cloneSeedOnEdit(_ doc: SplitDocument) async -> String {
|
||||
guard let store else { return doc.id }
|
||||
var clone = doc
|
||||
clone.id = ULID.make()
|
||||
clone.createdAt = Date()
|
||||
// Exercise ids are kept as-is — they only need uniqueness within the document.
|
||||
do {
|
||||
try await store.write(clone, to: clone.relativePath)
|
||||
CacheMapper.upsertSplit(clone, relativePath: clone.relativePath, into: context)
|
||||
// Soft-delete the seed (writes its veto stub, then removes the live file),
|
||||
// then evict its now-orphaned cache entity.
|
||||
await softDelete(id: doc.id, kind: "split", livePath: doc.relativePath)
|
||||
deleteCachedEntity(id: doc.id)
|
||||
try context.save()
|
||||
cloneRedirects[doc.id] = clone.id
|
||||
lastSyncError = nil
|
||||
onCacheChanged?()
|
||||
return clone.id
|
||||
} catch {
|
||||
report("Failed to fork edited starter split", error)
|
||||
return doc.id
|
||||
}
|
||||
}
|
||||
|
||||
func save(workout doc: WorkoutDocument) async {
|
||||
@@ -361,17 +438,113 @@ final class SyncEngine {
|
||||
(path as NSString).lastPathComponent.replacingOccurrences(of: ".json", with: "")
|
||||
}
|
||||
|
||||
/// Remove any live data file for `id` when its tombstone arrives. Matches by
|
||||
/// filename identity across every non-`Stubs/` path — deliberately NOT
|
||||
/// `resolveExistingPath(forID:)`, which would also match the stub itself.
|
||||
private func removeLiveFile(forID id: String) async {
|
||||
guard let store else { return }
|
||||
let target = "\(id).json"
|
||||
let livePaths = await store.list().filter {
|
||||
!$0.hasPrefix("Stubs/") && ($0 as NSString).lastPathComponent == target
|
||||
}
|
||||
for path in livePaths {
|
||||
try? await store.remove(at: path)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Maintenance
|
||||
|
||||
private func cleanupOldStubs() {
|
||||
guard let tombstones else { return }
|
||||
let exempt = SeedLibrary.seedIDs
|
||||
Task.detached(priority: .utility) {
|
||||
// Downloads evicted stubs to read their deletedAt, prunes past the
|
||||
// 30-day grace period.
|
||||
try? await tombstones.prune()
|
||||
// 30-day grace period. Seed tombstones veto resurrection permanently, so
|
||||
// they're exempt and never pruned.
|
||||
try? await tombstones.prune(exempting: exempt)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Seeding
|
||||
|
||||
/// True when the container holds no documents at all — not one data file and not
|
||||
/// one tombstone. A user with only workouts, or any tombstone (i.e. a prior
|
||||
/// delete), is not a new user, so we never auto-seed over them. Placeholder-aware
|
||||
/// by construction (`store.list()` sees evicted files too).
|
||||
private func containerEmpty() async -> Bool {
|
||||
guard let store else { return false }
|
||||
return await store.list().isEmpty
|
||||
}
|
||||
|
||||
/// Write the starter library exactly once, only into a verifiably empty container
|
||||
/// (the true first run). Deferred and re-checked after a settle delay: an empty
|
||||
/// listing right after connect can just mean the metadata index hasn't populated
|
||||
/// yet, and seeding into that illusion would duplicate a library that's about to
|
||||
/// arrive.
|
||||
private func autoSeedIfEmpty() async {
|
||||
guard let store, await containerEmpty() else { return }
|
||||
// Give the metadata index a chance to surface existing files before we conclude
|
||||
// the account is genuinely new.
|
||||
try? await Task.sleep(for: .seconds(5))
|
||||
guard iCloudStatus == .available, await containerEmpty() else { return }
|
||||
|
||||
for seed in SeedLibrary.seeds {
|
||||
do {
|
||||
// Verbatim bundle bytes: byte-identical files across devices make a
|
||||
// same-path conflict (two devices seeding at once) semantically empty.
|
||||
try await store.writeData(seed.data, to: seed.doc.relativePath)
|
||||
CacheMapper.upsertSplit(seed.doc, relativePath: seed.doc.relativePath, into: context)
|
||||
} catch {
|
||||
report("Failed to seed \(seed.doc.name)", error)
|
||||
}
|
||||
}
|
||||
do { try context.save() } catch { report("Cache save failed", error) }
|
||||
onCacheChanged?()
|
||||
}
|
||||
|
||||
/// Add one seed fresh: write its verbatim bundle bytes and upsert the cache. The
|
||||
/// on-demand "Add Starter Splits" path uses this for a seed that's neither present
|
||||
/// nor tombstoned.
|
||||
func writeSeed(_ seed: SeedLibrary.Seed) async {
|
||||
guard let store else { return }
|
||||
do {
|
||||
try await store.writeData(seed.data, to: seed.doc.relativePath)
|
||||
CacheMapper.upsertSplit(seed.doc, relativePath: seed.doc.relativePath, into: context)
|
||||
try context.save()
|
||||
lastSyncError = nil
|
||||
} catch {
|
||||
report("Failed to add starter split \(seed.doc.name)", error)
|
||||
}
|
||||
onCacheChanged?()
|
||||
}
|
||||
|
||||
/// Bring a previously-deleted seed back: lift its veto stub, then write its
|
||||
/// verbatim bundle bytes. The bundle is the canonical restore source (seed content
|
||||
/// is immutable), so this restores from the bundle rather than reconstructing from
|
||||
/// the stub — the seed's stub is only ever a minimal veto marker. The stub is
|
||||
/// removed first so neither a racing observer event nor a reconcile re-vetoes the
|
||||
/// file we're about to write while the stub still exists.
|
||||
func restoreSeed(_ seed: SeedLibrary.Seed) async {
|
||||
guard let store, let tombstones else { return }
|
||||
do {
|
||||
try await tombstones.removeStub(at: "\(seed.id).json")
|
||||
try await store.writeData(seed.data, to: seed.doc.relativePath)
|
||||
CacheMapper.upsertSplit(seed.doc, relativePath: seed.doc.relativePath, into: context)
|
||||
try context.save()
|
||||
lastSyncError = nil
|
||||
} catch {
|
||||
report("Failed to restore starter split \(seed.doc.name)", error)
|
||||
}
|
||||
onCacheChanged?()
|
||||
}
|
||||
|
||||
/// Whether a tombstone exists for `id` (placeholder-aware). The on-demand seed
|
||||
/// path checks this to restore rather than re-create a deleted seed.
|
||||
func isTombstoned(id: String) async -> Bool {
|
||||
guard let tombstones else { return false }
|
||||
return await tombstones.stubExists(id: id)
|
||||
}
|
||||
|
||||
// MARK: - Error Reporting
|
||||
|
||||
/// Record a non-fatal sync failure: log it and publish it as `lastSyncError`
|
||||
|
||||
Reference in New Issue
Block a user