SPB Git

Repository Public

TaskSyncTests.swift 17.8 KB 338 lines swift

1// SP Notes Core2// File: Tests/SPNotesSyncTests/TaskSyncTests.swift3// Description: Tasks edited offline (API-NEXT §4.2): client-chosen ids, the ordered outbox, idempotent retries after lost4//              answers, two devices on the same task, deletions, refused operations kept and surfaced, restart mid-queue.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import SPNotesAPI10import SPNotesStore11import Testing12@testable import SPNotesSync13@testable import SPNotesTestSupport1415@Suite("Task outbox (2.0)")16struct TaskSyncTests {17    @Test("a task created offline reaches the server under its own id, then the other device; a bare day is noon UTC")18    func createOfflineThenEverywhere() async throws {19        let world = World(apiLevel: 3)20        let fake = world.fake21        let a = try world.device("A"), b = try world.device("B")22        let page = try await a.create("Projet", [("b1", "texte")])23        a.setOffline(true)24        let task = try await a.tasks.create(title: "  Envoyer le plan  ", dueDay: "2026-11-21", priority: .high, pageId: page, blockId: "blk1")25        #expect(task.title == "Envoyer le plan")26        #expect(task.dueAt.map(APIDate.string(from:)) == "2026-11-21T12:00:00.000Z")27        #expect(try await a.tasks.list().map(\.id) == [task.id], "visible at once, offline")28        #expect(try await a.tasks.isPending(id: task.id))29        #expect(await a.sync() == .offline)30        #expect(try await a.store.entityOpCount(state: .pending) == 1)3132        a.setOffline(false)33        #expect(await a.sync() == .completed)34        let server = try #require(fake.task(task.id))35        #expect(server.title == "Envoyer le plan" && server.priority == "high" && server.pageId == page && server.blockId == "blk1")36        #expect(server.dueAt.map(APIDate.string(from:)) == "2026-11-21T12:00:00.000Z")37        #expect(fake.count("POST", "^/api/tasks$") == 1, "the page went first, then one creation")38        #expect(fake.requests.first { $0.method == "POST" && $0.path == "/api/tasks" }?.idempotencyKey == nil, "the client id is what makes it idempotent")39        try await expectTaskMirror(a)4041        #expect(await b.sync() == .completed)42        try await expectTaskMirror(b)43        #expect(try await b.tasks.list(pageId: page).map(\.id) == [task.id])44        await world.closeAll()45    }4647    @Test("lost answers: creation, update and deletion are each applied exactly once")48    func lostAnswers() async throws {49        let world = World(apiLevel: 3)50        let fake = world.fake51        let a = try world.device("A")52        let task = try await a.tasks.create(title: "Une fois")53        fake.inject(.dropResponse, method: "POST", path: "^/api/tasks$")54        #expect(await a.sync() == .offline)55        #expect(fake.task(task.id) != nil, "the server created it; the answer was lost")56        #expect(await a.sync() == .completed)57        #expect(fake.allTasks.count == 1)58        #expect(fake.requests.last { $0.method == "POST" && $0.path == "/api/tasks" }?.status == 200, "the retry got the stored task (x-existing)")59        try await expectTaskMirror(a)6061        try await a.tasks.update(id: task.id, TaskEdit(title: "Une fois, modifiée", status: .done))62        fake.inject(.dropResponse, method: "PATCH", path: "^/api/tasks/")63        #expect(await a.sync() == .offline)64        // Meanwhile the web reopens the task: the retry must not complete it again (same idempotency key → replay, not a second write).65        fake.webUpdateTask(task.id, status: "todo")66        #expect(await a.sync() == .completed)67        #expect(fake.task(task.id)?.status == "todo", "the lost update was applied once; the later change stands")68        #expect(fake.task(task.id)?.title == "Une fois, modifiée")69        try await expectTaskMirror(a)7071        try await a.tasks.delete(id: task.id)72        fake.inject(.dropResponse, method: "DELETE", path: "^/api/tasks/")73        #expect(await a.sync() == .offline)74        #expect(await a.sync() == .completed)75        #expect(fake.allTasks.isEmpty)76        try await expectTaskMirror(a)77        await world.closeAll()78    }7980    @Test("two devices edit the same task offline: different fields both win, the same field goes to the last one to arrive")81    func twoDevicesSameTask() async throws {82        let world = World(apiLevel: 3)83        let fake = world.fake84        let a = try world.device("A"), b = try world.device("B")85        let id = fake.webCreateTask(title: "Commune", priority: "medium")86        for device in [a, b] { #expect(await device.sync() == .completed) }8788        try await a.tasks.update(id: id, TaskEdit(title: "Titre de A", priority: .high))89        try await b.tasks.update(id: id, TaskEdit(status: .doing, dueAt: .value(Date(timeIntervalSince1970: 1_800_000_000))))90        try await b.tasks.update(id: id, TaskEdit(priority: .low))91        #expect(await a.sync() == .completed)92        #expect(await b.sync() == .completed)93        #expect(await a.sync() == .completed)94        let server = try #require(fake.task(id))95        #expect(server.title == "Titre de A", "A's field")96        #expect(server.status == "doing" && server.dueAt != nil, "B's fields")97        #expect(server.priority == "low", "same field: B arrived last")98        for device in [a, b] { try await expectTaskMirror(device) }99        await world.closeAll()100    }101102    @Test("a deletion wins over an edit made elsewhere; an edit queued behind it has nothing left to do")103    func deleteVersusEdit() async throws {104        let world = World(apiLevel: 3)105        let fake = world.fake106        let a = try world.device("A"), b = try world.device("B")107        let id = fake.webCreateTask(title: "Sursis")108        for device in [a, b] { #expect(await device.sync() == .completed) }109        try await a.tasks.delete(id: id)110        #expect(try await a.tasks.list(.all).isEmpty, "gone at once on the device that deleted it")111        try await b.tasks.update(id: id, TaskEdit(title: "Modifiée trop tard"))112        #expect(await a.sync() == .completed)113        #expect(await b.sync() == .completed)114        #expect(fake.task(id)?.deletedAt != nil)115        #expect(fake.task(id)?.title == "Sursis", "the edit was not applied to a deleted task")116        for device in [a, b] {117            #expect(await device.sync() == .completed)118            try await expectTaskMirror(device)119            #expect(await device.engine.currentStatus().rejected == 0)120        }121        await world.closeAll()122    }123124    @Test("the outbox keeps the order of a task: create, edits and delete queued offline replay faithfully")125    func orderedReplay() async throws {126        let world = World(apiLevel: 3)127        let fake = world.fake128        let a = try world.device("A")129        a.setOffline(true)130        let kept = try await a.tasks.create(title: "v1")131        try await a.tasks.update(id: kept.id, TaskEdit(title: "v2"))132        try await a.tasks.setDone(id: kept.id, true)133        try await a.tasks.update(id: kept.id, TaskEdit(title: "v3", dueAt: .value(Date(timeIntervalSince1970: 1_790_000_000))))134        try await a.tasks.update(id: kept.id, TaskEdit(dueAt: .null))135        let ephemeral = try await a.tasks.create(title: "éphémère")136        try await a.tasks.delete(id: ephemeral.id)137        a.setOffline(false)138        #expect(await a.sync() == .completed)139        let server = try #require(fake.task(kept.id))140        #expect(server.title == "v3" && server.status == "done" && server.dueAt == nil && server.completedAt != nil)141        #expect(fake.task(ephemeral.id)?.deletedAt != nil, "created then deleted, in that order")142        #expect(fake.requests.filter { $0.path.hasPrefix("/api/tasks") }.map(\.method) == ["POST", "PATCH", "PATCH", "PATCH", "PATCH", "POST", "DELETE"])143        try await expectTaskMirror(a)144        await world.closeAll()145    }146147    @Test("a task anchored to a page created offline: the page goes first, in the same sync call")148    func taskWaitsForItsPage() async throws {149        let world = World(apiLevel: 3)150        let fake = world.fake151        let a = try world.device("A")152        a.setOffline(true)153        let page = try await a.create("Nouvelle", [("b1", "x")])154        let task = try await a.tasks.create(title: "Ancrée", pageId: page)155        a.setOffline(false)156        fake.inject(.status(500), method: "POST", path: "^/api/pages$")     // the page creation fails once: the task must wait, not lose its anchor157        #expect(await a.sync() == .completed)158        #expect(fake.task(task.id) == nil)159        #expect(try await a.store.entityOps(state: .pending).count == 1)160        #expect(await a.sync() == .completed)161        #expect(fake.task(task.id)?.pageId == page)162        try await expectTaskMirror(a)163        await world.closeAll()164    }165166    @Test("a page in the server's trash: the creation of its task waits with backoff and goes when the page is back")167    func pageInServerTrash() async throws {168        let world = World(apiLevel: 3)169        let fake = world.fake170        let a = try world.device("A")171        let page = try await a.create("Dossier", [("b1", "x")])172        #expect(await a.sync() == .completed)173        fake.webTrash(page)174        let task = try await a.tasks.create(title: "En attente", pageId: page)   // the device has not seen the trash yet175        #expect(await a.sync() == .completed)176        let waiting = try await a.store.entityOps(kind: .task, entityId: task.id)177        #expect(waiting.count == 1 && waiting[0].state == .pending && waiting[0].attempts == 1 && waiting[0].lastError == "Unknown page", "not refused for good: retried later")178        #expect(await a.engine.currentStatus().rejected == 0)179        fake.webRestore(page)180        try await a.store.expediteEntityOps(id: waiting[0].id)      // the backoff (5 s) is over181        #expect(await a.sync() == .completed)182        #expect(fake.task(task.id)?.pageId == page)183        try await expectTaskMirror(a)184        await world.closeAll()185    }186187    @Test("an operation the server refuses for good is kept with its payload and surfaced; it blocks only its own task; retry and discard")188    func rejectedOperation() async throws {189        let world = World(apiLevel: 3)190        let fake = world.fake191        let a = try world.device("A")192        let refused = try await a.tasks.create(title: "Refusée")193        try await a.tasks.update(id: refused.id, TaskEdit(priority: .high))194        let other = try await a.tasks.create(title: "Autre")195        fake.inject(.status(400), method: "POST", path: "^/api/tasks$")196        #expect(await a.sync() == .completed, "one refused task does not fail the cycle")197        #expect(fake.task(other.id) != nil, "the other task went")198        #expect(fake.task(refused.id) == nil)199        var status = await a.engine.currentStatus()200        #expect(status.rejected == 1)201        #expect(status.pending == 1, "the update queued behind the refused creation waits")202        var operations = try await a.tasks.pendingOperations()203        #expect(operations.map(\.verb) == ["create", "update"])204        #expect(operations[0].state == .rejected && operations[0].lastError == "Injected failure 400")205        #expect(try await a.store.entityOps(state: .rejected).first?.payload != nil)206        #expect(try await a.tasks.task(id: refused.id)?.priority == "high", "the local task is untouched")207        // More cycles change nothing: no hammering, no loss.208        fake.clearLog()209        #expect(await a.sync() == .completed)210        #expect(fake.count("POST", "^/api/tasks$") == 0)211212        // Retry: the creation and then the update go through, in order.213        try await a.tasks.retry(operation: operations[0].id)214        #expect(await a.sync() == .completed)215        #expect(fake.task(refused.id)?.priority == "high")216        status = await a.engine.currentStatus()217        #expect(status.rejected == 0 && status.pending == 0)218        try await expectTaskMirror(a)219220        // Discard: the user abandons a refused creation; the task (and what was queued behind it) leaves the device.221        let doomed = try await a.tasks.create(title: "Abandonnée")222        try await a.tasks.setDone(id: doomed.id, true)223        fake.inject(.status(409, code: "id_taken"), method: "POST", path: "^/api/tasks$")224        #expect(await a.sync() == .completed)225        operations = try await a.tasks.pendingOperations()226        #expect(operations.first?.state == .rejected)227        try await a.tasks.discard(operation: operations[0].id)228        #expect(try await a.tasks.task(id: doomed.id) == nil)229        #expect(try await a.store.entityOpCount() == 0)230        #expect(await a.sync() == .completed)231        try await expectTaskMirror(a)232        await world.closeAll()233    }234235    @Test("discarding a refused edit puts the server's copy back on the device")236    func discardRestoresTheServerCopy() async throws {237        let world = World(apiLevel: 3)238        let fake = world.fake239        let a = try world.device("A")240        let id = fake.webCreateTask(title: "Serveur")241        #expect(await a.sync() == .completed)242        try await a.tasks.update(id: id, TaskEdit(title: "Locale"))243        fake.inject(.status(400), method: "PATCH", path: "^/api/tasks/")244        #expect(await a.sync() == .completed)245        let operation = try #require(try await a.tasks.pendingOperations().first)246        #expect(operation.state == .rejected)247        fake.webUpdateTask(id, priority: "high")248        try await a.tasks.discard(operation: operation.id)249        #expect(try await a.tasks.task(id: id)?.title == "Serveur")250        #expect(await a.sync() == .completed)251        try await expectTaskMirror(a)252        await world.closeAll()253    }254255    @Test("the app is killed in the middle of the queue: after the restart every operation goes exactly once")256    func restartMidQueue() async throws {257        let world = World(apiLevel: 3)258        let fake = world.fake259        let a = try world.device("A")260        var ids: [String] = []261        for i in 0..<6 { ids.append(try await a.tasks.create(title: "T\(i)").id) }262        try await a.tasks.update(id: ids[1], TaskEdit(title: "T1 bis"))263        try await a.tasks.delete(id: ids[4])264        // The first creation is held; the second one is applied but its answer is lost: the cycle stops in the middle of the queue.265        let gate = Gate()266        fake.inject(.hold(gate), method: "POST", path: "^/api/tasks$", count: 1)267        async let first = a.sync()268        await gate.reached()269        fake.inject(.dropResponse, method: "POST", path: "^/api/tasks$", count: 1)       // the 2nd creation is applied, its answer lost270        gate.open()271        #expect(await first == .offline)272        #expect(fake.allTasks.count == 2)273        try await a.restart()274        #expect(try await a.store.entityOpCount(state: .pending) == 7, "everything not acknowledged is still queued after the kill")275        #expect(await a.sync() == .completed)276        #expect(Set(fake.everyTask.map(\.id)) == Set(ids), "no duplicate, nothing missing")277        #expect(fake.task(ids[1])?.title == "T1 bis")278        #expect(fake.task(ids[4])?.deletedAt != nil)279        try await expectTaskMirror(a)280        await world.closeAll()281    }282283    @Test("server errors: a 500 on one task is retried with backoff and does not block the others; a failing server stops the cycle")284    func serverErrors() async throws {285        let world = World(apiLevel: 3)286        let fake = world.fake287        let a = try world.device("A")288        let first = try await a.tasks.create(title: "Première")289        let second = try await a.tasks.create(title: "Seconde")290        fake.inject(.status(500), method: "POST", path: "^/api/tasks$", count: 1)291        #expect(await a.sync() == .completed)292        #expect(fake.task(first.id) == nil && fake.task(second.id) != nil)293        let op = try #require(try await a.store.entityOps(kind: .task, entityId: first.id).first)294        #expect(op.state == .pending && op.attempts == 1 && op.nextAttemptAt > Date())295        fake.clearLog()296        #expect(await a.sync() == .completed)297        #expect(fake.count("POST", "^/api/tasks$") == 0, "in backoff: not sent again at once")298        try await a.store.expediteEntityOps(id: op.id)299        // A server that keeps failing: the cycle gives up after a few requests and nothing is lost.300        for i in 0..<5 { _ = try await a.tasks.create(title: "Lot \(i)") }301        fake.inject(.status(503), path: "^/api/tasks", count: 20)302        guard case .failed = await a.sync() else { Issue.record("expected a failed cycle"); return }303        fake.clearFaults()304        try await a.store.expediteEntityOps()305        #expect(await a.sync() == .completed)306        #expect(fake.allTasks.count == 7)307        try await expectTaskMirror(a)308        await world.closeAll()309    }310311    @Test("tasks changed on the web come back to the device (the 1.0 engine never pulled them)")312    func webChangesArrive() async throws {313        let world = World(apiLevel: 3)314        let fake = world.fake315        let a = try world.device("A")316        #expect(await a.sync() == .completed)317        let id = fake.webCreateTask(title: "Du web", priority: "low")318        #expect(await a.sync() == .completed)319        #expect(try await a.tasks.task(id: id)?.title == "Du web")320        fake.webUpdateTask(id, title: "Du web, renommée", status: "done")321        #expect(await a.sync() == .completed)322        #expect(try await a.tasks.list(.done).map(\.title) == ["Du web, renommée"])323        // A feed row that arrives while a local change waits does not overwrite it; the change goes on top.324        a.setOffline(true)325        try await a.tasks.update(id: id, TaskEdit(priority: .high))326        a.setOffline(false)327        fake.webUpdateTask(id, title: "Encore renommée")328        fake.inject(.status(500), method: "PATCH", path: "^/api/tasks/", count: 1)329        #expect(await a.sync() == .completed)330        #expect(try await a.tasks.task(id: id)?.priority == "high", "local change kept while it waits")331        try await a.store.expediteEntityOps()332        #expect(await a.sync() == .completed)333        #expect(fake.task(id)?.priority == "high" && fake.task(id)?.title == "Encore renommée")334        try await expectTaskMirror(a)335        await world.closeAll()336    }337}338
Files main
Menu

Theme