Fix backup progress state machine: pending queue, resolvedStatus, failure resolution

- BackupEngine: pre-filter assets against ManifestIndex before job.start() so
  totalFiles reflects only pending items (not full gallery). Short-circuit with
  allAlreadySafe() when queue is empty.
- BackupJob: add resolveSuccess() (upgrades stale .failed → .completed after
  reconciliation proves needBackup==0) and allAlreadySafe() for empty-queue case.
- BackupStatusService: expose refreshAndWait(force:) async for pull-to-refresh
  and post-failure reconciliation.
- BackupView: wire resolvedStatus throughout ringContentID, ringMainView,
  ringColor, and actionButton; fix progress label to show pending-queue
  denominator; handle .failed in onChange by reconciling and auto-resolving
  to .completed when counts confirm all photos are safe.

Co-Authored-By: Kutesir <kutesir@provoc.ug>
Co-Authored-By: Sentry <sentry@provoc.ug>
This commit is contained in:
Robin Kutesa
2026-05-17 15:58:54 +03:00
parent 819f2b949e
commit f40cf9ee37
5 changed files with 146 additions and 99 deletions

View File

@@ -73,7 +73,7 @@ final class BackupEngine: ObservableObject {
activeTransfer = nil
}
// 3. Load manifest build index (manifest Data+struct released after this block)
// 3. Load manifest build index (Data+struct released immediately after)
let manifestPath = "\(connection.remotePath)/\(BackupManifest.remoteFilename)"
let index: ManifestIndex
if let data = try? await transfer.downloadData(at: manifestPath),
@@ -85,8 +85,23 @@ final class BackupEngine: ObservableObject {
logger.info("No manifest — will check NAS file existence per asset")
}
// 4. Start job tracking
job.start(totalFiles: assets.count, totalBytes: 0)
// 4. Build PENDING QUEUE items not already confirmed in manifest.
// This is the denominator for progress; NOT the full gallery count.
let pendingAssets = assets.filter { asset in
!index.matches(localIdentifier: asset.localIdentifier) &&
!(index.isFilenameOnly && index.matches(filename: asset.filename))
}
logger.info("Pending queue: \(pendingAssets.count) of \(assets.count) total assets")
// If nothing is pending, finish immediately all already safe.
guard !pendingAssets.isEmpty else {
job.allAlreadySafe()
BackupStatusService.shared.refresh(force: false)
return BackupResult.empty(date: startDate)
}
// 5. Start job with PENDING count never the full gallery total.
job.start(totalFiles: pendingAssets.count, totalBytes: 0)
var uploaded = 0
var skipped = 0
@@ -95,40 +110,24 @@ final class BackupEngine: ObservableObject {
var speedTracker = SpeedTracker()
var manifestEntries: [ManifestEntry] = []
// 5. Transfer loop
for asset in assets {
// 6. Transfer loop manifest check already done above, only NAS-exists + upload here.
for asset in pendingAssets {
if isCancelled { break }
while case .paused = job.status {
try await Task.sleep(nanoseconds: 500_000_000)
}
// Primary dedup: manifest localIdentifier (O(1), no network call)
if index.matches(localIdentifier: asset.localIdentifier) {
job.fileCompleted(skipped: true)
skipped += 1
logger.debug("Skipped (manifest id): \(asset.filename, privacy: .public)")
continue
}
// Filename fallback: bootstrap manifest has no localIdentifiers
if index.isFilenameOnly && index.matches(filename: asset.filename) {
job.fileCompleted(skipped: true)
skipped += 1
logger.debug("Skipped (manifest filename): \(asset.filename, privacy: .public)")
continue
}
// NAS file existence check never overwrite
let baseRemotePath = "\(connection.remotePath)/\(asset.filename)"
let fileAlreadyExists = (try? await transfer.fileExists(at: baseRemotePath)) == true
if fileAlreadyExists {
// NAS file existence check skip without overwriting legacy files
if (try? await transfer.fileExists(at: baseRemotePath)) == true {
job.fileCompleted(skipped: true)
skipped += 1
logger.debug("Skipped (NAS exists, no-overwrite): \(asset.filename, privacy: .public)")
continue
}
// Upload
// Upload
do {
let localURL = try await photoService.exportAsset(asset)
defer { try? FileManager.default.removeItem(at: localURL) }
@@ -211,6 +210,9 @@ final class BackupEngine: ObservableObject {
func pause() { job.pause() }
func resume() { job.resume() }
/// Upgrades a stale .failed state to .completed when reconciliation proves needBackup == 0.
func resolveSuccess() { job.resolveSuccess() }
private func sendCompletionNotification(result: BackupResult) async {
let content = UNMutableNotificationContent()
content.title = result.hasErrors ? "Backup completed with errors" : "Backup complete"

View File

@@ -60,6 +60,12 @@ final class BackupStatusService: NSObject, ObservableObject {
}
}
/// Awaitable reconciliation used by pull-to-refresh and post-failure resolution.
func refreshAndWait(force: Bool = true) async {
cancelAll()
await performRefresh(force: force)
}
/// Called by BackupEngine after a completed run with newly uploaded entries.
/// Applies an optimistic count update, writes the manifest in background, then reconciles.
func refreshAfterBackup(entries: [ManifestEntry], connection: NASConnection) {