SPB Git

Repository Public

CanvasSyncTests.swift 15.0 KB 266 lines swift

1// SP Notes Core2// File: Tests/SPNotesSyncTests/CanvasSyncTests.swift3// Description: Canvases edited offline (API-NEXT §4.8): PUT with baseVersion, the three-way merge by node / edge id on a4//              409 or on a feed row, conflicts that keep both copies until the user decides, lost answers, the server's5//              trash, and a canvas drawn before its page exists on the server.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import Foundation10import SPNotesAPI11import SPNotesDocument12import SPNotesStore13import Testing14@testable import SPNotesSync15@testable import SPNotesTestSupport1617@Suite("Canvas sync (2.0)")18struct CanvasSyncTests {19    /// A canvas with two cards and one edge, known to both devices.20    private func shared(_ world: World, _ a: Device, _ b: Device) async throws -> String {21        var first = Canvas.document([Canvas.node("n1", "Hypothèse"), Canvas.node("n2", "Données", x: 300)])22        first.edges = [CanvasEdge(id: "e1", from: "n1", to: "n2", label: "motive")]23        let id = try await a.canvases.create(title: "Carte", document: first)24        #expect(await a.sync() == .completed)25        #expect(await b.sync() == .completed)26        try await expectCanvasMirror(a, id)27        try await expectCanvasMirror(b, id)28        return id29    }3031    @Test("a canvas drawn offline on a new page: the page is created as a canvas, the drawing merged over the empty server canvas and sent")32    func createdOffline() async throws {33        let world = World(apiLevel: 3)34        let fake = world.fake35        let a = try world.device("A"), b = try world.device("B")36        a.setOffline(true)37        let id = try await a.canvases.create(title: "Carte du projet", document: Canvas.document([Canvas.node("n1", "A")]))38        try await a.editCanvas(id) { $0.nodes.append(Canvas.node("n2", "B", x: 300)); $0.edges.append(CanvasEdge(id: "e1", from: "n1", to: "n2")) }39        #expect(try await a.canvases.state(pageId: id)?.isDirty == true)40        a.setOffline(false)41        #expect(await a.sync() == .completed)42        #expect(fake.page(id)?.type == "canvas")43        #expect(Canvas.texts(Canvas.parse(fake.canvasData(id))) == ["n1": "A", "n2": "B"])44        #expect(fake.canvasVersion(id) == 2, "version 1 is the empty canvas born with the page; one save on top")45        #expect(fake.count("PUT", "^/api/canvases/") == 1)46        try await expectCanvasMirror(a, id)47        #expect(await b.sync() == .completed)48        try await expectCanvasMirror(b, id)49        #expect(try await b.canvasDocument(id).edges.map(\.id) == ["e1"])50        // Saving the same document again is not an edit.51        #expect(try await a.canvases.save(pageId: id, try await a.canvasDocument(id)) == false)52        await world.closeAll()53    }5455    @Test("two devices change different cards offline: merged by id on the 409, both changes everywhere, no conflict")56    func differentCardsMerge() async throws {57        let world = World(apiLevel: 3)58        let fake = world.fake59        let a = try world.device("A"), b = try world.device("B")60        let id = try await shared(world, a, b)61        try await a.editCanvas(id) { $0.nodes[0].text = "Hypothèse H1"; $0.nodes.append(Canvas.node("n3", "Ajout de A", y: 200)) }62        try await b.editCanvas(id) { $0.nodes[1].x = 640; $0.nodes.append(Canvas.node("n4", "Ajout de B", y: 400)); $0.edges.append(CanvasEdge(id: "e2", from: "n2", to: "n4")) }63        #expect(await a.sync() == .completed)64        #expect(await b.sync() == .completed, "B's save is refused (409), merged with A's copy and sent again in the same call")65        #expect(fake.requests.filter { $0.method == "PUT" && $0.device == "B" }.map(\.status) == [409, 200])66        #expect(await a.sync() == .completed)67        let server = try #require(Canvas.parse(fake.canvasData(id)))68        #expect(Canvas.texts(server) == ["n1": "Hypothèse H1", "n2": "Données", "n3": "Ajout de A", "n4": "Ajout de B"])69        #expect(server.nodes.first { $0.id == "n2" }?.x == 640)70        #expect(Set(server.edges.map(\.id)) == ["e1", "e2"])71        for device in [a, b] {72            try await expectCanvasMirror(device, id)73            #expect(await device.engine.currentStatus().canvasConflicts == 0)74        }75        await world.closeAll()76    }7778    @Test("the same card changed differently: a conflict keeps both copies; nothing is overwritten on either side until the user decides")79    func sameCardConflict() async throws {80        let world = World(apiLevel: 3)81        let fake = world.fake82        let a = try world.device("A"), b = try world.device("B")83        let id = try await shared(world, a, b)84        try await a.editCanvas(id) { $0.nodes[0].text = "Version de A" }85        try await b.editCanvas(id) { $0.nodes[0].text = "Version de B"; $0.nodes.append(Canvas.node("n9", "Carte de B")) }86        #expect(await a.sync() == .completed)87        #expect(await b.sync() == .completed, "a conflict is not a failure of the cycle")8889        #expect(Canvas.texts(Canvas.parse(fake.canvasData(id)))["n1"] == "Version de A", "the server copy is not overwritten")90        #expect(try await b.canvasDocument(id).nodes[0].text == "Version de B", "the local copy is not overwritten")91        let status = await b.engine.currentStatus()92        #expect(status.canvasConflicts == 1)93        #expect(status.conflicts == 0, "page conflicts are counted apart")94        let conflict = try #require(try await b.canvases.conflict(pageId: id))95        #expect(conflict.local.nodes[0].text == "Version de B" && conflict.remote.nodes[0].text == "Version de A")96        #expect(conflict.merge.conflicts.map(\.id) == ["n1"])97        #expect(conflict.merge.conflicts[0].reason == .bothEdited)98        #expect(conflict.merge.merged.nodes.contains { $0.id == "n9" }, "the non-conflicting change is in the proposed merge")99        // While the conflict waits the canvas is still editable and is not pushed.100        try await b.editCanvas(id) { $0.nodes.append(Canvas.node("n10", "Pendant le conflit")) }101        fake.clearLog()102        #expect(await b.sync() == .completed)103        #expect(fake.count("PUT", "^/api/canvases/") == 0)104105        // The user takes A's text for the card and keeps everything else of B.106        let fresh = try #require(try await b.canvases.conflict(pageId: id))107        let decided = fresh.merge.merged.resolving(fresh.merge.conflicts[0], takingRemote: true)108        try await b.canvases.resolve(fresh, .merged(decided))109        #expect(await b.sync() == .completed)110        #expect(await a.sync() == .completed)111        #expect(Canvas.texts(Canvas.parse(fake.canvasData(id))) == ["n1": "Version de A", "n2": "Données", "n9": "Carte de B", "n10": "Pendant le conflit"])112        for device in [a, b] { try await expectCanvasMirror(device, id) }113        await world.closeAll()114    }115116    @Test("conflict decisions: keep mine overwrites the server copy, keep theirs gives back the replaced document")117    func conflictDecisions() async throws {118        let world = World(apiLevel: 3)119        let fake = world.fake120        let a = try world.device("A"), b = try world.device("B")121        let id = try await shared(world, a, b)122123        try await a.editCanvas(id) { $0.nodes[0].text = "A1" }124        try await b.editCanvas(id) { $0.nodes[0].text = "B1" }125        #expect(await a.sync() == .completed)126        #expect(await b.sync() == .completed)127        #expect(try await b.canvases.conflicts().map(\.pageId) == [id])128        #expect(try await b.canvases.resolve(pageId: id, .keepMine) == nil)129        #expect(await b.sync() == .completed)130        #expect(Canvas.texts(Canvas.parse(fake.canvasData(id)))["n1"] == "B1")131        #expect(await a.sync() == .completed)132        try await expectCanvasMirror(a, id)133134        try await a.editCanvas(id) { $0.nodes[0].text = "A2" }135        try await b.editCanvas(id) { $0.nodes[0].text = "B2" }136        #expect(await a.sync() == .completed)137        #expect(await b.sync() == .completed)138        let replaced = try await b.canvases.resolve(pageId: id, .keepTheirs)139        #expect(replaced?.nodes[0].text == "B2", "the replaced local document is handed back (undo)")140        #expect(await b.sync() == .completed)141        #expect(Canvas.texts(Canvas.parse(fake.canvasData(id)))["n1"] == "A2")142        for device in [a, b] { try await expectCanvasMirror(device, id) }143        await world.closeAll()144    }145146    @Test("edited on one device, deleted on the other: the edited card is kept and the conflict is reported (SPEC §7)")147    func editVersusDelete() async throws {148        let world = World(apiLevel: 3)149        let fake = world.fake150        let a = try world.device("A"), b = try world.device("B")151        let id = try await shared(world, a, b)152        try await a.editCanvas(id) { $0.edges.removeAll(); $0.nodes.removeAll { $0.id == "n2" } }153        try await b.editCanvas(id) { $0.nodes[1].text = "Données 2010–2025" }154        #expect(await a.sync() == .completed)155        #expect(await b.sync() == .completed)156        let conflict = try #require(try await b.canvases.conflict(pageId: id))157        #expect(conflict.merge.conflicts.contains { $0.id == "n2" && $0.reason == .editedAndDeleted })158        #expect(conflict.merge.merged.nodes.contains { $0.id == "n2" && $0.text == "Données 2010–2025" }, "the edited card survives in the merge")159        #expect(try await b.canvasDocument(id).nodes.contains { $0.id == "n2" }, "and on the device")160        try await b.canvases.resolve(conflict, .merged(conflict.merge.merged))161        #expect(await b.sync() == .completed)162        #expect(await a.sync() == .completed)163        #expect(Canvas.texts(Canvas.parse(fake.canvasData(id)))["n2"] == "Données 2010–2025")164        for device in [a, b] { try await expectCanvasMirror(device, id) }165        await world.closeAll()166    }167168    @Test("a lost answer: the retry meets its own write (409 with an identical copy) and settles without a conflict or a second version")169    func lostAnswer() async throws {170        let world = World(apiLevel: 3)171        let fake = world.fake172        let a = try world.device("A"), b = try world.device("B")173        let id = try await shared(world, a, b)174        try await a.editCanvas(id) { $0.nodes[0].text = "Après" }175        fake.inject(.dropResponse, method: "PUT", path: "^/api/canvases/")176        #expect(await a.sync() == .offline)177        let version = fake.canvasVersion(id)178        // The user keeps drawing before the next cycle.179        try await a.editCanvas(id) { $0.nodes.append(Canvas.node("n5", "Encore")) }180        #expect(await a.sync() == .completed)181        #expect(await a.engine.currentStatus().canvasConflicts == 0)182        #expect(fake.canvasVersion(id) == (version ?? 0) + 1, "one more version for the later drawing, none for the retry")183        #expect(Canvas.texts(Canvas.parse(fake.canvasData(id))) == ["n1": "Après", "n2": "Données", "n5": "Encore"])184        try await expectCanvasMirror(a, id)185        // Killed right after a save that the server applied: same outcome.186        try await a.editCanvas(id) { $0.nodes[0].text = "Avant le kill" }187        fake.inject(.dropResponse, method: "PUT", path: "^/api/canvases/")188        #expect(await a.sync() == .offline)189        try await a.restart()190        #expect(await a.sync() == .completed)191        try await expectCanvasMirror(a, id)192        #expect(await b.sync() == .completed)193        try await expectCanvasMirror(b, id)194        await world.closeAll()195    }196197    @Test("the server copy arrives by the feed while a local change waits: merged there too, then pushed")198    func feedMeetsLocalChange() async throws {199        let world = World(apiLevel: 3)200        let fake = world.fake201        let a = try world.device("A"), b = try world.device("B")202        let id = try await shared(world, a, b)203        try await b.editCanvas(id) { $0.nodes.append(Canvas.node("nb", "De B")) }204        #expect(await b.sync() == .completed)205        try await a.editCanvas(id) { $0.nodes.append(Canvas.node("na", "De A")) }206        // A's save fails for a server reason; the feed of the same cycle then brings B's copy.207        fake.inject(.status(500), method: "PUT", path: "^/api/canvases/", count: 1)208        #expect(await a.sync() == .completed)209        #expect(Canvas.texts(Canvas.parse(fake.canvasData(id))).keys.sorted() == ["n1", "n2", "na", "nb"])210        try await expectCanvasMirror(a, id)211        #expect(await b.sync() == .completed)212        try await expectCanvasMirror(b, id)213        // A change made on the web while the device is clean simply replaces the local copy.214        fake.webSaveCanvas(id, data: Canvas.document([Canvas.node("w1", "Web")]).jsonData())215        #expect(await a.sync() == .completed)216        #expect(Canvas.texts(try await a.canvasDocument(id)) == ["w1": "Web"])217        try await expectCanvasMirror(a, id)218        await world.closeAll()219    }220221    @Test("a canvas in the server's trash: the save waits with its error, nothing is lost, a restore lets it through; a purge removes it")222    func trashAndPurge() async throws {223        let world = World(apiLevel: 3)224        let fake = world.fake225        let a = try world.device("A"), b = try world.device("B")226        let id = try await shared(world, a, b)227        try await a.editCanvas(id) { $0.nodes.append(Canvas.node("n7", "Avant la corbeille")) }228        fake.webTrash(id)229        #expect(await a.sync() == .completed)230        let waiting = try #require(try await a.canvases.state(pageId: id))231        #expect(waiting.isDirty && waiting.syncError != nil)232        #expect(waiting.document.nodes.contains { $0.id == "n7" })233        fake.webRestore(id)234        #expect(await a.sync() == .completed)235        #expect(Canvas.texts(Canvas.parse(fake.canvasData(id)))["n7"] == "Avant la corbeille")236        try await expectCanvasMirror(a, id)237        // Purged on the web: page and canvas leave the device (tombstones `page` + `canvas`).238        fake.webPurge(id)239        #expect(await b.sync() == .completed)240        #expect(try await b.store.canvas(pageId: id) == nil)241        #expect(try await b.store.page(id: id) == nil)242        await world.closeAll()243    }244245    @Test("refresh reads a canvas on demand; offline it fails with the typed error and the local copy stays")246    func refreshOnDemand() async throws {247        let world = World(apiLevel: 3)248        let fake = world.fake249        let a = try world.device("A")250        let id = fake.webCreateCanvas(title: "Du web")251        fake.webSaveCanvas(id, data: Canvas.document([Canvas.node("w1", "Web")]).jsonData())252        #expect(try await a.canvases.state(pageId: id) == nil)253        let state = try #require(try await a.canvases.refresh(pageId: id))254        #expect(state.version == 2 && !state.isDirty && Canvas.texts(state.document) == ["w1": "Web"])255        a.setOffline(true)256        await #expect(throws: RepositoryError.offline) { try await a.canvases.refresh(pageId: id) }257        #expect(try await a.canvases.state(pageId: id)?.version == 2)258        a.setOffline(false)259        let notCanvas = fake.webCreatePage(title: "Pas un canvas")260        do { _ = try await a.canvases.refresh(pageId: notCanvas); Issue.record("expected an error") } catch let error as RepositoryError {261            guard case .notFound = error else { Issue.record("unexpected \(error)"); return }262        }263        await world.closeAll()264    }265}266
Files main
Menu

Theme