SPB Git

Repository Public

MirrorSync.swift 2.2 KB 50 lines swift

1// SP Drive iOS2// File: Sync/MirrorSync.swift3// Description: Incremental pull of the server's change feed into a store. Shared by the app's sync engine and the File Provider extension.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation89public struct PullResult: Sendable {10    /// Items as they were before / as they are now, in feed order.11    public var changed: [(old: DriveItem?, new: DriveItem)] = []12    public var deleted: [DriveItem] = []13    public var isEmpty: Bool { changed.isEmpty && deleted.isEmpty }14}1516public enum MirrorSync {17    /// Applies every change after the store's cursor. Items created on this device and not yet confirmed (`local-…`) are left alone.18    /// The cursor only moves after a page is stored, so an interruption repeats a page instead of skipping one.19    public static func pull(store: DriveStore, remote: DriveRemote, pageSize: Int = 1000) async throws -> PullResult {20        var result = PullResult()21        if store.rootID == nil { store.setMeta("root", try await remote.rootID()) }22        while true {23            try Task.checkCancellation()24            let since = store.cursor25            let page = try await remote.changes(since: since, limit: pageSize)26            if page.cursor < 0 {27                // the server's history is behind this device's cursor (restore from backup): compare everything again28                Log.sync.notice("server history restarted, pulling from the beginning")29                store.setCursor(0)30                continue31            }32            try store.db.transaction {33                for item in page.items {34                    let old = store.item(item.id)35                    try store.upsert(item)36                    if item.parentID == nil, item.isFolder { store.setMeta("root", item.id) }37                    result.changed.append((old, item))38                }39                for id in page.deleted {40                    store.addTombstone(id, rev: page.cursor)41                    if let old = store.item(id) { try store.deleteItem(id); result.deleted.append(old) }42                }43                store.setCursor(page.cursor)44            }45            if !page.more { break }46        }47        return result48    }49}50
Files main
Menu

Theme