Repository Public
1// SP Notes Core2// File: Sources/SPNotesStore/NotesStore+Canvas.swift3// Description: Local copies of canvases (2.0): offline edits with a base copy for the three-way merge, the same4// optimistic version model as pages, and conflict copies that never overwrite local work.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation910extension NotesStore {11 private static let canvasColumns = "page_id, json, version, base_json, dirty, rev, edit_seq, conflict_json, conflict_version, sync_error, updated_at"1213 private static func decodeCanvas(_ r: Row) -> CanvasRecord {14 CanvasRecord(pageId: r.string(0), json: r.data(1), version: Int(r.int(2)), baseJSON: r.optData(3), dirty: r.bool(4), rev: r.int(5),15 editSeq: r.int(6), conflictJSON: r.optData(7), conflictVersion: r.optInt(8).map(Int.init), syncError: r.optString(9), updatedAt: r.date(10))16 }1718 public func canvas(pageId: String) throws -> CanvasRecord? {19 try db.first("SELECT \(Self.canvasColumns) FROM canvases WHERE page_id=?", [pageId], Self.decodeCanvas)20 }2122 private func requireCanvas(_ pageId: String) throws -> CanvasRecord {23 guard let record = try canvas(pageId: pageId) else { throw StoreError.notFound("canvas \(pageId)") }24 return record25 }2627 /// Saves a local edit: the canvas becomes dirty, `editSeq` grows, and the last synced copy is kept as the base28 /// the first time. Returns false (nothing written) when the bytes are unchanged.29 @discardableResult30 public func saveCanvas(pageId: String, json: Data) throws -> Bool {31 guard !pageId.isEmpty else { throw StoreError.invalid("empty canvas page id") }32 return try write {33 let now = nowMillis()34 if let existing = try canvas(pageId: pageId) {35 guard existing.json != json else { return false }36 // The base is the last copy common with the server: taken once, before the first local edit.37 if !existing.dirty, existing.version > 0 { try db.run("UPDATE canvases SET base_json=json WHERE page_id=?", [pageId]) }38 try db.run("UPDATE canvases SET json=?, dirty=1, edit_seq=edit_seq+1, sync_error=NULL, updated_at=? WHERE page_id=?", [json, now, pageId])39 } else {40 try db.run("INSERT INTO canvases(page_id, json, version, dirty, edit_seq, updated_at) VALUES(?, ?, 0, 1, 1, ?)", [pageId, json, now])41 }42 pending.canvases.insert(pageId)43 return true44 }45 }4647 /// Compare-and-set save: writes `json` only when the stored canvas is still `expected` (byte for byte; nil = no48 /// canvas stored yet). Otherwise nothing is written and the current record is returned: the canvas moved (the49 /// engine applied or merged a server copy) since the editor loaded it — merge and try again50 /// (`CanvasRepository.save(pageId:_:editedFrom:)` does). Returns nil when the save went through or was a no-op.51 public func saveCanvas(pageId: String, json: Data, ifUnchangedFrom expected: Data?) throws -> CanvasRecord? {52 try write {53 let current = try canvas(pageId: pageId)54 guard current?.json == expected else { return current ?? CanvasRecord(pageId: pageId, json: Data(), version: 0, baseJSON: nil, dirty: false, rev: 0, editSeq: 0,55 conflictJSON: nil, conflictVersion: nil, syncError: nil, updatedAt: Date()) }56 _ = try saveCanvas(pageId: pageId, json: json)57 return nil58 }59 }6061 /// Canvases with local changes to send, oldest edit first. Those waiting for a conflict decision are excluded62 /// unless asked.63 public func canvasesNeedingPush(limit: Int = 50, includeConflicts: Bool = false) throws -> [CanvasRecord] {64 try db.query("""65 SELECT \(Self.canvasColumns) FROM canvases WHERE dirty=1\(includeConflicts ? "" : " AND conflict_json IS NULL") ORDER BY updated_at, page_id LIMIT ?66 """, [max(limit, 0)], Self.decodeCanvas)67 }6869 /// After the server accepted a push made at `pushedEditSeq`: stores the new version; when no edit happened70 /// since, the canvas is clean and its base is dropped, otherwise `pushed` (what was sent) becomes the new base.71 public func markCanvasPushed(pageId: String, version: Int, pushedEditSeq: Int64, pushed: Data) throws {72 try write {73 let record = try requireCanvas(pageId)74 if record.editSeq == pushedEditSeq {75 try db.run("UPDATE canvases SET version=?, dirty=0, base_json=NULL, sync_error=NULL WHERE page_id=?", [version, pageId])76 } else {77 try db.run("UPDATE canvases SET version=?, base_json=?, sync_error=NULL WHERE page_id=?", [version, pushed, pageId])78 }79 pending.canvases.insert(pageId)80 }81 }8283 public func markCanvasPushFailed(pageId: String, error: String) throws {84 try write {85 if try db.run("UPDATE canvases SET sync_error=? WHERE page_id=?", [error, pageId]) > 0 { pending.canvases.insert(pageId) }86 }87 }8889 /// Applies the server's copy. A clean canvas takes it; a dirty one is NOT touched: the three copies come back90 /// in `.diverged` for the caller to merge (the store does not know the canvas format).91 @discardableResult92 public func applyRemoteCanvas(pageId: String, json: Data, version: Int, rev: Int64 = 0) throws -> CanvasApplyResult {93 try write {94 let now = nowMillis()95 guard let existing = try canvas(pageId: pageId) else {96 try db.run("INSERT INTO canvases(page_id, json, version, dirty, rev, updated_at) VALUES(?, ?, ?, 0, ?, ?)", [pageId, json, version, rev, now])97 pending.canvases.insert(pageId)98 return .applied99 }100 if existing.dirty {101 if version <= existing.version { return .unchanged }102 return .diverged(base: existing.baseJSON, local: existing.json, remote: json, remoteVersion: version)103 }104 if version < existing.version || (version == existing.version && existing.json == json) {105 if rev > existing.rev { try db.run("UPDATE canvases SET rev=? WHERE page_id=?", [rev, pageId]) }106 return .unchanged107 }108 try db.run("UPDATE canvases SET json=?, version=?, rev=max(rev, ?), base_json=NULL, updated_at=? WHERE page_id=?", [json, version, rev, now, pageId])109 pending.canvases.insert(pageId)110 return .applied111 }112 }113114 /// Stores the outcome of a clean three-way merge: `merged` becomes the local JSON, the server copy `remote` at115 /// `remoteVersion` the new base. The canvas stays dirty (to push the merge) unless `merged` equals `remote`.116 /// Any conflict copy is cleared.117 ///118 /// `ifEditSeq`: compare-and-set — when given and the canvas was edited since the caller read it (another119 /// `editSeq`), nothing is written and false is returned: the merge was computed on a copy the user has since120 /// changed and must be done again.121 @discardableResult122 public func resolveCanvas(pageId: String, merged: Data, remote: Data, remoteVersion: Int, ifEditSeq expected: Int64? = nil) throws -> Bool {123 try write {124 let current = try requireCanvas(pageId)125 if let expected, current.editSeq != expected { return false }126 let same = merged == remote127 try db.run("""128 UPDATE canvases SET json=?, version=?, base_json=?, dirty=?, edit_seq=edit_seq+1, conflict_json=NULL, conflict_version=NULL,129 sync_error=NULL, updated_at=? WHERE page_id=?130 """, [merged, remoteVersion, same ? SQLValue.null : SQLValue.blob(remote), !same, nowMillis(), pageId])131 pending.canvases.insert(pageId)132 return true133 }134 }135136 /// Keeps a server copy that could not be merged next to the untouched local canvas, which leaves the push list137 /// until `resolveCanvas` (merged by the user) or `discardCanvasConflict`.138 public func recordCanvasConflict(pageId: String, remote: Data, remoteVersion: Int) throws {139 try write {140 _ = try requireCanvas(pageId)141 try db.run("UPDATE canvases SET conflict_json=?, conflict_version=? WHERE page_id=?", [remote, remoteVersion, pageId])142 pending.canvases.insert(pageId)143 }144 }145146 /// Drops the conflict copy and keeps the local canvas, rebased on the server version so that the next push147 /// overwrites the server copy (the user chose "mine").148 public func discardCanvasConflict(pageId: String) throws {149 try write {150 let record = try requireCanvas(pageId)151 guard let remote = record.conflictJSON else { return }152 try db.run("UPDATE canvases SET base_json=?, version=?, conflict_json=NULL, conflict_version=NULL WHERE page_id=?",153 [remote, record.conflictVersion ?? record.version, pageId])154 pending.canvases.insert(pageId)155 }156 }157158 public func canvasConflicts() throws -> [CanvasRecord] {159 try db.query("SELECT \(Self.canvasColumns) FROM canvases WHERE conflict_json IS NOT NULL ORDER BY page_id", [], Self.decodeCanvas)160 }161162 /// Removes the local copy of a canvas (its page was purged). Unknown ids are ignored.163 public func deleteCanvas(pageId: String) throws {164 try write {165 if try db.run("DELETE FROM canvases WHERE page_id=?", [pageId]) > 0 { pending.canvases.insert(pageId) }166 }167 }168}169