Repository Public
1// SP Notes Core2// File: Sources/SPNotesSync/Repositories/CanvasRepository.swift3// Description: Canvases for the apps: the local `spn-canvas-1` document of a canvas page, edited offline, sent by the4// engine with its base version, merged by node / edge id when the server copy moved, and — when the merge5// is not clean — a conflict that keeps both copies until the user decides. See docs/REPOSITORIES.md.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Foundation10import SPNotesAPI11import SPNotesDocument12import SPNotesStore1314/// The local state of a canvas.15public struct CanvasState: Sendable, Equatable {16 public var pageId: String17 public var document: CanvasDocument18 /// Server version the local copy derives from (0 = never synced).19 public var version: Int20 /// Local changes not acknowledged yet.21 public var isDirty: Bool22 /// The server copy could not be merged: see `CanvasRepository.conflict(pageId:)`.23 public var hasConflict: Bool24 /// The reason of the last refused save, if any (the canvas is tried again at the next cycle).25 public var syncError: String?26 public var updatedAt: Date27}2829/// Two copies of a canvas that could not be merged automatically. Nothing was changed locally.30public struct CanvasConflictState: Sendable, Equatable {31 public var pageId: String32 /// The canvas as it is on this device (untouched, still editable).33 public var local: CanvasDocument34 /// The server copy.35 public var remote: CanvasDocument36 public var remoteVersion: Int37 /// The last copy both sides had in common (empty when there is none).38 public var base: CanvasDocument39 /// The three-way merge: `merge.merged` keeps the local version of each conflicting element (and the edited40 /// version of an element the other side deleted); `merge.conflicts` lists them with both versions.41 public var merge: CanvasMergeResult42 /// Identifies the local copy the conflict was computed on (a later local edit changes it).43 public var localEditSeq: Int6444}4546public enum CanvasResolution: Sendable, Equatable {47 /// The local canvas replaces the server copy at the next cycle.48 case keepMine49 /// The server copy replaces the local canvas (the replaced document is returned by `resolve`).50 case keepTheirs51 /// A document assembled by the user (for instance `conflict.merge.merged` after `resolving(_:takingRemote:)`).52 case merged(CanvasDocument)53}5455public struct CanvasRepository: Sendable {56 let context: RepositoryContext57 public init(context: RepositoryContext) { self.context = context }5859 /// The local canvas of a page (nil when the device has none yet: call `refresh`).60 public func state(pageId: String) async throws -> CanvasState? {61 do {62 guard let record = try await context.store.canvas(pageId: pageId) else { return nil }63 let document = (try? CanvasDocument(data: record.json)) ?? CanvasDocument()64 return CanvasState(pageId: pageId, document: document, version: record.version, isDirty: record.dirty, hasConflict: record.hasConflict,65 syncError: record.syncError, updatedAt: record.updatedAt)66 } catch { throw RepositoryError.from(error) }67 }6869 /// Creates a canvas page on this device (works offline): a page of type `canvas` with an empty document as content,70 /// and its canvas. Returns the page id.71 @discardableResult72 public func create(title: String, parentId: String? = nil, section: String? = nil, document: CanvasDocument = CanvasDocument(), id: String = NotesAPI.newID()) async throws -> String {73 do {74 var page = NewPage(id: id, parentId: parentId, title: title, content: Data(#"{"type":"doc","content":[]}"#.utf8))75 page.type = "canvas"76 page.section = section77 _ = try await context.store.createPage(page)78 _ = try await context.store.saveCanvas(pageId: id, json: document.jsonData())79 await context.scheduleSync()80 return id81 } catch { throw RepositoryError.from(error) }82 }8384 /// Saves the canvas unconditionally (works offline): whatever is stored is replaced. Use it for a document the85 /// app just read and transformed in one go; an interactive editor uses `save(pageId:_:editedFrom:)`. Returns86 /// false when nothing changed.87 @discardableResult88 public func save(pageId: String, _ document: CanvasDocument) async throws -> Bool {89 do {90 let changed = try await context.store.saveCanvas(pageId: pageId, json: document.jsonData())91 if changed { await context.scheduleSync() }92 return changed93 } catch { throw RepositoryError.from(error) }94 }9596 /// Saves what an editor did to the canvas it loaded (`loaded` = the document of `state(pageId:)` the edit started97 /// from). When the stored canvas moved meanwhile — a cycle applied or merged the server copy while the user was98 /// drawing — the edit is merged into it by node / edge id instead of overwriting it (which would silently delete99 /// what the other device added). Returns the document now stored: the editor continues from it.100 /// Prefer this to `save(pageId:_:)` in an interactive editor.101 @discardableResult102 public func save(pageId: String, _ document: CanvasDocument, editedFrom loaded: CanvasDocument) async throws -> CanvasDocument {103 do {104 var expected: Data? = loaded.jsonData()105 if try await context.store.canvas(pageId: pageId) == nil { expected = nil }106 var candidate = document107 for _ in 0..<8 {108 guard let current = try await context.store.saveCanvas(pageId: pageId, json: candidate.jsonData(), ifUnchangedFrom: expected) else {109 await context.scheduleSync()110 return candidate111 }112 // The canvas moved under the editor: the user's changes (loaded → document) go on top of the stored copy.113 let stored = (try? CanvasDocument(data: current.json)) ?? CanvasDocument()114 candidate = CanvasDocument.merge(base: loaded, local: document, remote: stored).merged115 expected = current.json.isEmpty ? nil : current.json116 }117 throw RepositoryError.store("the canvas keeps changing while it is saved")118 } catch { throw RepositoryError.from(error) }119 }120121 /// Reads the canvas from the server now (first opening of a canvas the feed has not brought yet). A canvas with122 /// local changes is merged exactly like during a cycle. `.offline` when unreachable.123 @discardableResult124 public func refresh(pageId: String) async throws -> CanvasState? {125 let server = try await context.online { try await context.api.canvas(pageID: pageId) }126 do {127 let remote = SyncEngine.canonicalCanvas(server.data.data)128 if case .diverged(let base, _, _, let version) = try await context.store.applyRemoteCanvas(pageId: pageId, json: remote, version: server.version, rev: server.rev ?? 0) {129 if let engine = context.engine {130 if try await engine.reconcileCanvas(pageId: pageId, base: base, remote: remote, remoteVersion: version) { await context.scheduleSync() }131 }132 }133 } catch { throw RepositoryError.from(error) }134 return try await state(pageId: pageId)135 }136137 /// The canvases waiting for a decision.138 public func conflicts() async throws -> [CanvasConflictState] {139 do { return try await context.store.canvasConflicts().compactMap(Self.conflictState) } catch { throw RepositoryError.from(error) }140 }141142 public func conflict(pageId: String) async throws -> CanvasConflictState? {143 do { return try await context.store.canvas(pageId: pageId).flatMap(Self.conflictState) } catch { throw RepositoryError.from(error) }144 }145146 static func conflictState(_ record: CanvasRecord) -> CanvasConflictState? {147 guard let remoteJSON = record.conflictJSON else { return nil }148 let local = (try? CanvasDocument(data: record.json)) ?? CanvasDocument()149 let remote = (try? CanvasDocument(data: remoteJSON)) ?? CanvasDocument()150 let base = record.baseJSON.flatMap { try? CanvasDocument(data: $0) } ?? CanvasDocument()151 return CanvasConflictState(pageId: record.pageId, local: local, remote: remote, remoteVersion: record.conflictVersion ?? record.version, base: base,152 merge: CanvasDocument.merge(base: base, local: local, remote: remote), localEditSeq: record.editSeq)153 }154155 /// Settles a canvas conflict as it was shown to the user (`conflict` = the state the decision was made on). When156 /// the canvas moved since — a newer server copy was recorded, or the local canvas was edited — nothing is written157 /// and `.stale` is thrown: read `conflict(pageId:)` again (it may also be gone: a later server copy merged cleanly).158 /// Returns the document that was replaced on this device, if any (offer an undo).159 @discardableResult160 public func resolve(_ conflict: CanvasConflictState, _ resolution: CanvasResolution) async throws -> CanvasDocument? {161 do {162 let pageId = conflict.pageId163 guard let record = try await context.store.canvas(pageId: pageId), let remote = record.conflictJSON else { return nil }164 let version = record.conflictVersion ?? record.version165 guard version == conflict.remoteVersion, record.editSeq == conflict.localEditSeq else { throw RepositoryError.stale }166 var replaced: CanvasDocument?167 switch resolution {168 case .keepMine:169 try await context.store.discardCanvasConflict(pageId: pageId)170 case .keepTheirs:171 guard try await context.store.resolveCanvas(pageId: pageId, merged: remote, remote: remote, remoteVersion: version, ifEditSeq: record.editSeq) else { throw RepositoryError.stale }172 replaced = conflict.local173 case .merged(let document):174 guard try await context.store.resolveCanvas(pageId: pageId, merged: document.jsonData(), remote: remote, remoteVersion: version, ifEditSeq: record.editSeq) else { throw RepositoryError.stale }175 if conflict.local != document { replaced = conflict.local }176 }177 await context.scheduleSync()178 return replaced179 } catch { throw RepositoryError.from(error) }180 }181182 /// Settles the conflict of a canvas as it is now (reads it, then decides): for `.keepMine` / `.keepTheirs` buttons183 /// that do not show a merge.184 @discardableResult185 public func resolve(pageId: String, _ resolution: CanvasResolution) async throws -> CanvasDocument? {186 guard let conflict = try await conflict(pageId: pageId) else { return nil }187 return try await resolve(conflict, resolution)188 }189190 /// Changes of the local canvases (ids of their pages).191 public func changes() async -> AsyncStream<Set<String>> {192 let upstream = await context.store.changes()193 return AsyncStream { continuation in194 let task = Task {195 for await change in upstream { if case .canvases(let ids) = change { continuation.yield(ids) } }196 continuation.finish()197 }198 continuation.onTermination = { _ in task.cancel() }199 }200 }201}202