Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sync/ChangeDetector.swift3// Description: Detects what changed on the server since the last cursor — incrementally, page by page — applies it to the local mirror and says what kind of change each item went through.4import Foundation5import SPDriveCore67public enum ChangeKind: String, Sendable, Equatable { case created, contentChanged, renamed, moved, trashed, restored, deleted, metadata }8public struct DetectedChange: Sendable, Equatable {9 public var id: String; public var name: String; public var isFolder: Bool; public var kind: ChangeKind10}1112public struct ChangeDetector: Sendable {13 public let api: APIClient14 public let store: MetadataStore15 public init(api: APIClient, store: MetadataStore) { self.api = api; self.store = store }1617 /// Compares what the mirror knew with what the server now says.18 public static func classify(old: DriveItem?, new: DriveItem) -> ChangeKind {19 guard let old else { return .created }20 if old.trashedAt == nil, new.trashedAt != nil { return .trashed }21 if old.trashedAt != nil, new.trashedAt == nil { return .restored }22 if !new.isFolder, old.versionID != new.versionID || old.sha256 != new.sha256 { return .contentChanged }23 if old.parentID != new.parentID { return .moved }24 if old.name != new.name { return .renamed }25 return .metadata26 }27 /// True when the server has revisions the mirror has not seen (one small request).28 public func hasRemoteChanges() async throws -> Bool { try await api.syncCursor().head != store.cursor }2930 /// Pulls every change after the stored cursor. The cursor only moves together with the rows it accounts for, so an31 /// interruption at any point resumes without loss or repetition.32 @discardableResult public func pull(pageSize: Int = 1000, maxPages: Int = .max) async throws -> [DetectedChange] {33 var out: [DetectedChange] = [], pages = 034 while pages < maxPages {35 try Task.checkCancellation()36 let since = store.cursor37 let page = try await api.changes(since: since, limit: pageSize)38 if since > page.head {39 // the server knows less than this mirror (restored from a backup): rebuild from nothing40 try store.resetMirror(); pages += 1; continue41 }42 for item in page.items {43 // items the mirror already holds at this revision were written by this device a moment ago: not a remote change44 let old = try store.item(item.id)45 if let old, old.rev >= item.rev { continue }46 out.append(DetectedChange(id: item.id, name: item.name, isFolder: item.isFolder, kind: ChangeDetector.classify(old: old, new: item)))47 }48 for d in page.deleted { if let old = try store.item(d.id) { out.append(DetectedChange(id: d.id, name: old.name, isFolder: old.isFolder, kind: .deleted)) } }49 try store.apply(page)50 pages += 151 if !page.more { break }52 }53 return out54 }55}56