SPB Git

Repository Public

LiveEntitySyncTests.swift 11.6 KB 195 lines swift

1// SP Notes Core2// File: Tests/SPNotesSyncTests/LiveEntitySyncTests.swift3// Description: The 2.0 sync paths against the real scratch backend of API-NEXT (never production): two devices, tasks4//              through the outbox, canvases with merge and conflict, deletions and tombstones. Skipped unless5//              SPN_LIVE_URL and SPN_LIVE_TOKEN are set and the server advertises the `entities` feature.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9//10// Run (the origin of the scratch server is http://localhost:8483, so tunnel the same port):11//   ssh -f -N -L 8483:127.0.0.1:8483 M4M64c12//   SPN_LIVE_URL=http://localhost:8483 SPN_LIVE_TOKEN=$(ssh M4M64c 'cd ~/dev/note-next && bash scripts/next-dev-server.sh token') \13//   SPN_ONLY=Sync swift test --scratch-path .build-sync --filter LiveEntitySyncTests14import Foundation15import SPNotesAPI16import SPNotesDocument17import SPNotesStore18import Testing19@testable import SPNotesSync20@testable import SPNotesTestSupport2122private enum LiveNext {23    static func value(_ name: String) -> String? {24        guard let value = ProcessInfo.processInfo.environment[name], !value.isEmpty else { return nil }25        return value26    }27    static var url: URL? { value("SPN_LIVE_URL").flatMap(URL.init(string:)) }28    static var token: String? { value("SPN_LIVE_TOKEN") }29    static var enabled: Bool {30        guard let url, token != nil, let host = url.host else { return false }31        return !host.hasSuffix("spboucher.ai")32    }33}3435private final class LiveNextDevice: @unchecked Sendable {36    let name: String37    let directory: URL38    let store: NotesStore39    let api: NotesAPI40    let engine: SyncEngine4142    init(_ name: String) throws {43        self.name = name44        directory = FileManager.default.temporaryDirectory.appendingPathComponent("spn-live-next-\(name)-\(UUID().uuidString)")45        try FileManager.default.createDirectory(at: directory.appendingPathComponent("files"), withIntermediateDirectories: true)46        store = try NotesStore(url: directory.appendingPathComponent("notes.sqlite"))47        let configuration = APIConfiguration(baseURL: LiveNext.url!, userAgent: APIConfiguration.userAgent(appVersion: "2.0.0"))48        api = NotesAPI(client: HTTPClient(configuration: configuration, tokenStore: InMemoryTokenStore(token: LiveNext.token)))49        engine = SyncEngine(store: store, api: api, files: TestFiles(root: directory.appendingPathComponent("files")))50    }5152    deinit { try? FileManager.default.removeItem(at: directory) }5354    var context: RepositoryContext { RepositoryContext(store: store, api: api, engine: nil) }   // no background cycles: the test drives them55    var tasks: TasksRepository { TasksRepository(context: context) }56    var canvases: CanvasRepository { CanvasRepository(context: context) }5758    func edit(_ pageId: String, _ change: (inout CanvasDocument) -> Void) async throws {59        let loaded = try #require(try await canvases.state(pageId: pageId)).document60        var document = loaded61        change(&document)62        try await canvases.save(pageId: pageId, document, editedFrom: loaded)63    }64}6566@Suite("Live: entity sync against the scratch backend (2.0)")67struct LiveEntitySyncTests {68    @Test("two devices, the real 3.0 server: feed with kinds, tasks offline-first, canvas merge and conflict, deletions", .enabled(if: LiveNext.enabled))69    func twoDevices() async throws {70        let a = try LiveNextDevice("A"), b = try LiveNextDevice("B")71        let meta = try await a.api.meta()72        try #require(meta.has(ServerFeature.entities) && meta.has(ServerFeature.tasksV2) && meta.has(ServerFeature.canvas), "the server is not a 3.0 scratch instance")73        var pages: [String] = []74        var taskIds: [String] = []75        do {76            // 1. first cycle: a full copy with every kind77            #expect(await a.sync() == .completed)78            #expect(try await a.store.meta(SyncEngine.kindsKey) == SyncKind.all.joined(separator: ","))79            let head = try await a.api.sync(since: 0, limit: 1, kinds: SyncKind.all).head80            #expect(try await a.store.syncCursor() <= head)8182            // 2. a page, a task anchored to it (bare day), a free task and a canvas, all created before any request83            let digest = ContentDigest(content: Doc.data([("lb1", "Texte")]))84            let page = try await a.store.createPage(NewPage(title: "Live · entités \(UUID().uuidString.prefix(6))", content: Doc.data([("lb1", "Texte")]),85                                                            plainText: digest.plainText, wordCount: digest.wordCount, preview: digest.preview)).id86            pages.append(page)87            let anchored = try await a.tasks.create(title: "Live · ancrée", dueDay: "2026-12-24", priority: .high, pageId: page)88            let free = try await a.tasks.create(title: "Live · libre")89            taskIds = [anchored.id, free.id]90            var first = CanvasDocument(nodes: [Canvas.node("n1", "Hypothèse"), Canvas.node("n2", "Données", x: 320)])91            first.edges = [CanvasEdge(id: "e1", from: "n1", to: "n2", label: "motive")]92            let canvas = try await a.canvases.create(title: "Live · canvas \(UUID().uuidString.prefix(6))", document: first)93            pages.append(canvas)94            #expect(await a.sync() == .completed)95            let status = await a.engine.currentStatus()96            #expect(status.pending == 0 && status.rejected == 0 && status.canvasConflicts == 0)9798            let serverTask = try await a.api.task(id: anchored.id)99            #expect(serverTask.pageId == page && serverTask.priority == "high")100            #expect(serverTask.dueAt.map(APIDate.string(from:)) == "2026-12-24T12:00:00.000Z")101            let serverCanvas = try await a.api.canvas(pageID: canvas)102            #expect(serverCanvas.version == 2)103            #expect(try CanvasDocument(data: serverCanvas.data.data) == first)104            #expect(try await a.store.canvas(pageId: canvas)?.dirty == false)105            #expect(try await a.store.entity(kind: .task, id: anchored.id)?.dirty == false)106107            // 3. the other device receives everything through the feed108            #expect(await b.sync() == .completed)109            #expect(try await b.tasks.task(id: anchored.id)?.title == "Live · ancrée")110            #expect(try await b.tasks.list(pageId: page).map(\.id) == [anchored.id])111            #expect(try await b.canvases.state(pageId: canvas)?.document == first)112113            // 4. both edit the same task offline (different fields), and the same field114            try await a.tasks.update(id: anchored.id, TaskEdit(title: "Live · ancrée (A)"))115            try await b.tasks.update(id: anchored.id, TaskEdit(status: .done, dueAt: .null))116            try await b.tasks.update(id: free.id, TaskEdit(priority: .low))117            #expect(await a.sync() == .completed)118            #expect(await b.sync() == .completed)119            #expect(await a.sync() == .completed)120            let merged = try await a.api.task(id: anchored.id)121            #expect(merged.title == "Live · ancrée (A)" && merged.status == "done" && merged.dueAt == nil && merged.completedAt != nil)122            for device in [a, b] {123                let local = try #require(try await device.tasks.task(id: anchored.id))124                #expect(local.title == merged.title && local.status == merged.status && local.dueAt == nil, "\(device.name) mirrors the server task")125                #expect(try await device.tasks.task(id: free.id)?.priority == "low")126                #expect(try await device.store.entityOpCount() == 0)127            }128129            // 5. canvas: different cards on each device → merged on the 409130            try await a.edit(canvas) { $0.nodes[0].text = "Hypothèse H1"; $0.nodes.append(Canvas.node("n3", "De A", y: 240)) }131            try await b.edit(canvas) { $0.nodes[1].x = 640; $0.nodes.append(Canvas.node("n4", "De B", y: 480)) }132            #expect(await a.sync() == .completed)133            #expect(await b.sync() == .completed)134            #expect(await a.sync() == .completed)135            let afterMerge = try CanvasDocument(data: try await a.api.canvas(pageID: canvas).data.data)136            #expect(Canvas.texts(afterMerge) == ["n1": "Hypothèse H1", "n2": "Données", "n3": "De A", "n4": "De B"])137            #expect(afterMerge.nodes.first { $0.id == "n2" }?.x == 640)138            #expect(afterMerge.edges.map(\.id) == ["e1"])139            for device in [a, b] {140                let state = try #require(try await device.canvases.state(pageId: canvas))141                #expect(state.document == afterMerge && !state.isDirty && !state.hasConflict, "\(device.name) mirrors the server canvas")142            }143144            // 6. the same card changed differently → a conflict on the second device, both copies kept; decided, then everywhere145            try await a.edit(canvas) { $0.nodes[0].text = "Version de A" }146            try await b.edit(canvas) { $0.nodes[0].text = "Version de B" }147            #expect(await a.sync() == .completed)148            #expect(await b.sync() == .completed)149            #expect(await b.engine.currentStatus().canvasConflicts == 1)150            let conflict = try #require(try await b.canvases.conflict(pageId: canvas))151            #expect(conflict.remote.nodes[0].text == "Version de A" && conflict.local.nodes[0].text == "Version de B")152            #expect(try CanvasDocument(data: try await a.api.canvas(pageID: canvas).data.data).nodes[0].text == "Version de A", "the server copy was not overwritten")153            try await b.canvases.resolve(conflict, .keepMine)154            #expect(await b.sync() == .completed)155            #expect(await a.sync() == .completed)156            #expect(try await a.canvases.state(pageId: canvas)?.document.nodes[0].text == "Version de B")157            #expect(await b.engine.currentStatus().canvasConflicts == 0)158159            // 7. deletions: a task deleted on A leaves B (soft delete in the feed); an edit queued behind it has nothing left to do160            try await a.tasks.delete(id: free.id)161            try await b.tasks.update(id: free.id, TaskEdit(title: "Trop tard"))162            #expect(await a.sync() == .completed)163            #expect(await b.sync() == .completed)164            #expect(await b.sync() == .completed)165            #expect(try await b.tasks.task(id: free.id) == nil)166            #expect(try await a.api.task(id: free.id).deletedAt != nil)167            #expect(await b.engine.currentStatus().rejected == 0)168169            // 8. the canvas page is purged (when the session is fresh enough): tombstones `page` + `canvas` reach the other device170            _ = try await a.api.trashPage(id: canvas)171            do {172                _ = try await a.api.purgePage(id: canvas)173                #expect(await b.sync() == .completed)174                #expect(try await b.store.canvas(pageId: canvas) == nil)175                #expect(try await b.store.page(id: canvas) == nil)176            } catch let error as APIError where error.needsReauth {177                // An older development token: the purge path is covered by the fake; the trash still reaches B.178                #expect(await b.sync() == .completed)179                #expect(try await b.store.page(id: canvas)?.deletedAt != nil)180            }181        } catch {182            Issue.record("live scenario failed: \(error)")183        }184        // clean up: the scratch database is never reset185        for id in taskIds { _ = try? await a.api.removeTask(id: id) }186        for id in pages { _ = try? await a.api.trashPage(id: id); _ = try? await a.api.purgePage(id: id) }187        await a.engine.stop(); await b.engine.stop()188        await a.store.close(); await b.store.close()189    }190}191192private extension LiveNextDevice {193    func sync() async -> SyncOutcome { await engine.sync() }194}195
Files main
Menu

Theme