SPB Git

Repository Public

VQSyncedCollection.swift 4.5 KB 119 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/VQuantKit/Sync/VQSyncedCollection.swift3// Description: Observable stores for SwiftUI on top of the sync engine: one collection per kind, and the sync status.4import Foundation5import Observation67/// The objects of one kind, kept current from a `VQSyncEngine`. Reads are synchronous (SwiftUI friendly); writes go8/// to the engine's durable queue and show up at once.9///10/// ```swift11/// @State private var watchlists = VQSyncedCollection<VQWatchlist>(engine: engine)12/// List(watchlists.items) { w in Text(w.data.name) }.task { await watchlists.observe() }13/// ```14@MainActor15@Observable16public final class VQSyncedCollection<T: VQSyncData> {17    /// Live objects, newest first (pending local writes included).18    public private(set) var items: [VQObject<T>] = []19    /// Ids with a write the server has not accepted yet (show a "pending" mark).20    public private(set) var pendingIDs: Set<String> = []21    /// The last error of a write refused before queuing (bad id, too large).22    public private(set) var lastError: VQError?23    public private(set) var isLoaded = false2425    @ObservationIgnored private let engine: VQSyncEngine2627    public init(engine: VQSyncEngine) { self.engine = engine }2829    public subscript(id: String) -> VQObject<T>? { items.first { $0.id == id } }3031    /// Reads the current state once.32    public func refresh() async {33        let list = await engine.objects(of: T.self)34        let pending = await engine.pendingIDs(T.kind)35        if list != items { items = list }36        if pending != pendingIDs { pendingIDs = pending }37        isLoaded = true38    }3940    /// Follows the engine until the surrounding task is cancelled — call it from `.task { }`.41    public func observe() async {42        let events = await engine.events()43        await refresh()44        for await event in events {45            switch event {46            case .objectsChanged(let kinds): if kinds.contains(T.kind) { await refresh() }47            case .statusChanged: let pending = await engine.pendingIDs(T.kind); if pending != pendingIDs { pendingIDs = pending }48            case .conflict(let record): if record.key.kind == T.kind { await refresh() }49            }50        }51    }5253    /// Creates an object with a new id and returns the id.54    @discardableResult55    public func create(_ data: T, id: String = VQObjectID.make()) async -> String {56        await save(data, id: id)57        return id58    }5960    /// Saves (creates or updates) the object.61    public func save(_ data: T, id: String) async {62        do { _ = try await engine.put(data, id: id); lastError = nil }63        catch let e as VQError { lastError = e }64        catch { lastError = VQError(.rejected, message: String(describing: error)) }65        await refresh()66    }6768    /// Reads the object, lets `change` edit it, saves it. Does nothing when the id is unknown.69    public func update(_ id: String, _ change: (inout T) -> Void) async {70        guard var data = self[id]?.data else { return }71        change(&data)72        await save(data, id: id)73    }7475    public func delete(_ id: String) async {76        do { try await engine.delete(T.kind, id); lastError = nil }77        catch let e as VQError { lastError = e }78        catch { lastError = VQError(.rejected, message: String(describing: error)) }79        await refresh()80    }81}8283/// The sync status and the conflict list, observable (status dot, "3 writes pending", conflict sheet).84@MainActor85@Observable86public final class VQSyncStatusStore {87    public private(set) var status = VQSyncStatus()88    public private(set) var conflicts: [VQConflictRecord] = []8990    @ObservationIgnored private let engine: VQSyncEngine91    public init(engine: VQSyncEngine) { self.engine = engine }9293    public func observe() async {94        let events = await engine.events()95        status = await engine.status96        conflicts = await engine.conflicts97        for await event in events {98            switch event {99            case .statusChanged(let s):100                status = s101                let list = await engine.conflicts102                if list != conflicts { conflicts = list }103            case .conflict: conflicts = await engine.conflicts104            case .objectsChanged: break105            }106        }107    }108109    public func dismiss(_ id: String) async {110        await engine.dismissConflict(id)111        conflicts = await engine.conflicts112    }113114    public func keepRemote(_ id: String) async {115        try? await engine.restoreRemoteVersion(ofConflict: id)116        conflicts = await engine.conflicts117    }118}119
Files main
Menu

Theme