SPB Git

Repository Public

SyncEngineFakeServerTests.swift 51.2 KB 775 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Packages/SPMailCore/Tests/SPMailCoreTests/SyncEngineFakeServerTests.swift3// Description: The sync engine against the in-memory JMAP double (stub URLProtocol): anchor paging, failure injection (lost response after an4// accepted submission, 5xx bursts, cannotCalculateChanges, refused operations, interruption between pages), outbox backoff, draft coalescing5// and conflicts, the joinable pass, prefetch, attachment cache, Thread/get, EventSource resume, status model, detach, two devices.6import Foundation7import Testing8@testable import SPMailCore910/// Counts across the invocations of a `@Sendable` closure.11final class Counter: @unchecked Sendable {12    private let lock = NSLock()13    private var n = 014    func next() -> Int { lock.withLock { n += 1; return n } }15    var value: Int { lock.withLock { n } }16}1718struct Rig {19    let server: FakeMailServer20    let store: MailStore21    let engine: SyncEngine22    let dir: URL23    init(server: FakeMailServer = FakeMailServer(), account: String = "A", _ configure: (inout SyncEngine.Configuration) -> Void = { _ in }) throws {24        self.server = server25        (store, _, dir) = try tempStore()26        engine = server.engine(store, account: account, configure: configure)27    }28    func message(_ subject: String, text: String = "texte", html: String? = nil) -> OutgoingMessage {29        OutgoingMessage(from: EmailAddress(name: "Moi", email: server.address), to: [EmailAddress(email: "bob@stg.spboucher.ai")], subject: subject, text: text, html: html)30    }31    func cachedIds(_ box: String = "in") async throws -> [String] { try await store.threads("A", scope: .mailbox(box), threaded: false, limit: 5000).map(\.email.id) }32    func offline() { server.fault = { _, _ in .unreachable } }33    func online() { server.fault = nil }34}3536@Suite struct PaginationTests {37    // Item 5 — the old code paged with `position = number of cached rows`; three sparse rows made it skip three messages for good.38    @Test func olderPagesStartAtTheAnchorNotAtTheRowCount() async throws {39        let rig = try Rig { $0.initialWindow = 5; $0.pageSize = 5 }40        let ids = (1...30).map { rig.server.seed("M\($0)") } // m1 oldest … m30 newest41        try await rig.engine.fullSync() // window m30…m26, then the first older page m25…m2142        #expect(Set(try await rig.cachedIds()) == Set(ids[20...]))43        #expect(try await rig.store.folderSync("A", mailboxId: "in") == FolderSyncState(anchorReceivedAt: ISODate.parse(rig.server.email("m21")?["receivedAt"].stringValue), anchorId: "m21"))44        // sparse old rows arrive by other paths: a message opened from elsewhere, a search, a delta update of an old message45        try await rig.engine.ensureCached(ids: ["m3", "m4"])46        _ = try await rig.engine.search(SearchFilter(text: "M1"), limit: 3) // M19, M18, M1747        rig.server.patch("m9", ["keywords/$flagged": true])48        try await rig.engine.deltaSync()49        #expect(try await rig.cachedIds().count == 16)50        // the list can leave the sparse rows out, so they never sit right under the last loaded page51        #expect(try await rig.store.threads("A", scope: .mailbox("in"), threaded: false, withinHorizon: true).map(\.email.id) == ids[20...].reversed())52        // each page is exactly the next five, whatever else the cache holds53        #expect(try await rig.engine.loadOlder(mailboxId: "in") == 5)54        #expect(Set(try await rig.cachedIds()).isSuperset(of: ["m20", "m19", "m18", "m17", "m16"]))55        #expect(try await rig.store.folderSync("A", mailboxId: "in")?.anchorId == "m16")56        var pages = 057        while try await rig.engine.loadOlder(mailboxId: "in") > 0, pages < 20 { pages += 1 }58        let cachedAtEnd = Set(try await rig.cachedIds())59        #expect(cachedAtEnd == Set(ids), "gap: \(Set(ids).subtracting(cachedAtEnd).sorted())")60        #expect(await rig.engine.hasOlder(mailboxId: "in") == false)61        #expect(try await rig.store.folderSync("A", mailboxId: "in")?.isComplete == true)62        let queries = rig.server.count("Email/query")63        #expect(try await rig.engine.loadOlder(mailboxId: "in") == 0)64        #expect(rig.server.count("Email/query") == queries) // a complete folder costs no request65    }6667    @Test func pagingFallsBackOnDatesWhenTheAnchorIsGoneOrUnsupported() async throws {68        for anchorSupport in [true, false] {69            let rig = try Rig { $0.initialWindow = 4; $0.pageSize = 4 }70            rig.server.supportsAnchor = anchorSupport71            let ids = (1...22).map { rig.server.seed("M\($0)") }72            try await rig.engine.fullSync()73            let anchor = try #require(try await rig.store.folderSync("A", mailboxId: "in")?.anchorId)74            rig.server.destroy(anchor) // the anchor leaves the folder before the next page is asked75            var pages = 076            while try await rig.engine.loadOlder(mailboxId: "in") > 0, pages < 20 { pages += 1 }77            #expect(Set(try await rig.cachedIds()).isSuperset(of: Set(ids).subtracting([anchor])), "anchor support \(anchorSupport)")78        }79        // many messages within the same second (an import): the date fallback still reaches every one of them80        let rig = try Rig { $0.initialWindow = 5; $0.pageSize = 5 }81        rig.server.supportsAnchor = false82        let t = Date(timeIntervalSince1970: 1_700_000_000)83        let ids = (1...17).map { rig.server.seed("Même seconde \($0)", at: t) } + [rig.server.seed("Plus vieux", at: t.addingTimeInterval(-3600))]84        try await rig.engine.fullSync()85        var pages = 086        while try await rig.engine.loadOlder(mailboxId: "in") > 0, pages < 20 { pages += 1 }87        #expect(Set(try await rig.cachedIds()) == Set(ids))88    }8990    // Failure injection: interruption between two pages of a delta.91    @Test func deltaInterruptedBetweenPagesResumesFromTheLastPage() async throws {92        let rig = try Rig { $0.maxChanges = 2 }93        rig.server.seed("Avant")94        try await rig.engine.fullSync()95        let before = try await rig.store.state("A", "Email")96        let fresh = (1...6).map { rig.server.seed("Nouveau \($0)") }97        let events = Recorder(rig.engine.events)98        rig.server.fault = { r, nth in r.methods.first == "Email/changes" && nth == 2 ? .unreachable : nil }99        await #expect(throws: APIError.self) { try await rig.engine.deltaSync() }100        let half = try await rig.store.knownIds("A", among: fresh)101        let middle = try await rig.store.state("A", "Email")102        #expect(half.count == 2 && middle != before && middle != rig.server.currentEmailState) // page 1 applied AND its state stored103        try await Task.sleep(for: .milliseconds(50))104        #expect(events.all.contains { if case .newMail(let l) = $0 { return l.count == 2 } else { return false } }) // what page 1 brought is announced105        rig.online()106        let pagesBefore = rig.server.count("Email/changes")107        let r = try await rig.engine.deltaSync()108        #expect(!r.wasFull && r.changed == 4 && r.newMail.count == 4) // only the rest is fetched: nothing twice, nothing skipped109        #expect(rig.server.count("Email/changes") - pagesBefore == 2)110        #expect(try await rig.store.knownIds("A", among: fresh).count == 6)111        #expect(try await rig.store.state("A", "Email") == rig.server.currentEmailState)112    }113}114115@Suite struct PendingOperationTests {116    func rigWithThree() async throws -> (Rig, [String]) {117        let rig = try Rig { $0.maxPendingAttempts = 3 }118        let ids = ["Un", "Deux", "Trois"].map { rig.server.seed($0) }119        try await rig.engine.fullSync()120        rig.offline()121        await rig.engine.setFlagged(true, ids: [ids[0]])122        await rig.engine.setKeyword("$pinned", true, ids: [ids[1]])123        await rig.engine.setKeyword("lbl_1a2b3c4d", true, ids: [ids[2]])124        #expect(try await rig.store.pending("A").count == 3)125        rig.online()126        return (rig, ids)127    }128129    // Item 6 — a method-level error on the replay used to throw out of `flushPending` on every pass, forever (no delta sync ever again).130    @Test func aRefusedOperationIsDroppedRecordedAndTheOthersApplied() async throws {131        let (rig, ids) = try await rigWithThree()132        let activity = Recorder(rig.engine.activity)133        // the server rejects the whole Email/set as soon as it carries the second message134        rig.server.fault = { r, _ in r.methods == ["Email/set"] && r.mentions("\"\(ids[1])\"") ? .methodError(method: "Email/set", type: "invalidArguments") : nil }135        rig.server.seed("Arrivé pendant ce temps")136        try await rig.engine.syncNow() // must not throw…137        #expect(try await rig.cachedIds().count == 4) // …and the delta sync still ran138        #expect(try await rig.store.pending("A").isEmpty)139        let rejected = try await rig.store.rejectedOperations("A")140        #expect(rejected.map(\.emailId) == [ids[1]] && rejected.first?.error.contains("invalidArguments") == true && rejected.first?.patch["keywords/$pinned"].boolValue == true)141        #expect(rig.server.email(ids[0])?["keywords"]["$flagged"].boolValue == true && rig.server.email(ids[2])?["keywords"]["lbl_1a2b3c4d"].boolValue == true) // the valid ones went through142        #expect(try await rig.store.email("A", id: ids[1])?.keywords.contains("$pinned") == false) // server wins on the refused one143        #expect(try await rig.store.email("A", id: ids[2])?.keywords == ["lbl_1a2b3c4d"]) // label keywords round-trip144        try await Task.sleep(for: .milliseconds(50))145        #expect(activity.all.contains { if case .operationsRejected(let l) = $0 { return l.map(\.emailId) == [ids[1]] } else { return false } })146        try await rig.engine.syncNow() // and the next pass is clean147        try await rig.store.clearRejectedOperations("A")148        #expect(try await rig.store.rejectedOperations("A").isEmpty)149    }150151    @Test func aRefusalPerMessageDropsOnlyThatMessage() async throws {152        let (rig, ids) = try await rigWithThree()153        rig.server.refusedUpdates[ids[1]] = "invalidPatch"154        rig.server.destroy(ids[2]) // gone on the server meanwhile: notFound155        try await rig.engine.syncNow()156        #expect(try await rig.store.pending("A").isEmpty)157        let rejected = try await rig.store.rejectedOperations("A")158        #expect(Set(rejected.map(\.emailId)) == [ids[1], ids[2]] && rejected.contains { $0.error.hasPrefix("invalidPatch") } && rejected.contains { $0.error.hasPrefix("notFound") })159        #expect(rig.server.email(ids[0])?["keywords"]["$flagged"].boolValue == true)160        #expect(try await rig.store.email("A", id: ids[2]) == nil) // nothing resurrected161    }162163    // Failure injection: a burst of 5xx. Operations are kept, the pass goes on, nothing is dropped, everything lands once the burst is over.164    @Test func fiveHundredBurstKeepsEveryOperationAndThePassGoesOn() async throws {165        let (rig, ids) = try await rigWithThree()166        let burst = Counter()167        rig.server.fault = { r, _ in r.methods == ["Email/set"] && burst.next() <= 2 ? .status(503) : nil }168        rig.server.seed("Pendant la rafale")169        try await rig.engine.syncNow() // the replay is put off; the delta still runs170        #expect(try await rig.cachedIds().count == 4)171        var ops = try await rig.store.pending("A")172        #expect(ops.count == 3 && ops.allSatisfy { $0.attempts == 1 && $0.lastError != nil })173        #expect(try await rig.store.email("A", id: ids[0])?.isFlagged == true) // what the person did still shows174        try await rig.engine.syncNow() // second failure: the batch is taken apart, the healthy operations pass175        ops = try await rig.store.pending("A")176        #expect(ops.count == 1 && ops[0].attempts == 2)177        try await rig.engine.syncNow()178        #expect(try await rig.store.pending("A").isEmpty)179        #expect(try await rig.store.rejectedOperations("A").isEmpty)180        for (id, k) in zip(ids, ["$flagged", "$pinned", "lbl_1a2b3c4d"]) { #expect(rig.server.email(id)?["keywords"][k].boolValue == true) }181    }182183    @Test func anOperationTheServerChokesOnForeverIsGivenUpNotRetriedForever() async throws {184        let (rig, ids) = try await rigWithThree()185        rig.server.fault = { r, _ in r.methods == ["Email/set"] && r.mentions("\"\(ids[1])\"") ? .status(500) : nil }186        var passes = 0187        while try await !rig.store.pending("A").isEmpty, passes < 10 { try await rig.engine.syncNow(); passes += 1 }188        #expect(passes <= 4)189        let rejected = try await rig.store.rejectedOperations("A")190        #expect(rejected.map(\.emailId) == [ids[1]] && rejected.first?.error.contains("gave up after 3 attempts") == true)191        #expect(rig.server.email(ids[0])?["keywords"]["$flagged"].boolValue == true && rig.server.email(ids[2])?["keywords"]["lbl_1a2b3c4d"].boolValue == true)192    }193194    @Test func offlineStillThrowsAndKeepsTheQueue() async throws {195        let (rig, _) = try await rigWithThree()196        rig.offline()197        await #expect(throws: APIError.self) { try await rig.engine.syncNow() }198        let ops = try await rig.store.pending("A")199        #expect(ops.count == 3 && ops.allSatisfy { $0.attempts == 0 }) // a transport failure is not an attempt200    }201202    // Item 8 + failure injection `cannotCalculateChanges`: the recovery full sync keeps what was done offline and the bodies already read.203    @Test func fullResyncKeepsPendingOperationsAndCachedBodies() async throws {204        let rig = try Rig()205        let ids = ["Un", "Deux", "Trois"].map { rig.server.seed($0, text: "corps de \($0)") }206        try await rig.engine.fullSync()207        for id in ids { _ = try await rig.engine.body(for: id) }208        rig.offline()209        await rig.engine.setFlagged(true, ids: [ids[0]])210        await rig.engine.move(ids: [ids[1]], to: "tr")211        rig.online()212        rig.server.destroy(ids[2])213        rig.server.forgetHistory() // every delta from our state now answers cannotCalculateChanges214        let r = try await rig.engine.deltaSync()215        #expect(r.wasFull)216        #expect(try await rig.store.pending("A").count == 2) // the old code deleted them here: the flag and the move were silently lost217        #expect(try await rig.store.email("A", id: ids[0])?.isFlagged == true) // re-applied on the refetched copies218        #expect(try await rig.store.email("A", id: ids[1])?.mailboxIds == ["tr"])219        #expect(rig.server.email(ids[0])?["keywords"]["$flagged"].boolValue != true) // not on the server yet220        rig.offline()221        #expect(try await rig.engine.body(for: ids[0]).text == "corps de Un") // still readable offline222        #expect(try await rig.engine.body(for: ids[1]).text == "corps de Deux")223        #expect(try await rig.store.body("A", id: ids[2]) == nil) // the body of a message that no longer exists is not kept224        rig.online()225        try await rig.engine.syncNow()226        #expect(try await rig.store.pending("A").isEmpty && rig.server.email(ids[0])?["keywords"]["$flagged"].boolValue == true && rig.server.email(ids[1])?["mailboxIds"]["tr"].boolValue == true)227    }228}229230@Suite struct IdempotentSendTests {231    // Item 3 + failure injection: the server accepted the submission, the answer was lost. Before: the message was created and submitted again.232    /// [header filter works, EmailSubmission/query works, header filter answers but finds nothing (the real mail server's behaviour)]233    @Test(arguments: [[true, true, false], [false, true, false], [true, false, false], [false, false, false], [true, true, true], [true, false, true]])234    func lostResponseAfterAcceptanceIsNeverSentTwice(_ support: [Bool]) async throws {235        let rig = try Rig()236        rig.server.supportsHeaderFilter = support[0]237        rig.server.supportsSubmissionQuery = support[1]238        rig.server.headerFilterFindsNothing = support[2]239        try await rig.engine.fullSync()240        let activity = Recorder(rig.engine.activity)241        rig.server.fault = { r, nth in r.methods.contains("EmailSubmission/set") && nth == 1 ? .lostResponse : nil }242        let queued = await rig.engine.send(OutboxItem(account: "A", message: rig.message("Une seule fois")))243        #expect(queued.state == .queuedOffline && queued.submissionId == nil && queued.submissionUncertain == true) // honest: we do not know244        let mid = try #require(queued.message.messageId)245        #expect(rig.server.submissionCount == 1) // …but the server did accept it246        rig.online()247        try await rig.engine.syncNow()248        let done = try #require(try await rig.store.outboxItem(queued.id))249        #expect(done.state == .accepted && done.message.messageId == mid && done.submissionUncertain == nil, "state \(done.state) \(done.lastError ?? "")")250        #expect(rig.server.submissionCount == 1 && rig.server.count("EmailSubmission/set") == 1) // no second submission251        #expect(rig.server.allEmails.filter { $0["subject"].stringValue == "Une seule fois" }.count == 1) // no second copy252        #expect(done.serverEmailId == rig.server.emails(in: "se").first?["id"].stringValue)253        #expect((done.submissionId != nil) == support[1])254        try await Task.sleep(for: .milliseconds(50))255        #expect(activity.all.contains(.duplicateSendAvoided(outboxId: queued.id)))256        for _ in 0..<3 { await rig.engine.flushOutbox() }257        #expect(rig.server.submissionCount == 1)258    }259260    @Test func aMessageStoredButNotSubmittedIsSubmittedFromItsStoredCopy() async throws {261        let rig = try Rig()262        try await rig.engine.fullSync()263        // the server stores the message, refuses the submission, and that answer is lost264        rig.server.submissionError = "serverFail"265        rig.server.fault = { r, nth in r.methods.contains("EmailSubmission/set") && nth == 1 ? .lostResponse : nil }266        let queued = await rig.engine.send(OutboxItem(account: "A", message: rig.message("Stocké pas soumis")))267        #expect(queued.state == .queuedOffline && rig.server.submissionCount == 0 && rig.server.emails(in: "dr").count == 1)268        rig.online()269        rig.server.submissionError = nil270        try await rig.engine.syncNow()271        let done = try #require(try await rig.store.outboxItem(queued.id))272        #expect(done.state == .accepted && done.submissionId != nil)273        #expect(rig.server.submissionCount == 1 && rig.server.allEmails.count == 1 && rig.server.emails(in: "se").count == 1 && rig.server.emails(in: "dr").isEmpty)274    }275276    @Test func aRequestThatNeverReachedTheServerIsSimplySentOnce() async throws {277        let rig = try Rig()278        try await rig.engine.fullSync()279        rig.server.fault = { r, _ in r.methods.contains("EmailSubmission/set") ? .unreachable : nil }280        let queued = await rig.engine.send(OutboxItem(account: "A", message: rig.message("Jamais parti")))281        #expect(queued.state == .queuedOffline && rig.server.allEmails.isEmpty)282        rig.online()283        try await rig.engine.syncNow()284        #expect(try await rig.store.outboxItem(queued.id)?.state == .accepted && rig.server.submissionCount == 1 && rig.server.allEmails.count == 1)285        #expect(rig.server.allEmails.first?["messageId"].stringArray == [try #require(queued.message.messageId)]) // the Message-ID given at queue time is the one that left286    }287288    @Test func anItemInterruptedWhileSendingIsCheckedBeforeAnyResubmission() async throws {289        let rig = try Rig()290        try await rig.engine.fullSync()291        let sent = await rig.engine.send(OutboxItem(account: "A", message: rig.message("Tué en vol")))292        #expect(sent.state == .accepted)293        // the app was killed after the server accepted and before the answer was recorded: the stored item still says `sending`294        var crashed = sent295        crashed.state = .sending; crashed.submissionId = nil; crashed.serverEmailId = nil; crashed.serverCopyIsDraft = nil296        try await rig.store.saveOutbox(crashed)297        let relaunched = rig.server.engine(rig.store)298        await relaunched.flushOutbox()299        let after = try #require(try await rig.store.outboxItem(sent.id))300        #expect(after.state == .accepted && after.submissionId == sent.submissionId && rig.server.submissionCount == 1 && rig.server.allEmails.count == 1)301    }302303    // Item 4 — `destroy: [serverEmailId]` used to run on every submission, so sending an accepted item again destroyed the copy in Sent.304    @Test func sendingAnAcceptedItemAgainNeverDestroysTheSentCopy() async throws {305        let rig = try Rig()306        try await rig.engine.fullSync()307        let first = await rig.engine.send(OutboxItem(account: "A", message: rig.message("Copie envoyée")))308        let sentId = try #require(first.serverEmailId)309        #expect(first.state == .accepted && first.serverCopyIsDraft == false && rig.server.email(sentId)?["mailboxIds"]["se"].boolValue == true)310        // a double tap: the composer's copy still says `draft` while the store already holds the accepted item — nothing leaves twice311        var stale = first312        stale.state = .draft; stale.submissionId = nil; stale.serverEmailId = nil313        let tapped = await rig.engine.send(stale)314        #expect(tapped.state == .accepted && tapped.submissionId == first.submissionId && rig.server.submissionCount == 1)315        let second = await rig.engine.send(first) // an explicit « send again » of an accepted item316        #expect(second.state == .accepted && second.id != first.id && second.serverEmailId != sentId && second.message.messageId != first.message.messageId)317        #expect(rig.server.email(sentId) != nil && rig.server.emails(in: "se").count == 2 && rig.server.submissionCount == 2)318        #expect(try await rig.store.outboxItem(first.id)?.state == .accepted) // the first record is intact319        // an item shaped as 1.1.0 left it — queued again, still pointing at the sent copy, no `serverCopyIsDraft`320        var legacy = first321        legacy.id = UUID().uuidString; legacy.state = .queuedOffline; legacy.submissionId = nil; legacy.serverCopyIsDraft = nil; legacy.message.messageId = nil322        try await rig.store.saveOutbox(legacy)323        await rig.engine.flushOutbox()324        #expect(try await rig.store.outboxItem(legacy.id)?.state == .accepted)325        #expect(rig.server.email(sentId) != nil && rig.server.emails(in: "se").count == 3) // asked the server first: not a draft, not destroyed326        // discarding never destroys a submitted message either327        await rig.engine.discardDraft(id: first.id)328        #expect(rig.server.email(sentId) != nil)329    }330331    // Item 10 — per-item backoff: a message that keeps failing is not resubmitted by every pass.332    @Test func outboxBacksOffPerItemAndTellsWhen() async throws {333        let rig = try Rig { $0.outboxBackoff = Backoff(base: 5, factor: 2, maximum: 900, jitter: 0.2) }334        try await rig.engine.fullSync()335        rig.server.fault = { r, _ in r.methods.contains("EmailSubmission/set") ? .status(503) : nil }336        let t0 = Date()337        var item = await rig.engine.send(OutboxItem(account: "A", message: rig.message("Serveur en panne")))338        let wait1 = try #require(item.nextAttemptAt).timeIntervalSince(t0)339        #expect(item.state == .queuedOffline && item.attempts == 1 && wait1 >= 3.9 && wait1 <= 6.5 && item.isBackingOff() && item.lastError != nil)340        for _ in 0..<5 { try await rig.engine.syncNow() } // five passes while the item waits341        #expect(rig.server.count("EmailSubmission/set") == 1, "retry storm: \(rig.server.count("EmailSubmission/set")) submissions")342        // when its time comes it is tried once, and waits about twice as long343        item = try #require(try await rig.store.outboxItem(item.id))344        item.nextAttemptAt = Date().addingTimeInterval(-1)345        try await rig.store.saveOutbox(item)346        let t1 = Date()347        await rig.engine.flushOutbox()348        item = try #require(try await rig.store.outboxItem(item.id))349        let wait2 = try #require(item.nextAttemptAt).timeIntervalSince(t1)350        #expect(rig.server.count("EmailSubmission/set") == 2 && item.attempts == 2 && wait2 >= 7.9 && wait2 <= 12.5)351        // « retry now » does not wait, and the message leaves exactly once352        rig.online()353        let done = await rig.engine.send(item)354        #expect(done.state == .accepted && done.nextAttemptAt == nil && rig.server.submissionCount == 1 && rig.server.allEmails.count == 1)355    }356357    // The submission alone fails at the transport level (a large message on a bad link) while the rest of the sync works: the reconnection358    // shortcut applies once, then the item's own delay — not one submission per pass.359    @Test func aSubmissionThatKeepsFailingWhileTheSyncWorksIsNotRetriedOnEveryPass() async throws {360        let rig = try Rig()361        try await rig.engine.fullSync()362        rig.server.fault = { r, _ in r.methods.contains("EmailSubmission/set") ? .unreachable : nil }363        let queued = await rig.engine.send(OutboxItem(account: "A", message: rig.message("Lien instable")))364        #expect(queued.state == .queuedOffline)365        for _ in 0..<6 { try await rig.engine.syncNow() }366        #expect(rig.server.count("EmailSubmission/set") == 2, "\(rig.server.count("EmailSubmission/set")) submissions in 6 passes") // the first, one on « reconnection », then it waits367        let item = try #require(try await rig.store.outboxItem(queued.id))368        #expect(item.attempts == 2 && item.isBackingOff() && rig.server.allEmails.isEmpty)369    }370371    @Test func failedDistinguishesPermanentFromRetryable() async throws {372        let rig = try Rig()373        try await rig.engine.fullSync()374        rig.server.submissionError = "forbiddenFrom"375        let refused = await rig.engine.send(OutboxItem(account: "A", message: rig.message("Refusé pour de bon")))376        #expect(refused.state == .failed && refused.failureKind == .permanent && refused.isPermanentFailure && !refused.isRetryableFailure && refused.nextAttemptAt == nil && refused.lastError?.contains("forbiddenFrom") == true)377        let n = rig.server.count("EmailSubmission/set")378        for _ in 0..<3 { await rig.engine.flushOutbox() }379        #expect(rig.server.count("EmailSubmission/set") == n) // never retried by itself380        rig.server.submissionError = "serverFail"381        var temporary = await rig.engine.send(OutboxItem(account: "A", message: rig.message("Refusé pour l’instant")))382        #expect(temporary.state == .failed && temporary.failureKind == .retryable && temporary.isRetryableFailure && temporary.nextAttemptAt != nil && temporary.isBackingOff())383        let m = rig.server.count("EmailSubmission/set")384        await rig.engine.flushOutbox()385        #expect(rig.server.count("EmailSubmission/set") == m) // not before its time386        rig.server.submissionError = nil387        temporary.nextAttemptAt = Date().addingTimeInterval(-1)388        try await rig.store.saveOutbox(temporary)389        await rig.engine.flushOutbox()390        #expect(try await rig.store.outboxItem(temporary.id)?.state == .accepted)391        #expect(rig.server.allEmails.filter { $0["subject"].stringValue == "Refusé pour l’instant" }.count == 1) // the copy of the failed attempt was replaced, not duplicated392        #expect(await rig.engine.pendingWorkCount() == 0)393    }394}395396@Suite struct DraftSyncTests {397    // Item 11 — an unchanged draft costs nothing; saves of one draft never overlap.398    @Test func unchangedDraftsAreNotPushedAndSavesAreSerialised() async throws {399        let rig = try Rig()400        try await rig.engine.fullSync()401        var item = try await rig.engine.saveDraft(OutboxItem(account: "A", message: rig.message("Brouillon", text: "v1")))402        item = try #require(try await rig.engine.syncDraft(id: item.id))403        let first = try #require(item.serverEmailId)404        #expect(rig.server.count("Email/set") == 1 && !item.needsDraftSync && item.serverCopyIsDraft == true)405        // the autosave timer fires again with the same content: nothing is written, nothing is sent406        for _ in 0..<5 {407            let again = try await rig.engine.saveDraft(item)408            #expect(again.updatedAt == item.updatedAt && !again.needsDraftSync)409            _ = try await rig.engine.syncDraft(id: item.id)410        }411        #expect(rig.server.count("Email/set") == 1 && rig.server.emails(in: "dr").map { $0["id"].stringValue } == [first])412        // a burst of edits while the server is slow: calls queue up behind one another instead of overlapping413        rig.server.delay = { r in r.methods == ["Email/set"] ? 0.08 : 0 }414        let engine = rig.engine415        await withTaskGroup(of: Void.self) { g in416            for n in 2...6 {417                var edit = item418                edit.message.text = "v\(n)"419                let e = edit420                g.addTask { _ = try? await engine.saveDraft(e); _ = try? await engine.syncDraft(id: e.id) }421            }422        }423        _ = try await rig.engine.syncDraft(id: item.id)424        let drafts = rig.server.emails(in: "dr")425        let final = try #require(try await rig.store.outboxItem(item.id))426        #expect(drafts.count == 1, "overlapping saves left \(drafts.count) copies on the server")427        #expect(drafts.first?["bodyValues"]["t"]["value"].stringValue == final.message.text && drafts.first?["id"].stringValue == final.serverEmailId && !final.needsDraftSync)428        #expect(rig.server.count("Email/set") <= 6)429        // discarding removes our draft copy430        await rig.engine.discardDraft(id: item.id)431        #expect(rig.server.emails(in: "dr").isEmpty)432    }433434    // Two devices: a draft edited on both is not lost.435    @Test func aDraftEditedOnTwoDevicesKeepsBothVersions() async throws {436        let server = FakeMailServer()437        let a = try Rig(server: server), b = try Rig(server: server), c = try Rig(server: server)438        for r in [a, b, c] { try await r.engine.fullSync() }439        var onA = try await a.engine.saveDraft(OutboxItem(account: "A", message: a.message("Brouillon partagé", text: "version de départ", html: "<div>version de <b>départ</b></div>")))440        onA = try #require(try await a.engine.syncDraft(id: onA.id))441        try await b.engine.deltaSync(); try await c.engine.deltaSync()442        let sharedId = try #require(onA.serverEmailId)443        let shared = try #require(try await b.store.email("A", id: sharedId))444        var onB = try await b.engine.adoptServerDraft(shared)445        let onC = try await c.engine.adoptServerDraft(try #require(try await c.store.email("A", id: shared.id)))446        #expect(HTMLText.html(fromAttributed: onB.message.editableBody) == "<div>version de <b>départ</b></div>") // formatting survives adoption (item 2)447        // A edits and saves: the shared copy is replaced448        onA.message.text = "version de A"; onA.message.html = nil449        onA = try await a.engine.saveDraft(onA)450        onA = try #require(try await a.engine.syncDraft(id: onA.id))451        // B, which has not synced, edits its own copy and saves452        let activity = Recorder(b.engine.activity)453        onB.message.text = "version de B"; onB.message.html = nil454        onB = try await b.engine.saveDraft(onB)455        onB = try #require(try await b.engine.syncDraft(id: onB.id))456        let texts = Set(server.emails(in: "dr").compactMap { $0["bodyValues"]["t"]["value"].stringValue })457        #expect(texts == ["version de A", "version de B"], "a version was overwritten: \(texts)") // conflict resolution = no data loss458        #expect(onB.conflictedAt != nil && onA.conflictedAt == nil && onB.serverEmailId != onA.serverEmailId)459        try await Task.sleep(for: .milliseconds(50))460        #expect(activity.all.contains(.draftConflict(outboxId: onB.id)))461        // both devices see both drafts after a delta462        try await a.engine.deltaSync(); try await b.engine.deltaSync()463        #expect(Set(try await a.cachedIds("dr")) == Set(try await b.cachedIds("dr")))464        #expect(try await a.cachedIds("dr").count == 2)465        #expect(try await a.store.outboxItem(onA.id) != nil) // each keeps the draft it is writing466        #expect(try await b.store.outboxItem(onB.id) != nil)467        // C only mirrored the shared copy and changed nothing: its stale local copy goes, the two live versions are in its Drafts folder468        try await c.engine.deltaSync()469        #expect(try await c.store.outboxItem(onC.id) == nil)470        #expect(try await c.cachedIds("dr").count == 2)471    }472473    @Test func serverDraftsAreAdoptedWithoutFlattening() async throws {474        let rig = try Rig()475        let quote = OutgoingMessage.wrapQuote(#"<p>Le 3 mars, Alice a écrit :</p><blockquote type="cite"><table><tr><td>cellule</td></tr></table></blockquote>"#)476        let html = "<div>Ma <i>réponse</i></div>" + quote477        let id = rig.server.seed("Re: Projet", box: "dr", keywords: ["$draft", "$seen"], html: html, text: "Ma réponse\n\nLe 3 mars, Alice a écrit :\n> cellule")478        try await rig.engine.fullSync()479        let adopted = try await rig.engine.adoptServerDraft(try #require(try await rig.store.email("A", id: id)))480        #expect(adopted.message.fullHTML == html && adopted.message.quotedHTML == quote && adopted.message.text == "Ma réponse" && adopted.serverCopyIsDraft == true)481        #expect(adopted.message.editableBody.runs.contains { $0.inlinePresentationIntent == .emphasized })482        // reopening and saving without a change does not replace the server copy483        _ = try await rig.engine.saveDraft(adopted)484        _ = try await rig.engine.syncDraft(id: adopted.id)485        #expect(rig.server.count("Email/set") == 0 && rig.server.email(id) != nil)486    }487}488489@Suite struct PassTests {490    // Item 7 — a background task must be able to wait for the sync that is already running, changes requested meanwhile included.491    @Test func backgroundEntryPointJoinsTheRunningPassThenRunsOnceMore() async throws {492        let rig = try Rig()493        rig.server.seed("Déjà là")494        try await rig.engine.fullSync()495        rig.server.delay = { r in r.methods.first == "Email/changes" ? 0.3 : 0 }496        let engine = rig.engine497        let running = Task { try await engine.syncNow() }498        try await eventually("pass started") { await engine.status == .syncing ? true : nil }499        try await Task.sleep(for: .milliseconds(80)) // the first Email/changes has been answered by now; its answer is on its way500        let late = rig.server.seed("Arrivé pendant la passe")501        // `syncNow` (interface entry point) returns at once: a background task ending here would end before the sync does502        let t0 = Date()503        try await engine.syncNow()504        #expect(Date().timeIntervalSince(t0) < 0.15)505        #expect(try await rig.store.email("A", id: late) == nil)506        // the awaitable entry point joins the pass, which goes round once more507        try await engine.syncNowAndWait()508        #expect(try await rig.store.email("A", id: late) != nil)509        #expect(rig.server.count("Email/changes") == 2 && Date().timeIntervalSince(t0) > 0.3)510        try await running.value511        #expect(await engine.status == .idle)512        // with no pass running it simply runs one513        let n = rig.server.count("Email/changes")514        try await engine.syncNowAndWait()515        #expect(rig.server.count("Email/changes") == n + 1)516        // and a failing pass fails for the joiner too517        rig.server.fault = { r, _ in r.methods.first == "Email/changes" ? .methodError(method: "Email/changes", type: "serverFail") : nil }518        let failing = Task { try await engine.syncNow() }519        try await eventually("pass started") { await engine.status == .syncing ? true : nil }520        await #expect(throws: JMAPMethodError.self) { try await engine.syncNowAndWait() }521        _ = await failing.result522    }523524    // Item 16 — idle / syncing / offline(pending) / error(message, retryAt), published on the activity stream.525    @Test func statusModelFollowsThePass() async throws {526        let rig = try Rig()527        let id = rig.server.seed("Un")528        try await rig.engine.fullSync()529        let activity = Recorder(rig.engine.activity)530        func statuses() -> [SyncStatus] { activity.all.compactMap { if case .status(let s) = $0 { return s } else { return nil } } }531        #expect(await rig.engine.status == .idle)532        try await rig.engine.syncNow()533        rig.offline()534        await rig.engine.setFlagged(true, ids: [id])535        #expect(await rig.engine.status == .offline(pending: 1))536        _ = await rig.engine.send(OutboxItem(account: "A", message: rig.message("En attente")))537        await #expect(throws: APIError.self) { try await rig.engine.syncNow() }538        #expect(await rig.engine.status == .offline(pending: 2))539        #expect(await rig.engine.pendingWorkCount() == 2)540        rig.server.fault = { r, _ in r.methods.first == "Email/changes" ? .status(500) : nil }541        await #expect(throws: APIError.self) { try await rig.engine.syncNow() }542        guard case .error(let message, let retryAt) = await rig.engine.status else { Issue.record("expected an error status, got \(await rig.engine.status)"); return }543        #expect(!message.isEmpty && retryAt == nil) // no live loop: nothing is scheduled, and the status does not pretend otherwise544        rig.online()545        try await rig.engine.syncNow()546        #expect(await rig.engine.status == .idle)547        try await Task.sleep(for: .milliseconds(50))548        let seen = statuses()549        #expect(seen.first == .syncing && seen.contains(.idle) && seen.contains(.offline(pending: 1)) && seen.contains(.offline(pending: 2)) && seen.last == .idle)550        #expect(zip(seen, seen.dropFirst()).allSatisfy { $0 != $1 }) // only changes are published551    }552553    // Item 15 + status: the live loop gives the time of its next attempt.554    @Test func reconnectionCostsExactlyOneDeltaSyncAndResumesWithLastEventID() async throws {555        let rig = try Rig()556        rig.server.seed("Un")557        try await rig.engine.fullSync()558        // every connection: the server announces where it stands (the state we hold), then drops the stream559        rig.server.eventScript = [[rig.server.stateEvent(id: "evt-7")]]560        await rig.engine.startLive()561        try await eventually("three connections", timeout: 10) { rig.server.paths(containing: "/eventsource").count >= 4 ? true : nil }562        await rig.engine.stopLive()563        try await Task.sleep(for: .milliseconds(200))564        let connections = rig.server.paths(containing: "/eventsource")565        let deltas = rig.server.count("Email/changes")566        #expect(deltas == connections.count || deltas == connections.count - 1, "\(deltas) delta syncs for \(connections.count) connections") // the last one may have been cut before its sync567        #expect(connections.first?.headers["Last-Event-ID"] == nil)568        #expect(connections.dropFirst().allSatisfy { $0.headers["Last-Event-ID"] == "evt-7" })569        // an event that announces a state we do not hold does trigger a sync570        let rig2 = try Rig()571        try await rig2.engine.fullSync()572        let unknown = "event: state\ndata: {\"@type\":\"StateChange\",\"changed\":{\"acc\":{\"Email\":\"99999\"}}}\n\n"573        rig2.server.eventScript = [[rig2.server.stateEvent(), unknown]]574        rig2.server.holdEventStreams = true575        await rig2.engine.startLive()576        try await eventually("delta after the pushed change") { rig2.server.count("Email/changes") >= 2 ? true : nil }577        try await Task.sleep(for: .milliseconds(200))578        #expect(rig2.server.count("Email/changes") == 2 && rig2.server.paths(containing: "/eventsource").count == 1)579        await rig2.engine.stopLive()580        // a server that is down: the status carries the time of the next attempt581        let rig3 = try Rig { $0.backoff = Backoff(base: 30, factor: 2, maximum: 300, jitter: 0) }582        try await rig3.engine.fullSync()583        rig3.server.fault = { r, _ in r.path.hasSuffix("/eventsource") ? .status(503) : nil }584        await rig3.engine.startLive()585        let retry = try await eventually("error status") { () -> Date? in if case .error(_, let at?) = await rig3.engine.status { return at } else { return nil } }586        #expect(retry.timeIntervalSinceNow > 20 && retry.timeIntervalSinceNow < 31)587        await rig3.engine.stopLive()588    }589}590591@Suite struct OfflineReadingTests {592    // Item 13 — body prefetch: bounded, cancellable, skipped in Low Data Mode.593    @Test func prefetchIsBoundedCancellableAndSkippedInLowDataMode() async throws {594        let lowData = FakeRouter.Flag()595        let rig = try Rig { $0.prefetchCount = 5; $0.prefetchChunk = 2; $0.isConstrained = { lowData.isSet } }596        let ids = (1...12).map { rig.server.seed("M\($0)", text: "corps \($0)") }597        try await rig.engine.fullSync()598        func bodyRequests() -> Int { rig.server.sync { rig.server.requests.filter { $0.mentions("fetchAllBodyValues") }.count } }599        #expect(await rig.engine.prefetchNewest() == 5)600        #expect(try await rig.store.bodyIds("A", among: ids) == Set(ids.suffix(5)) && bodyRequests() == 3) // 2 + 2 + 1601        #expect(await rig.engine.prefetchNewest() == 0 && bodyRequests() == 3) // nothing fetched twice602        rig.offline()603        #expect(try await rig.engine.body(for: ids[11]).text == "corps 12") // readable offline without ever having been opened604        rig.online()605        // any list being shown can be handed over; still bounded606        #expect(await rig.engine.prefetchBodies(ids: Array(ids.prefix(7).reversed())) == 5)607        // Low Data Mode: not a single request608        lowData.set()609        let before = bodyRequests()610        #expect(await rig.engine.prefetchBodies(ids: ids, limit: 12) == 0)611        #expect(await rig.engine.prefetchNewest(count: 12) == 0)612        #expect(bodyRequests() == before)613614        // cancellation stops between two requests615        let rig2 = try Rig { $0.prefetchChunk = 1 }616        let many = (1...10).map { rig2.server.seed("N\($0)") }617        try await rig2.engine.fullSync()618        rig2.server.delay = { r in r.mentions("fetchAllBodyValues") ? 0.1 : 0 }619        let engine = rig2.engine620        let task = Task { await engine.prefetchBodies(ids: many, limit: 10) }621        try await Task.sleep(for: .milliseconds(250))622        task.cancel()623        let got = await task.value624        #expect(got >= 1 && got <= 4, "prefetched \(got) of 10 before the cancellation")625        try await Task.sleep(for: .milliseconds(300))626        #expect(try await rig2.store.bodyIds("A", among: many).count <= 4)627628        // after a pass the Inbox is prefetched by itself629        let rig3 = try Rig { $0.autoPrefetch = true; $0.prefetchCount = 3 }630        let auto = (1...6).map { rig3.server.seed("A\($0)") }631        try await rig3.engine.syncNow()632        _ = try await eventually("automatic prefetch") { try await rig3.store.bodyIds("A", among: auto).count == 3 ? true : nil }633    }634635    // Item 13 — attachments: sealed cache instead of a clear temporary file per opening.636    @Test func attachmentsAreServedFromTheSealedCache() async throws {637        let rig = try Rig()638        let payload = Data((0..<4000).map { UInt8($0 % 251) })639        rig.server.addBlob("blob-att", payload)640        let id = rig.server.seed("Avec pièce", attachments: [["blobId": "blob-att", "name": "rapport.pdf", "type": "application/pdf", "size": 4000, "disposition": "attachment"]])641        try await rig.engine.fullSync()642        let part = try #require(try await rig.engine.body(for: id).attachments.first)643        #expect(await rig.engine.cachedAttachment(part) == nil)644        #expect(try await rig.engine.fetchAttachment(part) == payload)645        #expect(try await rig.engine.download(part) == payload)646        #expect(await rig.engine.cachedAttachment(part) == payload)647        #expect(rig.server.paths(containing: "/download/").count == 1) // one download, then the cache648        rig.offline()649        #expect(try await rig.engine.fetchAttachment(part) == payload) // offline650        let file = try await rig.engine.attachmentFile(for: part)651        #expect(try Data(contentsOf: file) == payload && file.lastPathComponent == "rapport.pdf")652        #expect(!fileContains(rig.store.attachmentCacheDirectory, "rapport") && fileContains(rig.store.temporaryFilesDirectory.appendingPathComponent(file.deletingLastPathComponent().lastPathComponent), String(decoding: payload.prefix(1), as: UTF8.self)) == true)653        // an attachment that is not cached cannot be read offline, and says so654        let other = BodyPart(blobId: "blob-absent", size: 1, name: "x.bin", type: "application/octet-stream")655        await #expect(throws: APIError.self) { _ = try await rig.engine.fetchAttachment(other) }656    }657658    // Item 14 — the conversation comes from the server's thread, not from a SQL window over what happens to be cached.659    @Test func conversationIsCompletedFromTheServerThread() async throws {660        let rig = try Rig { $0.initialWindow = 2; $0.pageSize = 2 }661        let old1 = rig.server.seed("Projet", thread: "T"), old2 = rig.server.seed("Re: Projet", box: "se", thread: "T")662        for n in 1...6 { rig.server.seed("Autre \(n)"); rig.server.seed("Envoyé \(n)", box: "se") }663        let new = rig.server.seed("Re: Re: Projet", thread: "T")664        try await rig.engine.fullSync()665        #expect(try await rig.store.threadEmails("A", threadId: "T").map(\.id) == [new]) // what the cache alone knows of the conversation666        let whole = try await rig.engine.thread("T")667        #expect(whole.complete && whole.emails.map(\.id) == [old1, old2, new])668        let gets = rig.server.count("Email/get")669        #expect(try await rig.engine.thread("T").emails.count == 3 && rig.server.count("Email/get") == gets) // nothing fetched twice670        rig.offline()671        let cached = try await rig.engine.thread("T")672        #expect(!cached.complete && cached.emails.count == 3)673    }674675    // Item 9 — a mailbox that was removed: the engine is detached and that account's cache wiped; the other account is untouched.676    @Test func detachWipesOneAccountAndItsDecryptedFiles() async throws {677        let server = FakeMailServer()678        server.addBlob("blob-att", Data("PJ".utf8))679        let id = server.seed("Avec pièce", attachments: [["blobId": "blob-att", "name": "f.txt", "type": "text/plain", "size": 2, "disposition": "attachment"]])680        let (store, _, _) = try tempStore()681        let a = server.engine(store, account: "A"), b = server.engine(store, account: "B")682        for e in [a, b] {683            try await e.fullSync()684            let part = try #require(try await e.body(for: id).attachments.first)685            _ = try await e.fetchAttachment(part)686        }687        let file = try await a.attachmentFile(for: try #require(try await a.body(for: id).attachments.first))688        server.fault = { _, _ in .unreachable }689        await a.setFlagged(true, ids: [id])690        let draft = try await a.saveDraft(OutboxItem(account: "A", message: OutgoingMessage(from: EmailAddress(email: server.address), to: [EmailAddress(email: "x@stg.spboucher.ai")], subject: "À garder", text: "t")))691        server.fault = nil692        let ended = Task { () -> Bool in for await _ in a.events {}; return true }693        await a.detach()694        #expect(try await store.emailCount("A") == 0)695        #expect(try await store.mailboxes("A").isEmpty)696        #expect(try await store.pending("A").isEmpty)697        #expect(try await store.body("A", id: id) == nil)698        #expect(try await store.cachedAttachment("A", blobId: "blob-att") == nil)699        #expect(try await store.state("A", "Email") == nil)700        #expect(try await store.value("identities/A", as: [Identity].self) == nil && !FileManager.default.fileExists(atPath: file.path))701        #expect(try await store.outboxItem(draft.id) != nil) // an unsent draft is not cache702        #expect(try await store.emailCount("B") == 1)703        #expect(try await store.body("B", id: id) != nil)704        #expect(try await store.cachedAttachment("B", blobId: "blob-att") == Data("PJ".utf8))705        #expect(await raceValue(ended, seconds: 2) == true)706        #expect(await a.isDetached)707        await #expect(throws: StoreError.self) { try await a.deltaSync() } // a detached engine no longer talks to the server708        let c = server.engine(store, account: "A")709        await c.detach(removingOutbox: true)710        #expect(try await store.outboxItem(draft.id) == nil)711    }712}713714@Suite struct TwoDeviceTests {715    // Two engines, two stores, one account: what device A does is observed on device B through delta sync.716    @Test func flagMoveDeleteAndDraftOnOneDeviceReachTheOther() async throws {717        let server = FakeMailServer()718        let a = try Rig(server: server), b = try Rig(server: server)719        let ids = ["Un", "Deux", "Trois", "Quatre"].map { server.seed($0) }720        try await a.engine.fullSync(); try await b.engine.fullSync()721        await a.engine.setFlagged(true, ids: [ids[0]])722        await a.engine.setKeyword("$pinned", true, ids: [ids[0]])723        await a.engine.setKeyword("lbl_0badcafe", true, ids: [ids[3]])724        await a.engine.move(ids: [ids[1]], to: "tr")725        await a.engine.destroy(ids: [ids[2]])726        var draft = try await a.engine.saveDraft(OutboxItem(account: "A", message: a.message("Brouillon de A")))727        draft = try #require(try await a.engine.syncDraft(id: draft.id))728        let r = try await b.engine.deltaSync()729        #expect(!r.wasFull)730        #expect(try await b.store.email("A", id: ids[0])?.keywords == ["$flagged", "$pinned"])731        #expect(try await b.store.email("A", id: ids[3])?.keywords == ["lbl_0badcafe"])732        #expect(try await b.store.email("A", id: ids[1])?.mailboxIds == ["tr"])733        #expect(try await b.store.email("A", id: ids[2]) == nil)734        #expect(try await b.cachedIds("dr") == [try #require(draft.serverEmailId)])735        #expect(try await b.store.mailboxes("A").first { $0.id == "in" }?.totalEmails == 2) // counters follow the server736        for id in ids { #expect(try await a.store.email("A", id: id) == (try await b.store.email("A", id: id))) }737    }738739    // Concurrent conflicting changes resolve identically on both devices, with the server deciding.740    @Test func concurrentConflictingChangesConvergeOnTheServerVersion() async throws {741        let server = FakeMailServer()742        let a = try Rig(server: server), b = try Rig(server: server)743        let ids = ["Un", "Deux", "Trois"].map { server.seed($0) }744        try await a.engine.fullSync(); try await b.engine.fullSync()745        // A goes offline and changes three messages…746        a.offline()747        await a.engine.move(ids: [ids[0]], to: "tr")748        await a.engine.setFlagged(true, ids: [ids[1]])749        await a.engine.markSeen(true, ids: [ids[2]])750        // …while B, online, changes the same ones differently (the fault only cuts A's view in this test: B shares the server, so it acts directly)751        server.fault = nil752        await b.engine.move(ids: [ids[0]], to: "ju")753        await b.engine.setFlagged(true, ids: [ids[0]])754        await b.engine.destroy(ids: [ids[1]])755        await b.engine.setKeyword("$pinned", true, ids: [ids[2]])756        // A comes back757        try await a.engine.syncNow()758        try await b.engine.syncNow()759        try await a.engine.syncNow()760        for id in ids {761            let onA = try await a.store.email("A", id: id), onB = try await b.store.email("A", id: id)762            #expect(onA == onB, "devices disagree on \(id)")763            let truth = server.email(id)764            #expect(onA?.mailboxIds == truth.map { ($0["mailboxIds"].objectValue ?? [:]).keys.sorted() } && onA?.keywords == truth.map { ($0["keywords"].objectValue ?? [:]).keys.sorted() })765        }766        #expect(try await a.store.email("A", id: ids[1]) == nil) // destroyed on B: A's flag is refused, nothing is resurrected767        #expect(try await a.store.rejectedOperations("A").map(\.emailId) == [ids[1]])768        #expect(try await a.store.pending("A").isEmpty)769        #expect(try await a.store.email("A", id: ids[0])?.mailboxIds == ["tr"]) // per-property merge, as the server applied it770        #expect(try await a.store.email("A", id: ids[0])?.isFlagged == true)771        #expect(try await a.store.email("A", id: ids[2])?.keywords == ["$pinned", "$seen"])772        #expect(try await a.store.mailboxes("A") == (try await b.store.mailboxes("A")))773    }774}775
Files main
Menu

Theme