SPB Git

Repository Public

VQSyncTypes.swift 7.2 KB 140 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/VQuantKit/Sync/VQSyncTypes.swift3// Description: Value types of the sync engine: pending writes, conflict records, status, events.4import Foundation56/// A write made on this device that the server has not accepted yet.7public struct VQPendingWrite: Sendable, Hashable, VQJSONDecodable {8    public enum Action: Sendable, Hashable {9        case put(VQJSON)10        case delete11    }12    /// Position in this device's write order.13    public var opId: Int14    public var key: VQObjectKey15    public var action: Action16    /// The object as this device saw it when it made the edit (nil: it did not exist). The merge base.17    public var base: VQJSON?18    public var createdAt: Date1920    public init(opId: Int, key: VQObjectKey, action: Action, base: VQJSON?, createdAt: Date) {21        self.opId = opId; self.key = key; self.action = action; self.base = base; self.createdAt = createdAt22    }23    public init(json j: VQJSON) {24        opId = j.int("opId") ?? 025        key = VQObjectKey(kind: VQObjectKind(j.str("kind")), id: j.str("id"))26        action = j.str("action") == "delete" ? .delete : .put(j["data"] ?? .object([:]))27        base = j["base"].flatMap { $0.isNull ? nil : $0 }28        createdAt = j.date("createdAt") ?? Date(timeIntervalSince1970: 0)29    }30    public var json: VQJSON {31        var o: VQJSONObject = ["opId": .number(Double(opId)), "kind": .string(key.kind.rawValue), "id": .string(key.id),32                               "createdAt": .number((createdAt.timeIntervalSince1970 * 1000).rounded())]33        switch action {34        case .put(let d): o["action"] = "put"; o["data"] = d35        case .delete: o["action"] = "delete"36        }37        if let base { o["base"] = base }38        return .object(o)39    }40}4142/// What happened when a write of this device met a different state on the server. The UI can list these, show both43/// versions, and offer to restore the other one (`VQSyncEngine.restoreRemoteVersion(ofConflict:)`).44public struct VQConflictRecord: Sendable, Hashable, Identifiable, VQJSONDecodable {45    public enum Resolution: String, Sendable, Hashable {46        /// Element lists were merged (union, local edit wins per element); nothing of the other side was lost.47        case mergedElements = "merged_elements"48        /// Last writer wins: this device's version was written over a different server version.49        case localWon = "local_won"50        /// This device deleted an object that had changed on the server; the deletion was applied.51        case localDeleteWon = "local_delete_won"52        /// The object had been deleted on the server; this device's edit re-created it.53        case recreated54        /// The server refused the write (validation, size, server-only kind); the local edit was dropped.55        case rejected56    }57    public var id: String58    public var key: VQObjectKey59    public var at: Date60    public var resolution: Resolution61    /// True when content of the other side was discarded or the write was refused: show it to the person.62    /// (`mergedElements` alone is informational.)63    public var needsAttention: Bool64    /// What this device wanted to write (nil for a deletion).65    public var local: VQJSON?66    /// What the server held (nil when it held a tombstone).67    public var remote: VQJSON?68    /// What was written in the end (nil for a deletion or a refusal).69    public var result: VQJSON?70    public var remoteRev: Int71    public var remoteDevice: String72    /// Top-level keys where the server's change was overwritten.73    public var differingKeys: [String]74    /// Element lists that were merged.75    public var mergedLists: [String]76    /// The server's sentence for `rejected`.77    public var message: String?7879    public init(id: String, key: VQObjectKey, at: Date, resolution: Resolution, needsAttention: Bool, local: VQJSON?, remote: VQJSON?, result: VQJSON?,80                remoteRev: Int, remoteDevice: String, differingKeys: [String] = [], mergedLists: [String] = [], message: String? = nil) {81        self.id = id; self.key = key; self.at = at; self.resolution = resolution; self.needsAttention = needsAttention82        self.local = local; self.remote = remote; self.result = result; self.remoteRev = remoteRev; self.remoteDevice = remoteDevice83        self.differingKeys = differingKeys; self.mergedLists = mergedLists; self.message = message84    }85    public init(json j: VQJSON) {86        id = j.str("id"); key = VQObjectKey(kind: VQObjectKind(j.str("kind")), id: j.str("objectId"))87        at = j.date("at") ?? Date(timeIntervalSince1970: 0)88        resolution = Resolution(rawValue: j.str("resolution")) ?? .localWon89        needsAttention = j.flag("needsAttention")90        local = j["local"].flatMap { $0.isNull ? nil : $0 }; remote = j["remote"].flatMap { $0.isNull ? nil : $0 }; result = j["result"].flatMap { $0.isNull ? nil : $0 }91        remoteRev = j.int("remoteRev") ?? 0; remoteDevice = j.str("remoteDevice")92        differingKeys = j.strings("differingKeys"); mergedLists = j.strings("mergedLists"); message = j.optStr("message")93    }94    public var json: VQJSON {95        var o: VQJSONObject = ["id": .string(id), "kind": .string(key.kind.rawValue), "objectId": .string(key.id),96                               "at": .number((at.timeIntervalSince1970 * 1000).rounded()), "resolution": .string(resolution.rawValue),97                               "needsAttention": .bool(needsAttention), "remoteRev": .number(Double(remoteRev)), "remoteDevice": .string(remoteDevice),98                               "differingKeys": VQJSON(differingKeys), "mergedLists": VQJSON(mergedLists)]99        if let local { o["local"] = local }100        if let remote { o["remote"] = remote }101        if let result { o["result"] = result }102        if let message { o["message"] = .string(message) }103        return .object(o)104    }105}106107public struct VQSyncStatus: Sendable, Equatable {108    public enum Connection: Sendable, Equatable {109        /// `start()` was not called (or `stop()` was).110        case stopped111        case connecting112        /// The stream is open and said `hello`.113        case connected114        /// The stream dropped; a new attempt is made after `retryIn` seconds.115        case reconnecting(attempt: Int, retryIn: TimeInterval)116        /// The server answered 401 `x-vq-locked: 1`: the session of this device is dead. Sign in again.117        case locked118    }119    public var connection: Connection = .stopped120    /// Writes waiting for the server (the "offline queue").121    public var pendingWrites = 0122    /// The change-feed cursor (`seq`).123    public var cursor = 0124    public var lastPulledAt: Date?125    /// Conflicts with `needsAttention` that were not dismissed.126    public var conflictsNeedingAttention = 0127    /// The last transient failure, for a status tooltip.128    public var lastError: String?129    public init() {}130    /// Everything this device wrote was accepted and the stream is open.131    public var isSynced: Bool { connection == .connected && pendingWrites == 0 }132}133134public enum VQSyncEvent: Sendable, Equatable {135    /// Objects of these kinds changed in the local view (a pull, a local write, an accepted write, a merge).136    case objectsChanged(Set<VQObjectKind>)137    case statusChanged(VQSyncStatus)138    case conflict(VQConflictRecord)139}140
Files main
Menu

Theme