SPB Git

Repository Public

SyncModels.swift 8.9 KB 158 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/Core/Sync/SyncModels.swift3// Description: Sync feed of the backend (`/api/events`, `/api/sync`): change records, typed events and the pure reducer that turns changes into store refreshes.4import Foundation56/// One row of the server's change feed. The event says *what* changed; the client re-reads that entity.7public struct SyncChange: Sendable, Hashable, Codable, Identifiable {8    public enum Operation: String, Sendable, Codable { case upsert, delete }9    public var seq: Int10    /// `conversation` `message` `project` `prompt` `preset` `model` `settings` `memory` `draft` `provider` `attachment` `artifact` (unknown values are kept).11    public var entity: String12    /// Identifier of the changed entity (may be absent for list-level changes).13    public var entityId: String?14    public var op: Operation15    public var at: Date?16    /// Opaque identifier of the session that made the change (nil for server-side work).17    public var origin: String?18    public var id: Int { seq }1920    enum CodingKeys: String, CodingKey { case seq, entity, op, at, origin; case entityId = "id" }21    public init(seq: Int, entity: String, entityId: String? = nil, op: Operation = .upsert, at: Date? = nil, origin: String? = nil) {22        self.seq = seq; self.entity = entity; self.entityId = entityId; self.op = op; self.at = at; self.origin = origin23    }24    public init(from decoder: Decoder) throws {25        let c = try decoder.container(keyedBy: CodingKeys.self)26        guard let s = c.flexInt(.seq) else { throw DecodingError.dataCorruptedError(forKey: .seq, in: c, debugDescription: "missing seq") }27        seq = s; entity = c.optional(String.self, .entity) ?? "unknown"; entityId = c.optional(String.self, .entityId)28        op = c.optional(Operation.self, .op) ?? .upsert; at = c.optional(Date.self, .at); origin = c.optional(String.self, .origin)29    }30}3132/// `GET /api/sync?after=<seq>` — pull variant of the feed.33public struct SyncFeed: Sendable, Hashable, Codable {34    public var events: [SyncChange]35    public var head: Int36    /// The client is too far behind: the feed no longer holds every change since `after` → reload everything.37    public var truncated: Bool38    /// Generations currently running on the server (run ids).39    public var runs: [JSONValue]40    public var serverTime: Date?41    enum CodingKeys: String, CodingKey { case events, head, truncated, runs, serverTime }42    public init(events: [SyncChange] = [], head: Int = 0, truncated: Bool = false) { self.events = events; self.head = head; self.truncated = truncated; runs = [] }43    public init(from decoder: Decoder) throws {44        let c = try decoder.container(keyedBy: CodingKeys.self)45        events = (c.optional([Lossy<SyncChange>].self, .events) ?? []).compactMap(\.value); head = c.flexInt(.head) ?? (events.last?.seq ?? 0)46        truncated = c.optional(Bool.self, .truncated) ?? false; runs = c.optional([JSONValue].self, .runs) ?? []; serverTime = c.optional(Date.self, .serverTime)47    }48}4950/// Events of the long-lived `GET /api/events` stream.51public enum SyncEvent: Sendable, Equatable {52    case hello(head: Int, runs: [JSONValue])53    case change(SyncChange)54    case resync(head: Int)55    case unknown(String)5657    public init(_ sse: SSEEvent) {58        let d = JSONValue.parse(Data(sse.data.utf8)) ?? .null59        switch sse.event {60        case "hello": self = .hello(head: d["head"]?.intValue ?? 0, runs: d["runs"]?.arrayValue ?? [])61        case "resync": self = .resync(head: d["head"]?.intValue ?? 0)62        case "change":63            if let c = try? JSONDecoder.api().decode(SyncChange.self, from: Data(sse.data.utf8)) { self = .change(c) } else { self = .unknown("change") }64        default: self = .unknown(sse.event)65        }66    }67}6869/// What must be re-read after a batch of changes. Pure value: `reduce` is deterministic and order-independent, so the70/// same batch replayed after a reconnection produces the same refreshes.71public struct SyncInvalidation: Sendable, Equatable {72    /// The conversation list (titles, pins, order, new or deleted rows).73    public var conversationList = false74    /// Conversations whose row changed.75    public var conversations: Set<String> = []76    public var deletedConversations: Set<String> = []77    /// Message ids that changed (the feed does not say in which conversation: open conversations are re-read).78    public var messages: Set<String> = []79    public var models = false80    public var settings = false81    public var projects = false82    public var prompts = false83    public var presets = false84    public var memory = false85    public var providers = false86    public var attachments = false87    public var artifacts = false88    /// Draft scopes that changed on another device (conversation id, `new`, `new:<project>`).89    public var drafts: Set<String> = []90    /// Everything must be reloaded (`resync`, or a truncated pull).91    public var everything = false92    /// Highest sequence number seen.93    public var head = 094    public init() {}9596    public var isEmpty: Bool {97        !everything && !conversationList && conversations.isEmpty && deletedConversations.isEmpty && messages.isEmpty && !models && !settings && !projects && !prompts && !presets98            && !memory && !providers && !attachments && !artifacts && drafts.isEmpty99    }100    /// The open conversations must be re-read (a message changed, or the row of one of them did).101    public func touchesConversation(_ id: String) -> Bool { everything || !messages.isEmpty || conversations.contains(id) || deletedConversations.contains(id) }102103    public mutating func apply(_ c: SyncChange) {104        head = max(head, c.seq)105        switch c.entity {106        case "conversation":107            conversationList = true108            if let id = c.entityId { if c.op == .delete { deletedConversations.insert(id); conversations.remove(id) } else if !deletedConversations.contains(id) { conversations.insert(id) } }109        case "message": conversationList = true; if let id = c.entityId { messages.insert(id) }110        case "project": projects = true; conversationList = true111        case "prompt": prompts = true112        case "preset": presets = true113        case "model": models = true114        case "settings": settings = true115        case "memory": memory = true116        case "provider": providers = true; models = true117        case "attachment": attachments = true118        case "artifact": artifacts = true119        case "draft": if let id = c.entityId { drafts.insert(id) }; conversationList = true120        default: break // an entity this version does not know: nothing to refresh, the sequence still advances121        }122    }123    public mutating func merge(_ other: SyncInvalidation) {124        everything = everything || other.everything; conversationList = conversationList || other.conversationList125        deletedConversations.formUnion(other.deletedConversations); conversations.formUnion(other.conversations); conversations.subtract(deletedConversations)126        messages.formUnion(other.messages); drafts.formUnion(other.drafts)127        models = models || other.models; settings = settings || other.settings; projects = projects || other.projects; prompts = prompts || other.prompts; presets = presets || other.presets128        memory = memory || other.memory; providers = providers || other.providers; attachments = attachments || other.attachments; artifacts = artifacts || other.artifacts129        head = max(head, other.head)130    }131    public mutating func markEverything(head: Int) { everything = true; conversationList = true; models = true; settings = true; projects = true; prompts = true; presets = true; memory = true; providers = true; self.head = max(self.head, head) }132133    /// `after`: changes at or below this sequence number were already applied and are skipped.134    public static func reduce(_ changes: [SyncChange], after: Int = 0) -> SyncInvalidation {135        var inv = SyncInvalidation(); inv.head = after136        for c in changes where c.seq > after { inv.apply(c) }137        return inv138    }139    public static func reduce(_ feed: SyncFeed, after: Int) -> SyncInvalidation {140        var inv = reduce(feed.events, after: after)141        if feed.truncated { inv.markEverything(head: feed.head) }142        inv.head = max(inv.head, feed.head)143        return inv144    }145}146147/// Draft typed while the server could not be reached: kept on the Mac and pushed when the connection is back.148public struct PendingDraft: Sendable, Hashable, Codable {149    public var scope: String150    public var text: String151    public var attachmentIds: [String]152    public var updatedAt: Date153    public init(scope: String, text: String, attachmentIds: [String] = [], updatedAt: Date = Date()) { self.scope = scope; self.text = text; self.attachmentIds = attachmentIds; self.updatedAt = updatedAt }154155    /// Last write wins on the clock: the local draft is pushed only when it is newer than the server's.156    public func shouldReplace(serverUpdatedAt: Date?) -> Bool { guard let serverUpdatedAt else { return true }; return updatedAt > serverUpdatedAt }157}158
Files main
Menu

Theme