Add live backup status reconciliation with NAS manifest
BackupStatusService (new singleton, ObservableObject, PHPhotoLibraryChangeObserver):
- Loads cached BackupStatusSnapshot instantly from UserDefaults on init
- Full reconcile: fetch phone assets → connect NAS → load/build manifest → compare
→ enforce invariant (alreadySafe ≤ phoneTotal), persist result
- Debounced (30s) for photo library changes; force=true bypasses debounce
- If NAS unreachable: keeps last cached numbers, marks connectionState = .offline
- PHPhotoLibraryChangeObserver triggers refresh on any library change
BackupManifest (new):
- Stored at {remotePath}/.kisani.json on NAS
- Indexed by localIdentifier (PHAsset stable ID); filename fallback for legacy entries
- Built from directory listing if manifest missing (bootstrap for existing backups)
- merged/updated after each backup run via NASTransferProtocol.writeData
BackupStatusSnapshot (new):
- Single source of truth: phoneTotal, alreadySafe, needBackup (derived), nasArchiveTotal,
lastCheckedAt, connectionState
- Invariant enforced in service: alreadySafe = min(safe, phoneTotal)
Protocol / services:
- NASTransferProtocol: adds writeData(_ data: Data, to remotePath: String)
- SMBService: implements writeData via temp file + SMBClient.upload
- SFTPService: implements writeData via SFTP ByteBuffer write
BackupEngine:
- Tracks ManifestEntry per successful upload during backup loop
- After backup: calls BackupStatusService.refreshAfterBackup(entries:connection:)
which applies optimistic UI update then writes manifest + triggers reconcile
BackupView:
- Reads all stats from BackupStatusService.snapshot (not vm/nasFileCount)
- Stats labels: "NAS Archive" / "On iPhone" / "Need Backup" / "Already Safe"
- Live refresh triggers: .task (force), scenePhase.active (force),
nasReachable change (force), remotePath change (force), backup completed (+2s)
- Subtle status row below stats: "Checking…" spinner or "Updated X ago" with
wifi-slash icon when NAS offline; tap refresh button for forced reconcile
- AppMenuView sheet now correctly passes engine EnvironmentObject
BackupViewModel: stripped to auth-only (photosAuthStatus + requestPhotosAccess)
Co-Authored-By: Kutesir <kutesir@provoc.ug>
Co-Authored-By: Sentry <sentry@provoc.ug>
2026-05-17 12:51:03 +03:00
|
|
|
import Foundation
|
2026-05-17 13:06:44 +03:00
|
|
|
import Photos
|
|
|
|
|
|
|
|
|
|
// MARK: — ManifestIndex
|
|
|
|
|
// Lightweight comparison structure — two Sets for O(1) lookups.
|
|
|
|
|
// Built from BackupManifest and then the manifest is released.
|
perf: move heavy work off main actor, throttle progress updates, add signposts
BackupEngine:
- fetchAssets() runs in Task.detached — prevents 100-500ms UI freeze during
PHFetchResult enumeration on large libraries
- Manifest JSON decode + ManifestIndex Set construction run in Task.detached
- pendingAssets filter runs in Task.detached — O(N) array filter off main thread
- Progress updates throttled to 8 Hz via ProgressThrottle — eliminates the
continuous SwiftUI full-tree redraws caused by per-byte upload callbacks
- bytesSoFar captured by value in upload closure — avoids mutable var capture
- reserveCapacity on manifestEntries array
- os_signpost intervals on FetchAssets, NASConnect, ManifestLoad,
BuildPendingQueue, UploadLoop, UploadFile for Instruments profiling
BackupStatusService:
- countSafe() marked nonisolated — runs in Task.detached off main actor,
keeping touch/animation responsive during PHFetchResult batch enumeration
- ManifestIndex JSON decode + Set construction run in Task.detached
- Bootstrap ManifestIndex(nasListing:) construction off main actor
- writeManifest JSON decode/encode/merge off main actor
- os_signpost intervals on Reconcile, ManifestLoad, CountSafe
Model types:
- ManifestIndex, ManifestEntry, PhotoAsset, BackupFilter marked Sendable —
safe to pass across task boundaries without warnings
Co-Authored-By: Kutesir <kutesir@provoc.ug>
Co-Authored-By: Sentry <sentry@provoc.ug>
2026-05-17 16:42:48 +03:00
|
|
|
// Sendable: all stored properties are value types — safe to pass across task boundaries.
|
|
|
|
|
struct ManifestIndex: Sendable {
|
2026-05-17 13:06:44 +03:00
|
|
|
let localIdentifiers: Set<String> // PHAsset.localIdentifier (primary key)
|
|
|
|
|
let lowercasedFilenames: Set<String> // filename fallback for legacy/bootstrap entries
|
|
|
|
|
let totalCount: Int // non-hidden file count for NAS Archive stat
|
|
|
|
|
|
|
|
|
|
var isFilenameOnly: Bool { localIdentifiers.isEmpty }
|
|
|
|
|
|
|
|
|
|
func matches(localIdentifier id: String) -> Bool {
|
|
|
|
|
!id.isEmpty && localIdentifiers.contains(id)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func matches(filename: String) -> Bool {
|
|
|
|
|
lowercasedFilenames.contains(filename.lowercased())
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Build from decoded manifest — manifest released by caller after this returns
|
|
|
|
|
init(manifest: BackupManifest) {
|
|
|
|
|
var ids = Set<String>(minimumCapacity: manifest.entries.count)
|
|
|
|
|
var names = Set<String>(minimumCapacity: manifest.entries.count)
|
|
|
|
|
var count = 0
|
|
|
|
|
for entry in manifest.entries {
|
|
|
|
|
if !entry.filename.hasPrefix(".") { count += 1 }
|
|
|
|
|
if !entry.localIdentifier.isEmpty { ids.insert(entry.localIdentifier) }
|
|
|
|
|
names.insert(entry.filename.lowercased())
|
|
|
|
|
}
|
|
|
|
|
self.localIdentifiers = ids
|
|
|
|
|
self.lowercasedFilenames = names
|
|
|
|
|
self.totalCount = count
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Build from NAS directory listing (bootstrap — no localIdentifiers known)
|
|
|
|
|
init(nasListing items: [NASItem]) {
|
|
|
|
|
var names = Set<String>()
|
|
|
|
|
var count = 0
|
|
|
|
|
for item in items where !item.isDirectory && item.name != BackupManifest.remoteFilename {
|
|
|
|
|
if !item.name.hasPrefix(".") { count += 1 }
|
|
|
|
|
names.insert(item.name.lowercased())
|
|
|
|
|
}
|
|
|
|
|
self.localIdentifiers = []
|
|
|
|
|
self.lowercasedFilenames = names
|
|
|
|
|
self.totalCount = count
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// MARK: — ManifestEntry
|
Add live backup status reconciliation with NAS manifest
BackupStatusService (new singleton, ObservableObject, PHPhotoLibraryChangeObserver):
- Loads cached BackupStatusSnapshot instantly from UserDefaults on init
- Full reconcile: fetch phone assets → connect NAS → load/build manifest → compare
→ enforce invariant (alreadySafe ≤ phoneTotal), persist result
- Debounced (30s) for photo library changes; force=true bypasses debounce
- If NAS unreachable: keeps last cached numbers, marks connectionState = .offline
- PHPhotoLibraryChangeObserver triggers refresh on any library change
BackupManifest (new):
- Stored at {remotePath}/.kisani.json on NAS
- Indexed by localIdentifier (PHAsset stable ID); filename fallback for legacy entries
- Built from directory listing if manifest missing (bootstrap for existing backups)
- merged/updated after each backup run via NASTransferProtocol.writeData
BackupStatusSnapshot (new):
- Single source of truth: phoneTotal, alreadySafe, needBackup (derived), nasArchiveTotal,
lastCheckedAt, connectionState
- Invariant enforced in service: alreadySafe = min(safe, phoneTotal)
Protocol / services:
- NASTransferProtocol: adds writeData(_ data: Data, to remotePath: String)
- SMBService: implements writeData via temp file + SMBClient.upload
- SFTPService: implements writeData via SFTP ByteBuffer write
BackupEngine:
- Tracks ManifestEntry per successful upload during backup loop
- After backup: calls BackupStatusService.refreshAfterBackup(entries:connection:)
which applies optimistic UI update then writes manifest + triggers reconcile
BackupView:
- Reads all stats from BackupStatusService.snapshot (not vm/nasFileCount)
- Stats labels: "NAS Archive" / "On iPhone" / "Need Backup" / "Already Safe"
- Live refresh triggers: .task (force), scenePhase.active (force),
nasReachable change (force), remotePath change (force), backup completed (+2s)
- Subtle status row below stats: "Checking…" spinner or "Updated X ago" with
wifi-slash icon when NAS offline; tap refresh button for forced reconcile
- AppMenuView sheet now correctly passes engine EnvironmentObject
BackupViewModel: stripped to auth-only (photosAuthStatus + requestPhotosAccess)
Co-Authored-By: Kutesir <kutesir@provoc.ug>
Co-Authored-By: Sentry <sentry@provoc.ug>
2026-05-17 12:51:03 +03:00
|
|
|
|
perf: move heavy work off main actor, throttle progress updates, add signposts
BackupEngine:
- fetchAssets() runs in Task.detached — prevents 100-500ms UI freeze during
PHFetchResult enumeration on large libraries
- Manifest JSON decode + ManifestIndex Set construction run in Task.detached
- pendingAssets filter runs in Task.detached — O(N) array filter off main thread
- Progress updates throttled to 8 Hz via ProgressThrottle — eliminates the
continuous SwiftUI full-tree redraws caused by per-byte upload callbacks
- bytesSoFar captured by value in upload closure — avoids mutable var capture
- reserveCapacity on manifestEntries array
- os_signpost intervals on FetchAssets, NASConnect, ManifestLoad,
BuildPendingQueue, UploadLoop, UploadFile for Instruments profiling
BackupStatusService:
- countSafe() marked nonisolated — runs in Task.detached off main actor,
keeping touch/animation responsive during PHFetchResult batch enumeration
- ManifestIndex JSON decode + Set construction run in Task.detached
- Bootstrap ManifestIndex(nasListing:) construction off main actor
- writeManifest JSON decode/encode/merge off main actor
- os_signpost intervals on Reconcile, ManifestLoad, CountSafe
Model types:
- ManifestIndex, ManifestEntry, PhotoAsset, BackupFilter marked Sendable —
safe to pass across task boundaries without warnings
Co-Authored-By: Kutesir <kutesir@provoc.ug>
Co-Authored-By: Sentry <sentry@provoc.ug>
2026-05-17 16:42:48 +03:00
|
|
|
struct ManifestEntry: Codable, Sendable {
|
Add live backup status reconciliation with NAS manifest
BackupStatusService (new singleton, ObservableObject, PHPhotoLibraryChangeObserver):
- Loads cached BackupStatusSnapshot instantly from UserDefaults on init
- Full reconcile: fetch phone assets → connect NAS → load/build manifest → compare
→ enforce invariant (alreadySafe ≤ phoneTotal), persist result
- Debounced (30s) for photo library changes; force=true bypasses debounce
- If NAS unreachable: keeps last cached numbers, marks connectionState = .offline
- PHPhotoLibraryChangeObserver triggers refresh on any library change
BackupManifest (new):
- Stored at {remotePath}/.kisani.json on NAS
- Indexed by localIdentifier (PHAsset stable ID); filename fallback for legacy entries
- Built from directory listing if manifest missing (bootstrap for existing backups)
- merged/updated after each backup run via NASTransferProtocol.writeData
BackupStatusSnapshot (new):
- Single source of truth: phoneTotal, alreadySafe, needBackup (derived), nasArchiveTotal,
lastCheckedAt, connectionState
- Invariant enforced in service: alreadySafe = min(safe, phoneTotal)
Protocol / services:
- NASTransferProtocol: adds writeData(_ data: Data, to remotePath: String)
- SMBService: implements writeData via temp file + SMBClient.upload
- SFTPService: implements writeData via SFTP ByteBuffer write
BackupEngine:
- Tracks ManifestEntry per successful upload during backup loop
- After backup: calls BackupStatusService.refreshAfterBackup(entries:connection:)
which applies optimistic UI update then writes manifest + triggers reconcile
BackupView:
- Reads all stats from BackupStatusService.snapshot (not vm/nasFileCount)
- Stats labels: "NAS Archive" / "On iPhone" / "Need Backup" / "Already Safe"
- Live refresh triggers: .task (force), scenePhase.active (force),
nasReachable change (force), remotePath change (force), backup completed (+2s)
- Subtle status row below stats: "Checking…" spinner or "Updated X ago" with
wifi-slash icon when NAS offline; tap refresh button for forced reconcile
- AppMenuView sheet now correctly passes engine EnvironmentObject
BackupViewModel: stripped to auth-only (photosAuthStatus + requestPhotosAccess)
Co-Authored-By: Kutesir <kutesir@provoc.ug>
Co-Authored-By: Sentry <sentry@provoc.ug>
2026-05-17 12:51:03 +03:00
|
|
|
let localIdentifier: String // PHAsset.localIdentifier — primary key
|
|
|
|
|
let filename: String
|
|
|
|
|
let creationDate: Date?
|
|
|
|
|
let fileSize: Int64
|
|
|
|
|
let remotePath: String
|
|
|
|
|
let uploadedAt: Date
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
struct BackupManifest: Codable {
|
|
|
|
|
static let remoteFilename = ".kisani.json"
|
|
|
|
|
|
|
|
|
|
var version: Int = 1
|
|
|
|
|
var lastUpdated: Date = Date()
|
|
|
|
|
var entries: [ManifestEntry] = []
|
|
|
|
|
|
|
|
|
|
// Primary match: stable PHAsset localIdentifier
|
|
|
|
|
func contains(localIdentifier id: String) -> Bool {
|
|
|
|
|
guard !id.isEmpty else { return false }
|
|
|
|
|
return entries.contains { $0.localIdentifier == id }
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Fallback: case-insensitive filename (for assets backed up before manifest existed)
|
|
|
|
|
func containsByFilename(_ name: String) -> Bool {
|
|
|
|
|
let lower = name.lowercased()
|
|
|
|
|
return entries.contains { $0.filename.lowercased() == lower }
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Merge new entries, replacing any existing record for the same localIdentifier
|
|
|
|
|
mutating func merge(entries newEntries: [ManifestEntry]) {
|
|
|
|
|
let newIds = Set(newEntries.map { $0.localIdentifier }.filter { !$0.isEmpty })
|
|
|
|
|
entries.removeAll { !$0.localIdentifier.isEmpty && newIds.contains($0.localIdentifier) }
|
|
|
|
|
entries.append(contentsOf: newEntries)
|
|
|
|
|
lastUpdated = Date()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Bootstrap from a raw NAS directory listing (no localIdentifiers known)
|
|
|
|
|
static func buildFromNASListing(_ items: [NASItem]) -> BackupManifest {
|
|
|
|
|
var manifest = BackupManifest()
|
|
|
|
|
manifest.entries = items
|
|
|
|
|
.filter { !$0.isDirectory && $0.name != remoteFilename }
|
|
|
|
|
.map { item in
|
|
|
|
|
ManifestEntry(
|
|
|
|
|
localIdentifier: "",
|
|
|
|
|
filename: item.name,
|
|
|
|
|
creationDate: item.modifiedDate,
|
|
|
|
|
fileSize: item.size,
|
|
|
|
|
remotePath: item.path,
|
|
|
|
|
uploadedAt: item.modifiedDate ?? Date()
|
|
|
|
|
)
|
|
|
|
|
}
|
|
|
|
|
return manifest
|
|
|
|
|
}
|
|
|
|
|
}
|